From 9f2b431f215c04c255b42b9edf546e634bf8607b Mon Sep 17 00:00:00 2001 From: edmondlang Date: Sat, 16 Sep 2023 14:38:02 +0800 Subject: [PATCH 01/24] regenerate-invoice-with-first-bill-no --- .../RegenerateInvoiceBookingLogic.php | 48 ++++++++++++++----- ...oiceTransactionWithInvoiceNoProcessor.php} | 2 +- routes/web.php | 4 +- 3 files changed, 40 insertions(+), 14 deletions(-) rename app/Classes/Modules/Transactions/Processors/{CreateInvoiceTransactionProcessorWithInvoiceNo.php => CreateInvoiceTransactionWithInvoiceNoProcessor.php} (99%) diff --git a/app/Classes/Modules/Bookings/ControllersLogic/RegenerateInvoiceBookingLogic.php b/app/Classes/Modules/Bookings/ControllersLogic/RegenerateInvoiceBookingLogic.php index 252412a2..6af18568 100644 --- a/app/Classes/Modules/Bookings/ControllersLogic/RegenerateInvoiceBookingLogic.php +++ b/app/Classes/Modules/Bookings/ControllersLogic/RegenerateInvoiceBookingLogic.php @@ -9,6 +9,7 @@ use App\Classes\Modules\Bookings\Services\UpdatesBookingStatus; use App\Classes\Modules\Transactions\Services\DeletesTransaction; use App\Classes\Modules\Documents\Services\DeletesDocument; use App\Classes\Modules\Transactions\Processors\CreateInvoiceTransactionProcessor; +use App\Classes\Modules\Transactions\Processors\CreateInvoiceTransactionWithInvoiceNoProcessor; use App\Classes\ValueObjects\Constants\DocumentType; use App\Http\Resources\BookingResource; @@ -16,6 +17,7 @@ use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use App\Classes\ValueObjects\Constants\ApprovalStatus; use App\Classes\ValueObjects\Constants\TransactionType; +use Illuminate\Support\Carbon; class RegenerateInvoiceBookingLogic extends AbstractControllerLogic { @@ -23,7 +25,8 @@ class RegenerateInvoiceBookingLogic extends AbstractControllerLogic /** * @return array */ - protected function notification():array { + protected function notification(): array + { return [ 'title' => 'Regenerate Booking Invoice', 'message' => 'You have successfully regenerate booking invoice' @@ -48,6 +51,9 @@ class RegenerateInvoiceBookingLogic extends AbstractControllerLogic /** @var CreateInvoiceTransactionProcessor */ private $createInvoiceTransactionProcessor; + /** @var CreateInvoiceTransactionWithInvoiceNoProcessor */ + private $createInvoiceTransactionWithInvoiceNoProcessor; + /** * FetchBookingLogic constructor. * @param CanFetchBooking $canFetchBooking @@ -56,6 +62,7 @@ class RegenerateInvoiceBookingLogic extends AbstractControllerLogic * @param UpdatesBookingStatus $updatesBookingStatus * @param DeletesDocument $deletesDocument * @param CreateInvoiceTransactionProcessor $createInvoiceTransactionProcessor + * @param CreateInvoiceTransactionWithInvoiceNoProcessor $createInvoiceTransactionWithInvoiceNoProcessor */ public function __construct( CanFetchBooking $canFetchBooking, @@ -63,15 +70,16 @@ class RegenerateInvoiceBookingLogic extends AbstractControllerLogic DeletesTransaction $deletesTransaction, UpdatesBookingStatus $updatesBookingStatus, DeletesDocument $deletesDocument, - CreateInvoiceTransactionProcessor $createInvoiceTransactionProcessor - ) - { + CreateInvoiceTransactionProcessor $createInvoiceTransactionProcessor, + CreateInvoiceTransactionWithInvoiceNoProcessor $createInvoiceTransactionWithInvoiceNoProcessor + ) { $this->canFetchBooking = $canFetchBooking; $this->fetchesBooking = $fetchesBooking; $this->deletesTransaction = $deletesTransaction; $this->updatesBookingStatus = $updatesBookingStatus; $this->deletesDocument = $deletesDocument; $this->createInvoiceTransactionProcessor = $createInvoiceTransactionProcessor; + $this->createInvoiceTransactionWithInvoiceNoProcessor = $createInvoiceTransactionWithInvoiceNoProcessor; } @@ -82,18 +90,37 @@ class RegenerateInvoiceBookingLogic extends AbstractControllerLogic * @throws \App\Classes\Exceptions\MalformedRequestException * @throws \App\Classes\Exceptions\RequestValidationException */ - public function logic(Request $request) : JsonResponse + public function logic(Request $request): JsonResponse { $this->canFetchBooking->passes(); - $booking = $this->fetchesBooking->execute([ - 'id' => $request->route('id'), - 'status' => ApprovalStatus::COMPLETED, - 'with_transactions' => true] + $booking = $this->fetchesBooking->execute( + [ + 'id' => $request->route('id'), + 'status' => ApprovalStatus::COMPLETED, + 'with_transactions' => true + ] ); $this->updatesBookingStatus->execute($booking, ApprovalStatus::APPROVED); + $firstInvoice = $booking->transactions() + ->whereIn('type', [TransactionType::INVOICE]) + ->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-" . (string)(Carbon::now()->timestamp); + $currentInvoice->save(); + $transaction = $booking->transactions()->whereIn('type', [TransactionType::INVOICE, TransactionType::SUPPLIER_DELIVER])->get(); foreach ($transaction as $key => $row) { $this->deletesTransaction->execute($row); @@ -104,9 +131,8 @@ class RegenerateInvoiceBookingLogic extends AbstractControllerLogic $this->deletesDocument->execute($row); } - $this->createInvoiceTransactionProcessor->execute($booking); + $this->createInvoiceTransactionWithInvoiceNoProcessor->execute($booking, $firstBillNo); return $this->resourceResponse(new BookingResource($booking)); } - } diff --git a/app/Classes/Modules/Transactions/Processors/CreateInvoiceTransactionProcessorWithInvoiceNo.php b/app/Classes/Modules/Transactions/Processors/CreateInvoiceTransactionWithInvoiceNoProcessor.php similarity index 99% rename from app/Classes/Modules/Transactions/Processors/CreateInvoiceTransactionProcessorWithInvoiceNo.php rename to app/Classes/Modules/Transactions/Processors/CreateInvoiceTransactionWithInvoiceNoProcessor.php index 27dfbe59..612033f8 100644 --- a/app/Classes/Modules/Transactions/Processors/CreateInvoiceTransactionProcessorWithInvoiceNo.php +++ b/app/Classes/Modules/Transactions/Processors/CreateInvoiceTransactionWithInvoiceNoProcessor.php @@ -21,7 +21,7 @@ use App\Classes\ValueObjects\Constants\DocumentType; use App\Models\Booking; use App\Models\SegmentConstant; -class CreateInvoiceTransactionProcessorWithInvoiceNo +class CreateInvoiceTransactionWithInvoiceNoProcessor { /** @var CreatesTransaction */ diff --git a/routes/web.php b/routes/web.php index e2357c00..d75c96b0 100644 --- a/routes/web.php +++ b/routes/web.php @@ -26,7 +26,7 @@ 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\Documents\Services\DeletesDocument; -use App\Classes\Modules\Transactions\Processors\CreateInvoiceTransactionProcessorWithInvoiceNo; +use App\Classes\Modules\Transactions\Processors\CreateInvoiceTransactionWithInvoiceNoProcessor; use App\Classes\Modules\Transactions\Services\DeletesTransaction; use Illuminate\Support\Facades\Log; @@ -541,7 +541,7 @@ Route::get('/invoice/fix', function(){ $existing_invoice_bill_no->forceDelete(); } - (App()->make(CreateInvoiceTransactionProcessorWithInvoiceNo::class))->execute($booking, $bill_no); + (App()->make(CreateInvoiceTransactionWithInvoiceNoProcessor::class))->execute($booking, $bill_no); dump('regenerated invoice. Booking Marking - ' . $booking->marking . '. Bill_no - ' . $bill_no . '. Old bill_no - ' . $deletedInvoice->bill_no); Log::channel('regenerateInvoice')->info('regenerated invoice. Booking Marking - ' . $booking->marking . '. Bill_no - ' . $bill_no . '. Old bill_no - ' . $deletedInvoice->bill_no); } else { From 05b5823fe4d9c579bbd84440865a0efb35c67b92 Mon Sep 17 00:00:00 2001 From: Steve Ng Date: Mon, 23 Oct 2023 09:20:35 +0800 Subject: [PATCH 02/24] fixing unable mapping records and filtering function in Pending Export tab and listing data not same in Pending Export tab with export Invoice to autocount and calculate mapped percentage --- .../StatementTransactionPostingEnd.php | 18 +++++ .../StatementTransactionPostingStart.php | 18 +++++ ...ankStatementTransactionOwnersProcessor.php | 49 +++++++------ .../Services/ExportsInvoiceTransactions.php | 27 +++---- app/Models/AccountStatement.php | 2 + ...apped_rate_to_account_statements_table.php | 34 +++++++++ .../StatementTransactionComponent.vue | 2 +- .../sections/TransactionsMappingComponent.vue | 71 +++++++++++++++++-- 8 files changed, 182 insertions(+), 39 deletions(-) create mode 100644 app/Classes/General/Eloquent/Filters/StatementTransactionPostingEnd.php create mode 100644 app/Classes/General/Eloquent/Filters/StatementTransactionPostingStart.php create mode 100644 database/migrations/2023_10_22_140339_add_mapped_rate_to_account_statements_table.php diff --git a/app/Classes/General/Eloquent/Filters/StatementTransactionPostingEnd.php b/app/Classes/General/Eloquent/Filters/StatementTransactionPostingEnd.php new file mode 100644 index 00000000..e837245e --- /dev/null +++ b/app/Classes/General/Eloquent/Filters/StatementTransactionPostingEnd.php @@ -0,0 +1,18 @@ +whereDate('posting_date', '<=', date('Y-m-d',strtotime($value))); + } +} \ No newline at end of file diff --git a/app/Classes/General/Eloquent/Filters/StatementTransactionPostingStart.php b/app/Classes/General/Eloquent/Filters/StatementTransactionPostingStart.php new file mode 100644 index 00000000..c3560357 --- /dev/null +++ b/app/Classes/General/Eloquent/Filters/StatementTransactionPostingStart.php @@ -0,0 +1,18 @@ +whereDate('posting_date', '>=', date('Y-m-d',strtotime($value))); + } +} \ No newline at end of file diff --git a/app/Classes/Modules/Accounting/Processors/CreateBankStatementTransactionOwnersProcessor.php b/app/Classes/Modules/Accounting/Processors/CreateBankStatementTransactionOwnersProcessor.php index 36fc684a..6f7efe5e 100644 --- a/app/Classes/Modules/Accounting/Processors/CreateBankStatementTransactionOwnersProcessor.php +++ b/app/Classes/Modules/Accounting/Processors/CreateBankStatementTransactionOwnersProcessor.php @@ -28,6 +28,7 @@ class CreateBankStatementTransactionOwnersProcessor // $transactions = StatementTransaction::whereDoesntHave('owners')->where('amount', '<', 0)->get(); foreach ($transactions as $transaction) { + $mapped = false; $keywords = array_filter(explode(" ", $transaction->transaction_description . " " . $transaction->transaction_description_2)); if($transaction->amount > 0){ @@ -36,7 +37,7 @@ class CreateBankStatementTransactionOwnersProcessor $creditTransactions = $this->getTransactions($transaction->posting_date, $transaction->amount, TransactionType::PAYMENT, Booking::class, PaymentMethodType::WALLET, [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED], $keywords); foreach ($creditTransactions as $creditTransaction) { $isArray = is_array($creditTransaction); - $transaction->owners()->firstOrCreate([ + $data = $transaction->owners()->firstOrCreate([ 'type' => StatementTransactionOwnerType::SALES, 'system' => 'EXCHANGE', 'owner_type' => Transaction::class, @@ -45,12 +46,11 @@ class CreateBankStatementTransactionOwnersProcessor ]); } - // Shipping Portal Sales - $creditTransactions = $this->getTransactionsFromShippingPortal($transaction->amount, $this->getDateRange($transaction->posting_date, 1), 2, PaymentMethodType::WALLET); + $creditTransactions = $this->getTransactionsFromShippingPortal($transaction->amount, $this->getDateRange($transaction->posting_date, 1), [2], PaymentMethodType::WALLET); foreach ($creditTransactions as $creditTransaction) { if($creditTransaction['owner_type'] === Wallet::class) continue; - $transaction->owners()->firstOrCreate([ + $data = $transaction->owners()->firstOrCreate([ 'type' => StatementTransactionOwnerType::SALES, 'system' => 'SHIPPING_PORTAL', 'owner_type' => $creditTransaction['owner_type'], @@ -63,7 +63,7 @@ class CreateBankStatementTransactionOwnersProcessor $creditTransactions = $this->getTransactions($transaction->posting_date, $transaction->amount, TransactionType::TOP_UP, Wallet::class, null, [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED], $keywords); foreach ($creditTransactions as $creditTransaction) { $isArray = is_array($creditTransaction); - $transaction->owners()->firstOrCreate([ + $data = $transaction->owners()->firstOrCreate([ 'type' => StatementTransactionOwnerType::WALLET_TOP_UP, 'system' => 'EXCHANGE', 'owner_type' => Transaction::class, @@ -72,9 +72,9 @@ class CreateBankStatementTransactionOwnersProcessor ]); } - $creditTransactions = $this->getTransactionsFromShippingPortal($transaction->amount, $this->getDateRange($transaction->posting_date, 1), 5, null); + $creditTransactions = $this->getTransactionsFromShippingPortal($transaction->amount, $this->getDateRange($transaction->posting_date, 1), [5,15], null); foreach ($creditTransactions as $creditTransaction) { - $transaction->owners()->firstOrCreate([ + $data = $transaction->owners()->firstOrCreate([ 'type' => StatementTransactionOwnerType::WALLET_TOP_UP, 'system' => 'SHIPPING_PORTAL', 'owner_type' => $creditTransaction['owner_type'], @@ -85,7 +85,7 @@ class CreateBankStatementTransactionOwnersProcessor // fpx charge refund if($transaction->transaction_description === 'DUITNOW S/CHRG REFUND'){ - $transaction->owners()->firstOrCreate([ + $data = $transaction->owners()->firstOrCreate([ 'type' => StatementTransactionOwnerType::FPX_CHARGE_REFUND ]); } @@ -94,7 +94,7 @@ class CreateBankStatementTransactionOwnersProcessor // INTERNAL_BANK_TRANSFER_IN if(str_contains($transaction->transaction_description_2, 'CIEF WORLDWIDE')){ - $transaction->owners()->firstOrCreate([ + $data = $transaction->owners()->firstOrCreate([ 'type' => StatementTransactionOwnerType::INTERNAL_BANK_TRANSFER_IN ]); } @@ -119,7 +119,7 @@ class CreateBankStatementTransactionOwnersProcessor ->where('amount', '<=', (($transaction->amount * -1) + 0.01))->whereDate('created_at', '>=', $paymentDateStart)->whereDate('created_at', '<=', $paymentDateEnd)->get(); foreach ($debitTransactions as $debitTransaction) { - $transaction->owners()->firstOrCreate([ + $data = $transaction->owners()->firstOrCreate([ 'type' => StatementTransactionOwnerType::SUPPLIER_PAYMENT, 'system' => 'EXCHANGE', 'owner_type' => Group::class, @@ -135,7 +135,7 @@ class CreateBankStatementTransactionOwnersProcessor $debitTransactions = $this->getTransactions($transaction->posting_date, $transaction->amount, TransactionType::DEBIT_NOTE, Wallet::class, null, [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED], $keywords); foreach ($debitTransactions as $debitTransaction) { $isArray = is_array($creditTransaction); - $transaction->owners()->firstOrCreate([ + $data = $transaction->owners()->firstOrCreate([ 'type' => StatementTransactionOwnerType::WALLET_WITHDRAWAL, 'system' => 'EXCHANGE', 'owner_type' => Transaction::class, @@ -148,50 +148,52 @@ class CreateBankStatementTransactionOwnersProcessor // STATUTORY if(str_contains($transaction->transaction_description_2, 'PEMBANGUNAN SUMBER') || str_contains($transaction->transaction_description_2, 'HASIL') || str_contains($transaction->transaction_description_2, 'PERTUBUHAN KESELAMAT') || str_contains($transaction->transaction_description_2, 'KUMPULAN WANG SIMPAN')){ - $transaction->owners()->firstOrCreate([ + $data = $transaction->owners()->firstOrCreate([ 'type' => StatementTransactionOwnerType::STATUTORY ]); } // FPX_CHARGE if($transaction->transaction_description === 'DR DUITNOW S/CHRG' || str_contains($transaction->transaction_description, 'Manual FPX') || str_contains($transaction->transaction_description, 'CMS - DR FPX CHG')){ - $transaction->owners()->firstOrCreate([ + $data = $transaction->owners()->firstOrCreate([ 'type' => StatementTransactionOwnerType::FPX_CHARGE ]); } // BANK_CHARGE if($transaction->transaction_description === 'CMS - DR CORP CHG' || $transaction->transaction_description === 'MONTHLY PROFIT DEBIT'){ - $transaction->owners()->firstOrCreate([ + $data = $transaction->owners()->firstOrCreate([ 'type' => StatementTransactionOwnerType::BANK_CHARGE ]); } // CREDIT_CARD_PAYMENT if(str_contains($transaction->transaction_description_2, 'VISA CARD')){ - $transaction->owners()->firstOrCreate([ + $data = $transaction->owners()->firstOrCreate([ 'type' => StatementTransactionOwnerType::CREDIT_CARD_PAYMENT ]); } // INTERNAL_BANK_TRANSFER_OUT if(str_contains($transaction->transaction_description_2, 'CIEF WORLDWIDE') || str_contains($transaction->transaction_description_2, 'CIEF WORLWIDE') || str_contains($transaction->transaction_description_2, 'IZYIM GLOBAL')){ - $transaction->owners()->firstOrCreate([ + $data = $transaction->owners()->firstOrCreate([ 'type' => StatementTransactionOwnerType::INTERNAL_BANK_TRANSFER_OUT ]); } // non-operational charges if(str_contains($transaction->transaction_description_2, 'HIRE PURCHASE') || str_contains($transaction->transaction_description_2, 'TENAGA NASIONAL') || str_contains($transaction->transaction_description, 'CABLE CHARGE') || str_contains($transaction->transaction_description_2, 'CTOS DATA SYSTEMS') || str_contains($transaction->transaction_description_2, 'MAXIS')){ - $transaction->owners()->firstOrCreate([ + $data = $transaction->owners()->firstOrCreate([ 'type' => StatementTransactionOwnerType::NON_OPERATIONAL ]); } } + if (isset($data) && $data->wasRecentlyCreated) $mapped = true; + $this->updateMappedRate($transaction, $mapped); } - } + } - private function getTransactions($date, $amount, $type, $ownerType, $paymentMethod, $statuses, $keywords, $model = Transaction::class) { + private function getTransactions($date, $amount, $type, $ownerType, $paymentMethod, $statuses, $keywords, $model = Transaction::class) { $dateRange = $this->getDateRange($date, 4); if (App::environment(['production'])) { $query = $model::whereIn('status', $statuses) @@ -318,7 +320,7 @@ class CreateBankStatementTransactionOwnersProcessor try{ $client = new \GuzzleHttp\Client(['verify' => false]); - $response = $client->request('GET', $url.'?api-key=510acd13d8d24375cf038ad626c282565451461a9c2399357e0b65365300787e&filters={"order_by":{"column":"id","DESC":true},"status_in":[2]'.$paymentMethodFilter.',"created_after":"'.$dateRange['start_date'].'","created_before":"'.$dateRange['end_date'].'","amount_exceed":'.($amount - 0.01).',"amount_short":'.($amount + 0.01).',"type_in":['.$type.']}'); + $response = $client->request('GET', $url.'?api-key=510acd13d8d24375cf038ad626c282565451461a9c2399357e0b65365300787e&filters={"order_by":{"column":"id","DESC":true},"status_in":[2]'.$paymentMethodFilter.',"created_after":"'.$dateRange['start_date'].'","created_before":"'.$dateRange['end_date'].'","amount_exceed":'.($amount - 0.01).',"amount_short":'.($amount + 0.01).',"type_in":'.json_encode($type).'}'); $body = $response->getBody(); $data = json_decode($body, true); $payload = $data['payload']; @@ -345,4 +347,11 @@ class CreateBankStatementTransactionOwnersProcessor 'end_date' => $nextDay, ]; } + + private function updateMappedRate($transaction, $mapped) { + $statement = $transaction->statement; + $statement->total_rows = StatementTransaction::where('account_statement_id',$transaction->account_statement_id)->count(); + $statement->mapped_rows = $mapped ? $statement->mapped_rows+1 : $statement->mapped_rows; + $statement->save(); + } } diff --git a/app/Classes/Modules/Exports/Services/ExportsInvoiceTransactions.php b/app/Classes/Modules/Exports/Services/ExportsInvoiceTransactions.php index 79ca4380..2ecaada8 100644 --- a/app/Classes/Modules/Exports/Services/ExportsInvoiceTransactions.php +++ b/app/Classes/Modules/Exports/Services/ExportsInvoiceTransactions.php @@ -4,7 +4,6 @@ namespace App\Classes\Modules\Exports\Services; use App\Classes\ValueObjects\Constants\ApprovalStatus; use App\Classes\ValueObjects\Constants\StatementTransactionOwnerType; -use App\Models\StatementTransactionOwner; use App\Models\Transaction; use Maatwebsite\Excel\Concerns\Exportable; use Maatwebsite\Excel\Concerns\FromQuery; @@ -18,6 +17,8 @@ use App\Classes\Modules\Accounting\Processors\ListShippingPortalTransactions; use App\Classes\ValueObjects\Constants\ShippingTransactionType; use App\Classes\ValueObjects\Constants\TransactionType; use Illuminate\Support\Facades\Log; +use App\Classes\General\Eloquent\ApplyFiltersToQuery; +use App\Models\StatementTransaction; class ExportsInvoiceTransactions implements FromQuery, WithHeadings, WithHeadingRow, WithMapping, ShouldAutoSize { @@ -64,10 +65,9 @@ class ExportsInvoiceTransactions implements FromQuery, WithHeadings, WithHeading */ public function query() { - $data = StatementTransactionOwner::whereNull('invoice_reference') - ->whereIn('type', [StatementTransactionOwnerType::SALES, StatementTransactionOwnerType::WALLET_TOP_UP]) - ->whereIn('status', [ApprovalStatus::COMPLETED, ApprovalStatus::APPROVED]); - if ($this->request->has('bankStatementOwnerId')) $data = $data->whereIn('id',json_decode($this->request->input('bankStatementOwnerId'))); + $data = (new ApplyFiltersToQuery())->execute(StatementTransaction::query(), json_decode($this->request->input('filter'), true)); + if ($this->request->has('bankStatementTransactionId')) $data = $data->whereIn('id',json_decode($this->request->input('bankStatementTransactionId'), true)); + return $data; } @@ -78,11 +78,12 @@ class ExportsInvoiceTransactions implements FromQuery, WithHeadings, WithHeading */ public function map($transaction): array { + $statementTransactionOwner = $transaction->owners()->whereIn('status', [ApprovalStatus::APPROVED])->first(); $logArray = [ 'counter' => $this->counter, - 'system' => $transaction->system, - 'StatementTransactionOwner_id' => $transaction->id, - 'transaction_table_id' => $transaction->owner_id, + 'system' => $statementTransactionOwner->system, + 'StatementTransactionOwner_id' => $statementTransactionOwner->id, + 'transaction_table_id' => $statementTransactionOwner->owner_id, ]; $this->counter += 1; $logArray = json_encode($logArray); @@ -92,8 +93,8 @@ class ExportsInvoiceTransactions implements FromQuery, WithHeadings, WithHeading $textToAppend = Carbon::now()->format('[Y-m-d H:i:s]') . ' ' . $logArray . PHP_EOL; file_put_contents($filePath, $textToAppend, FILE_APPEND); - if ($transaction->system == 'EXCHANGE') { - $row = (App()->make($transaction->owner_type))->where('id', $transaction->owner_id)->first(); + if ($statementTransactionOwner->system == 'EXCHANGE') { + $row = (App()->make($statementTransactionOwner->owner_type))->where('id', $statementTransactionOwner->owner_id)->first(); $company = $row->type === TransactionType::PAYMENT ? $row->owner->company : $row->owner->owner; $booking = $row->owner; @@ -116,15 +117,15 @@ class ExportsInvoiceTransactions implements FromQuery, WithHeadings, WithHeading ]; } else { $row = (App()->make(ListShippingPortalTransactions::class))->execute([ - 'id' => $transaction->owner_id, + 'id' => $statementTransactionOwner->owner_id, 'with_company' => true, ]); if (empty($row) || $row[0]['status'] != 'success') { $textToAppend = Carbon::now()->format('[Y-m-d H:i:s]') . ' Fetch Shipping Transaction Fail ' . json_encode([ - 'id' => $transaction->owner_id, + 'id' => $statementTransactionOwner->owner_id, 'with_company' => true, - 'StatementTransactionOwner_id' => $transaction->id, + 'StatementTransactionOwner_id' => $statementTransactionOwner->id, ]) . PHP_EOL; file_put_contents($errorFilePath, $textToAppend, FILE_APPEND); diff --git a/app/Models/AccountStatement.php b/app/Models/AccountStatement.php index d9e53d60..2f5b0e8c 100644 --- a/app/Models/AccountStatement.php +++ b/app/Models/AccountStatement.php @@ -16,6 +16,8 @@ class AccountStatement extends Model 'total_amount', 'begin_balance', 'end_balance', + 'total_rows', + 'mapped_rows', ]; protected $casts = [ diff --git a/database/migrations/2023_10_22_140339_add_mapped_rate_to_account_statements_table.php b/database/migrations/2023_10_22_140339_add_mapped_rate_to_account_statements_table.php new file mode 100644 index 00000000..f6a8e7e7 --- /dev/null +++ b/database/migrations/2023_10_22_140339_add_mapped_rate_to_account_statements_table.php @@ -0,0 +1,34 @@ +integer('total_rows')->unsigned()->default(0)->after('end_balance'); + $table->integer('mapped_rows')->unsigned()->default(0)->after('end_balance'); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::table('account_statements', function (Blueprint $table) { + $table->dropColumn('total_rows'); + $table->dropColumn('mapped_rows'); + }); + } +} diff --git a/resources/assets/vue/components/accounting/elements/StatementTransactionComponent.vue b/resources/assets/vue/components/accounting/elements/StatementTransactionComponent.vue index 1caef408..b09b9a56 100644 --- a/resources/assets/vue/components/accounting/elements/StatementTransactionComponent.vue +++ b/resources/assets/vue/components/accounting/elements/StatementTransactionComponent.vue @@ -126,7 +126,7 @@
- +
Pending...
diff --git a/resources/assets/vue/components/accounting/sections/TransactionsMappingComponent.vue b/resources/assets/vue/components/accounting/sections/TransactionsMappingComponent.vue index 9d74dce1..4604f2e5 100644 --- a/resources/assets/vue/components/accounting/sections/TransactionsMappingComponent.vue +++ b/resources/assets/vue/components/accounting/sections/TransactionsMappingComponent.vue @@ -74,6 +74,32 @@ + + +
+
+
+ + + + +
+
+ + + + +
+
+
+ + Search + +
+
+
+
+
@@ -202,6 +228,10 @@ export default { data(){ return { + parameters: { + startDate: '', + endDate: '', + }, type: null, stage: null, exportStage: 0, @@ -215,6 +245,14 @@ export default { } }, validations: { + parameters: { + startDate: { + required + }, + endDate: { + required + }, + }, files: { // required // todo-new: set required if is pdf section } @@ -227,17 +265,31 @@ export default { this.mappedTrue = true; }, exportInvoiceToAutoCount(){ - window.open(this.route('invoiceTransactions.export')+'?bankStatementOwnerId='+this.getCheckedStatementOwners()+'&type=invoices', '_blank'); + const checkedStatementTransactions = this.getCheckedStatementOwners(); + + let route = this.route('invoiceTransactions.export')+'?type=invoices&filter='+JSON.stringify(this.filter); + if (checkedStatementTransactions) { + route += '&bankStatementTransactionId='+checkedStatementTransactions; + } + + window.open(route, '_blank'); }, exportReceiptToAutoCount(){ - window.open(this.route('invoiceTransactions.export')+'?bankStatementOwnerId='+this.getCheckedStatementOwners()+'&type=receipts', '_blank'); + const checkedStatementTransactions = this.getCheckedStatementOwners(); + + let route = this.route('invoiceTransactions.export')+'?type=receipts&filter='+JSON.stringify(this.filter); + if (checkedStatementTransactions) { + route += '&bankStatementTransactionId='+checkedStatementTransactions; + } + + window.open(route, '_blank'); }, getCheckedStatementOwners() { - let bankStatementOwnerId = []; + let bankStatementTransactionId = []; $('.request_export_item:checked').each(function() { - bankStatementOwnerId.push($(this).val()); + bankStatementTransactionId.push($(this).val()); }); - return JSON.stringify(bankStatementOwnerId); + return (bankStatementTransactionId.length > 0 ? JSON.stringify(bankStatementTransactionId) : null); }, successHandler(){ this.step += 1; @@ -263,6 +315,10 @@ export default { break; case 4: this.filter = {min_amount: 0, is_mapped: true, statement_transaction_owner_type_in: [1, 2], statement_transaction_owner_status_in: [2], per_page: 100, order_by: {column: 'posting_date', DESC: true}} + + if (typeof this.parameters.startDate != 'undefined' && this.parameters.startDate != '') this.filter = {...this.filter, ...{statement_transaction_posting_start: this.parameters.startDate}}; + + if (typeof this.parameters.endDate != 'undefined' && this.parameters.endDate != '') this.filter = {...this.filter, ...{statement_transaction_posting_end:this.parameters.endDate}}; break; } } @@ -280,6 +336,11 @@ export default { break; case 4: this.filter = {max_amount: 0, is_mapped: true, statement_transaction_owner_type_in: [3, 5], statement_transaction_owner_status_in: [2], per_page: 100, order_by: {column: 'posting_date', DESC: true}} + + if (typeof this.parameters.startDate != 'undefined' && this.parameters.startDate != '') this.filter = {...this.filter, ...{statement_transaction_posting_start: this.parameters.startDate}}; + + if (typeof this.parameters.endDate != 'undefined' && this.parameters.endDate != '') this.filter = {...this.filter, ...{statement_transaction_posting_end:this.parameters.endDate}}; + break; } } From bc5a8a91939e3b992a20ff0bb61069ba505bebd4 Mon Sep 17 00:00:00 2001 From: Steve Ng Date: Tue, 24 Oct 2023 21:21:51 +0800 Subject: [PATCH 03/24] fix bug in function import invoices --- .../Imports/ImportStatementInvoiceController.php | 10 ++-------- app/Models/StatementTransactionOwner.php | 1 + app/Models/Transaction.php | 16 ++++++++++++++++ 3 files changed, 19 insertions(+), 8 deletions(-) diff --git a/app/Http/Controllers/Imports/ImportStatementInvoiceController.php b/app/Http/Controllers/Imports/ImportStatementInvoiceController.php index 7ea3454e..73e58e87 100644 --- a/app/Http/Controllers/Imports/ImportStatementInvoiceController.php +++ b/app/Http/Controllers/Imports/ImportStatementInvoiceController.php @@ -137,16 +137,10 @@ class ImportStatementInvoiceController private function mappingExchange(Array $row) { $date = $row['date']; - $transactions = Transaction::where('original_amount', $row['net_total'])->whereRaw("DATE(created_at) = '$date'") - ->whereHas('receiverCompany', function($q) use($row) { - $q->where('debtor',$row['debtor_code']); - })->get(); + $transactions = Transaction::getReceiverWithJoinStatementTransactionAndOwner($row)->select('transactions.*')->where('statement_transactions.amount', $row['net_total'])->whereRaw("DATE(posting_date) = '$date'")->get(); if ($transactions && $transactions->count() == 0) { - $transactions = Transaction::where(DB::raw('FLOOR(original_amount)'), floor($row['net_total']))->whereRaw("DATE(created_at) = '$date'") - ->whereHas('receiverCompany', function($q) use($row) { - $q->where('debtor',$row['debtor_code']); - })->get(); + $transactions = Transaction::getReceiverWithJoinStatementTransactionAndOwner($row)->select('transactions.*')->where(DB::raw('FLOOR(statement_transactions.amount)'), floor($row['net_total']))->whereRaw("DATE(posting_date) = '$date'")->get(); } if ($transactions && $transactions->count() == 1) { diff --git a/app/Models/StatementTransactionOwner.php b/app/Models/StatementTransactionOwner.php index fb13f4b4..bd96efff 100644 --- a/app/Models/StatementTransactionOwner.php +++ b/app/Models/StatementTransactionOwner.php @@ -5,6 +5,7 @@ namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; +use Illuminate\Database\Eloquent\Relations\MorphTo; class StatementTransactionOwner extends Model { diff --git a/app/Models/Transaction.php b/app/Models/Transaction.php index 631a5fa5..185fdb36 100644 --- a/app/Models/Transaction.php +++ b/app/Models/Transaction.php @@ -221,6 +221,22 @@ class Transaction extends AbstractModel implements Documentable, Transactionable return $query->whereIn('status', [ApprovalStatus::APPROVED]); } + /** + * @param Builder $query + * @return Builder + */ + public function scopeGetReceiverWithJoinStatementTransactionAndOwner(Builder $query, Array $row) { + $query->join('companies',function($q) use ($row) { + $q->on('companies.id','=','transactions.receiver'); + $q->where('debtor',$row['debtor_code']); + }) + ->join('statement_transaction_owners', function ($q) { + $q->on('statement_transaction_owners.owner_id','=','transactions.id'); + $q->where('statement_transaction_owners.owner_type','=',Transaction::class); + }) + ->join('statement_transactions','statement_transactions.id','=','statement_transaction_owners.statement_transaction_id'); + } + /** * @return MorphMany */ From 910f190075c82c4e2467abab2318e6236f1365cd Mon Sep 17 00:00:00 2001 From: Steve Ng Date: Wed, 25 Oct 2023 18:03:31 +0800 Subject: [PATCH 04/24] fixing the unknown tab to list the transactions of is_mapped false and also mapped and status in rejected --- .../IsMappedFalseOrMappedButStatusIn.php | 25 +++++++++++++++++++ .../sections/TransactionsMappingComponent.vue | 2 +- 2 files changed, 26 insertions(+), 1 deletion(-) create mode 100644 app/Classes/General/Eloquent/Filters/IsMappedFalseOrMappedButStatusIn.php diff --git a/app/Classes/General/Eloquent/Filters/IsMappedFalseOrMappedButStatusIn.php b/app/Classes/General/Eloquent/Filters/IsMappedFalseOrMappedButStatusIn.php new file mode 100644 index 00000000..8b264ff5 --- /dev/null +++ b/app/Classes/General/Eloquent/Filters/IsMappedFalseOrMappedButStatusIn.php @@ -0,0 +1,25 @@ +where(function($q) use ($value) { + $q->whereDoesntHave('owners'); + $q->orwhereHas('owners', function($query) use ($value) { + $query->whereIn('status', $value); + }); + }); + } + +} diff --git a/resources/assets/vue/components/accounting/sections/TransactionsMappingComponent.vue b/resources/assets/vue/components/accounting/sections/TransactionsMappingComponent.vue index 4604f2e5..160221bf 100644 --- a/resources/assets/vue/components/accounting/sections/TransactionsMappingComponent.vue +++ b/resources/assets/vue/components/accounting/sections/TransactionsMappingComponent.vue @@ -311,7 +311,7 @@ export default { this.filter = {min_amount: 0, is_mapped: true, is_mapped_with_multiple: true, statement_transaction_owner_type_in: [1, 2], statement_transaction_owner_status_in: [1], per_page: 100, order_by: {column: 'posting_date', DESC: true}} break; case 3: - this.filter = {min_amount: 0, is_mapped: false, per_page: 100, order_by: {column: 'posting_date', DESC: true}} + this.filter = {min_amount: 0, is_mapped_false_or_mapped_but_status_in: [4], per_page: 100, order_by: {column: 'posting_date', DESC: true}} break; case 4: this.filter = {min_amount: 0, is_mapped: true, statement_transaction_owner_type_in: [1, 2], statement_transaction_owner_status_in: [2], per_page: 100, order_by: {column: 'posting_date', DESC: true}} From f47c3c9ecc1e4cfdb81121c85759d88a8ae80431 Mon Sep 17 00:00:00 2001 From: Steve Ng Date: Thu, 26 Oct 2023 00:01:10 +0800 Subject: [PATCH 05/24] fixing the unknown tab to list the transactions of is_mapped false and also mapped and status in rejected --- .../Eloquent/Filters/IsMappedFalseOrMappedButStatusIn.php | 4 +--- app/Models/StatementTransaction.php | 5 +++++ 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/app/Classes/General/Eloquent/Filters/IsMappedFalseOrMappedButStatusIn.php b/app/Classes/General/Eloquent/Filters/IsMappedFalseOrMappedButStatusIn.php index 8b264ff5..c0eb9e74 100644 --- a/app/Classes/General/Eloquent/Filters/IsMappedFalseOrMappedButStatusIn.php +++ b/app/Classes/General/Eloquent/Filters/IsMappedFalseOrMappedButStatusIn.php @@ -16,9 +16,7 @@ class IsMappedFalseOrMappedButStatusIn implements Filter { return $builder->where(function($q) use ($value) { $q->whereDoesntHave('owners'); - $q->orwhereHas('owners', function($query) use ($value) { - $query->whereIn('status', $value); - }); + $q->orwhereDoesntHave('owner_status'); }); } diff --git a/app/Models/StatementTransaction.php b/app/Models/StatementTransaction.php index eb4bcdc8..4bba7903 100644 --- a/app/Models/StatementTransaction.php +++ b/app/Models/StatementTransaction.php @@ -49,6 +49,11 @@ class StatementTransaction extends Model return $this->hasMany(StatementTransactionOwner::class); } + public function owner_status() + { + return $this->owners()->whereIn('status',[ApprovalStatus::APPROVED,ApprovalStatus::COMPLETED,ApprovalStatus::PENDING_VERIFICATION]); + } + public function scopeDoesntMapStatement($query) { $query->whereDoesntHave('owners', function($query){ From 5b681ac8c05e2f1f1fbd9b2292caaa2982322f26 Mon Sep 17 00:00:00 2001 From: Steve Ng Date: Sun, 29 Oct 2023 08:44:31 +0800 Subject: [PATCH 06/24] fixing the structure of export receipt to autocount and import receipt to exchange map failed --- .../Services/ExportsInvoiceTransactions.php | 21 +-- .../Services/ExportsReceiptTransactions.php | 132 ++++++++++++++++++ .../ExportCustomersToExcelController.php | 10 +- .../ImportStatementReceiptsController.php | 11 +- .../sections/TransactionsMappingComponent.vue | 5 +- routes/web.php | 1 + 6 files changed, 158 insertions(+), 22 deletions(-) create mode 100644 app/Classes/Modules/Exports/Services/ExportsReceiptTransactions.php diff --git a/app/Classes/Modules/Exports/Services/ExportsInvoiceTransactions.php b/app/Classes/Modules/Exports/Services/ExportsInvoiceTransactions.php index 2ecaada8..796ec19d 100644 --- a/app/Classes/Modules/Exports/Services/ExportsInvoiceTransactions.php +++ b/app/Classes/Modules/Exports/Services/ExportsInvoiceTransactions.php @@ -34,19 +34,12 @@ class ExportsInvoiceTransactions implements FromQuery, WithHeadings, WithHeading public function headings(): array { - $header = []; - if ($this->request->input('type') == 'invoices') { - $header[] = 'DocNo'; - $header[] = 'DocDate'; - $header[] = 'DebtorCode'; - } else { - $header[] = 'OrNo'; - $header[] = 'OrDate'; - $header[] = 'CreditorCode'; - } - $header[] = 'Ref'; - $header[] = ($this->request->input('type') == 'invoices' ? 'DebtorName' : 'CreditorName'); - $header = array_merge($header, [ + $header = [ + 'DocNo', + 'DocDate', + 'DebtorCode', + 'Ref', + 'DebtorName', 'CurrencyCode', 'ShipInfo', 'ItemCode', @@ -56,7 +49,7 @@ class ExportsInvoiceTransactions implements FromQuery, WithHeadings, WithHeading 'UnitPrice', 'AccNo', 'DeptNo' - ]); + ]; return $header; } diff --git a/app/Classes/Modules/Exports/Services/ExportsReceiptTransactions.php b/app/Classes/Modules/Exports/Services/ExportsReceiptTransactions.php new file mode 100644 index 00000000..07c5d3c1 --- /dev/null +++ b/app/Classes/Modules/Exports/Services/ExportsReceiptTransactions.php @@ -0,0 +1,132 @@ +request = $request; + } + + public function headings(): array + { + $header = [ + 'DocNo', + 'DocDate', + 'DebtorCode', + 'Description', + 'DocNo2', + 'ProjNo', + 'DeptNo', + 'CurrencyCode', + 'ToHomeRate', + 'ToDebtorRate', + 'Note', + 'PaymentMethod', + 'ChequeNo', + 'PaymentAmt', + 'BankCharge', + 'ToBankRate', + 'BankChargeTaxType', + 'BankChargeTaxRefNo', + 'BankChargeProjNo', + 'BankChargeDeptNo', + 'PaymentBy', + 'FloatDay', + 'IsRCHQ', + 'RCHQDate', + 'KnockOffDocType', + 'KnockOffDocNo', + 'KnockOffAmt', + '', + ]; + return $header; + } + + /** + * @return \Illuminate\Support\Collection|mixed + */ + public function query() + { + $data = (new ApplyFiltersToQuery())->execute(StatementTransaction::query(), json_decode($this->request->input('filter'), true)); + if ($this->request->has('bankStatementTransactionId')) $data = $data->whereIn('id',json_decode($this->request->input('bankStatementTransactionId'), true)); + + return $data; + } + + /** + * @param StatementTransaction $transaction + * + * @return array + */ + public function map($transaction): array + { + $statementTransactionOwner = $transaction->owners()->whereIn('status', [ApprovalStatus::APPROVED])->first(); + $logArray = [ + 'counter' => $this->counter, + 'system' => $statementTransactionOwner->system, + 'StatementTransactionOwner_id' => $statementTransactionOwner->id, + 'transaction_table_id' => $statementTransactionOwner->owner_id, + ]; + $this->counter += 1; + $logArray = json_encode($logArray); + + $filePath = storage_path('logs/exports_receipt_transactions.log'); + $errorFilePath = storage_path('logs/exports_receipt_transactions_error.log'); + $textToAppend = Carbon::now()->format('[Y-m-d H:i:s]') . ' ' . $logArray . PHP_EOL; + file_put_contents($filePath, $textToAppend, FILE_APPEND); + + $company = Company::where('name',$transaction->transaction_description_2)->first(); + + return [ + '<>', + Carbon::parse($transaction->posting_date)->format('d/m/Y'), + ($company ? $company->debtor : null), + $transaction->transaction_description, + '', + '', + '', + 'MYR', + 1, + 1, + '', + 'MBB', + '', + $transaction->amount, + '', + 1, + '', + '', + '', + '', + '', + '0', + '', + '', + 'RI', + $transaction->transaction_ref, + $transaction->amount, + '', + ]; + } +} diff --git a/app/Http/Controllers/Exports/ExportCustomersToExcelController.php b/app/Http/Controllers/Exports/ExportCustomersToExcelController.php index 7dfe0485..733c84fa 100644 --- a/app/Http/Controllers/Exports/ExportCustomersToExcelController.php +++ b/app/Http/Controllers/Exports/ExportCustomersToExcelController.php @@ -17,6 +17,7 @@ use Illuminate\Support\Facades\Auth; use Maatwebsite\Excel\Excel; use App\Classes\Modules\Exports\Services\ExportsImportedInvoiceMappeds; use App\Models\TransactionMappingLog; +use App\Classes\Modules\Exports\Services\ExportsReceiptTransactions; class ExportCustomersToExcelController { @@ -61,7 +62,14 @@ class ExportCustomersToExcelController public function invoiceTransactions(Request $request){ $exportsTransactions = new ExportsInvoiceTransactions($request); - $response = $exportsTransactions->download(($request->input('type') == 'invoices' ? 'invoice-transactions' : 'receipt-transactions').'.xls', Excel::XLS, ['Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']); + $response = $exportsTransactions->download('invoice-transactions.xls', Excel::XLS, ['Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']); + ob_end_clean(); + return $response; + } + + public function receiptTransactions(Request $request){ + $exportsTransactions = new ExportsReceiptTransactions($request); + $response = $exportsTransactions->download('receipt-transactions.xls', Excel::XLS, ['Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']); ob_end_clean(); return $response; } diff --git a/app/Http/Controllers/Imports/ImportStatementReceiptsController.php b/app/Http/Controllers/Imports/ImportStatementReceiptsController.php index 8021e3a9..f3b89db7 100644 --- a/app/Http/Controllers/Imports/ImportStatementReceiptsController.php +++ b/app/Http/Controllers/Imports/ImportStatementReceiptsController.php @@ -21,6 +21,7 @@ use App\Models\TransactionMappingLog; use App\Classes\ValueObjects\Response\ApiResponseObject; use App\Classes\ValueObjects\Constants\HttpStatus; use Illuminate\Http\JsonResponse; +use Illuminate\Support\Facades\DB; class ImportStatementReceiptsController { @@ -78,11 +79,11 @@ class ImportStatementReceiptsController private function mappingExchange(Array $row) { $date = $row['date']; - $transactions = Transaction::where('original_amount', $row['local_payment_amount'])->whereRaw("DATE(created_at) = '$date'") - ->whereHas('issuerCompany', function($q) use($row) { - $q->where('debtor',$row['debtor_code']); - }) - ->get(); + $transactions = Transaction::getReceiverWithJoinStatementTransactionAndOwner($row)->select('transactions.*')->where('statement_transactions.amount', $row['payment_amount'])->whereRaw("DATE(posting_date) = '$date'")->get(); + + if ($transactions && $transactions->count() == 0) { + $transactions = Transaction::getReceiverWithJoinStatementTransactionAndOwner($row)->select('transactions.*')->where(DB::raw('FLOOR(statement_transactions.amount)'), floor($row['payment_amount']))->whereRaw("DATE(posting_date) = '$date'")->get(); + } if ($transactions && $transactions->count() == 1) { foreach ($transactions as $key => $transaction) { diff --git a/resources/assets/vue/components/accounting/sections/TransactionsMappingComponent.vue b/resources/assets/vue/components/accounting/sections/TransactionsMappingComponent.vue index 160221bf..7a677bad 100644 --- a/resources/assets/vue/components/accounting/sections/TransactionsMappingComponent.vue +++ b/resources/assets/vue/components/accounting/sections/TransactionsMappingComponent.vue @@ -267,7 +267,7 @@ export default { exportInvoiceToAutoCount(){ const checkedStatementTransactions = this.getCheckedStatementOwners(); - let route = this.route('invoiceTransactions.export')+'?type=invoices&filter='+JSON.stringify(this.filter); + let route = this.route('invoiceTransactions.export')+'?filter='+JSON.stringify(this.filter); if (checkedStatementTransactions) { route += '&bankStatementTransactionId='+checkedStatementTransactions; } @@ -277,7 +277,8 @@ export default { exportReceiptToAutoCount(){ const checkedStatementTransactions = this.getCheckedStatementOwners(); - let route = this.route('invoiceTransactions.export')+'?type=receipts&filter='+JSON.stringify(this.filter); + this.filter['statement_transaction_owner_type_in'] = [3,4,5,7,13,14]; + let route = this.route('receiptTransactions.export')+'?filter='+JSON.stringify(this.filter); if (checkedStatementTransactions) { route += '&bankStatementTransactionId='+checkedStatementTransactions; } diff --git a/routes/web.php b/routes/web.php index 1dece5c3..18f8aa86 100644 --- a/routes/web.php +++ b/routes/web.php @@ -261,6 +261,7 @@ Route::get('/export/payment-transactions/f614e339d7058904a831aad742e24d55', 'Exp Route::get('/export/wallet-transactions/f614e339d7058904a831aad742e24d55', 'Exports\ExportCustomersToExcelController@walletTransactions')->name('walletTransactions.export'); Route::get('/export/booking-transactions', 'Exports\ExportCustomersToExcelController@bookingTransactions')->name('export.transactions.booking'); Route::get('/export/invoice-transactions/f614e339d7058904a831aad742e24d55', 'Exports\ExportCustomersToExcelController@invoiceTransactions')->name('invoiceTransactions.export'); +Route::get('/export/invoice-transactions/f614e339d7058904a831aad742e24d55', 'Exports\ExportCustomersToExcelController@receiptTransactions')->name('receiptTransactions.export'); Route::get('/export/imported-invoice-mapped', 'Exports\ExportCustomersToExcelController@importedInvoiceMapped')->name('importedInvoiceMapped.export'); Route::get('/products', function (\App\Classes\Modules\Exports\Services\ExportsProducts $exportsProducts) { From 5c5f54e03b6256131291cedf79d75e3d5ba0f6cc Mon Sep 17 00:00:00 2001 From: edmondlang Date: Mon, 30 Oct 2023 18:39:19 +0800 Subject: [PATCH 07/24] delete booking / expire the order payment --- .../ExpireBookingPaymentControllerLogic.php | 57 +++++++++++++++++++ .../ExpireBookingPaymentController.php | 20 +++++++ .../BookingDetailsSectionComponent.vue | 16 ++++++ routes/booking.php | 1 + 4 files changed, 94 insertions(+) create mode 100644 app/Classes/Modules/Bookings/ControllersLogic/ExpireBookingPaymentControllerLogic.php create mode 100644 app/Http/Controllers/Bookings/ExpireBookingPaymentController.php diff --git a/app/Classes/Modules/Bookings/ControllersLogic/ExpireBookingPaymentControllerLogic.php b/app/Classes/Modules/Bookings/ControllersLogic/ExpireBookingPaymentControllerLogic.php new file mode 100644 index 00000000..8ee2bbfa --- /dev/null +++ b/app/Classes/Modules/Bookings/ControllersLogic/ExpireBookingPaymentControllerLogic.php @@ -0,0 +1,57 @@ + 'Expire Payment', + 'message' => 'You have successfully expire the Payment' + ]; + } + + /** @var FetchesBooking */ + private $fetchesBooking; + + /** + * DeletePurchaseOrderPdfLogic constructor. + * @param FetchesBooking $fetchesBooking + */ + public function __construct(fetchesBooking $fetchesBooking) + { + $this->fetchesBooking = $fetchesBooking; + } + + + /** + * @param Request $request + * @return JsonResponse + * @throws \App\Classes\Exceptions\MalformedRequestException + */ + public function logic(Request $request) : JsonResponse + { + $booking = $this->fetchesBooking->execute(['id' => $request->route('id')]); + + $payment = $booking->transactions() + ->payments()->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED]) + ->first(); + + $payment->status = ApprovalStatus::EXPIRED; + $payment->save(); + + return $this->response([]); + } + +} diff --git a/app/Http/Controllers/Bookings/ExpireBookingPaymentController.php b/app/Http/Controllers/Bookings/ExpireBookingPaymentController.php new file mode 100644 index 00000000..f09fa38a --- /dev/null +++ b/app/Http/Controllers/Bookings/ExpireBookingPaymentController.php @@ -0,0 +1,20 @@ +execute($request); + } + +} \ No newline at end of file diff --git a/resources/assets/vue/components/bookings/sections/BookingDetailsSectionComponent.vue b/resources/assets/vue/components/bookings/sections/BookingDetailsSectionComponent.vue index a65c2ce8..a2762ce7 100644 --- a/resources/assets/vue/components/bookings/sections/BookingDetailsSectionComponent.vue +++ b/resources/assets/vue/components/bookings/sections/BookingDetailsSectionComponent.vue @@ -289,6 +289,22 @@
+
+
+
Delete Transfer
+
+ + + + +
diff --git a/routes/booking.php b/routes/booking.php index 81db27b6..119d24fa 100644 --- a/routes/booking.php +++ b/routes/booking.php @@ -19,6 +19,7 @@ Route::group(['prefix' => 'booking', 'as' => 'booking.', 'namespace' => 'Booking Route::post('create', 'CreateBookingPaymentController@create')->name('create'); Route::post('{payment_id}/verification/create', 'CreatePaymentVerificationController@create')->name('verification.create'); Route::put('/{payment_id}/approval/{status}', 'ApprovePaymentVerificationController@approve')->where('status', 'approve|reject')->name('approval'); + Route::post('delete', 'ExpireBookingPaymentController@expire')->name('expire'); }); Route::group(['prefix' => '{id}/refund', 'as' => 'refund.'], function () { From 4bf32ac28521dd0f36329e7395b6b19cd98c9854 Mon Sep 17 00:00:00 2001 From: Steve Ng Date: Wed, 1 Nov 2023 13:43:36 +0800 Subject: [PATCH 08/24] fix bug of update status of statement transaction owner when update invoice or receipt success, and paginate when next page with filtering date in Pending Export tab, and error on export invoive to autocount --- .../Controllers/Imports/ImportStatementInvoiceController.php | 5 ++++- .../Imports/ImportStatementReceiptsController.php | 5 ++++- .../assets/vue/components/general/elements/ListComponent.vue | 1 + routes/web.php | 2 +- 4 files changed, 10 insertions(+), 3 deletions(-) diff --git a/app/Http/Controllers/Imports/ImportStatementInvoiceController.php b/app/Http/Controllers/Imports/ImportStatementInvoiceController.php index 73e58e87..6cfdec08 100644 --- a/app/Http/Controllers/Imports/ImportStatementInvoiceController.php +++ b/app/Http/Controllers/Imports/ImportStatementInvoiceController.php @@ -154,7 +154,10 @@ class ImportStatementInvoiceController public function updateTransactionOwnerReference($transaction, String $docNo) { $transactionOwner = $transaction->transaction_owner; if ($transactionOwner) { - $transactionOwner->update(['invoice_reference'=>$docNo]); + $transactionOwner->update([ + 'invoice_reference'=>$docNo, + 'status'=>ApprovalStatus::COMPLETED + ]); return $transactionOwner->owner_reference; } return false; diff --git a/app/Http/Controllers/Imports/ImportStatementReceiptsController.php b/app/Http/Controllers/Imports/ImportStatementReceiptsController.php index f3b89db7..3c919376 100644 --- a/app/Http/Controllers/Imports/ImportStatementReceiptsController.php +++ b/app/Http/Controllers/Imports/ImportStatementReceiptsController.php @@ -96,7 +96,10 @@ class ImportStatementReceiptsController public function updateTransactionOwnerReference($transaction, String $docNo) { $transactionOwner = $transaction->transaction_owner; if ($transactionOwner) { - $transactionOwner->update(['receipt_reference'=>$docNo]); + $transactionOwner->update([ + 'receipt_reference'=>$docNo, + 'status'=>ApprovalStatus::COMPLETED + ]); return $transactionOwner->owner_reference; } return false; diff --git a/resources/assets/vue/components/general/elements/ListComponent.vue b/resources/assets/vue/components/general/elements/ListComponent.vue index 50d2fa19..8f54548b 100644 --- a/resources/assets/vue/components/general/elements/ListComponent.vue +++ b/resources/assets/vue/components/general/elements/ListComponent.vue @@ -99,6 +99,7 @@ updateFilters(filters){ this.filters = filters; this.setDecoratorDefault(); + this.$store.dispatch('updateListQueue', {'name': this.section, 'page': 1, 'filters': this.filters}); this.submit(this.endpoint + '?page=1&filters=' + JSON.stringify(this.filters), 'get', this.section, false, false) }, successHandler(response){ diff --git a/routes/web.php b/routes/web.php index 18f8aa86..989d3296 100644 --- a/routes/web.php +++ b/routes/web.php @@ -261,7 +261,7 @@ Route::get('/export/payment-transactions/f614e339d7058904a831aad742e24d55', 'Exp Route::get('/export/wallet-transactions/f614e339d7058904a831aad742e24d55', 'Exports\ExportCustomersToExcelController@walletTransactions')->name('walletTransactions.export'); Route::get('/export/booking-transactions', 'Exports\ExportCustomersToExcelController@bookingTransactions')->name('export.transactions.booking'); Route::get('/export/invoice-transactions/f614e339d7058904a831aad742e24d55', 'Exports\ExportCustomersToExcelController@invoiceTransactions')->name('invoiceTransactions.export'); -Route::get('/export/invoice-transactions/f614e339d7058904a831aad742e24d55', 'Exports\ExportCustomersToExcelController@receiptTransactions')->name('receiptTransactions.export'); +Route::get('/export/receipt-transactions/f614e339d7058904a831aad742e24d55', 'Exports\ExportCustomersToExcelController@receiptTransactions')->name('receiptTransactions.export'); Route::get('/export/imported-invoice-mapped', 'Exports\ExportCustomersToExcelController@importedInvoiceMapped')->name('importedInvoiceMapped.export'); Route::get('/products', function (\App\Classes\Modules\Exports\Services\ExportsProducts $exportsProducts) { From db88edabfe8116c4685ea862515d3d1de6377d90 Mon Sep 17 00:00:00 2001 From: Steve Ng Date: Sat, 4 Nov 2023 10:45:41 +0800 Subject: [PATCH 09/24] fix bug unmapped invoice --- .../Services/ExportsInvoiceTransactions.php | 19 ++++++++++++++++++- .../ImportStatementInvoiceController.php | 9 +-------- .../ImportStatementReceiptsController.php | 9 +-------- 3 files changed, 20 insertions(+), 17 deletions(-) diff --git a/app/Classes/Modules/Exports/Services/ExportsInvoiceTransactions.php b/app/Classes/Modules/Exports/Services/ExportsInvoiceTransactions.php index 796ec19d..a7041b1c 100644 --- a/app/Classes/Modules/Exports/Services/ExportsInvoiceTransactions.php +++ b/app/Classes/Modules/Exports/Services/ExportsInvoiceTransactions.php @@ -127,7 +127,24 @@ class ExportsInvoiceTransactions implements FromQuery, WithHeadings, WithHeading Log::info('Error in Exports Invoice Transactions ' . $this->counter); - return []; + return [ + 'Transaction Not Found', + $transaction->posting_date->format('m/d/Y H:m'), + $transaction->transaction_description.' - '.$transaction->transaction_description_2, + $statementTransactionOwner->system, + '', + '', + '', + '', + '', + '', + 0, + $transaction->amount, + '', + '', + '', + '' + ]; } $row = $row[0]; diff --git a/app/Http/Controllers/Imports/ImportStatementInvoiceController.php b/app/Http/Controllers/Imports/ImportStatementInvoiceController.php index 6cfdec08..8d2b920b 100644 --- a/app/Http/Controllers/Imports/ImportStatementInvoiceController.php +++ b/app/Http/Controllers/Imports/ImportStatementInvoiceController.php @@ -55,7 +55,7 @@ class ImportStatementInvoiceController foreach ($excelRows as $row) { $row['mapped_result_reference'] = null; $row['mapped_status'] = 'failed'; - $row['date'] = $this->changeExcelDate($row['date']); + $row['date'] = date('Y-m-d', strtotime($row['date'])); // Shipping Info // TOPUP -> map with transaction.bill_no @@ -162,11 +162,4 @@ class ImportStatementInvoiceController } return false; } - - public function changeExcelDate($date) - { - $unixTime = (($date - 25569) * 86400); - $date = new DateTime("@$unixTime"); - return $date->format('Y-m-d'); // Change the format to 'Y-m-d' - } } diff --git a/app/Http/Controllers/Imports/ImportStatementReceiptsController.php b/app/Http/Controllers/Imports/ImportStatementReceiptsController.php index 3c919376..4006e130 100644 --- a/app/Http/Controllers/Imports/ImportStatementReceiptsController.php +++ b/app/Http/Controllers/Imports/ImportStatementReceiptsController.php @@ -53,7 +53,7 @@ class ImportStatementReceiptsController foreach ($excelRows as $row) { $row['mapped_result_reference'] = null; $row['mapped_status'] = 'failed'; - $row['date'] = $this->changeExcelDate($row['doc_date']); + $row['date'] = date('Y-m-d', strtotime($row['doc_date'])); $returnReference = $this->mappingExchange($row); if ($returnReference) { @@ -104,11 +104,4 @@ class ImportStatementReceiptsController } return false; } - - public function changeExcelDate($date) - { - $unixTime = (($date - 25569) * 86400); - $date = new DateTime("@$unixTime"); - return $date->format('Y-m-d'); // Change the format to 'Y-m-d' - } } From 4de027c82f37df52d34615dae11a08e732b3a69a Mon Sep 17 00:00:00 2001 From: edmondlang Date: Thu, 9 Nov 2023 00:24:55 +0800 Subject: [PATCH 10/24] regenerate customer invoice in certain date period --- routes/web.php | 68 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) diff --git a/routes/web.php b/routes/web.php index 7325c90b..0efe0616 100644 --- a/routes/web.php +++ b/routes/web.php @@ -766,3 +766,71 @@ Route::get('/customer/vouchers/{marking}', function ($marking) { })->name('customer.reward'); Route::get('transaction/{id}/credit_note/download', 'Transactions\GenerateCreditNotePdfController@download')->name('transaction.credit_note.download'); + +Route::get('/invoice/{marking}/{started_at}/{ended_at}/fix', function($marking, $started_at, $ended_at) { + + set_time_limit(14400); + $processed_invoice = 1; + + if (is_null($marking) || empty($marking)) { + return 'Error - Marking is empty'; + } + + if (is_null($started_at) || empty($started_at)) { + return 'Error - Start Date is empty'; + } + + if (is_null($ended_at) || empty($ended_at)) { + return 'Error - End Date is empty'; + } + + $company = Company::where('reference', $marking)->first(); + if (!$company) { + return 'Error - Marking not found'; + } + dump('Company Id - ' . $company->id); + + // dd($marking, $started_at, $ended_at); + + $bookings = $company->bookings() + ->where('status', ApprovalStatus::COMPLETED) + ->whereDate('updated_at', '>=', Carbon::parse($started_at)) + ->whereDate('updated_at', '<=', Carbon::parse($ended_at)) + ->orderBy('id') + ->chunk(100, function ($bookings) use (&$processed_invoice) { + foreach ($bookings as $booking) { + + Log::channel('regenerateInvoice')->info('Counter ' . $processed_invoice); + dump('Counter ' . $processed_invoice); + $processed_invoice += 1; + + $booking->status = ApprovalStatus::APPROVED; + $booking->save(); + + $firstInvoice = $booking->transactions() + ->whereIn('type', [TransactionType::INVOICE]) + ->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-" . (string)(Carbon::now()->timestamp); + $currentInvoice->save(); + + $booking->transactions()->whereIn('transactions.type', [TransactionType::INVOICE, TransactionType::SUPPLIER_DELIVER])->delete(); + $booking->documents()->whereIn('document_type', [DocumentType::INVOICE, DocumentType::PURCHASE_ORDER, DocumentType::DELIVER_ORDER, DocumentType::SUPPLIER_DELIVER_ORDER])->delete(); + + (App()->make(CreateInvoiceTransactionWithInvoiceNoProcessor::class))->execute($booking, $firstBillNo); + dump('regenerated invoice. Booking Marking - ' . $booking->marking . '. Bill_no - ' . $firstBillNo . '. Old bill_no - ' . $currentInvoice->bill_no); + Log::channel('regenerateInvoice')->info('regenerated invoice. Booking Marking - ' . $booking->marking . '. Bill_no - ' . $firstBillNo . '. Old bill_no - ' . $currentInvoice->bill_no); + } + } + ); +})->name('invoice.fix.byCustomerMarking'); \ No newline at end of file From 9b46981593142d4b0ae140bd85eb691ca4adee9f Mon Sep 17 00:00:00 2001 From: edmondlang Date: Thu, 9 Nov 2023 09:43:09 +0800 Subject: [PATCH 11/24] update regenerate documents link --- routes/web.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/routes/web.php b/routes/web.php index 0efe0616..e2cd97fb 100644 --- a/routes/web.php +++ b/routes/web.php @@ -794,8 +794,8 @@ Route::get('/invoice/{marking}/{started_at}/{ended_at}/fix', function($marking, $bookings = $company->bookings() ->where('status', ApprovalStatus::COMPLETED) - ->whereDate('updated_at', '>=', Carbon::parse($started_at)) - ->whereDate('updated_at', '<=', Carbon::parse($ended_at)) + ->whereDate('created_at', '>=', Carbon::parse($started_at)) + ->whereDate('created_at', '<=', Carbon::parse($ended_at)) ->orderBy('id') ->chunk(100, function ($bookings) use (&$processed_invoice) { foreach ($bookings as $booking) { From fc2bdb4ff0afc230c2814de98021ce19483c6ec8 Mon Sep 17 00:00:00 2001 From: edmondlang Date: Thu, 9 Nov 2023 10:07:13 +0800 Subject: [PATCH 12/24] update regenerate invoice --- routes/web.php | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/routes/web.php b/routes/web.php index e2cd97fb..447d0d72 100644 --- a/routes/web.php +++ b/routes/web.php @@ -821,9 +821,17 @@ Route::get('/invoice/{marking}/{started_at}/{ended_at}/fix', function($marking, // update currentInvoice bill_no to '-deleted-' $currentInvoice = $booking->transactions()->where('type', TransactionType::INVOICE)->first(); - $currentInvoice->bill_no = $currentInvoice->bill_no ."-deleted-" . (string)(Carbon::now()->timestamp); + $currentInvoice->bill_no = $currentInvoice->bill_no ."-deleted-" . Str::random(10); $currentInvoice->save(); + $transactionWithSameBillNo = Transaction::where('bill_no', $firstBillNo)->get(); + if ($transactionWithSameBillNo) { + foreach ($transactionWithSameBillNo as $transaction) { + $transaction->bill_no = $transaction->bill_no . "-deleted-" . Str::random(10); + $transaction->save(); + } + } + $booking->transactions()->whereIn('transactions.type', [TransactionType::INVOICE, TransactionType::SUPPLIER_DELIVER])->delete(); $booking->documents()->whereIn('document_type', [DocumentType::INVOICE, DocumentType::PURCHASE_ORDER, DocumentType::DELIVER_ORDER, DocumentType::SUPPLIER_DELIVER_ORDER])->delete(); From 6fe1ca3e0e08fe62105ef971763a3090d965f1ab Mon Sep 17 00:00:00 2001 From: edmondlang Date: Thu, 9 Nov 2023 10:21:04 +0800 Subject: [PATCH 13/24] update regenerate invoice --- .../RegenerateInvoiceBookingLogic.php | 11 ++++++++++- routes/web.php | 3 ++- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/app/Classes/Modules/Bookings/ControllersLogic/RegenerateInvoiceBookingLogic.php b/app/Classes/Modules/Bookings/ControllersLogic/RegenerateInvoiceBookingLogic.php index 6af18568..5d067fd5 100644 --- a/app/Classes/Modules/Bookings/ControllersLogic/RegenerateInvoiceBookingLogic.php +++ b/app/Classes/Modules/Bookings/ControllersLogic/RegenerateInvoiceBookingLogic.php @@ -10,13 +10,14 @@ use App\Classes\Modules\Transactions\Services\DeletesTransaction; use App\Classes\Modules\Documents\Services\DeletesDocument; use App\Classes\Modules\Transactions\Processors\CreateInvoiceTransactionProcessor; use App\Classes\Modules\Transactions\Processors\CreateInvoiceTransactionWithInvoiceNoProcessor; - +use Illuminate\Support\Str; use App\Classes\ValueObjects\Constants\DocumentType; use App\Http\Resources\BookingResource; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use App\Classes\ValueObjects\Constants\ApprovalStatus; use App\Classes\ValueObjects\Constants\TransactionType; +use App\Models\Transaction; use Illuminate\Support\Carbon; class RegenerateInvoiceBookingLogic extends AbstractControllerLogic @@ -121,6 +122,14 @@ class RegenerateInvoiceBookingLogic extends AbstractControllerLogic $currentInvoice->bill_no = $currentInvoice->bill_no ."-deleted-" . (string)(Carbon::now()->timestamp); $currentInvoice->save(); + $transactionWithSameBillNo = Transaction::where('bill_no', $firstBillNo)->withTrashed()->get(); + if ($transactionWithSameBillNo) { + foreach ($transactionWithSameBillNo as $transaction) { + $transaction->bill_no = $transaction->bill_no . "-deleted-" . Str::random(10); + $transaction->save(); + } + } + $transaction = $booking->transactions()->whereIn('type', [TransactionType::INVOICE, TransactionType::SUPPLIER_DELIVER])->get(); foreach ($transaction as $key => $row) { $this->deletesTransaction->execute($row); diff --git a/routes/web.php b/routes/web.php index 447d0d72..ead4b3d2 100644 --- a/routes/web.php +++ b/routes/web.php @@ -802,6 +802,7 @@ Route::get('/invoice/{marking}/{started_at}/{ended_at}/fix', function($marking, Log::channel('regenerateInvoice')->info('Counter ' . $processed_invoice); dump('Counter ' . $processed_invoice); + dump('Marking ' . $booking->marking); $processed_invoice += 1; $booking->status = ApprovalStatus::APPROVED; @@ -824,7 +825,7 @@ Route::get('/invoice/{marking}/{started_at}/{ended_at}/fix', function($marking, $currentInvoice->bill_no = $currentInvoice->bill_no ."-deleted-" . Str::random(10); $currentInvoice->save(); - $transactionWithSameBillNo = Transaction::where('bill_no', $firstBillNo)->get(); + $transactionWithSameBillNo = Transaction::where('bill_no', $firstBillNo)->withTrashed()->get(); if ($transactionWithSameBillNo) { foreach ($transactionWithSameBillNo as $transaction) { $transaction->bill_no = $transaction->bill_no . "-deleted-" . Str::random(10); From d8a4510fc41e51c9480e3ac7ec73b8924c88019c Mon Sep 17 00:00:00 2001 From: Steve Ng Date: Sun, 12 Nov 2023 11:49:26 +0800 Subject: [PATCH 14/24] fix bug in import invoices and unknow tabs for status not in rejected --- .../UpdateBankStatementDetailLogic.php | 2 +- .../ImportStatementInvoiceController.php | 181 ++++++++++-------- .../ImportStatementReceiptsController.php | 65 ++++--- .../ImportedInvoiceMappedComponent.vue | 11 ++ 4 files changed, 152 insertions(+), 107 deletions(-) diff --git a/app/Classes/Modules/Accounting/ControllersLogic/UpdateBankStatementDetailLogic.php b/app/Classes/Modules/Accounting/ControllersLogic/UpdateBankStatementDetailLogic.php index 9f6c28e6..70186ce1 100644 --- a/app/Classes/Modules/Accounting/ControllersLogic/UpdateBankStatementDetailLogic.php +++ b/app/Classes/Modules/Accounting/ControllersLogic/UpdateBankStatementDetailLogic.php @@ -157,7 +157,7 @@ class UpdateBankStatementDetailLogic extends AbstractControllerLogic 'owner_reference' => $owner_reference, ]; - return $bankStatementTransaction->owners()->firstOrCreate($ownerData); + return $bankStatementTransaction->owners()->where('status','<>',ApprovalStatus::REJECTED)->firstOrCreate($ownerData); } private function editAccountMapped(StatementTransactionOwner $owner){ diff --git a/app/Http/Controllers/Imports/ImportStatementInvoiceController.php b/app/Http/Controllers/Imports/ImportStatementInvoiceController.php index 8d2b920b..56eecc7d 100644 --- a/app/Http/Controllers/Imports/ImportStatementInvoiceController.php +++ b/app/Http/Controllers/Imports/ImportStatementInvoiceController.php @@ -34,93 +34,111 @@ class ImportStatementInvoiceController $this->responseMessage = 'You have successfully imported invoice mapping'; } - /** - * @param Request $request - * @return array - * @throws \App\Classes\Exceptions\MalformedRequestException - */ - public function import(Request $request) : JsonResponse - { - ini_set('memory_limit', '-1'); - $importDate = date('Y-m-d H:i:s'); - $object = new DocumentObject('', $request->input('files'), '', ApprovalStatus::APPROVED, 'imports'); - $file = json_decode($object->getFiles()[0])->file_info->original->file; - - $import = new GenericImport(); - Excel::import($import, $file); - $excelRows = $import->rows; - $excelRows = $excelRows->toArray(); - - $data = []; - foreach ($excelRows as $row) { - $row['mapped_result_reference'] = null; - $row['mapped_status'] = 'failed'; - $row['date'] = date('Y-m-d', strtotime($row['date'])); - - // Shipping Info - // TOPUP -> map with transaction.bill_no - if (str_starts_with($row['shipping_info'], 'TOPUP')) { - // find in exchange first, if cannont then find in izyim - foreach (['exchange','izyim'] as $system) { - $returnReference = $this->mappingTopUp($row, $system); - if ($returnReference) { - $row['mapped_result_reference'] = $returnReference; - $row['mapped_status'] = 'success'; - } - } - } else { - $returnReference = $this->mappingExchange($row); + public function mapping($row) { + // Shipping Info + // TOPUP -> map with transaction.bill_no + if (str_starts_with($row['shipping_info'], 'TOPUP')) { + // find in exchange first, if cannont then find in izyim + foreach (['exchange','izyim'] as $system) { + $returnReference = $this->mappingTopUp($row, $system); if ($returnReference) { $row['mapped_result_reference'] = $returnReference; $row['mapped_status'] = 'success'; + return $row; } } - - TransactionMappingLog::create([ - 'imported_date'=>$importDate, - 'data'=>$row, - ]); - array_push($data, $row); - - - // if 5 digits -> exchange booking reference - // find transation - // find statement_transaction_owners, and fill up the details - - // if <5 digits, find the transaction id (order number in izyim), find the payment in izyim - // find transation - // find statement_transaction_owners, and fill up the details - - // dd([ - // 'type' => $statementTransactionOwnerType, - // 'system' => $system, - // // 'owner_type' => Transaction::class, - // // todo-new: make sure owner_type is a class - // 'owner_type' => $owner_type, - // 'owner_id' => $owner_id, - // 'owner_reference' => $owner_reference - // ]); - - // $bankStatementTransaction->owners()->firstOrCreate([ - // 'type' => $statementTransactionOwnerType, - // 'system' => $system, - // // 'owner_type' => Transaction::class, - // // todo-new: make sure owner_type is a class - // 'owner_type' => $owner_type, - // 'owner_id' => $owner_id, - // 'owner_reference' => $owner_reference - // ]); - - + } + + $returnReference = $this->mappingExchange($row); + if ($returnReference) { + $row['mapped_result_reference'] = $returnReference; + $row['mapped_status'] = 'success'; + return $row; } - return $this->response(['data'=>$data,'importedDate'=>$importDate]); + // if still unable to map, will try to check the shipping_info without TOPUP + foreach (['exchange','izyim'] as $system) { + $returnReference = $this->mappingTopUp($row, $system); + if ($returnReference) { + $row['mapped_result_reference'] = $returnReference; + $row['mapped_status'] = 'success'; + } + } + + return $row; } - public function response(?array $data = []) : JsonResponse { - return (new ApiResponseObject($this->responseTitle, - $this->responseMessage, - HttpStatus::OK_WITH_MESSAGE, $data))->handler(); + /** + * @param Request $request + * @return array + */ + public function import(Request $request) : JsonResponse + { + try { + ini_set('memory_limit', '-1'); + $importDate = date('Y-m-d H:i:s'); + $object = new DocumentObject('', $request->input('files'), '', ApprovalStatus::APPROVED, 'imports'); + $file = json_decode($object->getFiles()[0])->file_info->original->file; + + $import = new GenericImport(); + Excel::import($import, $file); + $excelRows = $import->rows; + $excelRows = $excelRows->toArray(); + + $data = []; + foreach ($excelRows as $row) { + $row['mapped_result_reference'] = null; + $row['mapped_status'] = 'failed'; + $row['date'] = in_array(gettype($row['date']), ['integer', 'double']) ? $this->changeExcelDate($row['date']) : date('Y-m-d', strtotime($row['date'])); + + $row = $this->mapping($row); + + TransactionMappingLog::create([ + 'imported_date'=>$importDate, + 'data'=>$row, + ]); + array_push($data, $row); + + + // if 5 digits -> exchange booking reference + // find transation + // find statement_transaction_owners, and fill up the details + + // if <5 digits, find the transaction id (order number in izyim), find the payment in izyim + // find transation + // find statement_transaction_owners, and fill up the details + + // dd([ + // 'type' => $statementTransactionOwnerType, + // 'system' => $system, + // // 'owner_type' => Transaction::class, + // // todo-new: make sure owner_type is a class + // 'owner_type' => $owner_type, + // 'owner_id' => $owner_id, + // 'owner_reference' => $owner_reference + // ]); + + // $bankStatementTransaction->owners()->firstOrCreate([ + // 'type' => $statementTransactionOwnerType, + // 'system' => $system, + // // 'owner_type' => Transaction::class, + // // todo-new: make sure owner_type is a class + // 'owner_type' => $owner_type, + // 'owner_id' => $owner_id, + // 'owner_reference' => $owner_reference + // ]); + + + } + + return $this->response($this->responseTitle, $this->responseMessage, HttpStatus::OK_WITH_MESSAGE, ['data'=>$data,'importedDate'=>$importDate]); + } catch (\Exception $exception){ + return $this->response('import invoice failed',$exception->getMessage(), ($exception->getCode()? $exception->getCode() : HttpStatus::SERVER_ERROR)); + } + } + + public function response(String $responseTitle, String $responseMessage, int $httpStatus, ?array $data = []) : JsonResponse { + return (new ApiResponseObject($responseTitle, $responseMessage, $httpStatus, $data))->handler(); } private function mappingTopUp(Array $row, String $system) { @@ -162,4 +180,11 @@ class ImportStatementInvoiceController } return false; } + + public function changeExcelDate($date) + { + $unixTime = (($date - 25569) * 86400); + $date = new DateTime("@$unixTime"); + return $date->format('Y-m-d'); // Change the format to 'Y-m-d' + } } diff --git a/app/Http/Controllers/Imports/ImportStatementReceiptsController.php b/app/Http/Controllers/Imports/ImportStatementReceiptsController.php index 4006e130..2cafeac0 100644 --- a/app/Http/Controllers/Imports/ImportStatementReceiptsController.php +++ b/app/Http/Controllers/Imports/ImportStatementReceiptsController.php @@ -40,41 +40,43 @@ class ImportStatementReceiptsController */ public function import(Request $request) { - $importDate = date('Y-m-d H:i:s'); - $object = new DocumentObject('', $request->input('files'), '', ApprovalStatus::APPROVED, 'imports'); - $file = json_decode($object->getFiles()[0])->file_info->original->file; + try { + $importDate = date('Y-m-d H:i:s'); + $object = new DocumentObject('', $request->input('files'), '', ApprovalStatus::APPROVED, 'imports'); + $file = json_decode($object->getFiles()[0])->file_info->original->file; - $import = new GenericImport(); - Excel::import($import, $file); - $excelRows = $import->rows; - $excelRows = $excelRows->toArray(); + $import = new GenericImport(); + Excel::import($import, $file); + $excelRows = $import->rows; + $excelRows = $excelRows->toArray(); - $data = []; - foreach ($excelRows as $row) { - $row['mapped_result_reference'] = null; - $row['mapped_status'] = 'failed'; - $row['date'] = date('Y-m-d', strtotime($row['doc_date'])); + $data = []; + foreach ($excelRows as $row) { + $row['mapped_result_reference'] = null; + $row['mapped_status'] = 'failed'; + $row['date'] = in_array(gettype($row['doc_date']), ['integer', 'double']) ? $this->changeExcelDate($row['doc_date']) : date('Y-m-d', strtotime($row['doc_date'])); - $returnReference = $this->mappingExchange($row); - if ($returnReference) { - $row['mapped_result_reference'] = $returnReference; - $row['mapped_status'] = 'success'; - } + $returnReference = $this->mappingExchange($row); + if ($returnReference) { + $row['mapped_result_reference'] = $returnReference; + $row['mapped_status'] = 'success'; + } - TransactionMappingLog::create([ - 'imported_date'=>$importDate, - 'data'=>$row, - ]); - array_push($data, $row); + TransactionMappingLog::create([ + 'imported_date'=>$importDate, + 'data'=>$row, + ]); + array_push($data, $row); + } + + return $this->response($this->responseTitle, $this->responseMessage, HttpStatus::OK_WITH_MESSAGE, ['data'=>$data,'importedDate'=>$importDate]); + } catch (\Exception $exception){ + return $this->response('import invoice failed',$exception->getMessage(), ($exception->getCode()? $exception->getCode() : HttpStatus::SERVER_ERROR)); } - - return $this->response(['data'=>$data,'importedDate'=>$importDate]); } - public function response(?array $data = []) : JsonResponse { - return (new ApiResponseObject($this->responseTitle, - $this->responseMessage, - HttpStatus::OK_WITH_MESSAGE, $data))->handler(); + public function response(String $responseTitle, String $responseMessage, int $httpStatus, ?array $data = []) : JsonResponse { + return (new ApiResponseObject($responseTitle, $responseMessage, $httpStatus, $data))->handler(); } private function mappingExchange(Array $row) { @@ -104,4 +106,11 @@ class ImportStatementReceiptsController } return false; } + + public function changeExcelDate($date) + { + $unixTime = (($date - 25569) * 86400); + $date = new DateTime("@$unixTime"); + return $date->format('Y-m-d'); // Change the format to 'Y-m-d' + } } diff --git a/resources/assets/vue/components/accounting/sections/ImportedInvoiceMappedComponent.vue b/resources/assets/vue/components/accounting/sections/ImportedInvoiceMappedComponent.vue index 3e52b70b..9fd29e45 100644 --- a/resources/assets/vue/components/accounting/sections/ImportedInvoiceMappedComponent.vue +++ b/resources/assets/vue/components/accounting/sections/ImportedInvoiceMappedComponent.vue @@ -8,6 +8,11 @@

{{ componentTitle }}

+
+
+ {{error}} +
+
-
+
Marking
{{this.item.company.reference}} @@ -34,7 +34,7 @@ {{this.item.convertible_currency.short_code}}
-
+
Transfer Type
{{this.item.service.name}}
From 7ab1cd47e54b4af7adc1f4b80a3f769a371f706a Mon Sep 17 00:00:00 2001 From: Steve Ng Date: Tue, 12 Dec 2023 16:24:36 +0800 Subject: [PATCH 19/24] change where condition for import receipts --- .../GroupApproveStatementTransactionLogic.php | 2 +- .../ImportStatementReceiptsController.php | 69 ++++++++++--------- .../StatementTransactionComponent.vue | 4 ++ 3 files changed, 41 insertions(+), 34 deletions(-) diff --git a/app/Classes/Modules/Accounting/ControllersLogic/GroupApproveStatementTransactionLogic.php b/app/Classes/Modules/Accounting/ControllersLogic/GroupApproveStatementTransactionLogic.php index f9eb9c7b..7ae8a2ae 100644 --- a/app/Classes/Modules/Accounting/ControllersLogic/GroupApproveStatementTransactionLogic.php +++ b/app/Classes/Modules/Accounting/ControllersLogic/GroupApproveStatementTransactionLogic.php @@ -62,7 +62,7 @@ class GroupApproveStatementTransactionLogic extends AbstractControllerLogic $statementTransactions = $this->listsBankStatementTransactions->execute($filters); foreach ($statementTransactions as $statementTransaction) { - $owners = $statementTransaction->owners; + $owners = $statementTransaction->owners()->where('status', ApprovalStatus::PENDING_VERIFICATION)->get(); if (count($owners)) { $this->updatesBankStatementTransactionOwnerStatus->execute($owners->first(), ApprovalStatus::APPROVED); diff --git a/app/Http/Controllers/Imports/ImportStatementReceiptsController.php b/app/Http/Controllers/Imports/ImportStatementReceiptsController.php index 2cafeac0..a43f2dda 100644 --- a/app/Http/Controllers/Imports/ImportStatementReceiptsController.php +++ b/app/Http/Controllers/Imports/ImportStatementReceiptsController.php @@ -2,32 +2,35 @@ namespace App\Http\Controllers\Imports; -use App\Classes\Modules\Documents\DataTransferObjects\DocumentObject; -use App\Classes\Modules\Imports\Services\GenericImport; -use App\Classes\Modules\Segments\DataTransferObjects\SeasonalSegmentObject; -use App\Classes\ValueObjects\Constants\ApprovalStatus; -use App\Models\Segment; -use App\Models\User; -use Carbon\Carbon; use DateTime; -use Illuminate\Http\Request; -use Maatwebsite\Excel\Facades\Excel; -use App\Classes\Modules\Segments\Services\CreatesSeasonalSegment; -use App\Classes\Modules\Companies\Processors\AssignSegmentProcessor; +use Carbon\Carbon; +use App\Models\User; use App\Models\Company; -use App\Models\SeasonalSegment; +use App\Models\Segment; use App\Models\Transaction; -use App\Models\TransactionMappingLog; -use App\Classes\ValueObjects\Response\ApiResponseObject; -use App\Classes\ValueObjects\Constants\HttpStatus; +use Illuminate\Http\Request; +use App\Models\SeasonalSegment; use Illuminate\Http\JsonResponse; use Illuminate\Support\Facades\DB; +use Maatwebsite\Excel\Facades\Excel; +use App\Models\TransactionMappingLog; +use App\Models\StatementTransactionOwner; +use App\Classes\ValueObjects\Constants\HttpStatus; +use App\Classes\ValueObjects\Constants\ApprovalStatus; +use App\Classes\Modules\Imports\Services\GenericImport; +use App\Classes\ValueObjects\Response\ApiResponseObject; +use App\Classes\Modules\Segments\Services\CreatesSeasonalSegment; +use App\Classes\Modules\Companies\Processors\AssignSegmentProcessor; +use App\Classes\Modules\Documents\DataTransferObjects\DocumentObject; +use App\Classes\Modules\Segments\DataTransferObjects\SeasonalSegmentObject; class ImportStatementReceiptsController { private $responseTitle; private $responseMessage; + private $removeStr = 'Payment for '; + public function __construct() { $this->responseTitle = 'Import Receipt Mapping'; $this->responseMessage = 'You have successfully imported receipt mapping'; @@ -56,11 +59,13 @@ class ImportStatementReceiptsController $row['mapped_status'] = 'failed'; $row['date'] = in_array(gettype($row['doc_date']), ['integer', 'double']) ? $this->changeExcelDate($row['doc_date']) : date('Y-m-d', strtotime($row['doc_date'])); - $returnReference = $this->mappingExchange($row); - if ($returnReference) { - $row['mapped_result_reference'] = $returnReference; - $row['mapped_status'] = 'success'; - } + if ($invRefer = $this->getInvoiceReference($row['description'])) { + $returnReference = $this->mappingExchange($invRefer, $row['doc_no']); + if ($returnReference) { + $row['mapped_result_reference'] = $returnReference; + $row['mapped_status'] = 'success'; + } + } TransactionMappingLog::create([ 'imported_date'=>$importDate, @@ -75,28 +80,26 @@ class ImportStatementReceiptsController } } + private function getInvoiceReference($invRefer) { + $arrStr = explode($this->removeStr, $invRefer); + if (isset($arrStr[1])) return $arrStr[1]; + return null; + } + public function response(String $responseTitle, String $responseMessage, int $httpStatus, ?array $data = []) : JsonResponse { return (new ApiResponseObject($responseTitle, $responseMessage, $httpStatus, $data))->handler(); } - private function mappingExchange(Array $row) { - $date = $row['date']; - $transactions = Transaction::getReceiverWithJoinStatementTransactionAndOwner($row)->select('transactions.*')->where('statement_transactions.amount', $row['payment_amount'])->whereRaw("DATE(posting_date) = '$date'")->get(); + private function mappingExchange($invRefer, $docNo) { + $transactionOwner = StatementTransactionOwner::where('invoice_reference',$invRefer)->whereNull('receipt_reference')->where('status', ApprovalStatus::COMPLETED)->first(); - if ($transactions && $transactions->count() == 0) { - $transactions = Transaction::getReceiverWithJoinStatementTransactionAndOwner($row)->select('transactions.*')->where(DB::raw('FLOOR(statement_transactions.amount)'), floor($row['payment_amount']))->whereRaw("DATE(posting_date) = '$date'")->get(); - } - - if ($transactions && $transactions->count() == 1) { - foreach ($transactions as $key => $transaction) { - return $this->updateTransactionOwnerReference($transaction, $row['doc_no']); - } + if ($transactionOwner) { + return $this->updateTransactionOwnerReference($transactionOwner, $docNo); } return false; } - public function updateTransactionOwnerReference($transaction, String $docNo) { - $transactionOwner = $transaction->transaction_owner; + public function updateTransactionOwnerReference($transactionOwner, String $docNo) { if ($transactionOwner) { $transactionOwner->update([ 'receipt_reference'=>$docNo, diff --git a/resources/assets/vue/components/accounting/elements/StatementTransactionComponent.vue b/resources/assets/vue/components/accounting/elements/StatementTransactionComponent.vue index b09b9a56..0c193871 100644 --- a/resources/assets/vue/components/accounting/elements/StatementTransactionComponent.vue +++ b/resources/assets/vue/components/accounting/elements/StatementTransactionComponent.vue @@ -4,6 +4,8 @@
{{ item.posting_date }}
{{ item.transaction_description_1 + ' - ' + item.transaction_description_2 }}
+ +
{{item.owners.pending_verification[0].system}}
@@ -51,6 +53,7 @@
+
@@ -93,6 +96,7 @@
+
From 7aedaa3c174cfd75f2df353abb1e0748fe579a48 Mon Sep 17 00:00:00 2001 From: Omair Saleh Date: Wed, 13 Dec 2023 13:36:54 +0800 Subject: [PATCH 20/24] show all active services for suppliers when not in segment --- app/Models/Company.php | 26 +++++++++++++++++++------- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/app/Models/Company.php b/app/Models/Company.php index 8b2e6081..a1416ebb 100644 --- a/app/Models/Company.php +++ b/app/Models/Company.php @@ -109,7 +109,7 @@ class Company extends AbstractModel implements Documentable { return $this->hasManyDeep(Transaction::class, [Booking::class], ['company_id', 'owner_id'], ['id', 'id']); } - + /** * @return HasMany */ @@ -130,13 +130,25 @@ class Company extends AbstractModel implements Documentable * @return Builder */ public function services(): Builder { - return ServiceType::where('status', ApprovalStatus::APPROVED)->whereHas('constants', function($query) { - $query->Where(function($query){ - $query->where('reference', SegmentConstants::SERVICE_TYPE)->where('detail->is_active', true); - })->orWhere(function($query) { - $query->where('reference', SegmentConstants::CUSTOM_SERVICE_TYPE)->where('detail->is_active', true)->whereIn('segment_id', $this->segments->pluck('id')); + + if ($this->type === 3) { + return ServiceType::where('status', ApprovalStatus::APPROVED)->whereHas('constants', function($query) { + $query->where(function($query) { + $query->where('reference', SegmentConstants::SERVICE_TYPE)->where('detail->is_active', true); + })->orWhere(function($query) { + $query->where('reference', SegmentConstants::CUSTOM_SERVICE_TYPE)->where('detail->is_active', true); + }); }); - }); + } else { + // Existing logic for other company types + return ServiceType::where('status', ApprovalStatus::APPROVED)->whereHas('constants', function($query) { + $query->Where(function($query){ + $query->where('reference', SegmentConstants::SERVICE_TYPE)->where('detail->is_active', true); + })->orWhere(function($query) { + $query->where('reference', SegmentConstants::CUSTOM_SERVICE_TYPE)->where('detail->is_active', true)->whereIn('segment_id', $this->segments->pluck('id')); + }); + }); + } } public function servicesConfigurations(): Collection { From 1ddf7923a51cd041986e57799c35737e19b2fbcf Mon Sep 17 00:00:00 2001 From: Omair Saleh Date: Wed, 13 Dec 2023 13:38:54 +0800 Subject: [PATCH 21/24] show all active services for suppliers when not in segment --- app/Models/Company.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Models/Company.php b/app/Models/Company.php index a1416ebb..54ae1e23 100644 --- a/app/Models/Company.php +++ b/app/Models/Company.php @@ -131,7 +131,7 @@ class Company extends AbstractModel implements Documentable */ public function services(): Builder { - if ($this->type === 3) { + if ($this->business_type === 3) { return ServiceType::where('status', ApprovalStatus::APPROVED)->whereHas('constants', function($query) { $query->where(function($query) { $query->where('reference', SegmentConstants::SERVICE_TYPE)->where('detail->is_active', true); From 18df0e256ba22d190fab84cf7927aa2b301b7f7d Mon Sep 17 00:00:00 2001 From: Dillon Ngo Date: Sat, 30 Dec 2023 01:15:27 +0800 Subject: [PATCH 22/24] Code sync from Shipping Portal, independent deployment of Vue Polling, checkout from dillon/34-jenkins-vapor --- .../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 ++ app/Classes/General/Helper.php | 24 +++ app/Classes/Jobs/ListBookingsJob.php | 50 +++++ app/Classes/Jobs/ListDocumentsJob.php | 61 ++++++ app/Classes/Jobs/ListTransactionsJob.php | 50 +++++ .../ControllersLogic/ListBookingJobLogic.php | 56 +++++ .../Processors/ListBookingsJobProcessor.php | 57 +++++ .../ControllersLogic/ListDocumentJobLogic.php | 74 +++++++ .../Processors/ListDocumentsJobProcessor.php | 54 +++++ .../ControllersLogic/FetchJobResultLogic.php | 54 +++++ .../ListGenericJobObject.php | 99 +++++++++ .../Jobs/Services/CreatesJobResult.php | 28 +++ .../Jobs/Services/FetchesJobResult.php | 33 +++ .../ListTransactionsJobLogic.php | 47 ++++ .../ListTransactionsJobProcessor.php | 50 +++++ .../Bookings/ListBookingsJobController.php | 22 ++ .../Documents/ListDocumentsJobController.php | 19 ++ .../Jobs/FetchJobResultController.php | 19 ++ .../ListTransactionsJobController.php | 21 ++ app/Http/Resources/BookingResource.php | 10 +- app/Http/Resources/CompanyResource.php | 31 ++- app/Http/Resources/DocumentResource.php | 5 +- app/Http/Resources/JobResultResource.php | 22 ++ app/Models/JobResult.php | 13 ++ ..._08_08_124848_create_job_results_table.php | 35 +++ ...31_add_new_column_to_job_results_table.php | 36 ++++ .../SupplierPendingOrdersSectionComponent.vue | 14 +- .../general/elements/ListPollingComponent.vue | 204 ++++++++++++++++++ routes/api.php | 4 + routes/currency.php | 2 +- routes/document.php | 3 +- routes/job.php | 7 + 37 files changed, 1281 insertions(+), 23 deletions(-) create mode 100644 app/Classes/Exceptions/JobResourceNotFoundException.php create mode 100644 app/Classes/General/Eloquent/Filters/JobId.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/Services/CreatesJobResult.php create mode 100644 app/Classes/Modules/Jobs/Services/FetchesJobResult.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/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 resources/assets/vue/components/general/elements/ListPollingComponent.vue 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/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..41f976a6 --- /dev/null +++ b/app/Classes/Jobs/ListBookingsJob.php @@ -0,0 +1,50 @@ +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..bbadc169 --- /dev/null +++ b/app/Classes/Jobs/ListDocumentsJob.php @@ -0,0 +1,61 @@ +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..6b8913a2 --- /dev/null +++ b/app/Classes/Jobs/ListTransactionsJob.php @@ -0,0 +1,50 @@ +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..c87751a3 --- /dev/null +++ b/app/Classes/Modules/Bookings/ControllersLogic/ListBookingJobLogic.php @@ -0,0 +1,56 @@ + 'List Booking Job', + 'message' => 'You have successfully submit a job to list bookings' + ]; + } + + /** + * @param Request $request + * @return JsonResponse + */ + public function logic(Request $request) : JsonResponse + { + $jobId = uniqid(); + + $user = Auth::user(); + $userInfo = (object) [ + 'email' => $user->email, + 'type' => $user->type, + ]; + + $listGenericJobObject = new ListGenericJobObject( + $request->fullUrl(), + $request->all(), + $jobId, + $userInfo + ); + + ListBookingsJob::dispatch($listGenericJobObject); + + $result = []; + $result['job_id'] = $jobId; + + 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..6ded2977 --- /dev/null +++ b/app/Classes/Modules/Bookings/Processors/ListBookingsJobProcessor.php @@ -0,0 +1,57 @@ +listsBookings = $listsBookings; + $this->createsJobResult = $createsJobResult; + } + + /** + * @param ListGenericJobObject $listGenericJobObject + * @return null|object + * @throws \App\Classes\Exceptions\MalformedRequestException + */ + 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(); + } + + //cief todo: remove comments + $result = Helper::collectionResponse(BookingResource::collection($query)); + + // $result = new JobBookingCollectionResponse($query, $listGenericJobObject->getuserInfo()); + // $result = $this->collectionResponse(new BookingResourceCollection(BookingResource::collection($query), $listGenericJobObject->getuserInfo())); + + $create = $this->createsJobResult->execute($listGenericJobObject, json_encode($result)); + + return $create; + } +} diff --git a/app/Classes/Modules/Documents/ControllersLogic/ListDocumentJobLogic.php b/app/Classes/Modules/Documents/ControllersLogic/ListDocumentJobLogic.php new file mode 100644 index 00000000..041bb9c8 --- /dev/null +++ b/app/Classes/Modules/Documents/ControllersLogic/ListDocumentJobLogic.php @@ -0,0 +1,74 @@ + 'List Document Job', + 'message' => 'You have successfully submit a job to list documents' + ]; + } + + /** + * @param Request $request + * @return JsonResponse + */ + public function logic(Request $request) : JsonResponse + { + $jobId = uniqid(); + + $user = Auth::user(); + $userInfo = (object) [ + 'email' => $user->email, + 'type' => $user->type, + ]; + + + $listGenericJobObject = new ListGenericJobObject( + $request->fullUrl(), + $request->all(), + $jobId, + $userInfo + ); + + ListDocumentsJob::dispatch($listGenericJobObject); + + //cief todo: remove comments + // // Create your job instance with delay, so we can back here within delay and take control in our hands. + // $job = new ListDocuments($listGenericJobObject); + // $job->delay(now()->addSeconds(5)); + + // // Dispath your job with our custom_dispatch helper. This will return job id from jobs table + // // $jobId = $this->custom_dispatch($job); + + + $result = []; + $result['job_id'] = $jobId; + + return $this->response(['data' => $result]); + } + + //cief todo: no longer need jobId + // function custom_dispatch($job): int { + // return app(\Illuminate\Contracts\Bus\Dispatcher::class)->dispatch($job); + // } +} diff --git a/app/Classes/Modules/Documents/Processors/ListDocumentsJobProcessor.php b/app/Classes/Modules/Documents/Processors/ListDocumentsJobProcessor.php new file mode 100644 index 00000000..eb7cf1c4 --- /dev/null +++ b/app/Classes/Modules/Documents/Processors/ListDocumentsJobProcessor.php @@ -0,0 +1,54 @@ +listsDocuments = $listsDocuments; + $this->createsJobResult = $createsJobResult; + } + + /** + * @param ListGenericJobObject $listGenericJobObject + * @return null|object + * @throws \App\Classes\Exceptions\MalformedRequestException + */ + 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(); + } + + $result = Helper::collectionResponse(DocumentResource::collection($query)); + + $create = $this->createsJobResult->execute($listGenericJobObject, json_encode($result)); + + return $create; + } +} diff --git a/app/Classes/Modules/Jobs/ControllersLogic/FetchJobResultLogic.php b/app/Classes/Modules/Jobs/ControllersLogic/FetchJobResultLogic.php new file mode 100644 index 00000000..366fda8c --- /dev/null +++ b/app/Classes/Modules/Jobs/ControllersLogic/FetchJobResultLogic.php @@ -0,0 +1,54 @@ + 'Retrieved Data', + 'message' => 'You have successfully retrieved data' + ]; + } + + /** @var FetchesJobResult */ + private $fetchesJobResult; + + /** + * FetchJobResultLogic constructor. + * @param FetchesJobResult $fetchesJobResult + */ + public function __construct(FetchesJobResult $fetchesJobResult) + { + $this->fetchesJobResult = $fetchesJobResult; + } + + + /** + * @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->fetchesJobResult->execute(['job_id' => $request->route('job_id')]); + + 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..365cd316 --- /dev/null +++ b/app/Classes/Modules/Jobs/DataTransferObjects/ListGenericJobObject.php @@ -0,0 +1,99 @@ +name = $name; + $this->payload = $payload; + $this->jobId = $jobId; + $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 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 setJobId(int $jobId) + // { + // $this->jobId = $jobId; + // } + + public function setJobCommandName(string $jobCommandName) + { + $this->jobCommandName = $jobCommandName; + } + + public function setJobCommand(string $jobCommand) + { + $this->jobCommand = $jobCommand; + } + +} diff --git a/app/Classes/Modules/Jobs/Services/CreatesJobResult.php b/app/Classes/Modules/Jobs/Services/CreatesJobResult.php new file mode 100644 index 00000000..00acc1eb --- /dev/null +++ b/app/Classes/Modules/Jobs/Services/CreatesJobResult.php @@ -0,0 +1,28 @@ +job_id = $listGenericJobObject->getJobId(); + $model->result = $result; + $model->url = $listGenericJobObject->getName(); + $model->job_command_name = $listGenericJobObject->getJobCommandName(); + $model->job_command = $listGenericJobObject->getJobCommand(); + + 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/Transactions/ControllersLogic/ListTransactionsJobLogic.php b/app/Classes/Modules/Transactions/ControllersLogic/ListTransactionsJobLogic.php new file mode 100644 index 00000000..d317d7eb --- /dev/null +++ b/app/Classes/Modules/Transactions/ControllersLogic/ListTransactionsJobLogic.php @@ -0,0 +1,47 @@ + 'List Transaction Job', + 'message' => 'You have successfully submit a job to list transactions' + ]; + } + + /** + * @param Request $request + * @return JsonResponse + */ + public function logic(Request $request) : JsonResponse + { + $jobId = uniqid(); + + $listGenericJobObject = new ListGenericJobObject( + $request->fullUrl(), + $request->all(), + $jobId + ); + + ListTransactionsJob::dispatch($listGenericJobObject); + + $result = []; + $result['job_id'] = $jobId; + + 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..36671c89 --- /dev/null +++ b/app/Classes/Modules/Transactions/Processors/ListTransactionsJobProcessor.php @@ -0,0 +1,50 @@ +listsTransactions = $listsTransactions; + $this->createsJobResult = $createsJobResult; + } + + /** + * @param ListGenericJobObject $listGenericJobObject + * @return null|object + * @throws \App\Classes\Exceptions\MalformedRequestException + */ + public function execute(ListGenericJobObject $listGenericJobObject) { + + $query = $this->listsTransactions->execute($this->listsTransactions->deserializeFilters($listGenericJobObject->getPayload()['filters']), ['page' => $listGenericJobObject->getPayload()['page']]); + + $result = Helper::collectionResponse(TransactionResource::collection($query)); + + $create = $this->createsJobResult->execute($listGenericJobObject, json_encode($result)); + + return $create; + } +} 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..c3c2e24d 100644 --- a/app/Http/Resources/BookingResource.php +++ b/app/Http/Resources/BookingResource.php @@ -11,10 +11,18 @@ use App\Classes\ValueObjects\Constants\TransactionType; use App\Classes\ValueObjects\Constants\DocumentType; use Carbon\Carbon; use Illuminate\Http\Resources\Json\JsonResource; +use Illuminate\Http\Resources\Json\AnonymousResourceCollection; use Illuminate\Support\Facades\Log; class BookingResource extends JsonResource { + private $userInfo; + + public function __construct($resource, $userInfo = null) + { + parent::__construct($resource); + $this->userInfo = $userInfo ?? ($resource->userInfo ?? null); + } /** * Transform the resource into an array. @@ -27,7 +35,7 @@ class BookingResource extends JsonResource { return [ 'id' => $this->id, - 'company' => new CompanyResource($this->company), + 'company' => new CompanyResource($this->company, $this->userInfo), 'bank' => new BankResource($this->bank), 'service' => new ServiceTypeResource($this->service), 'marking' => $this->marking, diff --git a/app/Http/Resources/CompanyResource.php b/app/Http/Resources/CompanyResource.php index 85ecee16..df3bcf49 100644 --- a/app/Http/Resources/CompanyResource.php +++ b/app/Http/Resources/CompanyResource.php @@ -19,6 +19,14 @@ use Illuminate\Support\Facades\Log; class CompanyResource extends JsonResource { + private $userInfo; + + public function __construct($resource, $userInfo = null) + { + parent::__construct($resource); + $this->userInfo = $userInfo; + } + /** * Transform the resource into an array. * @@ -33,6 +41,26 @@ class CompanyResource extends JsonResource $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; + } + + //cief todo: remove + // Log::error('CompanyResource 1: '. json_encode($userInfoEmail)); + // Log::error('CompanyResource 2: '. json_encode($userInfoType)); + + if(!is_null($userInfoEmail) && !is_null($userInfoType)){ + $userResource = new UserResource($userInfoType === RoleTypes::USER ? $this->employees()->where('email', '=', $userInfoEmail)->first() : $this->employees()->orderBy('id', 'DESC')->first()); + } + return [ 'id' => $this->id, 'name' => $this->name, @@ -43,7 +71,8 @@ class CompanyResource extends JsonResource 'status' => (int) $this->status, 'contact' => new ContactResource ($this->when($this->has('contacts'), $this->contacts->first())), 'address' => new AddressResource($this->when($this->has('addresses'), $this->addresses->where('billing', true)->first())), - 'employee' => new UserResource(Auth::user()->type === RoleTypes::USER ? $this->employees()->where('email', '=', Auth::user()->email)->first() : $this->employees()->orderBy('id', 'DESC')->first()), + //cief todo: this one need to decide what to do to replace Auth:user() when it is run by job queue + 'employee' => $userResource, 'identification' => new 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){ diff --git a/app/Http/Resources/DocumentResource.php b/app/Http/Resources/DocumentResource.php index 59933a67..6f9ade71 100644 --- a/app/Http/Resources/DocumentResource.php +++ b/app/Http/Resources/DocumentResource.php @@ -8,6 +8,9 @@ use App\Models\Document; use Carbon\Carbon; use Illuminate\Database\Eloquent\Model; use Illuminate\Http\Resources\Json\JsonResource; +use Illuminate\Support\Facades\Log; +use Illuminate\Support\Facades\Auth; +use Illuminate\Http\Resources\Json\AnonymousResourceCollection; class DocumentResource extends JsonResource { @@ -24,7 +27,7 @@ class DocumentResource extends JsonResource 'reference' => $this->reference, 'status' => (int) $this->status, 'document_type' => $this->document_type, - 'owner' => $this->relationLoaded('owner') ? ($this->owner instanceof Booking ? new BookingResource($this->owner) : new CompanyResource($this->owner)) : null, + 'owner' => $this->relationLoaded('owner') ? ($this->owner instanceof Booking ? new BookingResource($this->owner, $this->userInfo) : new CompanyResource($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/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/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/resources/assets/vue/components/bookings/sections/SupplierPendingOrdersSectionComponent.vue b/resources/assets/vue/components/bookings/sections/SupplierPendingOrdersSectionComponent.vue index 7df9c125..e6b66dcf 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..98e2a44b --- /dev/null +++ b/resources/assets/vue/components/general/elements/ListPollingComponent.vue @@ -0,0 +1,204 @@ + + + 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..f32d142e --- /dev/null +++ b/routes/job.php @@ -0,0 +1,7 @@ + 'job', 'as' => 'job.', 'namespace' => 'Jobs'], function () { + Route::get('/fetch/{job_id}', 'FetchJobResultController@fetch')->name('fetch'); +}); From 6da337b9dc50e1beb1cef220d2afcbafb37a698e Mon Sep 17 00:00:00 2001 From: Dillon Ngo Date: Sat, 30 Dec 2023 01:26:58 +0800 Subject: [PATCH 23/24] Code sync from Shipping Portal, independent deployment of Vue Polling, additional amendment to run Vue Polling at /billings --- ..._add_new_column_2_to_job_results_table.php | 34 +++++ .../AdminPaymentsBillingSectionComponent.vue | 136 ++++++++++++++++++ .../vue/general/mixins/aws/requestV2.js | 49 +++++++ .../assets/vue/general/mixins/tabHandler.js | 24 ++++ .../assets/vue/vuex/modules/crudRequestV2.js | 47 ++++++ resources/assets/vue/vuex/store.js | 4 +- resources/views/pages/billings.blade.php | 126 +--------------- 7 files changed, 295 insertions(+), 125 deletions(-) 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/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 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..03244ff4 --- /dev/null +++ b/resources/assets/vue/components/bookings/sections/AdminPaymentsBillingSectionComponent.vue @@ -0,0 +1,136 @@ + + 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..2445190e --- /dev/null +++ b/resources/assets/vue/vuex/modules/crudRequestV2.js @@ -0,0 +1,47 @@ +export default { + actions: { + crudRequestV2({getters, dispatch}, {endpoint, method, parameters}){ + 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 + } + }).then(response => { + if(response.status === 401 && window.location.href !== route('login') && window.location.href.indexOf(route('last_mile_delivery.login')) <= -1){ + dispatch('userAuthentication', {access_token: '', redirect_url: [7, 8].includes(getters.getCompanyModuleType) ? route('last_mile_delivery.login') : route('login')}); + } + + 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 From bf5ea2b2f23a00a49dbae4f76b628a9585ece1e6 Mon Sep 17 00:00:00 2001 From: Dillon Ngo Date: Sat, 30 Dec 2023 18:35:17 +0800 Subject: [PATCH 24/24] Code sync from Shipping Portal, independent deployment of Vue Polling, Performance Improvement and tweaking for better user experience --- .../Eloquent/Filters/OrderByIdDesc.php | 20 ++++ .../Eloquent/Filters/RequestSignature.php | 19 ++++ .../Eloquent/Filters/ResultNotNull.php | 18 ++++ .../ControllersLogic/ListBookingJobLogic.php | 25 ++++- .../Processors/ListBookingsJobProcessor.php | 33 ++---- .../ControllersLogic/ListDocumentJobLogic.php | 39 +++---- .../Processors/ListDocumentsJobProcessor.php | 31 +++--- .../ControllersLogic/FetchJobResultLogic.php | 17 ++- .../ListGenericJobObject.php | 31 ++++-- .../UpdateJobResultObject.php | 60 +++++++++++ .../Processors/FetchesJobResultProcessor.php | 45 ++++++++ .../Processors/UpdateJobResultProcessor.php | 64 +++++++++++ .../Jobs/Services/CreatesJobResult.php | 8 +- .../Modules/Jobs/Services/ListsJobResult.php | 33 ++++++ .../Jobs/Services/UpdatesJobResult.php | 28 +++++ .../ListTransactionsJobLogic.php | 31 +++++- .../ListTransactionsJobProcessor.php | 29 +++-- app/Http/Resources/BookingResource.php | 12 +-- app/Http/Resources/CompanyResource.php | 32 +----- app/Http/Resources/DocumentResource.php | 8 +- 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 ++++++++++++++++++ .../assets/vue/vuex/modules/crudRequestV2.js | 56 +++++----- 26 files changed, 809 insertions(+), 178 deletions(-) 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/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/ListsJobResult.php create mode 100644 app/Classes/Modules/Jobs/Services/UpdatesJobResult.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 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/Modules/Bookings/ControllersLogic/ListBookingJobLogic.php b/app/Classes/Modules/Bookings/ControllersLogic/ListBookingJobLogic.php index c87751a3..ef3570f7 100644 --- a/app/Classes/Modules/Bookings/ControllersLogic/ListBookingJobLogic.php +++ b/app/Classes/Modules/Bookings/ControllersLogic/ListBookingJobLogic.php @@ -5,12 +5,12 @@ namespace App\Classes\Modules\Bookings\ControllersLogic; use App\Classes\General\Abstracts\AbstractControllerLogic; use App\Classes\Jobs\ListBookingsJob; -use App\Classes\Modules\Bookings\Standards\Rules\CanListBookings; use App\Classes\Modules\Jobs\DataTransferObjects\ListGenericJobObject; -use ErrorException; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; +use App\Classes\Modules\Jobs\Services\CreatesJobResult; + class ListBookingJobLogic extends AbstractControllerLogic { @@ -24,6 +24,19 @@ class ListBookingJobLogic extends AbstractControllerLogic ]; } + /** @var CreatesJobResult */ + private $createsJobResult; + + /** + * ListPackingListsJobLogic constructor. + * @param CreatesJobResult $createsJobResult + */ + public function __construct(CreatesJobResult $createsJobResult) + { + $this->createsJobResult = $createsJobResult; + } + + /** * @param Request $request * @return JsonResponse @@ -34,13 +47,17 @@ class ListBookingJobLogic extends AbstractControllerLogic $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 ); @@ -50,6 +67,8 @@ class ListBookingJobLogic extends AbstractControllerLogic $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 index 6ded2977..2a09eb12 100644 --- a/app/Classes/Modules/Bookings/Processors/ListBookingsJobProcessor.php +++ b/app/Classes/Modules/Bookings/Processors/ListBookingsJobProcessor.php @@ -3,14 +3,10 @@ namespace App\Classes\Modules\Bookings\Processors; use App\Classes\Modules\Bookings\Services\ListsBookings; -use App\Classes\Modules\Jobs\Services\CreatesJobResult; -use App\Classes\Exceptions\MalformedRequestException; +use App\Classes\Modules\Jobs\Processors\UpdateJobResultProcessor; use App\Classes\General\Helper; -use Illuminate\Support\Facades\Http; -use Illuminate\Support\Facades\Log; use App\Classes\Modules\Jobs\DataTransferObjects\ListGenericJobObject; -use Illuminate\Http\Resources\Json\ResourceCollection; -use App\Http\Resources\BookingResource; +use App\Http\Resources\ListBookingJobResource; class ListBookingsJobProcessor { @@ -18,24 +14,25 @@ class ListBookingsJobProcessor /** @var ListsBookings */ private $listsBookings; - /** @var CreatesJobResult */ - private $createsJobResult; + /** @var UpdateJobResultProcessor */ + private $updateJobResultProcessor; /** * ListBookingsJobProcessor constructor. * @param ListsBookings $listsBookings - * @param CreatesJobResult $createsJobResult + * @param UpdateJobResultProcessor $updateJobResultProcessor */ - public function __construct(ListsBookings $listsBookings, CreatesJobResult $createsJobResult) + public function __construct(ListsBookings $listsBookings, UpdateJobResultProcessor $updateJobResultProcessor) { $this->listsBookings = $listsBookings; - $this->createsJobResult = $createsJobResult; + $this->updateJobResultProcessor = $updateJobResultProcessor; } /** * @param ListGenericJobObject $listGenericJobObject - * @return null|object + * @return void * @throws \App\Classes\Exceptions\MalformedRequestException + * @throws \App\Classes\Exceptions\JobResourceNotFoundException */ public function execute(ListGenericJobObject $listGenericJobObject) { @@ -43,15 +40,7 @@ class ListBookingsJobProcessor foreach ($query->items() as &$item) { $item['userInfo'] = $listGenericJobObject->getUserInfo(); } - - //cief todo: remove comments - $result = Helper::collectionResponse(BookingResource::collection($query)); - - // $result = new JobBookingCollectionResponse($query, $listGenericJobObject->getuserInfo()); - // $result = $this->collectionResponse(new BookingResourceCollection(BookingResource::collection($query), $listGenericJobObject->getuserInfo())); - - $create = $this->createsJobResult->execute($listGenericJobObject, json_encode($result)); - - return $create; + $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 index 041bb9c8..5e895ad8 100644 --- a/app/Classes/Modules/Documents/ControllersLogic/ListDocumentJobLogic.php +++ b/app/Classes/Modules/Documents/ControllersLogic/ListDocumentJobLogic.php @@ -4,15 +4,11 @@ namespace App\Classes\Modules\Documents\ControllersLogic; use App\Classes\General\Abstracts\AbstractControllerLogic; -use App\Classes\Modules\Documents\Services\ListsDocuments; +use App\Classes\Modules\Jobs\Services\CreatesJobResult; use App\Classes\Modules\Jobs\DataTransferObjects\ListGenericJobObject; use App\Classes\Jobs\ListDocumentsJob; -use App\Http\Resources\DocumentResource; -use ErrorException; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; -use App\Classes\General\Helper; -use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Auth; class ListDocumentJobLogic extends AbstractControllerLogic @@ -28,6 +24,19 @@ class ListDocumentJobLogic extends AbstractControllerLogic ]; } + /** @var CreatesJobResult */ + private $createsJobResult; + + /** + * ListDocumentJobLogic constructor. + * @param CreatesJobResult $createsJobResult + */ + public function __construct(CreatesJobResult $createsJobResult) + { + $this->createsJobResult = $createsJobResult; + } + + /** * @param Request $request * @return JsonResponse @@ -42,33 +51,25 @@ class ListDocumentJobLogic extends AbstractControllerLogic '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); - //cief todo: remove comments - // // Create your job instance with delay, so we can back here within delay and take control in our hands. - // $job = new ListDocuments($listGenericJobObject); - // $job->delay(now()->addSeconds(5)); - - // // Dispath your job with our custom_dispatch helper. This will return job id from jobs table - // // $jobId = $this->custom_dispatch($job); - - $result = []; $result['job_id'] = $jobId; + $this->createsJobResult->execute($listGenericJobObject); + return $this->response(['data' => $result]); } - - //cief todo: no longer need jobId - // function custom_dispatch($job): int { - // return app(\Illuminate\Contracts\Bus\Dispatcher::class)->dispatch($job); - // } } diff --git a/app/Classes/Modules/Documents/Processors/ListDocumentsJobProcessor.php b/app/Classes/Modules/Documents/Processors/ListDocumentsJobProcessor.php index eb7cf1c4..70777f0c 100644 --- a/app/Classes/Modules/Documents/Processors/ListDocumentsJobProcessor.php +++ b/app/Classes/Modules/Documents/Processors/ListDocumentsJobProcessor.php @@ -3,15 +3,10 @@ namespace App\Classes\Modules\Documents\Processors; use App\Classes\Modules\Documents\Services\ListsDocuments; -use App\Classes\Modules\Jobs\Services\CreatesJobResult; -use App\Classes\Exceptions\MalformedRequestException; +use App\Classes\Modules\Jobs\Processors\UpdateJobResultProcessor; use App\Classes\General\Helper; -use Illuminate\Support\Facades\Http; -use Illuminate\Support\Facades\Log; use App\Classes\Modules\Jobs\DataTransferObjects\ListGenericJobObject; -use App\Http\Controllers\Documents\ListDocumentsController; -use Illuminate\Http\Resources\Json\ResourceCollection; -use App\Http\Resources\DocumentResource; +use App\Http\Resources\ListDocumentJobResource; class ListDocumentsJobProcessor { @@ -19,24 +14,25 @@ class ListDocumentsJobProcessor /** @var ListsDocuments */ private $listsDocuments; - /** @var CreatesJobResult */ - private $createsJobResult; + /** @var UpdateJobResultProcessor */ + private $updateJobResultProcessor; /** * ListDocumentsJobProcessor constructor. * @param ListsDocuments $listsDocuments - * @param CreatesJobResult $createsJobResult + * @param UpdateJobResultProcessor $updateJobResultProcessor */ - public function __construct(ListsDocuments $listsDocuments, CreatesJobResult $createsJobResult) + public function __construct(ListsDocuments $listsDocuments, UpdateJobResultProcessor $updateJobResultProcessor) { $this->listsDocuments = $listsDocuments; - $this->createsJobResult = $createsJobResult; + $this->updateJobResultProcessor = $updateJobResultProcessor; } /** * @param ListGenericJobObject $listGenericJobObject - * @return null|object + * @return void * @throws \App\Classes\Exceptions\MalformedRequestException + * @throws \App\Classes\Exceptions\JobResourceNotFoundException */ public function execute(ListGenericJobObject $listGenericJobObject) { @@ -44,11 +40,8 @@ class ListDocumentsJobProcessor foreach ($query->items() as &$item) { $item['userInfo'] = $listGenericJobObject->getUserInfo(); } - - $result = Helper::collectionResponse(DocumentResource::collection($query)); - - $create = $this->createsJobResult->execute($listGenericJobObject, json_encode($result)); - - return $create; + $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 index 366fda8c..c4b72cf0 100644 --- a/app/Classes/Modules/Jobs/ControllersLogic/FetchJobResultLogic.php +++ b/app/Classes/Modules/Jobs/ControllersLogic/FetchJobResultLogic.php @@ -4,9 +4,8 @@ namespace App\Classes\Modules\Jobs\ControllersLogic; use App\Classes\General\Abstracts\AbstractControllerLogic; -use App\Classes\Modules\Jobs\Services\FetchesJobResult; +use App\Classes\Modules\Jobs\Processors\FetchesJobResultProcessor; use App\Http\Resources\JobResultResource; -use ErrorException; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; @@ -23,16 +22,16 @@ class FetchJobResultLogic extends AbstractControllerLogic ]; } - /** @var FetchesJobResult */ - private $fetchesJobResult; + /** @var FetchesJobResultProcessor */ + private $fetchesJobResultProcessor; /** * FetchJobResultLogic constructor. - * @param FetchesJobResult $fetchesJobResult + * @param FetchesJobResultProcessor $fetchesJobResultProcessor */ - public function __construct(FetchesJobResult $fetchesJobResult) + public function __construct(FetchesJobResultProcessor $fetchesJobResultProcessor) { - $this->fetchesJobResult = $fetchesJobResult; + $this->fetchesJobResultProcessor = $fetchesJobResultProcessor; } @@ -45,10 +44,8 @@ class FetchJobResultLogic extends AbstractControllerLogic */ public function logic(Request $request) : JsonResponse { - $query = $this->fetchesJobResult->execute(['job_id' => $request->route('job_id')]); - + $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 index 365cd316..953d77d7 100644 --- a/app/Classes/Modules/Jobs/DataTransferObjects/ListGenericJobObject.php +++ b/app/Classes/Modules/Jobs/DataTransferObjects/ListGenericJobObject.php @@ -2,7 +2,6 @@ namespace App\Classes\Modules\Jobs\DataTransferObjects; -use Illuminate\Http\Request; use App\Classes\General\Interfaces\DataTransferObject; class ListGenericJobObject implements DataTransferObject @@ -16,6 +15,12 @@ class ListGenericJobObject implements DataTransferObject /** @var string */ private $jobId; + /** @var string */ + private $requestSignature; + + /** @var string */ + private $resultSignature; + /** @var object */ private $userInfo; @@ -25,11 +30,13 @@ class ListGenericJobObject implements DataTransferObject /** @var string */ private $jobCommand; - public function __construct(string $name, array $payload, string $jobId, object $userInfo = null) + public function __construct(string $name, array $payload, string $requestSignature, ?string $resultSignature, string $jobId, object $userInfo = null) { $this->name = $name; $this->payload = $payload; $this->jobId = $jobId; + $this->requestSignature = $requestSignature; + $this->resultSignature = $resultSignature; $this->userInfo = $userInfo; } @@ -57,6 +64,22 @@ class ListGenericJobObject implements DataTransferObject return $this->jobId; } + /** + * @return string + */ + public function getRequestSignature(): string + { + return $this->requestSignature; + } + + /** + * @return string + */ + public function getResultSignature(): ?string + { + return $this->resultSignature; + } + /** * @return object */ @@ -81,10 +104,6 @@ class ListGenericJobObject implements DataTransferObject return $this->jobCommand; } - // public function setJobId(int $jobId) - // { - // $this->jobId = $jobId; - // } public function setJobCommandName(string $jobCommandName) { 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..e19456e7 --- /dev/null +++ b/app/Classes/Modules/Jobs/Processors/FetchesJobResultProcessor.php @@ -0,0 +1,45 @@ +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(!$res1->result){ + Log::info('Job id: '.$request->route('job_id')); + $res2 = $this->fetchesJobResult->execute(['request_signature' => $res1->request_signature, 'result_not_null' => true, 'order_by_id_desc' => true]); + Log::info('Job id: '.$res2->id." , request_signature: ".$res2->request_signature); + return $res2; + } + + 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..fff83bb0 --- /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 index 00acc1eb..e70e0e6a 100644 --- a/app/Classes/Modules/Jobs/Services/CreatesJobResult.php +++ b/app/Classes/Modules/Jobs/Services/CreatesJobResult.php @@ -10,18 +10,16 @@ class CreatesJobResult extends AbstractUpdateRecord { /** * @param ListGenericJobObject $listGenericJobObject - * @param string $result * @return \Illuminate\Database\Eloquent\Model * @throws \App\Classes\Exceptions\MalformedRequestException */ - public function execute(ListGenericJobObject $listGenericJobObject, string $result) + public function execute(ListGenericJobObject $listGenericJobObject) { $model = new JobResult(); $model->job_id = $listGenericJobObject->getJobId(); - $model->result = $result; + $model->request_signature = $listGenericJobObject->getRequestSignature(); + $model->result_signature = $listGenericJobObject->getResultSignature(); $model->url = $listGenericJobObject->getName(); - $model->job_command_name = $listGenericJobObject->getJobCommandName(); - $model->job_command = $listGenericJobObject->getJobCommand(); return $this->handler($model); } 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 index d317d7eb..654a360f 100644 --- a/app/Classes/Modules/Transactions/ControllersLogic/ListTransactionsJobLogic.php +++ b/app/Classes/Modules/Transactions/ControllersLogic/ListTransactionsJobLogic.php @@ -5,10 +5,11 @@ namespace App\Classes\Modules\Transactions\ControllersLogic; use App\Classes\General\Abstracts\AbstractControllerLogic; use App\Classes\Jobs\ListTransactionsJob; +use App\Classes\Modules\Jobs\Services\CreatesJobResult; use App\Classes\Modules\Jobs\DataTransferObjects\ListGenericJobObject; -use ErrorException; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; +use Illuminate\Support\Facades\Auth; class ListTransactionsJobLogic extends AbstractControllerLogic { @@ -22,6 +23,19 @@ class ListTransactionsJobLogic extends AbstractControllerLogic ]; } + /** @var CreatesJobResult */ + private $createsJobResult; + + /** + * ListTransactionsJobLogic constructor. + * @param CreatesJobResult $createsJobResult + */ + public function __construct(CreatesJobResult $createsJobResult) + { + $this->createsJobResult = $createsJobResult; + } + + /** * @param Request $request * @return JsonResponse @@ -30,10 +44,21 @@ class ListTransactionsJobLogic extends AbstractControllerLogic { $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(), - $jobId + $requestSignature, + null, + $jobId, + $userInfo ); ListTransactionsJob::dispatch($listGenericJobObject); @@ -41,6 +66,8 @@ class ListTransactionsJobLogic extends AbstractControllerLogic $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 index 36671c89..475d4715 100644 --- a/app/Classes/Modules/Transactions/Processors/ListTransactionsJobProcessor.php +++ b/app/Classes/Modules/Transactions/Processors/ListTransactionsJobProcessor.php @@ -3,14 +3,10 @@ namespace App\Classes\Modules\Transactions\Processors; use App\Classes\Modules\Transactions\Services\ListsTransactions; -use App\Classes\Modules\Jobs\Services\CreatesJobResult; -use App\Classes\Exceptions\MalformedRequestException; +use App\Classes\Modules\Jobs\Processors\UpdateJobResultProcessor; use App\Classes\General\Helper; -use Illuminate\Support\Facades\Http; -use Illuminate\Support\Facades\Log; use App\Classes\Modules\Jobs\DataTransferObjects\ListGenericJobObject; -use Illuminate\Http\Resources\Json\ResourceCollection; -use App\Http\Resources\TransactionResource; +use App\Http\Resources\ListTransactionJobResource; class ListTransactionsJobProcessor { @@ -18,33 +14,32 @@ class ListTransactionsJobProcessor /** @var ListsTransactions */ private $listsTransactions; - /** @var CreatesJobResult */ - private $createsJobResult; + /** @var UpdateJobResultProcessor */ + private $updateJobResultProcessor; /** * ListTransactionsJobProcessor constructor. * @param ListsTransactions $listsTransactions - * @param CreatesJobResult $createsJobResult + * @param UpdateJobResultProcessor $updateJobResultProcessor */ - public function __construct(ListsTransactions $listsTransactions, CreatesJobResult $createsJobResult) + public function __construct(ListsTransactions $listsTransactions, UpdateJobResultProcessor $updateJobResultProcessor) { $this->listsTransactions = $listsTransactions; - $this->createsJobResult = $createsJobResult; + $this->updateJobResultProcessor = $updateJobResultProcessor; } /** * @param ListGenericJobObject $listGenericJobObject - * @return null|object + * @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']]); - $result = Helper::collectionResponse(TransactionResource::collection($query)); - - $create = $this->createsJobResult->execute($listGenericJobObject, json_encode($result)); - - return $create; + $resultCurrent = Helper::collectionResponse(ListTransactionJobResource::collection($query)); + $this->updateJobResultProcessor->execute($listGenericJobObject, $resultCurrent); } } + diff --git a/app/Http/Resources/BookingResource.php b/app/Http/Resources/BookingResource.php index c3c2e24d..70fbc95c 100644 --- a/app/Http/Resources/BookingResource.php +++ b/app/Http/Resources/BookingResource.php @@ -11,19 +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\Http\Resources\Json\AnonymousResourceCollection; -use Illuminate\Support\Facades\Log; class BookingResource extends JsonResource { - private $userInfo; - - public function __construct($resource, $userInfo = null) - { - parent::__construct($resource); - $this->userInfo = $userInfo ?? ($resource->userInfo ?? null); - } - /** * Transform the resource into an array. * @@ -35,7 +25,7 @@ class BookingResource extends JsonResource { return [ 'id' => $this->id, - 'company' => new CompanyResource($this->company, $this->userInfo), + 'company' => new CompanyResource($this->company), 'bank' => new BankResource($this->bank), 'service' => new ServiceTypeResource($this->service), 'marking' => $this->marking, diff --git a/app/Http/Resources/CompanyResource.php b/app/Http/Resources/CompanyResource.php index df3bcf49..eff2bd1b 100644 --- a/app/Http/Resources/CompanyResource.php +++ b/app/Http/Resources/CompanyResource.php @@ -15,18 +15,9 @@ 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 { - private $userInfo; - - public function __construct($resource, $userInfo = null) - { - parent::__construct($resource); - $this->userInfo = $userInfo; - } - /** * Transform the resource into an array. * @@ -41,26 +32,6 @@ class CompanyResource extends JsonResource $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; - } - - //cief todo: remove - // Log::error('CompanyResource 1: '. json_encode($userInfoEmail)); - // Log::error('CompanyResource 2: '. json_encode($userInfoType)); - - if(!is_null($userInfoEmail) && !is_null($userInfoType)){ - $userResource = new UserResource($userInfoType === RoleTypes::USER ? $this->employees()->where('email', '=', $userInfoEmail)->first() : $this->employees()->orderBy('id', 'DESC')->first()); - } - return [ 'id' => $this->id, 'name' => $this->name, @@ -71,8 +42,7 @@ class CompanyResource extends JsonResource 'status' => (int) $this->status, 'contact' => new ContactResource ($this->when($this->has('contacts'), $this->contacts->first())), 'address' => new AddressResource($this->when($this->has('addresses'), $this->addresses->where('billing', true)->first())), - //cief todo: this one need to decide what to do to replace Auth:user() when it is run by job queue - 'employee' => $userResource, + 'employee' => new UserResource(Auth::user()->type === RoleTypes::USER ? $this->employees()->where('email', '=', Auth::user()->email)->first() : $this->employees()->orderBy('id', 'DESC')->first()), 'identification' => new 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){ diff --git a/app/Http/Resources/DocumentResource.php b/app/Http/Resources/DocumentResource.php index 6f9ade71..c0f801bb 100644 --- a/app/Http/Resources/DocumentResource.php +++ b/app/Http/Resources/DocumentResource.php @@ -3,14 +3,8 @@ 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; -use Illuminate\Support\Facades\Log; -use Illuminate\Support\Facades\Auth; -use Illuminate\Http\Resources\Json\AnonymousResourceCollection; class DocumentResource extends JsonResource { @@ -27,7 +21,7 @@ class DocumentResource extends JsonResource 'reference' => $this->reference, 'status' => (int) $this->status, 'document_type' => $this->document_type, - 'owner' => $this->relationLoaded('owner') ? ($this->owner instanceof Booking ? new BookingResource($this->owner, $this->userInfo) : new CompanyResource($this->owner, $this->userInfo)) : null, + 'owner' => $this->relationLoaded('owner') ? ($this->owner instanceof Booking ? new BookingResource($this->owner) : new CompanyResource($this->owner)) : 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/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/resources/assets/vue/vuex/modules/crudRequestV2.js b/resources/assets/vue/vuex/modules/crudRequestV2.js index 2445190e..355b1edb 100644 --- a/resources/assets/vue/vuex/modules/crudRequestV2.js +++ b/resources/assets/vue/vuex/modules/crudRequestV2.js @@ -1,35 +1,39 @@ export default { actions: { crudRequestV2({getters, dispatch}, {endpoint, method, parameters}){ - 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 - } - }).then(response => { - if(response.status === 401 && window.location.href !== route('login') && window.location.href.indexOf(route('last_mile_delivery.login')) <= -1){ - dispatch('userAuthentication', {access_token: '', redirect_url: [7, 8].includes(getters.getCompanyModuleType) ? route('last_mile_delivery.login') : route('login')}); + 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 response; + // 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; + + }) + }); } } }