From cd80950d65bb5552d921a1c0e44be6611d89dbe6 Mon Sep 17 00:00:00 2001 From: JiaSheng Date: Sat, 23 Sep 2023 11:56:21 +0800 Subject: [PATCH 01/59] expired booking --- .../Commands/ExpiredBookingCommand.php | 95 +++++++++++++++++++ app/Console/Kernel.php | 4 + 2 files changed, 99 insertions(+) create mode 100644 app/Console/Commands/ExpiredBookingCommand.php diff --git a/app/Console/Commands/ExpiredBookingCommand.php b/app/Console/Commands/ExpiredBookingCommand.php new file mode 100644 index 00000000..2598b380 --- /dev/null +++ b/app/Console/Commands/ExpiredBookingCommand.php @@ -0,0 +1,95 @@ +updatesBookingStatus = $updatesBookingStatus; + } + + /** + * Execute the console command. + * + * @return int + */ + public function handle() + { + // Cancel booking without payment & purchase order (1 month) + $bookings = Booking::where('status', ApprovalStatus::APPROVED) + ->where('created_at', '<', now()->subDays(30)->endOfDay()) + ->where(function ($query) { + $query->whereDoesntHave('transactions') + ->orWhereDoesntHave('transactions', function($transaction) { + return $transaction->where('type', TransactionType::PAYMENT)->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED]); + }); + })->get(); + + foreach ($bookings as $booking) { + $this->updatesBookingStatus->execute($booking, ApprovalStatus::EXPIRED); + Log::info("Expired Booking without payment & purchase order, booking id: " . $booking->id); + $transactions = $booking->transactions; + + foreach ($transactions as $transaction) { + $transaction->status = ApprovalStatus::EXPIRED; + $transaction->save(); + Log::info("Expired Transaction id: {$transaction->id} from Booking id: {$booking->id}"); + } + } + + // Cancel booking without payment but with purchase order (2 month) + $bookings = Booking::where('status', ApprovalStatus::APPROVED) + ->where('created_at', '<', now()->subDays(60)->endOfDay()) + ->where(function ($query) { + $query->whereDoesntHave('transactions', function($transaction) { + return $transaction->where('type', TransactionType::PAYMENT)->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED]); + })->whereHas('transactions', function($transaction) { + return $transaction->where('type', TransactionType::PURCHASE_ORDER); + }); + })->get(); + + foreach ($bookings as $booking) { + $this->updatesBookingStatus->execute($booking, ApprovalStatus::EXPIRED); + Log::info("Expired Booking without payment but with purchase order, booking id: " . $booking->id); + $transactions = $booking->transactions; + + foreach ($transactions as $transaction) { + $transaction->status = ApprovalStatus::EXPIRED; + $transaction->save(); + Log::info("Expired Transaction id: {$transaction->id} from Booking id: {$booking->id}"); + } + } + } +} diff --git a/app/Console/Kernel.php b/app/Console/Kernel.php index cb9cf060..0355aea1 100644 --- a/app/Console/Kernel.php +++ b/app/Console/Kernel.php @@ -43,6 +43,10 @@ class Kernel extends ConsoleKernel ->everyMinute() ->appendOutputTo(storage_path().'/logs/regenerateInvoice.log') ->withoutOverlapping(); + + $schedule->command('booking:expired') + ->dailyAt('02:00') + ->withoutOverlapping(); } /** From 32602cab31318eb8813696fdd238a17181cfd38b Mon Sep 17 00:00:00 2001 From: JiaSheng Date: Sat, 23 Sep 2023 13:00:04 +0800 Subject: [PATCH 02/59] auto fill purchase order command --- .../Commands/AutoFillPurchaseOrderCommand.php | 112 ++++++++++++++++++ .../Commands/ExpiredBookingCommand.php | 4 +- 2 files changed, 114 insertions(+), 2 deletions(-) create mode 100644 app/Console/Commands/AutoFillPurchaseOrderCommand.php diff --git a/app/Console/Commands/AutoFillPurchaseOrderCommand.php b/app/Console/Commands/AutoFillPurchaseOrderCommand.php new file mode 100644 index 00000000..059232d2 --- /dev/null +++ b/app/Console/Commands/AutoFillPurchaseOrderCommand.php @@ -0,0 +1,112 @@ +generatesPurchaseOrderProducts = $generatesPurchaseOrderProducts; + $this->generatesTransactionBillNumber = $generatesTransactionBillNumber; + $this->createPurchaseOrderTransactionProcessor = $createPurchaseOrderTransactionProcessor; + } + + /** + * Execute the console command. + * + * @return int + */ + public function handle() + { + $bookings = Booking::where('status', ApprovalStatus::APPROVED) + ->where('created_at', '<', now()->subDays(60)->endOfDay()) + ->whereHas('transactions', function($transaction) { + return $transaction->where('type', TransactionType::PAYMENT)->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED]); + }) + ->whereDoesntHave('transactions', function($transaction){ + $transaction->where('type', TransactionType::PURCHASE_ORDER); + $transaction->whereIn('status', [ApprovalStatus::PENDING_VERIFICATION, ApprovalStatus::APPROVED]); + })->get(); + + foreach ($bookings as $booking) { + $po = Transaction::where('type', TransactionType::PURCHASE_ORDER) + ->where('status', ApprovalStatus::APPROVED)->where('issuer', $booking->company_id) + ->select('*', DB::raw('abs(amount - ' . $booking->fix_amount . ') as nearest_price'))->orderBy('nearest_price')->first(); + + + if (!$po) { + $po = Transaction::where('type', TransactionType::PURCHASE_ORDER) + ->where('status', ApprovalStatus::APPROVED)->select('*', DB::raw('abs(amount - ' . $booking->fix_amount . ') as nearest_price'))->orderBy('nearest_price')->first(); + } + + $products = $this->generatesPurchaseOrderProducts->execute($po, $booking->fix_amount); + + $deference = $booking->fix_amount - $products->sum('total'); + + if($deference > -150 && $deference < 150 && $deference != 0) { + + $products->push([ + 'description' => $deference < 0 ? 'Discount':'Shipping Fee', + 'quantity' => 1, + 'stockCode' => '', + 'total' => $deference, + 'unit_price' => $deference + ]); + } + + $billNumber = $this->generatesTransactionBillNumber->execute('XPO-'); + + $total = $products->sum('total'); + + $object = new TransactionObject($billNumber, TransactionType::PURCHASE_ORDER, $booking->company->id, 1, + 1, PaymentMethodType::CASH, + $total, $total, $booking->fix_currency_id, $booking->fix_currency_id, + 1, 0, 0, null, ApprovalStatus::PENDING_SUBMISSION, $products->toArray()); + + $this->createPurchaseOrderTransactionProcessor->execute($booking, $object); + } + } +} diff --git a/app/Console/Commands/ExpiredBookingCommand.php b/app/Console/Commands/ExpiredBookingCommand.php index 2598b380..37fe8612 100644 --- a/app/Console/Commands/ExpiredBookingCommand.php +++ b/app/Console/Commands/ExpiredBookingCommand.php @@ -55,7 +55,7 @@ class ExpiredBookingCommand extends Command ->orWhereDoesntHave('transactions', function($transaction) { return $transaction->where('type', TransactionType::PAYMENT)->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED]); }); - })->get(); + })->get(); foreach ($bookings as $booking) { $this->updatesBookingStatus->execute($booking, ApprovalStatus::EXPIRED); @@ -78,7 +78,7 @@ class ExpiredBookingCommand extends Command })->whereHas('transactions', function($transaction) { return $transaction->where('type', TransactionType::PURCHASE_ORDER); }); - })->get(); + })->get(); foreach ($bookings as $booking) { $this->updatesBookingStatus->execute($booking, ApprovalStatus::EXPIRED); From f1c23d46dde54f6cbcd768df15370d4972624b54 Mon Sep 17 00:00:00 2001 From: JiaSheng Date: Tue, 26 Sep 2023 21:30:51 +0800 Subject: [PATCH 03/59] update --- app/Console/Commands/AutoFillPurchaseOrderCommand.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/app/Console/Commands/AutoFillPurchaseOrderCommand.php b/app/Console/Commands/AutoFillPurchaseOrderCommand.php index 059232d2..65a6fa93 100644 --- a/app/Console/Commands/AutoFillPurchaseOrderCommand.php +++ b/app/Console/Commands/AutoFillPurchaseOrderCommand.php @@ -16,7 +16,7 @@ use App\Classes\ValueObjects\Constants\PaymentMethodType; use App\Models\Transaction; use Illuminate\Support\Facades\DB; -class ExpiredBookingCommand extends Command +class AutoFillPurchaseOrderCommand extends Command { /** * The name and signature of the console command. @@ -61,6 +61,7 @@ class ExpiredBookingCommand extends Command */ public function handle() { + // 5. If purchase order not fill up in 2 month, auto fill up it $bookings = Booking::where('status', ApprovalStatus::APPROVED) ->where('created_at', '<', now()->subDays(60)->endOfDay()) ->whereHas('transactions', function($transaction) { From 75f44fae74126045ebf5ac58108e374596b7045e Mon Sep 17 00:00:00 2001 From: JiaSheng Date: Tue, 26 Sep 2023 21:31:09 +0800 Subject: [PATCH 04/59] update --- app/Console/Commands/ExpiredBookingCommand.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/Console/Commands/ExpiredBookingCommand.php b/app/Console/Commands/ExpiredBookingCommand.php index 37fe8612..c5b4081c 100644 --- a/app/Console/Commands/ExpiredBookingCommand.php +++ b/app/Console/Commands/ExpiredBookingCommand.php @@ -47,7 +47,7 @@ class ExpiredBookingCommand extends Command */ public function handle() { - // Cancel booking without payment & purchase order (1 month) + // 1. Cancel booking without payment & purchase order (1 month) $bookings = Booking::where('status', ApprovalStatus::APPROVED) ->where('created_at', '<', now()->subDays(30)->endOfDay()) ->where(function ($query) { @@ -69,7 +69,7 @@ class ExpiredBookingCommand extends Command } } - // Cancel booking without payment but with purchase order (2 month) + // 2. Cancel booking without payment but with purchase order (2 month) $bookings = Booking::where('status', ApprovalStatus::APPROVED) ->where('created_at', '<', now()->subDays(60)->endOfDay()) ->where(function ($query) { From 4be3b11a505c663a78f6f6abc42223f5fe0e1bc5 Mon Sep 17 00:00:00 2001 From: JiaSheng Date: Tue, 26 Sep 2023 21:32:20 +0800 Subject: [PATCH 05/59] add auto fill purchase order job inside kernel --- app/Console/Kernel.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/app/Console/Kernel.php b/app/Console/Kernel.php index 0355aea1..46e77f3a 100644 --- a/app/Console/Kernel.php +++ b/app/Console/Kernel.php @@ -47,6 +47,10 @@ class Kernel extends ConsoleKernel $schedule->command('booking:expired') ->dailyAt('02:00') ->withoutOverlapping(); + + $schedule->command('purchaseOrder:autoFill') + ->dailyAt('03:00') + ->withoutOverlapping(); } /** From a84cbdde6a09d0fecc4342f1014e868fae868f36 Mon Sep 17 00:00:00 2001 From: JiaSheng Date: Wed, 27 Sep 2023 14:12:32 +0800 Subject: [PATCH 06/59] add cancel booking for refunded payment --- .../Commands/ExpiredBookingCommand.php | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/app/Console/Commands/ExpiredBookingCommand.php b/app/Console/Commands/ExpiredBookingCommand.php index c5b4081c..d79b7b9c 100644 --- a/app/Console/Commands/ExpiredBookingCommand.php +++ b/app/Console/Commands/ExpiredBookingCommand.php @@ -9,6 +9,7 @@ use Illuminate\Console\Command; use Carbon\Carbon; use Illuminate\Support\Facades\Log; use App\Classes\Modules\Bookings\Services\UpdatesBookingStatus; +use App\Models\Transaction; class ExpiredBookingCommand extends Command { @@ -91,5 +92,62 @@ class ExpiredBookingCommand extends Command Log::info("Expired Transaction id: {$transaction->id} from Booking id: {$booking->id}"); } } + + // 3. Cancel fully refunded payment & cancel booking + $transactions = Transaction::where('type', TransactionType::CREDIT_NOTE)->get(); + + foreach ($transactions as $transaction) { + // get the booking marking + $marking = substr($transaction->payment_reference, -5); + + // for a special payment reference on transaction id: 152013 + if (!is_numeric($marking)) { + $payment_reference = explode(" ", trim($transaction->payment_reference)); + if (count($payment_reference) > 1) { + $marking = $payment_reference[count($payment_reference) - 2]; + } + } + + if (is_numeric($marking)) { + $booking = Booking::where('marking', $marking)->first(); + + if ($booking) { + if ($booking->status === ApprovalStatus::APPROVED) { + $bookingPayment = $booking->transactions()->payments()->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED])->first(); + if (!$bookingPayment) { + $bookingPayment = $booking->transactions()->payments()->count(); + Log::info("Credit note transaction id: {$transaction->id}, there are {$bookingPayment} payment for the booking."); + $bookingPayment = $booking->transactions()->payments()->whereIn('status', [ApprovalStatus::EXPIRED, ApprovalStatus::REJECTED])->first(); + $status = ApprovalStatus::APPROVAL_STATUS_ID[$bookingPayment->status]; + Log::info("Credit note transaction id: {$transaction->id}, the payment for the booking is in status {$status}"); + } + $bookingPaymentAmount = $bookingPayment->amount; + // check if the booking is fully refund + $amountDifference = bcsub($transaction->amount, $bookingPaymentAmount); + + if (abs($amountDifference) < 0.01) { + // rejecting booking payment transaction + $bookingPayment->status = ApprovalStatus::REJECTED; + $bookingPayment->save(); + + //expired booking + $this->updatesBookingStatus->execute($booking, ApprovalStatus::EXPIRED); + Log::info("Credit note transaction id: {$transaction->id} is fully refunded, the refunded amount was {$transaction->amount} the payment reference is: {$transaction->payment_reference}"); + Log::info("Credit note transaction id: {$transaction->id}, Rejected Booking Transaction Payment id: {$bookingPayment->id}, the payment amount was {$bookingPayment->amount}"); + Log::info("Credit note transaction id: {$transaction->id}, Expired Booking id: {$booking->id}"); + } else { + Log::info("Credit note transaction id: {$transaction->id} is not fully refunded, the refunded amount was {$transaction->amount}, the payment amount was {$bookingPayment->amount}, the payment reference is: {$transaction->payment_reference}"); + } + } else { + $status = ApprovalStatus::APPROVAL_STATUS_ID[$booking->status]; + Log::info("Credit note transaction id: {$transaction->id}, booking status is {$status}"); + } + } else { + Log::info("Credit note transaction id: {$transaction->id}, booking marking not found, the payment reference is: {$transaction->payment_reference}"); + } + } else { + Log::info("Credit note transaction id: {$transaction->id} does not have booking marking, the payment reference is: {$transaction->payment_reference}"); + } + } } } From 946ee7b6f978305c69f8099aed9f8a9e33d4781c Mon Sep 17 00:00:00 2001 From: JiaSheng Date: Fri, 29 Sep 2023 15:42:15 +0800 Subject: [PATCH 07/59] refund booking --- .../CreateBookingRefundLogic.php | 20 ++++++++++--------- .../UpdateRefundTransactionStatusLogic.php | 4 +++- .../elements/PaymentHistoryComponent.vue | 6 +++--- 3 files changed, 17 insertions(+), 13 deletions(-) diff --git a/app/Classes/Modules/Bookings/ControllersLogic/CreateBookingRefundLogic.php b/app/Classes/Modules/Bookings/ControllersLogic/CreateBookingRefundLogic.php index d31ee2ce..398312c9 100644 --- a/app/Classes/Modules/Bookings/ControllersLogic/CreateBookingRefundLogic.php +++ b/app/Classes/Modules/Bookings/ControllersLogic/CreateBookingRefundLogic.php @@ -19,6 +19,7 @@ use App\Classes\Modules\Bookings\Services\CalculatesBookingRefundAmount; use App\Classes\Modules\Transactions\DataTransferObjects\TransactionObject; use App\Classes\Modules\Transactions\Services\GeneratesTransactionBillNumber; use App\Classes\Modules\Transactions\DataTransferObjects\TransactionRefundCalculationObject; +use App\Classes\ValueObjects\Constants\PaymentMethodType; class CreateBookingRefundLogic extends AbstractControllerLogic { @@ -84,21 +85,22 @@ class CreateBookingRefundLogic extends AbstractControllerLogic $billNumber = $this->generatesTransactionBillNumber->execute('RFD-'); - $refund = $transaction->transactions()->refunds()->sum('amount'); + $refund = $transaction->transactions()->refunds()->whereIn('status', [ApprovalStatus::PENDING_VERIFICATION, ApprovalStatus::APPROVED])->sum('original_amount'); if($refund + $request->input('amount') > $transaction->original_amount) throw new MalformedRequestException('Your refund must not be greater than '. $transaction->original_amount .'.'); - $amount = $transaction->booking->fix_currency_id == 1 ? $request->input('amount') : $request->input('amount') / $transaction->currency_rate; + // $transactionRefundCalculationObject = new TransactionRefundCalculationObject($booking, $transaction, $request->input('amount')); + // $transactionRefundCalculationObject->init(); - - $transactionRefundCalculationObject = new TransactionRefundCalculationObject($booking, $transaction, $amount); - $transactionRefundCalculationObject->init(); + $refundAmount = bcdiv($request->input('amount'), $transaction->currency_rate, 7); + // refund service charges if is fully refund + $refundTotal = ($refund + $request->input('amount')) == $transaction->original_amount ? $refundAmount + $transaction->service_charge + $transaction->tax : $refundAmount; $object = new TransactionObject($billNumber, TransactionType::REFUND, 1, $booking->company->id, - 1, $transactionRefundCalculationObject->getConversionObject()->getPaymentMethod(), - $transactionRefundCalculationObject->getRefundTotalAmount(), $transactionRefundCalculationObject->getAmount(), 1, - $transactionRefundCalculationObject->getConversionObject()->getCurrencyId(), $transactionRefundCalculationObject->getTransaction()->currency_rate, - $transactionRefundCalculationObject->getRefundTax(), $transactionRefundCalculationObject->getRefundServiceCharge(), null, ApprovalStatus::PENDING_VERIFICATION, [], $transaction->bill_no); + 1, PaymentMethodType::CASH, + $refundTotal, $request->input('amount'), 1, + $transaction->original_currency_id, $transaction->currency_rate, + $transaction->tax, $transaction->service_charge, null, ApprovalStatus::PENDING_VERIFICATION, [], $transaction->bill_no); $transaction = $this->createsTransaction->execute($transaction, $object); diff --git a/app/Classes/Modules/Transactions/ControllersLogic/UpdateRefundTransactionStatusLogic.php b/app/Classes/Modules/Transactions/ControllersLogic/UpdateRefundTransactionStatusLogic.php index b86e4878..bf704359 100644 --- a/app/Classes/Modules/Transactions/ControllersLogic/UpdateRefundTransactionStatusLogic.php +++ b/app/Classes/Modules/Transactions/ControllersLogic/UpdateRefundTransactionStatusLogic.php @@ -73,7 +73,9 @@ class UpdateRefundTransactionStatusLogic extends AbstractControllerLogic $booking = $transaction->owner->owner; - $reference = 'Credit Voucher for Overpaid for Ref. '.$booking->marking; + $paymentTransaction = $transaction->owner; + + $reference = $transaction->amount == $paymentTransaction->amount ? 'Fully Refund for Ref. ' . $booking->marking : 'Partially Refund for Ref. ' . $booking->marking; if ($transaction->status == ApprovalStatus::APPROVED) { $this->creditWalletProcessor->execute($booking->company, $transaction->type, $transaction->amount, $reference); diff --git a/resources/assets/vue/components/bookings/elements/PaymentHistoryComponent.vue b/resources/assets/vue/components/bookings/elements/PaymentHistoryComponent.vue index ce4ba5a7..63cb4687 100644 --- a/resources/assets/vue/components/bookings/elements/PaymentHistoryComponent.vue +++ b/resources/assets/vue/components/bookings/elements/PaymentHistoryComponent.vue @@ -133,7 +133,7 @@
Requested Refund Amount
-
{{item.currency.short_code}} {{(Math.round((totalRequestedRefund + Number.EPSILON) * 100) / 100).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}}
+
{{item.original_currency.short_code}} {{(Math.round((totalRequestedRefund + Number.EPSILON) * 100) / 100).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}}
@@ -271,9 +271,9 @@
-
+
- + From 1ac2ac3102c3f2b5e3aff5907d4136fd362e4fb3 Mon Sep 17 00:00:00 2001 From: Dillon Ngo Date: Wed, 29 Nov 2023 23:39:15 +0800 Subject: [PATCH 08/59] Voucherify UI update for kexin to take a look --- .../forms/BookingPaymentQuotationComponent.vue | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/resources/assets/vue/components/bookings/forms/BookingPaymentQuotationComponent.vue b/resources/assets/vue/components/bookings/forms/BookingPaymentQuotationComponent.vue index 6f18170c..50c6c701 100644 --- a/resources/assets/vue/components/bookings/forms/BookingPaymentQuotationComponent.vue +++ b/resources/assets/vue/components/bookings/forms/BookingPaymentQuotationComponent.vue @@ -244,17 +244,17 @@
- +
- + Apply a voucher
@@ -262,11 +262,11 @@ {{ voucherCodeFailedReason }} Voucher applied
- +
From 52c2dade88e485677bf015b4a3d0cc3d60ea5937 Mon Sep 17 00:00:00 2001 From: Dillon Ngo Date: Sun, 3 Dec 2023 23:13:52 +0800 Subject: [PATCH 09/59] Update UI based on kexin feedback --- .../elements/AvailableVouchersComponent.vue | 19 +++++++++++-------- .../BookingPaymentQuotationComponent.vue | 14 +++++++------- 2 files changed, 18 insertions(+), 15 deletions(-) diff --git a/resources/assets/vue/components/bookings/elements/AvailableVouchersComponent.vue b/resources/assets/vue/components/bookings/elements/AvailableVouchersComponent.vue index 45722aaf..7c3d5494 100644 --- a/resources/assets/vue/components/bookings/elements/AvailableVouchersComponent.vue +++ b/resources/assets/vue/components/bookings/elements/AvailableVouchersComponent.vue @@ -3,18 +3,21 @@
-
-
-

{{ item.voucher.code }}

+
List of Vouchers, click to select
+
+ + {{ item.voucher.code }} +
+
+ Valid till {{ item.voucher.end_date }} -
-
+ + No expiry date -
+
diff --git a/resources/assets/vue/components/bookings/forms/BookingPaymentQuotationComponent.vue b/resources/assets/vue/components/bookings/forms/BookingPaymentQuotationComponent.vue index 50c6c701..50a421b5 100644 --- a/resources/assets/vue/components/bookings/forms/BookingPaymentQuotationComponent.vue +++ b/resources/assets/vue/components/bookings/forms/BookingPaymentQuotationComponent.vue @@ -244,11 +244,11 @@
-
+
@@ -256,17 +256,17 @@
+
+
+ +
+
Apply a voucher
{{ voucherCodeFailedReason }} Voucher applied
-
-
- -
-
From 19d08242d52715ade37228e3fc6dc3fa88af32f8 Mon Sep 17 00:00:00 2001 From: Dillon Ngo Date: Sun, 3 Dec 2023 23:17:09 +0800 Subject: [PATCH 10/59] Update UI based on kexin feedback --- .../forms/BookingPaymentQuotationComponent.vue | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/resources/assets/vue/components/bookings/forms/BookingPaymentQuotationComponent.vue b/resources/assets/vue/components/bookings/forms/BookingPaymentQuotationComponent.vue index 50a421b5..e0e2ae8d 100644 --- a/resources/assets/vue/components/bookings/forms/BookingPaymentQuotationComponent.vue +++ b/resources/assets/vue/components/bookings/forms/BookingPaymentQuotationComponent.vue @@ -256,17 +256,17 @@
-
-
- -
-
Apply a voucher
{{ voucherCodeFailedReason }} Voucher applied
+
+
+ +
+
From 96c00ea66b68aace86afe6272cc7ee8594739028 Mon Sep 17 00:00:00 2001 From: Dillon Ngo Date: Sun, 3 Dec 2023 23:19:31 +0800 Subject: [PATCH 11/59] Update UI based on kexin feedback --- .../bookings/forms/BookingPaymentQuotationComponent.vue | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/resources/assets/vue/components/bookings/forms/BookingPaymentQuotationComponent.vue b/resources/assets/vue/components/bookings/forms/BookingPaymentQuotationComponent.vue index e0e2ae8d..73f7a006 100644 --- a/resources/assets/vue/components/bookings/forms/BookingPaymentQuotationComponent.vue +++ b/resources/assets/vue/components/bookings/forms/BookingPaymentQuotationComponent.vue @@ -257,7 +257,7 @@
Apply a voucher -
+
{{ voucherCodeFailedReason }} Voucher applied From 150f6a69d6dc77dcf032723aa49fec3529df3759 Mon Sep 17 00:00:00 2001 From: Dillon Ngo Date: Sun, 3 Dec 2023 23:34:36 +0800 Subject: [PATCH 12/59] Update UI based on kexin feedback --- .../bookings/elements/AvailableVouchersComponent.vue | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/resources/assets/vue/components/bookings/elements/AvailableVouchersComponent.vue b/resources/assets/vue/components/bookings/elements/AvailableVouchersComponent.vue index 7c3d5494..4ac885ff 100644 --- a/resources/assets/vue/components/bookings/elements/AvailableVouchersComponent.vue +++ b/resources/assets/vue/components/bookings/elements/AvailableVouchersComponent.vue @@ -1,9 +1,9 @@ diff --git a/resources/views/pages/billings_experiment.blade.php b/resources/views/pages/billings_experiment.blade.php new file mode 100644 index 00000000..d1caee2d --- /dev/null +++ b/resources/views/pages/billings_experiment.blade.php @@ -0,0 +1,9 @@ +@extends('layouts.base_portal') +@section('inner_content') +
+
+ + +
+
+@endsection diff --git a/routes/job.php b/routes/job.php index f32d142e..028e9468 100644 --- a/routes/job.php +++ b/routes/job.php @@ -4,4 +4,5 @@ use Illuminate\Support\Facades\Route; Route::group(['prefix' => 'job', 'as' => 'job.', 'namespace' => 'Jobs'], function () { Route::get('/fetch/{job_id}', 'FetchJobResultController@fetch')->name('fetch'); + Route::get('/fetch/{job_id}/{is_last}', 'FetchJobResultController@fetch')->name('fetch.last.attempt'); }); diff --git a/routes/web.php b/routes/web.php index ead4b3d2..4e9afd11 100644 --- a/routes/web.php +++ b/routes/web.php @@ -92,6 +92,12 @@ Route::get('/billings', function () { return view('pages.billings'); })->name('billings'); +/* Vue Polling Experiment - Starts */ +Route::get('/billings-experiment', function () { + return view('pages.billings_experiment'); +})->name('billings.experiment'); +/* Vue Polling Experiment - Ends */ + Route::get('/currency_orders', function () { return view('pages.currency_orders'); })->name('currency_orders'); @@ -813,13 +819,13 @@ Route::get('/invoice/{marking}/{started_at}/{ended_at}/fix', function($marking, ->withTrashed() ->orderBy('created_at', 'asc') ->first(); - + // get the first bill_no $firstBillNo = $firstInvoice->bill_no; if (strpos($firstBillNo, '-deleted') !== false) { $firstBillNo = substr($firstBillNo, 0, strpos($firstBillNo, '-deleted')); } - + // update currentInvoice bill_no to '-deleted-' $currentInvoice = $booking->transactions()->where('type', TransactionType::INVOICE)->first(); $currentInvoice->bill_no = $currentInvoice->bill_no ."-deleted-" . Str::random(10); @@ -842,4 +848,4 @@ Route::get('/invoice/{marking}/{started_at}/{ended_at}/fix', function($marking, } } ); -})->name('invoice.fix.byCustomerMarking'); \ No newline at end of file +})->name('invoice.fix.byCustomerMarking'); From ea4795e5c861616064c9ceae521aefedd60769c2 Mon Sep 17 00:00:00 2001 From: Dillon Ngo Date: Sun, 11 Feb 2024 09:53:09 +0000 Subject: [PATCH 24/59] Revert "Merge branch 'dillon/51-vue-polling-experimental-2' into 'master'" This reverts merge request !152 --- .../JobResourceNotFoundException.php | 11 - .../Abstracts/AbstractControllerLogic.php | 15 +- .../General/Eloquent/AbstractFetchRecord.php | 14 +- .../General/Eloquent/AbstractGetRecord.php | 26 +-- .../General/Eloquent/AbstractListRecord.php | 14 +- .../General/Eloquent/Filters/JobId.php | 20 -- .../Eloquent/Filters/OrderByIdDesc.php | 20 -- .../Eloquent/Filters/RequestSignature.php | 19 -- .../Eloquent/Filters/ResultNotNull.php | 18 -- app/Classes/General/Helper.php | 24 -- app/Classes/Jobs/ListBookingsJob.php | 52 ----- app/Classes/Jobs/ListDocumentsJob.php | 63 ------ app/Classes/Jobs/ListTransactionsJob.php | 52 ----- .../ControllersLogic/ListBookingJobLogic.php | 75 ------ .../Processors/ListBookingsJobProcessor.php | 46 ---- .../ControllersLogic/ListDocumentJobLogic.php | 75 ------ .../Processors/ListDocumentsJobProcessor.php | 47 ---- .../ControllersLogic/FetchJobResultLogic.php | 51 ----- .../ListGenericJobObject.php | 118 ---------- .../UpdateJobResultObject.php | 60 ----- .../Processors/FetchesJobResultProcessor.php | 47 ---- .../Processors/UpdateJobResultProcessor.php | 64 ------ .../Jobs/Services/CreatesJobResult.php | 26 --- .../Jobs/Services/FetchesJobResult.php | 33 --- .../Modules/Jobs/Services/ListsJobResult.php | 33 --- .../Jobs/Services/UpdatesJobResult.php | 28 --- .../ListTransactionsJobLogic.php | 74 ------ .../ListTransactionsJobProcessor.php | 45 ---- .../Bookings/ListBookingsJobController.php | 22 -- .../Documents/ListDocumentsJobController.php | 19 -- .../Jobs/FetchJobResultController.php | 19 -- .../ListTransactionsJobController.php | 21 -- app/Http/Resources/BookingResource.php | 2 + app/Http/Resources/CompanyResource.php | 1 + app/Http/Resources/DocumentResource.php | 3 + app/Http/Resources/JobResultResource.php | 22 -- app/Http/Resources/ListBookingJobResource.php | 81 ------- .../Resources/ListDocumentJobResource.php | 31 --- .../Resources/ListTransactionJobResource.php | 54 ----- app/Http/Resources/V2/BookingV2Resource.php | 82 ------- app/Http/Resources/V2/CompanyV2Resource.php | 100 -------- app/Models/JobResult.php | 13 -- ..._08_08_124848_create_job_results_table.php | 35 --- ...31_add_new_column_to_job_results_table.php | 36 --- ..._add_new_column_2_to_job_results_table.php | 34 --- .../AdminPaymentsBillingSectionComponent.vue | 136 ----------- ...PaymentsBillingSectionPollingComponent.vue | 136 ----------- .../SupplierPendingOrdersSectionComponent.vue | 10 +- .../general/elements/ListPollingComponent.vue | 213 ------------------ .../vue/general/mixins/aws/requestV2.js | 49 ---- .../assets/vue/general/mixins/tabHandler.js | 24 -- .../assets/vue/vuex/modules/crudRequestV2.js | 51 ----- resources/assets/vue/vuex/store.js | 4 +- resources/views/pages/billings.blade.php | 126 ++++++++++- .../views/pages/billings_experiment.blade.php | 9 - routes/api.php | 4 - routes/currency.php | 2 +- routes/document.php | 3 +- routes/job.php | 8 - routes/web.php | 12 +- 60 files changed, 152 insertions(+), 2380 deletions(-) delete mode 100644 app/Classes/Exceptions/JobResourceNotFoundException.php delete mode 100644 app/Classes/General/Eloquent/Filters/JobId.php delete mode 100644 app/Classes/General/Eloquent/Filters/OrderByIdDesc.php delete mode 100644 app/Classes/General/Eloquent/Filters/RequestSignature.php delete mode 100644 app/Classes/General/Eloquent/Filters/ResultNotNull.php delete mode 100644 app/Classes/Jobs/ListBookingsJob.php delete mode 100644 app/Classes/Jobs/ListDocumentsJob.php delete mode 100644 app/Classes/Jobs/ListTransactionsJob.php delete mode 100644 app/Classes/Modules/Bookings/ControllersLogic/ListBookingJobLogic.php delete mode 100644 app/Classes/Modules/Bookings/Processors/ListBookingsJobProcessor.php delete mode 100644 app/Classes/Modules/Documents/ControllersLogic/ListDocumentJobLogic.php delete mode 100644 app/Classes/Modules/Documents/Processors/ListDocumentsJobProcessor.php delete mode 100644 app/Classes/Modules/Jobs/ControllersLogic/FetchJobResultLogic.php delete mode 100644 app/Classes/Modules/Jobs/DataTransferObjects/ListGenericJobObject.php delete mode 100644 app/Classes/Modules/Jobs/DataTransferObjects/UpdateJobResultObject.php delete mode 100644 app/Classes/Modules/Jobs/Processors/FetchesJobResultProcessor.php delete mode 100644 app/Classes/Modules/Jobs/Processors/UpdateJobResultProcessor.php delete mode 100644 app/Classes/Modules/Jobs/Services/CreatesJobResult.php delete mode 100644 app/Classes/Modules/Jobs/Services/FetchesJobResult.php delete mode 100644 app/Classes/Modules/Jobs/Services/ListsJobResult.php delete mode 100644 app/Classes/Modules/Jobs/Services/UpdatesJobResult.php delete mode 100644 app/Classes/Modules/Transactions/ControllersLogic/ListTransactionsJobLogic.php delete mode 100644 app/Classes/Modules/Transactions/Processors/ListTransactionsJobProcessor.php delete mode 100644 app/Http/Controllers/Bookings/ListBookingsJobController.php delete mode 100644 app/Http/Controllers/Documents/ListDocumentsJobController.php delete mode 100644 app/Http/Controllers/Jobs/FetchJobResultController.php delete mode 100644 app/Http/Controllers/Transactions/ListTransactionsJobController.php delete mode 100644 app/Http/Resources/JobResultResource.php delete mode 100644 app/Http/Resources/ListBookingJobResource.php delete mode 100644 app/Http/Resources/ListDocumentJobResource.php delete mode 100644 app/Http/Resources/ListTransactionJobResource.php delete mode 100644 app/Http/Resources/V2/BookingV2Resource.php delete mode 100644 app/Http/Resources/V2/CompanyV2Resource.php delete mode 100644 app/Models/JobResult.php delete mode 100644 database/migrations/2023_08_08_124848_create_job_results_table.php delete mode 100644 database/migrations/2023_08_29_063531_add_new_column_to_job_results_table.php delete mode 100644 database/migrations/2023_12_11_193200_add_new_column_2_to_job_results_table.php delete mode 100644 resources/assets/vue/components/bookings/sections/AdminPaymentsBillingSectionComponent.vue delete mode 100644 resources/assets/vue/components/bookings/sections/AdminPaymentsBillingSectionPollingComponent.vue delete mode 100644 resources/assets/vue/components/general/elements/ListPollingComponent.vue delete mode 100644 resources/assets/vue/general/mixins/aws/requestV2.js delete mode 100644 resources/assets/vue/general/mixins/tabHandler.js delete mode 100644 resources/assets/vue/vuex/modules/crudRequestV2.js delete mode 100644 resources/views/pages/billings_experiment.blade.php delete mode 100644 routes/job.php diff --git a/app/Classes/Exceptions/JobResourceNotFoundException.php b/app/Classes/Exceptions/JobResourceNotFoundException.php deleted file mode 100644 index a8ef358e..00000000 --- a/app/Classes/Exceptions/JobResourceNotFoundException.php +++ /dev/null @@ -1,11 +0,0 @@ -getMessage(), - $exception->getTrace()[0]['file'], - $exception->getTrace()[0]['line'] - )); - } - else{ - log::error($exception); - } - + log::error($exception); return (new ApiResponseObject($this->getNotificationTitle().' failed', $exception->getMessage(), $exception->getCode() ? $exception->getCode() : HttpStatus::SERVER_ERROR))->handler(); diff --git a/app/Classes/General/Eloquent/AbstractFetchRecord.php b/app/Classes/General/Eloquent/AbstractFetchRecord.php index 503fb369..248deee7 100644 --- a/app/Classes/General/Eloquent/AbstractFetchRecord.php +++ b/app/Classes/General/Eloquent/AbstractFetchRecord.php @@ -4,11 +4,9 @@ namespace App\Classes\General\Eloquent; use App\Classes\Exceptions\ResourceNotFoundException; -use App\Classes\Exceptions\JobResourceNotFoundException; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; use Psy\Exception\ErrorException; -use Illuminate\Support\Facades\Log; abstract class AbstractFetchRecord extends AbstractGetRecord { @@ -29,18 +27,12 @@ abstract class AbstractFetchRecord extends AbstractGetRecord * @return Model * @throws ResourceNotFoundException */ - public function getResults(Builder $query, array $param = []): Model { + public function getResults(Builder $query): Model { if(!$query->exists()){ - $table = $query->getModel()->getTable(); - if($table ==='job_results'){ - throw new JobResourceNotFoundException('Unable to find any job based on the criteria provided'); - } - else{ - throw new ResourceNotFoundException('Unable to find any record based on the criteria provided'); - } + throw new ResourceNotFoundException('Unable to find any record based on the criteria provided'); } return $query->first(); } -} +} \ No newline at end of file diff --git a/app/Classes/General/Eloquent/AbstractGetRecord.php b/app/Classes/General/Eloquent/AbstractGetRecord.php index 1a7eac3e..f927d818 100644 --- a/app/Classes/General/Eloquent/AbstractGetRecord.php +++ b/app/Classes/General/Eloquent/AbstractGetRecord.php @@ -30,25 +30,11 @@ abstract class AbstractGetRecord return $this->filters->only(self::DECORATION_FILTERS); } - // /** - // * @param null|string $json - // * @return array - // */ - // public function deserializeFilters(?string $json): array { - // return $json !== null ? collect(json_decode($json))->toArray() : []; - // } - /** - * @param null|string $param + * @param null|string $json * @return array */ - public function deserializeFilters($param): array { - if(gettype($param) == "array"){ - $json = implode(',', $param); - } - else{ - $json = $param; - } + public function deserializeFilters(?string $json): array { return $json !== null ? collect(json_decode($json))->toArray() : []; } @@ -64,9 +50,9 @@ abstract class AbstractGetRecord * @param array $filters * @return mixed */ - public function handler(array $filters, array $params = []){ + public function handler(array $filters){ $this->filters = collect($filters); - return $this->getResults($this->applyFiltersToQuery(), $params); + return $this->getResults($this->applyFiltersToQuery()); } @@ -79,6 +65,6 @@ abstract class AbstractGetRecord * @param Builder $query * @return mixed */ - abstract function getResults(Builder $query, array $params = []); + abstract function getResults(Builder $query); -} +} \ No newline at end of file diff --git a/app/Classes/General/Eloquent/AbstractListRecord.php b/app/Classes/General/Eloquent/AbstractListRecord.php index f898f108..7b7d0df9 100644 --- a/app/Classes/General/Eloquent/AbstractListRecord.php +++ b/app/Classes/General/Eloquent/AbstractListRecord.php @@ -17,11 +17,11 @@ abstract class AbstractListRecord extends AbstractGetRecord * @return mixed * @throws MalformedRequestException */ - public function execute(array $filters = [], array $param = []){ + public function execute(array $filters = []){ try{ - return $this->handler($filters, $param); + return $this->handler($filters); } catch (QueryException $exception){ log::error($exception); @@ -30,24 +30,18 @@ abstract class AbstractListRecord extends AbstractGetRecord } - /** * @param Builder $query * @return mixed */ - public function getResults(Builder $query, array $param = []) { + public function getResults(Builder $query) { $filters = $this->getDecorationFilters(); if($filters->has('order_by')){ $query = $query->orderBy($filters->get('order_by')->column, $filters->get('order_by')->DESC ? 'DESC': 'ASC'); } - if(!empty($param)){ - return $filters->has('per_page') ? $query->paginate($filters->get('per_page'), ['*'], 'page', $param['page']) : $query->get(); //page data from query parameters e.g ?page=1 - } - else{ - return $filters->has('per_page') ? $query->paginate($filters->get('per_page')) : $query->get(); - } + return $filters->has('per_page') ? $query->paginate($filters->get('per_page')) : $query->get(); } diff --git a/app/Classes/General/Eloquent/Filters/JobId.php b/app/Classes/General/Eloquent/Filters/JobId.php deleted file mode 100644 index 42ac51a4..00000000 --- a/app/Classes/General/Eloquent/Filters/JobId.php +++ /dev/null @@ -1,20 +0,0 @@ -where('job_id', $value); - } - -} diff --git a/app/Classes/General/Eloquent/Filters/OrderByIdDesc.php b/app/Classes/General/Eloquent/Filters/OrderByIdDesc.php deleted file mode 100644 index 547ec9bd..00000000 --- a/app/Classes/General/Eloquent/Filters/OrderByIdDesc.php +++ /dev/null @@ -1,20 +0,0 @@ -orderBy('id', 'desc'); - } - -} diff --git a/app/Classes/General/Eloquent/Filters/RequestSignature.php b/app/Classes/General/Eloquent/Filters/RequestSignature.php deleted file mode 100644 index 67dde0a3..00000000 --- a/app/Classes/General/Eloquent/Filters/RequestSignature.php +++ /dev/null @@ -1,19 +0,0 @@ -where('request_signature', $value); - } - -} diff --git a/app/Classes/General/Eloquent/Filters/ResultNotNull.php b/app/Classes/General/Eloquent/Filters/ResultNotNull.php deleted file mode 100644 index 3f6a0341..00000000 --- a/app/Classes/General/Eloquent/Filters/ResultNotNull.php +++ /dev/null @@ -1,18 +0,0 @@ -whereNotNull('result'); - } -} diff --git a/app/Classes/General/Helper.php b/app/Classes/General/Helper.php index 45c72f53..ac89540b 100644 --- a/app/Classes/General/Helper.php +++ b/app/Classes/General/Helper.php @@ -2,7 +2,6 @@ namespace App\Classes\General; -use Illuminate\Http\Resources\Json\ResourceCollection; use Illuminate\Support\Facades\Log; use Illuminate\Support\Str; @@ -43,27 +42,4 @@ class Helper } } } - - /** - * @param null|string $param - * @return array - */ - static function deserializeFilters($param): array { - if(gettype($param) == "array"){ - $json = implode(',', $param); - } - else{ - $json = $param; - } - return $json !== null ? collect(json_decode($json))->toArray() : []; - } - - /** - * @param ResourceCollection $collection - * @return array - */ - static function collectionResponse(ResourceCollection $collection){ - return json_decode($collection->response()->getContent(), true); - } - } diff --git a/app/Classes/Jobs/ListBookingsJob.php b/app/Classes/Jobs/ListBookingsJob.php deleted file mode 100644 index b021b71d..00000000 --- a/app/Classes/Jobs/ListBookingsJob.php +++ /dev/null @@ -1,52 +0,0 @@ -listGenericJobObject = $listGenericJobObject; - } - - public function handle() - { - $rawPayload = $this->job->payload(); - if(isset($rawPayload['data']['commandName'])){ - $this->listGenericJobObject->setJobCommandName($rawPayload['data']['commandName']); - } - - if(isset($rawPayload['data']['command'])){ - $this->listGenericJobObject->setJobCommand($rawPayload['data']['command']); - } - - $result = (App()->make(ListBookingsJobProcessor::class))->execute($this->listGenericJobObject); - } - - public function getJobId(){ - return $this->job->getJobId(); - } -} diff --git a/app/Classes/Jobs/ListDocumentsJob.php b/app/Classes/Jobs/ListDocumentsJob.php deleted file mode 100644 index 6e93062b..00000000 --- a/app/Classes/Jobs/ListDocumentsJob.php +++ /dev/null @@ -1,63 +0,0 @@ -listGenericJobObject = $listGenericJobObject; - } - - public function handle() - { - $rawPayload = $this->job->payload(); - if(isset($rawPayload['data']['commandName'])){ - $this->listGenericJobObject->setJobCommandName($rawPayload['data']['commandName']); - } - - if(isset($rawPayload['data']['command'])){ - $this->listGenericJobObject->setJobCommand($rawPayload['data']['command']); - } - - $result = (App()->make(ListDocumentsJobProcessor::class))->execute($this->listGenericJobObject); - - //cief todo: Insert into DB: job id, query result, timestamp - // Store the result in the job_results table - - //cief todo: why cannot save data in table like this - // $model = new JobResult(); - // $model->job_id = $this->job->getJobId(); - // $model->result = json_encode($result); - // $model->save(); - - // Log::error(json_encode($model->id)); - } - - public function getJobId(){ - return $this->job->getJobId(); - } -} diff --git a/app/Classes/Jobs/ListTransactionsJob.php b/app/Classes/Jobs/ListTransactionsJob.php deleted file mode 100644 index a2b28656..00000000 --- a/app/Classes/Jobs/ListTransactionsJob.php +++ /dev/null @@ -1,52 +0,0 @@ -listGenericJobObject = $listGenericJobObject; - } - - public function handle() - { - $rawPayload = $this->job->payload(); - if(isset($rawPayload['data']['commandName'])){ - $this->listGenericJobObject->setJobCommandName($rawPayload['data']['commandName']); - } - - if(isset($rawPayload['data']['command'])){ - $this->listGenericJobObject->setJobCommand($rawPayload['data']['command']); - } - - $result = (App()->make(ListTransactionsJobProcessor::class))->execute($this->listGenericJobObject); - } - - public function getJobId(){ - return $this->job->getJobId(); - } -} diff --git a/app/Classes/Modules/Bookings/ControllersLogic/ListBookingJobLogic.php b/app/Classes/Modules/Bookings/ControllersLogic/ListBookingJobLogic.php deleted file mode 100644 index ef3570f7..00000000 --- a/app/Classes/Modules/Bookings/ControllersLogic/ListBookingJobLogic.php +++ /dev/null @@ -1,75 +0,0 @@ - 'List Booking Job', - 'message' => 'You have successfully submit a job to list bookings' - ]; - } - - /** @var CreatesJobResult */ - private $createsJobResult; - - /** - * ListPackingListsJobLogic constructor. - * @param CreatesJobResult $createsJobResult - */ - public function __construct(CreatesJobResult $createsJobResult) - { - $this->createsJobResult = $createsJobResult; - } - - - /** - * @param Request $request - * @return JsonResponse - */ - public function logic(Request $request) : JsonResponse - { - $jobId = uniqid(); - - $user = Auth::user(); - $userInfo = (object) [ - 'type' => $user->type, - ]; - - $userInfoJson = json_encode($userInfo); - $requestSignature = md5($userInfoJson . $request->fullUrl()); - - $listGenericJobObject = new ListGenericJobObject( - $request->fullUrl(), - $request->all(), - $requestSignature, - null, - $jobId, - $userInfo - ); - - ListBookingsJob::dispatch($listGenericJobObject); - - $result = []; - $result['job_id'] = $jobId; - - $this->createsJobResult->execute($listGenericJobObject); - - return $this->response(['data' => $result]); - } - -} diff --git a/app/Classes/Modules/Bookings/Processors/ListBookingsJobProcessor.php b/app/Classes/Modules/Bookings/Processors/ListBookingsJobProcessor.php deleted file mode 100644 index 2a09eb12..00000000 --- a/app/Classes/Modules/Bookings/Processors/ListBookingsJobProcessor.php +++ /dev/null @@ -1,46 +0,0 @@ -listsBookings = $listsBookings; - $this->updateJobResultProcessor = $updateJobResultProcessor; - } - - /** - * @param ListGenericJobObject $listGenericJobObject - * @return void - * @throws \App\Classes\Exceptions\MalformedRequestException - * @throws \App\Classes\Exceptions\JobResourceNotFoundException - */ - public function execute(ListGenericJobObject $listGenericJobObject) { - - $query = $this->listsBookings->execute($this->listsBookings->deserializeFilters($listGenericJobObject->getPayload()['filters']), ['page' => $listGenericJobObject->getPayload()['page']]); - foreach ($query->items() as &$item) { - $item['userInfo'] = $listGenericJobObject->getUserInfo(); - } - $resultCurrent = Helper::collectionResponse(ListBookingJobResource::collection($query)); - $this->updateJobResultProcessor->execute($listGenericJobObject, $resultCurrent); - } -} diff --git a/app/Classes/Modules/Documents/ControllersLogic/ListDocumentJobLogic.php b/app/Classes/Modules/Documents/ControllersLogic/ListDocumentJobLogic.php deleted file mode 100644 index 5e895ad8..00000000 --- a/app/Classes/Modules/Documents/ControllersLogic/ListDocumentJobLogic.php +++ /dev/null @@ -1,75 +0,0 @@ - 'List Document Job', - 'message' => 'You have successfully submit a job to list documents' - ]; - } - - /** @var CreatesJobResult */ - private $createsJobResult; - - /** - * ListDocumentJobLogic constructor. - * @param CreatesJobResult $createsJobResult - */ - public function __construct(CreatesJobResult $createsJobResult) - { - $this->createsJobResult = $createsJobResult; - } - - - /** - * @param Request $request - * @return JsonResponse - */ - public function logic(Request $request) : JsonResponse - { - $jobId = uniqid(); - - $user = Auth::user(); - $userInfo = (object) [ - 'email' => $user->email, - 'type' => $user->type, - ]; - - $userInfoJson = json_encode($userInfo); - $requestSignature = md5($userInfoJson . $request->fullUrl()); - - $listGenericJobObject = new ListGenericJobObject( - $request->fullUrl(), - $request->all(), - $requestSignature, - null, - $jobId, - $userInfo - ); - - ListDocumentsJob::dispatch($listGenericJobObject); - - $result = []; - $result['job_id'] = $jobId; - - $this->createsJobResult->execute($listGenericJobObject); - - return $this->response(['data' => $result]); - } -} diff --git a/app/Classes/Modules/Documents/Processors/ListDocumentsJobProcessor.php b/app/Classes/Modules/Documents/Processors/ListDocumentsJobProcessor.php deleted file mode 100644 index 70777f0c..00000000 --- a/app/Classes/Modules/Documents/Processors/ListDocumentsJobProcessor.php +++ /dev/null @@ -1,47 +0,0 @@ -listsDocuments = $listsDocuments; - $this->updateJobResultProcessor = $updateJobResultProcessor; - } - - /** - * @param ListGenericJobObject $listGenericJobObject - * @return void - * @throws \App\Classes\Exceptions\MalformedRequestException - * @throws \App\Classes\Exceptions\JobResourceNotFoundException - */ - public function execute(ListGenericJobObject $listGenericJobObject) { - - $query = $this->listsDocuments->execute($this->listsDocuments->deserializeFilters($listGenericJobObject->getPayload()['filters']), ['page' => $listGenericJobObject->getPayload()['page']]); - foreach ($query->items() as &$item) { - $item['userInfo'] = $listGenericJobObject->getUserInfo(); - } - $resultCurrent = Helper::collectionResponse(ListDocumentJobResource::collection($query)); - $this->updateJobResultProcessor->execute($listGenericJobObject, $resultCurrent); - } -} - diff --git a/app/Classes/Modules/Jobs/ControllersLogic/FetchJobResultLogic.php b/app/Classes/Modules/Jobs/ControllersLogic/FetchJobResultLogic.php deleted file mode 100644 index c4b72cf0..00000000 --- a/app/Classes/Modules/Jobs/ControllersLogic/FetchJobResultLogic.php +++ /dev/null @@ -1,51 +0,0 @@ - 'Retrieved Data', - 'message' => 'You have successfully retrieved data' - ]; - } - - /** @var FetchesJobResultProcessor */ - private $fetchesJobResultProcessor; - - /** - * FetchJobResultLogic constructor. - * @param FetchesJobResultProcessor $fetchesJobResultProcessor - */ - public function __construct(FetchesJobResultProcessor $fetchesJobResultProcessor) - { - $this->fetchesJobResultProcessor = $fetchesJobResultProcessor; - } - - - /** - * @param Request $request - * @return JsonResponse - * @throws \App\Classes\Exceptions\AccessForbiddenException - * @throws \App\Classes\Exceptions\MalformedRequestException - * @throws \App\Classes\Exceptions\RequestValidationException - */ - public function logic(Request $request) : JsonResponse - { - $query = $this->fetchesJobResultProcessor->execute($request); - return $this->resourceResponse(new JobResultResource($query)); - } - -} diff --git a/app/Classes/Modules/Jobs/DataTransferObjects/ListGenericJobObject.php b/app/Classes/Modules/Jobs/DataTransferObjects/ListGenericJobObject.php deleted file mode 100644 index 953d77d7..00000000 --- a/app/Classes/Modules/Jobs/DataTransferObjects/ListGenericJobObject.php +++ /dev/null @@ -1,118 +0,0 @@ -name = $name; - $this->payload = $payload; - $this->jobId = $jobId; - $this->requestSignature = $requestSignature; - $this->resultSignature = $resultSignature; - $this->userInfo = $userInfo; - } - - /** - * @return string - */ - public function getName(): string - { - return $this->name; - } - - /** - * @return array - */ - public function getPayload(): array - { - return $this->payload; - } - - /** - * @return string - */ - public function getJobId(): string - { - return $this->jobId; - } - - /** - * @return string - */ - public function getRequestSignature(): string - { - return $this->requestSignature; - } - - /** - * @return string - */ - public function getResultSignature(): ?string - { - return $this->resultSignature; - } - - /** - * @return object - */ - public function getUserInfo(): object - { - return $this->userInfo; - } - - /** - * @return string - */ - public function getJobCommandName(): string - { - return $this->jobCommandName; - } - - /** - * @return string - */ - public function getJobCommand(): string - { - return $this->jobCommand; - } - - - public function setJobCommandName(string $jobCommandName) - { - $this->jobCommandName = $jobCommandName; - } - - public function setJobCommand(string $jobCommand) - { - $this->jobCommand = $jobCommand; - } - -} diff --git a/app/Classes/Modules/Jobs/DataTransferObjects/UpdateJobResultObject.php b/app/Classes/Modules/Jobs/DataTransferObjects/UpdateJobResultObject.php deleted file mode 100644 index 636c56b0..00000000 --- a/app/Classes/Modules/Jobs/DataTransferObjects/UpdateJobResultObject.php +++ /dev/null @@ -1,60 +0,0 @@ -result = $result; - $this->resultSignature = $resultSignature; - $this->jobCommandName = $jobCommandName; - $this->jobCommand = $jobCommand; - } - - /** - * @return string - */ - public function getResult(): string - { - return $this->result; - } - - /** - * @return array - */ - public function getResultSignature(): string - { - return $this->resultSignature; - } - - /** - * @return string - */ - public function getJobCommandName(): string - { - return $this->jobCommandName; - } - - /** - * @return string - */ - public function getJobCommand(): string - { - return $this->jobCommand; - } -} diff --git a/app/Classes/Modules/Jobs/Processors/FetchesJobResultProcessor.php b/app/Classes/Modules/Jobs/Processors/FetchesJobResultProcessor.php deleted file mode 100644 index 89783fe8..00000000 --- a/app/Classes/Modules/Jobs/Processors/FetchesJobResultProcessor.php +++ /dev/null @@ -1,47 +0,0 @@ -fetchesJobResult = $fetchesJobResult; - } - - - /** - * @param Request $request - * @return Model - * @throws \App\Classes\Exceptions\MalformedRequestException - * @throws \App\Classes\Exceptions\JobResourceNotFoundException - * @throws \App\Classes\Exceptions\ResourceNotFoundException - */ - public function execute(Request $request){ - - $res1 = $this->fetchesJobResult->execute(['job_id' => $request->route('job_id')]); - if($request->route('is_last')){ - $res2 = $this->fetchesJobResult->execute(['request_signature' => $res1->request_signature, 'result_not_null' => true, 'order_by_id_desc' => true]); - return $res2; - } - - if(!$res1->result){ - throw new JobResourceNotFoundException('Unable to find any job based on the criteria provided'); - } - - return $res1; - } -} diff --git a/app/Classes/Modules/Jobs/Processors/UpdateJobResultProcessor.php b/app/Classes/Modules/Jobs/Processors/UpdateJobResultProcessor.php deleted file mode 100644 index 0106417d..00000000 --- a/app/Classes/Modules/Jobs/Processors/UpdateJobResultProcessor.php +++ /dev/null @@ -1,64 +0,0 @@ -fetchesJobResult = $fetchesJobResult; - $this->updatesJobResult = $updatesJobResult; - } - - /** - * @param ListGenericJobObject $listGenericJobObject - * @param array $resultCurrent - * @return void - * @throws \App\Classes\Exceptions\MalformedRequestException - * @throws \App\Classes\Exceptions\JobResourceNotFoundException - */ - public function execute(ListGenericJobObject $listGenericJobObject, $resultCurrent) { - $jobResultCurrent = $this->fetchesJobResult->execute(['job_id' => $listGenericJobObject->getJobId()]); - $resultCurrentJson = json_encode($resultCurrent); - $resultSignatureCurrent = md5($resultCurrentJson); - - try{ - $jobResultExisting = $this->fetchesJobResult->execute(['request_signature' => $jobResultCurrent->request_signature, 'result_not_null' => true, 'order_by_id_desc' => true]); - $resultSignatureExisting = $jobResultExisting->result_signature; - //if($resultSignatureExisting != $resultSignatureCurrent){ - $this->updateJobResult($jobResultCurrent, $resultCurrentJson, $resultSignatureCurrent, $listGenericJobObject->getJobCommandName(), $listGenericJobObject->getJobCommand()); - //} - } catch (JobResourceNotFoundException $exception){ - $this->updateJobResult($jobResultCurrent, $resultCurrentJson, $resultSignatureCurrent, $listGenericJobObject->getJobCommandName(), $listGenericJobObject->getJobCommand()); - } - } - - private function updateJobResult($jobResultCurrent, $resultCurrentJson, $resultSignatureCurrent, $jobCommandName, $jobCommand){ - $updateJobResultObject = new UpdateJobResultObject( - $resultCurrentJson, - $resultSignatureCurrent, - $jobCommandName, - $jobCommand - ); - $create = $this->updatesJobResult->execute($jobResultCurrent, $updateJobResultObject); - } -} diff --git a/app/Classes/Modules/Jobs/Services/CreatesJobResult.php b/app/Classes/Modules/Jobs/Services/CreatesJobResult.php deleted file mode 100644 index e70e0e6a..00000000 --- a/app/Classes/Modules/Jobs/Services/CreatesJobResult.php +++ /dev/null @@ -1,26 +0,0 @@ -job_id = $listGenericJobObject->getJobId(); - $model->request_signature = $listGenericJobObject->getRequestSignature(); - $model->result_signature = $listGenericJobObject->getResultSignature(); - $model->url = $listGenericJobObject->getName(); - - return $this->handler($model); - } -} diff --git a/app/Classes/Modules/Jobs/Services/FetchesJobResult.php b/app/Classes/Modules/Jobs/Services/FetchesJobResult.php deleted file mode 100644 index 1cc99cb6..00000000 --- a/app/Classes/Modules/Jobs/Services/FetchesJobResult.php +++ /dev/null @@ -1,33 +0,0 @@ -repository = $repository; - } - - - /** - * @return Builder - */ - public function getRepository(): Builder - { - return $this->repository->newQuery(); - } -} diff --git a/app/Classes/Modules/Jobs/Services/ListsJobResult.php b/app/Classes/Modules/Jobs/Services/ListsJobResult.php deleted file mode 100644 index 55f3b267..00000000 --- a/app/Classes/Modules/Jobs/Services/ListsJobResult.php +++ /dev/null @@ -1,33 +0,0 @@ -repository = $repository; - } - - - /** - * @return Builder - */ - function getRepository(): Builder - { - return $this->repository->newQuery(); - } -} diff --git a/app/Classes/Modules/Jobs/Services/UpdatesJobResult.php b/app/Classes/Modules/Jobs/Services/UpdatesJobResult.php deleted file mode 100644 index ab3d9385..00000000 --- a/app/Classes/Modules/Jobs/Services/UpdatesJobResult.php +++ /dev/null @@ -1,28 +0,0 @@ -result = $updateJobResultObject->getResult(); - $model->result_signature = $updateJobResultObject->getResultSignature(); - $model->job_command_name = $updateJobResultObject->getJobCommandName(); - $model->job_command = $updateJobResultObject->getJobCommand(); - - return $this->handler($model); - - } -} diff --git a/app/Classes/Modules/Transactions/ControllersLogic/ListTransactionsJobLogic.php b/app/Classes/Modules/Transactions/ControllersLogic/ListTransactionsJobLogic.php deleted file mode 100644 index 654a360f..00000000 --- a/app/Classes/Modules/Transactions/ControllersLogic/ListTransactionsJobLogic.php +++ /dev/null @@ -1,74 +0,0 @@ - 'List Transaction Job', - 'message' => 'You have successfully submit a job to list transactions' - ]; - } - - /** @var CreatesJobResult */ - private $createsJobResult; - - /** - * ListTransactionsJobLogic constructor. - * @param CreatesJobResult $createsJobResult - */ - public function __construct(CreatesJobResult $createsJobResult) - { - $this->createsJobResult = $createsJobResult; - } - - - /** - * @param Request $request - * @return JsonResponse - */ - public function logic(Request $request) : JsonResponse - { - $jobId = uniqid(); - - $user = Auth::user(); - $userInfo = (object) [ - 'type' => $user->type, - ]; - - $userInfoJson = json_encode($userInfo); - $requestSignature = md5($userInfoJson . $request->fullUrl()); - - $listGenericJobObject = new ListGenericJobObject( - $request->fullUrl(), - $request->all(), - $requestSignature, - null, - $jobId, - $userInfo - ); - - ListTransactionsJob::dispatch($listGenericJobObject); - - $result = []; - $result['job_id'] = $jobId; - - $this->createsJobResult->execute($listGenericJobObject); - - return $this->response(['data' => $result]); - } - -} diff --git a/app/Classes/Modules/Transactions/Processors/ListTransactionsJobProcessor.php b/app/Classes/Modules/Transactions/Processors/ListTransactionsJobProcessor.php deleted file mode 100644 index 475d4715..00000000 --- a/app/Classes/Modules/Transactions/Processors/ListTransactionsJobProcessor.php +++ /dev/null @@ -1,45 +0,0 @@ -listsTransactions = $listsTransactions; - $this->updateJobResultProcessor = $updateJobResultProcessor; - } - - /** - * @param ListGenericJobObject $listGenericJobObject - * @return void - * @throws \App\Classes\Exceptions\MalformedRequestException - * @throws \App\Classes\Exceptions\JobResourceNotFoundException - */ - public function execute(ListGenericJobObject $listGenericJobObject) { - - $query = $this->listsTransactions->execute($this->listsTransactions->deserializeFilters($listGenericJobObject->getPayload()['filters']), ['page' => $listGenericJobObject->getPayload()['page']]); - - $resultCurrent = Helper::collectionResponse(ListTransactionJobResource::collection($query)); - $this->updateJobResultProcessor->execute($listGenericJobObject, $resultCurrent); - } -} - diff --git a/app/Http/Controllers/Bookings/ListBookingsJobController.php b/app/Http/Controllers/Bookings/ListBookingsJobController.php deleted file mode 100644 index 9b32fc77..00000000 --- a/app/Http/Controllers/Bookings/ListBookingsJobController.php +++ /dev/null @@ -1,22 +0,0 @@ -execute($request); - } -} diff --git a/app/Http/Controllers/Documents/ListDocumentsJobController.php b/app/Http/Controllers/Documents/ListDocumentsJobController.php deleted file mode 100644 index 8b763085..00000000 --- a/app/Http/Controllers/Documents/ListDocumentsJobController.php +++ /dev/null @@ -1,19 +0,0 @@ -execute($request); - } -} diff --git a/app/Http/Controllers/Jobs/FetchJobResultController.php b/app/Http/Controllers/Jobs/FetchJobResultController.php deleted file mode 100644 index cfef2f5c..00000000 --- a/app/Http/Controllers/Jobs/FetchJobResultController.php +++ /dev/null @@ -1,19 +0,0 @@ -execute($request); - } -} diff --git a/app/Http/Controllers/Transactions/ListTransactionsJobController.php b/app/Http/Controllers/Transactions/ListTransactionsJobController.php deleted file mode 100644 index fb341d5d..00000000 --- a/app/Http/Controllers/Transactions/ListTransactionsJobController.php +++ /dev/null @@ -1,21 +0,0 @@ -execute($request); - } -} diff --git a/app/Http/Resources/BookingResource.php b/app/Http/Resources/BookingResource.php index 70fbc95c..f3a7881d 100644 --- a/app/Http/Resources/BookingResource.php +++ b/app/Http/Resources/BookingResource.php @@ -11,9 +11,11 @@ use App\Classes\ValueObjects\Constants\TransactionType; use App\Classes\ValueObjects\Constants\DocumentType; use Carbon\Carbon; use Illuminate\Http\Resources\Json\JsonResource; +use Illuminate\Support\Facades\Log; class BookingResource extends JsonResource { + /** * Transform the resource into an array. * diff --git a/app/Http/Resources/CompanyResource.php b/app/Http/Resources/CompanyResource.php index eff2bd1b..85ecee16 100644 --- a/app/Http/Resources/CompanyResource.php +++ b/app/Http/Resources/CompanyResource.php @@ -15,6 +15,7 @@ use App\Models\SegmentConstant; use Carbon\Carbon; use Illuminate\Http\Resources\Json\JsonResource; use Illuminate\Support\Facades\Auth; +use Illuminate\Support\Facades\Log; class CompanyResource extends JsonResource { diff --git a/app/Http/Resources/DocumentResource.php b/app/Http/Resources/DocumentResource.php index c0f801bb..59933a67 100644 --- a/app/Http/Resources/DocumentResource.php +++ b/app/Http/Resources/DocumentResource.php @@ -3,7 +3,10 @@ namespace App\Http\Resources; use App\Models\Booking; +use App\Models\Company; +use App\Models\Document; use Carbon\Carbon; +use Illuminate\Database\Eloquent\Model; use Illuminate\Http\Resources\Json\JsonResource; class DocumentResource extends JsonResource diff --git a/app/Http/Resources/JobResultResource.php b/app/Http/Resources/JobResultResource.php deleted file mode 100644 index 51bc1898..00000000 --- a/app/Http/Resources/JobResultResource.php +++ /dev/null @@ -1,22 +0,0 @@ - $this->job_id, - 'result' => $this->result, - ]; - } -} diff --git a/app/Http/Resources/ListBookingJobResource.php b/app/Http/Resources/ListBookingJobResource.php deleted file mode 100644 index 06f8c38d..00000000 --- a/app/Http/Resources/ListBookingJobResource.php +++ /dev/null @@ -1,81 +0,0 @@ -userInfo = $userInfo ?? ($resource->userInfo ?? null); - } - - /** - * Transform the resource into an array. - * - * @param \Illuminate\Http\Request $request - * @return array - * @throws \Illuminate\Contracts\Container\BindingResolutionException - */ - public function toArray($request) - { - return [ - 'id' => $this->id, - 'company' => new CompanyResource($this->company, $this->userInfo), - 'bank' => new BankResource($this->bank), - 'service' => new ServiceTypeResource($this->service), - 'marking' => $this->marking, - 'amount' => $this->fix_amount, - 'floating_amount' => floatval((App()->make(CalculatesBookingFloatingAmount::class))->execute($this->resource, $this->fix_currency_id)), - 'paid_amount' => floatval((App()->make(CalculatesBookingPayableAmount::class))->execute($this->resource, $this->fix_currency_id)) - floatval((App()->make(CalculatesBookingRefundAmount::class))->execute($this->resource, $this->fix_currency_id)), - 'outstanding_amount' => floatval((App()->make(CalculatesBookingOutstanding::class))->execute($this->resource)) - floatval((App()->make(CalculatesBookingRefundAmount::class))->execute($this->resource, $this->fix_currency_id)), - 'fixed_currency' => new CurrencyResource($this->fixedCurrency), - 'convertible_currency' => new CurrencyResource($this->convertibleCurrency), - 'conversion_currency' => new CurrencyResource($this->conversionCurrency), - 'documents' => [ - 'purchase_order' => new DocumentResource($this->documents()->where('document_type', DocumentType::PURCHASE_ORDER)->first()), - 'delivery_order' => new DocumentResource($this->documents()->where('document_type', DocumentType::DELIVER_ORDER)->first()), - 'invoice' => new DocumentResource($this->documents()->where('document_type', DocumentType::INVOICE)->first()), - 'supplier_delivery_order' => new DocumentResource($this->documents()->where('document_type', DocumentType::SUPPLIER_DELIVER_ORDER)->first()), - 'proforma_invoice' => new DocumentResource($this->documents()->where('document_type', DocumentType::PROFORMA_INVOICE)->whereNotIn('status', [ApprovalStatus::REJECTED, ApprovalStatus::EXPIRED])->orderByDesc('id')->first()), - 'ecommerce_purchase_order' => new DocumentResource($this->documents()->where('document_type', DocumentType::ECOMMERCE_PURCHASE_ORDER)->first()), - ], - 'status' => $this->status, - 'created_at' => Carbon::parse($this->created_at)->format('d-m-Y'), - 'created_at_with_time' => Carbon::parse($this->created_at)->format('d-m-Y h:i:s A'), - $this->mergeWhen($this->relationLoaded('transactions'), [ - 'purchase_order' => new TransactionResource($this->transactions()->where('type', TransactionType::PURCHASE_ORDER)->first()), - 'payment_attempts' => TransactionResource::collection( - $this->transactions() - ->payments()->where('status', ApprovalStatus::PENDING_SUBMISSION) - ->whereDate('expires_on', '>=', Carbon::now()) - ->get() - ), - 'expired_payment_attempts' => TransactionResource::collection($this->transactions()->payments()->where('status', ApprovalStatus::PENDING_SUBMISSION)->whereDate('expires_on', '>=', Carbon::now())->where('expires_on', '>', Carbon::now()->toTimeString())->get()), - 'payment_history' => TransactionResource::collection($this->transactions()->where(function($query){ - $query->where(function($query){ - $query->payments()->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::PENDING_VERIFICATION, ApprovalStatus::COMPLETED, ApprovalStatus::REJECTED]); - })->orWhere(function($query){ - $query->where(function($query){ - $query->where('type', TransactionType::REFUND)->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::PENDING_VERIFICATION, ApprovalStatus::REJECTED, ApprovalStatus::COMPLETED]); - })->orWhere(function($query){ - $query->where('type', TransactionType::CREDIT_NOTE)->whereIn('status', [ApprovalStatus::PENDING_VERIFICATION, ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED]); - }); - }); - })->latest()->get()) - ]) - ]; - } -} diff --git a/app/Http/Resources/ListDocumentJobResource.php b/app/Http/Resources/ListDocumentJobResource.php deleted file mode 100644 index edf549ef..00000000 --- a/app/Http/Resources/ListDocumentJobResource.php +++ /dev/null @@ -1,31 +0,0 @@ - $this->id, - 'reference' => $this->reference, - 'status' => (int) $this->status, - 'document_type' => $this->document_type, - 'owner' => $this->relationLoaded('owner') ? ($this->owner instanceof Booking ? new BookingV2Resource($this->owner, $this->userInfo) : new CompanyV2Resource($this->owner, $this->userInfo)) : null, - 'files' => FileResource::collection($this->files), - 'created_at' => Carbon::parse($this->created_at)->format('d-m-Y h:i:s A') - ]; - } -} diff --git a/app/Http/Resources/ListTransactionJobResource.php b/app/Http/Resources/ListTransactionJobResource.php deleted file mode 100644 index 6c4c0ece..00000000 --- a/app/Http/Resources/ListTransactionJobResource.php +++ /dev/null @@ -1,54 +0,0 @@ -type, [TransactionType::BILL, TransactionType::REFUND])? $this->owner->owner : $this->owner; - $days = $this->created_at->endOfDay()->addWeekdays($booking->service_id === 3 ? 3 : 1); - - return [ - 'id' => $this->id, - 'booking' => new BookingResource($booking), - 'type' => (int) $this->type, - 'bill_no' => $this->bill_no, - 'payment_reference' => $this->payment_reference, - 'payment_method' => (float) $this->payment_method, - 'recipient_bank_account' => new BankResource($booking->bank), - 'issuer_name' => $this->issuerCompany->name, - 'issuer_id' => $this->issuerCompany->id, - 'amount' => (double) $this->amount, - 'original_amount' => (double) $this->original_amount, - 'currency' => new CurrencyResource($this->currency), - 'original_currency' => new CurrencyResource($this->original_currency), - 'service_charge' => (double) $this->service_charge, - 'tax' => (double) $this->tax, - 'currency_rate' => (double) $this->currency_rate, - 'status' => (int) $this->status, - 'details' => TransactionDetailResource::collection($this->transactionDetails), - 'documents' => new DocumentResource($this->documents()->first()), - 'transaction_bill' => new TransactionResource($this->when((int) $this->type === TransactionType::PAYMENT, $this->transactions()->bills()->first())), - 'transaction_refunds' => TransactionResource::collection($this->when((int) $this->type === TransactionType::PAYMENT, $this->transactions()->refunds()->get())), - 'expires_on' => Carbon::parse($this->expires_on)->format('d-m-Y h:i:s A'), - 'updated_at' => Carbon::parse($this->updated_at)->format('d-m-Y h:i:s A'), - 'interval' => [ - 'value' => $days->gt(Carbon::now()) ? '+' : '-', - 'duration' => $days->diff(Carbon::now())->format('%d'), - ], - 'redemption' => new VoucherRedemptionResource($this->voucherRedemption) - ]; - } -} diff --git a/app/Http/Resources/V2/BookingV2Resource.php b/app/Http/Resources/V2/BookingV2Resource.php deleted file mode 100644 index ee17181e..00000000 --- a/app/Http/Resources/V2/BookingV2Resource.php +++ /dev/null @@ -1,82 +0,0 @@ -userInfo = $userInfo ?? ($resource->userInfo ?? null); - } - - /** - * Transform the resource into an array. - * - * @param \Illuminate\Http\Request $request - * @return array - * @throws \Illuminate\Contracts\Container\BindingResolutionException - */ - public function toArray($request) - { - return [ - 'id' => $this->id, - 'company' => new CompanyV2Resource($this->company, $this->userInfo), - 'bank' => new V1\BankResource($this->bank), - 'service' => new V1\ServiceTypeResource($this->service), - 'marking' => $this->marking, - 'amount' => $this->fix_amount, - 'floating_amount' => floatval((App()->make(CalculatesBookingFloatingAmount::class))->execute($this->resource, $this->fix_currency_id)), - 'paid_amount' => floatval((App()->make(CalculatesBookingPayableAmount::class))->execute($this->resource, $this->fix_currency_id)) - floatval((App()->make(CalculatesBookingRefundAmount::class))->execute($this->resource, $this->fix_currency_id)), - 'outstanding_amount' => floatval((App()->make(CalculatesBookingOutstanding::class))->execute($this->resource)) - floatval((App()->make(CalculatesBookingRefundAmount::class))->execute($this->resource, $this->fix_currency_id)), - 'fixed_currency' => new V1\CurrencyResource($this->fixedCurrency), - 'convertible_currency' => new V1\CurrencyResource($this->convertibleCurrency), - 'conversion_currency' => new V1\CurrencyResource($this->conversionCurrency), - 'documents' => [ - 'purchase_order' => new V1\DocumentResource($this->documents()->where('document_type', DocumentType::PURCHASE_ORDER)->first()), - 'delivery_order' => new V1\DocumentResource($this->documents()->where('document_type', DocumentType::DELIVER_ORDER)->first()), - 'invoice' => new V1\DocumentResource($this->documents()->where('document_type', DocumentType::INVOICE)->first()), - 'supplier_delivery_order' => new V1\DocumentResource($this->documents()->where('document_type', DocumentType::SUPPLIER_DELIVER_ORDER)->first()), - 'proforma_invoice' => new V1\DocumentResource($this->documents()->where('document_type', DocumentType::PROFORMA_INVOICE)->whereNotIn('status', [ApprovalStatus::REJECTED, ApprovalStatus::EXPIRED])->orderByDesc('id')->first()), - 'ecommerce_purchase_order' => new V1\DocumentResource($this->documents()->where('document_type', DocumentType::ECOMMERCE_PURCHASE_ORDER)->first()), - ], - 'status' => $this->status, - 'created_at' => Carbon::parse($this->created_at)->format('d-m-Y'), - 'created_at_with_time' => Carbon::parse($this->created_at)->format('d-m-Y h:i:s A'), - $this->mergeWhen($this->relationLoaded('transactions'), [ - 'purchase_order' => new V1\TransactionResource($this->transactions()->where('type', TransactionType::PURCHASE_ORDER)->first()), - 'payment_attempts' => V1\TransactionResource::collection( - $this->transactions() - ->payments()->where('status', ApprovalStatus::PENDING_SUBMISSION) - ->whereDate('expires_on', '>=', Carbon::now()) - ->get() - ), - 'expired_payment_attempts' => V1\TransactionResource::collection($this->transactions()->payments()->where('status', ApprovalStatus::PENDING_SUBMISSION)->whereDate('expires_on', '>=', Carbon::now())->where('expires_on', '>', Carbon::now()->toTimeString())->get()), - 'payment_history' => V1\TransactionResource::collection($this->transactions()->where(function($query){ - $query->where(function($query){ - $query->payments()->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::PENDING_VERIFICATION, ApprovalStatus::COMPLETED, ApprovalStatus::REJECTED]); - })->orWhere(function($query){ - $query->where(function($query){ - $query->where('type', TransactionType::REFUND)->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::PENDING_VERIFICATION, ApprovalStatus::REJECTED, ApprovalStatus::COMPLETED]); - })->orWhere(function($query){ - $query->where('type', TransactionType::CREDIT_NOTE)->whereIn('status', [ApprovalStatus::PENDING_VERIFICATION, ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED]); - }); - }); - })->latest()->get()) - ]) - ]; - } -} diff --git a/app/Http/Resources/V2/CompanyV2Resource.php b/app/Http/Resources/V2/CompanyV2Resource.php deleted file mode 100644 index 64fca7c7..00000000 --- a/app/Http/Resources/V2/CompanyV2Resource.php +++ /dev/null @@ -1,100 +0,0 @@ -userInfo = $userInfo; - } - - /** - * Transform the resource into an array. - * - * @param \Illuminate\Http\Request $request - * @return array - */ - public function toArray($request) - { - $lastPayment = $this->transactions()->where('transactions.type', TransactionType::PAYMENT)->whereIn('transactions.status', [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED])->orderBy('id', 'DESC')->first(); - $totalPayments = $this->transactions()->where('transactions.type', TransactionType::PAYMENT)->whereIn('transactions.status', [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED])->sum('amount'); - - $segment = SegmentConstant::where('reference', SegmentConstants::SUPPLIER_CURRENCIES)->where('detail->id', $this->id)->first(); - $serviceCharge = SegmentConstant::where('reference', SegmentConstants::SERVICE_CHARGE)->where('detail->id', $this->id)->first(); - - $userResource = null; - - $userInfoEmail = $this->userInfo && isset($this->userInfo->email) ? $this->userInfo->email : null; - $userInfoType = $this->userInfo && isset($this->userInfo->type) ? $this->userInfo->type : null; - - if(!$userInfoEmail && Auth::user()){ - $userInfoEmail = Auth::user()->email; - } - if(!$userInfoType && Auth::user()){ - $userInfoType = Auth::user()->type; - } - - if(!is_null($userInfoEmail) && !is_null($userInfoType)){ - $userResource = new V1\UserResource($userInfoType === RoleTypes::USER ? $this->employees()->where('email', '=', $userInfoEmail)->first() : $this->employees()->orderBy('id', 'DESC')->first()); - } - - return [ - 'id' => $this->id, - 'name' => $this->name, - 'reference' => $this->reference, - 'debtor' => $this->debtor, - 'type' => (int) $this->type, - 'business_type' => (int) $this->business_type, - 'status' => (int) $this->status, - 'contact' => new V1\ContactResource ($this->when($this->has('contacts'), $this->contacts->first())), - 'address' => new V1\AddressResource($this->when($this->has('addresses'), $this->addresses->where('billing', true)->first())), - 'employee' => $userResource, - 'identification' => new V1\DocumentResource($this->documents->whereIn('document_type', DocumentType::IDENTIFICATION_DOCUMENTS)->first()), - 'bookings' => $this->whenLoaded('bookings', $this->bookings()->orderBy('id', 'DESC')->get(), []), - 'confirmed_bookings' => $this->bookings()->whereHas('transactions', function ($query){ - $query->where('type', TransactionType::PAYMENT)->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED]); - })->count(), - 'total_payments' => (float) $totalPayments, - 'average_spending_per_day' => (float) $totalPayments / ($this->created_at->diff(Carbon::now())->days === 0 ? 1 : $this->created_at->diff(Carbon::now())->days), - 'average_spending_per_booking' => (float) $totalPayments > 0 ? $totalPayments / $this->bookings()->whereHas('transactions', function ($query){ - $query->where('type', TransactionType::PAYMENT)->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED]); - })->count() : $totalPayments, - 'last_payment' => $lastPayment ? $lastPayment->created_at->diffForHumans() : 'No Payments', - 'personal_banks' => V1\BankResource::collection($this->banks->where('type', BankAccountType::PERSONAL)), - 'recipient_banks' => [ - 'accounts' => V1\BankResource::collection($this->banks->where('type', BankAccountType::EXTERNAL)), - 'default' => new V1\BankResource($this->banks->where('type', BankAccountType::EXTERNAL)->where('default', true)->first()) - ], - 'segments' => V1\SegmentResource::collection($this->segments), - 'seasonalSegment' => $this->whenLoaded('seasonalSegments', V1\SeasonalSegmentResource::collection($this->seasonalSegments)), - 'services' => (new FetchesCompanyServices())->getServices($this->servicesConfigurations()), - 'wallet' => $this->whenLoaded('wallets', new V1\WalletResource($this->wallets()->with('transactions')->first()), new V1\WalletResource($this->wallets()->first())), - 'created_at' => $this->created_at->format('d-m-Y'), - $this->mergeWhen($this->business_type === BusinessType::CURRENCY_VENDOR, [ - 'currencies' => $segment ? V1\CurrencyResource::collection(Currency::whereIn('id', $segment->detail->currencies)->get()) : [], - 'service_charge' => $serviceCharge - ]) - - ]; - } -} diff --git a/app/Models/JobResult.php b/app/Models/JobResult.php deleted file mode 100644 index f30b5076..00000000 --- a/app/Models/JobResult.php +++ /dev/null @@ -1,13 +0,0 @@ -id(); - $table->string('job_id', 50); - $table->longText('result')->nullable(); - $table->timestamps(); - - // $table->foreign('job_id')->references('id')->on('jobs')->onDelete('cascade'); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::dropIfExists('job_results'); - } -} diff --git a/database/migrations/2023_08_29_063531_add_new_column_to_job_results_table.php b/database/migrations/2023_08_29_063531_add_new_column_to_job_results_table.php deleted file mode 100644 index 8e6b8342..00000000 --- a/database/migrations/2023_08_29_063531_add_new_column_to_job_results_table.php +++ /dev/null @@ -1,36 +0,0 @@ -longText('url')->after('result')->nullable(); - $table->string('job_command_name')->after('url')->nullable(); - $table->longText('job_command')->after('job_command_name')->nullable(); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('job_results', function (Blueprint $table) { - $table->dropColumn('url'); - $table->dropColumn('job_command_name'); - $table->dropColumn('job_command'); - }); - } -} diff --git a/database/migrations/2023_12_11_193200_add_new_column_2_to_job_results_table.php b/database/migrations/2023_12_11_193200_add_new_column_2_to_job_results_table.php deleted file mode 100644 index 12c6d57f..00000000 --- a/database/migrations/2023_12_11_193200_add_new_column_2_to_job_results_table.php +++ /dev/null @@ -1,34 +0,0 @@ -string('request_signature')->after('job_id')->nullable(); - $table->string('result_signature')->after('request_signature')->nullable(); - }); - } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::table('job_results', function (Blueprint $table) { - $table->dropColumn('request_signature'); - $table->dropColumn('result_signature'); - }); - } -} diff --git a/resources/assets/vue/components/bookings/sections/AdminPaymentsBillingSectionComponent.vue b/resources/assets/vue/components/bookings/sections/AdminPaymentsBillingSectionComponent.vue deleted file mode 100644 index 966ccbbc..00000000 --- a/resources/assets/vue/components/bookings/sections/AdminPaymentsBillingSectionComponent.vue +++ /dev/null @@ -1,136 +0,0 @@ - - diff --git a/resources/assets/vue/components/bookings/sections/AdminPaymentsBillingSectionPollingComponent.vue b/resources/assets/vue/components/bookings/sections/AdminPaymentsBillingSectionPollingComponent.vue deleted file mode 100644 index 47d14857..00000000 --- a/resources/assets/vue/components/bookings/sections/AdminPaymentsBillingSectionPollingComponent.vue +++ /dev/null @@ -1,136 +0,0 @@ - - diff --git a/resources/assets/vue/components/bookings/sections/SupplierPendingOrdersSectionComponent.vue b/resources/assets/vue/components/bookings/sections/SupplierPendingOrdersSectionComponent.vue index d2b69080..7df9c125 100644 --- a/resources/assets/vue/components/bookings/sections/SupplierPendingOrdersSectionComponent.vue +++ b/resources/assets/vue/components/bookings/sections/SupplierPendingOrdersSectionComponent.vue @@ -117,17 +117,11 @@
- -
@@ -171,7 +165,7 @@ } }, created(){ - this.submit(route('api.company.list') + '?filters=' + JSON.stringify({'business_type': 3, 'status_in': [1, 2, 0]}), 'get', 'pendingOrdersSection', false, false); //cief todo: Uncaught (in promise) null + this.submit(route('api.company.list') + '?filters=' + JSON.stringify({'business_type': 3, 'status_in': [1, 2, 0]}), 'get', 'pendingOrdersSection', false, false) }, methods: { successHandler(response){ @@ -216,4 +210,4 @@ } - + \ No newline at end of file diff --git a/resources/assets/vue/components/general/elements/ListPollingComponent.vue b/resources/assets/vue/components/general/elements/ListPollingComponent.vue deleted file mode 100644 index fcd3b8b8..00000000 --- a/resources/assets/vue/components/general/elements/ListPollingComponent.vue +++ /dev/null @@ -1,213 +0,0 @@ - - - diff --git a/resources/assets/vue/general/mixins/aws/requestV2.js b/resources/assets/vue/general/mixins/aws/requestV2.js deleted file mode 100644 index 12b27542..00000000 --- a/resources/assets/vue/general/mixins/aws/requestV2.js +++ /dev/null @@ -1,49 +0,0 @@ -export default { - methods: { - poll(url, method, section, successNotification = true, errorNotification = true){ - if(!this.validate()){ return; } - if (section) { - this.$store.dispatch('toggleLoading', {name: section, status: true}) - } - this.$store.dispatch('crudRequestV2', { - endpoint: url, - method: method, - parameters: this.parameters - }).then(response => { - let statusCode = response.status, - success = response.ok; - - response.json().then(response => { - - if(!success){ - this.openModal(); - errorNotification ? this.$store.dispatch('createNotification', {title: response.title, message: response.message, type: 'error'}): null; - this.errorHandler(response, statusCode); return; - } - - successNotification ? this.$store.dispatch('createNotification', {title: response.title, message: response.message, type: 'success'}): null; - this.successHandler(response) - - - }); - }).catch((error) => { - this.$store.dispatch('createNotification', {title: 'Unexpected Error', message: 'An unexpected error has occurred. Try again!', type: 'error'}); - }).then(() => { - if (section) { - this.$store.dispatch('toggleLoading', {name: section, status: false}) - } - }) - - }, - validate() { - if(this.$v){ - this.$v.$touch(); - return !this.$v.$invalid; - } - return true; - }, - successHandler(response){}, - errorHandler(response){} - } - -} diff --git a/resources/assets/vue/general/mixins/tabHandler.js b/resources/assets/vue/general/mixins/tabHandler.js deleted file mode 100644 index 81790ed0..00000000 --- a/resources/assets/vue/general/mixins/tabHandler.js +++ /dev/null @@ -1,24 +0,0 @@ -export default { - data() { - return { - activeTab: null, - displayedTabs: [], - }; - }, - methods: { - setActiveTab(event) { - const tabName = event.currentTarget.getAttribute('tab-name'); - // console.log(`Tab "${tabName}" clicked`); - this.activeTab = tabName; - if (!this.displayedTabs.includes(tabName)) { - this.displayedTabs.push(tabName); - } - }, - isActiveTab(tabName) { - return this.activeTab === tabName; - }, - showTabContent(tabName) { - return this.displayedTabs.includes(tabName); - }, - }, -} diff --git a/resources/assets/vue/vuex/modules/crudRequestV2.js b/resources/assets/vue/vuex/modules/crudRequestV2.js deleted file mode 100644 index 355b1edb..00000000 --- a/resources/assets/vue/vuex/modules/crudRequestV2.js +++ /dev/null @@ -1,51 +0,0 @@ -export default { - actions: { - crudRequestV2({getters, dispatch}, {endpoint, method, parameters}){ - return dispatch('ensureReCaptchaIsSet').then(function () { - const queryDomain = endpoint.split('?')[0]; - let encodedParams = endpoint.split('?')[1]; - let decodedParams = fullyDecodeURI(encodedParams); - const queryParams = encodeURIComponent(decodedParams); - encodedParams = queryParams.toString(); - let filteredEncodedParams = encodedParams.replace(/%3D/g,'='); - filteredEncodedParams = filteredEncodedParams.replace(/%26/g,'&'); - let combinedAbsoluteUrl = queryDomain; - if(filteredEncodedParams !== undefined && filteredEncodedParams !== 'undefined'){ - combinedAbsoluteUrl = queryDomain + '?' + filteredEncodedParams; - } - - // return fetch(endpoint, { - return fetch(combinedAbsoluteUrl, { - method: method, - responseType: 'json', - body: parameters ? JSON.stringify(parameters):null, - headers: { - 'content-type': 'application/json', - 'Authorization': 'Bearer '+getters.getAccessToken, - 'captcha-token': getters.getReCaptcha - } - }).then(response => { - - if(response.status === 401 && window.location.href !== route('login')){ - dispatch('userAuthentication', {access_token: '', redirect_url: '/'}); - } - - return response; - - }) - }); - } - } -} - -function isEncoded(uri) { - uri = uri || ''; - return uri !== decodeURIComponent(uri); -} - -function fullyDecodeURI(uri){ - while (isEncoded(uri)){ - uri = decodeURIComponent(uri); - } - return uri; -} diff --git a/resources/assets/vue/vuex/store.js b/resources/assets/vue/vuex/store.js index ff10c673..2c3d911b 100644 --- a/resources/assets/vue/vuex/store.js +++ b/resources/assets/vue/vuex/store.js @@ -4,7 +4,6 @@ import toggleSection from './modules/toggleSection' import toggleLoading from './modules/toggleLoading' import createNotification from './modules/createNotification' import crudRequest from './modules/crudRequest' -import crudRequestV2 from './modules/crudRequestV2' import authentication from './modules/authentication' import loadRequestQueue from './modules/loadRequestQueue' @@ -17,7 +16,6 @@ export default new Vuex.Store({ loadRequestQueue, createNotification, crudRequest, - crudRequestV2, authentication } -}) +}) \ No newline at end of file diff --git a/resources/views/pages/billings.blade.php b/resources/views/pages/billings.blade.php index da84f8b9..4bc012d5 100644 --- a/resources/views/pages/billings.blade.php +++ b/resources/views/pages/billings.blade.php @@ -3,7 +3,129 @@
- + +
+
+
+
+
+
+
+
+
+
+
+
+ +
+
+
+
+
Invoice
+
+
+
+
+
+
+
+
+
+
+ +
+
+
+
+
Purchase Order
+
+
+
+
+
+
+
+
+
+
+ +
+
+
+
+
Delivery Order
+
+
+
+
+
+
+
+
+
+
+ +
+
+
+
+
Supplier Delivery Order
+
+
+
+
+
+
+
+
+
+
+
+
+
+ + + +
+
+ + + +
+
+ + + +
+
+ + + +
+
+
+
+
-@endsection +@endsection \ No newline at end of file diff --git a/resources/views/pages/billings_experiment.blade.php b/resources/views/pages/billings_experiment.blade.php deleted file mode 100644 index d1caee2d..00000000 --- a/resources/views/pages/billings_experiment.blade.php +++ /dev/null @@ -1,9 +0,0 @@ -@extends('layouts.base_portal') -@section('inner_content') -
-
- - -
-
-@endsection diff --git a/routes/api.php b/routes/api.php index 460bd772..8b4bada0 100644 --- a/routes/api.php +++ b/routes/api.php @@ -67,10 +67,6 @@ Route::group(['middleware' => 'api', 'prefix' => 'v1', 'as' => 'api.'], function require __DIR__ . '/milestone.php'; - // require __DIR__ . '/accounting.php'; //cief todo: To check if this is needed - - require __DIR__ . '/job.php'; - // require __DIR__ . '/rate.php'; // require __DIR__ . '/receipt.php'; diff --git a/routes/currency.php b/routes/currency.php index ba55c9a2..b621aad6 100644 --- a/routes/currency.php +++ b/routes/currency.php @@ -1,4 +1,4 @@ - 'document', 'as' => 'document.', 'namespace' => 'Documents'], function () { Route::get('/list', 'ListDocumentsController@list')->name('list'); - Route::get('/list/job', 'ListDocumentsJobController@list')->name('list.job'); Route::delete('/{id}/delete', 'DeleteDocumentController@delete')->name('delete'); Route::put('/{id}/approve', 'ApproveDocumentController@approve')->name('status.approve'); Route::put('/{id}/reject', 'RejectDocumentController@reject')->name('status.reject'); Route::put('/{id}/reference/update', 'UpdateDocumentReferenceController@update')->name('reference.update'); -}); +}); \ No newline at end of file diff --git a/routes/job.php b/routes/job.php deleted file mode 100644 index 028e9468..00000000 --- a/routes/job.php +++ /dev/null @@ -1,8 +0,0 @@ - 'job', 'as' => 'job.', 'namespace' => 'Jobs'], function () { - Route::get('/fetch/{job_id}', 'FetchJobResultController@fetch')->name('fetch'); - Route::get('/fetch/{job_id}/{is_last}', 'FetchJobResultController@fetch')->name('fetch.last.attempt'); -}); diff --git a/routes/web.php b/routes/web.php index a6590c17..bf2892bb 100644 --- a/routes/web.php +++ b/routes/web.php @@ -92,12 +92,6 @@ Route::get('/billings', function () { return view('pages.billings'); })->name('billings'); -/* Vue Polling Experiment - Starts */ -Route::get('/billings-experiment', function () { - return view('pages.billings_experiment'); -})->name('billings.experiment'); -/* Vue Polling Experiment - Ends */ - Route::get('/currency_orders', function () { return view('pages.currency_orders'); })->name('currency_orders'); @@ -836,13 +830,13 @@ Route::get('/invoice/{marking}/{started_at}/{ended_at}/fix', function($marking, ->withTrashed() ->orderBy('created_at', 'asc') ->first(); - + // get the first bill_no $firstBillNo = $firstInvoice->bill_no; if (strpos($firstBillNo, '-deleted') !== false) { $firstBillNo = substr($firstBillNo, 0, strpos($firstBillNo, '-deleted')); } - + // update currentInvoice bill_no to '-deleted-' $currentInvoice = $booking->transactions()->where('type', TransactionType::INVOICE)->first(); $currentInvoice->bill_no = $currentInvoice->bill_no ."-deleted-" . Str::random(10); @@ -865,4 +859,4 @@ Route::get('/invoice/{marking}/{started_at}/{ended_at}/fix', function($marking, } } ); -})->name('invoice.fix.byCustomerMarking'); +})->name('invoice.fix.byCustomerMarking'); \ No newline at end of file From f8230990f4f46348cd37551bd18fa1f75a2232d2 Mon Sep 17 00:00:00 2001 From: Dillon Ngo Date: Sun, 11 Feb 2024 10:28:05 +0000 Subject: [PATCH 25/59] Revert "Merge branch 'revert-b9668bb6' into 'master'" This reverts merge request !157 --- .../JobResourceNotFoundException.php | 11 + .../Abstracts/AbstractControllerLogic.php | 15 +- .../General/Eloquent/AbstractFetchRecord.php | 14 +- .../General/Eloquent/AbstractGetRecord.php | 26 ++- .../General/Eloquent/AbstractListRecord.php | 14 +- .../General/Eloquent/Filters/JobId.php | 20 ++ .../Eloquent/Filters/OrderByIdDesc.php | 20 ++ .../Eloquent/Filters/RequestSignature.php | 19 ++ .../Eloquent/Filters/ResultNotNull.php | 18 ++ app/Classes/General/Helper.php | 24 ++ app/Classes/Jobs/ListBookingsJob.php | 52 +++++ app/Classes/Jobs/ListDocumentsJob.php | 63 ++++++ app/Classes/Jobs/ListTransactionsJob.php | 52 +++++ .../ControllersLogic/ListBookingJobLogic.php | 75 ++++++ .../Processors/ListBookingsJobProcessor.php | 46 ++++ .../ControllersLogic/ListDocumentJobLogic.php | 75 ++++++ .../Processors/ListDocumentsJobProcessor.php | 47 ++++ .../ControllersLogic/FetchJobResultLogic.php | 51 +++++ .../ListGenericJobObject.php | 118 ++++++++++ .../UpdateJobResultObject.php | 60 +++++ .../Processors/FetchesJobResultProcessor.php | 47 ++++ .../Processors/UpdateJobResultProcessor.php | 64 ++++++ .../Jobs/Services/CreatesJobResult.php | 26 +++ .../Jobs/Services/FetchesJobResult.php | 33 +++ .../Modules/Jobs/Services/ListsJobResult.php | 33 +++ .../Jobs/Services/UpdatesJobResult.php | 28 +++ .../ListTransactionsJobLogic.php | 74 ++++++ .../ListTransactionsJobProcessor.php | 45 ++++ .../Bookings/ListBookingsJobController.php | 22 ++ .../Documents/ListDocumentsJobController.php | 19 ++ .../Jobs/FetchJobResultController.php | 19 ++ .../ListTransactionsJobController.php | 21 ++ app/Http/Resources/BookingResource.php | 2 - app/Http/Resources/CompanyResource.php | 1 - app/Http/Resources/DocumentResource.php | 3 - app/Http/Resources/JobResultResource.php | 22 ++ app/Http/Resources/ListBookingJobResource.php | 81 +++++++ .../Resources/ListDocumentJobResource.php | 31 +++ .../Resources/ListTransactionJobResource.php | 54 +++++ app/Http/Resources/V2/BookingV2Resource.php | 82 +++++++ app/Http/Resources/V2/CompanyV2Resource.php | 100 ++++++++ app/Models/JobResult.php | 13 ++ ..._08_08_124848_create_job_results_table.php | 35 +++ ...31_add_new_column_to_job_results_table.php | 36 +++ ..._add_new_column_2_to_job_results_table.php | 34 +++ .../AdminPaymentsBillingSectionComponent.vue | 136 +++++++++++ ...PaymentsBillingSectionPollingComponent.vue | 136 +++++++++++ .../SupplierPendingOrdersSectionComponent.vue | 10 +- .../general/elements/ListPollingComponent.vue | 213 ++++++++++++++++++ .../vue/general/mixins/aws/requestV2.js | 49 ++++ .../assets/vue/general/mixins/tabHandler.js | 24 ++ .../assets/vue/vuex/modules/crudRequestV2.js | 51 +++++ resources/assets/vue/vuex/store.js | 4 +- resources/views/pages/billings.blade.php | 126 +---------- .../views/pages/billings_experiment.blade.php | 9 + routes/api.php | 4 + routes/currency.php | 2 +- routes/document.php | 3 +- routes/job.php | 8 + routes/web.php | 12 +- 60 files changed, 2380 insertions(+), 152 deletions(-) create mode 100644 app/Classes/Exceptions/JobResourceNotFoundException.php create mode 100644 app/Classes/General/Eloquent/Filters/JobId.php create mode 100644 app/Classes/General/Eloquent/Filters/OrderByIdDesc.php create mode 100644 app/Classes/General/Eloquent/Filters/RequestSignature.php create mode 100644 app/Classes/General/Eloquent/Filters/ResultNotNull.php create mode 100644 app/Classes/Jobs/ListBookingsJob.php create mode 100644 app/Classes/Jobs/ListDocumentsJob.php create mode 100644 app/Classes/Jobs/ListTransactionsJob.php create mode 100644 app/Classes/Modules/Bookings/ControllersLogic/ListBookingJobLogic.php create mode 100644 app/Classes/Modules/Bookings/Processors/ListBookingsJobProcessor.php create mode 100644 app/Classes/Modules/Documents/ControllersLogic/ListDocumentJobLogic.php create mode 100644 app/Classes/Modules/Documents/Processors/ListDocumentsJobProcessor.php create mode 100644 app/Classes/Modules/Jobs/ControllersLogic/FetchJobResultLogic.php create mode 100644 app/Classes/Modules/Jobs/DataTransferObjects/ListGenericJobObject.php create mode 100644 app/Classes/Modules/Jobs/DataTransferObjects/UpdateJobResultObject.php create mode 100644 app/Classes/Modules/Jobs/Processors/FetchesJobResultProcessor.php create mode 100644 app/Classes/Modules/Jobs/Processors/UpdateJobResultProcessor.php create mode 100644 app/Classes/Modules/Jobs/Services/CreatesJobResult.php create mode 100644 app/Classes/Modules/Jobs/Services/FetchesJobResult.php create mode 100644 app/Classes/Modules/Jobs/Services/ListsJobResult.php create mode 100644 app/Classes/Modules/Jobs/Services/UpdatesJobResult.php create mode 100644 app/Classes/Modules/Transactions/ControllersLogic/ListTransactionsJobLogic.php create mode 100644 app/Classes/Modules/Transactions/Processors/ListTransactionsJobProcessor.php create mode 100644 app/Http/Controllers/Bookings/ListBookingsJobController.php create mode 100644 app/Http/Controllers/Documents/ListDocumentsJobController.php create mode 100644 app/Http/Controllers/Jobs/FetchJobResultController.php create mode 100644 app/Http/Controllers/Transactions/ListTransactionsJobController.php create mode 100644 app/Http/Resources/JobResultResource.php create mode 100644 app/Http/Resources/ListBookingJobResource.php create mode 100644 app/Http/Resources/ListDocumentJobResource.php create mode 100644 app/Http/Resources/ListTransactionJobResource.php create mode 100644 app/Http/Resources/V2/BookingV2Resource.php create mode 100644 app/Http/Resources/V2/CompanyV2Resource.php create mode 100644 app/Models/JobResult.php create mode 100644 database/migrations/2023_08_08_124848_create_job_results_table.php create mode 100644 database/migrations/2023_08_29_063531_add_new_column_to_job_results_table.php create mode 100644 database/migrations/2023_12_11_193200_add_new_column_2_to_job_results_table.php create mode 100644 resources/assets/vue/components/bookings/sections/AdminPaymentsBillingSectionComponent.vue create mode 100644 resources/assets/vue/components/bookings/sections/AdminPaymentsBillingSectionPollingComponent.vue create mode 100644 resources/assets/vue/components/general/elements/ListPollingComponent.vue create mode 100644 resources/assets/vue/general/mixins/aws/requestV2.js create mode 100644 resources/assets/vue/general/mixins/tabHandler.js create mode 100644 resources/assets/vue/vuex/modules/crudRequestV2.js create mode 100644 resources/views/pages/billings_experiment.blade.php create mode 100644 routes/job.php diff --git a/app/Classes/Exceptions/JobResourceNotFoundException.php b/app/Classes/Exceptions/JobResourceNotFoundException.php new file mode 100644 index 00000000..a8ef358e --- /dev/null +++ b/app/Classes/Exceptions/JobResourceNotFoundException.php @@ -0,0 +1,11 @@ +getMessage(), + $exception->getTrace()[0]['file'], + $exception->getTrace()[0]['line'] + )); + } + else{ + log::error($exception); + } + return (new ApiResponseObject($this->getNotificationTitle().' failed', $exception->getMessage(), $exception->getCode() ? $exception->getCode() : HttpStatus::SERVER_ERROR))->handler(); diff --git a/app/Classes/General/Eloquent/AbstractFetchRecord.php b/app/Classes/General/Eloquent/AbstractFetchRecord.php index 248deee7..503fb369 100644 --- a/app/Classes/General/Eloquent/AbstractFetchRecord.php +++ b/app/Classes/General/Eloquent/AbstractFetchRecord.php @@ -4,9 +4,11 @@ namespace App\Classes\General\Eloquent; use App\Classes\Exceptions\ResourceNotFoundException; +use App\Classes\Exceptions\JobResourceNotFoundException; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; use Psy\Exception\ErrorException; +use Illuminate\Support\Facades\Log; abstract class AbstractFetchRecord extends AbstractGetRecord { @@ -27,12 +29,18 @@ abstract class AbstractFetchRecord extends AbstractGetRecord * @return Model * @throws ResourceNotFoundException */ - public function getResults(Builder $query): Model { + public function getResults(Builder $query, array $param = []): Model { if(!$query->exists()){ - throw new ResourceNotFoundException('Unable to find any record based on the criteria provided'); + $table = $query->getModel()->getTable(); + if($table ==='job_results'){ + throw new JobResourceNotFoundException('Unable to find any job based on the criteria provided'); + } + else{ + throw new ResourceNotFoundException('Unable to find any record based on the criteria provided'); + } } return $query->first(); } -} \ No newline at end of file +} diff --git a/app/Classes/General/Eloquent/AbstractGetRecord.php b/app/Classes/General/Eloquent/AbstractGetRecord.php index f927d818..1a7eac3e 100644 --- a/app/Classes/General/Eloquent/AbstractGetRecord.php +++ b/app/Classes/General/Eloquent/AbstractGetRecord.php @@ -30,11 +30,25 @@ abstract class AbstractGetRecord return $this->filters->only(self::DECORATION_FILTERS); } + // /** + // * @param null|string $json + // * @return array + // */ + // public function deserializeFilters(?string $json): array { + // return $json !== null ? collect(json_decode($json))->toArray() : []; + // } + /** - * @param null|string $json + * @param null|string $param * @return array */ - public function deserializeFilters(?string $json): array { + public function deserializeFilters($param): array { + if(gettype($param) == "array"){ + $json = implode(',', $param); + } + else{ + $json = $param; + } return $json !== null ? collect(json_decode($json))->toArray() : []; } @@ -50,9 +64,9 @@ abstract class AbstractGetRecord * @param array $filters * @return mixed */ - public function handler(array $filters){ + public function handler(array $filters, array $params = []){ $this->filters = collect($filters); - return $this->getResults($this->applyFiltersToQuery()); + return $this->getResults($this->applyFiltersToQuery(), $params); } @@ -65,6 +79,6 @@ abstract class AbstractGetRecord * @param Builder $query * @return mixed */ - abstract function getResults(Builder $query); + abstract function getResults(Builder $query, array $params = []); -} \ No newline at end of file +} diff --git a/app/Classes/General/Eloquent/AbstractListRecord.php b/app/Classes/General/Eloquent/AbstractListRecord.php index 7b7d0df9..f898f108 100644 --- a/app/Classes/General/Eloquent/AbstractListRecord.php +++ b/app/Classes/General/Eloquent/AbstractListRecord.php @@ -17,11 +17,11 @@ abstract class AbstractListRecord extends AbstractGetRecord * @return mixed * @throws MalformedRequestException */ - public function execute(array $filters = []){ + public function execute(array $filters = [], array $param = []){ try{ - return $this->handler($filters); + return $this->handler($filters, $param); } catch (QueryException $exception){ log::error($exception); @@ -30,18 +30,24 @@ abstract class AbstractListRecord extends AbstractGetRecord } + /** * @param Builder $query * @return mixed */ - public function getResults(Builder $query) { + public function getResults(Builder $query, array $param = []) { $filters = $this->getDecorationFilters(); if($filters->has('order_by')){ $query = $query->orderBy($filters->get('order_by')->column, $filters->get('order_by')->DESC ? 'DESC': 'ASC'); } - return $filters->has('per_page') ? $query->paginate($filters->get('per_page')) : $query->get(); + if(!empty($param)){ + return $filters->has('per_page') ? $query->paginate($filters->get('per_page'), ['*'], 'page', $param['page']) : $query->get(); //page data from query parameters e.g ?page=1 + } + else{ + return $filters->has('per_page') ? $query->paginate($filters->get('per_page')) : $query->get(); + } } diff --git a/app/Classes/General/Eloquent/Filters/JobId.php b/app/Classes/General/Eloquent/Filters/JobId.php new file mode 100644 index 00000000..42ac51a4 --- /dev/null +++ b/app/Classes/General/Eloquent/Filters/JobId.php @@ -0,0 +1,20 @@ +where('job_id', $value); + } + +} diff --git a/app/Classes/General/Eloquent/Filters/OrderByIdDesc.php b/app/Classes/General/Eloquent/Filters/OrderByIdDesc.php new file mode 100644 index 00000000..547ec9bd --- /dev/null +++ b/app/Classes/General/Eloquent/Filters/OrderByIdDesc.php @@ -0,0 +1,20 @@ +orderBy('id', 'desc'); + } + +} diff --git a/app/Classes/General/Eloquent/Filters/RequestSignature.php b/app/Classes/General/Eloquent/Filters/RequestSignature.php new file mode 100644 index 00000000..67dde0a3 --- /dev/null +++ b/app/Classes/General/Eloquent/Filters/RequestSignature.php @@ -0,0 +1,19 @@ +where('request_signature', $value); + } + +} diff --git a/app/Classes/General/Eloquent/Filters/ResultNotNull.php b/app/Classes/General/Eloquent/Filters/ResultNotNull.php new file mode 100644 index 00000000..3f6a0341 --- /dev/null +++ b/app/Classes/General/Eloquent/Filters/ResultNotNull.php @@ -0,0 +1,18 @@ +whereNotNull('result'); + } +} diff --git a/app/Classes/General/Helper.php b/app/Classes/General/Helper.php index ac89540b..45c72f53 100644 --- a/app/Classes/General/Helper.php +++ b/app/Classes/General/Helper.php @@ -2,6 +2,7 @@ namespace App\Classes\General; +use Illuminate\Http\Resources\Json\ResourceCollection; use Illuminate\Support\Facades\Log; use Illuminate\Support\Str; @@ -42,4 +43,27 @@ class Helper } } } + + /** + * @param null|string $param + * @return array + */ + static function deserializeFilters($param): array { + if(gettype($param) == "array"){ + $json = implode(',', $param); + } + else{ + $json = $param; + } + return $json !== null ? collect(json_decode($json))->toArray() : []; + } + + /** + * @param ResourceCollection $collection + * @return array + */ + static function collectionResponse(ResourceCollection $collection){ + return json_decode($collection->response()->getContent(), true); + } + } diff --git a/app/Classes/Jobs/ListBookingsJob.php b/app/Classes/Jobs/ListBookingsJob.php new file mode 100644 index 00000000..b021b71d --- /dev/null +++ b/app/Classes/Jobs/ListBookingsJob.php @@ -0,0 +1,52 @@ +listGenericJobObject = $listGenericJobObject; + } + + public function handle() + { + $rawPayload = $this->job->payload(); + if(isset($rawPayload['data']['commandName'])){ + $this->listGenericJobObject->setJobCommandName($rawPayload['data']['commandName']); + } + + if(isset($rawPayload['data']['command'])){ + $this->listGenericJobObject->setJobCommand($rawPayload['data']['command']); + } + + $result = (App()->make(ListBookingsJobProcessor::class))->execute($this->listGenericJobObject); + } + + public function getJobId(){ + return $this->job->getJobId(); + } +} diff --git a/app/Classes/Jobs/ListDocumentsJob.php b/app/Classes/Jobs/ListDocumentsJob.php new file mode 100644 index 00000000..6e93062b --- /dev/null +++ b/app/Classes/Jobs/ListDocumentsJob.php @@ -0,0 +1,63 @@ +listGenericJobObject = $listGenericJobObject; + } + + public function handle() + { + $rawPayload = $this->job->payload(); + if(isset($rawPayload['data']['commandName'])){ + $this->listGenericJobObject->setJobCommandName($rawPayload['data']['commandName']); + } + + if(isset($rawPayload['data']['command'])){ + $this->listGenericJobObject->setJobCommand($rawPayload['data']['command']); + } + + $result = (App()->make(ListDocumentsJobProcessor::class))->execute($this->listGenericJobObject); + + //cief todo: Insert into DB: job id, query result, timestamp + // Store the result in the job_results table + + //cief todo: why cannot save data in table like this + // $model = new JobResult(); + // $model->job_id = $this->job->getJobId(); + // $model->result = json_encode($result); + // $model->save(); + + // Log::error(json_encode($model->id)); + } + + public function getJobId(){ + return $this->job->getJobId(); + } +} diff --git a/app/Classes/Jobs/ListTransactionsJob.php b/app/Classes/Jobs/ListTransactionsJob.php new file mode 100644 index 00000000..a2b28656 --- /dev/null +++ b/app/Classes/Jobs/ListTransactionsJob.php @@ -0,0 +1,52 @@ +listGenericJobObject = $listGenericJobObject; + } + + public function handle() + { + $rawPayload = $this->job->payload(); + if(isset($rawPayload['data']['commandName'])){ + $this->listGenericJobObject->setJobCommandName($rawPayload['data']['commandName']); + } + + if(isset($rawPayload['data']['command'])){ + $this->listGenericJobObject->setJobCommand($rawPayload['data']['command']); + } + + $result = (App()->make(ListTransactionsJobProcessor::class))->execute($this->listGenericJobObject); + } + + public function getJobId(){ + return $this->job->getJobId(); + } +} diff --git a/app/Classes/Modules/Bookings/ControllersLogic/ListBookingJobLogic.php b/app/Classes/Modules/Bookings/ControllersLogic/ListBookingJobLogic.php new file mode 100644 index 00000000..ef3570f7 --- /dev/null +++ b/app/Classes/Modules/Bookings/ControllersLogic/ListBookingJobLogic.php @@ -0,0 +1,75 @@ + 'List Booking Job', + 'message' => 'You have successfully submit a job to list bookings' + ]; + } + + /** @var CreatesJobResult */ + private $createsJobResult; + + /** + * ListPackingListsJobLogic constructor. + * @param CreatesJobResult $createsJobResult + */ + public function __construct(CreatesJobResult $createsJobResult) + { + $this->createsJobResult = $createsJobResult; + } + + + /** + * @param Request $request + * @return JsonResponse + */ + public function logic(Request $request) : JsonResponse + { + $jobId = uniqid(); + + $user = Auth::user(); + $userInfo = (object) [ + 'type' => $user->type, + ]; + + $userInfoJson = json_encode($userInfo); + $requestSignature = md5($userInfoJson . $request->fullUrl()); + + $listGenericJobObject = new ListGenericJobObject( + $request->fullUrl(), + $request->all(), + $requestSignature, + null, + $jobId, + $userInfo + ); + + ListBookingsJob::dispatch($listGenericJobObject); + + $result = []; + $result['job_id'] = $jobId; + + $this->createsJobResult->execute($listGenericJobObject); + + return $this->response(['data' => $result]); + } + +} diff --git a/app/Classes/Modules/Bookings/Processors/ListBookingsJobProcessor.php b/app/Classes/Modules/Bookings/Processors/ListBookingsJobProcessor.php new file mode 100644 index 00000000..2a09eb12 --- /dev/null +++ b/app/Classes/Modules/Bookings/Processors/ListBookingsJobProcessor.php @@ -0,0 +1,46 @@ +listsBookings = $listsBookings; + $this->updateJobResultProcessor = $updateJobResultProcessor; + } + + /** + * @param ListGenericJobObject $listGenericJobObject + * @return void + * @throws \App\Classes\Exceptions\MalformedRequestException + * @throws \App\Classes\Exceptions\JobResourceNotFoundException + */ + public function execute(ListGenericJobObject $listGenericJobObject) { + + $query = $this->listsBookings->execute($this->listsBookings->deserializeFilters($listGenericJobObject->getPayload()['filters']), ['page' => $listGenericJobObject->getPayload()['page']]); + foreach ($query->items() as &$item) { + $item['userInfo'] = $listGenericJobObject->getUserInfo(); + } + $resultCurrent = Helper::collectionResponse(ListBookingJobResource::collection($query)); + $this->updateJobResultProcessor->execute($listGenericJobObject, $resultCurrent); + } +} diff --git a/app/Classes/Modules/Documents/ControllersLogic/ListDocumentJobLogic.php b/app/Classes/Modules/Documents/ControllersLogic/ListDocumentJobLogic.php new file mode 100644 index 00000000..5e895ad8 --- /dev/null +++ b/app/Classes/Modules/Documents/ControllersLogic/ListDocumentJobLogic.php @@ -0,0 +1,75 @@ + 'List Document Job', + 'message' => 'You have successfully submit a job to list documents' + ]; + } + + /** @var CreatesJobResult */ + private $createsJobResult; + + /** + * ListDocumentJobLogic constructor. + * @param CreatesJobResult $createsJobResult + */ + public function __construct(CreatesJobResult $createsJobResult) + { + $this->createsJobResult = $createsJobResult; + } + + + /** + * @param Request $request + * @return JsonResponse + */ + public function logic(Request $request) : JsonResponse + { + $jobId = uniqid(); + + $user = Auth::user(); + $userInfo = (object) [ + 'email' => $user->email, + 'type' => $user->type, + ]; + + $userInfoJson = json_encode($userInfo); + $requestSignature = md5($userInfoJson . $request->fullUrl()); + + $listGenericJobObject = new ListGenericJobObject( + $request->fullUrl(), + $request->all(), + $requestSignature, + null, + $jobId, + $userInfo + ); + + ListDocumentsJob::dispatch($listGenericJobObject); + + $result = []; + $result['job_id'] = $jobId; + + $this->createsJobResult->execute($listGenericJobObject); + + return $this->response(['data' => $result]); + } +} diff --git a/app/Classes/Modules/Documents/Processors/ListDocumentsJobProcessor.php b/app/Classes/Modules/Documents/Processors/ListDocumentsJobProcessor.php new file mode 100644 index 00000000..70777f0c --- /dev/null +++ b/app/Classes/Modules/Documents/Processors/ListDocumentsJobProcessor.php @@ -0,0 +1,47 @@ +listsDocuments = $listsDocuments; + $this->updateJobResultProcessor = $updateJobResultProcessor; + } + + /** + * @param ListGenericJobObject $listGenericJobObject + * @return void + * @throws \App\Classes\Exceptions\MalformedRequestException + * @throws \App\Classes\Exceptions\JobResourceNotFoundException + */ + public function execute(ListGenericJobObject $listGenericJobObject) { + + $query = $this->listsDocuments->execute($this->listsDocuments->deserializeFilters($listGenericJobObject->getPayload()['filters']), ['page' => $listGenericJobObject->getPayload()['page']]); + foreach ($query->items() as &$item) { + $item['userInfo'] = $listGenericJobObject->getUserInfo(); + } + $resultCurrent = Helper::collectionResponse(ListDocumentJobResource::collection($query)); + $this->updateJobResultProcessor->execute($listGenericJobObject, $resultCurrent); + } +} + diff --git a/app/Classes/Modules/Jobs/ControllersLogic/FetchJobResultLogic.php b/app/Classes/Modules/Jobs/ControllersLogic/FetchJobResultLogic.php new file mode 100644 index 00000000..c4b72cf0 --- /dev/null +++ b/app/Classes/Modules/Jobs/ControllersLogic/FetchJobResultLogic.php @@ -0,0 +1,51 @@ + 'Retrieved Data', + 'message' => 'You have successfully retrieved data' + ]; + } + + /** @var FetchesJobResultProcessor */ + private $fetchesJobResultProcessor; + + /** + * FetchJobResultLogic constructor. + * @param FetchesJobResultProcessor $fetchesJobResultProcessor + */ + public function __construct(FetchesJobResultProcessor $fetchesJobResultProcessor) + { + $this->fetchesJobResultProcessor = $fetchesJobResultProcessor; + } + + + /** + * @param Request $request + * @return JsonResponse + * @throws \App\Classes\Exceptions\AccessForbiddenException + * @throws \App\Classes\Exceptions\MalformedRequestException + * @throws \App\Classes\Exceptions\RequestValidationException + */ + public function logic(Request $request) : JsonResponse + { + $query = $this->fetchesJobResultProcessor->execute($request); + return $this->resourceResponse(new JobResultResource($query)); + } + +} diff --git a/app/Classes/Modules/Jobs/DataTransferObjects/ListGenericJobObject.php b/app/Classes/Modules/Jobs/DataTransferObjects/ListGenericJobObject.php new file mode 100644 index 00000000..953d77d7 --- /dev/null +++ b/app/Classes/Modules/Jobs/DataTransferObjects/ListGenericJobObject.php @@ -0,0 +1,118 @@ +name = $name; + $this->payload = $payload; + $this->jobId = $jobId; + $this->requestSignature = $requestSignature; + $this->resultSignature = $resultSignature; + $this->userInfo = $userInfo; + } + + /** + * @return string + */ + public function getName(): string + { + return $this->name; + } + + /** + * @return array + */ + public function getPayload(): array + { + return $this->payload; + } + + /** + * @return string + */ + public function getJobId(): string + { + return $this->jobId; + } + + /** + * @return string + */ + public function getRequestSignature(): string + { + return $this->requestSignature; + } + + /** + * @return string + */ + public function getResultSignature(): ?string + { + return $this->resultSignature; + } + + /** + * @return object + */ + public function getUserInfo(): object + { + return $this->userInfo; + } + + /** + * @return string + */ + public function getJobCommandName(): string + { + return $this->jobCommandName; + } + + /** + * @return string + */ + public function getJobCommand(): string + { + return $this->jobCommand; + } + + + public function setJobCommandName(string $jobCommandName) + { + $this->jobCommandName = $jobCommandName; + } + + public function setJobCommand(string $jobCommand) + { + $this->jobCommand = $jobCommand; + } + +} diff --git a/app/Classes/Modules/Jobs/DataTransferObjects/UpdateJobResultObject.php b/app/Classes/Modules/Jobs/DataTransferObjects/UpdateJobResultObject.php new file mode 100644 index 00000000..636c56b0 --- /dev/null +++ b/app/Classes/Modules/Jobs/DataTransferObjects/UpdateJobResultObject.php @@ -0,0 +1,60 @@ +result = $result; + $this->resultSignature = $resultSignature; + $this->jobCommandName = $jobCommandName; + $this->jobCommand = $jobCommand; + } + + /** + * @return string + */ + public function getResult(): string + { + return $this->result; + } + + /** + * @return array + */ + public function getResultSignature(): string + { + return $this->resultSignature; + } + + /** + * @return string + */ + public function getJobCommandName(): string + { + return $this->jobCommandName; + } + + /** + * @return string + */ + public function getJobCommand(): string + { + return $this->jobCommand; + } +} diff --git a/app/Classes/Modules/Jobs/Processors/FetchesJobResultProcessor.php b/app/Classes/Modules/Jobs/Processors/FetchesJobResultProcessor.php new file mode 100644 index 00000000..89783fe8 --- /dev/null +++ b/app/Classes/Modules/Jobs/Processors/FetchesJobResultProcessor.php @@ -0,0 +1,47 @@ +fetchesJobResult = $fetchesJobResult; + } + + + /** + * @param Request $request + * @return Model + * @throws \App\Classes\Exceptions\MalformedRequestException + * @throws \App\Classes\Exceptions\JobResourceNotFoundException + * @throws \App\Classes\Exceptions\ResourceNotFoundException + */ + public function execute(Request $request){ + + $res1 = $this->fetchesJobResult->execute(['job_id' => $request->route('job_id')]); + if($request->route('is_last')){ + $res2 = $this->fetchesJobResult->execute(['request_signature' => $res1->request_signature, 'result_not_null' => true, 'order_by_id_desc' => true]); + return $res2; + } + + if(!$res1->result){ + throw new JobResourceNotFoundException('Unable to find any job based on the criteria provided'); + } + + return $res1; + } +} diff --git a/app/Classes/Modules/Jobs/Processors/UpdateJobResultProcessor.php b/app/Classes/Modules/Jobs/Processors/UpdateJobResultProcessor.php new file mode 100644 index 00000000..0106417d --- /dev/null +++ b/app/Classes/Modules/Jobs/Processors/UpdateJobResultProcessor.php @@ -0,0 +1,64 @@ +fetchesJobResult = $fetchesJobResult; + $this->updatesJobResult = $updatesJobResult; + } + + /** + * @param ListGenericJobObject $listGenericJobObject + * @param array $resultCurrent + * @return void + * @throws \App\Classes\Exceptions\MalformedRequestException + * @throws \App\Classes\Exceptions\JobResourceNotFoundException + */ + public function execute(ListGenericJobObject $listGenericJobObject, $resultCurrent) { + $jobResultCurrent = $this->fetchesJobResult->execute(['job_id' => $listGenericJobObject->getJobId()]); + $resultCurrentJson = json_encode($resultCurrent); + $resultSignatureCurrent = md5($resultCurrentJson); + + try{ + $jobResultExisting = $this->fetchesJobResult->execute(['request_signature' => $jobResultCurrent->request_signature, 'result_not_null' => true, 'order_by_id_desc' => true]); + $resultSignatureExisting = $jobResultExisting->result_signature; + //if($resultSignatureExisting != $resultSignatureCurrent){ + $this->updateJobResult($jobResultCurrent, $resultCurrentJson, $resultSignatureCurrent, $listGenericJobObject->getJobCommandName(), $listGenericJobObject->getJobCommand()); + //} + } catch (JobResourceNotFoundException $exception){ + $this->updateJobResult($jobResultCurrent, $resultCurrentJson, $resultSignatureCurrent, $listGenericJobObject->getJobCommandName(), $listGenericJobObject->getJobCommand()); + } + } + + private function updateJobResult($jobResultCurrent, $resultCurrentJson, $resultSignatureCurrent, $jobCommandName, $jobCommand){ + $updateJobResultObject = new UpdateJobResultObject( + $resultCurrentJson, + $resultSignatureCurrent, + $jobCommandName, + $jobCommand + ); + $create = $this->updatesJobResult->execute($jobResultCurrent, $updateJobResultObject); + } +} diff --git a/app/Classes/Modules/Jobs/Services/CreatesJobResult.php b/app/Classes/Modules/Jobs/Services/CreatesJobResult.php new file mode 100644 index 00000000..e70e0e6a --- /dev/null +++ b/app/Classes/Modules/Jobs/Services/CreatesJobResult.php @@ -0,0 +1,26 @@ +job_id = $listGenericJobObject->getJobId(); + $model->request_signature = $listGenericJobObject->getRequestSignature(); + $model->result_signature = $listGenericJobObject->getResultSignature(); + $model->url = $listGenericJobObject->getName(); + + return $this->handler($model); + } +} diff --git a/app/Classes/Modules/Jobs/Services/FetchesJobResult.php b/app/Classes/Modules/Jobs/Services/FetchesJobResult.php new file mode 100644 index 00000000..1cc99cb6 --- /dev/null +++ b/app/Classes/Modules/Jobs/Services/FetchesJobResult.php @@ -0,0 +1,33 @@ +repository = $repository; + } + + + /** + * @return Builder + */ + public function getRepository(): Builder + { + return $this->repository->newQuery(); + } +} diff --git a/app/Classes/Modules/Jobs/Services/ListsJobResult.php b/app/Classes/Modules/Jobs/Services/ListsJobResult.php new file mode 100644 index 00000000..55f3b267 --- /dev/null +++ b/app/Classes/Modules/Jobs/Services/ListsJobResult.php @@ -0,0 +1,33 @@ +repository = $repository; + } + + + /** + * @return Builder + */ + function getRepository(): Builder + { + return $this->repository->newQuery(); + } +} diff --git a/app/Classes/Modules/Jobs/Services/UpdatesJobResult.php b/app/Classes/Modules/Jobs/Services/UpdatesJobResult.php new file mode 100644 index 00000000..ab3d9385 --- /dev/null +++ b/app/Classes/Modules/Jobs/Services/UpdatesJobResult.php @@ -0,0 +1,28 @@ +result = $updateJobResultObject->getResult(); + $model->result_signature = $updateJobResultObject->getResultSignature(); + $model->job_command_name = $updateJobResultObject->getJobCommandName(); + $model->job_command = $updateJobResultObject->getJobCommand(); + + return $this->handler($model); + + } +} diff --git a/app/Classes/Modules/Transactions/ControllersLogic/ListTransactionsJobLogic.php b/app/Classes/Modules/Transactions/ControllersLogic/ListTransactionsJobLogic.php new file mode 100644 index 00000000..654a360f --- /dev/null +++ b/app/Classes/Modules/Transactions/ControllersLogic/ListTransactionsJobLogic.php @@ -0,0 +1,74 @@ + 'List Transaction Job', + 'message' => 'You have successfully submit a job to list transactions' + ]; + } + + /** @var CreatesJobResult */ + private $createsJobResult; + + /** + * ListTransactionsJobLogic constructor. + * @param CreatesJobResult $createsJobResult + */ + public function __construct(CreatesJobResult $createsJobResult) + { + $this->createsJobResult = $createsJobResult; + } + + + /** + * @param Request $request + * @return JsonResponse + */ + public function logic(Request $request) : JsonResponse + { + $jobId = uniqid(); + + $user = Auth::user(); + $userInfo = (object) [ + 'type' => $user->type, + ]; + + $userInfoJson = json_encode($userInfo); + $requestSignature = md5($userInfoJson . $request->fullUrl()); + + $listGenericJobObject = new ListGenericJobObject( + $request->fullUrl(), + $request->all(), + $requestSignature, + null, + $jobId, + $userInfo + ); + + ListTransactionsJob::dispatch($listGenericJobObject); + + $result = []; + $result['job_id'] = $jobId; + + $this->createsJobResult->execute($listGenericJobObject); + + return $this->response(['data' => $result]); + } + +} diff --git a/app/Classes/Modules/Transactions/Processors/ListTransactionsJobProcessor.php b/app/Classes/Modules/Transactions/Processors/ListTransactionsJobProcessor.php new file mode 100644 index 00000000..475d4715 --- /dev/null +++ b/app/Classes/Modules/Transactions/Processors/ListTransactionsJobProcessor.php @@ -0,0 +1,45 @@ +listsTransactions = $listsTransactions; + $this->updateJobResultProcessor = $updateJobResultProcessor; + } + + /** + * @param ListGenericJobObject $listGenericJobObject + * @return void + * @throws \App\Classes\Exceptions\MalformedRequestException + * @throws \App\Classes\Exceptions\JobResourceNotFoundException + */ + public function execute(ListGenericJobObject $listGenericJobObject) { + + $query = $this->listsTransactions->execute($this->listsTransactions->deserializeFilters($listGenericJobObject->getPayload()['filters']), ['page' => $listGenericJobObject->getPayload()['page']]); + + $resultCurrent = Helper::collectionResponse(ListTransactionJobResource::collection($query)); + $this->updateJobResultProcessor->execute($listGenericJobObject, $resultCurrent); + } +} + diff --git a/app/Http/Controllers/Bookings/ListBookingsJobController.php b/app/Http/Controllers/Bookings/ListBookingsJobController.php new file mode 100644 index 00000000..9b32fc77 --- /dev/null +++ b/app/Http/Controllers/Bookings/ListBookingsJobController.php @@ -0,0 +1,22 @@ +execute($request); + } +} diff --git a/app/Http/Controllers/Documents/ListDocumentsJobController.php b/app/Http/Controllers/Documents/ListDocumentsJobController.php new file mode 100644 index 00000000..8b763085 --- /dev/null +++ b/app/Http/Controllers/Documents/ListDocumentsJobController.php @@ -0,0 +1,19 @@ +execute($request); + } +} diff --git a/app/Http/Controllers/Jobs/FetchJobResultController.php b/app/Http/Controllers/Jobs/FetchJobResultController.php new file mode 100644 index 00000000..cfef2f5c --- /dev/null +++ b/app/Http/Controllers/Jobs/FetchJobResultController.php @@ -0,0 +1,19 @@ +execute($request); + } +} diff --git a/app/Http/Controllers/Transactions/ListTransactionsJobController.php b/app/Http/Controllers/Transactions/ListTransactionsJobController.php new file mode 100644 index 00000000..fb341d5d --- /dev/null +++ b/app/Http/Controllers/Transactions/ListTransactionsJobController.php @@ -0,0 +1,21 @@ +execute($request); + } +} diff --git a/app/Http/Resources/BookingResource.php b/app/Http/Resources/BookingResource.php index f3a7881d..70fbc95c 100644 --- a/app/Http/Resources/BookingResource.php +++ b/app/Http/Resources/BookingResource.php @@ -11,11 +11,9 @@ use App\Classes\ValueObjects\Constants\TransactionType; use App\Classes\ValueObjects\Constants\DocumentType; use Carbon\Carbon; use Illuminate\Http\Resources\Json\JsonResource; -use Illuminate\Support\Facades\Log; class BookingResource extends JsonResource { - /** * Transform the resource into an array. * diff --git a/app/Http/Resources/CompanyResource.php b/app/Http/Resources/CompanyResource.php index 85ecee16..eff2bd1b 100644 --- a/app/Http/Resources/CompanyResource.php +++ b/app/Http/Resources/CompanyResource.php @@ -15,7 +15,6 @@ use App\Models\SegmentConstant; use Carbon\Carbon; use Illuminate\Http\Resources\Json\JsonResource; use Illuminate\Support\Facades\Auth; -use Illuminate\Support\Facades\Log; class CompanyResource extends JsonResource { diff --git a/app/Http/Resources/DocumentResource.php b/app/Http/Resources/DocumentResource.php index 59933a67..c0f801bb 100644 --- a/app/Http/Resources/DocumentResource.php +++ b/app/Http/Resources/DocumentResource.php @@ -3,10 +3,7 @@ namespace App\Http\Resources; use App\Models\Booking; -use App\Models\Company; -use App\Models\Document; use Carbon\Carbon; -use Illuminate\Database\Eloquent\Model; use Illuminate\Http\Resources\Json\JsonResource; class DocumentResource extends JsonResource diff --git a/app/Http/Resources/JobResultResource.php b/app/Http/Resources/JobResultResource.php new file mode 100644 index 00000000..51bc1898 --- /dev/null +++ b/app/Http/Resources/JobResultResource.php @@ -0,0 +1,22 @@ + $this->job_id, + 'result' => $this->result, + ]; + } +} diff --git a/app/Http/Resources/ListBookingJobResource.php b/app/Http/Resources/ListBookingJobResource.php new file mode 100644 index 00000000..06f8c38d --- /dev/null +++ b/app/Http/Resources/ListBookingJobResource.php @@ -0,0 +1,81 @@ +userInfo = $userInfo ?? ($resource->userInfo ?? null); + } + + /** + * Transform the resource into an array. + * + * @param \Illuminate\Http\Request $request + * @return array + * @throws \Illuminate\Contracts\Container\BindingResolutionException + */ + public function toArray($request) + { + return [ + 'id' => $this->id, + 'company' => new CompanyResource($this->company, $this->userInfo), + 'bank' => new BankResource($this->bank), + 'service' => new ServiceTypeResource($this->service), + 'marking' => $this->marking, + 'amount' => $this->fix_amount, + 'floating_amount' => floatval((App()->make(CalculatesBookingFloatingAmount::class))->execute($this->resource, $this->fix_currency_id)), + 'paid_amount' => floatval((App()->make(CalculatesBookingPayableAmount::class))->execute($this->resource, $this->fix_currency_id)) - floatval((App()->make(CalculatesBookingRefundAmount::class))->execute($this->resource, $this->fix_currency_id)), + 'outstanding_amount' => floatval((App()->make(CalculatesBookingOutstanding::class))->execute($this->resource)) - floatval((App()->make(CalculatesBookingRefundAmount::class))->execute($this->resource, $this->fix_currency_id)), + 'fixed_currency' => new CurrencyResource($this->fixedCurrency), + 'convertible_currency' => new CurrencyResource($this->convertibleCurrency), + 'conversion_currency' => new CurrencyResource($this->conversionCurrency), + 'documents' => [ + 'purchase_order' => new DocumentResource($this->documents()->where('document_type', DocumentType::PURCHASE_ORDER)->first()), + 'delivery_order' => new DocumentResource($this->documents()->where('document_type', DocumentType::DELIVER_ORDER)->first()), + 'invoice' => new DocumentResource($this->documents()->where('document_type', DocumentType::INVOICE)->first()), + 'supplier_delivery_order' => new DocumentResource($this->documents()->where('document_type', DocumentType::SUPPLIER_DELIVER_ORDER)->first()), + 'proforma_invoice' => new DocumentResource($this->documents()->where('document_type', DocumentType::PROFORMA_INVOICE)->whereNotIn('status', [ApprovalStatus::REJECTED, ApprovalStatus::EXPIRED])->orderByDesc('id')->first()), + 'ecommerce_purchase_order' => new DocumentResource($this->documents()->where('document_type', DocumentType::ECOMMERCE_PURCHASE_ORDER)->first()), + ], + 'status' => $this->status, + 'created_at' => Carbon::parse($this->created_at)->format('d-m-Y'), + 'created_at_with_time' => Carbon::parse($this->created_at)->format('d-m-Y h:i:s A'), + $this->mergeWhen($this->relationLoaded('transactions'), [ + 'purchase_order' => new TransactionResource($this->transactions()->where('type', TransactionType::PURCHASE_ORDER)->first()), + 'payment_attempts' => TransactionResource::collection( + $this->transactions() + ->payments()->where('status', ApprovalStatus::PENDING_SUBMISSION) + ->whereDate('expires_on', '>=', Carbon::now()) + ->get() + ), + 'expired_payment_attempts' => TransactionResource::collection($this->transactions()->payments()->where('status', ApprovalStatus::PENDING_SUBMISSION)->whereDate('expires_on', '>=', Carbon::now())->where('expires_on', '>', Carbon::now()->toTimeString())->get()), + 'payment_history' => TransactionResource::collection($this->transactions()->where(function($query){ + $query->where(function($query){ + $query->payments()->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::PENDING_VERIFICATION, ApprovalStatus::COMPLETED, ApprovalStatus::REJECTED]); + })->orWhere(function($query){ + $query->where(function($query){ + $query->where('type', TransactionType::REFUND)->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::PENDING_VERIFICATION, ApprovalStatus::REJECTED, ApprovalStatus::COMPLETED]); + })->orWhere(function($query){ + $query->where('type', TransactionType::CREDIT_NOTE)->whereIn('status', [ApprovalStatus::PENDING_VERIFICATION, ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED]); + }); + }); + })->latest()->get()) + ]) + ]; + } +} diff --git a/app/Http/Resources/ListDocumentJobResource.php b/app/Http/Resources/ListDocumentJobResource.php new file mode 100644 index 00000000..edf549ef --- /dev/null +++ b/app/Http/Resources/ListDocumentJobResource.php @@ -0,0 +1,31 @@ + $this->id, + 'reference' => $this->reference, + 'status' => (int) $this->status, + 'document_type' => $this->document_type, + 'owner' => $this->relationLoaded('owner') ? ($this->owner instanceof Booking ? new BookingV2Resource($this->owner, $this->userInfo) : new CompanyV2Resource($this->owner, $this->userInfo)) : null, + 'files' => FileResource::collection($this->files), + 'created_at' => Carbon::parse($this->created_at)->format('d-m-Y h:i:s A') + ]; + } +} diff --git a/app/Http/Resources/ListTransactionJobResource.php b/app/Http/Resources/ListTransactionJobResource.php new file mode 100644 index 00000000..6c4c0ece --- /dev/null +++ b/app/Http/Resources/ListTransactionJobResource.php @@ -0,0 +1,54 @@ +type, [TransactionType::BILL, TransactionType::REFUND])? $this->owner->owner : $this->owner; + $days = $this->created_at->endOfDay()->addWeekdays($booking->service_id === 3 ? 3 : 1); + + return [ + 'id' => $this->id, + 'booking' => new BookingResource($booking), + 'type' => (int) $this->type, + 'bill_no' => $this->bill_no, + 'payment_reference' => $this->payment_reference, + 'payment_method' => (float) $this->payment_method, + 'recipient_bank_account' => new BankResource($booking->bank), + 'issuer_name' => $this->issuerCompany->name, + 'issuer_id' => $this->issuerCompany->id, + 'amount' => (double) $this->amount, + 'original_amount' => (double) $this->original_amount, + 'currency' => new CurrencyResource($this->currency), + 'original_currency' => new CurrencyResource($this->original_currency), + 'service_charge' => (double) $this->service_charge, + 'tax' => (double) $this->tax, + 'currency_rate' => (double) $this->currency_rate, + 'status' => (int) $this->status, + 'details' => TransactionDetailResource::collection($this->transactionDetails), + 'documents' => new DocumentResource($this->documents()->first()), + 'transaction_bill' => new TransactionResource($this->when((int) $this->type === TransactionType::PAYMENT, $this->transactions()->bills()->first())), + 'transaction_refunds' => TransactionResource::collection($this->when((int) $this->type === TransactionType::PAYMENT, $this->transactions()->refunds()->get())), + 'expires_on' => Carbon::parse($this->expires_on)->format('d-m-Y h:i:s A'), + 'updated_at' => Carbon::parse($this->updated_at)->format('d-m-Y h:i:s A'), + 'interval' => [ + 'value' => $days->gt(Carbon::now()) ? '+' : '-', + 'duration' => $days->diff(Carbon::now())->format('%d'), + ], + 'redemption' => new VoucherRedemptionResource($this->voucherRedemption) + ]; + } +} diff --git a/app/Http/Resources/V2/BookingV2Resource.php b/app/Http/Resources/V2/BookingV2Resource.php new file mode 100644 index 00000000..ee17181e --- /dev/null +++ b/app/Http/Resources/V2/BookingV2Resource.php @@ -0,0 +1,82 @@ +userInfo = $userInfo ?? ($resource->userInfo ?? null); + } + + /** + * Transform the resource into an array. + * + * @param \Illuminate\Http\Request $request + * @return array + * @throws \Illuminate\Contracts\Container\BindingResolutionException + */ + public function toArray($request) + { + return [ + 'id' => $this->id, + 'company' => new CompanyV2Resource($this->company, $this->userInfo), + 'bank' => new V1\BankResource($this->bank), + 'service' => new V1\ServiceTypeResource($this->service), + 'marking' => $this->marking, + 'amount' => $this->fix_amount, + 'floating_amount' => floatval((App()->make(CalculatesBookingFloatingAmount::class))->execute($this->resource, $this->fix_currency_id)), + 'paid_amount' => floatval((App()->make(CalculatesBookingPayableAmount::class))->execute($this->resource, $this->fix_currency_id)) - floatval((App()->make(CalculatesBookingRefundAmount::class))->execute($this->resource, $this->fix_currency_id)), + 'outstanding_amount' => floatval((App()->make(CalculatesBookingOutstanding::class))->execute($this->resource)) - floatval((App()->make(CalculatesBookingRefundAmount::class))->execute($this->resource, $this->fix_currency_id)), + 'fixed_currency' => new V1\CurrencyResource($this->fixedCurrency), + 'convertible_currency' => new V1\CurrencyResource($this->convertibleCurrency), + 'conversion_currency' => new V1\CurrencyResource($this->conversionCurrency), + 'documents' => [ + 'purchase_order' => new V1\DocumentResource($this->documents()->where('document_type', DocumentType::PURCHASE_ORDER)->first()), + 'delivery_order' => new V1\DocumentResource($this->documents()->where('document_type', DocumentType::DELIVER_ORDER)->first()), + 'invoice' => new V1\DocumentResource($this->documents()->where('document_type', DocumentType::INVOICE)->first()), + 'supplier_delivery_order' => new V1\DocumentResource($this->documents()->where('document_type', DocumentType::SUPPLIER_DELIVER_ORDER)->first()), + 'proforma_invoice' => new V1\DocumentResource($this->documents()->where('document_type', DocumentType::PROFORMA_INVOICE)->whereNotIn('status', [ApprovalStatus::REJECTED, ApprovalStatus::EXPIRED])->orderByDesc('id')->first()), + 'ecommerce_purchase_order' => new V1\DocumentResource($this->documents()->where('document_type', DocumentType::ECOMMERCE_PURCHASE_ORDER)->first()), + ], + 'status' => $this->status, + 'created_at' => Carbon::parse($this->created_at)->format('d-m-Y'), + 'created_at_with_time' => Carbon::parse($this->created_at)->format('d-m-Y h:i:s A'), + $this->mergeWhen($this->relationLoaded('transactions'), [ + 'purchase_order' => new V1\TransactionResource($this->transactions()->where('type', TransactionType::PURCHASE_ORDER)->first()), + 'payment_attempts' => V1\TransactionResource::collection( + $this->transactions() + ->payments()->where('status', ApprovalStatus::PENDING_SUBMISSION) + ->whereDate('expires_on', '>=', Carbon::now()) + ->get() + ), + 'expired_payment_attempts' => V1\TransactionResource::collection($this->transactions()->payments()->where('status', ApprovalStatus::PENDING_SUBMISSION)->whereDate('expires_on', '>=', Carbon::now())->where('expires_on', '>', Carbon::now()->toTimeString())->get()), + 'payment_history' => V1\TransactionResource::collection($this->transactions()->where(function($query){ + $query->where(function($query){ + $query->payments()->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::PENDING_VERIFICATION, ApprovalStatus::COMPLETED, ApprovalStatus::REJECTED]); + })->orWhere(function($query){ + $query->where(function($query){ + $query->where('type', TransactionType::REFUND)->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::PENDING_VERIFICATION, ApprovalStatus::REJECTED, ApprovalStatus::COMPLETED]); + })->orWhere(function($query){ + $query->where('type', TransactionType::CREDIT_NOTE)->whereIn('status', [ApprovalStatus::PENDING_VERIFICATION, ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED]); + }); + }); + })->latest()->get()) + ]) + ]; + } +} diff --git a/app/Http/Resources/V2/CompanyV2Resource.php b/app/Http/Resources/V2/CompanyV2Resource.php new file mode 100644 index 00000000..64fca7c7 --- /dev/null +++ b/app/Http/Resources/V2/CompanyV2Resource.php @@ -0,0 +1,100 @@ +userInfo = $userInfo; + } + + /** + * Transform the resource into an array. + * + * @param \Illuminate\Http\Request $request + * @return array + */ + public function toArray($request) + { + $lastPayment = $this->transactions()->where('transactions.type', TransactionType::PAYMENT)->whereIn('transactions.status', [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED])->orderBy('id', 'DESC')->first(); + $totalPayments = $this->transactions()->where('transactions.type', TransactionType::PAYMENT)->whereIn('transactions.status', [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED])->sum('amount'); + + $segment = SegmentConstant::where('reference', SegmentConstants::SUPPLIER_CURRENCIES)->where('detail->id', $this->id)->first(); + $serviceCharge = SegmentConstant::where('reference', SegmentConstants::SERVICE_CHARGE)->where('detail->id', $this->id)->first(); + + $userResource = null; + + $userInfoEmail = $this->userInfo && isset($this->userInfo->email) ? $this->userInfo->email : null; + $userInfoType = $this->userInfo && isset($this->userInfo->type) ? $this->userInfo->type : null; + + if(!$userInfoEmail && Auth::user()){ + $userInfoEmail = Auth::user()->email; + } + if(!$userInfoType && Auth::user()){ + $userInfoType = Auth::user()->type; + } + + if(!is_null($userInfoEmail) && !is_null($userInfoType)){ + $userResource = new V1\UserResource($userInfoType === RoleTypes::USER ? $this->employees()->where('email', '=', $userInfoEmail)->first() : $this->employees()->orderBy('id', 'DESC')->first()); + } + + return [ + 'id' => $this->id, + 'name' => $this->name, + 'reference' => $this->reference, + 'debtor' => $this->debtor, + 'type' => (int) $this->type, + 'business_type' => (int) $this->business_type, + 'status' => (int) $this->status, + 'contact' => new V1\ContactResource ($this->when($this->has('contacts'), $this->contacts->first())), + 'address' => new V1\AddressResource($this->when($this->has('addresses'), $this->addresses->where('billing', true)->first())), + 'employee' => $userResource, + 'identification' => new V1\DocumentResource($this->documents->whereIn('document_type', DocumentType::IDENTIFICATION_DOCUMENTS)->first()), + 'bookings' => $this->whenLoaded('bookings', $this->bookings()->orderBy('id', 'DESC')->get(), []), + 'confirmed_bookings' => $this->bookings()->whereHas('transactions', function ($query){ + $query->where('type', TransactionType::PAYMENT)->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED]); + })->count(), + 'total_payments' => (float) $totalPayments, + 'average_spending_per_day' => (float) $totalPayments / ($this->created_at->diff(Carbon::now())->days === 0 ? 1 : $this->created_at->diff(Carbon::now())->days), + 'average_spending_per_booking' => (float) $totalPayments > 0 ? $totalPayments / $this->bookings()->whereHas('transactions', function ($query){ + $query->where('type', TransactionType::PAYMENT)->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED]); + })->count() : $totalPayments, + 'last_payment' => $lastPayment ? $lastPayment->created_at->diffForHumans() : 'No Payments', + 'personal_banks' => V1\BankResource::collection($this->banks->where('type', BankAccountType::PERSONAL)), + 'recipient_banks' => [ + 'accounts' => V1\BankResource::collection($this->banks->where('type', BankAccountType::EXTERNAL)), + 'default' => new V1\BankResource($this->banks->where('type', BankAccountType::EXTERNAL)->where('default', true)->first()) + ], + 'segments' => V1\SegmentResource::collection($this->segments), + 'seasonalSegment' => $this->whenLoaded('seasonalSegments', V1\SeasonalSegmentResource::collection($this->seasonalSegments)), + 'services' => (new FetchesCompanyServices())->getServices($this->servicesConfigurations()), + 'wallet' => $this->whenLoaded('wallets', new V1\WalletResource($this->wallets()->with('transactions')->first()), new V1\WalletResource($this->wallets()->first())), + 'created_at' => $this->created_at->format('d-m-Y'), + $this->mergeWhen($this->business_type === BusinessType::CURRENCY_VENDOR, [ + 'currencies' => $segment ? V1\CurrencyResource::collection(Currency::whereIn('id', $segment->detail->currencies)->get()) : [], + 'service_charge' => $serviceCharge + ]) + + ]; + } +} diff --git a/app/Models/JobResult.php b/app/Models/JobResult.php new file mode 100644 index 00000000..f30b5076 --- /dev/null +++ b/app/Models/JobResult.php @@ -0,0 +1,13 @@ +id(); + $table->string('job_id', 50); + $table->longText('result')->nullable(); + $table->timestamps(); + + // $table->foreign('job_id')->references('id')->on('jobs')->onDelete('cascade'); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::dropIfExists('job_results'); + } +} diff --git a/database/migrations/2023_08_29_063531_add_new_column_to_job_results_table.php b/database/migrations/2023_08_29_063531_add_new_column_to_job_results_table.php new file mode 100644 index 00000000..8e6b8342 --- /dev/null +++ b/database/migrations/2023_08_29_063531_add_new_column_to_job_results_table.php @@ -0,0 +1,36 @@ +longText('url')->after('result')->nullable(); + $table->string('job_command_name')->after('url')->nullable(); + $table->longText('job_command')->after('job_command_name')->nullable(); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::table('job_results', function (Blueprint $table) { + $table->dropColumn('url'); + $table->dropColumn('job_command_name'); + $table->dropColumn('job_command'); + }); + } +} diff --git a/database/migrations/2023_12_11_193200_add_new_column_2_to_job_results_table.php b/database/migrations/2023_12_11_193200_add_new_column_2_to_job_results_table.php new file mode 100644 index 00000000..12c6d57f --- /dev/null +++ b/database/migrations/2023_12_11_193200_add_new_column_2_to_job_results_table.php @@ -0,0 +1,34 @@ +string('request_signature')->after('job_id')->nullable(); + $table->string('result_signature')->after('request_signature')->nullable(); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::table('job_results', function (Blueprint $table) { + $table->dropColumn('request_signature'); + $table->dropColumn('result_signature'); + }); + } +} diff --git a/resources/assets/vue/components/bookings/sections/AdminPaymentsBillingSectionComponent.vue b/resources/assets/vue/components/bookings/sections/AdminPaymentsBillingSectionComponent.vue new file mode 100644 index 00000000..966ccbbc --- /dev/null +++ b/resources/assets/vue/components/bookings/sections/AdminPaymentsBillingSectionComponent.vue @@ -0,0 +1,136 @@ + + diff --git a/resources/assets/vue/components/bookings/sections/AdminPaymentsBillingSectionPollingComponent.vue b/resources/assets/vue/components/bookings/sections/AdminPaymentsBillingSectionPollingComponent.vue new file mode 100644 index 00000000..47d14857 --- /dev/null +++ b/resources/assets/vue/components/bookings/sections/AdminPaymentsBillingSectionPollingComponent.vue @@ -0,0 +1,136 @@ + + diff --git a/resources/assets/vue/components/bookings/sections/SupplierPendingOrdersSectionComponent.vue b/resources/assets/vue/components/bookings/sections/SupplierPendingOrdersSectionComponent.vue index 7df9c125..d2b69080 100644 --- a/resources/assets/vue/components/bookings/sections/SupplierPendingOrdersSectionComponent.vue +++ b/resources/assets/vue/components/bookings/sections/SupplierPendingOrdersSectionComponent.vue @@ -117,11 +117,17 @@
+ +
@@ -165,7 +171,7 @@ } }, created(){ - this.submit(route('api.company.list') + '?filters=' + JSON.stringify({'business_type': 3, 'status_in': [1, 2, 0]}), 'get', 'pendingOrdersSection', false, false) + this.submit(route('api.company.list') + '?filters=' + JSON.stringify({'business_type': 3, 'status_in': [1, 2, 0]}), 'get', 'pendingOrdersSection', false, false); //cief todo: Uncaught (in promise) null }, methods: { successHandler(response){ @@ -210,4 +216,4 @@ } - \ No newline at end of file + diff --git a/resources/assets/vue/components/general/elements/ListPollingComponent.vue b/resources/assets/vue/components/general/elements/ListPollingComponent.vue new file mode 100644 index 00000000..fcd3b8b8 --- /dev/null +++ b/resources/assets/vue/components/general/elements/ListPollingComponent.vue @@ -0,0 +1,213 @@ + + + diff --git a/resources/assets/vue/general/mixins/aws/requestV2.js b/resources/assets/vue/general/mixins/aws/requestV2.js new file mode 100644 index 00000000..12b27542 --- /dev/null +++ b/resources/assets/vue/general/mixins/aws/requestV2.js @@ -0,0 +1,49 @@ +export default { + methods: { + poll(url, method, section, successNotification = true, errorNotification = true){ + if(!this.validate()){ return; } + if (section) { + this.$store.dispatch('toggleLoading', {name: section, status: true}) + } + this.$store.dispatch('crudRequestV2', { + endpoint: url, + method: method, + parameters: this.parameters + }).then(response => { + let statusCode = response.status, + success = response.ok; + + response.json().then(response => { + + if(!success){ + this.openModal(); + errorNotification ? this.$store.dispatch('createNotification', {title: response.title, message: response.message, type: 'error'}): null; + this.errorHandler(response, statusCode); return; + } + + successNotification ? this.$store.dispatch('createNotification', {title: response.title, message: response.message, type: 'success'}): null; + this.successHandler(response) + + + }); + }).catch((error) => { + this.$store.dispatch('createNotification', {title: 'Unexpected Error', message: 'An unexpected error has occurred. Try again!', type: 'error'}); + }).then(() => { + if (section) { + this.$store.dispatch('toggleLoading', {name: section, status: false}) + } + }) + + }, + validate() { + if(this.$v){ + this.$v.$touch(); + return !this.$v.$invalid; + } + return true; + }, + successHandler(response){}, + errorHandler(response){} + } + +} diff --git a/resources/assets/vue/general/mixins/tabHandler.js b/resources/assets/vue/general/mixins/tabHandler.js new file mode 100644 index 00000000..81790ed0 --- /dev/null +++ b/resources/assets/vue/general/mixins/tabHandler.js @@ -0,0 +1,24 @@ +export default { + data() { + return { + activeTab: null, + displayedTabs: [], + }; + }, + methods: { + setActiveTab(event) { + const tabName = event.currentTarget.getAttribute('tab-name'); + // console.log(`Tab "${tabName}" clicked`); + this.activeTab = tabName; + if (!this.displayedTabs.includes(tabName)) { + this.displayedTabs.push(tabName); + } + }, + isActiveTab(tabName) { + return this.activeTab === tabName; + }, + showTabContent(tabName) { + return this.displayedTabs.includes(tabName); + }, + }, +} diff --git a/resources/assets/vue/vuex/modules/crudRequestV2.js b/resources/assets/vue/vuex/modules/crudRequestV2.js new file mode 100644 index 00000000..355b1edb --- /dev/null +++ b/resources/assets/vue/vuex/modules/crudRequestV2.js @@ -0,0 +1,51 @@ +export default { + actions: { + crudRequestV2({getters, dispatch}, {endpoint, method, parameters}){ + return dispatch('ensureReCaptchaIsSet').then(function () { + const queryDomain = endpoint.split('?')[0]; + let encodedParams = endpoint.split('?')[1]; + let decodedParams = fullyDecodeURI(encodedParams); + const queryParams = encodeURIComponent(decodedParams); + encodedParams = queryParams.toString(); + let filteredEncodedParams = encodedParams.replace(/%3D/g,'='); + filteredEncodedParams = filteredEncodedParams.replace(/%26/g,'&'); + let combinedAbsoluteUrl = queryDomain; + if(filteredEncodedParams !== undefined && filteredEncodedParams !== 'undefined'){ + combinedAbsoluteUrl = queryDomain + '?' + filteredEncodedParams; + } + + // return fetch(endpoint, { + return fetch(combinedAbsoluteUrl, { + method: method, + responseType: 'json', + body: parameters ? JSON.stringify(parameters):null, + headers: { + 'content-type': 'application/json', + 'Authorization': 'Bearer '+getters.getAccessToken, + 'captcha-token': getters.getReCaptcha + } + }).then(response => { + + if(response.status === 401 && window.location.href !== route('login')){ + dispatch('userAuthentication', {access_token: '', redirect_url: '/'}); + } + + return response; + + }) + }); + } + } +} + +function isEncoded(uri) { + uri = uri || ''; + return uri !== decodeURIComponent(uri); +} + +function fullyDecodeURI(uri){ + while (isEncoded(uri)){ + uri = decodeURIComponent(uri); + } + return uri; +} diff --git a/resources/assets/vue/vuex/store.js b/resources/assets/vue/vuex/store.js index 2c3d911b..ff10c673 100644 --- a/resources/assets/vue/vuex/store.js +++ b/resources/assets/vue/vuex/store.js @@ -4,6 +4,7 @@ import toggleSection from './modules/toggleSection' import toggleLoading from './modules/toggleLoading' import createNotification from './modules/createNotification' import crudRequest from './modules/crudRequest' +import crudRequestV2 from './modules/crudRequestV2' import authentication from './modules/authentication' import loadRequestQueue from './modules/loadRequestQueue' @@ -16,6 +17,7 @@ export default new Vuex.Store({ loadRequestQueue, createNotification, crudRequest, + crudRequestV2, authentication } -}) \ No newline at end of file +}) diff --git a/resources/views/pages/billings.blade.php b/resources/views/pages/billings.blade.php index 4bc012d5..da84f8b9 100644 --- a/resources/views/pages/billings.blade.php +++ b/resources/views/pages/billings.blade.php @@ -3,129 +3,7 @@
- -
-
-
-
-
-
-
-
-
-
-
-
- -
-
-
-
-
Invoice
-
-
-
-
-
-
-
-
-
-
- -
-
-
-
-
Purchase Order
-
-
-
-
-
-
-
-
-
-
- -
-
-
-
-
Delivery Order
-
-
-
-
-
-
-
-
-
-
- -
-
-
-
-
Supplier Delivery Order
-
-
-
-
-
-
-
-
-
-
-
-
-
- - - -
-
- - - -
-
- - - -
-
- - - -
-
-
-
-
+
-@endsection \ No newline at end of file +@endsection diff --git a/resources/views/pages/billings_experiment.blade.php b/resources/views/pages/billings_experiment.blade.php new file mode 100644 index 00000000..d1caee2d --- /dev/null +++ b/resources/views/pages/billings_experiment.blade.php @@ -0,0 +1,9 @@ +@extends('layouts.base_portal') +@section('inner_content') +
+
+ + +
+
+@endsection diff --git a/routes/api.php b/routes/api.php index 8b4bada0..460bd772 100644 --- a/routes/api.php +++ b/routes/api.php @@ -67,6 +67,10 @@ Route::group(['middleware' => 'api', 'prefix' => 'v1', 'as' => 'api.'], function require __DIR__ . '/milestone.php'; + // require __DIR__ . '/accounting.php'; //cief todo: To check if this is needed + + require __DIR__ . '/job.php'; + // require __DIR__ . '/rate.php'; // require __DIR__ . '/receipt.php'; diff --git a/routes/currency.php b/routes/currency.php index b621aad6..ba55c9a2 100644 --- a/routes/currency.php +++ b/routes/currency.php @@ -1,4 +1,4 @@ - 'document', 'as' => 'document.', 'namespace' => 'Documents'], function () { Route::get('/list', 'ListDocumentsController@list')->name('list'); + Route::get('/list/job', 'ListDocumentsJobController@list')->name('list.job'); Route::delete('/{id}/delete', 'DeleteDocumentController@delete')->name('delete'); Route::put('/{id}/approve', 'ApproveDocumentController@approve')->name('status.approve'); Route::put('/{id}/reject', 'RejectDocumentController@reject')->name('status.reject'); Route::put('/{id}/reference/update', 'UpdateDocumentReferenceController@update')->name('reference.update'); -}); \ No newline at end of file +}); diff --git a/routes/job.php b/routes/job.php new file mode 100644 index 00000000..028e9468 --- /dev/null +++ b/routes/job.php @@ -0,0 +1,8 @@ + 'job', 'as' => 'job.', 'namespace' => 'Jobs'], function () { + Route::get('/fetch/{job_id}', 'FetchJobResultController@fetch')->name('fetch'); + Route::get('/fetch/{job_id}/{is_last}', 'FetchJobResultController@fetch')->name('fetch.last.attempt'); +}); diff --git a/routes/web.php b/routes/web.php index bf2892bb..a6590c17 100644 --- a/routes/web.php +++ b/routes/web.php @@ -92,6 +92,12 @@ Route::get('/billings', function () { return view('pages.billings'); })->name('billings'); +/* Vue Polling Experiment - Starts */ +Route::get('/billings-experiment', function () { + return view('pages.billings_experiment'); +})->name('billings.experiment'); +/* Vue Polling Experiment - Ends */ + Route::get('/currency_orders', function () { return view('pages.currency_orders'); })->name('currency_orders'); @@ -830,13 +836,13 @@ Route::get('/invoice/{marking}/{started_at}/{ended_at}/fix', function($marking, ->withTrashed() ->orderBy('created_at', 'asc') ->first(); - + // get the first bill_no $firstBillNo = $firstInvoice->bill_no; if (strpos($firstBillNo, '-deleted') !== false) { $firstBillNo = substr($firstBillNo, 0, strpos($firstBillNo, '-deleted')); } - + // update currentInvoice bill_no to '-deleted-' $currentInvoice = $booking->transactions()->where('type', TransactionType::INVOICE)->first(); $currentInvoice->bill_no = $currentInvoice->bill_no ."-deleted-" . Str::random(10); @@ -859,4 +865,4 @@ Route::get('/invoice/{marking}/{started_at}/{ended_at}/fix', function($marking, } } ); -})->name('invoice.fix.byCustomerMarking'); \ No newline at end of file +})->name('invoice.fix.byCustomerMarking'); From f08343439052ff23e122217e123cd3d314b5a7f6 Mon Sep 17 00:00:00 2001 From: edmondlang Date: Fri, 16 Feb 2024 14:59:11 +0800 Subject: [PATCH 26/59] update refund ui and logic --- .../CreateBookingPaymentLogic.php | 10 +- .../CreateBookingRefundLogic.php | 8 +- .../ControllersLogic/FetchBookingLogic.php | 2 +- .../FetchBookingPaymentQuotationLogic.php | 9 +- .../CalculatesBookingRefundAmount.php | 27 ++- .../UpdateRefundTransactionStatusLogic.php | 21 ++- app/Http/Resources/BookingResource.php | 4 +- app/Http/Resources/TransactionResource.php | 1 + .../elements/PaymentHistoryComponent.vue | 105 ++++++++---- .../elements/RefundConfirmationComponent.vue | 157 ++++++++---------- .../elements/RefundVerificationComponent.vue | 2 +- .../forms/PurchaseOrderFormComponent.vue | 6 +- routes/transaction.php | 2 +- 13 files changed, 208 insertions(+), 146 deletions(-) diff --git a/app/Classes/Modules/Bookings/ControllersLogic/CreateBookingPaymentLogic.php b/app/Classes/Modules/Bookings/ControllersLogic/CreateBookingPaymentLogic.php index c429d91d..ab654675 100644 --- a/app/Classes/Modules/Bookings/ControllersLogic/CreateBookingPaymentLogic.php +++ b/app/Classes/Modules/Bookings/ControllersLogic/CreateBookingPaymentLogic.php @@ -19,6 +19,7 @@ use App\Classes\ValueObjects\Constants\PaymentMethodType; use App\Classes\ValueObjects\Constants\TransactionType; use App\Classes\Modules\Currencies\DataTransferObjects\CurrencyConversionObject; use App\Http\Resources\TransactionResource; +use App\Classes\Modules\Bookings\Services\CalculatesBookingRefundAmount; use App\Classes\Modules\Transactions\Processors\CreateCashBackTransactionProcessor; use App\Classes\Modules\Vouchers\Processors\Voucherify\BookingToVoucherifyProcessor; @@ -77,6 +78,9 @@ class CreateBookingPaymentLogic extends AbstractControllerLogic /** @var BookingToVoucherifyProcessor */ private $bookingToVoucherifyProcessor; + /** @var CalculatesBookingRefundAmount */ + private $calculatesBookingRefundAmount; + /** * CreateBookingPaymentLogic constructor. * @param FetchesBookingQuotation $fetchBookingQuotation @@ -90,8 +94,9 @@ class CreateBookingPaymentLogic extends AbstractControllerLogic * @param CreateCashBackTransactionProcessor $createCashBackTransactionProcessor * @param RecalculatesWalletBalance $recalculatesWalletBalance * @param BookingToVoucherifyProcessor $bookingToVoucherifyProcessor + * @param CalculatesBookingRefundAmount $calculatesBookingRefundAmount */ - public function __construct(FetchesBookingQuotation $fetchBookingQuotation, FetchesCompanyPaymentAttemptLimit $fetchesCompanyPaymentAttemptLimit, GeneratesTransactionBillNumber $generatesTransactionBillNumber, CreatesTransaction $createsTransaction, CalculatesBookingOutstanding $calculatesBookingOutstanding, CreatesBillplzBill $createsBillplzBill, UpdatesWalletBalance $updatesWalletBalance, UpdatesTransactionStatus $updatesTransactionStatus, CreateCashBackTransactionProcessor $createCashBackTransactionProcessor, RecalculatesWalletBalance $recalculatesWalletBalance, BookingToVoucherifyProcessor $bookingToVoucherifyProcessor) + public function __construct(FetchesBookingQuotation $fetchBookingQuotation, FetchesCompanyPaymentAttemptLimit $fetchesCompanyPaymentAttemptLimit, GeneratesTransactionBillNumber $generatesTransactionBillNumber, CreatesTransaction $createsTransaction, CalculatesBookingOutstanding $calculatesBookingOutstanding, CreatesBillplzBill $createsBillplzBill, UpdatesWalletBalance $updatesWalletBalance, UpdatesTransactionStatus $updatesTransactionStatus, CreateCashBackTransactionProcessor $createCashBackTransactionProcessor, RecalculatesWalletBalance $recalculatesWalletBalance, BookingToVoucherifyProcessor $bookingToVoucherifyProcessor, CalculatesBookingRefundAmount $calculatesBookingRefundAmount) { $this->fetchBookingQuotation = $fetchBookingQuotation; $this->fetchesCompanyPaymentAttemptLimit = $fetchesCompanyPaymentAttemptLimit; @@ -104,6 +109,7 @@ class CreateBookingPaymentLogic extends AbstractControllerLogic $this->createCashBackTransactionProcessor = $createCashBackTransactionProcessor; $this->recalculatesWalletBalance = $recalculatesWalletBalance; $this->bookingToVoucherifyProcessor = $bookingToVoucherifyProcessor; + $this->calculatesBookingRefundAmount = $calculatesBookingRefundAmount; } /** @@ -119,7 +125,7 @@ class CreateBookingPaymentLogic extends AbstractControllerLogic $conversionObject = new CurrencyConversionObject(floatval(str_replace(',', '', $request->input('amount'))), $booking->convertible_currency_id, $booking->service_id, $booking->fix_currency_id === 1 ? 0:1, PaymentMethodType::PAYMENT_METHODS[$request->input('payment_method')]); - $outstanding = $this->calculatesBookingOutstanding->execute($booking); + $outstanding = $this->calculatesBookingOutstanding->execute($booking) + $this->calculatesBookingRefundAmount->execute($booking, $booking->fix_currency_id); if($conversionObject->getAmount() > round($outstanding, 2)) throw new MalformedRequestException('Your payment must not be greater than '. $outstanding .'.'); diff --git a/app/Classes/Modules/Bookings/ControllersLogic/CreateBookingRefundLogic.php b/app/Classes/Modules/Bookings/ControllersLogic/CreateBookingRefundLogic.php index 7455e689..0648629e 100644 --- a/app/Classes/Modules/Bookings/ControllersLogic/CreateBookingRefundLogic.php +++ b/app/Classes/Modules/Bookings/ControllersLogic/CreateBookingRefundLogic.php @@ -15,7 +15,6 @@ use App\Classes\Modules\Transactions\Services\CreatesTransaction; use App\Classes\Modules\Transactions\Services\FetchesTransaction; use App\Classes\Modules\Bookings\Services\FetchesBookingQuotation; use App\Classes\Modules\Transactions\Services\UpdatesTransactionStatus; -use App\Classes\Modules\Bookings\Services\CalculatesBookingRefundAmount; use App\Classes\Modules\Transactions\DataTransferObjects\TransactionObject; use App\Classes\Modules\Transactions\Services\GeneratesTransactionBillNumber; use App\Classes\Modules\Transactions\DataTransferObjects\TransactionRefundCalculationObject; @@ -49,9 +48,6 @@ class CreateBookingRefundLogic extends AbstractControllerLogic /** @var CreatesTransaction */ private $createsTransaction; - /** @var CalculatesBookingRefundAmount */ - private $calculatesBookingRefundAmount; - /** * CreateBookingPaymentLogic constructor. * @param FetchesBookingQuotation $fetchBookingQuotation @@ -59,16 +55,14 @@ class CreateBookingRefundLogic extends AbstractControllerLogic * @param UpdatesTransactionStatus $updatesTransactionStatus * @param GeneratesTransactionBillNumber $generatesTransactionBillNumber * @param CreatesTransaction $createsTransaction - * @param CalculatesBookingRefundAmount $calculatesBookingRefundAmount */ - public function __construct(FetchesBookingQuotation $fetchBookingQuotation, FetchesTransaction $fetchesTransaction, UpdatesTransactionStatus $updatesTransactionStatus, GeneratesTransactionBillNumber $generatesTransactionBillNumber, CreatesTransaction $createsTransaction, CalculatesBookingRefundAmount $calculatesBookingRefundAmount) + public function __construct(FetchesBookingQuotation $fetchBookingQuotation, FetchesTransaction $fetchesTransaction, UpdatesTransactionStatus $updatesTransactionStatus, GeneratesTransactionBillNumber $generatesTransactionBillNumber, CreatesTransaction $createsTransaction) { $this->fetchBookingQuotation = $fetchBookingQuotation; $this->fetchesTransaction = $fetchesTransaction; $this->updatesTransactionStatus = $updatesTransactionStatus; $this->generatesTransactionBillNumber = $generatesTransactionBillNumber; $this->createsTransaction = $createsTransaction; - $this->calculatesBookingRefundAmount = $calculatesBookingRefundAmount; } /** diff --git a/app/Classes/Modules/Bookings/ControllersLogic/FetchBookingLogic.php b/app/Classes/Modules/Bookings/ControllersLogic/FetchBookingLogic.php index d9857548..d1f2286e 100644 --- a/app/Classes/Modules/Bookings/ControllersLogic/FetchBookingLogic.php +++ b/app/Classes/Modules/Bookings/ControllersLogic/FetchBookingLogic.php @@ -18,7 +18,7 @@ class FetchBookingLogic extends AbstractControllerLogic */ protected function notification():array { return [ - 'title' => 'Retrieved Address', + 'title' => 'Retrieved Booking', 'message' => 'You have successfully retrieved a Address' ]; } diff --git a/app/Classes/Modules/Bookings/ControllersLogic/FetchBookingPaymentQuotationLogic.php b/app/Classes/Modules/Bookings/ControllersLogic/FetchBookingPaymentQuotationLogic.php index 8effdb2f..e9a42101 100644 --- a/app/Classes/Modules/Bookings/ControllersLogic/FetchBookingPaymentQuotationLogic.php +++ b/app/Classes/Modules/Bookings/ControllersLogic/FetchBookingPaymentQuotationLogic.php @@ -14,6 +14,7 @@ use App\Classes\ValueObjects\Constants\PaymentMethodType; use App\Models\Booking; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; +use App\Classes\Modules\Bookings\Services\CalculatesBookingRefundAmount; class FetchBookingPaymentQuotationLogic extends AbstractControllerLogic { @@ -40,6 +41,9 @@ class FetchBookingPaymentQuotationLogic extends AbstractControllerLogic /** @var CalculatesBookingOutstanding */ private $calculatesBookingOutstanding; + /** @var CalculatesBookingRefundAmount */ + private $calculatesBookingRefundAmount; + /** * FetchBookingPaymentQuotationLogic constructor. * @param FetchesBookingQuotation $fetchBookingQuotation @@ -47,12 +51,13 @@ class FetchBookingPaymentQuotationLogic extends AbstractControllerLogic * @param FetchesCompanyPaymentAttemptLimit $fetchesCompanyPaymentAttemptLimit * @param CalculatesBookingOutstanding $calculatesBookingOutstanding */ - public function __construct(FetchesBookingQuotation $fetchBookingQuotation, GeneratesBookingQuotation $generatesBookingQuotation, FetchesCompanyPaymentAttemptLimit $fetchesCompanyPaymentAttemptLimit, CalculatesBookingOutstanding $calculatesBookingOutstanding) + public function __construct(FetchesBookingQuotation $fetchBookingQuotation, GeneratesBookingQuotation $generatesBookingQuotation, FetchesCompanyPaymentAttemptLimit $fetchesCompanyPaymentAttemptLimit, CalculatesBookingOutstanding $calculatesBookingOutstanding, CalculatesBookingRefundAmount $calculatesBookingRefundAmount) { $this->fetchBookingQuotation = $fetchBookingQuotation; $this->generatesBookingQuotation = $generatesBookingQuotation; $this->fetchesCompanyPaymentAttemptLimit = $fetchesCompanyPaymentAttemptLimit; $this->calculatesBookingOutstanding = $calculatesBookingOutstanding; + $this->calculatesBookingRefundAmount = $calculatesBookingRefundAmount; } /** @@ -66,7 +71,7 @@ class FetchBookingPaymentQuotationLogic extends AbstractControllerLogic $conversionObject = new CurrencyConversionObject(floatval(str_replace(',', '', $request->input('amount'))), $booking->convertible_currency_id, $booking->service_id, $booking->fix_currency_id === 1 ? 0:1, PaymentMethodType::PAYMENT_METHODS[$request->input('payment_method')]); - $outstanding = $this->calculatesBookingOutstanding->execute($booking); + $outstanding = $this->calculatesBookingOutstanding->execute($booking) + $this->calculatesBookingRefundAmount->execute($booking, $booking->fix_currency_id); if($conversionObject->getAmount() > round($outstanding, 2)) throw new MalformedRequestException('Your payment must not be greater than '.$booking->fixedCurrency->short_code.' '. number_format((float)$outstanding, 2, '.', ',')); //Voucherify diff --git a/app/Classes/Modules/Bookings/Services/CalculatesBookingRefundAmount.php b/app/Classes/Modules/Bookings/Services/CalculatesBookingRefundAmount.php index 14a4a9ef..f6dab1f4 100644 --- a/app/Classes/Modules/Bookings/Services/CalculatesBookingRefundAmount.php +++ b/app/Classes/Modules/Bookings/Services/CalculatesBookingRefundAmount.php @@ -2,19 +2,30 @@ namespace App\Classes\Modules\Bookings\Services; - use App\Classes\ValueObjects\Constants\ApprovalStatus; -use App\Classes\ValueObjects\Constants\TransactionType; use App\Models\Booking; -use Carbon\Carbon; class CalculatesBookingRefundAmount { + public function execute(Booking $booking, int $type, ?string $payment_reference = null): float + { + $refundAmounts = $booking->transactions()->payments()->get()->map(function ($payment) use ($type) { + return $this->calculateRefundAmount($payment, $type); + }); - public function execute(Booking $booking, int $type, ?string $payment_reference = NULL){ - return $type === 1 ? - $booking->transactions()->refunds($payment_reference) - ->selectRaw('sum(amount - service_charge - tax) as sub_total')->get()->sum('sub_total') : $booking->transactions()->refunds($payment_reference)->sum('original_amount'); + $totalRefundAmount = $refundAmounts->sum(); + + return $totalRefundAmount; } -} \ No newline at end of file + private function calculateRefundAmount($payment, int $type): float + { + $refundTransactions = $payment->transactions()->refunds()->whereIn('status', [ApprovalStatus::APPROVED]); + + if ($type === 1) { + return $refundTransactions->selectRaw('sum(amount - service_charge - tax) as sub_total')->get()->sum('sub_total'); + } + + return $refundTransactions->sum('original_amount'); + } +} diff --git a/app/Classes/Modules/Transactions/ControllersLogic/UpdateRefundTransactionStatusLogic.php b/app/Classes/Modules/Transactions/ControllersLogic/UpdateRefundTransactionStatusLogic.php index bf704359..04fa5e6a 100644 --- a/app/Classes/Modules/Transactions/ControllersLogic/UpdateRefundTransactionStatusLogic.php +++ b/app/Classes/Modules/Transactions/ControllersLogic/UpdateRefundTransactionStatusLogic.php @@ -13,6 +13,8 @@ use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use App\Classes\Modules\Wallets\Processors\CreditWalletProcessor; +use App\Classes\Modules\Bookings\Services\CalculatesBookingPayableAmount; +use App\Classes\Modules\Bookings\Services\CalculatesBookingRefundAmount; class UpdateRefundTransactionStatusLogic extends AbstractControllerLogic @@ -43,6 +45,12 @@ class UpdateRefundTransactionStatusLogic extends AbstractControllerLogic /** @var CreditWalletProcessor */ private $creditWalletProcessor; + /** @var CalculatesBookingPayableAmount */ + private $calculatesBookingPayableAmount; + + /** @var CalculatesBookingRefundAmount */ + private $calculatesBookingRefundAmount; + /** * CreatePaymentVerificationDocumentLogic constructor. * @param FetchesCompany $fetchesCompany @@ -50,14 +58,18 @@ class UpdateRefundTransactionStatusLogic extends AbstractControllerLogic * @param UpdatesTransactionStatus $updatesTransactionStatus * @param DeletesDocument $deletesDocument * @param CreditWalletProcessor $creditWalletProcessor + * @param CalculatesBookingPayableAmount $calculatesBookingPayableAmount + * @param CalculatesBookingRefundAmount $calculatesBookingRefundAmount */ - public function __construct(FetchesCompany $fetchesCompany, FetchesTransaction $fetchesTransaction, UpdatesTransactionStatus $updatesTransactionStatus, DeletesDocument $deletesDocument, CreditWalletProcessor $creditWalletProcessor) + public function __construct(FetchesCompany $fetchesCompany, FetchesTransaction $fetchesTransaction, UpdatesTransactionStatus $updatesTransactionStatus, DeletesDocument $deletesDocument, CreditWalletProcessor $creditWalletProcessor, CalculatesBookingPayableAmount $calculatesBookingPayableAmount, CalculatesBookingRefundAmount $calculatesBookingRefundAmount) { $this->fetchesCompany = $fetchesCompany; $this->fetchesTransaction = $fetchesTransaction; $this->updatesTransactionStatus = $updatesTransactionStatus; $this->deletesDocument = $deletesDocument; $this->creditWalletProcessor = $creditWalletProcessor; + $this->calculatesBookingPayableAmount = $calculatesBookingPayableAmount; + $this->calculatesBookingRefundAmount = $calculatesBookingRefundAmount; } /** @@ -69,7 +81,7 @@ class UpdateRefundTransactionStatusLogic extends AbstractControllerLogic { $transaction = $this->fetchesTransaction->execute(['id' => $request->route('id')]); - $transaction = $this->updatesTransactionStatus->execute($transaction, $request->input('status')); + $transaction = $this->updatesTransactionStatus->execute($transaction, $request->route('status')); $booking = $transaction->owner->owner; @@ -81,7 +93,10 @@ class UpdateRefundTransactionStatusLogic extends AbstractControllerLogic $this->creditWalletProcessor->execute($booking->company, $transaction->type, $transaction->amount, $reference); } - + $paidAmount = $this->calculatesBookingPayableAmount->execute($booking, $booking->fix_currency_id) - $this->calculatesBookingRefundAmount->execute($booking, $booking->fix_currency_id); + if (!$paidAmount > 0) { + $this->updatesTransactionStatus->execute($paymentTransaction, ApprovalStatus::REFUNDED); + } return $this->response([]); } diff --git a/app/Http/Resources/BookingResource.php b/app/Http/Resources/BookingResource.php index f3a7881d..ea3278c4 100644 --- a/app/Http/Resources/BookingResource.php +++ b/app/Http/Resources/BookingResource.php @@ -34,7 +34,7 @@ class BookingResource extends JsonResource 'amount' => $this->fix_amount, 'floating_amount' => floatval((App()->make(CalculatesBookingFloatingAmount::class))->execute($this->resource, $this->fix_currency_id)), 'paid_amount' => floatval((App()->make(CalculatesBookingPayableAmount::class))->execute($this->resource, $this->fix_currency_id)) - floatval((App()->make(CalculatesBookingRefundAmount::class))->execute($this->resource, $this->fix_currency_id)), - 'outstanding_amount' => floatval((App()->make(CalculatesBookingOutstanding::class))->execute($this->resource)) - floatval((App()->make(CalculatesBookingRefundAmount::class))->execute($this->resource, $this->fix_currency_id)), + 'outstanding_amount' => floatval((App()->make(CalculatesBookingOutstanding::class))->execute($this->resource)) + floatval((App()->make(CalculatesBookingRefundAmount::class))->execute($this->resource, $this->fix_currency_id)), 'fixed_currency' => new CurrencyResource($this->fixedCurrency), 'convertible_currency' => new CurrencyResource($this->convertibleCurrency), 'conversion_currency' => new CurrencyResource($this->conversionCurrency), @@ -60,7 +60,7 @@ class BookingResource extends JsonResource 'expired_payment_attempts' => TransactionResource::collection($this->transactions()->payments()->where('status', ApprovalStatus::PENDING_SUBMISSION)->whereDate('expires_on', '>=', Carbon::now())->where('expires_on', '>', Carbon::now()->toTimeString())->get()), 'payment_history' => TransactionResource::collection($this->transactions()->where(function($query){ $query->where(function($query){ - $query->payments()->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::PENDING_VERIFICATION, ApprovalStatus::COMPLETED, ApprovalStatus::REJECTED]); + $query->payments()->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::PENDING_VERIFICATION, ApprovalStatus::COMPLETED, ApprovalStatus::REJECTED, ApprovalStatus::REFUNDED]); })->orWhere(function($query){ $query->where(function($query){ $query->where('type', TransactionType::REFUND)->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::PENDING_VERIFICATION, ApprovalStatus::REJECTED, ApprovalStatus::COMPLETED]); diff --git a/app/Http/Resources/TransactionResource.php b/app/Http/Resources/TransactionResource.php index 27fd17ab..9e743042 100644 --- a/app/Http/Resources/TransactionResource.php +++ b/app/Http/Resources/TransactionResource.php @@ -45,6 +45,7 @@ class TransactionResource extends JsonResource 'transaction_refunds' => TransactionResource::collection($this->when((int) $this->type === TransactionType::PAYMENT, $this->transactions()->refunds()->get())), 'expires_on' => Carbon::parse($this->expires_on)->format('d-m-Y h:i:s A'), 'updated_at' => Carbon::parse($this->updated_at)->format('d-m-Y h:i:s A'), + 'created_at' => Carbon::parse($this->created_at)->format('d-m-Y h:i:s A'), 'interval' => [ 'value' => $days->gt(Carbon::now()) ? '+' : '-', 'duration' => $days->diff(Carbon::now())->format('%d'), diff --git a/resources/assets/vue/components/bookings/elements/PaymentHistoryComponent.vue b/resources/assets/vue/components/bookings/elements/PaymentHistoryComponent.vue index 43e2e96d..00d51f06 100644 --- a/resources/assets/vue/components/bookings/elements/PaymentHistoryComponent.vue +++ b/resources/assets/vue/components/bookings/elements/PaymentHistoryComponent.vue @@ -4,12 +4,12 @@
-
+
Status
-
- {{ item.status === 1 ? 'Pending Verification' : item.status === 4 ? 'Rejected' : 'Processing Payment'}} +
+ {{ item.status === 7 ? 'Refunded' : (item.status === 1 ? 'Processing Payment' : 'Transferred')}}
{{ item.status === 1 ? 'Pending Verification' : item.status === 4 ? 'Rejected' : 'Processing Payment'}} @@ -39,7 +39,7 @@
-
+
@@ -147,13 +147,13 @@
Refunded Amount
-
{{item.original_currency.short_code}} {{(Math.round((totalRefunds + Number.EPSILON) * 100) / 100).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}}
+
{{item.original_currency.short_code}} {{(Math.round((totalRefunds + Number.EPSILON) * 100) / 100).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}}
-
{{item.currency.short_code}} {{(Math.round((totalConvertRefunds + Number.EPSILON) * 100) / 100).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}}
+
{{item.currency.short_code}} {{(Math.round((totalConvertRefunds + Number.EPSILON) * 100) / 100).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}}
@@ -292,7 +292,7 @@
-
+
@@ -301,42 +301,83 @@
- +
-
-
-
-
{{ index + 1 }}. Refund updated on
+
+
+
+
Created At
+
+ {{ refund.created_at }} +
+
+
+
Status
+
+
{{ refund.status === 1 ? 'Pending Verification' : refund.status === 2 ? 'Approved' : 'Rejected'}}
+
+
+
+
Amount
+
+
{{refund.currency.short_code}} {{(Math.round((refund.amount + Number.EPSILON) * 100) / 100).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}}
+
-
{{ refund.updated_at }}
+
Amount
+
+
{{refund.original_currency.short_code}} {{(Math.round((refund.original_amount + Number.EPSILON) * 100) / 100).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}}
+
-
+
-
    Refund status
-
-
-
{{ refund.status === 1 ? 'Pending Verification' : refund.status === 2 ? 'Approved' : 'Rejected'}}
-
-
-
-
-
    Requested Refund Amount
-
-
-
{{refund.original_currency.short_code}} {{(Math.round((refund.original_amount + Number.EPSILON) * 100) / 100).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}}
-
-
-
-
-
-
{{refund.currency.short_code}} {{(Math.round((refund.amount + Number.EPSILON) * 100) / 100).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}}
+ + + + + + + + + + +
diff --git a/resources/assets/vue/components/bookings/elements/RefundConfirmationComponent.vue b/resources/assets/vue/components/bookings/elements/RefundConfirmationComponent.vue index de2cd48f..ec5f1ac6 100644 --- a/resources/assets/vue/components/bookings/elements/RefundConfirmationComponent.vue +++ b/resources/assets/vue/components/bookings/elements/RefundConfirmationComponent.vue @@ -3,64 +3,42 @@
-
-
-
Request Refund
+
Request Refund
+
+
+
+
+
Refund Type:
+
+
+ {{ method.name }}
-
+
-
+ + + + +
+
+
-
-
-
-
-
-
-
-
-
Refund Type:
-
-
- Full Refund -
-
- Partial Refund -
-
-
-
-
-
- - - - -
-
-
-
-
{{data.booking.fixed_currency.short_code}}
-
-
-
-
-
-
-
-
-
-
+
{{ data.booking.fixed_currency.short_code }}
- +
@@ -71,47 +49,54 @@ \ No newline at end of file + }, + mixins: [FormHandler, ModalFormHandler] +} + diff --git a/resources/assets/vue/components/bookings/elements/RefundVerificationComponent.vue b/resources/assets/vue/components/bookings/elements/RefundVerificationComponent.vue index 42d5682e..24ec68a6 100644 --- a/resources/assets/vue/components/bookings/elements/RefundVerificationComponent.vue +++ b/resources/assets/vue/components/bookings/elements/RefundVerificationComponent.vue @@ -115,7 +115,7 @@ approveRefund(status){ this.isLoading = true; this.parameters.status = status; - this.submit(this.route('api.transaction.refund.status.update', this.data.id), 'put', 'listRefundTransactionSection', true, true); + this.submit(this.route('api.transaction.refund.status.update', this.data.id, status), 'put', 'listRefundTransactionSection', true, true); }, }, mixins: [componentHandler, staticFormHandler] diff --git a/resources/assets/vue/components/bookings/forms/PurchaseOrderFormComponent.vue b/resources/assets/vue/components/bookings/forms/PurchaseOrderFormComponent.vue index 9a1bf774..9b8045f9 100644 --- a/resources/assets/vue/components/bookings/forms/PurchaseOrderFormComponent.vue +++ b/resources/assets/vue/components/bookings/forms/PurchaseOrderFormComponent.vue @@ -240,7 +240,11 @@ }, watch: { 'data': function () { - this.products = this.data.purchase_order.details + if (this.data && this.data.purchase_order && this.data.purchase_order.details) { + this.products = this.data.purchase_order.details; + } else { + this.products = []; + } } }, methods: { diff --git a/routes/transaction.php b/routes/transaction.php index e714d6b7..f2f4a630 100644 --- a/routes/transaction.php +++ b/routes/transaction.php @@ -11,7 +11,7 @@ Route::group(['prefix' => 'transactions', 'namespace' => 'Transactions', 'as' => route::post('{id}/bill/verification', 'CreatePaymentProofDocumentController@verify')->name('bill.verification'); route::post('{id}/bill/pay', 'CreatePaymentProofDocumentController@pay')->name('bill.pay'); Route::put('/{id}/bill/{status}', 'UpdatePaymentTransactionStatusController@update')->where('status', 'pending|complete')->name('bill.status'); - Route::put('/{id}/refund/status/update', 'UpdateRefundTransactionStatusController@update')->name('refund.status.update'); + Route::put('/{id}/refund/status/update/{status}', 'UpdateRefundTransactionStatusController@update')->name('refund.status.update'); route::delete('{id}/bill/delete', 'DeletePaymentProofDocumentController@delete')->name('bill.delete'); From 609b71f549e5062640d464b673bce6842f2603b6 Mon Sep 17 00:00:00 2001 From: edmondlang Date: Mon, 19 Feb 2024 00:57:42 +0800 Subject: [PATCH 27/59] code upfate for refund booking --- .../Services/CalculatesBookingRefundAmount.php | 2 +- .../UpdateRefundTransactionStatusLogic.php | 14 +++++++------- app/Http/Resources/TransactionResource.php | 2 ++ .../elements/PaymentHistoryComponent.vue | 2 +- .../elements/RefundConfirmationComponent.vue | 16 +++++++++++++--- 5 files changed, 24 insertions(+), 12 deletions(-) diff --git a/app/Classes/Modules/Bookings/Services/CalculatesBookingRefundAmount.php b/app/Classes/Modules/Bookings/Services/CalculatesBookingRefundAmount.php index f6dab1f4..239545af 100644 --- a/app/Classes/Modules/Bookings/Services/CalculatesBookingRefundAmount.php +++ b/app/Classes/Modules/Bookings/Services/CalculatesBookingRefundAmount.php @@ -18,7 +18,7 @@ class CalculatesBookingRefundAmount return $totalRefundAmount; } - private function calculateRefundAmount($payment, int $type): float + public function calculateRefundAmount($payment, int $type): float { $refundTransactions = $payment->transactions()->refunds()->whereIn('status', [ApprovalStatus::APPROVED]); diff --git a/app/Classes/Modules/Transactions/ControllersLogic/UpdateRefundTransactionStatusLogic.php b/app/Classes/Modules/Transactions/ControllersLogic/UpdateRefundTransactionStatusLogic.php index 04fa5e6a..d0e5802a 100644 --- a/app/Classes/Modules/Transactions/ControllersLogic/UpdateRefundTransactionStatusLogic.php +++ b/app/Classes/Modules/Transactions/ControllersLogic/UpdateRefundTransactionStatusLogic.php @@ -79,18 +79,18 @@ class UpdateRefundTransactionStatusLogic extends AbstractControllerLogic */ public function logic(Request $request) : JsonResponse { - $transaction = $this->fetchesTransaction->execute(['id' => $request->route('id')]); + $refundTransaction = $this->fetchesTransaction->execute(['id' => $request->route('id')]); - $transaction = $this->updatesTransactionStatus->execute($transaction, $request->route('status')); + $refundTransaction = $this->updatesTransactionStatus->execute($refundTransaction, $request->route('status')); - $booking = $transaction->owner->owner; + $paymentTransaction = $refundTransaction->owner; - $paymentTransaction = $transaction->owner; + $booking = $paymentTransaction->owner; - $reference = $transaction->amount == $paymentTransaction->amount ? 'Fully Refund for Ref. ' . $booking->marking : 'Partially Refund for Ref. ' . $booking->marking; + $reference = $refundTransaction->amount == $paymentTransaction->amount ? 'Fully Refund for Ref. ' . $booking->marking : 'Partially Refund for Ref. ' . $booking->marking; - if ($transaction->status == ApprovalStatus::APPROVED) { - $this->creditWalletProcessor->execute($booking->company, $transaction->type, $transaction->amount, $reference); + if ($refundTransaction->status == ApprovalStatus::APPROVED) { + $this->creditWalletProcessor->execute($booking->company, $refundTransaction->type, $refundTransaction->amount, $reference); } $paidAmount = $this->calculatesBookingPayableAmount->execute($booking, $booking->fix_currency_id) - $this->calculatesBookingRefundAmount->execute($booking, $booking->fix_currency_id); diff --git a/app/Http/Resources/TransactionResource.php b/app/Http/Resources/TransactionResource.php index 9e743042..09967f4c 100644 --- a/app/Http/Resources/TransactionResource.php +++ b/app/Http/Resources/TransactionResource.php @@ -2,6 +2,7 @@ namespace App\Http\Resources; +use App\Classes\Modules\Bookings\Services\CalculatesBookingRefundAmount; use App\Classes\ValueObjects\Constants\TransactionType; use App\Models\Booking; use Carbon\Carbon; @@ -43,6 +44,7 @@ class TransactionResource extends JsonResource 'documents' => new DocumentResource($this->documents()->first()), 'transaction_bill' => new TransactionResource($this->when((int) $this->type === TransactionType::PAYMENT, $this->transactions()->bills()->first())), 'transaction_refunds' => TransactionResource::collection($this->when((int) $this->type === TransactionType::PAYMENT, $this->transactions()->refunds()->get())), + 'refunded_amount' => $this->booking ? floatval((App()->make(CalculatesBookingRefundAmount::class))->calculateRefundAmount($this->resource, $this->booking->fix_currency_id)) : null, 'expires_on' => Carbon::parse($this->expires_on)->format('d-m-Y h:i:s A'), 'updated_at' => Carbon::parse($this->updated_at)->format('d-m-Y h:i:s A'), 'created_at' => Carbon::parse($this->created_at)->format('d-m-Y h:i:s A'), diff --git a/resources/assets/vue/components/bookings/elements/PaymentHistoryComponent.vue b/resources/assets/vue/components/bookings/elements/PaymentHistoryComponent.vue index 00d51f06..877ec248 100644 --- a/resources/assets/vue/components/bookings/elements/PaymentHistoryComponent.vue +++ b/resources/assets/vue/components/bookings/elements/PaymentHistoryComponent.vue @@ -291,7 +291,7 @@
-
+
diff --git a/resources/assets/vue/components/bookings/elements/RefundConfirmationComponent.vue b/resources/assets/vue/components/bookings/elements/RefundConfirmationComponent.vue index ec5f1ac6..75253aaa 100644 --- a/resources/assets/vue/components/bookings/elements/RefundConfirmationComponent.vue +++ b/resources/assets/vue/components/bookings/elements/RefundConfirmationComponent.vue @@ -35,13 +35,20 @@
+
+
+
Paid Amount: {{ paidAmount }}
+
Refund Amount: {{ refundAmount }}
+
+
- +
@@ -78,11 +85,15 @@ export default { }, computed: { refundAmount() { - return (Math.round((this.data.booking.amount - this.totalRefunds + Number.EPSILON) * 100) / 100).toFixed(2); + // return (Math.round((this.data.booking.amount - this.totalRefunds + Number.EPSILON) * 100) / 100).toFixed(2); + return (Math.round((this.data.original_amount - this.data.refunded_amount + Number.EPSILON) * 100) / 100).toFixed(2); }, refundMaxValue() { return this.refundAmount; }, + paidAmount() { + return this.data.original_amount; + }, }, methods: { submitForm() { @@ -94,7 +105,6 @@ export default { if (this.refundMethod.name === 'Fully Refund') { this.refundAmount = this.refundMaxValue; } - console.log(this.refundAmount); }, }, mixins: [FormHandler, ModalFormHandler] From 9e3c34eb7383e9c2bb6855487e336bfe9de34bc6 Mon Sep 17 00:00:00 2001 From: edmondlang Date: Tue, 20 Feb 2024 22:41:28 +0800 Subject: [PATCH 28/59] change payment status when it has been fully refunded --- .../ControllersLogic/UpdateRefundTransactionStatusLogic.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Classes/Modules/Transactions/ControllersLogic/UpdateRefundTransactionStatusLogic.php b/app/Classes/Modules/Transactions/ControllersLogic/UpdateRefundTransactionStatusLogic.php index d0e5802a..09e4b102 100644 --- a/app/Classes/Modules/Transactions/ControllersLogic/UpdateRefundTransactionStatusLogic.php +++ b/app/Classes/Modules/Transactions/ControllersLogic/UpdateRefundTransactionStatusLogic.php @@ -93,7 +93,7 @@ class UpdateRefundTransactionStatusLogic extends AbstractControllerLogic $this->creditWalletProcessor->execute($booking->company, $refundTransaction->type, $refundTransaction->amount, $reference); } - $paidAmount = $this->calculatesBookingPayableAmount->execute($booking, $booking->fix_currency_id) - $this->calculatesBookingRefundAmount->execute($booking, $booking->fix_currency_id); + $paidAmount = $paymentTransaction->original_amount - $this->calculatesBookingRefundAmount->calculateRefundAmount($paymentTransaction, $booking->fix_currency_id); if (!$paidAmount > 0) { $this->updatesTransactionStatus->execute($paymentTransaction, ApprovalStatus::REFUNDED); } From 9aa75630ff3dbff177816678db84d5609b5a4099 Mon Sep 17 00:00:00 2001 From: edmondlang Date: Wed, 21 Feb 2024 00:20:45 +0800 Subject: [PATCH 29/59] update code for refund booking --- app/Http/Resources/BookingResource.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/app/Http/Resources/BookingResource.php b/app/Http/Resources/BookingResource.php index 04204a37..6803eec9 100644 --- a/app/Http/Resources/BookingResource.php +++ b/app/Http/Resources/BookingResource.php @@ -32,7 +32,8 @@ class BookingResource extends JsonResource 'amount' => $this->fix_amount, 'floating_amount' => floatval((App()->make(CalculatesBookingFloatingAmount::class))->execute($this->resource, $this->fix_currency_id)), 'paid_amount' => floatval((App()->make(CalculatesBookingPayableAmount::class))->execute($this->resource, $this->fix_currency_id)) - floatval((App()->make(CalculatesBookingRefundAmount::class))->execute($this->resource, $this->fix_currency_id)), - 'outstanding_amount' => floatval((App()->make(CalculatesBookingOutstanding::class))->execute($this->resource)) + floatval((App()->make(CalculatesBookingRefundAmount::class))->execute($this->resource, $this->fix_currency_id)), + // 'outstanding_amount' => floatval((App()->make(CalculatesBookingOutstanding::class))->execute($this->resource)) + floatval((App()->make(CalculatesBookingRefundAmount::class))->execute($this->resource, $this->fix_currency_id)), + 'outstanding_amount' => floatval((App()->make(CalculatesBookingOutstanding::class))->execute($this->resource)), 'fixed_currency' => new CurrencyResource($this->fixedCurrency), 'convertible_currency' => new CurrencyResource($this->convertibleCurrency), 'conversion_currency' => new CurrencyResource($this->conversionCurrency), From df17a8497ddc98fcc7ca39ffd1b2bdbd45b0e811 Mon Sep 17 00:00:00 2001 From: edmondlang Date: Wed, 21 Feb 2024 00:33:08 +0800 Subject: [PATCH 30/59] comment partial refund function --- .../ControllersLogic/CreateSupplierTransactionLogic.php | 1 + .../sections/SupplierPendingOrdersSectionComponent.vue | 4 +++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/app/Classes/Modules/Transactions/ControllersLogic/CreateSupplierTransactionLogic.php b/app/Classes/Modules/Transactions/ControllersLogic/CreateSupplierTransactionLogic.php index fb324267..4c407cf5 100644 --- a/app/Classes/Modules/Transactions/ControllersLogic/CreateSupplierTransactionLogic.php +++ b/app/Classes/Modules/Transactions/ControllersLogic/CreateSupplierTransactionLogic.php @@ -82,6 +82,7 @@ class CreateSupplierTransactionLogic extends AbstractControllerLogic $payments = $request->input('payments'); + // todo-refund: activate this for partial refund foreach($payments as $payment){ $payment = $this->fetchesTransaction->execute(['id' => $payment['id']]); diff --git a/resources/assets/vue/components/bookings/sections/SupplierPendingOrdersSectionComponent.vue b/resources/assets/vue/components/bookings/sections/SupplierPendingOrdersSectionComponent.vue index aee9ab40..fa345d58 100644 --- a/resources/assets/vue/components/bookings/sections/SupplierPendingOrdersSectionComponent.vue +++ b/resources/assets/vue/components/bookings/sections/SupplierPendingOrdersSectionComponent.vue @@ -200,7 +200,9 @@ }, updateList(){ - this.$refs.pendingOrdersList.updateFilters({per_page: 10000, status: 2, type: 1, is_not_fully_refunded: true, original_currency_id_in: [this.selectedCurrency.id], transaction_service_id: this.selectedService.id}); + // todo-refund: activate this for partial refund + // this.$refs.pendingOrdersList.updateFilters({per_page: 10000, status: 2, type: 1, original_currency_id_in: [this.selectedCurrency.id], transaction_service_id: this.selectedService.id, is_not_fully_refunded: true}); + this.$refs.pendingOrdersList.updateFilters({per_page: 10000, status: 2, type: 1, original_currency_id_in: [this.selectedCurrency.id], transaction_service_id: this.selectedService.id}); this.selectedSupplier.status = false; this.currencyDropdownLaunch.status = false; From 28c0aeff77b7b4cf7ca0985be4f431b2832616c1 Mon Sep 17 00:00:00 2001 From: edmondlang Date: Mon, 26 Feb 2024 00:38:25 +0800 Subject: [PATCH 31/59] dont show payment on homepage if it is in refund process --- .../Filters/DoesNotHaveRefundInProgress.php | 24 +++++++++++++++++++ .../SupplierPendingOrdersSectionComponent.vue | 4 ++-- 2 files changed, 26 insertions(+), 2 deletions(-) create mode 100644 app/Classes/General/Eloquent/Filters/DoesNotHaveRefundInProgress.php diff --git a/app/Classes/General/Eloquent/Filters/DoesNotHaveRefundInProgress.php b/app/Classes/General/Eloquent/Filters/DoesNotHaveRefundInProgress.php new file mode 100644 index 00000000..60618626 --- /dev/null +++ b/app/Classes/General/Eloquent/Filters/DoesNotHaveRefundInProgress.php @@ -0,0 +1,24 @@ +whereDoesntHave('transactions', function ($query) { + return $query->where('type', TransactionType::REFUND)->whereIn('status', [ApprovalStatus::PENDING_SUBMISSION, ApprovalStatus::PENDING_VERIFICATION]); + }); + } +} diff --git a/resources/assets/vue/components/bookings/sections/SupplierPendingOrdersSectionComponent.vue b/resources/assets/vue/components/bookings/sections/SupplierPendingOrdersSectionComponent.vue index fa345d58..8f6fb8c7 100644 --- a/resources/assets/vue/components/bookings/sections/SupplierPendingOrdersSectionComponent.vue +++ b/resources/assets/vue/components/bookings/sections/SupplierPendingOrdersSectionComponent.vue @@ -117,7 +117,7 @@
- + @@ -202,7 +202,7 @@ // todo-refund: activate this for partial refund // this.$refs.pendingOrdersList.updateFilters({per_page: 10000, status: 2, type: 1, original_currency_id_in: [this.selectedCurrency.id], transaction_service_id: this.selectedService.id, is_not_fully_refunded: true}); - this.$refs.pendingOrdersList.updateFilters({per_page: 10000, status: 2, type: 1, original_currency_id_in: [this.selectedCurrency.id], transaction_service_id: this.selectedService.id}); + this.$refs.pendingOrdersList.updateFilters({per_page: 10, status: 2, type: 1, original_currency_id_in: [this.selectedCurrency.id], transaction_service_id: this.selectedService.id, does_not_have_refund_in_progress: true}); this.selectedSupplier.status = false; this.currencyDropdownLaunch.status = false; From f84b04c26caa336abad90a87e66991c21f44532c Mon Sep 17 00:00:00 2001 From: edmondlang Date: Tue, 27 Feb 2024 01:08:16 +0800 Subject: [PATCH 32/59] update logging and indentation --- app/Console/Commands/ExpiredBookingCommand.php | 6 ++++-- app/Console/Kernel.php | 8 ++++---- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/app/Console/Commands/ExpiredBookingCommand.php b/app/Console/Commands/ExpiredBookingCommand.php index ca690c67..5779a9e9 100644 --- a/app/Console/Commands/ExpiredBookingCommand.php +++ b/app/Console/Commands/ExpiredBookingCommand.php @@ -66,9 +66,10 @@ class ExpiredBookingCommand extends Command $transactions = $booking->transactions; foreach ($transactions as $transaction) { + $prevStatus = $transaction->status; $transaction->status = ApprovalStatus::EXPIRED; $transaction->save(); - Log::info("Expired Transaction id: {$transaction->id} from Booking id: {$booking->id}"); + Log::info("Expired Transaction id: {$transaction->id} from Booking id: {$booking->id}. Status before update: {$prevStatus}"); } } @@ -89,9 +90,10 @@ class ExpiredBookingCommand extends Command $transactions = $booking->transactions; foreach ($transactions as $transaction) { + $prevStatus = $transaction->status; $transaction->status = ApprovalStatus::EXPIRED; $transaction->save(); - Log::info("Expired Transaction id: {$transaction->id} from Booking id: {$booking->id}"); + Log::info("Expired Transaction id: {$transaction->id} from Booking id: {$booking->id}. Status before update: {$prevStatus}"); } } } diff --git a/app/Console/Kernel.php b/app/Console/Kernel.php index 412ed70f..5e9aa8a8 100644 --- a/app/Console/Kernel.php +++ b/app/Console/Kernel.php @@ -45,12 +45,12 @@ class Kernel extends ConsoleKernel ->withoutOverlapping(); $schedule->command('booking:expired') - ->dailyAt('02:00') - ->withoutOverlapping(); + ->dailyAt('02:00') + ->withoutOverlapping(); $schedule->command('purchaseOrder:autoFill') - ->dailyAt('03:00') - ->withoutOverlapping(); + ->dailyAt('03:00') + ->withoutOverlapping(); } /** From efb909555e0a3edbf15eb95083a1b5a4994400e4 Mon Sep 17 00:00:00 2001 From: edmondlang Date: Fri, 1 Mar 2024 14:28:52 +0800 Subject: [PATCH 33/59] debug payment not showing issue --- routes/web.php | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/routes/web.php b/routes/web.php index a6590c17..1fb2878f 100644 --- a/routes/web.php +++ b/routes/web.php @@ -866,3 +866,55 @@ Route::get('/invoice/{marking}/{started_at}/{ended_at}/fix', function($marking, } ); })->name('invoice.fix.byCustomerMarking'); + +Route::get('/transfer/{marking}/payment-details', function ($marking) { + $booking = Booking::where('marking', $marking)->first(); + + $transactions = $booking->transactions()->withTrashed()->get(); + + $statusLabels = [ + 0 => 'PAYMENT_ATTEMPT', + 1 => 'PAYMENT', + 2 => 'INVOICE', + 3 => 'BILL', + 4 => 'PROFORMA', + 5 => 'TOP_UP', + 6 => 'REFUND', + 7 => 'PURCHASE_ORDER', + 8 => 'SUPPLIER_DELIVER', + 9 => 'CREDIT_NOTE', + 10 => 'WITHDRAW', + 11 => 'DEBIT_NOTE', + 12 => 'TRANSFER_FEE', + 13 => 'CASH_BACK', + ]; + + $ApprovalStatus = ApprovalStatus::APPROVAL_STATUS_ID; + + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + + foreach ($transactions as $transaction) { + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + } + + echo ''; + echo '
IDAmountTypeStatusCreated AtDeleted At
' . $transaction->id . '' . $transaction->amount . '' . $statusLabels[$transaction->type] . '' . $ApprovalStatus [$transaction->status] . '' . $transaction->created_at . '' . $transaction->deleted_at . '
'; +}); From 5cf55453fd690186aa03413add24a54d38805a3e Mon Sep 17 00:00:00 2001 From: edmondlang Date: Fri, 1 Mar 2024 21:57:06 +0800 Subject: [PATCH 34/59] show-booking-expired for debug payment not showing --- app/Console/Kernel.php | 12 ++++---- routes/web.php | 70 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 76 insertions(+), 6 deletions(-) diff --git a/app/Console/Kernel.php b/app/Console/Kernel.php index 5e9aa8a8..d1f54f52 100644 --- a/app/Console/Kernel.php +++ b/app/Console/Kernel.php @@ -44,13 +44,13 @@ class Kernel extends ConsoleKernel ->appendOutputTo(storage_path().'/logs/delete-bulk-download-files.log') ->withoutOverlapping(); - $schedule->command('booking:expired') - ->dailyAt('02:00') - ->withoutOverlapping(); + // $schedule->command('booking:expired') + // ->dailyAt('02:00') + // ->withoutOverlapping(); - $schedule->command('purchaseOrder:autoFill') - ->dailyAt('03:00') - ->withoutOverlapping(); + // $schedule->command('purchaseOrder:autoFill') + // ->dailyAt('03:00') + // ->withoutOverlapping(); } /** diff --git a/routes/web.php b/routes/web.php index 1fb2878f..44380046 100644 --- a/routes/web.php +++ b/routes/web.php @@ -872,6 +872,8 @@ Route::get('/transfer/{marking}/payment-details', function ($marking) { $transactions = $booking->transactions()->withTrashed()->get(); + $paymentMethods = PaymentMethodType::PAYMENT_METHODS_ID; + $statusLabels = [ 0 => 'PAYMENT_ATTEMPT', 1 => 'PAYMENT', @@ -898,6 +900,7 @@ Route::get('/transfer/{marking}/payment-details', function ($marking) { echo 'Amount'; echo 'Type'; echo 'Status'; + echo 'Payment Method'; echo 'Created At'; echo 'Deleted At'; echo ''; @@ -910,6 +913,7 @@ Route::get('/transfer/{marking}/payment-details', function ($marking) { echo '' . $transaction->amount . ''; echo '' . $statusLabels[$transaction->type] . ''; echo '' . $ApprovalStatus [$transaction->status] . ''; + echo '' . $paymentMethods [$transaction->payment_method] . ''; echo '' . $transaction->created_at . ''; echo '' . $transaction->deleted_at . ''; echo ''; @@ -917,4 +921,70 @@ Route::get('/transfer/{marking}/payment-details', function ($marking) { echo ''; echo ''; + + echo '
'; + echo 'Wallet Details'; + +})->name('booking.details.transactions'); + +Route::get('show-booking-expired', function () { + $transactions = Transaction::where('type', TransactionType::PAYMENT) + ->where('status', ApprovalStatus::EXPIRED) + ->whereDate('updated_at', '>=', '2024-02-16') + ->orderBy('updated_at', 'desc') + ->get(); + // print_r(count($transactions)); + + + $statusLabels = [ + 0 => 'PAYMENT_ATTEMPT', + 1 => 'PAYMENT', + 2 => 'INVOICE', + 3 => 'BILL', + 4 => 'PROFORMA', + 5 => 'TOP_UP', + 6 => 'REFUND', + 7 => 'PURCHASE_ORDER', + 8 => 'SUPPLIER_DELIVER', + 9 => 'CREDIT_NOTE', + 10 => 'WITHDRAW', + 11 => 'DEBIT_NOTE', + 12 => 'TRANSFER_FEE', + 13 => 'CASH_BACK', + ]; + + $ApprovalStatus = ApprovalStatus::APPROVAL_STATUS_ID; + + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + + $counter = 1; + + foreach ($transactions as $transaction) { + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + } + + echo ''; + echo '
CounterIDBookingPaymentsAmountTypeStatusUpdated At
' . $counter++ . '' . $transaction->id . '' . ''.$transaction->owner->marking.'' . '' . 'Payments' . '' . $transaction->amount . '' . $statusLabels[$transaction->type] . '' . $ApprovalStatus [$transaction->status] . '' . $transaction->updated_at . '
'; }); From dfc2ddd09b8809b5db806139d92e4ddc333c2f6f Mon Sep 17 00:00:00 2001 From: edmondlang Date: Fri, 1 Mar 2024 22:49:14 +0800 Subject: [PATCH 35/59] debug payment not showing issue --- routes/web.php | 30 ++++++++++++++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/routes/web.php b/routes/web.php index 44380046..ddc5ae7e 100644 --- a/routes/web.php +++ b/routes/web.php @@ -922,8 +922,10 @@ Route::get('/transfer/{marking}/payment-details', function ($marking) { echo ''; echo ''; - echo '
'; - echo 'Wallet Details'; + echo '
----------------------------------------------------------------
'; + + echo 'Wallet Details'; + })->name('booking.details.transactions'); @@ -931,6 +933,7 @@ Route::get('show-booking-expired', function () { $transactions = Transaction::where('type', TransactionType::PAYMENT) ->where('status', ApprovalStatus::EXPIRED) ->whereDate('updated_at', '>=', '2024-02-16') + ->take(10) ->orderBy('updated_at', 'desc') ->get(); // print_r(count($transactions)); @@ -954,6 +957,8 @@ Route::get('show-booking-expired', function () { ]; $ApprovalStatus = ApprovalStatus::APPROVAL_STATUS_ID; + + $paymentMethods = PaymentMethodType::PAYMENT_METHODS_ID; echo ''; echo ''; @@ -965,6 +970,8 @@ Route::get('show-booking-expired', function () { echo ''; echo ''; echo ''; + echo ''; + echo ''; echo ''; echo ''; echo ''; @@ -973,6 +980,23 @@ Route::get('show-booking-expired', function () { $counter = 1; foreach ($transactions as $transaction) { + + $billplz_status = null; + + if ($transaction->payment_method == PaymentMethodType::PAYMENT_GATEWAY) { + $response = Http::withBasicAuth(config('billplz.api_key') . ':', '')->get(config('billplz.base_url') . '/api/v3/bills/' . $transaction->payment_reference); + if ($response->successful()) { + $data = $response->json(); + if ($data['paid']) { + $billplz_status = 'Paid'; + } else { + $billplz_status = $transaction->id . " => Fraud"; + } + } else { + $billplz_status = $transaction->id . " => billplz error"; + } + } + echo ''; echo ''; echo ''; @@ -981,6 +1005,8 @@ Route::get('show-booking-expired', function () { echo ''; echo ''; echo ''; + echo ''; + echo ''; echo ''; echo ''; } From b2dd34106ccfea281d1bad2a6fde0e4a2a266a57 Mon Sep 17 00:00:00 2001 From: edmondlang Date: Fri, 1 Mar 2024 22:51:56 +0800 Subject: [PATCH 36/59] debug payment not showing issue --- routes/web.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/routes/web.php b/routes/web.php index ddc5ae7e..bc6730f5 100644 --- a/routes/web.php +++ b/routes/web.php @@ -973,6 +973,7 @@ Route::get('show-booking-expired', function () { echo ''; echo ''; echo ''; + echo ''; echo ''; echo ''; echo ''; @@ -1008,6 +1009,7 @@ Route::get('show-booking-expired', function () { echo ''; echo ''; echo ''; + echo ''; echo ''; } From 42a399999a8edb965da5b5686467ea116f45bf4c Mon Sep 17 00:00:00 2001 From: JiaSheng Date: Fri, 1 Mar 2024 23:28:14 +0800 Subject: [PATCH 37/59] uncomment and log to specific file for booking expired command --- app/Console/Commands/ExpiredBookingCommand.php | 8 ++++---- app/Console/Kernel.php | 7 ++++--- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/app/Console/Commands/ExpiredBookingCommand.php b/app/Console/Commands/ExpiredBookingCommand.php index 5779a9e9..2be39c15 100644 --- a/app/Console/Commands/ExpiredBookingCommand.php +++ b/app/Console/Commands/ExpiredBookingCommand.php @@ -62,14 +62,14 @@ class ExpiredBookingCommand extends Command foreach ($bookings as $booking) { $this->updatesBookingStatus->execute($booking, ApprovalStatus::EXPIRED); - Log::info("Expired Booking without payment & purchase order, booking id: " . $booking->id); + $this->info("Expired Booking without payment & purchase order, booking id: " . $booking->id); $transactions = $booking->transactions; foreach ($transactions as $transaction) { $prevStatus = $transaction->status; $transaction->status = ApprovalStatus::EXPIRED; $transaction->save(); - Log::info("Expired Transaction id: {$transaction->id} from Booking id: {$booking->id}. Status before update: {$prevStatus}"); + $this->info("Expired Transaction id: {$transaction->id} from Booking id: {$booking->id}. Status before update: {$prevStatus}"); } } @@ -86,14 +86,14 @@ class ExpiredBookingCommand extends Command foreach ($bookings as $booking) { $this->updatesBookingStatus->execute($booking, ApprovalStatus::EXPIRED); - Log::info("Expired Booking without payment but with purchase order, booking id: " . $booking->id); + $this->info("Expired Booking without payment but with purchase order, booking id: " . $booking->id); $transactions = $booking->transactions; foreach ($transactions as $transaction) { $prevStatus = $transaction->status; $transaction->status = ApprovalStatus::EXPIRED; $transaction->save(); - Log::info("Expired Transaction id: {$transaction->id} from Booking id: {$booking->id}. Status before update: {$prevStatus}"); + $this->info("Expired Transaction id: {$transaction->id} from Booking id: {$booking->id}. Status before update: {$prevStatus}"); } } } diff --git a/app/Console/Kernel.php b/app/Console/Kernel.php index d1f54f52..e455eea1 100644 --- a/app/Console/Kernel.php +++ b/app/Console/Kernel.php @@ -44,9 +44,10 @@ class Kernel extends ConsoleKernel ->appendOutputTo(storage_path().'/logs/delete-bulk-download-files.log') ->withoutOverlapping(); - // $schedule->command('booking:expired') - // ->dailyAt('02:00') - // ->withoutOverlapping(); + $schedule->command('booking:expired') + ->dailyAt('02:00') + ->appendOutputTo(storage_path().'/logs/expire-booking.log') + ->withoutOverlapping(); // $schedule->command('purchaseOrder:autoFill') // ->dailyAt('03:00') From 8b22b49937d5b66d1d6cf0c1b39f838e97c4e7a4 Mon Sep 17 00:00:00 2001 From: edmondlang Date: Sat, 2 Mar 2024 00:25:00 +0800 Subject: [PATCH 38/59] remove testing code --- routes/web.php | 150 ------------------------------------------------- 1 file changed, 150 deletions(-) diff --git a/routes/web.php b/routes/web.php index bc6730f5..a6590c17 100644 --- a/routes/web.php +++ b/routes/web.php @@ -866,153 +866,3 @@ Route::get('/invoice/{marking}/{started_at}/{ended_at}/fix', function($marking, } ); })->name('invoice.fix.byCustomerMarking'); - -Route::get('/transfer/{marking}/payment-details', function ($marking) { - $booking = Booking::where('marking', $marking)->first(); - - $transactions = $booking->transactions()->withTrashed()->get(); - - $paymentMethods = PaymentMethodType::PAYMENT_METHODS_ID; - - $statusLabels = [ - 0 => 'PAYMENT_ATTEMPT', - 1 => 'PAYMENT', - 2 => 'INVOICE', - 3 => 'BILL', - 4 => 'PROFORMA', - 5 => 'TOP_UP', - 6 => 'REFUND', - 7 => 'PURCHASE_ORDER', - 8 => 'SUPPLIER_DELIVER', - 9 => 'CREDIT_NOTE', - 10 => 'WITHDRAW', - 11 => 'DEBIT_NOTE', - 12 => 'TRANSFER_FEE', - 13 => 'CASH_BACK', - ]; - - $ApprovalStatus = ApprovalStatus::APPROVAL_STATUS_ID; - - echo '
AmountTypeStatusPayment MethodBillPlz ResponseUpdated At
' . $counter++ . '' . $transaction->id . '' . $transaction->amount . '' . $statusLabels[$transaction->type] . '' . $ApprovalStatus [$transaction->status] . '' . $paymentMethods [$transaction->payment_method] . '' . $billplz_status . '' . $transaction->updated_at . '
Payment MethodBillPlz ResponseUpdated AtCreated At
' . $paymentMethods [$transaction->payment_method] . '' . $billplz_status . '' . $transaction->updated_at . '' . $transaction->created_at . '
'; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - - foreach ($transactions as $transaction) { - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - } - - echo ''; - echo '
IDAmountTypeStatusPayment MethodCreated AtDeleted At
' . $transaction->id . '' . $transaction->amount . '' . $statusLabels[$transaction->type] . '' . $ApprovalStatus [$transaction->status] . '' . $paymentMethods [$transaction->payment_method] . '' . $transaction->created_at . '' . $transaction->deleted_at . '
'; - - echo '
----------------------------------------------------------------
'; - - echo 'Wallet Details'; - - -})->name('booking.details.transactions'); - -Route::get('show-booking-expired', function () { - $transactions = Transaction::where('type', TransactionType::PAYMENT) - ->where('status', ApprovalStatus::EXPIRED) - ->whereDate('updated_at', '>=', '2024-02-16') - ->take(10) - ->orderBy('updated_at', 'desc') - ->get(); - // print_r(count($transactions)); - - - $statusLabels = [ - 0 => 'PAYMENT_ATTEMPT', - 1 => 'PAYMENT', - 2 => 'INVOICE', - 3 => 'BILL', - 4 => 'PROFORMA', - 5 => 'TOP_UP', - 6 => 'REFUND', - 7 => 'PURCHASE_ORDER', - 8 => 'SUPPLIER_DELIVER', - 9 => 'CREDIT_NOTE', - 10 => 'WITHDRAW', - 11 => 'DEBIT_NOTE', - 12 => 'TRANSFER_FEE', - 13 => 'CASH_BACK', - ]; - - $ApprovalStatus = ApprovalStatus::APPROVAL_STATUS_ID; - - $paymentMethods = PaymentMethodType::PAYMENT_METHODS_ID; - - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - - $counter = 1; - - foreach ($transactions as $transaction) { - - $billplz_status = null; - - if ($transaction->payment_method == PaymentMethodType::PAYMENT_GATEWAY) { - $response = Http::withBasicAuth(config('billplz.api_key') . ':', '')->get(config('billplz.base_url') . '/api/v3/bills/' . $transaction->payment_reference); - if ($response->successful()) { - $data = $response->json(); - if ($data['paid']) { - $billplz_status = 'Paid'; - } else { - $billplz_status = $transaction->id . " => Fraud"; - } - } else { - $billplz_status = $transaction->id . " => billplz error"; - } - } - - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - } - - echo ''; - echo '
CounterIDBookingPaymentsAmountTypeStatusPayment MethodBillPlz ResponseUpdated AtCreated At
' . $counter++ . '' . $transaction->id . '' . ''.$transaction->owner->marking.'' . '' . 'Payments' . '' . $transaction->amount . '' . $statusLabels[$transaction->type] . '' . $ApprovalStatus [$transaction->status] . '' . $paymentMethods [$transaction->payment_method] . '' . $billplz_status . '' . $transaction->updated_at . '' . $transaction->created_at . '
'; -}); From 2d5bbac3b1f5d21889f3a7846ae33e7f4b32a010 Mon Sep 17 00:00:00 2001 From: edmondlang Date: Sat, 2 Mar 2024 00:32:55 +0800 Subject: [PATCH 39/59] update ExpiredBookingCommand logging - add timestamp --- app/Console/Commands/ExpiredBookingCommand.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/app/Console/Commands/ExpiredBookingCommand.php b/app/Console/Commands/ExpiredBookingCommand.php index 2be39c15..fe4f260e 100644 --- a/app/Console/Commands/ExpiredBookingCommand.php +++ b/app/Console/Commands/ExpiredBookingCommand.php @@ -62,14 +62,14 @@ class ExpiredBookingCommand extends Command foreach ($bookings as $booking) { $this->updatesBookingStatus->execute($booking, ApprovalStatus::EXPIRED); - $this->info("Expired Booking without payment & purchase order, booking id: " . $booking->id); + $this->info(Carbon::now() . " : Expired Booking without payment & purchase order, booking id: " . $booking->id); $transactions = $booking->transactions; foreach ($transactions as $transaction) { $prevStatus = $transaction->status; $transaction->status = ApprovalStatus::EXPIRED; $transaction->save(); - $this->info("Expired Transaction id: {$transaction->id} from Booking id: {$booking->id}. Status before update: {$prevStatus}"); + $this->info(Carbon::now() . " : Expired Transaction id: {$transaction->id} from Booking id: {$booking->id}. Status before update: {$prevStatus}"); } } @@ -86,14 +86,14 @@ class ExpiredBookingCommand extends Command foreach ($bookings as $booking) { $this->updatesBookingStatus->execute($booking, ApprovalStatus::EXPIRED); - $this->info("Expired Booking without payment but with purchase order, booking id: " . $booking->id); + $this->info(Carbon::now() . " : Expired Booking without payment but with purchase order, booking id: " . $booking->id); $transactions = $booking->transactions; foreach ($transactions as $transaction) { $prevStatus = $transaction->status; $transaction->status = ApprovalStatus::EXPIRED; $transaction->save(); - $this->info("Expired Transaction id: {$transaction->id} from Booking id: {$booking->id}. Status before update: {$prevStatus}"); + $this->info(Carbon::now() . " : Expired Transaction id: {$transaction->id} from Booking id: {$booking->id}. Status before update: {$prevStatus}"); } } } From df7f9531e82ca8fcc3750318716cbd4d7f816cf1 Mon Sep 17 00:00:00 2001 From: Omair Saleh Date: Thu, 7 Mar 2024 11:38:03 +0800 Subject: [PATCH 40/59] fix payment history display transfer status --- .../elements/PaymentHistoryComponent.vue | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/resources/assets/vue/components/bookings/elements/PaymentHistoryComponent.vue b/resources/assets/vue/components/bookings/elements/PaymentHistoryComponent.vue index 877ec248..90270fee 100644 --- a/resources/assets/vue/components/bookings/elements/PaymentHistoryComponent.vue +++ b/resources/assets/vue/components/bookings/elements/PaymentHistoryComponent.vue @@ -8,8 +8,17 @@
Status
-
- {{ item.status === 7 ? 'Refunded' : (item.status === 1 ? 'Processing Payment' : 'Transferred')}} +
+ {{ item.status === 1 ? 'Pending Verification' : item.status === 4 ? 'Rejected' : 'Processing Payment'}} +
+
+ {{ item.status === 1 ? 'Pending Verification' : item.status === 4 ? 'Rejected' : 'Processing Payment'}} +
+
+
+
Status
+
+ {{ item.status === 7 ? 'Refunded' : (item.status === 1 ? 'Pending Verification' : item.status === 4 ? 'Rejected' : 'Payment Approved')}}
{{ item.status === 1 ? 'Pending Verification' : item.status === 4 ? 'Rejected' : 'Processing Payment'}} @@ -18,7 +27,7 @@
Payment Amount
- {{item.currency.short_code}} {{(Math.round((item.amount + Number.EPSILON) * 100) / 100).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}} + {{item.original_currency.short_code}} {{(Math.round((item.original_amount + Number.EPSILON) * 100) / 100).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}}
@@ -61,7 +70,7 @@
Status
-
+
{{ item.transaction_bill.status === 1 ? 'Processing Payment' : 'Transferred'}}
From 32224f6803cc36185e53387794063098b12bde8e Mon Sep 17 00:00:00 2001 From: Omair Saleh Date: Thu, 7 Mar 2024 11:43:19 +0800 Subject: [PATCH 41/59] fix payment history display transfer status --- .../bookings/elements/PaymentHistoryComponent.vue | 9 --------- 1 file changed, 9 deletions(-) diff --git a/resources/assets/vue/components/bookings/elements/PaymentHistoryComponent.vue b/resources/assets/vue/components/bookings/elements/PaymentHistoryComponent.vue index 90270fee..1db22609 100644 --- a/resources/assets/vue/components/bookings/elements/PaymentHistoryComponent.vue +++ b/resources/assets/vue/components/bookings/elements/PaymentHistoryComponent.vue @@ -6,15 +6,6 @@
-
-
Status
-
- {{ item.status === 1 ? 'Pending Verification' : item.status === 4 ? 'Rejected' : 'Processing Payment'}} -
-
- {{ item.status === 1 ? 'Pending Verification' : item.status === 4 ? 'Rejected' : 'Processing Payment'}} -
-
Status
From 70300412467eeeb9b0877c6afb34877c8def563b Mon Sep 17 00:00:00 2001 From: Omair Saleh Date: Thu, 7 Mar 2024 11:46:46 +0800 Subject: [PATCH 42/59] fix payment history display transfer status --- .../components/bookings/elements/PaymentHistoryComponent.vue | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/resources/assets/vue/components/bookings/elements/PaymentHistoryComponent.vue b/resources/assets/vue/components/bookings/elements/PaymentHistoryComponent.vue index 1db22609..a6556cd2 100644 --- a/resources/assets/vue/components/bookings/elements/PaymentHistoryComponent.vue +++ b/resources/assets/vue/components/bookings/elements/PaymentHistoryComponent.vue @@ -61,7 +61,7 @@
Status
-
+
{{ item.transaction_bill.status === 1 ? 'Processing Payment' : 'Transferred'}}
From b0e3467fbe40bf1590a041509511eb5e7fc60412 Mon Sep 17 00:00:00 2001 From: JiaSheng Date: Thu, 7 Mar 2024 15:41:21 +0800 Subject: [PATCH 43/59] export pending order should not export order with refund in progress --- routes/web.php | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/routes/web.php b/routes/web.php index a6590c17..9016724c 100644 --- a/routes/web.php +++ b/routes/web.php @@ -386,7 +386,11 @@ Route::get('/segments', function (Request $request) { })->name('segments'); Route::get('/pending_orders', function(){ - $payments = Transaction::where('type', TransactionType::PAYMENT)->where('owner_type', Booking::class)->whereIn('status', [ApprovalStatus::APPROVED])->get(); + $payments = Transaction::where('type', TransactionType::PAYMENT)->where('owner_type', Booking::class)->whereIn('status', [ApprovalStatus::APPROVED]) + ->whereDoesntHave('transactions', function ($query) { + return $query->where('type', TransactionType::REFUND)->whereIn('status', [ApprovalStatus::PENDING_SUBMISSION, ApprovalStatus::PENDING_VERIFICATION]); + }) + ->get(); echo ''; $i = 0; From 6d8cce464c2ee568bdeaf24a08692843b3e7d61b Mon Sep 17 00:00:00 2001 From: Omair Saleh Date: Fri, 8 Mar 2024 03:08:21 +0800 Subject: [PATCH 44/59] don't paginate the pending currency order page --- .../bookings/sections/SupplierPendingOrdersSectionComponent.vue | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/resources/assets/vue/components/bookings/sections/SupplierPendingOrdersSectionComponent.vue b/resources/assets/vue/components/bookings/sections/SupplierPendingOrdersSectionComponent.vue index 8f6fb8c7..fb766fe4 100644 --- a/resources/assets/vue/components/bookings/sections/SupplierPendingOrdersSectionComponent.vue +++ b/resources/assets/vue/components/bookings/sections/SupplierPendingOrdersSectionComponent.vue @@ -202,7 +202,7 @@ // todo-refund: activate this for partial refund // this.$refs.pendingOrdersList.updateFilters({per_page: 10000, status: 2, type: 1, original_currency_id_in: [this.selectedCurrency.id], transaction_service_id: this.selectedService.id, is_not_fully_refunded: true}); - this.$refs.pendingOrdersList.updateFilters({per_page: 10, status: 2, type: 1, original_currency_id_in: [this.selectedCurrency.id], transaction_service_id: this.selectedService.id, does_not_have_refund_in_progress: true}); + this.$refs.pendingOrdersList.updateFilters({per_page: 10000, status: 2, type: 1, original_currency_id_in: [this.selectedCurrency.id], transaction_service_id: this.selectedService.id, does_not_have_refund_in_progress: true}); this.selectedSupplier.status = false; this.currencyDropdownLaunch.status = false; From 626bec90d2381ca7ea1b3f61bd5f739c2434a331 Mon Sep 17 00:00:00 2001 From: JiaSheng Date: Mon, 11 Mar 2024 01:14:40 +0800 Subject: [PATCH 45/59] update export pending order so that partial refund booking show correct amount --- routes/web.php | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/routes/web.php b/routes/web.php index 9016724c..ef5538ab 100644 --- a/routes/web.php +++ b/routes/web.php @@ -25,6 +25,7 @@ use Spatie\Activitylog\Models\Activity; use Webklex\PDFMerger\Facades\PDFMergerFacade as PDFMerger; use App\Classes\Modules\Documents\DataTransferObjects\DocumentObject; use App\Classes\Modules\Bookings\Processors\CreatePurchaseOrderFor1688OrderProcessor; +use App\Classes\Modules\Bookings\Services\CalculatesBookingRefundAmount; use App\Classes\Modules\Documents\Services\DeletesDocument; use App\Classes\Modules\Transactions\Processors\CreateInvoiceTransactionWithInvoiceNoProcessor; use App\Classes\Modules\Transactions\Services\DeletesTransaction; @@ -396,6 +397,8 @@ Route::get('/pending_orders', function(){ $i = 0; foreach ($payments as $payment){ $booking = $payment->owner; + $original_refunds = floatval((App()->make(CalculatesBookingRefundAmount::class))->calculateRefundAmount($payment, $booking->fix_currency_id)); + $refunds = $original_refunds / $payment->currency_rate; if(!$booking instanceof Booking){ dd($payment); } @@ -411,11 +414,11 @@ Route::get('/pending_orders', function(){ echo ''; echo ''; echo ''; - echo ''; + echo ''; echo ''; echo ''; echo ''; - echo ''; + echo ''; echo ''; echo ''; echo ''; From 36cde82a19ba93a70230105b2efcd9782f536ccd Mon Sep 17 00:00:00 2001 From: Dillon Ngo Date: Thu, 14 Mar 2024 15:52:20 +0800 Subject: [PATCH 46/59] Send welcome email with voucher to user upon successful verification of customer email adddress --- .../General/Interfaces/KeyValueInterface.php | 12 ++++ app/Classes/Jobs/SendWelcomeVoucherEmail.php | 70 +++++++++++++++++++ .../ControllersLogic/CreateCustomerLogic.php | 3 +- .../UserEmailVerificationLogic.php | 29 +++++++- .../KeyValuePairObject.php | 44 ++++++++++++ .../Accounts/Services/CreatesKeyValuePair.php | 28 ++++++++ .../ListUserVouchersLogic.php | 7 ++ .../Notifications/WelcomeVoucherEmail.php | 43 ++++++++++++ .../ValueObjects/Constants/Vouchers.php | 8 +++ app/Http/Resources/KeyValueBasicResource.php | 24 +++++++ app/Http/Resources/UserRewardResource.php | 8 +++ app/Http/Resources/VoucherResource.php | 17 +++-- app/Models/KeyValuePair.php | 15 ++++ app/Models/User.php | 21 +++++- ...08_135259_create_key_value_pairs_table.php | 37 ++++++++++ .../SingleUserRewardItemComponent.vue | 7 ++ .../emails/accounts/welcome_voucher.blade.php | 8 +++ routes/web.php | 18 +++-- 18 files changed, 384 insertions(+), 15 deletions(-) create mode 100644 app/Classes/General/Interfaces/KeyValueInterface.php create mode 100644 app/Classes/Jobs/SendWelcomeVoucherEmail.php create mode 100644 app/Classes/Modules/Accounts/DataTransferObjects/KeyValuePairObject.php create mode 100644 app/Classes/Modules/Accounts/Services/CreatesKeyValuePair.php create mode 100644 app/Classes/Notifications/WelcomeVoucherEmail.php create mode 100644 app/Classes/ValueObjects/Constants/Vouchers.php create mode 100644 app/Http/Resources/KeyValueBasicResource.php create mode 100644 app/Models/KeyValuePair.php create mode 100644 database/migrations/2024_03_08_135259_create_key_value_pairs_table.php create mode 100644 resources/views/emails/accounts/welcome_voucher.blade.php diff --git a/app/Classes/General/Interfaces/KeyValueInterface.php b/app/Classes/General/Interfaces/KeyValueInterface.php new file mode 100644 index 00000000..fbee5265 --- /dev/null +++ b/app/Classes/General/Interfaces/KeyValueInterface.php @@ -0,0 +1,12 @@ +user = $user; + $this->voucher = $voucher; + $this->emailSentCount = $emailSentCount; + } + + + public function handle() + { + $currentDatetime = Carbon::now(); + $dateToCompare = Carbon::parse($this->voucher->end_date); + if (!$this->user->hasAttribute($this->voucher->code."_EMAIL_COUNT") + && $this->user->rewards->where('voucher_id', $this->voucher->id)->count() > 0 + && $currentDatetime->isBefore($dateToCompare)) + { + //Key #1 + $keyValuePairObject = new KeyValuePairObject( + $this->voucher->code."_EMAIL_COUNT", + $this->emailSentCount + ); + (App()->make(CreatesKeyValuePair::class))->execute($this->user, $keyValuePairObject); + + //Key #2 + $keyValuePairObject = new KeyValuePairObject( + $this->voucher->code."_EMAIL_DATE_".$this->emailSentCount, + Carbon::now() + ); + (App()->make(CreatesKeyValuePair::class))->execute($this->user, $keyValuePairObject); + + $this->user->notify(new WelcomeVoucherEmail($this->user, $this->voucher)); + } + } +} diff --git a/app/Classes/Modules/Accounts/ControllersLogic/CreateCustomerLogic.php b/app/Classes/Modules/Accounts/ControllersLogic/CreateCustomerLogic.php index fa6a9ae7..0f7bdb61 100644 --- a/app/Classes/Modules/Accounts/ControllersLogic/CreateCustomerLogic.php +++ b/app/Classes/Modules/Accounts/ControllersLogic/CreateCustomerLogic.php @@ -30,6 +30,7 @@ use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use Illuminate\Support\Facades\App; use App\Classes\Modules\Segments\Services\CreatesSeasonalSegment; +use App\Classes\ValueObjects\Constants\Vouchers; class CreateCustomerLogic extends AbstractControllerLogic { @@ -159,7 +160,7 @@ class CreateCustomerLogic extends AbstractControllerLogic $this->newCustomerToVoucherifyProcessor->execute($company->id, $user, true); - $this->createVoucherProcessor->execute($user, 'WELCOME50%OFF'); + $this->createVoucherProcessor->execute($user, Vouchers::WELCOME_50_PERCENT_OFF); return $this->response($this->authenticationProcessor->execute($request, false)); diff --git a/app/Classes/Modules/Accounts/ControllersLogic/UserEmailVerificationLogic.php b/app/Classes/Modules/Accounts/ControllersLogic/UserEmailVerificationLogic.php index bae6f5eb..13a8bcc7 100644 --- a/app/Classes/Modules/Accounts/ControllersLogic/UserEmailVerificationLogic.php +++ b/app/Classes/Modules/Accounts/ControllersLogic/UserEmailVerificationLogic.php @@ -9,6 +9,9 @@ use App\Classes\Modules\Accounts\Services\CompletesEmailVerificationAttempt; use App\Classes\Modules\Accounts\Services\FetchesEmailVerificationAttempt; use App\Classes\Modules\Accounts\Services\VerifiesUser; use App\Classes\Modules\Accounts\Standards\Criteria\EmailVerificationActiveAttemptExists; +use App\Classes\Modules\Vouchers\Services\FetchesVoucher; +use App\Classes\Jobs\SendWelcomeVoucherEmail; +use App\Classes\ValueObjects\Constants\Vouchers; use App\Models\UserEmailVerification; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; @@ -36,19 +39,29 @@ class UserEmailVerificationLogic extends AbstractControllerLogic /** @var VerifiesUser */ private $verifiesUser; + /** @var SendWelcomeVoucherEmail */ + private $sendWelcomeVoucherEmail; + + /** @var FetchesVoucher */ + private $fetchesVoucher; + /** * UserEmailVerificationLogic constructor. * @param EmailVerificationActiveAttemptExists $emailVerificationActiveAttemptExists * @param CompletesEmailVerificationAttempt $completesEmailVerificationAttempt * @param FetchesEmailVerificationAttempt $fetchesEmailVerificationAttempt * @param VerifiesUser $verifiesUser + * @param SendWelcomeVoucherEmail $sendWelcomeVoucherEmail + * @param FetchesVoucher $fetchesVoucher */ - public function __construct(EmailVerificationActiveAttemptExists $emailVerificationActiveAttemptExists, CompletesEmailVerificationAttempt $completesEmailVerificationAttempt, FetchesEmailVerificationAttempt $fetchesEmailVerificationAttempt, VerifiesUser $verifiesUser) + public function __construct(EmailVerificationActiveAttemptExists $emailVerificationActiveAttemptExists, CompletesEmailVerificationAttempt $completesEmailVerificationAttempt, FetchesEmailVerificationAttempt $fetchesEmailVerificationAttempt, VerifiesUser $verifiesUser, SendWelcomeVoucherEmail $sendWelcomeVoucherEmail, FetchesVoucher $fetchesVoucher) { $this->emailVerificationActiveAttemptExists = $emailVerificationActiveAttemptExists; $this->completesEmailVerificationAttempt = $completesEmailVerificationAttempt; $this->fetchesEmailVerificationAttempt = $fetchesEmailVerificationAttempt; $this->verifiesUser = $verifiesUser; + $this->sendWelcomeVoucherEmail = $sendWelcomeVoucherEmail; + $this->fetchesVoucher = $fetchesVoucher; } /** @@ -68,9 +81,19 @@ class UserEmailVerificationLogic extends AbstractControllerLogic $this->completesEmailVerificationAttempt->execute($attempt); - $this->verifiesUser->execute($attempt->user); + $user = $attempt->user; + $this->verifiesUser->execute($user); + + // if (env('SENDING_EMAIL_WELCOME_VOUCHER_ENABLED', false)){ + if (app()->environment('production') && env('SENDING_EMAIL_WELCOME_VOUCHER_ENABLED', false)){ + try{ //In case voucher got deleted unintentionally + $voucher = $this->fetchesVoucher->execute(['code' => Vouchers::WELCOME_50_PERCENT_OFF]); + if($voucher) $this->sendWelcomeVoucherEmail::dispatch($user, $voucher, 1); + } + catch(\Exception $e){} + } return $this->response([]); } -} \ No newline at end of file +} diff --git a/app/Classes/Modules/Accounts/DataTransferObjects/KeyValuePairObject.php b/app/Classes/Modules/Accounts/DataTransferObjects/KeyValuePairObject.php new file mode 100644 index 00000000..fd1eff49 --- /dev/null +++ b/app/Classes/Modules/Accounts/DataTransferObjects/KeyValuePairObject.php @@ -0,0 +1,44 @@ +key = $key; + $this->value = $value; + } + + /** + * @return string + */ + public function getKey(): string + { + return $this->key; + } + + /** + * @return string + */ + public function getValue(): string + { + return $this->value; + } + +} diff --git a/app/Classes/Modules/Accounts/Services/CreatesKeyValuePair.php b/app/Classes/Modules/Accounts/Services/CreatesKeyValuePair.php new file mode 100644 index 00000000..c963ec4e --- /dev/null +++ b/app/Classes/Modules/Accounts/Services/CreatesKeyValuePair.php @@ -0,0 +1,28 @@ +key = $object->getKey(); + $model->value = $object->getValue(); + + return $this->handler($kv->attributes(), $model); + + } +} diff --git a/app/Classes/Modules/Vouchers/ControllersLogic/ListUserVouchersLogic.php b/app/Classes/Modules/Vouchers/ControllersLogic/ListUserVouchersLogic.php index 16356f0f..013be9d6 100644 --- a/app/Classes/Modules/Vouchers/ControllersLogic/ListUserVouchersLogic.php +++ b/app/Classes/Modules/Vouchers/ControllersLogic/ListUserVouchersLogic.php @@ -4,9 +4,11 @@ namespace App\Classes\Modules\Vouchers\ControllersLogic; use App\Classes\General\Abstracts\AbstractControllerLogic; use App\Classes\Modules\Rewards\Services\ListsUserRewards; +use App\Classes\ValueObjects\Constants\RoleTypes; use App\Http\Resources\UserRewardResource; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; +use Illuminate\Support\Facades\Auth; class ListUserVouchersLogic extends AbstractControllerLogic { @@ -40,6 +42,11 @@ class ListUserVouchersLogic extends AbstractControllerLogic public function logic(Request $request) : JsonResponse { $query = $this->listsUserRewards->execute($this->listsUserRewards->deserializeFilters($request->input('filters'))); + + if(in_array(Auth::user()->type, RoleTypes::ADMIN_ROLES)){ + $request->merge(['isAdmin' => true]); + } + return $this->collectionResponse(UserRewardResource::collection($query)); } diff --git a/app/Classes/Notifications/WelcomeVoucherEmail.php b/app/Classes/Notifications/WelcomeVoucherEmail.php new file mode 100644 index 00000000..0800b8cc --- /dev/null +++ b/app/Classes/Notifications/WelcomeVoucherEmail.php @@ -0,0 +1,43 @@ +user = $user; + $this->voucher = $voucher; + } + + + public function toMail() + { + $this->voucher->end_date = Carbon::parse($this->voucher->end_date)->format('Y-m-d'); + $mailMessage = (new MailMessage) + ->subject('Welcome Voucher') + ->view('emails.accounts.welcome_voucher', ['user' => $this->user, 'voucher' => $this->voucher]); + + return $mailMessage; + } + + +} diff --git a/app/Classes/ValueObjects/Constants/Vouchers.php b/app/Classes/ValueObjects/Constants/Vouchers.php new file mode 100644 index 00000000..d43194f9 --- /dev/null +++ b/app/Classes/ValueObjects/Constants/Vouchers.php @@ -0,0 +1,8 @@ + $this->id, + 'key' => $this->key, + 'value' => $this->value, + ]; + } +} diff --git a/app/Http/Resources/UserRewardResource.php b/app/Http/Resources/UserRewardResource.php index ed693b4c..b988a1d3 100644 --- a/app/Http/Resources/UserRewardResource.php +++ b/app/Http/Resources/UserRewardResource.php @@ -2,6 +2,7 @@ namespace App\Http\Resources; + use Illuminate\Http\Resources\Json\JsonResource; class UserRewardResource extends JsonResource @@ -14,6 +15,13 @@ class UserRewardResource extends JsonResource */ public function toArray($request) { + $emailReminder = null; + if ($request->has('isAdmin')) { + $keyValuePairs = $this->user->attributes()->get(); + $emailReminder = KeyValueBasicResource::collection($keyValuePairs); + $this->voucher->email = $emailReminder; + } + return [ 'id' => $this->id, 'user_id' => $this->user_id, diff --git a/app/Http/Resources/VoucherResource.php b/app/Http/Resources/VoucherResource.php index 54193eeb..3f3112bb 100644 --- a/app/Http/Resources/VoucherResource.php +++ b/app/Http/Resources/VoucherResource.php @@ -2,6 +2,7 @@ namespace App\Http\Resources; +use ArrayObject; use Illuminate\Http\Resources\Json\JsonResource; class VoucherResource extends JsonResource @@ -14,9 +15,16 @@ class VoucherResource extends JsonResource */ public function toArray($request) { - $filteredRedemptions = $this->redemptions->filter(function ($redemption) { - return $redemption->transaction && $redemption->transaction->owner; - }); + $filteredRedemptions = new ArrayObject([]); + if ($request->has('filters') && str_contains($request->input('filters'), "has_active_reward")) { + $filteredRedemptions = new ArrayObject([]); + } + else{ + $filteredRedemptions = $this->redemptions->filter(function ($redemption) { + return $redemption->transaction && $redemption->transaction->owner; + }); + } + return [ 'id' => $this->id, 'name' => $this->name, @@ -25,7 +33,8 @@ class VoucherResource extends JsonResource 'value' => (float) $this->value, 'start_date' => $this->start_date, 'end_date' => $this->end_date, - 'is_redeemed' => $filteredRedemptions->count() > 0 + 'is_redeemed' => $filteredRedemptions->count() > 0, + 'email' => $this->email ? new KeyValueBasicResource($this->email->where('key', $this->code.'_EMAIL_COUNT')->first()) : null, ]; } } diff --git a/app/Models/KeyValuePair.php b/app/Models/KeyValuePair.php new file mode 100644 index 00000000..3ad6d6cd --- /dev/null +++ b/app/Models/KeyValuePair.php @@ -0,0 +1,15 @@ +morphTo(); + } +} diff --git a/app/Models/User.php b/app/Models/User.php index 4bc7ec17..7e0a4aa9 100644 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -2,6 +2,7 @@ namespace App\Models; +use App\Classes\General\Interfaces\KeyValueInterface; use App\Classes\General\Interfaces\Voucherifiable; use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Database\Eloquent\Relations\HasMany; @@ -26,7 +27,8 @@ class User extends AbstractModel implements AuthenticatableContract, AuthorizableContract, CanResetPasswordContract, - Voucherifiable + Voucherifiable, + KeyValueInterface { use HasRoles, Notifiable, Authenticatable, Authorizable, CanResetPassword, MustVerifyEmail, SoftDeletes; @@ -101,4 +103,21 @@ class User extends AbstractModel implements { return $this->HasMany(UserReward::class, 'user_id', 'id'); } + + public function hasAttribute(string $key, $value = null): bool + { + $query = $this->attributes()->where('key', $key); + + if ($value !== null) { + $query->where('value', $value); + } + + return $query->exists(); + } + + + public function attributes(): MorphMany + { + return $this->morphMany(KeyValuePair::class, 'owner'); + } } diff --git a/database/migrations/2024_03_08_135259_create_key_value_pairs_table.php b/database/migrations/2024_03_08_135259_create_key_value_pairs_table.php new file mode 100644 index 00000000..b952ff56 --- /dev/null +++ b/database/migrations/2024_03_08_135259_create_key_value_pairs_table.php @@ -0,0 +1,37 @@ +id(); + $table->string('owner_type'); //'user', 'order', 'transaction' + $table->unsignedBigInteger('owner_id'); + $table->string('key'); + $table->string('value'); + $table->timestamps(); + + $table->index(['owner_type', 'owner_id']); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::dropIfExists('key_value_pairs'); + } +} diff --git a/resources/assets/vue/components/companies/elements/SingleUserRewardItemComponent.vue b/resources/assets/vue/components/companies/elements/SingleUserRewardItemComponent.vue index 8f25ab60..9cc2409a 100644 --- a/resources/assets/vue/components/companies/elements/SingleUserRewardItemComponent.vue +++ b/resources/assets/vue/components/companies/elements/SingleUserRewardItemComponent.vue @@ -9,6 +9,10 @@

RM{{ item.voucher.value/100 }} Discount

{{ item.voucher.value }}% Discount

+
+ + +
'.$booking->marking.''.\App\Classes\ValueObjects\Constants\PaymentMethodType::PAYMENT_METHODS_ID[$payment->payment_method].''.$payment->currency->short_code.''.$payment->amount.''.number_format(bcsub($payment->amount, $refunds, 7), 5, '.', '').''.$booking->company->reference.''.$payment->original_currency->short_code.''.$payment->original_amount.''.number_format(bcsub($payment->original_amount, $original_refunds, 7), 5, '.', '').''.$booking->service->name.''.$payment->updated_at->diffForHumans().'
'; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + + foreach ($approvedTransactions as $approvedTransaction) { + echo ''; + echo ''; + echo ''; + echo ''; + } + + echo ''; + echo '
BookingPayment Date
' . $approvedTransaction->owner->marking . '' . $approvedTransaction->created_at . '
'; + + $startDate = Carbon::createFromFormat('d-m-Y', $from_date)->startOfDay(); + $endDate = Carbon::createFromFormat('d-m-Y', $to_date)->endOfDay(); + + $approvalSatatusArray = ApprovalStatus::APPROVAL_STATUS_ID; + + echo '

Bills in the date range

'; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + + + $datas = Transaction::where('type', TransactionType::BILL)->whereBetween('created_at', [$startDate, $endDate])->get(); + + foreach ($datas as $data) { + echo ''; + $payment = $data->owner; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + } + + echo ''; + echo '
StatusBills Created AtBookingPayment Date
' . $approvalSatatusArray[$data['status']] . '' . $data->created_at . '' . $data->owner->owner->marking . '' . $payment->created_at . '
'; +}); From 937610272c3a8bf84b61227ac236acdc3cfb4d81 Mon Sep 17 00:00:00 2001 From: Omair Saleh Date: Wed, 27 Mar 2024 09:42:24 +0800 Subject: [PATCH 54/59] tidy up whiteform report --- routes/web.php | 33 +++++++++++++++++++++------------ 1 file changed, 21 insertions(+), 12 deletions(-) diff --git a/routes/web.php b/routes/web.php index d6798271..06e0dc67 100644 --- a/routes/web.php +++ b/routes/web.php @@ -882,14 +882,17 @@ Route::get('/invoice/{marking}/{started_at}/{ended_at}/fix', function($marking, Route::get('/show-white-form-transactions-in-date-range/{from_date}/{to_date}', function ($from_date, $to_date) { - $approvedTransactions = Transaction::where('type', TransactionType::PAYMENT)->where('status', ApprovalStatus::APPROVED)->where('owner_type', '!=', Wallet::class)->get(); - echo '

Approved Payments

'; + $approvedTransactions = Transaction::where('type', TransactionType::PAYMENT)->whereIn('status', [ApprovalStatus::PENDING_VERIFICATION, ApprovalStatus::APPROVED])->where('owner_type', '!=', Wallet::class)->orderBy('status')->get(); + + echo '

Pending Orders Payments

'; echo ''; echo ''; echo ''; echo ''; + echo ''; echo ''; + echo ''; echo ''; echo ''; echo ''; @@ -897,7 +900,9 @@ Route::get('/show-white-form-transactions-in-date-range/{from_date}/{to_date}', foreach ($approvedTransactions as $approvedTransaction) { echo ''; echo ''; + echo ''; echo ''; + echo ''; echo ''; } @@ -907,30 +912,34 @@ Route::get('/show-white-form-transactions-in-date-range/{from_date}/{to_date}', $startDate = Carbon::createFromFormat('d-m-Y', $from_date)->startOfDay(); $endDate = Carbon::createFromFormat('d-m-Y', $to_date)->endOfDay(); - $approvalSatatusArray = ApprovalStatus::APPROVAL_STATUS_ID; echo '

Bills in the date range

'; echo '
BookingAmountPayment DateStatus
' . $approvedTransaction->owner->marking . '' . $approvedTransaction->amount . '' . $approvedTransaction->created_at . '' . ApprovalStatus::APPROVAL_STATUS_ID[$approvedTransaction->status] . '
'; echo ''; echo ''; - echo ''; - echo ''; echo ''; - echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; echo ''; echo ''; echo ''; - $datas = Transaction::where('type', TransactionType::BILL)->whereBetween('created_at', [$startDate, $endDate])->get(); + $bills = Transaction::where('type', TransactionType::BILL)->whereBetween('created_at', [$startDate, $endDate])->get(); - foreach ($datas as $data) { + foreach ($bills as $bill) { echo ''; - $payment = $data->owner; - echo ''; - echo ''; - echo ''; + $payment = $bill->owner; + $po = $payment->owner->transaction()->where('type', TransactionType::PURCHASE_ORDER)->whereIn('status', [ApprovalStatus::PENDING_VERIFICATION, ApprovalStatus::APPROVED])->first(); + echo ''; echo ''; + echo ''; + echo ''; + echo ''; + echo ''; echo ''; } From 9a6e41ff3b17553aa838acf65cba7c57946c8d35 Mon Sep 17 00:00:00 2001 From: Omair Saleh Date: Wed, 27 Mar 2024 09:47:42 +0800 Subject: [PATCH 55/59] tidy up whiteform report --- routes/web.php | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/routes/web.php b/routes/web.php index 06e0dc67..246cb94b 100644 --- a/routes/web.php +++ b/routes/web.php @@ -900,7 +900,7 @@ Route::get('/show-white-form-transactions-in-date-range/{from_date}/{to_date}', foreach ($approvedTransactions as $approvedTransaction) { echo ''; echo ''; - echo ''; + echo ''; echo ''; echo ''; echo ''; @@ -918,8 +918,10 @@ Route::get('/show-white-form-transactions-in-date-range/{from_date}/{to_date}', echo ''; echo ''; echo ''; + echo ''; echo ''; echo ''; + echo ''; echo ''; echo ''; echo ''; @@ -933,10 +935,11 @@ Route::get('/show-white-form-transactions-in-date-range/{from_date}/{to_date}', foreach ($bills as $bill) { echo ''; $payment = $bill->owner; - $po = $payment->owner->transaction()->where('type', TransactionType::PURCHASE_ORDER)->whereIn('status', [ApprovalStatus::PENDING_VERIFICATION, ApprovalStatus::APPROVED])->first(); + $po = $payment->owner->transactions()->where('type', TransactionType::PURCHASE_ORDER)->whereIn('status', [ApprovalStatus::PENDING_VERIFICATION, ApprovalStatus::APPROVED])->first(); echo ''; echo ''; echo ''; + echo ''; echo ''; echo ''; echo ''; From baa8551b66aff21e8b3e4204ffdbaa255f66b59c Mon Sep 17 00:00:00 2001 From: Omair Saleh Date: Wed, 27 Mar 2024 09:54:58 +0800 Subject: [PATCH 56/59] tidy up whiteform report --- routes/web.php | 1 + 1 file changed, 1 insertion(+) diff --git a/routes/web.php b/routes/web.php index 246cb94b..ab187f16 100644 --- a/routes/web.php +++ b/routes/web.php @@ -936,6 +936,7 @@ Route::get('/show-white-form-transactions-in-date-range/{from_date}/{to_date}', echo ''; $payment = $bill->owner; $po = $payment->owner->transactions()->where('type', TransactionType::PURCHASE_ORDER)->whereIn('status', [ApprovalStatus::PENDING_VERIFICATION, ApprovalStatus::APPROVED])->first(); + var_dump($po); echo ''; echo ''; echo ''; From eb857937983887ad7ecc65c41137e863fe8372dc Mon Sep 17 00:00:00 2001 From: Omair Saleh Date: Wed, 27 Mar 2024 10:02:25 +0800 Subject: [PATCH 57/59] tidy up whiteform report --- routes/web.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/routes/web.php b/routes/web.php index ab187f16..d899f657 100644 --- a/routes/web.php +++ b/routes/web.php @@ -936,13 +936,12 @@ Route::get('/show-white-form-transactions-in-date-range/{from_date}/{to_date}', echo ''; $payment = $bill->owner; $po = $payment->owner->transactions()->where('type', TransactionType::PURCHASE_ORDER)->whereIn('status', [ApprovalStatus::PENDING_VERIFICATION, ApprovalStatus::APPROVED])->first(); - var_dump($po); echo ''; echo ''; echo ''; echo ''; echo ''; - echo ''; +// echo ''; echo ''; echo ''; } From b9765fbcf7e5b60652927a70d67b101236040391 Mon Sep 17 00:00:00 2001 From: Omair Saleh Date: Wed, 27 Mar 2024 10:03:26 +0800 Subject: [PATCH 58/59] tidy up whiteform report --- routes/web.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/routes/web.php b/routes/web.php index d899f657..6f4d12e7 100644 --- a/routes/web.php +++ b/routes/web.php @@ -941,8 +941,8 @@ Route::get('/show-white-form-transactions-in-date-range/{from_date}/{to_date}', echo ''; echo ''; echo ''; -// echo ''; - echo ''; + echo ''; + echo ''; echo ''; } From bb1cb6d44e4300ee253a28f486738d95a58cb0c1 Mon Sep 17 00:00:00 2001 From: Omair Saleh Date: Wed, 27 Mar 2024 10:11:02 +0800 Subject: [PATCH 59/59] tidy up whiteform report --- routes/web.php | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/routes/web.php b/routes/web.php index 6f4d12e7..1143c48c 100644 --- a/routes/web.php +++ b/routes/web.php @@ -901,7 +901,7 @@ Route::get('/show-white-form-transactions-in-date-range/{from_date}/{to_date}', echo ''; echo ''; echo ''; - echo ''; + echo ''; echo ''; echo ''; } @@ -937,12 +937,13 @@ Route::get('/show-white-form-transactions-in-date-range/{from_date}/{to_date}', $payment = $bill->owner; $po = $payment->owner->transactions()->where('type', TransactionType::PURCHASE_ORDER)->whereIn('status', [ApprovalStatus::PENDING_VERIFICATION, ApprovalStatus::APPROVED])->first(); echo ''; - echo ''; - echo ''; + echo ''; + echo ''; + echo ''; echo ''; - echo ''; - echo ''; - echo ''; + echo ''; + echo ''; + echo ''; echo ''; }
StatusBills Created AtBookingPayment DateCustomer payment dateWhite form dateUpload bank slip DatePO submit datePO approve date
' . $approvalSatatusArray[$data['status']] . '' . $data->created_at . '' . $data->owner->owner->marking . '' . $payment->owner->marking . '' . $payment->created_at . '' . $bill->created_at . '' . $bill->status === ApprovalStatus::APPROVED ? $bill->updated_at : 'Pending Upload' . '' . $po ? $po->updated_at : 'Pending Submission' . '' . $po ? ($po->status === ApprovalStatus::APPROVED ? $po->updated_at : '' ) : '' . '
' . $approvedTransaction->owner->marking . '' . $approvedTransaction->amount . '' . round($approvedTransaction->amount, 2) . '' . $approvedTransaction->created_at . '' . ApprovalStatus::APPROVAL_STATUS_ID[$approvedTransaction->status] . '
BookingAmountCustomer payment dateWhite form dateSupplierUpload bank slip DatePO submit datePO approve date
' . $payment->owner->marking . '' . $payment->created_at . '' . $bill->created_at . '' . $bill->issuerCompany->name . '' . $bill->status === ApprovalStatus::APPROVED ? $bill->updated_at : 'Pending Upload' . '' . $po ? $po->updated_at : 'Pending Submission' . '' . $po ? ($po->status === ApprovalStatus::APPROVED ? $po->updated_at : '' ) : '' . '
' . $payment->owner->marking . '' . $payment->created_at . '' . $bill->created_at . '
' . $payment->owner->marking . '' . $payment->created_at . '' . $bill->created_at . '' . $bill->issuerCompany->name . '' . $bill->status === ApprovalStatus::APPROVED ? $bill->updated_at : 'Pending Upload' . '' . $po ? $po->updated_at : 'Pending Submission' . '' . $po ? $po->updated_at : 'Pending Submission' . '' . $po ? ($po->status === ApprovalStatus::APPROVED ? $po->updated_at : '' ) : '' . '
' . $bill->created_at . '' . $bill->issuerCompany->name . '' . $bill->status === ApprovalStatus::APPROVED ? $bill->updated_at : 'Pending Upload' . '' . $po ? $po->updated_at : 'Pending Submission' . '' . $po ? ($po->status === ApprovalStatus::APPROVED ? $po->updated_at : '' ) : '' . '' . ($po ? $po->updated_at : 'Pending Submission') . '' . ($po ? ($po->status === ApprovalStatus::APPROVED ? $po->updated_at : '' ) : '' ). '
' . $approvedTransaction->owner->marking . '' . round($approvedTransaction->amount, 2) . '' . $approvedTransaction->created_at . '' . $approvedTransaction->created_at->format('d-m-Y h:i A') . '' . ApprovalStatus::APPROVAL_STATUS_ID[$approvedTransaction->status] . '
' . $payment->owner->marking . '' . $payment->created_at . '' . $bill->created_at . '' . round($payment->amount, 2) . '' . $payment->created_at->format('d-m-Y h:i A') . '' . $bill->created_at->format('d-m-Y h:i A') . '' . $bill->issuerCompany->name . '' . $bill->status === ApprovalStatus::APPROVED ? $bill->updated_at : 'Pending Upload' . '' . ($po ? $po->updated_at : 'Pending Submission') . '' . ($po ? ($po->status === ApprovalStatus::APPROVED ? $po->updated_at : '' ) : '' ). '' . ($bill->status === ApprovalStatus::APPROVED ? $bill->updated_at->format('d-m-Y h:i A') : 'Pending Upload') . '' . ($po ? $po->updated_at->format('d-m-Y h:i A') : 'Pending Submission') . '' . ($po ? ($po->status === ApprovalStatus::APPROVED ? $po->updated_at->format('d-m-Y h:i A') : '' ) : '' ). '