Merge branch 'master' of gitlab.com:CIEFWorldwideSdnBhd/exchange-2.0 into 1688-integration

# Conflicts:
#	routes/api.php
This commit is contained in:
JiaSheng
2024-03-31 22:21:01 +08:00
129 changed files with 3727 additions and 377 deletions
@@ -0,0 +1,11 @@
<?php
namespace App\Classes\Exceptions;
use App\Classes\ValueObjects\Constants\HttpStatus;
final class JobResourceNotFoundException extends ServiceApiException {
public function __construct(?string $message = null) {
parent::__construct($message ?? 'Unable to find the requested resource', HttpStatus::RESOURCE_NOT_FOUND);
}
}
@@ -17,6 +17,7 @@ use Illuminate\Http\Resources\Json\ResourceCollection;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Classes\Exceptions\JobResourceNotFoundException;
abstract class AbstractControllerLogic
{
@@ -67,7 +68,19 @@ abstract class AbstractControllerLogic
return $response;
} catch (ErrorException|GeneralExceptions $exception){
log::error($exception);
if ($exception instanceof JobResourceNotFoundException) {
Log::channel('vue_polling')->info(sprintf(
"Uncaught exception '%s' with message '%s' in %s:%d",
get_class($exception),
$exception->getMessage(),
$exception->getTrace()[0]['file'],
$exception->getTrace()[0]['line']
));
}
else{
log::error($exception);
}
return (new ApiResponseObject($this->getNotificationTitle().' failed', $exception->getMessage(),
$exception->getCode() ? $exception->getCode() : HttpStatus::SERVER_ERROR))->handler();
@@ -4,9 +4,11 @@ namespace App\Classes\General\Eloquent;
use App\Classes\Exceptions\ResourceNotFoundException;
use App\Classes\Exceptions\JobResourceNotFoundException;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Psy\Exception\ErrorException;
use Illuminate\Support\Facades\Log;
abstract class AbstractFetchRecord extends AbstractGetRecord
{
@@ -27,12 +29,18 @@ abstract class AbstractFetchRecord extends AbstractGetRecord
* @return Model
* @throws ResourceNotFoundException
*/
public function getResults(Builder $query): Model {
public function getResults(Builder $query, array $param = []): Model {
if(!$query->exists()){
throw new ResourceNotFoundException('Unable to find any record based on the criteria provided');
$table = $query->getModel()->getTable();
if($table ==='job_results'){
throw new JobResourceNotFoundException('Unable to find any job based on the criteria provided');
}
else{
throw new ResourceNotFoundException('Unable to find any record based on the criteria provided');
}
}
return $query->first();
}
}
}
@@ -30,11 +30,25 @@ abstract class AbstractGetRecord
return $this->filters->only(self::DECORATION_FILTERS);
}
// /**
// * @param null|string $json
// * @return array
// */
// public function deserializeFilters(?string $json): array {
// return $json !== null ? collect(json_decode($json))->toArray() : [];
// }
/**
* @param null|string $json
* @param null|string $param
* @return array
*/
public function deserializeFilters(?string $json): array {
public function deserializeFilters($param): array {
if(gettype($param) == "array"){
$json = implode(',', $param);
}
else{
$json = $param;
}
return $json !== null ? collect(json_decode($json))->toArray() : [];
}
@@ -50,9 +64,9 @@ abstract class AbstractGetRecord
* @param array $filters
* @return mixed
*/
public function handler(array $filters){
public function handler(array $filters, array $params = []){
$this->filters = collect($filters);
return $this->getResults($this->applyFiltersToQuery());
return $this->getResults($this->applyFiltersToQuery(), $params);
}
@@ -65,6 +79,6 @@ abstract class AbstractGetRecord
* @param Builder $query
* @return mixed
*/
abstract function getResults(Builder $query);
abstract function getResults(Builder $query, array $params = []);
}
}
@@ -17,11 +17,11 @@ abstract class AbstractListRecord extends AbstractGetRecord
* @return mixed
* @throws MalformedRequestException
*/
public function execute(array $filters = []){
public function execute(array $filters = [], array $param = []){
try{
return $this->handler($filters);
return $this->handler($filters, $param);
} catch (QueryException $exception){
log::error($exception);
@@ -30,18 +30,24 @@ abstract class AbstractListRecord extends AbstractGetRecord
}
/**
* @param Builder $query
* @return mixed
*/
public function getResults(Builder $query) {
public function getResults(Builder $query, array $param = []) {
$filters = $this->getDecorationFilters();
if($filters->has('order_by')){
$query = $query->orderBy($filters->get('order_by')->column, $filters->get('order_by')->DESC ? 'DESC': 'ASC');
}
return $filters->has('per_page') ? $query->paginate($filters->get('per_page')) : $query->get();
if(!empty($param)){
return $filters->has('per_page') ? $query->paginate($filters->get('per_page'), ['*'], 'page', $param['page']) : $query->get(); //page data from query parameters e.g ?page=1
}
else{
return $filters->has('per_page') ? $query->paginate($filters->get('per_page')) : $query->get();
}
}
@@ -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,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,20 @@
<?php
namespace App\Classes\General\Eloquent\Filters;
use Illuminate\Database\Eloquent\Builder;
class JobId implements Filter
{
/**
* @param Builder $builder
* @param $value
* @return Builder|mixed
*/
public static function apply(Builder $builder, $value)
{
return $builder->where('job_id', $value);
}
}
@@ -0,0 +1,20 @@
<?php
namespace App\Classes\General\Eloquent\Filters;
use Illuminate\Database\Eloquent\Builder;
class OrderByIdDesc implements Filter
{
/**
* @param Builder $builder
* @param $value
* @return Builder|mixed
*/
public static function apply(Builder $builder, $value)
{
return $builder->orderBy('id', 'desc');
}
}
@@ -0,0 +1,19 @@
<?php
namespace App\Classes\General\Eloquent\Filters;
use Illuminate\Database\Eloquent\Builder;
class RequestSignature implements Filter
{
/**
* @param Builder $builder
* @param $value
* @return Builder|mixed
*/
public static function apply(Builder $builder, $value)
{
return $builder->where('request_signature', $value);
}
}
@@ -0,0 +1,18 @@
<?php
namespace App\Classes\General\Eloquent\Filters;
use Illuminate\Database\Eloquent\Builder;
class ResultNotNull implements Filter
{
/**
* @param Builder $builder
* @param $value
* @return Builder|mixed
*/
public static function apply(Builder $builder, $value)
{
return $builder->whereNotNull('result');
}
}
+24
View File
@@ -2,6 +2,7 @@
namespace App\Classes\General;
use Illuminate\Http\Resources\Json\ResourceCollection;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
@@ -42,4 +43,27 @@ class Helper
}
}
}
/**
* @param null|string $param
* @return array
*/
static function deserializeFilters($param): array {
if(gettype($param) == "array"){
$json = implode(',', $param);
}
else{
$json = $param;
}
return $json !== null ? collect(json_decode($json))->toArray() : [];
}
/**
* @param ResourceCollection $collection
* @return array
*/
static function collectionResponse(ResourceCollection $collection){
return json_decode($collection->response()->getContent(), true);
}
}
@@ -0,0 +1,12 @@
<?php
namespace App\Classes\General\Interfaces;
use Illuminate\Database\Eloquent\Relations\MorphMany;
interface KeyValueInterface
{
public function attributes(): morphMany;
}
+52
View File
@@ -0,0 +1,52 @@
<?php
namespace App\Classes\Jobs;
use App\Classes\Modules\Bookings\Processors\ListBookingsJobProcessor;
use App\Classes\Modules\Jobs\DataTransferObjects\ListGenericJobObject;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Models\JobResult;
use Illuminate\Support\Facades\Log;
class ListBookingsJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public $timeout = 900;
/** @var ListGenericJobObject */
private $listGenericJobObject;
private $jobId;
/**
* ListBookingsJob constructor.
* @param ListGenericJobObject $listGenericJobObject
*/
public function __construct(ListGenericJobObject $listGenericJobObject)
{
$this->listGenericJobObject = $listGenericJobObject;
}
public function handle()
{
$rawPayload = $this->job->payload();
if(isset($rawPayload['data']['commandName'])){
$this->listGenericJobObject->setJobCommandName($rawPayload['data']['commandName']);
}
if(isset($rawPayload['data']['command'])){
$this->listGenericJobObject->setJobCommand($rawPayload['data']['command']);
}
$result = (App()->make(ListBookingsJobProcessor::class))->execute($this->listGenericJobObject);
}
public function getJobId(){
return $this->job->getJobId();
}
}
+63
View File
@@ -0,0 +1,63 @@
<?php
namespace App\Classes\Jobs;
use App\Classes\Modules\Documents\Processors\ListDocumentsJobProcessor;
use App\Classes\Modules\Jobs\DataTransferObjects\ListGenericJobObject;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Models\JobResult;
use Illuminate\Support\Facades\Log;
class ListDocumentsJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public $timeout = 900;
/** @var ListGenericJobObject */
private $listGenericJobObject;
private $jobId;
/**
* ListDocumentsJob constructor.
* @param ListGenericJobObject $listGenericJobObject
*/
public function __construct(ListGenericJobObject $listGenericJobObject)
{
$this->listGenericJobObject = $listGenericJobObject;
}
public function handle()
{
$rawPayload = $this->job->payload();
if(isset($rawPayload['data']['commandName'])){
$this->listGenericJobObject->setJobCommandName($rawPayload['data']['commandName']);
}
if(isset($rawPayload['data']['command'])){
$this->listGenericJobObject->setJobCommand($rawPayload['data']['command']);
}
$result = (App()->make(ListDocumentsJobProcessor::class))->execute($this->listGenericJobObject);
//cief todo: Insert into DB: job id, query result, timestamp
// Store the result in the job_results table
//cief todo: why cannot save data in table like this
// $model = new JobResult();
// $model->job_id = $this->job->getJobId();
// $model->result = json_encode($result);
// $model->save();
// Log::error(json_encode($model->id));
}
public function getJobId(){
return $this->job->getJobId();
}
}
+52
View File
@@ -0,0 +1,52 @@
<?php
namespace App\Classes\Jobs;
use App\Classes\Modules\Transactions\Processors\ListTransactionsJobProcessor;
use App\Classes\Modules\Jobs\DataTransferObjects\ListGenericJobObject;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Models\JobResult;
use Illuminate\Support\Facades\Log;
class ListTransactionsJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public $timeout = 900;
/** @var ListGenericJobObject */
private $listGenericJobObject;
private $jobId;
/**
* ListTransactionsJob constructor.
* @param ListGenericJobObject $listGenericJobObject
*/
public function __construct(ListGenericJobObject $listGenericJobObject)
{
$this->listGenericJobObject = $listGenericJobObject;
}
public function handle()
{
$rawPayload = $this->job->payload();
if(isset($rawPayload['data']['commandName'])){
$this->listGenericJobObject->setJobCommandName($rawPayload['data']['commandName']);
}
if(isset($rawPayload['data']['command'])){
$this->listGenericJobObject->setJobCommand($rawPayload['data']['command']);
}
$result = (App()->make(ListTransactionsJobProcessor::class))->execute($this->listGenericJobObject);
}
public function getJobId(){
return $this->job->getJobId();
}
}
@@ -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());
@@ -30,6 +30,7 @@ use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use App\Classes\Modules\Segments\Services\CreatesSeasonalSegment;
use App\Classes\ValueObjects\Constants\Vouchers;
class CreateCustomerLogic extends AbstractControllerLogic
{
@@ -159,7 +160,7 @@ class CreateCustomerLogic extends AbstractControllerLogic
$this->newCustomerToVoucherifyProcessor->execute($company->id, $user, true);
$this->createVoucherProcessor->execute($user, 'WELCOME50%OFF');
$this->createVoucherProcessor->execute($user, Vouchers::WELCOME_50_PERCENT_OFF);
return $this->response($this->authenticationProcessor->execute($request, false));
@@ -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
@@ -0,0 +1,75 @@
<?php
namespace App\Classes\Modules\Bookings\ControllersLogic;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Jobs\ListBookingsJob;
use App\Classes\Modules\Jobs\DataTransferObjects\ListGenericJobObject;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Classes\Modules\Jobs\Services\CreatesJobResult;
class ListBookingJobLogic extends AbstractControllerLogic
{
/**
* @return array
*/
protected function notification():array {
return [
'title' => 'List Booking Job',
'message' => 'You have successfully submit a job to list bookings'
];
}
/** @var CreatesJobResult */
private $createsJobResult;
/**
* ListPackingListsJobLogic constructor.
* @param CreatesJobResult $createsJobResult
*/
public function __construct(CreatesJobResult $createsJobResult)
{
$this->createsJobResult = $createsJobResult;
}
/**
* @param Request $request
* @return JsonResponse
*/
public function logic(Request $request) : JsonResponse
{
$jobId = uniqid();
$user = Auth::user();
$userInfo = (object) [
'type' => $user->type,
];
$userInfoJson = json_encode($userInfo);
$requestSignature = md5($userInfoJson . $request->fullUrl());
$listGenericJobObject = new ListGenericJobObject(
$request->fullUrl(),
$request->all(),
$requestSignature,
null,
$jobId,
$userInfo
);
ListBookingsJob::dispatch($listGenericJobObject)->onQueue('high_priority');
$result = [];
$result['job_id'] = $jobId;
$this->createsJobResult->execute($listGenericJobObject);
return $this->response(['data' => $result]);
}
}
@@ -0,0 +1,46 @@
<?php
namespace App\Classes\Modules\Bookings\Processors;
use App\Classes\Modules\Bookings\Services\ListsBookings;
use App\Classes\Modules\Jobs\Processors\UpdateJobResultProcessor;
use App\Classes\General\Helper;
use App\Classes\Modules\Jobs\DataTransferObjects\ListGenericJobObject;
use App\Http\Resources\ListBookingJobResource;
class ListBookingsJobProcessor
{
/** @var ListsBookings */
private $listsBookings;
/** @var UpdateJobResultProcessor */
private $updateJobResultProcessor;
/**
* ListBookingsJobProcessor constructor.
* @param ListsBookings $listsBookings
* @param UpdateJobResultProcessor $updateJobResultProcessor
*/
public function __construct(ListsBookings $listsBookings, UpdateJobResultProcessor $updateJobResultProcessor)
{
$this->listsBookings = $listsBookings;
$this->updateJobResultProcessor = $updateJobResultProcessor;
}
/**
* @param ListGenericJobObject $listGenericJobObject
* @return void
* @throws \App\Classes\Exceptions\MalformedRequestException
* @throws \App\Classes\Exceptions\JobResourceNotFoundException
*/
public function execute(ListGenericJobObject $listGenericJobObject) {
$query = $this->listsBookings->execute($this->listsBookings->deserializeFilters($listGenericJobObject->getPayload()['filters']), ['page' => $listGenericJobObject->getPayload()['page']]);
foreach ($query->items() as &$item) {
$item['userInfo'] = $listGenericJobObject->getUserInfo();
}
$resultCurrent = Helper::collectionResponse(ListBookingJobResource::collection($query));
$this->updateJobResultProcessor->execute($listGenericJobObject, $resultCurrent);
}
}
@@ -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');
}
}
@@ -0,0 +1,75 @@
<?php
namespace App\Classes\Modules\Documents\ControllersLogic;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Jobs\Services\CreatesJobResult;
use App\Classes\Modules\Jobs\DataTransferObjects\ListGenericJobObject;
use App\Classes\Jobs\ListDocumentsJob;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class ListDocumentJobLogic extends AbstractControllerLogic
{
/**
* @return array
*/
protected function notification():array {
return [
'title' => 'List Document Job',
'message' => 'You have successfully submit a job to list documents'
];
}
/** @var CreatesJobResult */
private $createsJobResult;
/**
* ListDocumentJobLogic constructor.
* @param CreatesJobResult $createsJobResult
*/
public function __construct(CreatesJobResult $createsJobResult)
{
$this->createsJobResult = $createsJobResult;
}
/**
* @param Request $request
* @return JsonResponse
*/
public function logic(Request $request) : JsonResponse
{
$jobId = uniqid();
$user = Auth::user();
$userInfo = (object) [
'email' => $user->email,
'type' => $user->type,
];
$userInfoJson = json_encode($userInfo);
$requestSignature = md5($userInfoJson . $request->fullUrl());
$listGenericJobObject = new ListGenericJobObject(
$request->fullUrl(),
$request->all(),
$requestSignature,
null,
$jobId,
$userInfo
);
ListDocumentsJob::dispatch($listGenericJobObject)->onQueue('high_priority');
$result = [];
$result['job_id'] = $jobId;
$this->createsJobResult->execute($listGenericJobObject);
return $this->response(['data' => $result]);
}
}
@@ -0,0 +1,47 @@
<?php
namespace App\Classes\Modules\Documents\Processors;
use App\Classes\Modules\Documents\Services\ListsDocuments;
use App\Classes\Modules\Jobs\Processors\UpdateJobResultProcessor;
use App\Classes\General\Helper;
use App\Classes\Modules\Jobs\DataTransferObjects\ListGenericJobObject;
use App\Http\Resources\ListDocumentJobResource;
class ListDocumentsJobProcessor
{
/** @var ListsDocuments */
private $listsDocuments;
/** @var UpdateJobResultProcessor */
private $updateJobResultProcessor;
/**
* ListDocumentsJobProcessor constructor.
* @param ListsDocuments $listsDocuments
* @param UpdateJobResultProcessor $updateJobResultProcessor
*/
public function __construct(ListsDocuments $listsDocuments, UpdateJobResultProcessor $updateJobResultProcessor)
{
$this->listsDocuments = $listsDocuments;
$this->updateJobResultProcessor = $updateJobResultProcessor;
}
/**
* @param ListGenericJobObject $listGenericJobObject
* @return void
* @throws \App\Classes\Exceptions\MalformedRequestException
* @throws \App\Classes\Exceptions\JobResourceNotFoundException
*/
public function execute(ListGenericJobObject $listGenericJobObject) {
$query = $this->listsDocuments->execute($this->listsDocuments->deserializeFilters($listGenericJobObject->getPayload()['filters']), ['page' => $listGenericJobObject->getPayload()['page']]);
foreach ($query->items() as &$item) {
$item['userInfo'] = $listGenericJobObject->getUserInfo();
}
$resultCurrent = Helper::collectionResponse(ListDocumentJobResource::collection($query));
$this->updateJobResultProcessor->execute($listGenericJobObject, $resultCurrent);
}
}
@@ -0,0 +1,51 @@
<?php
namespace App\Classes\Modules\Jobs\ControllersLogic;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Jobs\Processors\FetchesJobResultProcessor;
use App\Http\Resources\JobResultResource;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class FetchJobResultLogic extends AbstractControllerLogic
{
/**
* @return array
*/
protected function notification():array {
return [
'title' => 'Retrieved Data',
'message' => 'You have successfully retrieved data'
];
}
/** @var FetchesJobResultProcessor */
private $fetchesJobResultProcessor;
/**
* FetchJobResultLogic constructor.
* @param FetchesJobResultProcessor $fetchesJobResultProcessor
*/
public function __construct(FetchesJobResultProcessor $fetchesJobResultProcessor)
{
$this->fetchesJobResultProcessor = $fetchesJobResultProcessor;
}
/**
* @param Request $request
* @return JsonResponse
* @throws \App\Classes\Exceptions\AccessForbiddenException
* @throws \App\Classes\Exceptions\MalformedRequestException
* @throws \App\Classes\Exceptions\RequestValidationException
*/
public function logic(Request $request) : JsonResponse
{
$query = $this->fetchesJobResultProcessor->execute($request);
return $this->resourceResponse(new JobResultResource($query));
}
}
@@ -0,0 +1,118 @@
<?php
namespace App\Classes\Modules\Jobs\DataTransferObjects;
use App\Classes\General\Interfaces\DataTransferObject;
class ListGenericJobObject implements DataTransferObject
{
/** @var string */
private $name;
/** @var array */
private $payload;
/** @var string */
private $jobId;
/** @var string */
private $requestSignature;
/** @var string */
private $resultSignature;
/** @var object */
private $userInfo;
/** @var string */
private $jobCommandName;
/** @var string */
private $jobCommand;
public function __construct(string $name, array $payload, string $requestSignature, ?string $resultSignature, string $jobId, object $userInfo = null)
{
$this->name = $name;
$this->payload = $payload;
$this->jobId = $jobId;
$this->requestSignature = $requestSignature;
$this->resultSignature = $resultSignature;
$this->userInfo = $userInfo;
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* @return array
*/
public function getPayload(): array
{
return $this->payload;
}
/**
* @return string
*/
public function getJobId(): string
{
return $this->jobId;
}
/**
* @return string
*/
public function getRequestSignature(): string
{
return $this->requestSignature;
}
/**
* @return string
*/
public function getResultSignature(): ?string
{
return $this->resultSignature;
}
/**
* @return object
*/
public function getUserInfo(): object
{
return $this->userInfo;
}
/**
* @return string
*/
public function getJobCommandName(): string
{
return $this->jobCommandName;
}
/**
* @return string
*/
public function getJobCommand(): string
{
return $this->jobCommand;
}
public function setJobCommandName(string $jobCommandName)
{
$this->jobCommandName = $jobCommandName;
}
public function setJobCommand(string $jobCommand)
{
$this->jobCommand = $jobCommand;
}
}
@@ -0,0 +1,60 @@
<?php
namespace App\Classes\Modules\Jobs\DataTransferObjects;
use App\Classes\General\Interfaces\DataTransferObject;
class UpdateJobResultObject implements DataTransferObject
{
/** @var string */
private $result;
/** @var string */
private $resultSignature;
/** @var string */
private $jobCommandName;
/** @var string */
private $jobCommand;
public function __construct(string $result, string $resultSignature, string $jobCommandName, string $jobCommand)
{
$this->result = $result;
$this->resultSignature = $resultSignature;
$this->jobCommandName = $jobCommandName;
$this->jobCommand = $jobCommand;
}
/**
* @return string
*/
public function getResult(): string
{
return $this->result;
}
/**
* @return array
*/
public function getResultSignature(): string
{
return $this->resultSignature;
}
/**
* @return string
*/
public function getJobCommandName(): string
{
return $this->jobCommandName;
}
/**
* @return string
*/
public function getJobCommand(): string
{
return $this->jobCommand;
}
}
@@ -0,0 +1,47 @@
<?php
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;
class FetchesJobResultProcessor
{
/** @var FetchesJobResult */
private $fetchesJobResult;
/**
* FetchesJobResultProcessor constructor.
* @param FetchesJobResult $fetchesJobResult
*/
public function __construct(FetchesJobResult $fetchesJobResult)
{
$this->fetchesJobResult = $fetchesJobResult;
}
/**
* @param Request $request
* @return Model
* @throws \App\Classes\Exceptions\MalformedRequestException
* @throws \App\Classes\Exceptions\JobResourceNotFoundException
* @throws \App\Classes\Exceptions\ResourceNotFoundException
*/
public function execute(Request $request){
$res1 = $this->fetchesJobResult->execute(['job_id' => $request->route('job_id')]);
if($request->route('is_last')){
$res2 = $this->fetchesJobResult->execute(['request_signature' => $res1->request_signature, 'result_not_null' => true, 'order_by_id_desc' => true]);
return $res2;
}
if(!$res1->result){
throw new JobResourceNotFoundException('Unable to find any job based on the criteria provided');
}
return $res1;
}
}
@@ -0,0 +1,64 @@
<?php
namespace App\Classes\Modules\Jobs\Processors;
use App\Classes\Modules\Jobs\Services\UpdatesJobResult;
use App\Classes\Modules\Jobs\Services\FetchesJobResult;
use App\Classes\Exceptions\JobResourceNotFoundException;
use App\Classes\Modules\Jobs\DataTransferObjects\ListGenericJobObject;
use App\Classes\Modules\Jobs\DataTransferObjects\UpdateJobResultObject;
class UpdateJobResultProcessor
{
/** @var FetchesJobResult */
private $fetchesJobResult;
/** @var UpdatesJobResult */
private $updatesJobResult;
/**
* UpdateJobResultProcessor constructor.
* @param FetchesJobResult $fetchesJobResult
* @param UpdatesJobResult $updatesJobResult
*/
public function __construct(FetchesJobResult $fetchesJobResult, UpdatesJobResult $updatesJobResult)
{
$this->fetchesJobResult = $fetchesJobResult;
$this->updatesJobResult = $updatesJobResult;
}
/**
* @param ListGenericJobObject $listGenericJobObject
* @param array $resultCurrent
* @return void
* @throws \App\Classes\Exceptions\MalformedRequestException
* @throws \App\Classes\Exceptions\JobResourceNotFoundException
*/
public function execute(ListGenericJobObject $listGenericJobObject, $resultCurrent) {
$jobResultCurrent = $this->fetchesJobResult->execute(['job_id' => $listGenericJobObject->getJobId()]);
$resultCurrentJson = json_encode($resultCurrent);
$resultSignatureCurrent = md5($resultCurrentJson);
try{
$jobResultExisting = $this->fetchesJobResult->execute(['request_signature' => $jobResultCurrent->request_signature, 'result_not_null' => true, 'order_by_id_desc' => true]);
$resultSignatureExisting = $jobResultExisting->result_signature;
//if($resultSignatureExisting != $resultSignatureCurrent){
$this->updateJobResult($jobResultCurrent, $resultCurrentJson, $resultSignatureCurrent, $listGenericJobObject->getJobCommandName(), $listGenericJobObject->getJobCommand());
//}
} catch (JobResourceNotFoundException $exception){
$this->updateJobResult($jobResultCurrent, $resultCurrentJson, $resultSignatureCurrent, $listGenericJobObject->getJobCommandName(), $listGenericJobObject->getJobCommand());
}
}
private function updateJobResult($jobResultCurrent, $resultCurrentJson, $resultSignatureCurrent, $jobCommandName, $jobCommand){
$updateJobResultObject = new UpdateJobResultObject(
$resultCurrentJson,
$resultSignatureCurrent,
$jobCommandName,
$jobCommand
);
$create = $this->updatesJobResult->execute($jobResultCurrent, $updateJobResultObject);
}
}
@@ -0,0 +1,26 @@
<?php
namespace App\Classes\Modules\Jobs\Services;
use App\Classes\General\Eloquent\AbstractUpdateRecord;
use App\Models\JobResult;
use App\Classes\Modules\Jobs\DataTransferObjects\ListGenericJobObject;
class CreatesJobResult extends AbstractUpdateRecord
{
/**
* @param ListGenericJobObject $listGenericJobObject
* @return \Illuminate\Database\Eloquent\Model
* @throws \App\Classes\Exceptions\MalformedRequestException
*/
public function execute(ListGenericJobObject $listGenericJobObject)
{
$model = new JobResult();
$model->job_id = $listGenericJobObject->getJobId();
$model->request_signature = $listGenericJobObject->getRequestSignature();
$model->result_signature = $listGenericJobObject->getResultSignature();
$model->url = $listGenericJobObject->getName();
return $this->handler($model);
}
}
@@ -0,0 +1,33 @@
<?php
namespace App\Classes\Modules\Jobs\Services;
use App\Classes\General\Eloquent\AbstractFetchRecord;
use Illuminate\Database\Eloquent\Builder;
use App\Models\JobResult;
class FetchesJobResult extends AbstractFetchRecord
{
/** @var JobResult */
private $repository;
/**
* FetchesJobResult constructor.
* @param JobResult $repository
*/
public function __construct(JobResult $repository)
{
$this->repository = $repository;
}
/**
* @return Builder
*/
public function getRepository(): Builder
{
return $this->repository->newQuery();
}
}
@@ -0,0 +1,33 @@
<?php
namespace App\Classes\Modules\Jobs\Services;
use App\Classes\General\Eloquent\AbstractListRecord;
use Illuminate\Database\Eloquent\Builder;
use App\Models\JobResult;
class ListsJobResult extends AbstractListRecord
{
/** @var JobResult */
private $repository;
/**
* ListsJobResult constructor.
* @param JobResult $repository
*/
public function __construct(JobResult $repository)
{
$this->repository = $repository;
}
/**
* @return Builder
*/
function getRepository(): Builder
{
return $this->repository->newQuery();
}
}
@@ -0,0 +1,28 @@
<?php
namespace App\Classes\Modules\Jobs\Services;
use App\Classes\General\Eloquent\AbstractUpdateRecord;
use App\Classes\Modules\Jobs\DataTransferObjects\UpdateJobResultObject;
use App\Models\JobResult;
class UpdatesJobResult extends AbstractUpdateRecord
{
/**
* @param JobResult $model
* @param UpdateJobResultObject $updateJobResultObject
* @return \Illuminate\Database\Eloquent\Model
* @throws \App\Classes\Exceptions\MalformedRequestException
*/
public function execute(JobResult $model, UpdateJobResultObject $updateJobResultObject) {
$model->result = $updateJobResultObject->getResult();
$model->result_signature = $updateJobResultObject->getResultSignature();
$model->job_command_name = $updateJobResultObject->getJobCommandName();
$model->job_command = $updateJobResultObject->getJobCommand();
return $this->handler($model);
}
}
@@ -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([]);
@@ -0,0 +1,74 @@
<?php
namespace App\Classes\Modules\Transactions\ControllersLogic;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Jobs\ListTransactionsJob;
use App\Classes\Modules\Jobs\Services\CreatesJobResult;
use App\Classes\Modules\Jobs\DataTransferObjects\ListGenericJobObject;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class ListTransactionsJobLogic extends AbstractControllerLogic
{
/**
* @return array
*/
protected function notification():array {
return [
'title' => 'List Transaction Job',
'message' => 'You have successfully submit a job to list transactions'
];
}
/** @var CreatesJobResult */
private $createsJobResult;
/**
* ListTransactionsJobLogic constructor.
* @param CreatesJobResult $createsJobResult
*/
public function __construct(CreatesJobResult $createsJobResult)
{
$this->createsJobResult = $createsJobResult;
}
/**
* @param Request $request
* @return JsonResponse
*/
public function logic(Request $request) : JsonResponse
{
$jobId = uniqid();
$user = Auth::user();
$userInfo = (object) [
'type' => $user->type,
];
$userInfoJson = json_encode($userInfo);
$requestSignature = md5($userInfoJson . $request->fullUrl());
$listGenericJobObject = new ListGenericJobObject(
$request->fullUrl(),
$request->all(),
$requestSignature,
null,
$jobId,
$userInfo
);
ListTransactionsJob::dispatch($listGenericJobObject)->onQueue('high_priority');
$result = [];
$result['job_id'] = $jobId;
$this->createsJobResult->execute($listGenericJobObject);
return $this->response(['data' => $result]);
}
}
@@ -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));
@@ -0,0 +1,45 @@
<?php
namespace App\Classes\Modules\Transactions\Processors;
use App\Classes\Modules\Transactions\Services\ListsTransactions;
use App\Classes\Modules\Jobs\Processors\UpdateJobResultProcessor;
use App\Classes\General\Helper;
use App\Classes\Modules\Jobs\DataTransferObjects\ListGenericJobObject;
use App\Http\Resources\ListTransactionJobResource;
class ListTransactionsJobProcessor
{
/** @var ListsTransactions */
private $listsTransactions;
/** @var UpdateJobResultProcessor */
private $updateJobResultProcessor;
/**
* ListTransactionsJobProcessor constructor.
* @param ListsTransactions $listsTransactions
* @param UpdateJobResultProcessor $updateJobResultProcessor
*/
public function __construct(ListsTransactions $listsTransactions, UpdateJobResultProcessor $updateJobResultProcessor)
{
$this->listsTransactions = $listsTransactions;
$this->updateJobResultProcessor = $updateJobResultProcessor;
}
/**
* @param ListGenericJobObject $listGenericJobObject
* @return void
* @throws \App\Classes\Exceptions\MalformedRequestException
* @throws \App\Classes\Exceptions\JobResourceNotFoundException
*/
public function execute(ListGenericJobObject $listGenericJobObject) {
$query = $this->listsTransactions->execute($this->listsTransactions->deserializeFilters($listGenericJobObject->getPayload()['filters']), ['page' => $listGenericJobObject->getPayload()['page']]);
$resultCurrent = Helper::collectionResponse(ListTransactionJobResource::collection($query));
$this->updateJobResultProcessor->execute($listGenericJobObject, $resultCurrent);
}
}
@@ -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}");
}
}
}
}
+9
View File
@@ -43,6 +43,15 @@ class Kernel extends ConsoleKernel
->hourly()
->appendOutputTo(storage_path().'/logs/delete-bulk-download-files.log')
->withoutOverlapping();
$schedule->command('booking:expired')
->dailyAt('02:00')
->appendOutputTo(storage_path().'/logs/expire-booking.log')
->withoutOverlapping();
// $schedule->command('purchaseOrder:autoFill')
// ->dailyAt('03:00')
// ->withoutOverlapping();
}
/**
@@ -0,0 +1,22 @@
<?php
namespace App\Http\Controllers\Bookings;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use App\Classes\Modules\Bookings\ControllersLogic\ListBookingJobLogic;
class ListBookingsJobController
{
/**
* @param Request $request
* @param ListBookingJobLogic $logic
* @return JsonResponse
*/
public function list(Request $request, ListBookingJobLogic $logic) : JsonResponse {
return $logic->execute($request);
}
}
@@ -0,0 +1,19 @@
<?php
namespace App\Http\Controllers\Documents;
use App\Classes\Modules\Documents\ControllersLogic\ListDocumentJobLogic;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class ListDocumentsJobController
{
/**
* @param Request $request
* @param ListDocumentJobLogic $logic
* @return JsonResponse
*/
public function list(Request $request, ListDocumentJobLogic $logic): JsonResponse {
return $logic->execute($request);
}
}
@@ -0,0 +1,19 @@
<?php
namespace App\Http\Controllers\Jobs;
use App\Classes\Modules\Jobs\ControllersLogic\FetchJobResultLogic;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class FetchJobResultController
{
/**
* @param Request $request
* @param FetchJobResultLogic $logic
* @return JsonResponse
*/
public function fetch(Request $request, FetchJobResultLogic $logic): JsonResponse {
return $logic->execute($request);
}
}
@@ -0,0 +1,21 @@
<?php
namespace App\Http\Controllers\Transactions;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use App\Classes\Modules\Transactions\ControllersLogic\ListTransactionsJobLogic;
class ListTransactionsJobController
{
/**
* @param Request $request
* @param ListTransactionsJobLogic $logic
* @return JsonResponse
*/
public function list(Request $request, ListTransactionsJobLogic $logic) : JsonResponse {
return $logic->execute($request);
}
}
+3 -4
View File
@@ -11,11 +11,9 @@ use App\Classes\ValueObjects\Constants\TransactionType;
use App\Classes\ValueObjects\Constants\DocumentType;
use Carbon\Carbon;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\Log;
class BookingResource extends JsonResource
{
/**
* Transform the resource into an array.
*
@@ -34,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),
@@ -60,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]);
-1
View File
@@ -15,7 +15,6 @@ use App\Models\SegmentConstant;
use Carbon\Carbon;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
class CompanyResource extends JsonResource
{
-3
View File
@@ -3,10 +3,7 @@
namespace App\Http\Resources;
use App\Models\Booking;
use App\Models\Company;
use App\Models\Document;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Resources\Json\JsonResource;
class DocumentResource extends JsonResource
+22
View File
@@ -0,0 +1,22 @@
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class JobResultResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'job_id' => $this->job_id,
'result' => $this->result,
];
}
}
@@ -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,81 @@
<?php
namespace App\Http\Resources;
use App\Classes\Modules\Bookings\Services\CalculatesBookingFloatingAmount;
use App\Classes\Modules\Bookings\Services\CalculatesBookingOutstanding;
use App\Classes\Modules\Bookings\Services\CalculatesBookingPayableAmount;
use App\Classes\Modules\Bookings\Services\CalculatesBookingRefundAmount;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\TransactionType;
use App\Classes\ValueObjects\Constants\DocumentType;
use Carbon\Carbon;
use Illuminate\Http\Resources\Json\JsonResource;
class ListBookingJobResource extends JsonResource
{
private $userInfo;
public function __construct($resource, $userInfo = null)
{
parent::__construct($resource);
$this->userInfo = $userInfo ?? ($resource->userInfo ?? null);
}
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
* @throws \Illuminate\Contracts\Container\BindingResolutionException
*/
public function toArray($request)
{
return [
'id' => $this->id,
'company' => new CompanyResource($this->company, $this->userInfo),
'bank' => new BankResource($this->bank),
'service' => new ServiceTypeResource($this->service),
'marking' => $this->marking,
'amount' => $this->fix_amount,
'floating_amount' => floatval((App()->make(CalculatesBookingFloatingAmount::class))->execute($this->resource, $this->fix_currency_id)),
'paid_amount' => floatval((App()->make(CalculatesBookingPayableAmount::class))->execute($this->resource, $this->fix_currency_id)) - floatval((App()->make(CalculatesBookingRefundAmount::class))->execute($this->resource, $this->fix_currency_id)),
'outstanding_amount' => floatval((App()->make(CalculatesBookingOutstanding::class))->execute($this->resource)) - floatval((App()->make(CalculatesBookingRefundAmount::class))->execute($this->resource, $this->fix_currency_id)),
'fixed_currency' => new CurrencyResource($this->fixedCurrency),
'convertible_currency' => new CurrencyResource($this->convertibleCurrency),
'conversion_currency' => new CurrencyResource($this->conversionCurrency),
'documents' => [
'purchase_order' => new DocumentResource($this->documents()->where('document_type', DocumentType::PURCHASE_ORDER)->first()),
'delivery_order' => new DocumentResource($this->documents()->where('document_type', DocumentType::DELIVER_ORDER)->first()),
'invoice' => new DocumentResource($this->documents()->where('document_type', DocumentType::INVOICE)->first()),
'supplier_delivery_order' => new DocumentResource($this->documents()->where('document_type', DocumentType::SUPPLIER_DELIVER_ORDER)->first()),
'proforma_invoice' => new DocumentResource($this->documents()->where('document_type', DocumentType::PROFORMA_INVOICE)->whereNotIn('status', [ApprovalStatus::REJECTED, ApprovalStatus::EXPIRED])->orderByDesc('id')->first()),
'ecommerce_purchase_order' => new DocumentResource($this->documents()->where('document_type', DocumentType::ECOMMERCE_PURCHASE_ORDER)->first()),
],
'status' => $this->status,
'created_at' => Carbon::parse($this->created_at)->format('d-m-Y'),
'created_at_with_time' => Carbon::parse($this->created_at)->format('d-m-Y h:i:s A'),
$this->mergeWhen($this->relationLoaded('transactions'), [
'purchase_order' => new TransactionResource($this->transactions()->where('type', TransactionType::PURCHASE_ORDER)->first()),
'payment_attempts' => TransactionResource::collection(
$this->transactions()
->payments()->where('status', ApprovalStatus::PENDING_SUBMISSION)
->whereDate('expires_on', '>=', Carbon::now())
->get()
),
'expired_payment_attempts' => TransactionResource::collection($this->transactions()->payments()->where('status', ApprovalStatus::PENDING_SUBMISSION)->whereDate('expires_on', '>=', Carbon::now())->where('expires_on', '>', Carbon::now()->toTimeString())->get()),
'payment_history' => TransactionResource::collection($this->transactions()->where(function($query){
$query->where(function($query){
$query->payments()->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::PENDING_VERIFICATION, ApprovalStatus::COMPLETED, ApprovalStatus::REJECTED]);
})->orWhere(function($query){
$query->where(function($query){
$query->where('type', TransactionType::REFUND)->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::PENDING_VERIFICATION, ApprovalStatus::REJECTED, ApprovalStatus::COMPLETED]);
})->orWhere(function($query){
$query->where('type', TransactionType::CREDIT_NOTE)->whereIn('status', [ApprovalStatus::PENDING_VERIFICATION, ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED]);
});
});
})->latest()->get())
])
];
}
}
@@ -0,0 +1,31 @@
<?php
namespace App\Http\Resources;
use App\Models\Booking;
use Carbon\Carbon;
use Illuminate\Http\Resources\Json\JsonResource;
use App\Http\Resources\V2\BookingV2Resource;
use App\Http\Resources\V2\CompanyV2Resource;
class ListDocumentJobResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'reference' => $this->reference,
'status' => (int) $this->status,
'document_type' => $this->document_type,
'owner' => $this->relationLoaded('owner') ? ($this->owner instanceof Booking ? new BookingV2Resource($this->owner, $this->userInfo) : new CompanyV2Resource($this->owner, $this->userInfo)) : null,
'files' => FileResource::collection($this->files),
'created_at' => Carbon::parse($this->created_at)->format('d-m-Y h:i:s A')
];
}
}
@@ -0,0 +1,54 @@
<?php
namespace App\Http\Resources;
use App\Classes\ValueObjects\Constants\TransactionType;
use Carbon\Carbon;
use Illuminate\Http\Resources\Json\JsonResource;
class ListTransactionJobResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
$booking = in_array((int)$this->type, [TransactionType::BILL, TransactionType::REFUND])? $this->owner->owner : $this->owner;
$days = $this->created_at->endOfDay()->addWeekdays($booking->service_id === 3 ? 3 : 1);
return [
'id' => $this->id,
'booking' => new BookingResource($booking),
'type' => (int) $this->type,
'bill_no' => $this->bill_no,
'payment_reference' => $this->payment_reference,
'payment_method' => (float) $this->payment_method,
'recipient_bank_account' => new BankResource($booking->bank),
'issuer_name' => $this->issuerCompany->name,
'issuer_id' => $this->issuerCompany->id,
'amount' => (double) $this->amount,
'original_amount' => (double) $this->original_amount,
'currency' => new CurrencyResource($this->currency),
'original_currency' => new CurrencyResource($this->original_currency),
'service_charge' => (double) $this->service_charge,
'tax' => (double) $this->tax,
'currency_rate' => (double) $this->currency_rate,
'status' => (int) $this->status,
'details' => TransactionDetailResource::collection($this->transactionDetails),
'documents' => new DocumentResource($this->documents()->first()),
'transaction_bill' => new TransactionResource($this->when((int) $this->type === TransactionType::PAYMENT, $this->transactions()->bills()->first())),
'transaction_refunds' => TransactionResource::collection($this->when((int) $this->type === TransactionType::PAYMENT, $this->transactions()->refunds()->get())),
'expires_on' => Carbon::parse($this->expires_on)->format('d-m-Y h:i:s A'),
'updated_at' => Carbon::parse($this->updated_at)->format('d-m-Y h:i:s A'),
'interval' => [
'value' => $days->gt(Carbon::now()) ? '+' : '-',
'duration' => $days->diff(Carbon::now())->format('%d'),
],
'redemption' => new VoucherRedemptionResource($this->voucherRedemption)
];
}
}
@@ -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,
@@ -0,0 +1,82 @@
<?php
namespace App\Http\Resources\V2;
use App\Classes\Modules\Bookings\Services\CalculatesBookingFloatingAmount;
use App\Classes\Modules\Bookings\Services\CalculatesBookingOutstanding;
use App\Classes\Modules\Bookings\Services\CalculatesBookingPayableAmount;
use App\Classes\Modules\Bookings\Services\CalculatesBookingRefundAmount;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\TransactionType;
use App\Classes\ValueObjects\Constants\DocumentType;
use Carbon\Carbon;
use Illuminate\Http\Resources\Json\JsonResource;
use App\Http\Resources as V1;
class BookingV2Resource extends JsonResource
{
private $userInfo;
public function __construct($resource, $userInfo = null)
{
parent::__construct($resource);
$this->userInfo = $userInfo ?? ($resource->userInfo ?? null);
}
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
* @throws \Illuminate\Contracts\Container\BindingResolutionException
*/
public function toArray($request)
{
return [
'id' => $this->id,
'company' => new CompanyV2Resource($this->company, $this->userInfo),
'bank' => new V1\BankResource($this->bank),
'service' => new V1\ServiceTypeResource($this->service),
'marking' => $this->marking,
'amount' => $this->fix_amount,
'floating_amount' => floatval((App()->make(CalculatesBookingFloatingAmount::class))->execute($this->resource, $this->fix_currency_id)),
'paid_amount' => floatval((App()->make(CalculatesBookingPayableAmount::class))->execute($this->resource, $this->fix_currency_id)) - floatval((App()->make(CalculatesBookingRefundAmount::class))->execute($this->resource, $this->fix_currency_id)),
'outstanding_amount' => floatval((App()->make(CalculatesBookingOutstanding::class))->execute($this->resource)) - floatval((App()->make(CalculatesBookingRefundAmount::class))->execute($this->resource, $this->fix_currency_id)),
'fixed_currency' => new V1\CurrencyResource($this->fixedCurrency),
'convertible_currency' => new V1\CurrencyResource($this->convertibleCurrency),
'conversion_currency' => new V1\CurrencyResource($this->conversionCurrency),
'documents' => [
'purchase_order' => new V1\DocumentResource($this->documents()->where('document_type', DocumentType::PURCHASE_ORDER)->first()),
'delivery_order' => new V1\DocumentResource($this->documents()->where('document_type', DocumentType::DELIVER_ORDER)->first()),
'invoice' => new V1\DocumentResource($this->documents()->where('document_type', DocumentType::INVOICE)->first()),
'supplier_delivery_order' => new V1\DocumentResource($this->documents()->where('document_type', DocumentType::SUPPLIER_DELIVER_ORDER)->first()),
'proforma_invoice' => new V1\DocumentResource($this->documents()->where('document_type', DocumentType::PROFORMA_INVOICE)->whereNotIn('status', [ApprovalStatus::REJECTED, ApprovalStatus::EXPIRED])->orderByDesc('id')->first()),
'ecommerce_purchase_order' => new V1\DocumentResource($this->documents()->where('document_type', DocumentType::ECOMMERCE_PURCHASE_ORDER)->first()),
],
'status' => $this->status,
'created_at' => Carbon::parse($this->created_at)->format('d-m-Y'),
'created_at_with_time' => Carbon::parse($this->created_at)->format('d-m-Y h:i:s A'),
$this->mergeWhen($this->relationLoaded('transactions'), [
'purchase_order' => new V1\TransactionResource($this->transactions()->where('type', TransactionType::PURCHASE_ORDER)->first()),
'payment_attempts' => V1\TransactionResource::collection(
$this->transactions()
->payments()->where('status', ApprovalStatus::PENDING_SUBMISSION)
->whereDate('expires_on', '>=', Carbon::now())
->get()
),
'expired_payment_attempts' => V1\TransactionResource::collection($this->transactions()->payments()->where('status', ApprovalStatus::PENDING_SUBMISSION)->whereDate('expires_on', '>=', Carbon::now())->where('expires_on', '>', Carbon::now()->toTimeString())->get()),
'payment_history' => V1\TransactionResource::collection($this->transactions()->where(function($query){
$query->where(function($query){
$query->payments()->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::PENDING_VERIFICATION, ApprovalStatus::COMPLETED, ApprovalStatus::REJECTED]);
})->orWhere(function($query){
$query->where(function($query){
$query->where('type', TransactionType::REFUND)->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::PENDING_VERIFICATION, ApprovalStatus::REJECTED, ApprovalStatus::COMPLETED]);
})->orWhere(function($query){
$query->where('type', TransactionType::CREDIT_NOTE)->whereIn('status', [ApprovalStatus::PENDING_VERIFICATION, ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED]);
});
});
})->latest()->get())
])
];
}
}
+100
View File
@@ -0,0 +1,100 @@
<?php
namespace App\Http\Resources\V2;
use App\Classes\Modules\Companies\Services\FetchesCompanyServices;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\BankAccountType;
use App\Classes\ValueObjects\Constants\BusinessType;
use App\Classes\ValueObjects\Constants\DocumentType;
use App\Classes\ValueObjects\Constants\RoleTypes;
use App\Classes\ValueObjects\Constants\SegmentConstants;
use App\Classes\ValueObjects\Constants\TransactionType;
use App\Models\Currency;
use App\Models\SegmentConstant;
use Carbon\Carbon;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\Auth;
use App\Http\Resources as V1;
class CompanyV2Resource extends JsonResource
{
private $userInfo;
public function __construct($resource, $userInfo = null)
{
parent::__construct($resource);
$this->userInfo = $userInfo;
}
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
$lastPayment = $this->transactions()->where('transactions.type', TransactionType::PAYMENT)->whereIn('transactions.status', [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED])->orderBy('id', 'DESC')->first();
$totalPayments = $this->transactions()->where('transactions.type', TransactionType::PAYMENT)->whereIn('transactions.status', [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED])->sum('amount');
$segment = SegmentConstant::where('reference', SegmentConstants::SUPPLIER_CURRENCIES)->where('detail->id', $this->id)->first();
$serviceCharge = SegmentConstant::where('reference', SegmentConstants::SERVICE_CHARGE)->where('detail->id', $this->id)->first();
$userResource = null;
$userInfoEmail = $this->userInfo && isset($this->userInfo->email) ? $this->userInfo->email : null;
$userInfoType = $this->userInfo && isset($this->userInfo->type) ? $this->userInfo->type : null;
if(!$userInfoEmail && Auth::user()){
$userInfoEmail = Auth::user()->email;
}
if(!$userInfoType && Auth::user()){
$userInfoType = Auth::user()->type;
}
if(!is_null($userInfoEmail) && !is_null($userInfoType)){
$userResource = new V1\UserResource($userInfoType === RoleTypes::USER ? $this->employees()->where('email', '=', $userInfoEmail)->first() : $this->employees()->orderBy('id', 'DESC')->first());
}
return [
'id' => $this->id,
'name' => $this->name,
'reference' => $this->reference,
'debtor' => $this->debtor,
'type' => (int) $this->type,
'business_type' => (int) $this->business_type,
'status' => (int) $this->status,
'contact' => new V1\ContactResource ($this->when($this->has('contacts'), $this->contacts->first())),
'address' => new V1\AddressResource($this->when($this->has('addresses'), $this->addresses->where('billing', true)->first())),
'employee' => $userResource,
'identification' => new V1\DocumentResource($this->documents->whereIn('document_type', DocumentType::IDENTIFICATION_DOCUMENTS)->first()),
'bookings' => $this->whenLoaded('bookings', $this->bookings()->orderBy('id', 'DESC')->get(), []),
'confirmed_bookings' => $this->bookings()->whereHas('transactions', function ($query){
$query->where('type', TransactionType::PAYMENT)->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED]);
})->count(),
'total_payments' => (float) $totalPayments,
'average_spending_per_day' => (float) $totalPayments / ($this->created_at->diff(Carbon::now())->days === 0 ? 1 : $this->created_at->diff(Carbon::now())->days),
'average_spending_per_booking' => (float) $totalPayments > 0 ? $totalPayments / $this->bookings()->whereHas('transactions', function ($query){
$query->where('type', TransactionType::PAYMENT)->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED]);
})->count() : $totalPayments,
'last_payment' => $lastPayment ? $lastPayment->created_at->diffForHumans() : 'No Payments',
'personal_banks' => V1\BankResource::collection($this->banks->where('type', BankAccountType::PERSONAL)),
'recipient_banks' => [
'accounts' => V1\BankResource::collection($this->banks->where('type', BankAccountType::EXTERNAL)),
'default' => new V1\BankResource($this->banks->where('type', BankAccountType::EXTERNAL)->where('default', true)->first())
],
'segments' => V1\SegmentResource::collection($this->segments),
'seasonalSegment' => $this->whenLoaded('seasonalSegments', V1\SeasonalSegmentResource::collection($this->seasonalSegments)),
'services' => (new FetchesCompanyServices())->getServices($this->servicesConfigurations()),
'wallet' => $this->whenLoaded('wallets', new V1\WalletResource($this->wallets()->with('transactions')->first()), new V1\WalletResource($this->wallets()->first())),
'created_at' => $this->created_at->format('d-m-Y'),
$this->mergeWhen($this->business_type === BusinessType::CURRENCY_VENDOR, [
'currencies' => $segment ? V1\CurrencyResource::collection(Currency::whereIn('id', $segment->detail->currencies)->get()) : [],
'service_charge' => $serviceCharge
])
];
}
}
+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,
];
}
}
+13
View File
@@ -0,0 +1,13 @@
<?php
namespace App\Models;
class JobResult extends AbstractModel
{
protected $table = 'job_results';
public $fillable = [
'job_id',
'result'
];
}
+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();
}
}
+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');
}
}
+13
View File
@@ -108,6 +108,19 @@ return [
'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,35 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateJobResultsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('job_results', function (Blueprint $table) {
$table->id();
$table->string('job_id', 50);
$table->longText('result')->nullable();
$table->timestamps();
// $table->foreign('job_id')->references('id')->on('jobs')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('job_results');
}
}

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