Merge branch 'master' into dillon/34.1-jenkins-vapor

This commit is contained in:
Dillon Ngo
2024-03-22 14:05:47 +08:00
113 changed files with 2439 additions and 364 deletions
@@ -69,7 +69,7 @@ abstract class AbstractControllerLogic
} catch (ErrorException|GeneralExceptions $exception){
if ($exception instanceof JobResourceNotFoundException) {
Log::error(sprintf(
Log::channel('vue_polling')->info(sprintf(
"Uncaught exception '%s' with message '%s' in %s:%d",
get_class($exception),
$exception->getMessage(),
@@ -0,0 +1,24 @@
<?php
namespace App\Classes\General\Eloquent\Filters;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\TransactionType;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\DB;
class DoesNotHaveRefundInProgress implements Filter
{
/**
* @param Builder $builder
* @param $value
* @return Builder|mixed
*/
public static function apply(Builder $builder, $value)
{
return $builder->whereDoesntHave('transactions', function ($query) {
return $query->where('type', TransactionType::REFUND)->whereIn('status', [ApprovalStatus::PENDING_SUBMISSION, ApprovalStatus::PENDING_VERIFICATION]);
});
}
}
@@ -0,0 +1,18 @@
<?php
namespace App\Classes\General\Eloquent\Filters;
use Illuminate\Database\Eloquent\Builder;
class GroupByImportedDate implements Filter
{
/**
* @param Builder $builder
* @param $value
* @return mixed
*/
public static function apply(Builder $builder, $value)
{
return $builder->groupby('imported_date');
}
}
@@ -0,0 +1,18 @@
<?php
namespace App\Classes\General\Eloquent\Filters;
use Illuminate\Database\Eloquent\Builder;
class ImportedDateFrom implements Filter
{
/**
* @param Builder $builder
* @param $value
* @return mixed
*/
public static function apply(Builder $builder, $value)
{
return $builder->whereDate('imported_date', '>=', date('Y-m-d',strtotime($value)));
}
}
@@ -0,0 +1,18 @@
<?php
namespace App\Classes\General\Eloquent\Filters;
use Illuminate\Database\Eloquent\Builder;
class ImportedDateTo implements Filter
{
/**
* @param Builder $builder
* @param $value
* @return mixed
*/
public static function apply(Builder $builder, $value)
{
return $builder->whereDate('imported_date', '<=', date('Y-m-d',strtotime($value)));
}
}
@@ -0,0 +1,24 @@
<?php
namespace App\Classes\General\Eloquent\Filters;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\DB;
class IsNotFullyRefunded implements Filter
{
/**
* @param Builder $builder
* @param $value
* @return Builder|mixed
*/
public static function apply(Builder $builder, $value)
{
return $builder->withSum(['transactions as total_refund_amount' => function($q) {
$q->refunds()->where('status', ApprovalStatus::APPROVED);
}], 'original_amount')
->having('total_refund_amount', '<', DB::raw('original_amount'));
}
}
@@ -0,0 +1,22 @@
<?php
namespace App\Classes\General\Eloquent\Filters;
use Illuminate\Database\Eloquent\Builder;
class StatementTransactionInvoiceReference implements Filter
{
/**
* @param Builder $builder
* @param $value
* @return Builder|mixed
*/
public static function apply(Builder $builder, $value)
{
return $builder->whereHas('owners', function ($query) use ($value) {
return $query->where('Invoice_reference', $value);
});
}
}
@@ -0,0 +1,22 @@
<?php
namespace App\Classes\General\Eloquent\Filters;
use Illuminate\Database\Eloquent\Builder;
class StatementTransactionOwnerReference implements Filter
{
/**
* @param Builder $builder
* @param $value
* @return Builder|mixed
*/
public static function apply(Builder $builder, $value)
{
return $builder->whereHas('owners', function ($query) use ($value) {
return $query->where('owner_reference', $value);
});
}
}
@@ -0,0 +1,22 @@
<?php
namespace App\Classes\General\Eloquent\Filters;
use Illuminate\Database\Eloquent\Builder;
class StatementTransactionReceiptReference implements Filter
{
/**
* @param Builder $builder
* @param $value
* @return Builder|mixed
*/
public static function apply(Builder $builder, $value)
{
return $builder->whereHas('owners', function ($query) use ($value) {
return $query->where('receipt_reference', $value);
});
}
}
@@ -0,0 +1,12 @@
<?php
namespace App\Classes\General\Interfaces;
use Illuminate\Database\Eloquent\Relations\MorphMany;
interface KeyValueInterface
{
public function attributes(): morphMany;
}
+2
View File
@@ -16,6 +16,8 @@ class ListBookingsJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public $timeout = 900;
/** @var ListGenericJobObject */
private $listGenericJobObject;
+2
View File
@@ -16,6 +16,8 @@ class ListDocumentsJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public $timeout = 900;
/** @var ListGenericJobObject */
private $listGenericJobObject;
+2
View File
@@ -16,6 +16,8 @@ class ListTransactionsJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public $timeout = 900;
/** @var ListGenericJobObject */
private $listGenericJobObject;
@@ -0,0 +1,70 @@
<?php
namespace App\Classes\Jobs;
use App\Classes\Modules\Accounts\DataTransferObjects\KeyValuePairObject;
use App\Classes\Modules\Accounts\Services\CreatesKeyValuePair;
use App\Classes\Notifications\WelcomeVoucherEmail;
use App\Models\User;
use App\Models\Voucher;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class SendWelcomeVoucherEmail implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/** @var User */
private $user;
/** @var Voucher */
private $voucher;
/** @var int */
private $emailSentCount;
/**
* SendWelcomeVoucherEmail constructor.
* @param User $user
* @param Voucher $voucher
* @param int $emailSentCount
*/
public function __construct(User $user, Voucher $voucher, int $emailSentCount = 1)
{
$this->user = $user;
$this->voucher = $voucher;
$this->emailSentCount = $emailSentCount;
}
public function handle()
{
$currentDatetime = Carbon::now();
$dateToCompare = Carbon::parse($this->voucher->end_date);
if (!$this->user->hasAttribute($this->voucher->code."_EMAIL_COUNT")
&& $this->user->rewards->where('voucher_id', $this->voucher->id)->count() > 0
&& $currentDatetime->isBefore($dateToCompare))
{
//Key #1
$keyValuePairObject = new KeyValuePairObject(
$this->voucher->code."_EMAIL_COUNT",
$this->emailSentCount
);
(App()->make(CreatesKeyValuePair::class))->execute($this->user, $keyValuePairObject);
//Key #2
$keyValuePairObject = new KeyValuePairObject(
$this->voucher->code."_EMAIL_DATE_".$this->emailSentCount,
Carbon::now()
);
(App()->make(CreatesKeyValuePair::class))->execute($this->user, $keyValuePairObject);
$this->user->notify(new WelcomeVoucherEmail($this->user, $this->voucher));
}
}
}
+3 -4
View File
@@ -57,16 +57,15 @@ class UpdatePerfexCRMInvoice implements ShouldQueue
$number = 'EXC-'.$number;
$invoice = (App()->make(FetchesPerfexCRMInvoice::class))->execute($customer->userid,"INV-", $number);
Log::error(json_encode('UpdatePerfexCRMInvoice debug $number: '.$number));
Log::channel('perfex_crm')->info(('UpdatePerfexCRMInvoice debug $number: '.$number));
if(is_null($invoice)){
$result = (App()->make(CreatePerfexCRMInvoiceProcessor::class))->execute($transaction);
if ($result) {
$invoiceId = $result->payload['id'];
} else {
// Log::error(json_encode('UpdatePerfexCRMInvoice CreatePerfexCRMInvoiceProcessor failed'));
$log['message'] = 'UpdatePerfexCRMInvoice CreatePerfexCRMInvoiceProcessor failed';
Helper::debugLogger($log);
Log::channel('perfex_crm')->info($log);
}
}
else{
@@ -75,7 +74,7 @@ class UpdatePerfexCRMInvoice implements ShouldQueue
//This only run when invoice already exist and the invoice does not have a PAID status
if($invoiceStatus != PerfexCRMInvoiceStatus::PAID){
Log::error(json_encode('UpdatePerfexCRMInvoice debug $this->updatePerfexCRMInvoiceObject->getProjectId(): '.$this->updatePerfexCRMInvoiceObject->getProjectId()));
Log::channel('perfex_crm')->info('UpdatePerfexCRMInvoice debug $this->updatePerfexCRMInvoiceObject->getProjectId(): '.$this->updatePerfexCRMInvoiceObject->getProjectId());
//update invoice
(App()->make(UpdatesPerfexCRMInvoice::class))->execute($invoice, $this->updatePerfexCRMInvoiceObject->getProjectId());
@@ -0,0 +1,49 @@
<?php
namespace App\Classes\Modules\Accounting\ControllersLogic;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Resources\TransactionMappingLogResource;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Accounting\Services\ListTransactionMappingLogs;
class HistoryImportedTransactionMappedControllerLogic extends AbstractControllerLogic
{
/**
* @return array
*/
protected function notification(): array
{
return [
'title' => 'Retrieved History Imported Invoices',
'message' => 'You have successfully retrieved history imported invoices'
];
}
/** @var ListTransactionMappingLogs */
private $listTransactionMappingLogs;
/**
* UpdateAnnouncementLogic constructor.
* @param ListTransactionMappingLogs $listTransactionMappingLogs
*/
public function __construct(
ListTransactionMappingLogs $listTransactionMappingLogs
) {
$this->listTransactionMappingLogs = $listTransactionMappingLogs;
}
/**
* @param Request $request
* @return JsonResponse
*/
public function logic(Request $request): JsonResponse
{
$query = $this->listTransactionMappingLogs->execute($this->listTransactionMappingLogs->deserializeFilters($request->input('filters')));
return $this->collectionResponse(TransactionMappingLogResource::collection($query));
}
}
@@ -2,16 +2,14 @@
namespace App\Classes\Modules\Accounting\ControllersLogic;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Accounting\Services\FetchesBankStatementTransaction;
use App\Http\Resources\BankStatementTransactionResource;
use App\Classes\Modules\Accounting\Services\UpdatesBankStatementTransactionOwnerStatus;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\StatementTransactionOwnerType;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use App\Classes\Modules\Transactions\Services\UpdatesTransactionStatus;
use Illuminate\Http\JsonResponse;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Http\Resources\BankStatementTransactionOwnerResource;
use App\Classes\ValueObjects\Constants\StatementTransactionOwnerType;
use App\Classes\Modules\Accounting\Services\FetchesBankStatementTransactionOwner;
use App\Classes\Modules\Accounting\Services\UpdatesBankStatementTransactionOwnerStatus;
class UpdateStatementTransactionStatusLogic extends AbstractControllerLogic
{
@@ -27,29 +25,23 @@ class UpdateStatementTransactionStatusLogic extends AbstractControllerLogic
];
}
/** @var FetchesBankStatementTransaction */
private $fetchesBankStatementTransaction;
/** @var FetchesBankStatementTransactionOwner */
private $fetchesBankStatementTransactionOwner;
/** @var UpdatesBankStatementTransactionOwnerStatus */
private $updatesBankStatementTransactionOwnerStatus;
/** @var UpdatesTransactionStatus */
private $updatesTransactionStatus;
/**
* UpdateAnnouncementLogic constructor.
* @param FetchesBankStatementTransaction $fetchesBankStatementTransaction
* @param FetchesBankStatementTransactionOwner $fetchesBankStatementTransactionOwner
* @param UpdatesBankStatementTransactionOwnerStatus $updatesBankStatementTransactionOwnerStatus
* @param UpdatesTransactionStatus $updatesTransactionStatus
*/
public function __construct(
FetchesBankStatementTransaction $fetchesBankStatementTransaction,
UpdatesBankStatementTransactionOwnerStatus $updatesBankStatementTransactionOwnerStatus,
UpdatesTransactionStatus $updatesTransactionStatus
FetchesBankStatementTransactionOwner $fetchesBankStatementTransactionOwner,
UpdatesBankStatementTransactionOwnerStatus $updatesBankStatementTransactionOwnerStatus
) {
$this->fetchesBankStatementTransaction = $fetchesBankStatementTransaction;
$this->fetchesBankStatementTransactionOwner = $fetchesBankStatementTransactionOwner;
$this->updatesBankStatementTransactionOwnerStatus = $updatesBankStatementTransactionOwnerStatus;
$this->updatesTransactionStatus = $updatesTransactionStatus;
}
/**
@@ -61,21 +53,10 @@ class UpdateStatementTransactionStatusLogic extends AbstractControllerLogic
*/
public function logic(Request $request): JsonResponse
{
$statementTrasaction = $this->fetchesBankStatementTransaction->execute(['id' => $request->route('id')]);
$statementTrasactionOwner = $statementTrasaction->owners->first();
$statementTrasactionOwner = $this->fetchesBankStatementTransactionOwner->execute(['id' => $request->route('id')]);
$this->updatesBankStatementTransactionOwnerStatus->execute($statementTrasactionOwner, $request->route('status') == 'approve' ? ApprovalStatus::APPROVED : ApprovalStatus::REJECTED);
// todo-new: approve payments status, need to check the owner(if system is shipping, need to api with shipping portal)
// if ($request->route('status') == 'approve') {
// if ($statementTrasactionOwner->transaction->type === StatementTransactionOwnerType::SALES) {
// if ($statementTrasactionOwner->owner->status === ApprovalStatus::PENDING_VERIFICATION) {
// $this->updatesTransactionStatus->execute($statementTrasactionOwner->owner, ApprovalStatus::APPROVED);
// }
// }
// }
return $this->resourceResponse(new BankStatementTransactionResource($statementTrasaction));
return $this->resourceResponse(new BankStatementTransactionOwnerResource($statementTrasactionOwner));
}
}
@@ -13,6 +13,7 @@ class ListShippingPortalTransactions
{
try {
$url = 'https://izyim.cief-malaysia.com/public/api/v1/transactions/mappable/query/with-details';
// $url = 'http://127.0.0.1:8001/public/api/v1/transactions/mappable/query/with-details';
$client = new \GuzzleHttp\Client(['verify' => false]);
$response = $client->request('GET', $url . '?api-key=510acd13d8d24375cf038ad626c282565451461a9c2399357e0b65365300787e&filters=' . json_encode($filters));
$body = $response->getBody();
@@ -0,0 +1,31 @@
<?php
namespace App\Classes\Modules\Accounting\Services;
use App\Models\StatementTransactionOwner;
use Illuminate\Database\Eloquent\Builder;
use App\Classes\General\Eloquent\AbstractFetchRecord;
class FetchesBankStatementTransactionOwner extends AbstractFetchRecord
{
/** @var StatementTransactionOwner */
private $repository;
/**
* FetchesBankStatementDetails constructor.
* @param StatementTransactionOwner $repository
*/
public function __construct(StatementTransactionOwner $repository)
{
$this->repository = $repository;
}
/**
* @return Builder
*/
public function getRepository(): Builder
{
return $this->repository->newQuery();
}
}
@@ -0,0 +1,32 @@
<?php
namespace App\Classes\Modules\Accounting\Services;
use App\Models\TransactionMappingLog;
use Illuminate\Database\Eloquent\Builder;
use App\Classes\General\Eloquent\AbstractListRecord;
class ListTransactionMappingLogs extends AbstractListRecord
{
/** @var TransactionMappingLog */
private $repository;
/**
* ListsBankStatementDetails constructor.
* @param TransactionMappingLog $repository
*/
public function __construct(TransactionMappingLog $repository)
{
$this->repository = $repository;
}
/**
* @return Builder
*/
public function getRepository(): Builder
{
return $this->repository->newQuery();
}
}
@@ -30,6 +30,7 @@ use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use App\Classes\Modules\Segments\Services\CreatesSeasonalSegment;
use App\Classes\ValueObjects\Constants\Vouchers;
class CreateCustomerLogic extends AbstractControllerLogic
{
@@ -162,7 +163,7 @@ class CreateCustomerLogic extends AbstractControllerLogic
$this->newCustomerToVoucherifyProcessor->execute($company->id, $user, true);
$this->createVoucherProcessor->execute($user, 'WELCOME50%OFF');
$this->createVoucherProcessor->execute($user, Vouchers::WELCOME_50_PERCENT_OFF);
return $this->response($this->authenticationProcessor->execute($request, false));
@@ -9,6 +9,9 @@ use App\Classes\Modules\Accounts\Services\CompletesEmailVerificationAttempt;
use App\Classes\Modules\Accounts\Services\FetchesEmailVerificationAttempt;
use App\Classes\Modules\Accounts\Services\VerifiesUser;
use App\Classes\Modules\Accounts\Standards\Criteria\EmailVerificationActiveAttemptExists;
use App\Classes\Modules\Vouchers\Services\FetchesVoucher;
use App\Classes\Jobs\SendWelcomeVoucherEmail;
use App\Classes\ValueObjects\Constants\Vouchers;
use App\Models\UserEmailVerification;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
@@ -36,19 +39,29 @@ class UserEmailVerificationLogic extends AbstractControllerLogic
/** @var VerifiesUser */
private $verifiesUser;
/** @var SendWelcomeVoucherEmail */
private $sendWelcomeVoucherEmail;
/** @var FetchesVoucher */
private $fetchesVoucher;
/**
* UserEmailVerificationLogic constructor.
* @param EmailVerificationActiveAttemptExists $emailVerificationActiveAttemptExists
* @param CompletesEmailVerificationAttempt $completesEmailVerificationAttempt
* @param FetchesEmailVerificationAttempt $fetchesEmailVerificationAttempt
* @param VerifiesUser $verifiesUser
* @param SendWelcomeVoucherEmail $sendWelcomeVoucherEmail
* @param FetchesVoucher $fetchesVoucher
*/
public function __construct(EmailVerificationActiveAttemptExists $emailVerificationActiveAttemptExists, CompletesEmailVerificationAttempt $completesEmailVerificationAttempt, FetchesEmailVerificationAttempt $fetchesEmailVerificationAttempt, VerifiesUser $verifiesUser)
public function __construct(EmailVerificationActiveAttemptExists $emailVerificationActiveAttemptExists, CompletesEmailVerificationAttempt $completesEmailVerificationAttempt, FetchesEmailVerificationAttempt $fetchesEmailVerificationAttempt, VerifiesUser $verifiesUser, SendWelcomeVoucherEmail $sendWelcomeVoucherEmail, FetchesVoucher $fetchesVoucher)
{
$this->emailVerificationActiveAttemptExists = $emailVerificationActiveAttemptExists;
$this->completesEmailVerificationAttempt = $completesEmailVerificationAttempt;
$this->fetchesEmailVerificationAttempt = $fetchesEmailVerificationAttempt;
$this->verifiesUser = $verifiesUser;
$this->sendWelcomeVoucherEmail = $sendWelcomeVoucherEmail;
$this->fetchesVoucher = $fetchesVoucher;
}
/**
@@ -68,9 +81,19 @@ class UserEmailVerificationLogic extends AbstractControllerLogic
$this->completesEmailVerificationAttempt->execute($attempt);
$this->verifiesUser->execute($attempt->user);
$user = $attempt->user;
$this->verifiesUser->execute($user);
// if (env('SENDING_EMAIL_WELCOME_VOUCHER_ENABLED', false)){
if (app()->environment('production') && env('SENDING_EMAIL_WELCOME_VOUCHER_ENABLED', false)){
try{ //In case voucher got deleted unintentionally
$voucher = $this->fetchesVoucher->execute(['code' => Vouchers::WELCOME_50_PERCENT_OFF]);
if($voucher) $this->sendWelcomeVoucherEmail::dispatch($user, $voucher, 1);
}
catch(\Exception $e){}
}
return $this->response([]);
}
}
}
@@ -0,0 +1,44 @@
<?php
namespace App\Classes\Modules\Accounts\DataTransferObjects;
use App\Classes\General\Interfaces\DataTransferObject;
class KeyValuePairObject implements DataTransferObject
{
/** @var string */
private $key;
/** @var string */
private $value;
/**
* KeyValuePairObject constructor.
* @param string $key
* @param string $value
*/
public function __construct(string $key, string $value)
{
$this->key = $key;
$this->value = $value;
}
/**
* @return string
*/
public function getKey(): string
{
return $this->key;
}
/**
* @return string
*/
public function getValue(): string
{
return $this->value;
}
}
@@ -0,0 +1,28 @@
<?php
namespace App\Classes\Modules\Accounts\Services;
use App\Classes\General\Eloquent\AbstractUpdateRelationshipRecord;
use App\Classes\General\Interfaces\KeyValueInterface;
use App\Classes\Modules\Accounts\DataTransferObjects\KeyValuePairObject;
use App\Models\KeyValuePair;
class CreatesKeyValuePair extends AbstractUpdateRelationshipRecord
{
/**
* @param KeyValueInterface $kv
* @param KeyValuePairObject $object
* @return \Illuminate\Database\Eloquent\Model
* @throws \App\Classes\Exceptions\MalformedRequestException
*/
public function execute(KeyValueInterface $kv, KeyValuePairObject $object) {
$model = new KeyValuePair();
$model->key = $object->getKey();
$model->value = $object->getValue();
return $this->handler($kv->attributes(), $model);
}
}
@@ -19,6 +19,7 @@ use App\Classes\ValueObjects\Constants\PaymentMethodType;
use App\Classes\ValueObjects\Constants\TransactionType;
use App\Classes\Modules\Currencies\DataTransferObjects\CurrencyConversionObject;
use App\Http\Resources\TransactionResource;
use App\Classes\Modules\Bookings\Services\CalculatesBookingRefundAmount;
use App\Classes\Modules\Transactions\Processors\CreateCashBackTransactionProcessor;
use App\Classes\Modules\Vouchers\Processors\Voucherify\BookingToVoucherifyProcessor;
@@ -77,6 +78,9 @@ class CreateBookingPaymentLogic extends AbstractControllerLogic
/** @var BookingToVoucherifyProcessor */
private $bookingToVoucherifyProcessor;
/** @var CalculatesBookingRefundAmount */
private $calculatesBookingRefundAmount;
/**
* CreateBookingPaymentLogic constructor.
* @param FetchesBookingQuotation $fetchBookingQuotation
@@ -90,8 +94,9 @@ class CreateBookingPaymentLogic extends AbstractControllerLogic
* @param CreateCashBackTransactionProcessor $createCashBackTransactionProcessor
* @param RecalculatesWalletBalance $recalculatesWalletBalance
* @param BookingToVoucherifyProcessor $bookingToVoucherifyProcessor
* @param CalculatesBookingRefundAmount $calculatesBookingRefundAmount
*/
public function __construct(FetchesBookingQuotation $fetchBookingQuotation, FetchesCompanyPaymentAttemptLimit $fetchesCompanyPaymentAttemptLimit, GeneratesTransactionBillNumber $generatesTransactionBillNumber, CreatesTransaction $createsTransaction, CalculatesBookingOutstanding $calculatesBookingOutstanding, CreatesBillplzBill $createsBillplzBill, UpdatesWalletBalance $updatesWalletBalance, UpdatesTransactionStatus $updatesTransactionStatus, CreateCashBackTransactionProcessor $createCashBackTransactionProcessor, RecalculatesWalletBalance $recalculatesWalletBalance, BookingToVoucherifyProcessor $bookingToVoucherifyProcessor)
public function __construct(FetchesBookingQuotation $fetchBookingQuotation, FetchesCompanyPaymentAttemptLimit $fetchesCompanyPaymentAttemptLimit, GeneratesTransactionBillNumber $generatesTransactionBillNumber, CreatesTransaction $createsTransaction, CalculatesBookingOutstanding $calculatesBookingOutstanding, CreatesBillplzBill $createsBillplzBill, UpdatesWalletBalance $updatesWalletBalance, UpdatesTransactionStatus $updatesTransactionStatus, CreateCashBackTransactionProcessor $createCashBackTransactionProcessor, RecalculatesWalletBalance $recalculatesWalletBalance, BookingToVoucherifyProcessor $bookingToVoucherifyProcessor, CalculatesBookingRefundAmount $calculatesBookingRefundAmount)
{
$this->fetchBookingQuotation = $fetchBookingQuotation;
$this->fetchesCompanyPaymentAttemptLimit = $fetchesCompanyPaymentAttemptLimit;
@@ -104,6 +109,7 @@ class CreateBookingPaymentLogic extends AbstractControllerLogic
$this->createCashBackTransactionProcessor = $createCashBackTransactionProcessor;
$this->recalculatesWalletBalance = $recalculatesWalletBalance;
$this->bookingToVoucherifyProcessor = $bookingToVoucherifyProcessor;
$this->calculatesBookingRefundAmount = $calculatesBookingRefundAmount;
}
/**
@@ -119,7 +125,7 @@ class CreateBookingPaymentLogic extends AbstractControllerLogic
$conversionObject = new CurrencyConversionObject(floatval(str_replace(',', '', $request->input('amount'))), $booking->convertible_currency_id, $booking->service_id, $booking->fix_currency_id === 1 ? 0:1, PaymentMethodType::PAYMENT_METHODS[$request->input('payment_method')]);
$outstanding = $this->calculatesBookingOutstanding->execute($booking);
$outstanding = $this->calculatesBookingOutstanding->execute($booking) + $this->calculatesBookingRefundAmount->execute($booking, $booking->fix_currency_id);
if($conversionObject->getAmount() > round($outstanding, 2)) throw new MalformedRequestException('Your payment must not be greater than '. $outstanding .'.');
@@ -15,10 +15,10 @@ use App\Classes\Modules\Transactions\Services\CreatesTransaction;
use App\Classes\Modules\Transactions\Services\FetchesTransaction;
use App\Classes\Modules\Bookings\Services\FetchesBookingQuotation;
use App\Classes\Modules\Transactions\Services\UpdatesTransactionStatus;
use App\Classes\Modules\Bookings\Services\CalculatesBookingRefundAmount;
use App\Classes\Modules\Transactions\DataTransferObjects\TransactionObject;
use App\Classes\Modules\Transactions\Services\GeneratesTransactionBillNumber;
use App\Classes\Modules\Transactions\DataTransferObjects\TransactionRefundCalculationObject;
use App\Classes\ValueObjects\Constants\PaymentMethodType;
class CreateBookingRefundLogic extends AbstractControllerLogic
{
@@ -48,9 +48,6 @@ class CreateBookingRefundLogic extends AbstractControllerLogic
/** @var CreatesTransaction */
private $createsTransaction;
/** @var CalculatesBookingRefundAmount */
private $calculatesBookingRefundAmount;
/**
* CreateBookingPaymentLogic constructor.
* @param FetchesBookingQuotation $fetchBookingQuotation
@@ -58,16 +55,14 @@ class CreateBookingRefundLogic extends AbstractControllerLogic
* @param UpdatesTransactionStatus $updatesTransactionStatus
* @param GeneratesTransactionBillNumber $generatesTransactionBillNumber
* @param CreatesTransaction $createsTransaction
* @param CalculatesBookingRefundAmount $calculatesBookingRefundAmount
*/
public function __construct(FetchesBookingQuotation $fetchBookingQuotation, FetchesTransaction $fetchesTransaction, UpdatesTransactionStatus $updatesTransactionStatus, GeneratesTransactionBillNumber $generatesTransactionBillNumber, CreatesTransaction $createsTransaction, CalculatesBookingRefundAmount $calculatesBookingRefundAmount)
public function __construct(FetchesBookingQuotation $fetchBookingQuotation, FetchesTransaction $fetchesTransaction, UpdatesTransactionStatus $updatesTransactionStatus, GeneratesTransactionBillNumber $generatesTransactionBillNumber, CreatesTransaction $createsTransaction)
{
$this->fetchBookingQuotation = $fetchBookingQuotation;
$this->fetchesTransaction = $fetchesTransaction;
$this->updatesTransactionStatus = $updatesTransactionStatus;
$this->generatesTransactionBillNumber = $generatesTransactionBillNumber;
$this->createsTransaction = $createsTransaction;
$this->calculatesBookingRefundAmount = $calculatesBookingRefundAmount;
}
/**
@@ -80,25 +75,30 @@ class CreateBookingRefundLogic extends AbstractControllerLogic
$transaction = $this->fetchesTransaction->execute(['id' => $request->route('payment_id')]);
if ($transaction->transactions()->bills()->first()) {
throw new MalformedRequestException('Booking under white form cannot request for refund');
}
$booking = $transaction->owner;
$billNumber = $this->generatesTransactionBillNumber->execute('RFD-');
$refund = $transaction->transactions()->refunds()->sum('amount');
$refund = $transaction->transactions()->refunds()->whereIn('status', [ApprovalStatus::PENDING_VERIFICATION, ApprovalStatus::APPROVED])->sum('original_amount');
if($refund + $request->input('amount') > $transaction->original_amount) throw new MalformedRequestException('Your refund must not be greater than '. $transaction->original_amount .'.');
$amount = $transaction->booking->fix_currency_id == 1 ? $request->input('amount') : $request->input('amount') / $transaction->currency_rate;
// $transactionRefundCalculationObject = new TransactionRefundCalculationObject($booking, $transaction, $request->input('amount'));
// $transactionRefundCalculationObject->init();
$transactionRefundCalculationObject = new TransactionRefundCalculationObject($booking, $transaction, $amount);
$transactionRefundCalculationObject->init();
$refundAmount = bcdiv($request->input('amount'), $transaction->currency_rate, 7);
// refund service charges if is fully refund
$refundTotal = ($refund + $request->input('amount')) == $transaction->original_amount ? $refundAmount + $transaction->service_charge + $transaction->tax : $refundAmount;
$object = new TransactionObject($billNumber, TransactionType::REFUND, 1, $booking->company->id,
1, $transactionRefundCalculationObject->getConversionObject()->getPaymentMethod(),
$transactionRefundCalculationObject->getRefundTotalAmount(), $transactionRefundCalculationObject->getAmount(), 1,
$transactionRefundCalculationObject->getConversionObject()->getCurrencyId(), $transactionRefundCalculationObject->getTransaction()->currency_rate,
$transactionRefundCalculationObject->getRefundTax(), $transactionRefundCalculationObject->getRefundServiceCharge(), null, ApprovalStatus::PENDING_VERIFICATION, [], $transaction->bill_no);
1, PaymentMethodType::CASH,
$refundTotal, $request->input('amount'), 1,
$transaction->original_currency_id, $transaction->currency_rate,
0, 0, null, ApprovalStatus::PENDING_VERIFICATION, [], $transaction->bill_no);
$transaction = $this->createsTransaction->execute($transaction, $object);
@@ -18,7 +18,7 @@ class FetchBookingLogic extends AbstractControllerLogic
*/
protected function notification():array {
return [
'title' => 'Retrieved Address',
'title' => 'Retrieved Booking',
'message' => 'You have successfully retrieved a Address'
];
}
@@ -14,6 +14,7 @@ use App\Classes\ValueObjects\Constants\PaymentMethodType;
use App\Models\Booking;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use App\Classes\Modules\Bookings\Services\CalculatesBookingRefundAmount;
class FetchBookingPaymentQuotationLogic extends AbstractControllerLogic
{
@@ -40,6 +41,9 @@ class FetchBookingPaymentQuotationLogic extends AbstractControllerLogic
/** @var CalculatesBookingOutstanding */
private $calculatesBookingOutstanding;
/** @var CalculatesBookingRefundAmount */
private $calculatesBookingRefundAmount;
/**
* FetchBookingPaymentQuotationLogic constructor.
* @param FetchesBookingQuotation $fetchBookingQuotation
@@ -47,12 +51,13 @@ class FetchBookingPaymentQuotationLogic extends AbstractControllerLogic
* @param FetchesCompanyPaymentAttemptLimit $fetchesCompanyPaymentAttemptLimit
* @param CalculatesBookingOutstanding $calculatesBookingOutstanding
*/
public function __construct(FetchesBookingQuotation $fetchBookingQuotation, GeneratesBookingQuotation $generatesBookingQuotation, FetchesCompanyPaymentAttemptLimit $fetchesCompanyPaymentAttemptLimit, CalculatesBookingOutstanding $calculatesBookingOutstanding)
public function __construct(FetchesBookingQuotation $fetchBookingQuotation, GeneratesBookingQuotation $generatesBookingQuotation, FetchesCompanyPaymentAttemptLimit $fetchesCompanyPaymentAttemptLimit, CalculatesBookingOutstanding $calculatesBookingOutstanding, CalculatesBookingRefundAmount $calculatesBookingRefundAmount)
{
$this->fetchBookingQuotation = $fetchBookingQuotation;
$this->generatesBookingQuotation = $generatesBookingQuotation;
$this->fetchesCompanyPaymentAttemptLimit = $fetchesCompanyPaymentAttemptLimit;
$this->calculatesBookingOutstanding = $calculatesBookingOutstanding;
$this->calculatesBookingRefundAmount = $calculatesBookingRefundAmount;
}
/**
@@ -66,7 +71,7 @@ class FetchBookingPaymentQuotationLogic extends AbstractControllerLogic
$conversionObject = new CurrencyConversionObject(floatval(str_replace(',', '', $request->input('amount'))), $booking->convertible_currency_id, $booking->service_id, $booking->fix_currency_id === 1 ? 0:1, PaymentMethodType::PAYMENT_METHODS[$request->input('payment_method')]);
$outstanding = $this->calculatesBookingOutstanding->execute($booking);
$outstanding = $this->calculatesBookingOutstanding->execute($booking) + $this->calculatesBookingRefundAmount->execute($booking, $booking->fix_currency_id);
if($conversionObject->getAmount() > round($outstanding, 2)) throw new MalformedRequestException('Your payment must not be greater than '.$booking->fixedCurrency->short_code.' '. number_format((float)$outstanding, 2, '.', ','));
//Voucherify
@@ -2,19 +2,30 @@
namespace App\Classes\Modules\Bookings\Services;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\TransactionType;
use App\Models\Booking;
use Carbon\Carbon;
class CalculatesBookingRefundAmount
{
public function execute(Booking $booking, int $type, ?string $payment_reference = null): float
{
$refundAmounts = $booking->transactions()->payments()->get()->map(function ($payment) use ($type) {
return $this->calculateRefundAmount($payment, $type);
});
public function execute(Booking $booking, int $type, ?string $payment_reference = NULL){
return $type === 1 ?
$booking->transactions()->refunds($payment_reference)
->selectRaw('sum(amount - service_charge - tax) as sub_total')->get()->sum('sub_total') : $booking->transactions()->refunds($payment_reference)->sum('original_amount');
$totalRefundAmount = $refundAmounts->sum();
return $totalRefundAmount;
}
}
public function calculateRefundAmount($payment, int $type): float
{
$refundTransactions = $payment->transactions()->refunds()->whereIn('status', [ApprovalStatus::APPROVED]);
if ($type === 1) {
return $refundTransactions->selectRaw('sum(amount - service_charge - tax) as sub_total')->get()->sum('sub_total');
}
return $refundTransactions->sum('original_amount');
}
}
@@ -59,7 +59,6 @@ class ExportsImportedInvoiceMappeds implements FromQuery, WithHeadings, WithHead
*/
public function map($transaction): array
{
// dd($transaction);
$this->count += 1;
$data = $transaction->data;
return [
@@ -0,0 +1,86 @@
<?php
namespace App\Classes\Modules\Exports\Services;
use Carbon\Carbon;
use Illuminate\Support\Arr;
use Illuminate\Http\Request;
use App\Models\TransactionMappingLog;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
class ExportsImportedReceiptMappeds implements FromQuery, WithHeadings, WithHeadingRow, WithMapping, ShouldAutoSize
{
use Exportable;
private $dateTime;
private $count;
private $counter = 1;
public function __construct(Request $request)
{
$this->dateTime = $request->input('date').' '.$request->input('time');
$this->count = 0;
}
public function headings(): array
{
return [
'Check',
'Doc No',
'Doc Date',
'Debtor Code',
'Company Name',
'Description',
'Payment Amount',
'Created User',
'Curr.',
'To Home Rate',
'Local Payment Amount',
'Cancelled',
'Mapped Status',
'Mapped Reference No',
];
}
/**
* @return \Illuminate\Support\Collection|mixed
*/
public function query()
{
return TransactionMappingLog::where('imported_date', $this->dateTime);
}
/**
* @param Transaction $transaction
*
* @return array
*/
public function map($transaction): array
{
$this->count += 1;
$data = $transaction->data;
return [
$this->count,
Arr::get($data,'doc_no'),
Arr::get($data,'doc_date'),
Arr::get($data,'debtor_code'),
Arr::get($data,'company_name'),
Arr::get($data,'description'),
Arr::get($data,'payment_amount'),
Arr::get($data,'created_user'),
Arr::get($data,'curr'),
Arr::get($data,'to_home_rate'),
Arr::get($data,'local_payment_amount'),
Arr::get($data,'cancelled'),
Arr::get($data,'2nd_doc_no'),
Arr::get($data,'mapped_status'),
Arr::get($data,'mapped_result_reference'),
];
}
}
@@ -108,13 +108,13 @@ class ExportsInvoiceTransactions implements FromQuery, WithHeadings, WithHeading
'500-0000',
'CIEF'
];
} else {
} elseif ($statementTransactionOwner->owner_id) {
$row = (App()->make(ListShippingPortalTransactions::class))->execute([
'id' => $statementTransactionOwner->owner_id,
'with_company' => true,
]);
if (empty($row) || $row[0]['status'] != 'success') {
if (!empty($row) && $row[0]['status'] == 'success') {
$textToAppend = Carbon::now()->format('[Y-m-d H:i:s]') . ' Fetch Shipping Transaction Fail ' . json_encode([
'id' => $statementTransactionOwner->owner_id,
'with_company' => true,
@@ -125,46 +125,46 @@ class ExportsInvoiceTransactions implements FromQuery, WithHeadings, WithHeading
$textToAppend = Carbon::now()->format('[Y-m-d H:i:s]') . ' Shipping Portal Respnose ' . json_encode($row) . PHP_EOL;
file_put_contents($errorFilePath, $textToAppend, FILE_APPEND);
Log::info('Error in Exports Invoice Transactions ' . $this->counter);
$row = $row[0];
return [
'Transaction Not Found',
$transaction->posting_date->format('m/d/Y H:m'),
$transaction->transaction_description.' - '.$transaction->transaction_description_2,
$statementTransactionOwner->system,
'<<New>>',
Carbon::parse($row['created_at'])->format('m/d/Y H:m'),
$row['debtor_code'],
$row['type'] === ShippingTransactionType::PAYMENT ? $row['order_reference'] : $row['marking'],
'',
'MYR',
$row['type'] === ShippingTransactionType::PAYMENT ? $row['order_reference'] : $row['bill_no'],
$row['type'] === ShippingTransactionType::PAYMENT ? '' : 'W1',
$row['type'] === ShippingTransactionType::PAYMENT ? 'PLEASE REFER TO THE ATTACHED APPENDIX REF `' . $row['order_reference'] : 'CREDIT SALES',
'',
'',
'',
'',
'',
0,
$transaction->amount,
'',
'',
'',
''
1,
round($row['amount'], 2),
'500-0000',
'CIEF'
];
}
$row = $row[0];
return [
'<<New>>',
Carbon::parse($row['updated_at'])->format('m/d/Y H:m'),
$row['debtor_code'],
$row['type'] === ShippingTransactionType::PAYMENT ? $row['order_reference'] : $row['marking'],
'',
'MYR',
$row['type'] === ShippingTransactionType::PAYMENT ? $row['order_reference'] : $row['bill_no'],
$row['type'] === ShippingTransactionType::PAYMENT ? '' : 'W1',
$row['type'] === ShippingTransactionType::PAYMENT ? 'PLEASE REFER TO THE ATTACHED APPENDIX REF `' . $row['order_reference'] : 'CREDIT SALES',
'',
1,
round($row['amount'], 2),
'500-0000',
'CIEF'
];
}
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,
'',
'',
'',
''
];
}
}
@@ -2,6 +2,7 @@
namespace App\Classes\Modules\Jobs\Processors;
use App\Classes\Exceptions\JobResourceNotFoundException;
use App\Classes\Modules\Jobs\Services\FetchesJobResult;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
@@ -32,12 +33,13 @@ class FetchesJobResultProcessor
public function execute(Request $request){
$res1 = $this->fetchesJobResult->execute(['job_id' => $request->route('job_id')]);
if($request->route('is_last')){
$res2 = $this->fetchesJobResult->execute(['request_signature' => $res1->request_signature, 'result_not_null' => true, 'order_by_id_desc' => true]);
return $res2;
}
if(!$res1->result){
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;
throw new JobResourceNotFoundException('Unable to find any job based on the criteria provided');
}
return $res1;
@@ -44,9 +44,9 @@ class UpdateJobResultProcessor
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){
//if($resultSignatureExisting != $resultSignatureCurrent){
$this->updateJobResult($jobResultCurrent, $resultCurrentJson, $resultSignatureCurrent, $listGenericJobObject->getJobCommandName(), $listGenericJobObject->getJobCommand());
}
//}
} catch (JobResourceNotFoundException $exception){
$this->updateJobResult($jobResultCurrent, $resultCurrentJson, $resultSignatureCurrent, $listGenericJobObject->getJobCommandName(), $listGenericJobObject->getJobCommand());
}
@@ -108,12 +108,12 @@ class CreatePerfexCRMInvoiceProcessor
$email = null;
if ($firstSupplier) {
$email = $firstSupplier->email;
Log::error('CreatePerfexCRMInvoiceProcessor debug:'.$email);
Log::channel('perfex_crm')->info('CreatePerfexCRMInvoiceProcessor debug:'.$email);
} else {
$bookingMarking = $transaction->owner->marking;
$serviceTypeName = $transaction->owner->company->services()->where('id', $transaction->owner->service_id)->first()->name;
$projectName = 'Exchange | '.$serviceTypeName.' | '.$bookingMarking;
Log::error('$projectName: '.$projectName);
Log::channel('perfex_crm')->info('$projectName: '.$projectName);
return $email;
}
@@ -62,7 +62,7 @@ class FetchPerfexCRMInvoiceProcessor
$invoiceId = $result->payload['id'];
} else {
$log['message'] = 'FetchPerfexCRMInvoiceProcessor failed for transaction > bill_no: '.$number;
Helper::debugLogger($log);
Log::channel('perfex_crm')->info($log);
}
}
else{
@@ -217,8 +217,8 @@ class UpdatePerfexCRMProcessor
}
$result = $this->fetchesPerfexCRMTask->execute($taskName, $milestoneId, 'project', $projectId, $updatePerfexCRMObject->getInvoiceId());
// Log::error("UpdatePerfexCRMProcessor task: ".$taskName." , ".json_encode($result));
Log::error("UpdatePerfexCRMProcessor task: ".$taskName);
// Log::channel('perfex_crm')->info("UpdatePerfexCRMProcessor task: ".$taskName." , ".json_encode($result));
Log::channel('perfex_crm')->info("UpdatePerfexCRMProcessor task: ".$taskName);
if(isset($result->payload)){
//&& $result->payload[0]['status'] == PerfexCRMTaskStatus::NOT_STARTED
@@ -24,7 +24,7 @@ class ConvertsPerfexCRMLeadToCustomer
return (object) $data;
}else{
Log::error($response);
Log::channel('perfex_crm')->info($response);
return null;
}
}catch(\Exception $exception){
@@ -27,7 +27,7 @@ class CreatesPerfexCRMCustomer
$data = $response->json();
return (object) $data;
}else{
Log::error($response);
Log::channel('perfex_crm')->info($response);
return null;
}
}catch(\Exception $exception){
@@ -34,7 +34,7 @@ class CreatesPerfexCRMCustomerContact
$data = $response->json();
return (object) $data;
}else{
Log::error($response);
Log::channel('perfex_crm')->info($response);
return null;
}
}catch(\Exception $exception){
@@ -33,7 +33,7 @@ class CreatesPerfexCRMCustomerProject
$data = $response->json();
return (object) $data;
}else{
Log::error($response);
Log::channel('perfex_crm')->info($response);
return null;
}
}catch(\Exception $exception){
@@ -53,7 +53,7 @@ class CreatesPerfexCRMInvoice
$data = $response->json();
return (object) $data;
}else{
Log::error($response);
Log::channel('perfex_crm')->info($response);
return null;
}
}catch(\Exception $exception){
@@ -33,7 +33,7 @@ class CreatesPerfexCRMInvoicePayment
$data = $response->json();
return (object) $data;
}else{
Log::error($response);
Log::channel('perfex_crm')->info($response);
return null;
}
}catch(\Exception $exception){
@@ -40,7 +40,7 @@ class CreatesPerfexCRMLead
$data = $response->json();
return (object) $data;
}else{
Log::error($response);
Log::channel('perfex_crm')->info($response);
return null;
}
}catch(\Exception $exception){
@@ -36,7 +36,7 @@ class CreatesPerfexCRMMilestone
$data = $response->json();
return (object) $data;
}else{
Log::error($response);
Log::channel('perfex_crm')->info($response);
return null;
}
}catch(\Exception $exception){
@@ -56,7 +56,7 @@ class CreatesPerfexCRMTask
$data = $response->json();
return (object) $data;
}else{
Log::error($response);
Log::channel('perfex_crm')->info($response);
return null;
}
}catch(\Exception $exception){
@@ -24,7 +24,7 @@ class FetchesPerfexCRMCustomer
return (object) $data;
}else{
Log::error($response);
Log::channel('perfex_crm')->info($response);
return null;
}
}catch(\Exception $exception){
@@ -26,7 +26,7 @@ class FetchesPerfexCRMInvoice
return (object) $data;
}else{
Log::error($response);
Log::channel('perfex_crm')->info($response);
return null;
}
}catch(\Exception $exception){
@@ -24,7 +24,7 @@ class FetchesPerfexCRMLead
return (object) $data;
}else{
Log::error($response);
Log::channel('perfex_crm')->info($response);
return null;
}
}catch(\Exception $exception){
@@ -30,7 +30,7 @@ class FetchesPerfexCRMMilestone
return (object) $data;
}else{
Log::error($response);
Log::channel('perfex_crm')->info($response);
return null;
}
}catch(\Exception $exception){
@@ -30,7 +30,7 @@ class FetchesPerfexCRMProject
return (object) $data;
}else{
Log::error($response);
Log::channel('perfex_crm')->info($response);
return null;
}
}catch(\Exception $exception){
@@ -44,7 +44,7 @@ class FetchesPerfexCRMTask
return (object) $data;
}else{
Helper::debugLogger($response);
Log::channel('perfex_crm')->info($response);
return null;
}
}catch(\Exception $exception){
@@ -38,7 +38,7 @@ class UpdatesPerfexCRMCustomer
$data = $response->json();
return (object) $data;
}else{
Helper::debugLogger($response);
Log::channel('perfex_crm')->info($response);
return null;
}
}catch(\Exception $exception){
@@ -60,7 +60,7 @@ class UpdatesPerfexCRMInvoice
$data = $response->json();
return (object) $data;
}else{
Log::error($response);
Log::channel('perfex_crm')->info($response);
return null;
}
}catch(\Exception $exception){
@@ -41,7 +41,7 @@ class UpdatesPerfexCRMLead
$data = $response->json();
return (object) $data;
}else{
Log::error($response);
Log::channel('perfex_crm')->info($response);
return null;
}
}catch(\Exception $exception){
@@ -33,7 +33,7 @@ class UpdatesPerfexCRMProject
$data = $response->json();
return (object) $data;
}else{
Log::error($response);
Log::channel('perfex_crm')->info($response);
return null;
}
}catch(\Exception $exception){
@@ -40,7 +40,7 @@ class UpdatesPerfexCRMTask
$data = $response->json();
return (object) $data;
}else{
Log::error($response);
Log::channel('perfex_crm')->info($response);
return null;
}
}catch(\Exception $exception){
@@ -3,6 +3,7 @@
namespace App\Classes\Modules\Transactions\ControllersLogic;
use App\Classes\Exceptions\MalformedRequestException;
use App\Classes\Modules\Transactions\Processors\CreateSupplierTransactionProcessor;
use App\Classes\Modules\Transactions\Services\GeneratesTransactionBillNumber;
use App\Models\Document;
@@ -18,6 +19,7 @@ use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Companies\Services\FetchesCompany;
use App\Classes\Modules\Documents\Services\CreatesDocument;
use App\Classes\Modules\Documents\DataTransferObjects\DocumentObject;
use App\Classes\Modules\Transactions\Services\FetchesTransaction;
class CreateSupplierTransactionLogic extends AbstractControllerLogic
{
@@ -48,6 +50,9 @@ class CreateSupplierTransactionLogic extends AbstractControllerLogic
/** @var GeneratesTransactionBillNumber */
private $generatesTransactionBillNumber;
/** @var FetchesTransaction */
private $fetchesTransaction;
/**
* CreateSupplierTransactionLogic constructor.
@@ -56,14 +61,16 @@ class CreateSupplierTransactionLogic extends AbstractControllerLogic
* @param CreatesDocument $createsDocument
* @param CreatesFiles $createsFile
* @param GeneratesTransactionBillNumber $generatesTransactionBillNumber
* @param FetchesTransaction $fetchesTransaction
*/
public function __construct(FetchesCompany $fetchesCompany, CreateSupplierTransactionProcessor $createSupplierTransactionProcessor, CreatesDocument $createsDocument, CreatesFiles $createsFile, GeneratesTransactionBillNumber $generatesTransactionBillNumber)
public function __construct(FetchesCompany $fetchesCompany, CreateSupplierTransactionProcessor $createSupplierTransactionProcessor, CreatesDocument $createsDocument, CreatesFiles $createsFile, GeneratesTransactionBillNumber $generatesTransactionBillNumber, FetchesTransaction $fetchesTransaction)
{
$this->fetchesCompany = $fetchesCompany;
$this->createSupplierTransactionProcessor = $createSupplierTransactionProcessor;
$this->createsDocument = $createsDocument;
$this->createsFile = $createsFile;
$this->generatesTransactionBillNumber = $generatesTransactionBillNumber;
$this->fetchesTransaction = $fetchesTransaction;
}
public function logic(Request $request) : JsonResponse
@@ -75,6 +82,23 @@ class CreateSupplierTransactionLogic extends AbstractControllerLogic
$payments = $request->input('payments');
// todo-refund: activate this for partial refund
foreach($payments as $payment){
$payment = $this->fetchesTransaction->execute(['id' => $payment['id']]);
$pendingRefundRequest = $payment->transactions()->refunds()->where('status', ApprovalStatus::PENDING_VERIFICATION)->first();
if ($pendingRefundRequest) {
throw new MalformedRequestException('Unable to create supplier order for pending refund request payment');
}
$totalRefund = $payment->transactions()->refunds()->where('status', ApprovalStatus::APPROVED)->sum('original_amount');
if ($payment->original_amount - $totalRefund <= 0) {
throw new MalformedRequestException('Unable to create supplier order for fully refunded payment');
}
}
$this->createSupplierTransactionProcessor->execute($supplier, $rate, $payments);
if(!count($this->createSupplierTransactionProcessor->getBills())) return $this->response([]);
@@ -13,6 +13,8 @@ use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use App\Classes\Modules\Wallets\Processors\CreditWalletProcessor;
use App\Classes\Modules\Bookings\Services\CalculatesBookingPayableAmount;
use App\Classes\Modules\Bookings\Services\CalculatesBookingRefundAmount;
class UpdateRefundTransactionStatusLogic extends AbstractControllerLogic
@@ -43,6 +45,12 @@ class UpdateRefundTransactionStatusLogic extends AbstractControllerLogic
/** @var CreditWalletProcessor */
private $creditWalletProcessor;
/** @var CalculatesBookingPayableAmount */
private $calculatesBookingPayableAmount;
/** @var CalculatesBookingRefundAmount */
private $calculatesBookingRefundAmount;
/**
* CreatePaymentVerificationDocumentLogic constructor.
* @param FetchesCompany $fetchesCompany
@@ -50,14 +58,18 @@ class UpdateRefundTransactionStatusLogic extends AbstractControllerLogic
* @param UpdatesTransactionStatus $updatesTransactionStatus
* @param DeletesDocument $deletesDocument
* @param CreditWalletProcessor $creditWalletProcessor
* @param CalculatesBookingPayableAmount $calculatesBookingPayableAmount
* @param CalculatesBookingRefundAmount $calculatesBookingRefundAmount
*/
public function __construct(FetchesCompany $fetchesCompany, FetchesTransaction $fetchesTransaction, UpdatesTransactionStatus $updatesTransactionStatus, DeletesDocument $deletesDocument, CreditWalletProcessor $creditWalletProcessor)
public function __construct(FetchesCompany $fetchesCompany, FetchesTransaction $fetchesTransaction, UpdatesTransactionStatus $updatesTransactionStatus, DeletesDocument $deletesDocument, CreditWalletProcessor $creditWalletProcessor, CalculatesBookingPayableAmount $calculatesBookingPayableAmount, CalculatesBookingRefundAmount $calculatesBookingRefundAmount)
{
$this->fetchesCompany = $fetchesCompany;
$this->fetchesTransaction = $fetchesTransaction;
$this->updatesTransactionStatus = $updatesTransactionStatus;
$this->deletesDocument = $deletesDocument;
$this->creditWalletProcessor = $creditWalletProcessor;
$this->calculatesBookingPayableAmount = $calculatesBookingPayableAmount;
$this->calculatesBookingRefundAmount = $calculatesBookingRefundAmount;
}
/**
@@ -67,19 +79,24 @@ class UpdateRefundTransactionStatusLogic extends AbstractControllerLogic
*/
public function logic(Request $request) : JsonResponse
{
$transaction = $this->fetchesTransaction->execute(['id' => $request->route('id')]);
$refundTransaction = $this->fetchesTransaction->execute(['id' => $request->route('id')]);
$transaction = $this->updatesTransactionStatus->execute($transaction, $request->input('status'));
$refundTransaction = $this->updatesTransactionStatus->execute($refundTransaction, $request->route('status'));
$booking = $transaction->owner->owner;
$paymentTransaction = $refundTransaction->owner;
$reference = 'Credit Voucher for Overpaid for Ref. '.$booking->marking;
$booking = $paymentTransaction->owner;
if ($transaction->status == ApprovalStatus::APPROVED) {
$this->creditWalletProcessor->execute($booking->company, $transaction->type, $transaction->amount, $reference);
$reference = $refundTransaction->amount == $paymentTransaction->amount ? 'Fully Refund for Ref. ' . $booking->marking : 'Partially Refund for Ref. ' . $booking->marking;
if ($refundTransaction->status == ApprovalStatus::APPROVED) {
$this->creditWalletProcessor->execute($booking->company, $refundTransaction->type, $refundTransaction->amount, $reference);
}
$paidAmount = $paymentTransaction->original_amount - $this->calculatesBookingRefundAmount->calculateRefundAmount($paymentTransaction, $booking->fix_currency_id);
if (!$paidAmount > 0) {
$this->updatesTransactionStatus->execute($paymentTransaction, ApprovalStatus::REFUNDED);
}
return $this->response([]);
}
@@ -81,15 +81,19 @@ class CreateSupplierTransactionProcessor
if($payment->status !== ApprovalStatus::APPROVED) continue;
$totalRefund = $payment->transactions()->refunds()->where('status', ApprovalStatus::APPROVED)->sum('original_amount');
$original_amount_after_refund = $payment->original_amount - $totalRefund;
$this->updatesTransactionStatus->execute($payment, ApprovalStatus::COMPLETED);
$billNumber = $this->generatesTransactionBillNumber->execute('SPLR-');
$constant = SegmentConstant::where('reference', SegmentConstants::SERVICE_CHARGE)->where('detail->id', $supplier->id)->first();
$serviceCharge = $this->calculatesTransactionServiceCharge->execute($payment->original_amount, $rate, $constant);
$serviceCharge = $this->calculatesTransactionServiceCharge->execute($original_amount_after_refund, $rate, $constant);
$object = new TransactionObject($billNumber, TransactionType::BILL, $supplier->id, 1,
$supplier->banks()->where('default', true)->first()->id, PaymentMethodType::CASH,
$payment->original_amount * (1 / $rate), $payment->original_amount, 1, $payment->original_currency_id,
$original_amount_after_refund * (1 / $rate), $original_amount_after_refund, 1, $payment->original_currency_id,
$rate, 0, $serviceCharge, null, ApprovalStatus::PENDING_SUBMISSION);
/** @var Transaction $billTransaction */
@@ -101,7 +105,7 @@ class CreateSupplierTransactionProcessor
$transferFee = $this->calculatesTransactionTransferFee->execute($billTransaction->original_amount, $constant);
$object = new TransactionObject($transferFeeNumber, TransactionType::TRANSFER_FEE, 1, $supplier->id,
$supplier->banks()->where('default', true)->first()->id, PaymentMethodType::CASH,
$payment->original_amount, $payment->original_amount, $payment->original_currency_id, $payment->original_currency_id,
$original_amount_after_refund, $original_amount_after_refund, $payment->original_currency_id, $payment->original_currency_id,
1, 0, $transferFee, null, ApprovalStatus::PENDING_VERIFICATION);
$this->pushTransferFee($this->createsTransaction->execute($billTransaction, $object));
@@ -4,9 +4,11 @@ namespace App\Classes\Modules\Vouchers\ControllersLogic;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Rewards\Services\ListsUserRewards;
use App\Classes\ValueObjects\Constants\RoleTypes;
use App\Http\Resources\UserRewardResource;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class ListUserVouchersLogic extends AbstractControllerLogic
{
@@ -40,6 +42,11 @@ class ListUserVouchersLogic extends AbstractControllerLogic
public function logic(Request $request) : JsonResponse
{
$query = $this->listsUserRewards->execute($this->listsUserRewards->deserializeFilters($request->input('filters')));
if(in_array(Auth::user()->type, RoleTypes::ADMIN_ROLES)){
$request->merge(['isAdmin' => true]);
}
return $this->collectionResponse(UserRewardResource::collection($query));
}
@@ -44,10 +44,16 @@ class ValidateVoucherLogic extends AbstractControllerLogic
{
$booking = Booking::find($request->input('itemId'));
$employee = $booking->company->employees()->first();
$amount = $this->floatvalue($request->input('amount'));
$validateVoucherifyVoucherObject = new ValidateVoucherifyVoucherObject($booking->company_id, $request->input('voucherCode'), $request->input('amount'), $employee);
$validateVoucherifyVoucherObject = new ValidateVoucherifyVoucherObject($booking->company_id, $request->input('voucherCode'), $amount, $employee);
$result = $this->validatesVoucherifyVoucher->execute($validateVoucherifyVoucherObject);
return $this->response(['data' => $result]);
}
private function floatvalue($val){
$val = str_replace(",",".",$val);
$val = preg_replace('/\.(?=.*\.)/', '', $val);
return floatval($val);
}
}
@@ -3,6 +3,7 @@
namespace App\Classes\Modules\Vouchers\DataTransferObjects;
use App\Classes\General\Interfaces\DataTransferObject;
use Carbon\Carbon;
use DateTime;
use Illuminate\Support\Facades\Log;
@@ -86,7 +87,8 @@ class VoucherObject implements DataTransferObject
{
try {
if(!$this->startDate) return null;
$dateTime = new DateTime($this->startDate);
// $dateTime = new DateTime($this->startDate);
$dateTime = Carbon::parse($this->startDate)->tz('Asia/Kuala_Lumpur');
return $dateTime;
} catch (\Exception $e) {
Log::error($e);
@@ -101,7 +103,7 @@ class VoucherObject implements DataTransferObject
{
try {
if(!$this->endDate) return null;
$dateTime = new DateTime($this->endDate);
$dateTime = Carbon::parse($this->endDate)->tz('Asia/Kuala_Lumpur');
return $dateTime;
} catch (\Exception $e) {
Log::error($e);
@@ -0,0 +1,43 @@
<?php
namespace App\Classes\Notifications;
use App\Models\User;
use App\Models\Voucher;
use Carbon\Carbon;
use Illuminate\Notifications\Messages\MailMessage;
class WelcomeVoucherEmail extends AbstractEmail
{
/** @var User */
private $user;
/** @var Voucher */
private $voucher;
/**
* WelcomeVoucherEmail constructor.
* @param User $user
* @param Voucher $voucher
*/
public function __construct(User $user, Voucher $voucher)
{
$this->user = $user;
$this->voucher = $voucher;
}
public function toMail()
{
$this->voucher->end_date = Carbon::parse($this->voucher->end_date)->format('Y-m-d');
$mailMessage = (new MailMessage)
->subject('Welcome Voucher')
->view('emails.accounts.welcome_voucher', ['user' => $this->user, 'voucher' => $this->voucher]);
return $mailMessage;
}
}
@@ -0,0 +1,8 @@
<?php
namespace App\Classes\ValueObjects\Constants;
final class Vouchers {
public const WELCOME_50_PERCENT_OFF = 'WELCOME50%OFF';
}
@@ -0,0 +1,113 @@
<?php
namespace App\Console\Commands;
use App\Classes\Modules\Transactions\DataTransferObjects\TransactionObject;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\TransactionType;
use App\Models\Booking;
use Illuminate\Console\Command;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;
use App\Classes\Modules\Transactions\Processors\CreatePurchaseOrderTransactionProcessor;
use App\Classes\Modules\Transactions\Services\GeneratesPurchaseOrderProducts;
use App\Classes\Modules\Transactions\Services\GeneratesTransactionBillNumber;
use App\Classes\ValueObjects\Constants\PaymentMethodType;
use App\Models\Transaction;
use Illuminate\Support\Facades\DB;
class AutoFillPurchaseOrderCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'purchaseOrder:autoFill';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Auto fill up the purchase order for booking that have payment';
/** @var GeneratesPurchaseOrderProducts */
private $generatesPurchaseOrderProducts;
/** @var GeneratesTransactionBillNumber */
private $generatesTransactionBillNumber;
/** @var CreatePurchaseOrderTransactionProcessor */
private $createPurchaseOrderTransactionProcessor;
/**
* Create a new command instance.
*
* @return void
*/
public function __construct(GeneratesPurchaseOrderProducts $generatesPurchaseOrderProducts, GeneratesTransactionBillNumber $generatesTransactionBillNumber, CreatePurchaseOrderTransactionProcessor $createPurchaseOrderTransactionProcessor)
{
parent::__construct();
$this->generatesPurchaseOrderProducts = $generatesPurchaseOrderProducts;
$this->generatesTransactionBillNumber = $generatesTransactionBillNumber;
$this->createPurchaseOrderTransactionProcessor = $createPurchaseOrderTransactionProcessor;
}
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
// 5. If purchase order not fill up in 2 month, auto fill up it
$bookings = Booking::where('status', ApprovalStatus::APPROVED)
->where('created_at', '<', now()->subDays(60)->endOfDay())
->whereHas('transactions', function($transaction) {
return $transaction->where('type', TransactionType::PAYMENT)->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED]);
})
->whereDoesntHave('transactions', function($transaction){
$transaction->where('type', TransactionType::PURCHASE_ORDER);
$transaction->whereIn('status', [ApprovalStatus::PENDING_VERIFICATION, ApprovalStatus::APPROVED]);
})->get();
foreach ($bookings as $booking) {
$po = Transaction::where('type', TransactionType::PURCHASE_ORDER)
->where('status', ApprovalStatus::APPROVED)->where('issuer', $booking->company_id)
->select('*', DB::raw('abs(amount - ' . $booking->fix_amount . ') as nearest_price'))->orderBy('nearest_price')->first();
if (!$po) {
$po = Transaction::where('type', TransactionType::PURCHASE_ORDER)
->where('status', ApprovalStatus::APPROVED)->select('*', DB::raw('abs(amount - ' . $booking->fix_amount . ') as nearest_price'))->orderBy('nearest_price')->first();
}
$products = $this->generatesPurchaseOrderProducts->execute($po, $booking->fix_amount);
$deference = $booking->fix_amount - $products->sum('total');
if($deference > -150 && $deference < 150 && $deference != 0) {
$products->push([
'description' => $deference < 0 ? 'Discount':'Shipping Fee',
'quantity' => 1,
'stockCode' => '',
'total' => $deference,
'unit_price' => $deference
]);
}
$billNumber = $this->generatesTransactionBillNumber->execute('XPO-');
$total = $products->sum('total');
$object = new TransactionObject($billNumber, TransactionType::PURCHASE_ORDER, $booking->company->id, 1,
1, PaymentMethodType::CASH,
$total, $total, $booking->fix_currency_id, $booking->fix_currency_id,
1, 0, 0, null, ApprovalStatus::PENDING_SUBMISSION, $products->toArray());
$this->createPurchaseOrderTransactionProcessor->execute($booking, $object);
}
}
}
@@ -0,0 +1,100 @@
<?php
namespace App\Console\Commands;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\TransactionType;
use App\Models\Booking;
use Illuminate\Console\Command;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;
use App\Classes\Modules\Bookings\Services\UpdatesBookingStatus;
use App\Models\Transaction;
class ExpiredBookingCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'booking:expired';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Expiring booking that do not have further action by user';
/** @var UpdatesBookingStatus */
private $updatesBookingStatus;
/**
* Create a new command instance.
*
* @return void
*/
public function __construct(UpdatesBookingStatus $updatesBookingStatus)
{
parent::__construct();
$this->updatesBookingStatus = $updatesBookingStatus;
}
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
// 1. Cancel booking without payment & purchase order (1 month)
$bookings = Booking::where('status', ApprovalStatus::APPROVED)
->where('created_at', '<', now()->subDays(30)->endOfDay())
->where(function ($query) {
$query->whereDoesntHave('transactions')
->orWhereDoesntHave('transactions', function($transaction) {
return $transaction->where('type', TransactionType::PURCHASE_ORDER)->orWhere(function ($q) {
$q->where('type', TransactionType::PAYMENT)->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED]);
});
});
})->get();
foreach ($bookings as $booking) {
$this->updatesBookingStatus->execute($booking, ApprovalStatus::EXPIRED);
$this->info(Carbon::now() . " : Expired Booking without payment & purchase order, booking id: " . $booking->id);
$transactions = $booking->transactions;
foreach ($transactions as $transaction) {
$prevStatus = $transaction->status;
$transaction->status = ApprovalStatus::EXPIRED;
$transaction->save();
$this->info(Carbon::now() . " : Expired Transaction id: {$transaction->id} from Booking id: {$booking->id}. Status before update: {$prevStatus}");
}
}
// 2. Cancel booking without payment but with purchase order (2 month)
$bookings = Booking::where('status', ApprovalStatus::APPROVED)
->where('created_at', '<', now()->subDays(60)->endOfDay())
->where(function ($query) {
$query->whereDoesntHave('transactions', function($transaction) {
return $transaction->where('type', TransactionType::PAYMENT)->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED]);
})->whereHas('transactions', function($transaction) {
return $transaction->where('type', TransactionType::PURCHASE_ORDER);
});
})->get();
foreach ($bookings as $booking) {
$this->updatesBookingStatus->execute($booking, ApprovalStatus::EXPIRED);
$this->info(Carbon::now() . " : Expired Booking without payment but with purchase order, booking id: " . $booking->id);
$transactions = $booking->transactions;
foreach ($transactions as $transaction) {
$prevStatus = $transaction->status;
$transaction->status = ApprovalStatus::EXPIRED;
$transaction->save();
$this->info(Carbon::now() . " : Expired Transaction id: {$transaction->id} from Booking id: {$booking->id}. Status before update: {$prevStatus}");
}
}
}
}
@@ -0,0 +1,162 @@
<?php
namespace App\Console\Commands;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\TransactionType;
use App\Models\Booking;
use Illuminate\Console\Command;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;
use App\Classes\Modules\Bookings\Services\UpdatesBookingStatus;
use App\Classes\Modules\Transactions\DataTransferObjects\TransactionObject;
use App\Classes\Modules\Transactions\Services\CreatesTransaction;
use App\Classes\Modules\Transactions\Services\GeneratesTransactionBillNumber;
use App\Classes\ValueObjects\Constants\PaymentMethodType;
use App\Models\Transaction;
class ExpiredRefundedBookingCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'RefundedBooking:expired';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Expiring refunded booking';
/** @var UpdatesBookingStatus */
private $updatesBookingStatus;
/** @var GeneratesTransactionBillNumber */
private $generatesTransactionBillNumber;
/** @var CreatesTransaction */
private $createsTransaction;
/**
* Create a new command instance.
*
* @return void
*/
public function __construct(UpdatesBookingStatus $updatesBookingStatus, GeneratesTransactionBillNumber $generatesTransactionBillNumber, CreatesTransaction $createsTransaction)
{
parent::__construct();
$this->updatesBookingStatus = $updatesBookingStatus;
$this->generatesTransactionBillNumber = $generatesTransactionBillNumber;
$this->createsTransaction = $createsTransaction;
}
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
// 3. Cancel fully refunded payment & cancel booking
$transactions = Transaction::where('type', TransactionType::CREDIT_NOTE)->where('payment_reference', 'LIKE', "%refund%")->get();
foreach ($transactions as $transaction) {
// get the booking marking
$payment_reference = explode(" ", trim($transaction->payment_reference));
// $marking = substr($transaction->payment_reference, -5);
$marking = trim(end($payment_reference));
if (!preg_match('/^[0-9]+$/', $marking)) {
$payment_reference = explode(".", trim($transaction->payment_reference));
$marking = trim(end($payment_reference));
}
// for a special payment reference on transaction id: 140231
if (!preg_match('/^[0-9]+$/', $marking)) {
$payment_reference = explode("No", trim($transaction->payment_reference));
$marking = end($payment_reference);
}
// for a special payment reference on transaction id: 152013
if (!preg_match('/^[0-9]+$/', $marking)) {
$payment_reference = explode(" ", trim($transaction->payment_reference));
$marking = end($payment_reference);
$marking = prev($payment_reference);
}
if (preg_match('/^[0-9]+$/', $marking)) {
$booking = Booking::where('marking', $marking)->first();
if ($booking) {
$bookingPayment = $booking->transactions()->payments()->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED])->first();
if (!$bookingPayment) {
$bookingPaymentCount = $booking->transactions()->payments()->count();
if ($bookingPaymentCount > 1) {
Log::info("Credit note transaction id: {$transaction->id}, there are {$bookingPaymentCount} payment for the booking.");
foreach ($booking->transactions()->payments()->get() as $bp) {
if ($transaction->amount - $bp->amount < 0.01) {
$bookingPayment = $bp;
break;
}
}
}
if (!$bookingPayment) {
$bookingPayment = $booking->transactions()->payments()->whereIn('status', [ApprovalStatus::SUSPENDED, ApprovalStatus::EXPIRED, ApprovalStatus::REJECTED])->orderBy('id', 'DESC')->first();
}
$status = ApprovalStatus::APPROVAL_STATUS_ID[$bookingPayment->status];
Log::info("Credit note transaction id: {$transaction->id}, the payment for the booking is in status {$status}");
}
$bookingPaymentAmount = $bookingPayment->amount;
// check if the booking is fully refund
$amountDifference = bcsub($transaction->amount, $bookingPaymentAmount, 7);
if (abs($amountDifference) < 0.01) {
// rejecting booking payment transaction
// $bookingPayment->status = ApprovalStatus::REJECTED;
// $bookingPayment->save();
//expired booking
// $this->updatesBookingStatus->execute($booking, ApprovalStatus::EXPIRED);
Log::info("Credit note transaction id: {$transaction->id} is fully refunded, the refunded amount was {$transaction->amount} the payment reference is: {$transaction->payment_reference}");
// Log::info("Credit note transaction id: {$transaction->id}, Rejected Booking Transaction Payment id: {$bookingPayment->id}, the payment amount was {$bookingPayment->amount}");
// Log::info("Credit note transaction id: {$transaction->id}, Expired Booking id: {$booking->id}");
} else {
Log::info("Credit note transaction id: {$transaction->id} is not fully refunded, the refunded amount was {$transaction->amount}, the payment amount was {$bookingPayment->amount}, the payment reference is: {$transaction->payment_reference}");
}
$refund = $bookingPayment->transactions()->refunds()->where('amount', $transaction->amount)->where('status', ApprovalStatus::APPROVED)->first();
$bookingInWhiteForm = $bookingPayment->transactions()->bills()->first();
if ($refund) {
Log::info("Credit note transaction id: {$transaction->id}, already created same amount of refund transaction for same booking payment transaction");
}
if ($bookingInWhiteForm) {
Log::info("Credit note transaction id: {$transaction->id}, booking is in white form");
}
if (!$refund && !$bookingInWhiteForm) {
$billNumber = $this->generatesTransactionBillNumber->execute('RFD-');
$object = new TransactionObject($billNumber, TransactionType::REFUND, 1, $booking->company->id,
1, PaymentMethodType::CASH,
$transaction->amount, $transaction->amount * $bookingPayment->currency_rate, 1,
$bookingPayment->original_currency_id, $bookingPayment->currency_rate,
0, 0, null, ApprovalStatus::APPROVED, [], $bookingPayment->bill_no);
$transaction = $this->createsTransaction->execute($bookingPayment, $object);
}
} else {
Log::info("Credit note transaction id: {$transaction->id}, booking marking not found, the payment reference is: {$transaction->payment_reference}");
}
} else {
Log::info("Credit note transaction id: {$transaction->id} does not have booking marking, the payment reference is: {$transaction->payment_reference}");
}
}
}
}
+11
View File
@@ -67,6 +67,17 @@ class Kernel extends ConsoleKernel
->hourly()
->appendOutputTo(storage_path().'/logs/delete-bulk-download-files.log')
->withoutOverlapping();
//cief todo: command version 2
$schedule->command('booking:expired')
->dailyAt('02:00')
->appendOutputTo(storage_path().'/logs/expire-booking.log')
->withoutOverlapping();
//cief todo: command version 2
// $schedule->command('purchaseOrder:autoFill')
// ->dailyAt('03:00')
// ->withoutOverlapping();
}
}
@@ -0,0 +1,20 @@
<?php
namespace App\Http\Controllers\Accounting;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Classes\Modules\Accounting\ControllersLogic\HistoryImportedTransactionMappedControllerLogic;
class HistoryImportedTransactionMappedController
{
/**
* @param Request $request
* @param ApprovePaymentLogic $logic
* @return JsonResponse
*/
public function getImported(Request $request, HistoryImportedTransactionMappedControllerLogic $logic): JsonResponse {
return $logic->execute($request);
}
}
@@ -18,6 +18,7 @@ use Maatwebsite\Excel\Excel;
use App\Classes\Modules\Exports\Services\ExportsImportedInvoiceMappeds;
use App\Models\TransactionMappingLog;
use App\Classes\Modules\Exports\Services\ExportsReceiptTransactions;
use App\Classes\Modules\Exports\Services\ExportsImportedReceiptMappeds;
class ExportCustomersToExcelController
{
@@ -91,4 +92,10 @@ class ExportCustomersToExcelController
ob_end_clean();
return $response;
}
public function importedReceiptMapped(ExportsImportedReceiptMappeds $exportsImportedReceiptMappeds, Request $request) {
$response = $exportsImportedReceiptMappeds->download($request->input('fileName').'.xls', Excel::XLS, ['Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']);
ob_end_clean();
return $response;
}
}
@@ -100,6 +100,7 @@ class ImportStatementInvoiceController
TransactionMappingLog::create([
'imported_date'=>$importDate,
'type' => 'invoices',
'data'=>$row,
]);
array_push($data, $row);
@@ -69,6 +69,7 @@ class ImportStatementReceiptsController
TransactionMappingLog::create([
'imported_date'=>$importDate,
'type' => 'receipts',
'data'=>$row,
]);
array_push($data, $row);
+3 -2
View File
@@ -32,7 +32,8 @@ class BookingResource extends JsonResource
'amount' => $this->fix_amount,
'floating_amount' => floatval((App()->make(CalculatesBookingFloatingAmount::class))->execute($this->resource, $this->fix_currency_id)),
'paid_amount' => floatval((App()->make(CalculatesBookingPayableAmount::class))->execute($this->resource, $this->fix_currency_id)) - floatval((App()->make(CalculatesBookingRefundAmount::class))->execute($this->resource, $this->fix_currency_id)),
'outstanding_amount' => floatval((App()->make(CalculatesBookingOutstanding::class))->execute($this->resource)) - floatval((App()->make(CalculatesBookingRefundAmount::class))->execute($this->resource, $this->fix_currency_id)),
// 'outstanding_amount' => floatval((App()->make(CalculatesBookingOutstanding::class))->execute($this->resource)) + floatval((App()->make(CalculatesBookingRefundAmount::class))->execute($this->resource, $this->fix_currency_id)),
'outstanding_amount' => floatval((App()->make(CalculatesBookingOutstanding::class))->execute($this->resource)),
'fixed_currency' => new CurrencyResource($this->fixedCurrency),
'convertible_currency' => new CurrencyResource($this->convertibleCurrency),
'conversion_currency' => new CurrencyResource($this->conversionCurrency),
@@ -58,7 +59,7 @@ class BookingResource extends JsonResource
'expired_payment_attempts' => TransactionResource::collection($this->transactions()->payments()->where('status', ApprovalStatus::PENDING_SUBMISSION)->whereDate('expires_on', '>=', Carbon::now())->where('expires_on', '>', Carbon::now()->toTimeString())->get()),
'payment_history' => TransactionResource::collection($this->transactions()->where(function($query){
$query->where(function($query){
$query->payments()->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::PENDING_VERIFICATION, ApprovalStatus::COMPLETED, ApprovalStatus::REJECTED]);
$query->payments()->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::PENDING_VERIFICATION, ApprovalStatus::COMPLETED, ApprovalStatus::REJECTED, ApprovalStatus::REFUNDED]);
})->orWhere(function($query){
$query->where(function($query){
$query->where('type', TransactionType::REFUND)->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::PENDING_VERIFICATION, ApprovalStatus::REJECTED, ApprovalStatus::COMPLETED]);
@@ -0,0 +1,24 @@
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class KeyValueBasicResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
// 'id' => $this->id,
'key' => $this->key,
'value' => $this->value,
];
}
}
@@ -0,0 +1,23 @@
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class TransactionMappingLogResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'imported_date' => $this->imported_date,
'type' => $this->type
];
}
}
@@ -2,6 +2,7 @@
namespace App\Http\Resources;
use App\Classes\Modules\Bookings\Services\CalculatesBookingRefundAmount;
use App\Classes\ValueObjects\Constants\TransactionType;
use App\Models\Booking;
use Carbon\Carbon;
@@ -43,8 +44,10 @@ class TransactionResource extends JsonResource
'documents' => new DocumentResource($this->documents()->first()),
'transaction_bill' => new TransactionResource($this->when((int) $this->type === TransactionType::PAYMENT, $this->transactions()->bills()->first())),
'transaction_refunds' => TransactionResource::collection($this->when((int) $this->type === TransactionType::PAYMENT, $this->transactions()->refunds()->get())),
'refunded_amount' => $this->booking ? floatval((App()->make(CalculatesBookingRefundAmount::class))->calculateRefundAmount($this->resource, $this->booking->fix_currency_id)) : null,
'expires_on' => Carbon::parse($this->expires_on)->format('d-m-Y h:i:s A'),
'updated_at' => Carbon::parse($this->updated_at)->format('d-m-Y h:i:s A'),
'created_at' => Carbon::parse($this->created_at)->format('d-m-Y h:i:s A'),
'interval' => [
'value' => $days->gt(Carbon::now()) ? '+' : '-',
'duration' => $days->diff(Carbon::now())->format('%d'),
@@ -2,6 +2,7 @@
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class UserRewardResource extends JsonResource
@@ -14,6 +15,13 @@ class UserRewardResource extends JsonResource
*/
public function toArray($request)
{
$emailReminder = null;
if ($request->has('isAdmin')) {
$keyValuePairs = $this->user->attributes()->get();
$emailReminder = KeyValueBasicResource::collection($keyValuePairs);
$this->voucher->email = $emailReminder;
}
return [
'id' => $this->id,
'user_id' => $this->user_id,
+13 -4
View File
@@ -2,6 +2,7 @@
namespace App\Http\Resources;
use ArrayObject;
use Illuminate\Http\Resources\Json\JsonResource;
class VoucherResource extends JsonResource
@@ -14,9 +15,16 @@ class VoucherResource extends JsonResource
*/
public function toArray($request)
{
$filteredRedemptions = $this->redemptions->filter(function ($redemption) {
return $redemption->transaction && $redemption->transaction->owner;
});
$filteredRedemptions = new ArrayObject([]);
if ($request->has('filters') && str_contains($request->input('filters'), "has_active_reward")) {
$filteredRedemptions = new ArrayObject([]);
}
else{
$filteredRedemptions = $this->redemptions->filter(function ($redemption) {
return $redemption->transaction && $redemption->transaction->owner;
});
}
return [
'id' => $this->id,
'name' => $this->name,
@@ -25,7 +33,8 @@ class VoucherResource extends JsonResource
'value' => (float) $this->value,
'start_date' => $this->start_date,
'end_date' => $this->end_date,
'is_redeemed' => $filteredRedemptions->count() > 0
'is_redeemed' => $filteredRedemptions->count() > 0,
'email' => $this->email ? new KeyValueBasicResource($this->email->where('key', $this->code.'_EMAIL_COUNT')->first()) : null,
];
}
}
+15
View File
@@ -0,0 +1,15 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Relations\MorphTo;
class KeyValuePair extends AbstractModel
{
protected $table = 'key_value_pairs';
public function owner(): MorphTo
{
return $this->morphTo();
}
}
+1 -1
View File
@@ -7,7 +7,7 @@ use Illuminate\Database\Eloquent\Model;
class TransactionMappingLog extends Model
{
protected $fillable = ['imported_by','data','imported_date'];
protected $fillable = ['imported_by','data','imported_date','type'];
protected $casts = [
'data' => 'array',
+20 -1
View File
@@ -2,6 +2,7 @@
namespace App\Models;
use App\Classes\General\Interfaces\KeyValueInterface;
use App\Classes\General\Interfaces\Voucherifiable;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
@@ -26,7 +27,8 @@ class User extends AbstractModel implements
AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract,
Voucherifiable
Voucherifiable,
KeyValueInterface
{
use HasRoles, Notifiable, Authenticatable, Authorizable, CanResetPassword, MustVerifyEmail, SoftDeletes;
@@ -101,4 +103,21 @@ class User extends AbstractModel implements
{
return $this->HasMany(UserReward::class, 'user_id', 'id');
}
public function hasAttribute(string $key, $value = null): bool
{
$query = $this->attributes()->where('key', $key);
if ($value !== null) {
$query->where('value', $value);
}
return $query->exists();
}
public function attributes(): MorphMany
{
return $this->morphMany(KeyValuePair::class, 'owner');
}
}
+17
View File
@@ -104,6 +104,23 @@ return [
'path' => storage_path('logs/regenerateInvoice.log'),
'level' => 'info',
],
'guzzleShippingPortal' => [
'driver' => 'errorlog',
'level' => 'debug',
],
'vue_polling' => [
'driver' => 'single',
'path' => storage_path('logs/laravel_vue_plling.log'),
'level' => 'info',
],
'perfex_crm' => [
'driver' => 'single',
'path' => storage_path('logs/laravel_perfex_crm.log'),
'level' => 'info',
],
],
];
+7
View File
@@ -34,6 +34,13 @@ return [
'driver' => 'sync',
],
'high_priority' => [
'driver' => 'database',
'table' => 'jobs',
'queue' => 'high_priority',
'retry_after' => 90,
],
'database' => [
'driver' => 'database',
'table' => 'jobs',
@@ -0,0 +1,40 @@
<?php
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddTypeToTransactionMappingLogsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('transaction_mapping_logs', function (Blueprint $table) {
$table->string('type',50)->default('invoices')->after('imported_date');
});
foreach (DB::table('transaction_mapping_logs')->get() as $key => $value) {
$data = json_decode($value->data);
DB::table('transaction_mapping_logs')->where('id',$value->id)->update([
'type' => (isset($data->description) ? 'receipts' : 'invoices')
]);
}
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('transaction_mapping_logs', function (Blueprint $table) {
$table->dropColumn('type');
});
}
}
@@ -0,0 +1,37 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateKeyValuePairsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('key_value_pairs', function (Blueprint $table) {
$table->id();
$table->string('owner_type'); //'user', 'order', 'transaction'
$table->unsignedBigInteger('owner_id');
$table->string('key');
$table->string('value');
$table->timestamps();
$table->index(['owner_type', 'owner_id']);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('key_value_pairs');
}
}
@@ -0,0 +1,39 @@
<template>
<div class="row m-b-10 parentContainer">
<div class="col">
<div class="row p-b-10 b-b b-grey">
<div class="col-2">{{ item.imported_date }}</div>
<div class="col-2">
<button class="btn btn-xs btn-outline-success b-rad-none m-r-5" @click="downloadInvoiceMapped(item.imported_date)">
Download Invoices Mapped
</button>
</div>
</div>
</div>
</div>
</template>
<script>
import componentHandler from '../../../general/mixins/componentHandler';
export default {
props: {
stage: {
type: Number,
default: 0
},
section:{
type: String,
required: true
},
},
methods: {
downloadInvoiceMapped(importedDate) {
var arrDateTime = importedDate.split(" ");
const fileName = 'InvoiceMapped';
window.open(this.route('importedInvoiceMapped.export')+'?date='+arrDateTime[0]+'&time='+arrDateTime[1]+'&fileName='+fileName, '_blank');
},
},
mixins: [componentHandler]
}
</script>
@@ -0,0 +1,39 @@
<template>
<div class="row m-b-10 parentContainer">
<div class="col">
<div class="row p-b-10 b-b b-grey">
<div class="col-2">{{ item.imported_date }}</div>
<div class="col-2">
<button class="btn btn-xs btn-outline-success b-rad-none m-r-5" @click="downloadInvoiceMapped(item.imported_date)">
Download Receipts Mapped
</button>
</div>
</div>
</div>
</div>
</template>
<script>
import componentHandler from '../../../general/mixins/componentHandler';
export default {
props: {
stage: {
type: Number,
default: 0
},
section:{
type: String,
required: true
},
},
methods: {
downloadInvoiceMapped(importedDate) {
var arrDateTime = importedDate.split(" ");
const fileName = 'ReceiptMapped';
window.open(this.route('importedReceiptMapped.export')+'?date='+arrDateTime[0]+'&time='+arrDateTime[1]+'&fileName='+fileName, '_blank');
},
},
mixins: [componentHandler]
}
</script>
@@ -74,7 +74,7 @@
<div class="row parentContainer" v-for="owner in item.owners.pending_verification">
<div class="col d-flex justify-content-between">
<a :href="owner.reference_link" target="_blank">{{ owner.reference }}</a>
<div v-if="stage === 2">
<div v-if="stage === 2" style="display: flex;">
<button class="btn btn-xs btn-outline-primary b-rad-none m-r-5 requestModal" data-type="approveCorrectMappingTransaction">
<i class="fa fa-check fa-fw"></i>
</button>
@@ -89,6 +89,21 @@
>
</general-confirmation-form-component>
</modal-component>
<button class="btn btn-xs btn-outline-danger b-rad-none m-r-5 requestModal" data-type="revertPendingMappingTransaction">
<i class="fa fa-times fa-fw"></i>
</button>
<modal-component class="animate__animated animate__fast animate__fadeIn" type="revertPendingMappingTransaction">
<general-confirmation-form-component
contentText="Are you sure you want to reject this mapping?"
modalType="delete"
class="text-center"
:apiRoute="route('api.accounting.statement_transaction.owner.status.update', owner.id, 'reject')"
apiMethod="post"
:section="section"
>
</general-confirmation-form-component>
</modal-component>
</div>
</div>
</div>
@@ -143,7 +158,7 @@
contentText="Are you sure you want to reject this mapping?"
modalType="delete"
class="text-center"
:apiRoute="route('api.accounting.statement_transaction.owner.status.update', item.id, 'reject')"
:apiRoute="route('api.accounting.statement_transaction.owner.status.update', item.owners.pending_verification[0].id, 'reject')"
apiMethod="post"
:section="section"
>
@@ -98,21 +98,17 @@
},
methods: {
appendComponentTitle() {
this.componentTitle = this.section == 'importInvoiceMapping' ? 'Imported Invoices Mapped' : 'Imported Receipts Mapped';
this.componentTitle = 'Imported Invoices Mapped';
},
appendComponentTableHeader() {
if (this.section == 'importInvoiceMapping') {
this.tableHeaders = ['No','Doc No','Date','Debtor Code','Debtor Name','Shipping Info','Net Total','Cancelled','Mapped Status','Mapped Reference No','Payment Received Date'];
} else {
this.tableHeaders = ['No','OR No','Date','Creditor Code','Creditor Name','Shipping Info','Net Total','Cancelled','Mapped Status','Mapped Reference No'];
}
this.tableHeaders = ['No','Doc No','Date','Debtor Code','Debtor Name','Shipping Info','Net Total','Cancelled','Mapped Status','Mapped Reference No','Payment Received Date'];
},
importInvoice(){
this.isLoading = true;
this.parameters = {
files: this.files
};
this.submit(this.route('api.'+(this.section == 'importInvoiceMapping' ? 'import_invoices' : 'import_receipts')+'.upload'), 'post', this.section, true, false);
this.submit(this.route('api.import_invoices.upload'), 'post', this.section, true, false);
},
successHandler(response){
@@ -128,7 +124,7 @@
downloadInvoiceMapped() {
var arrDateTime = this.importedDate.split(" ");
const fileName = this.section == 'importInvoiceMapping' ? 'InvoiceMapped' : 'ReceiptMapped';
const fileName = 'importInvoiceMapping';
window.open(this.route('importedInvoiceMapped.export')+'?date='+arrDateTime[0]+'&time='+arrDateTime[1]+'&fileName='+fileName, '_blank');
},
@@ -0,0 +1,138 @@
<template>
<div class="row h-100 parentContainer">
<div class="col-12" style="min-height: 20px;">
<loading-component style="height: 20px; top: 0;" key="1" color="success" v-show="isLoading"></loading-component>
</div>
<div class="col-12">
<div class="card">
<div class="card-header">
<h3>{{ componentTitle }}</h3>
<div class="row m-b-10 animate__animated animate__fadeInUpBig animate__fast" v-if="error">
<div class="col">
<small class="bold fs-10 text-danger">{{error}}</small>
</div>
</div>
<div class="text-right">
<button class="btn btn-xs btn-outline-success b-rad-none m-r-5" @click="downloadInvoiceMapped">
Download Receipts Mapped
</button>
</div>
</div>
<!-- /.card-header -->
<div class="card-body table-responsive p-0">
<table class="table table-hover">
<thead>
<tr>
<th v-for="item in tableHeaders">{{ item }}</th>
</tr>
</thead>
<tbody v-show="!isLoading">
<tr v-for="(item, index) in $store.getters.getListData(section)">
<td>{{index+1}}</td>
<td>{{item.check }}</td>
<td>{{item.doc_no}}</td>
<td>{{item.doc_date }}}</td>
<td>{{item.debtor_code}}</td>
<td>{{item.company_name}}</td>
<td>{{item.description}}</td>
<td>{{item.payment_amount}}</td>
<td>{{item.created_user}}</td>
<td>{{item.curr}}</td>
<td>{{item.to_home_rate}}</td>
<td>{{item.local_payment_amount}}</td>
<td>{{item.cancelled}}</td>
<td>{{item.mapped_status}}</td>
<td>{{item.mapped_result_reference}}</td>
</tr>
</tbody>
</table>
</div>
<!-- /.card-body -->
<div class="card-footer">
</div>
</div>
</div>
<div class="col-12">
<pagination-component :section="section" class="mb-5" ref="pagination"></pagination-component>
</div>
</div>
</template>
<script>
export default {
props: {
files: {
required: true
},
type: {
type: String,
required: true,
},
section:{
type: String,
required: true
},
},
data() {
return {
isLoading: false,
error: '',
importedDate: null,
}
},
computed: {
pendingQueue() {
return this.$store.getters.isInCompleteQueue(this.section);
}
},
watch: {
pendingQueue(inComplete, oldValue){
if(inComplete){
this.importInvoice();
}
},
},
created(){
this.appendComponentTitle();
this.appendComponentTableHeader();
this.$store.dispatch('updateListQueue', {'name': this.section});
},
methods: {
appendComponentTitle() {
this.componentTitle = 'Imported Receipts Mapped';
},
appendComponentTableHeader() {
this.tableHeaders = ['Check','Doc No','Doc Date','Debtor Code','Company Name','Description','Payment Amount','Created User','Curr.','To Home Rate','Local Payment Amount','Cancelled','Mapped Status','Mapped Reference No'];
},
importInvoice(){
this.isLoading = true;
this.parameters = {
files: this.files
};
this.submit(this.route('api.import_receipts.upload'), 'post', this.section, true, false);
},
successHandler(response){
this.$store.dispatch('completeList', {'name': this.section, 'data': response.payload.data});
this.importedDate = response.payload.importedDate;
this.isLoading = false;
},
errorHandler(error){
this.isLoading = false;
this.error = error.message;
},
downloadInvoiceMapped() {
var arrDateTime = this.importedDate.split(" ");
const fileName = 'ReceiptMapped';
window.open(this.route('importedReceiptMapped.export')+'?date='+arrDateTime[0]+'&time='+arrDateTime[1]+'&fileName='+fileName, '_blank');
},
}
}
</script>
@@ -3,19 +3,74 @@
<div class="col">
<div class="row">
<div class="col">
<div class="row justify-content-center align-items-center m-t-50 m-b-50" v-show="step === 0">
<div class="col-5">
<div class="row text-center">
<div class="col b-a b-grey padding-20 m-r-15 pointer bg-complete text-white" @click="getReportFilter()">Mapped Report</div>
<div class="justify-content-center align-items-center m-t-50 m-b-50" v-show="step === 0">
<div class="row">
<div class="col-3">
<div class="row text-center">
<div class="col b-a b-grey padding-20 m-r-15 pointer bg-complete text-white" @click="getReportFilter()">Mapped Report</div>
</div>
</div>
<div class="col-3">
<div class="row text-center">
<div class="col b-a b-grey padding-20 m-r-15 pointer bg-complete text-white" @click="getHistoryImportedInvReport()">History Imported Invoices Report</div>
</div>
</div>
<div class="col-3">
<div class="row text-center">
<div class="col b-a b-grey padding-20 m-r-15 pointer bg-complete text-white" @click="getHistoryImportedRecReport()">History Imported Receipts Report</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row" v-if="step == 1">
<div class="row" v-if="step > 0 && report == 'mappedRecords'">
<div class="col">
<div class="row">
<div class="col">
<div class="justify-content-center align-items-center m-t-50 m-b-50">
<div class="row mb-3">
<div class="col-4">
<validation-wrapper-component :validator="$v.parameters.owner_reference">
<label class="text-primary">Reference</label>
<input type="text" class="form-control" v-model="parameters.owner_reference">
</validation-wrapper-component>
</div>
<div class="col-4">
<validation-wrapper-component :validator="$v.parameters.invoice_reference">
<label class="text-primary">Invoice Reference</label>
<input type="text" class="form-control" v-model="parameters.invoice_reference">
</validation-wrapper-component>
</div>
<div class="col-4">
<validation-wrapper-component :validator="$v.parameters.receipt_reference">
<label class="text-primary">Receipt Reference</label>
<input type="text" class="form-control" v-model="parameters.receipt_reference">
</validation-wrapper-component>
</div>
</div>
<div class="row">
<div class="col-3">
<validation-wrapper-component :validator="$v.parameters.startDate">
<label class="all-caps">Start Date</label>
<date-picker-component :parameters="parameters" v-model.lazy="parameters.startDate"></date-picker-component>
</validation-wrapper-component>
</div>
<div class="col-3">
<validation-wrapper-component :validator="$v.parameters.endDate">
<label class="all-caps">End Date</label>
<date-picker-component :parameters="parameters" v-model.lazy="parameters.endDate"></date-picker-component>
</validation-wrapper-component>
</div>
<div class="col-3">
<div class="row text-center">
<div class="col b-a b-grey padding-20 m-r-15 pointer bg-complete text-white" @click="getReportFilter()">Mapped Report</div>
</div>
</div>
</div>
</div>
<div class="row m-t-10 m-b-10">
<div class="col">
<div class="row p-t-10 p-b-10 b-b b-grey text-master-light">
@@ -35,7 +90,7 @@
</div>
</div>
<list-component ref="TransactionsMappedList" section="TransactionsMappedSection" :endpoint="route('api.accounting.bank.transaction')" :options="filter">
<list-component :key="step" ref="TransactionsMappedList" section="TransactionsMappedSection" :endpoint="route('api.accounting.bank.transaction')" :options="filter">
<template slot="list" slot-scope="{data}">
<statement-transaction-mapped-component :data="data" :section="section"></statement-transaction-mapped-component>
</template>
@@ -44,22 +99,175 @@
</div>
</div>
</div>
<!-- report for imported Invoices -->
<div class="row" v-if="step > 0 && report == 'importedInv'">
<div class="col">
<div class="row">
<div class="col">
<div class="justify-content-center align-items-center m-t-50 m-b-50">
<div class="row">
<div class="col-3">
<validation-wrapper-component :validator="$v.parameters.startDate">
<label class="all-caps">Start Date</label>
<date-picker-component :parameters="parameters" v-model.lazy="parameters.startDate"></date-picker-component>
</validation-wrapper-component>
</div>
<div class="col-3">
<validation-wrapper-component :validator="$v.parameters.endDate">
<label class="all-caps">End Date</label>
<date-picker-component :parameters="parameters" v-model.lazy="parameters.endDate"></date-picker-component>
</validation-wrapper-component>
</div>
<div class="col-3">
<div class="row text-center">
<div class="col b-a b-grey padding-20 m-r-15 pointer bg-complete text-white" @click="getHistoryImportedInvReport()">History Imported Invoices Report</div>
</div>
</div>
</div>
</div>
<div class="row m-t-10 m-b-10">
<div class="col">
<div class="row p-t-10 p-b-10 b-b b-grey text-master-light">
<div class="col-2">Date</div>
</div>
</div>
</div>
<list-component :key="step" ref="HistoryImportedInvList" section="HistoryImportedInvSection" :endpoint="route('api.accounting.history.imported')" :options="filter">
<template slot="list" slot-scope="{data}">
<history-imported-invoices :data="data" :section="section"></history-imported-invoices>
</template>
</list-component>
</div>
</div>
</div>
</div>
<!-- report for imported Receipts -->
<div class="row" v-if="step > 0 && report == 'importedRec'">
<div class="col">
<div class="row">
<div class="col">
<div class="justify-content-center align-items-center m-t-50 m-b-50">
<div class="row">
<div class="col-3">
<validation-wrapper-component :validator="$v.parameters.startDate">
<label class="all-caps">Start Date</label>
<date-picker-component :parameters="parameters" v-model.lazy="parameters.startDate"></date-picker-component>
</validation-wrapper-component>
</div>
<div class="col-3">
<validation-wrapper-component :validator="$v.parameters.endDate">
<label class="all-caps">End Date</label>
<date-picker-component :parameters="parameters" v-model.lazy="parameters.endDate"></date-picker-component>
</validation-wrapper-component>
</div>
<div class="col-3">
<div class="row text-center">
<div class="col b-a b-grey padding-20 m-r-15 pointer bg-complete text-white" @click="getHistoryImportedRecReport()">History Imported Receipts Report</div>
</div>
</div>
</div>
</div>
<div class="row m-t-10 m-b-10">
<div class="col">
<div class="row p-t-10 p-b-10 b-b b-grey text-master-light">
<div class="col-2">Date</div>
</div>
</div>
</div>
<list-component :key="step" ref="HistoryImportedRecList" section="HistoryImportedRecSection" :endpoint="route('api.accounting.history.imported')" :options="filter">
<template slot="list" slot-scope="{data}">
<history-imported-receipts :data="data" :section="section"></history-imported-receipts>
</template>
</list-component>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
import { required } from "vuelidate/lib/validators";
export default {
data() {
return {
parameters: {
startDate: '',
endDate: '',
owner_reference: '',
invoice_reference: '',
receipt_reference: ''
},
step: 0,
filter: {},
report: ''
}
},
validations: {
parameters: {
startDate: {
required
},
endDate: {
required
},
owner_reference: {},
invoice_reference: {},
receipt_reference: {}
},
},
created(){
this.parameters.startDate = this.startDate();
this.parameters.endDate = this.endDate();
},
methods: {
startDate() {
var date = new Date();
return '01-'+(date.getMonth() + 1)+'-'+date.getFullYear();
},
endDate() {
var date = new Date();
var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
return lastDay.getDate()+'-'+(lastDay.getMonth() + 1)+'-'+lastDay.getFullYear();
},
getReportFilter() {
this.filter = {min_amount: 0, is_mapped: true, statement_transaction_owner_type_in: [1, 2], statement_transaction_owner_status_in: [3], per_page: 100, order_by: {column: 'posting_date', DESC: true}};
this.step = 1
this.filter = {...this.filter, ...{statement_transaction_posting_start: this.parameters.startDate}};
this.filter = {...this.filter, ...{statement_transaction_posting_end:this.parameters.endDate}}
if (typeof this.parameters.owner_reference != 'undefined' && this.parameters.owner_reference != '') this.filter = {...this.filter, ...{statement_transaction_owner_reference: this.parameters.owner_reference}};
if (typeof this.parameters.invoice_reference != 'undefined' && this.parameters.invoice_reference != '') this.filter = {...this.filter, ...{statement_transaction_invoice_reference: this.parameters.invoice_reference}};
if (typeof this.parameters.receipt_reference != 'undefined' && this.parameters.receipt_reference != '') this.filter = {...this.filter, ...{statement_transaction_receipt_reference: this.parameters.receipt_reference}};
this.step = this.step + 1;
this.report = 'mappedRecords';
},
getHistoryImportedRecReport() {
this.filter = {
imported_date_from: this.parameters.startDate,
imported_date_to:this.parameters.endDate,
group_by_imported_date:true,
type:'receipts'
};
this.step = this.step + 1;
this.report = 'importedRec';
},
getHistoryImportedInvReport() {
this.filter = {
imported_date_from: this.parameters.startDate,
imported_date_to:this.parameters.endDate,
group_by_imported_date:true,
type:'invoices'
};
this.step = this.step + 1;
this.report = 'importedInv';
}
},
}
@@ -164,7 +164,7 @@
<div class="row">
<div class="col-12">
<modal-component class="animate__animated animate__fast animate__fadeIn" styleType="fill-in" type="ModalImportInvoice">
<imported-invoice-mapped-component section="importInvoiceMapping" v-if="mappedTrue" :files="files"></imported-invoice-mapped-component>
<imported-invoice-mapped-component section="importInvoiceMapping" v-if="invMappedTrue" :files="files"></imported-invoice-mapped-component>
</modal-component>
</div>
</div>
@@ -192,7 +192,7 @@
</file-input-component>
</div>
</div>
<div class="btn btn-lg btn-primary m-t-20 requestModal" data-type="ModalImportInvoice" @click="importReceipts">Import Receipts</div>
<div class="btn btn-lg btn-primary m-t-20 requestModal" data-type="ModalImportReceipt" @click="importReceipts">Import Receipts</div>
<!-- todo-new: delete later --><br><div class="btn btn-lg btn-primary m-t-20" @click="exportStage++">Nest Step</div>
<br>
<div class="row">
@@ -202,8 +202,8 @@
</div>
<div class="row">
<div class="col-12">
<modal-component class="animate__animated animate__fast animate__fadeIn" styleType="fill-in" type="ModalImportInvoice">
<imported-invoice-mapped-component section="importReceiptMapping" v-if="mappedTrue" :files="files"></imported-invoice-mapped-component>
<modal-component class="animate__animated animate__fast animate__fadeIn" styleType="fill-in" type="ModalImportReceipt">
<imported-receipt-mapped-component section="importReceiptMapping" v-if="recMappedTrue" :files="files"></imported-receipt-mapped-component>
</modal-component>
</div>
</div>
@@ -240,7 +240,8 @@ export default {
files: [],
parameters: {},
section: 'bankTransactionSection',
mappedTrue: false,
invMappedTrue: false,
recMappedTrue: false,
selectAll: false,
}
},
@@ -259,10 +260,10 @@ export default {
},
methods: {
importInvoice(){
this.mappedTrue = true;
this.invMappedTrue = true;
},
importReceipts(){
this.mappedTrue = true;
this.recMappedTrue = true;
},
exportInvoiceToAutoCount(){
const checkedStatementTransactions = this.getCheckedStatementOwners();
@@ -1,20 +1,23 @@
<template>
<div class="row">
<div class="col">
<div class="row text-left no-margin bg-white" v-if="!isLoading" v-for="item in vouchers" v-bind:key="item.id" >
<div v-if="vouchers && vouchers.length > 0" class="row fs-10 p-b-5">List of Vouchers, click to select</div>
<div class="row text-left no-margin bg-white p-b-10" v-if="!isLoading" v-for="item in vouchers" v-bind:key="item.id" >
<div id="select-option" name="select-option" class="col b-b b-grey p-t-10 p-b-10 pointer p-t-10 p-b-10" @click="selectVoucher(item)">
<div class="row parentContainer">
<div class="col">
<p>{{ item.voucher.code }}</p>
<div class="row">
<!-- <div class="col">
<p v-if="item.voucher.type == 'AMOUNT'">RM{{ item.voucher.value/100 }} Discount</p>
<p v-if="item.voucher.type == 'PERCENT'">{{ item.voucher.value }}% Discount</p>
</div>
<div class="col" v-if="item.voucher.end_date">
</div> -->
<span>{{ item.voucher.code }}</span>
</div>
<div class="row">
<span v-if="item.voucher.end_date">
Valid till {{ item.voucher.end_date }}
</div>
<div class="col" v-else>
</span>
<span v-else>
No expiry date
</div>
</span>
</div>
</div>
</div>
@@ -4,12 +4,12 @@
<div class="row" v-if="!item.transaction_bill">
<div class="col">
<div class="row">
<div class="col p-t-10 p-b-10 p-r-0 pointer" @click="clickExpand()" :class="[{'bg-master-lighter': item.status === 1 && item.type !== 6}, {'bg-white': item.status !== 1 && item.status !== 4}, {'bg-warning-lighter': item.type === 6}]">
<div class="col p-t-10 p-b-10 p-r-0 pointer" @click="clickExpand()" :class="[{'bg-master-lighter': item.status === 1 && item.type !== 6}, {'bg-white': item.status !== 1 && item.status !== 4}, {'bg-warning-lighter': item.status === 7}, {'bg-warning-lighter': item.type === 6}]">
<div class="row m-b-5">
<div class="col-auto">
<div class="font-heading fs-8 muted all-caps">Status</div>
<div class="font-heading fs-10 bold" v-if="item.type === 1" :class="[{'text-danger': item.status === 1 || item.status === 4}, {'text-success': item.status !== 1 && item.status !== 4}]">
{{ item.status === 1 ? 'Pending Verification' : item.status === 4 ? 'Rejected' : 'Processing Payment'}}
<div class="font-heading fs-10 bold" v-if="item.type === 1" :class="[{'text-danger': item.status === 1 || item.status === 4}, {'text-success': item.status !== 1 && item.status !== 4 && item.status !== 7}, {'text-danger': item.status === 7}]">
{{ item.status === 7 ? 'Refunded' : (item.status === 1 ? 'Pending Verification' : item.status === 4 ? 'Rejected' : 'Payment Approved')}}
</div>
<div class="font-heading fs-10 bold" v-if="item.type === 6" :class="[{'text-danger': item.status === 1 || item.status === 4}, {'text-success': item.status !== 1 && item.status !== 4}]">
{{ item.status === 1 ? 'Pending Verification' : item.status === 4 ? 'Rejected' : 'Processing Payment'}}
@@ -18,13 +18,13 @@
<div class="col-auto p-l-0">
<div class="font-heading fs-8 muted all-caps">Payment Amount</div>
<div class="font-heading fs-10 bold">
{{item.currency.short_code}} {{(Math.round((item.amount + Number.EPSILON) * 100) / 100).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}}
{{item.original_currency.short_code}} {{(Math.round((item.original_amount + Number.EPSILON) * 100) / 100).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}}
</div>
</div>
<div class="col-auto p-l-0" v-if="totalRefunds !== 0">
<div class="font-heading fs-8 muted all-caps">Refunded Amount</div>
<div class="font-heading fs-10 bold text-danger">
{{item.original_currency.short_code}} {{(Math.round((totalRefunds + Number.EPSILON) * 100) / 100).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}}
{{item.currency.short_code}} {{(Math.round((totalConvertRefunds + Number.EPSILON) * 100) / 100).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}}
</div>
</div>
</div>
@@ -39,7 +39,7 @@
</div>
</div>
</div>
<div class="col-auto" v-if="item.status !== 3" :class="[{'bg-master-light': item.status === 1 && item.type !== 6}, {'bg-master-lighter': item.status === 2}, {'bg-warning-light': item.type === 6}]">
<div class="col-auto" v-if="item.status !== 3" :class="[{'bg-master-light': item.status === 1 && item.type !== 6}, {'bg-master-lighter': item.status === 2}, {'bg-warning-lighter': item.status === 7}, {'bg-warning-light': item.type === 6}]">
<div class="row align-items-center h-100" v-if="item.status !== 1 || item.payment_method !== 5">
<div class="col">
<i class="fa" :class="[{'fa-cloud-download': item.status === 1 || item.status === 2}, {'fa-ban': item.status === 4}, {'muted': item.status === 1 || item.status === 2}, {'text-danger': item.status === 4}]"></i>
@@ -61,7 +61,7 @@
<div class="row m-b-5">
<div class="col-auto">
<div class="font-heading fs-8 muted all-caps">Status</div>
<div class="font-heading fs-10 bold" :class="[{'text-danger': item.transaction_bill.status === 1 || item.transaction_bill.status === 4}, {'text-success': item.transaction_bill.status !== 1 && item.transaction_bill.status !== 4}]">
<div class="font-heading fs-10 bold" :class="[{'text-success': item.transaction_bill.status !== 4}, {'text-success': item.transaction_bill.status !== 1 && item.transaction_bill.status !== 4}]">
{{ item.transaction_bill.status === 1 ? 'Processing Payment' : 'Transferred'}}
</div>
</div>
@@ -133,7 +133,13 @@
<div class="font-heading all-caps fs-10">Requested Refund Amount</div>
</div>
<div class="col-auto text-right">
<div class="font-heading fs-10">{{item.currency.short_code}} {{(Math.round((totalRequestedRefund + Number.EPSILON) * 100) / 100).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}}</div>
<div class="font-heading fs-10">{{item.original_currency.short_code}} {{(Math.round((totalRequestedRefund + Number.EPSILON) * 100) / 100).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}}</div>
</div>
</div>
<div class="row align-items-end m-b-10 bold text-danger" v-if="totalRequestedRefund != 0">
<div class="col"></div>
<div class="col-auto text-right">
<div class="font-heading fs-10">{{item.currency.short_code}} {{(Math.round((totalRequestedConvertRefund + Number.EPSILON) * 100) / 100).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}}</div>
</div>
</div>
<div class="row align-items-end m-b-10 bold text-danger" v-if="totalRefunds != 0">
@@ -141,7 +147,13 @@
<div class="font-heading all-caps fs-10">Refunded Amount</div>
</div>
<div class="col-auto text-right">
<div class="font-heading fs-12">{{item.original_currency.short_code}} {{(Math.round((totalRefunds + Number.EPSILON) * 100) / 100).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}}</div>
<div class="font-heading fs-10">{{item.original_currency.short_code}} {{(Math.round((totalRefunds + Number.EPSILON) * 100) / 100).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}}</div>
</div>
</div>
<div class="row align-items-end m-b-10 bold text-danger" v-if="totalRefunds != 0">
<div class="col"></div>
<div class="col-auto text-right">
<div class="font-heading fs-10">{{item.currency.short_code}} {{(Math.round((totalConvertRefunds + Number.EPSILON) * 100) / 100).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}}</div>
</div>
</div>
<div class="row align-items-end bold m-b-10 text-primary">
@@ -187,6 +199,14 @@
<div class="font-heading fs-12">MYR {{(Math.round((item.amount + Number.EPSILON) * 100) / 100).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}}</div>
</div>
</div>
<div class="row align-items-end m-b-10 bold text-success" v-if="totalRefunds != 0">
<div class="col">
<div class="font-heading all-caps fs-10">Your Payment After Refund</div>
</div>
<div class="col-auto text-right">
<div class="font-heading fs-12">MYR {{(Math.round((item.amount - totalConvertRefunds + Number.EPSILON) * 100) / 100).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}}</div>
</div>
</div>
<div class="row">
<div class="col">
<div class="font-heading all-caps fs-10 m-b-5">Your Payment Proof</div>
@@ -271,14 +291,96 @@
</div>
</div>
</div>
<div class="row m-t-10" v-show="[2, 3].includes(item.status) && totalRequestedConvertRefund < data.booking.amount">
<div class="col">
<button class="btn btn-xs all-caps b-rad-none bg-master-lighter btn-block no-border requestModal hide" data-type="transferSummary">Request Refund</button>
<div class="row m-t-10" v-show="[2, 3].includes(item.status) && (totalRequestedRefund + totalRefunds) < data.original_amount">
<div class="col" v-if="!item.transaction_bill && $store.getters.isAdmin">
<button class="btn btn-xs all-caps b-rad-none bg-master-lighter btn-block no-border requestModal" data-type="transferSummary">Request Refund</button>
<modal-component class="animate__animated animate__fast animate__fadeIn" styleType="fill-in" type="transferSummary" size="large">
<refund-confirmation-component :data="data" :section="section" :totalRefunds="totalRequestedRefund + totalRefunds"></refund-confirmation-component>
</modal-component>
</div>
</div>
<div class="row m-t-10" v-if="data.transaction_refunds.length > 0">
<div class="col">
<button class="btn btn-xs all-caps b-rad-none bg-master-lighter btn-block no-border pointer" @click="clickExpandRefundTransactions">
<div class="row justify-content-between">
<div class="col-auto">
<i class="fa" :class="[{'fa-angle-up': expandRefundTransactions}, {'fa-angle-down': !expandRefundTransactions}]"></i>
</div>
<div class="col">
Show Refund Transactions
</div>
<div class="col-auto">
<i class="fa" :class="[{'fa-angle-up': expandRefundTransactions}, {'fa-angle-down': !expandRefundTransactions}]"></i>
</div>
</div>
</button>
</div>
</div>
</div>
</div>
<div class="row" v-if="data.transaction_refunds.length > 0 && expandRefundTransactions">
<div class="col bg-white padding-15">
<div class="b-b b-grey m-b-5" v-for="(refund, index) in data.transaction_refunds">
<div class="row m-b-10">
<div class="col-auto">
<div class="font-heading fs-10 muted all-caps">Created At</div>
<div class="font-heading fs-10">
{{ refund.created_at }}
</div>
</div>
<div class="col-auto">
<div class="font-heading fs-10 muted all-caps">Status</div>
<div class="font-heading fs-10">
<div class="font-heading fs-10 bold" :class="[{'text-warning': refund.status === 1}, {'text-success': refund.status === 2}, {'text-danger': refund.status === 4}]">{{ refund.status === 1 ? 'Pending Verification' : refund.status === 2 ? 'Approved' : 'Rejected'}}</div>
</div>
</div>
<div class="col text-right">
<div class="font-heading fs-10 muted all-caps">Amount</div>
<div class="font-heading fs-10">
<div class="font-heading fs-10">{{refund.currency.short_code}} {{(Math.round((refund.amount + Number.EPSILON) * 100) / 100).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}}</div>
</div>
</div>
<div class="col-auto text-right">
<div class="font-heading fs-10 muted all-caps">Amount</div>
<div class="font-heading fs-14 text-success bold">
<div class="font-heading fs-10">{{refund.original_currency.short_code}} {{(Math.round((refund.original_amount + Number.EPSILON) * 100) / 100).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}}</div>
</div>
</div>
</div>
<div class="row m-b-15 text-right parentContainer" v-if="$store.getters.isAdmin && refund.status === 1">
<div class="col">
<button class="btn btn-xs btn-outline-danger b-rad-none m-r-5 requestModal" data-type="rejectRefund">
<i class="fa fa-times fa-fw"></i>
</button>
<modal-component class="animate__animated animate__fast animate__fadeIn" type="rejectRefund">
<general-confirmation-form-component
contentText="Are you sure you want to reject this refund?"
modalType="delete"
class="text-center"
:apiRoute="route('api.transaction.refund.status.update', refund.id, 4)"
apiMethod="put"
:section="section"
>
</general-confirmation-form-component>
</modal-component>
<button class="btn btn-xs btn-outline-primary b-rad-none m-r-5 requestModal" data-type="approveRefund">
<i class="fa fa-check fa-fw"></i>
</button>
<modal-component class="animate__animated animate__fast animate__fadeIn" type="approveRefund">
<general-confirmation-form-component
contentText="Are you sure you want to approve this refund?"
modalType="confirm"
class="text-center"
:apiRoute="route('api.transaction.refund.status.update', refund.id, 2)"
apiMethod="put"
:section="section"
>
</general-confirmation-form-component>
</modal-component>
</div>
</div>
</div>
</div>
</div>
</div>
@@ -291,6 +393,7 @@
data(){
return {
expandPaymentDetails: false,
expandRefundTransactions: false,
amount: (Math.round(1000 * 100) / 100).toFixed(2),
parameters: {
amount: (Math.round(1000 * 100) / 100).toFixed(2),
@@ -313,12 +416,12 @@
let vm = this;
var TotalRequestedRefund = 0;
this.data.transaction_refunds.forEach(function(refunds) {
TotalRequestedRefund += refunds.status === 1 ? refunds.original_amount : 0;
TotalRequestedRefund += refunds.status === 1 ? refunds.amount : 0;
});
if (vm.data.booking.fixed_currency.id != 1 && this.data.transaction_refunds[0]) {
TotalRequestedRefund = (TotalRequestedRefund * this.data.transaction_refunds[0].currency_rate);
}
return ((Math.round((TotalRequestedRefund + Number.EPSILON) * 100) / 100).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
// if (vm.data.booking.fixed_currency.id != 1 && this.data.transaction_refunds[0]) {
// TotalRequestedRefund = (TotalRequestedRefund * this.data.transaction_refunds[0].currency_rate);
// }
return TotalRequestedRefund;
},
totalRefunds() {
var TotalRequestedRefund = 0;
@@ -326,11 +429,22 @@
TotalRequestedRefund += refunds.status === 2 ? refunds.original_amount : 0;
});
return TotalRequestedRefund;
},
totalConvertRefunds() {
var TotalRequestedRefund = 0;
this.data.transaction_refunds.forEach(function(refunds) {
TotalRequestedRefund += refunds.status === 2 ? refunds.amount : 0;
});
return TotalRequestedRefund;
}
},
methods: {
clickExpand(){
this.expandPaymentDetails = !this.expandPaymentDetails;
this.expandRefundTransactions = false;
},
clickExpandRefundTransactions(){
this.expandRefundTransactions = !this.expandRefundTransactions;
},
},
mixins: [componentHandler]
@@ -3,67 +3,52 @@
<div class="col bg-white padding-25">
<div class="row p-b-10">
<div class="col">
<div class="row m-b-5">
<div class="col">
<div class="font-heading all-caps bold fs-10">Request Refund</div>
<div class="font-heading all-caps bold fs-10">Request Refund</div>
</div>
</div>
<div class="row m-b-10">
<div class="col-7">
<div class="font-heading all-caps fs-10 m-b-5">Refund Type:</div>
<div class="row p-l-15">
<div v-for="(method, index) in refundMethods" :key="index"
class="col p-t-20 p-b-20 bg-master-lightest text-center b-grey pointer"
:class="{ 'bg-complete text-white': method.name === refundMethod.name }"
@click="updateRefundType(method)">
{{ method.name }}
</div>
</div>
</div>
</div>
<div class="row">
<div class="row m-r-0 m-b-10" v-if="refundMethod.name === 'Partially Refund'">
<div class="col">
<div class="row">
<validation-wrapper-component :validator="$v.refundAmount">
<label>Amount</label>
<input class="form-control" name="amount" v-model="refundAmount"
:disabled="refundMethod.name === 'Fully Refund'" v-money="moneyV2">
</validation-wrapper-component>
</div>
<div class="col-auto b-r b-t b-b b-grey">
<div class="row h-100 align-items-center">
<div class="col">
<div class="row m-b-10">
<div class="col">
<div class="row parentContainer">
<div class="col">
<div class="row" >
<div class="col-7 p-r-0">
<div class="row m-b-10">
<div class="col">
<div class="font-heading all-caps fs-10 m-b-5">Refund Type: </div>
<div class="row p-l-15">
<div class="col p-t-20 p-b-20 bg-master-lightest text-center b-grey pointer" :class="[{'bg-complete': refundMethod.name === 'Fully Refund'}, {'text-white': refundMethod.name === 'Fully Refund'}]" @click="updateRefundType({name: 'Fully Refund'})">
Full Refund
</div>
<div class="col p-t-20 p-b-20 bg-master-lightest text-center b-grey pointer" :class="[{'bg-complete': refundMethod.name === 'Partially Refund'}, {'text-white': refundMethod.name === 'Partially Refund'}]" @click="updateRefundType({name: 'Partially Refund'})">
Partial Refund
</div>
</div>
</div>
</div>
<div class="row m-r-0 m-b-10" v-if="refundMethod.name === 'Partially Refund'">
<div class="col p-r-0">
<validation-wrapper-component :validator="$v.refundAmount">
<label>Amount</label>
<input class="form-control" name="amount" v-model="refundAmount" :disabled="refundMethod.name == 'Fully Refund'" v-money="moneyV2">
</validation-wrapper-component>
</div>
<div class="col-auto b-r b-t b-b b-grey">
<div class="row h-100 align-items-center">
<div class="col">
<div class="font-heading fs-10 muted">{{data.booking.fixed_currency.short_code}}</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="font-heading fs-10 muted">{{ data.booking.fixed_currency.short_code }}</div>
</div>
</div>
</div>
</div>
<div class="row m-t-10 m-b-10">
<div class="col">
<div class="font-heading all-caps fs-10 m-b-5">Paid Amount: {{ paidAmount }}</div>
<div class="font-heading all-caps fs-10 m-b-5">Refund Amount: {{ refundAmount }}</div>
</div>
</div>
<div class="row">
<div class="col-auto">
<button class="btn btn-lg btn-default bg-master-lightest b-rad-none all-caps fs-12" data-dismiss="modal">Cancel</button>
<button class="btn btn-lg btn-default bg-master-lightest b-rad-none all-caps fs-12"
data-dismiss="modal">Cancel</button>
</div>
<div class="col text-right">
<button class="btn btn-lg btn-success b-rad-none all-caps fs-12" @click="submitForm()">Confirm & Proceed</button>
<button class="btn btn-lg btn-success b-rad-none all-caps fs-12" @click="submitForm()">Confirm &
Proceed</button>
</div>
</div>
</div>
@@ -71,47 +56,57 @@
</template>
<script>
import FormHandler from '../../../general/mixins/formHandler';
import ModalFormHandler from '../../../general/mixins/modalFormHandler';
import { required, maxValue } from "vuelidate/lib/validators";
export default {
props: {
totalRefunds:{
type: Number,
default: 0,
import FormHandler from '../../../general/mixins/formHandler';
import ModalFormHandler from '../../../general/mixins/modalFormHandler';
import { maxValue } from "vuelidate/lib/validators";
export default {
props: {
totalRefunds: {
type: Number,
default: 0,
}
},
data() {
return {
refundMethod: { name: 'Fully Refund', status: false },
refundMethods: [
{ name: 'Fully Refund', label: 'Full Refund' },
// { name: 'Partially Refund', label: 'Partial Refund' }
]
}
},
validations() {
return {
refundAmount: {
maxValue: maxValue(this.refundMaxValue)
}
}
},
computed: {
refundAmount() {
// return (Math.round((this.data.booking.amount - this.totalRefunds + Number.EPSILON) * 100) / 100).toFixed(2);
return (Math.round((this.data.original_amount - this.data.refunded_amount + Number.EPSILON) * 100) / 100).toFixed(2);
},
refundMaxValue() {
return this.refundAmount;
},
paidAmount() {
return this.data.original_amount;
},
},
methods: {
submitForm() {
this.parameters.amount = this.refundAmount;
this.submit(this.route('api.booking.refund.create', this.data.booking.id, this.data.id), 'post', this.section, true, true)
},
updateRefundType(refund) {
this.refundMethod = { ...refund, status: !this.refundMethod.status };
if (this.refundMethod.name === 'Fully Refund') {
this.refundAmount = this.refundMaxValue;
}
},
data(){
return {
refundAmount: (Math.round((this.data.booking.amount - this.totalRefunds + Number.EPSILON) * 100) / 100).toFixed(2),
refundMethod: {
name: 'Partially Refund',
status: false
},
refundMaxValue: (Math.round((this.data.booking.amount - this.totalRefunds + Number.EPSILON) * 100) / 100).toFixed(2),
}
},
validations() {
return {
refundAmount: {
// required,
maxValue: maxValue(this.refundMaxValue)
}
}
},
methods: {
submitForm(){
this.parameters.amount = this.refundAmount;
this.submit(this.route('api.booking.refund.create', this.data.booking.id, this.data.id), 'post', this.section, true, true)
},
updateRefundType(refund){
this.refundMethod = {
name: refund.name,
status: !this.refundMethod.status
}
this.refundMethod.name === 'Fully Refund' ? this.refundAmount = this.refundMaxValue : '';
},
},
mixins: [FormHandler, ModalFormHandler]
}
</script>
},
mixins: [FormHandler, ModalFormHandler]
}
</script>
@@ -115,7 +115,7 @@
approveRefund(status){
this.isLoading = true;
this.parameters.status = status;
this.submit(this.route('api.transaction.refund.status.update', this.data.id), 'put', 'listRefundTransactionSection', true, true);
this.submit(this.route('api.transaction.refund.status.update', this.data.id, status), 'put', 'listRefundTransactionSection', true, true);
},
},
mixins: [componentHandler, staticFormHandler]
@@ -56,6 +56,16 @@
<span class="flag-icon" :class="'flag-icon-'+item.original_currency.country.short_code.toLowerCase()"></span> {{item.original_currency.short_code}}
</div>
</div>
<div class="col text-right" v-if="totalRefunds !== 0">
<div class="row">
<div class="col">
<div class="font-heading fs-10 muted all-caps">Refunded Amount</div>
<div class="font-heading fs-14 text-danger bold">
{{(Math.round((totalRefunds + Number.EPSILON) * 100) / 100).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}}
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-auto">
@@ -95,7 +105,7 @@
<div class="col text-right">
<div class="font-heading fs-10 muted all-caps">Amount</div>
<div class="font-heading fs-14 text-success bold">
{{(Math.round((item.original_amount + Number.EPSILON) * 100) / 100).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}}
{{(Math.round((item.original_amount - totalRefunds + Number.EPSILON) * 100) / 100).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}}
</div>
</div>
</div>
@@ -124,11 +134,20 @@
active: false,
}
},
computed: {
totalRefunds() {
var TotalRequestedRefund = 0;
this.data.transaction_refunds.forEach(function(refunds) {
TotalRequestedRefund += refunds.status === 2 ? refunds.original_amount : 0;
});
return TotalRequestedRefund;
}
},
methods: {
activate(){
this.active = !this.active;
this.$emit('input', this.item)
}
},
},
mixins: [componentHandler]
}
@@ -252,21 +252,21 @@
</div>
</validation-wrapper-component>
</div>
<!-- <modal-component id="choose-voucher-modal" class="animate__animated animate__fast animate__fadeIn" styleType="fill-in" type="voucherList">
<modal-component id="choose-voucher-modal" class="animate__animated animate__fast animate__fadeIn" styleType="fill-in" type="voucherList">
<list-vouchers-component :employee="data.company.employee" @selected-voucher="handleSelectedVoucher"></list-vouchers-component>
</modal-component> -->
</modal-component>
</div>
<span class="text-primary bold text-underline m-l-5 cursor text-small fs-12" style="margin-bottom: -10px; margin-top: -5px;" @click="showApplyVoucher=!showApplyVoucher" v-show="!showApplyVoucher">Apply a voucher</span>
<div class="row m-l-0 m-r-0" style="height: 20px">
<div class="row m-l-0 m-r-0" v-show="showApplyVoucher" style="height: 20px">
<i class="fa fa-spinner fa-spin m-b-5" v-if="voucherIsChecking"></i>
<span class="text-danger" v-if="voucherCodeFailedReason">{{ voucherCodeFailedReason }}</span>
<span class="text-success" v-if="voucherCodeFailedReason === '' && voucherValidated">Voucher applied</span>
</div>
<!-- <div class="row m-l-0 m-r-0">
<div class="row m-l-0 m-r-0" v-show="showApplyVoucher">
<div class="col">
<available-vouchers-component :employee="data.company.employee" @selected-voucher="handleSelectedVoucher"></available-vouchers-component>
</div>
</div> -->
</div>
<div class="row m-t-5">
<div class="col">
<div class="row p-l-15 p-r-15">
@@ -240,7 +240,11 @@
},
watch: {
'data': function () {
this.products = this.data.purchase_order.details
if (this.data && this.data.purchase_order && this.data.purchase_order.details) {
this.products = this.data.purchase_order.details;
} else {
this.products = [];
}
}
},
methods: {

Some files were not shown because too many files have changed in this diff Show More