Compare commits

..

4 Commits

298 changed files with 1537 additions and 11649 deletions
@@ -1,20 +0,0 @@
<?php
namespace App\Classes\General\Eloquent\Filters;
use Illuminate\Database\Eloquent\Builder;
class ClaimantId implements Filter
{
/**
* @param Builder $builder
* @param $value
* @return Builder|mixed
*/
public static function apply(Builder $builder, $value)
{
return $builder->where('claimant_id', $value);
}
}
@@ -1,23 +0,0 @@
<?php
namespace App\Classes\General\Eloquent\Filters;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;
class DoesNotHaveTransactionType implements Filter
{
/**
* @param Builder $builder
* @param $value
* @return mixed
*/
public static function apply(Builder $builder, $value)
{
return $builder->whereDoesntHave('transactions', function (Builder $query) use($value) {
$query->where('type', $value);
})->whereHas('containers', function ($query){
return $query->whereDate('loading_date', '>=', Carbon::parse('08-08-2022'));
});
}
}
@@ -1,20 +0,0 @@
<?php
namespace App\Classes\General\Eloquent\Filters;
use Illuminate\Database\Eloquent\Builder;
class HasInvoiceStatusIn implements Filter
{
/**
* @param Builder $builder
* @param $value
* @return mixed
*/
public static function apply(Builder $builder, $value)
{
return $builder->whereHas('transactions', function (Builder $query) use($value) {
$query->where('type', 1)->whereIn('status', $value);
});
}
}
@@ -1,20 +0,0 @@
<?php
namespace App\Classes\General\Eloquent\Filters;
use Illuminate\Database\Eloquent\Builder;
class HasTransactionType implements Filter
{
/**
* @param Builder $builder
* @param $value
* @return mixed
*/
public static function apply(Builder $builder, $value)
{
return $builder->whereHas('transactions', function (Builder $query) use($value) {
$query->where('type', $value);
});
}
}
@@ -4,7 +4,7 @@ namespace App\Classes\General\Eloquent\Filters;
use Illuminate\Database\Eloquent\Builder;
class TypeIn implements Filter
class OwnerId implements Filter
{
/**
@@ -14,7 +14,7 @@ class TypeIn implements Filter
*/
public static function apply(Builder $builder, $value)
{
return $builder->whereIn('type', $value);
return $builder->where('owner_id', $value);
}
}
@@ -1,31 +0,0 @@
<?php
namespace App\Classes\General\Eloquent\Filters;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use Illuminate\Support\Carbon;
use Illuminate\Database\Eloquent\Builder;
class PackingListDeliveryStatus implements Filter
{
/**
* @param Builder $builder
* @param $value
* @return Builder|mixed
*/
public static function apply(Builder $builder, $value)
{
return $value == 1 ? $builder->whereHas('containers', function ($query){
$query->where('containers.status', ApprovalStatus::COMPLETED);
})->whereDoesntHave('transports') : ($value == 2 ? $builder->whereHas('transports', function (Builder $query) use ($value) {
$query->whereDoesntHave('schedules', function (Builder $query) use ($value) {
$query->where('status', '!=', ApprovalStatus::EXPIRED)->where('eta', '<=', Carbon::now());
});
}) : $builder->whereHas('transports', function (Builder $query) use ($value) {
$query->whereHas('schedules', function (Builder $query) use ($value) {
$query->where('status', '!=', ApprovalStatus::EXPIRED)->where('eta', '<=', Carbon::now());
});
}));
}
}
@@ -1,20 +0,0 @@
<?php
namespace App\Classes\General\Eloquent\Filters;
use Illuminate\Database\Eloquent\Builder;
class SegmentIdIn implements Filter
{
/**
* @param Builder $builder
* @param $value
* @return Builder|mixed
*/
public static function apply(Builder $builder, $value)
{
return $builder->whereIn('segment_id', $value);
}
}
@@ -1,21 +0,0 @@
<?php
namespace App\Classes\General\Eloquent\Filters;
use App\Models\User;
use Illuminate\Database\Eloquent\Builder;
class TargetId implements Filter
{
/**
* @param Builder $builder
* @param $value
* @return Builder|mixed
*/
public static function apply(Builder $builder, $value)
{
return $builder->where('target_type', User::class)->where('target_id', $value);
}
}
@@ -1,15 +0,0 @@
<?php
namespace App\Classes\General\Interfaces;
use Illuminate\Database\Eloquent\Relations\MorphTo;
interface Notifiable
{
public function subject(): MorphTo;
public function target(): MorphTo;
public function causer(): MorphTo;
}
@@ -15,7 +15,6 @@ use App\Classes\Modules\Companies\Processors\CreateCompanyModuleProcessor;
use App\Classes\Modules\Companies\DataTransferObjects\EmploymentObject;
use App\Classes\Modules\Companies\Services\ApprovesCompanyConnection;
use App\Classes\Modules\Companies\Services\CreatesCompanyConnection;
use App\Classes\Modules\Companies\Services\FetchesCompanyModule;
use App\Classes\Modules\Contacts\DataTransferObjects\ContactObject;
use App\Classes\Modules\Contacts\Processors\CreateContactProcessor;
use App\Classes\Modules\Documents\Processors\UploadIdentityDocumentProcessor;
@@ -77,9 +76,6 @@ class CreateCustomerLogic extends AbstractControllerLogic
/** @var GenerateEmailVerificationAttemptProcessor */
private $generateEmailVerificationAttemptProcessor;
/** @var FetchesCompanyModule */
private $fetchesCompanyModule;
/**
* CreateCustomerLogic constructor.
* @param CreateUserProcessor $createUserProcessor
@@ -92,9 +88,8 @@ class CreateCustomerLogic extends AbstractControllerLogic
* @param UploadIdentityDocumentProcessor $uploadIdentityDocumentProcessor
* @param AuthenticationProcessor $authenticationProcessor
* @param GenerateEmailVerificationAttemptProcessor $generateEmailVerificationAttemptProcessor
* @param FetchesCompanyModule $fetchesCompanyModule
*/
public function __construct(CreateUserProcessor $createUserProcessor, CreateCompanyProcessor $createCompanyProcessor, CreateCompanyModuleProcessor $createCompanyModuleProcessor, CreateContactProcessor $createContactProcessor, CreatesCompanyConnection $createsCompanyConnection, ApprovesCompanyConnection $approvesCompanyConnection, AssignEmployeeProcessor $assignEmployeeProcessor, UploadIdentityDocumentProcessor $uploadIdentityDocumentProcessor, AuthenticationProcessor $authenticationProcessor, GenerateEmailVerificationAttemptProcessor $generateEmailVerificationAttemptProcessor, FetchesCompanyModule $fetchesCompanyModule)
public function __construct(CreateUserProcessor $createUserProcessor, CreateCompanyProcessor $createCompanyProcessor, CreateCompanyModuleProcessor $createCompanyModuleProcessor, CreateContactProcessor $createContactProcessor, CreatesCompanyConnection $createsCompanyConnection, ApprovesCompanyConnection $approvesCompanyConnection, AssignEmployeeProcessor $assignEmployeeProcessor, UploadIdentityDocumentProcessor $uploadIdentityDocumentProcessor, AuthenticationProcessor $authenticationProcessor, GenerateEmailVerificationAttemptProcessor $generateEmailVerificationAttemptProcessor)
{
$this->createUserProcessor = $createUserProcessor;
$this->createCompanyProcessor = $createCompanyProcessor;
@@ -106,7 +101,6 @@ class CreateCustomerLogic extends AbstractControllerLogic
$this->uploadIdentityDocumentProcessor = $uploadIdentityDocumentProcessor;
$this->authenticationProcessor = $authenticationProcessor;
$this->generateEmailVerificationAttemptProcessor = $generateEmailVerificationAttemptProcessor;
$this->fetchesCompanyModule = $fetchesCompanyModule;
}
/**
@@ -132,9 +126,7 @@ class CreateCustomerLogic extends AbstractControllerLogic
/** @var CompanyModule $companyModule */
$companyModule = $this->createCompanyModuleProcessor->execute($company, BusinessType::IMPORTER);
$inviter = $this->fetchesCompanyModule->execute(['reference'=>'CIEF']);
$connectionObject = new CompanyConnectionObject($companyModule, $inviter, mt_rand(1000, 9999).(new GeneratesInitials())->name($company->name)->length(3)->generate(), 'CIEF');
$connectionObject = new CompanyConnectionObject($companyModule, 'CIEF', mt_rand(1000, 9999).(new GeneratesInitials())->name($company->name)->length(3)->generate());
$connection = $this->createsCompanyConnection->execute($connectionObject);
@@ -12,7 +12,6 @@ use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\ValueObjects\Constants\Notifications;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
class GeneratePasswordResetLogic extends AbstractControllerLogic
{
@@ -2,7 +2,6 @@
namespace App\Classes\Modules\Accounts\Services;
use App\Classes\ValueObjects\Constants\BusinessType;
use App\Classes\ValueObjects\Constants\RoleTypes;
use App\Models\User;
@@ -12,11 +11,6 @@ class AuthenticationRedirect
public function url(User $user){
if($user->type === RoleTypes::USER){
if (in_array($user->companyModule()->first()->type, [BusinessType::ONLINE_SELLER, BusinessType::LAST_MILE_DELIVERY_AGENT])) {
return route('last_mile_delivery.dashboard');
}
return route('dashboard');
}
@@ -68,11 +68,7 @@ class GeneratesAuthenticationToken {
$companyModule = $user->companyModule()->first();
$claims = array_merge($claims, [
'company_id' => $companyModule->company_id,
'company_module_id' => $companyModule->id,
'company_module_type' => $companyModule->type,
'company_name' => $companyModule->name,
'company_marking' => $companyModule->type !== 8 ? $companyModule->inviters()->withPivot('invitee_reference')->first()->pivot->invitee_reference : 'HWT',
'company_id' => $companyModule->company_id
]);
}
@@ -14,7 +14,6 @@ use App\Classes\Modules\Contacts\DataTransferObjects\ContactObject;
use App\Classes\Modules\Contacts\Processors\CreateContactProcessor;
use App\Classes\Modules\Remarks\DataTransferObjects\RemarkObject;
use App\Classes\Modules\Remarks\Processors\CreateRemarkProcessor;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Http\Resources\AddressResource;
use App\Models\Address;
use ErrorException;
@@ -83,7 +82,7 @@ class CreateAddressLogic extends AbstractControllerLogic
$district = $this->fetchesDistrict->execute(['id' => $request->input('district_id')]);
$object = new AddressObject($request->input('street_one'), $request->input('street_two'), $district->country_id, $district->state_id, $district->id, $request->input('post_code'), $request->input('type'), ApprovalStatus::APPROVED, $request->input('reference'));
$object = new AddressObject($request->input('street_one'), $request->input('street_two'), $district->country_id, $district->state_id, $district->id, $request->input('post_code'), $request->input('reference'));
$this->canCreateAddress->passes($object);
@@ -13,8 +13,6 @@ use App\Classes\Modules\Contacts\DataTransferObjects\ContactObject;
use App\Classes\Modules\Contacts\Processors\CreateContactProcessor;
use App\Classes\Modules\Remarks\DataTransferObjects\RemarkObject;
use App\Classes\Modules\Remarks\Processors\CreateRemarkProcessor;
use App\Classes\ValueObjects\Constants\AddressType;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Http\Resources\AddressResource;
use App\Models\Address;
use Illuminate\Http\JsonResponse;
@@ -81,7 +79,7 @@ class UpdateAddressLogic extends AbstractControllerLogic
{
$district = $this->fetchesDistrict->execute(['id' => $request->input('district_id')]);
$object = new AddressObject($request->input('street_one'), $request->input('street_two'), $district->country_id, $district->state_id, $district->id, $request->input('post_code'), AddressType::DELIVERY, ApprovalStatus::APPROVED, $request->input('reference'));
$object = new AddressObject($request->input('street_one'), $request->input('street_two'), $district->country_id, $district->state_id, $district->id, $request->input('post_code'), $request->input('reference'));
$this->canUpdateAddress->passes($object);
@@ -26,12 +26,6 @@ class AddressObject implements DataTransferObject
/** @var int */
private $postCode;
/** @var int */
private $type;
/** @var int */
private $status;
/** @var string|null */
private $reference;
@@ -43,11 +37,9 @@ class AddressObject implements DataTransferObject
* @param int $stateId
* @param int $districtId
* @param int $postCode
* @param int $type
* @param int $status
* @param null|string $reference
*/
public function __construct(string $streetOne, ?string $streetTwo, int $countryId, int $stateId, int $districtId, int $postCode, int $type, int $status, ?string $reference = null)
public function __construct(string $streetOne, ?string $streetTwo, int $countryId, int $stateId, int $districtId, int $postCode, ?string $reference = null, ?int $status = ApprovalStatus::APPROVED)
{
$this->streetOne = $streetOne;
$this->streetTwo = $streetTwo;
@@ -55,9 +47,8 @@ class AddressObject implements DataTransferObject
$this->stateId = $stateId;
$this->districtId = $districtId;
$this->postCode = $postCode;
$this->type = $type;
$this->status = $status;
$this->reference = $reference;
$this->status = $status;
}
/**
@@ -109,11 +100,11 @@ class AddressObject implements DataTransferObject
}
/**
* @return int
* @return null|string
*/
public function getType(): int
public function getReference(): ?string
{
return $this->type;
return $this->reference;
}
/**
@@ -124,13 +115,5 @@ class AddressObject implements DataTransferObject
return $this->status;
}
/**
* @return null|string
*/
public function getReference(): ?string
{
return $this->reference;
}
}
@@ -10,8 +10,6 @@ namespace App\Classes\Modules\Addresses\Services;
use App\Classes\Modules\Addresses\DataTransferObjects\AddressObject;
use App\Classes\ValueObjects\Constants\AddressType;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Models\District;
use App\Models\OldAddress;
@@ -33,7 +31,7 @@ class CleansOldAddress
return null;
}
return new AddressObject($this->cleanAddress($address->street_one, $district, $address->post_code), $this->cleanAddress($address->street_two, $district, $address->post_code), $district->country_id, $district->state_id, $district->id, $address->post_code, AddressType::DELIVERY, ApprovalStatus::APPROVED, 'Delivery Address');
return new AddressObject($this->cleanAddress($address->street_one, $district, $address->post_code), $this->cleanAddress($address->street_two, $district, $address->post_code), $district->country_id, $district->state_id, $district->id, $address->post_code, 'Delivery Address');
}
@@ -29,7 +29,6 @@ class CreatesAddress extends AbstractUpdateRelationshipRecord
$model->district_id = $object->getDistrictId();
$model->postcode = $object->getPostCode();
$model->status = $object->getStatus();
$model->type = $object->getType();
return $this->handler($addressable->addresses(), $model);
@@ -1,91 +0,0 @@
<?php
namespace App\Classes\Modules\Billplzs\ControllersLogic;
use App\Classes\Modules\Wallets\DataTransferObjects\WalletObject;
use App\Classes\Modules\Wallets\Services\UpdatesWallet;
use App\Classes\Exceptions\ResourceNotFoundException;
use App\Classes\Modules\Wallets\Services\UpdatesWalletBalance;
use App\Http\Resources\TransactionResource;
use App\Models\Booking;
use App\Models\User;
use App\Models\Wallet;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Classes\Exceptions\MalformedRequestException;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\Modules\Billplzs\Services\GetBillplzBill;
use App\Classes\Modules\Billplzs\DataTransferObjects\BillplzXSignatureObject;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Transactions\Services\FetchesTransaction;
use App\Classes\Modules\Transactions\Services\UpdatesTransactionStatus;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
class CallbackBillplzLogic
{
/** @var GetBillplzBill */
private $getBillplzBill;
/** @var FetchesTransaction */
private $fetchesTransaction;
/** @var UpdatesTransactionStatus */
private $updatesTransactionStatus;
/** @var UpdatesWalletBalance */
private $updatesWalletBalance;
/**
* CallbackBillplzLogic constructor.
* @param GetBillplzBill $getBillplzBill
* @param FetchesTransaction $fetchesTransaction
* @param UpdatesTransactionStatus $updatesTransactionStatus
* @param UpdatesWalletBalance $updatesWalletBalance
*/
public function __construct(GetBillplzBill $getBillplzBill, FetchesTransaction $fetchesTransaction, UpdatesTransactionStatus $updatesTransactionStatus)
{
$this->getBillplzBill = $getBillplzBill;
$this->fetchesTransaction = $fetchesTransaction;
$this->updatesTransactionStatus = $updatesTransactionStatus;
}
/**
* @param Request $request
* @return bool|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
* @throws MalformedRequestException
* @throws ResourceNotFoundException
*/
public function execute(Request $request)
{
$billplzXSignatureObject = new BillplzXSignatureObject($request);
if(!$billplzXSignatureObject->isValidSignature()){
throw new MalformedRequestException('Billplz Payment validation failed.');
}
$billPlz = $this->getBillplzBill->execute($billplzXSignatureObject->getBillPlzId());
if(!$billPlz) throw new ResourceNotFoundException('Billplz bill not found.');
$transaction = $this->fetchesTransaction->execute(['payment_reference' => $billplzXSignatureObject->getBillPlzId()]);
if($billPlz->state === 'paid') {
$status = ApprovalStatus::APPROVED;
}
if($billPlz->state === 'due') {
$status = $billplzXSignatureObject->getStatus() === 'failed' ? ApprovalStatus::REJECTED : ApprovalStatus::PENDING_VERIFICATION;
}
$token = Auth::fromUser(User::find(1));
$request->headers->set('Authorization', 'Bearer '.$token);
$marking = $transaction->owner()->first()->owner()->first();
return $request->method() === 'POST' ? true : view('pages.payments_redirect', ['marking' => $marking->reference, 'transaction' => $transaction, 'status' => $status]);
}
}
@@ -1,54 +0,0 @@
<?php
namespace App\Classes\Modules\Billplzs\ControllersLogic;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Billplzs\Services\CreatesBillplzBill;
use ErrorException;
use App\Classes\Exceptions\MalformedRequestException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class CreateBillplzBillLogic extends AbstractControllerLogic
{
/**
* @return array
*/
protected function notification():array {
return [
'title' => 'Created Billplz Bill',
'message' => 'You have successfully created a new Bill'
];
}
/** @var CreatesBillplzBill */
private $createsBillplzBill;
/**
* CreateBookingLogic constructor.
* @param CreatesBillplzBill $createsBillplzBill
*/
public function __construct(CreatesBillplzBill $createsBillplzBill)
{
$this->createsBillplzBill = $createsBillplzBill;
}
/**
* @param Request $request
* @return JsonResponse
* @throws MalformedRequestException
*/
public function logic(Request $request) : JsonResponse
{
$billPlz = $this->createsBillplzBill->execute($request->user()->name, $request->user()->email, $request->input('description'), 200, $request->input('bankName'));
if(!$billPlz) throw new MalformedRequestException('Unable to get correct response from billplz server.');
return $this->response(['data' => $billPlz]);
}
}
@@ -1,120 +0,0 @@
<?php
namespace App\Classes\Modules\Billplzs\DataTransferObjects;
use Illuminate\Http\Request;
use App\Classes\General\Interfaces\DataTransferObject;
use function PHPSTORM_META\map;
class BillplzXSignatureObject implements DataTransferObject
{
/** @var string */
private $billPlzId;
/** @var string */
private $status;
/** @var array */
private $billPlzConstructArray;
/** @var string */
private $billPlzConstructString;
/** @var string */
private $billPlzComputedXSignature;
/** @var string */
private $type;
/** @var Request */
private $request;
/** @var string */
private $requestXSignature;
public function __construct(Request $request)
{
$this->type = $request->exists('billplz') ? 'redirect' : 'callback';
$this->request = $this->type === 'redirect' ? $request->input('billplz') : $request;
$this->billPlzId = $this->request['id'];
$this->status = $this->request['transaction_status'];
$this->requestXSignature = $this->request['x_signature'];
$this->_constructBillplzArray()->_natSortBillplzArray()->_constructBillplzString()->_computeBillplzXSignature();
}
private function _constructBillplzArray(){
$this->billPlzConstructArray = collect($this->request)->forget('x_signature')->map(function($item, $key){
return $this->type === 'redirect' ? 'billplz'.$key.$item : $key.$item;
})->toArray();
return $this;
}
private function _natCaseSortBillplzArray(){
natcasesort($this->billPlzConstructArray);
return $this;
}
private function _natSortBillplzArray(){
natsort($this->billPlzConstructArray);
return $this;
}
private function _constructBillplzString(){
$this->billPlzConstructString = implode('|', $this->billPlzConstructArray);
return $this;
}
private function _computeBillplzXSignature(){
$this->billPlzComputedXSignature = hash_hmac('sha256', $this->billPlzConstructString, config('billplz.x_signature_key'));
return $this;
}
public function getBillPlzId(): string
{
return $this->billPlzId;
}
public function getStatus(): string
{
return $this->status;
}
/**
* @return array
*/
public function getBillPlzConstructArray(): array
{
return $this->billPlzConstructArray;
}
/**
* @return string
*/
public function getBillPlzConstructString(): string
{
return $this->billPlzConstructString;
}
/**
* @return string
*/
public function getBillPlzComputedXSignature(): string
{
return $this->billPlzComputedXSignature;
}
public function isValidSignature(): bool
{
return $this->billPlzComputedXSignature === $this->requestXSignature ? true : false;
}
}
@@ -1,57 +0,0 @@
<?php
namespace App\Classes\Modules\Billplzs\Services;
use Illuminate\Support\Facades\Http;
use App\Classes\Exceptions\MalformedRequestException;
class CreatesBillplzBill
{
/**
* @param string $name
* @param string $email
* @param string $description
* @param float $amount
* @param string $billNumber
* @param null|string $bankCode
* @param null|Boolean $wallet
* @return null|object
* @throws MalformedRequestException
*/
public function execute(string $name, string $email, string $description, float $amount, string $billNumber, ?string $bankCode = null, ?bool $wallet = null) {
try{
// config('billplz.maybank')
$response = Http::withBasicAuth(config('billplz.api_key').':', '')->post(config('billplz.base_url').'/api/v3/bills', [
'collection_id' => $wallet ? config('billplz.wallet_collection_id') : config('billplz.collection_id'),
'name' => $name,
'email' => $email,
'description' => $description,
'amount' => $this->finalizeAmount($amount),
'redirect_url' => route('online_payment.redirect'),
'callback_url' => route('api.online_payment.callback'),
'reference_1_label' => 'Bank Code',
'reference_1' => $bankCode ? $bankCode : '',
'reference_2_label' => 'Bill Number',
'reference_2' => $billNumber
]);
if($response->successful()){
$data = $response->json();
$data['url'] = $data['url'].'?auto_submit=true';
return (object) $data;
}else{
return null;
}
}catch(\Exception $exception){
throw new MalformedRequestException('Unable to get correct response from billplz server' . $exception->getMessage());
}
}
protected function finalizeAmount($amount){
$number = round($amount, 2) * 100;
return (string) $number;
}
}
@@ -1,31 +0,0 @@
<?php
namespace App\Classes\Modules\Billplzs\Services;
use App\Classes\Exceptions\MalformedRequestException;
use Illuminate\Support\Facades\Http;
class GetBillplzBill
{
/**
* @param string $billPlzId
* @return null|object
* @throws MalformedRequestException
*/
public function execute(string $billPlzId) {
try{
$response = Http::withBasicAuth(config('billplz.api_key').':', '')->get(config('billplz.base_url').'/api/v3/bills/'.$billPlzId);
if($response->successful()){
$data = $response->json();
return (object) $data;
}else{
return null;
}
}catch(\Exception $exception){
throw new MalformedRequestException('Unable to get correct response from billplz server');
}
}
}
@@ -14,8 +14,6 @@ use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Documents\Services\FetchesDocument;
use App\Classes\Modules\Documents\Services\ApprovesDocument;
use App\Classes\Modules\Notifications\DataTransferObjects\NotificationObject;
Use App\Classes\Modules\Notifications\Processors\CreateNotificationProcessor;
use App\Models\Document;
use Illuminate\Http\JsonResponse;
@@ -52,9 +50,6 @@ class ApproveIdentificationDocumentLogic extends AbstractControllerLogic
/** @var UpdatesOrdersStatus */
private $updatesOrdersStatus;
/** @var CreateNotificationProcessor */
private $createNotificationProcessor;
/**
* ApproveIdentificationDocumentLogic constructor.
* @param CanApproveDocument $canApproveDocument
@@ -63,9 +58,8 @@ class ApproveIdentificationDocumentLogic extends AbstractControllerLogic
* @param FetchesDocument $fetchesDocument
* @param UpdatesCompanyStatus $updatesCompanyStatus
* @param UpdatesOrdersStatus $updatesOrdersStatus
* @param CreateNotificationProcessor $createNotificationProcessor
*/
public function __construct(CanApproveDocument $canApproveDocument, ApprovesDocument $approvesDocument, RejectsDocument $rejectsDocument, FetchesDocument $fetchesDocument, UpdatesCompanyStatus $updatesCompanyStatus, UpdatesOrdersStatus $updatesOrdersStatus, CreateNotificationProcessor $createNotificationProcessor)
public function __construct(CanApproveDocument $canApproveDocument, ApprovesDocument $approvesDocument, RejectsDocument $rejectsDocument, FetchesDocument $fetchesDocument, UpdatesCompanyStatus $updatesCompanyStatus, UpdatesOrdersStatus $updatesOrdersStatus)
{
$this->canApproveDocument = $canApproveDocument;
$this->approvesDocument = $approvesDocument;
@@ -73,7 +67,6 @@ class ApproveIdentificationDocumentLogic extends AbstractControllerLogic
$this->fetchesDocument = $fetchesDocument;
$this->updatesCompanyStatus = $updatesCompanyStatus;
$this->updatesOrdersStatus = $updatesOrdersStatus;
$this->createNotificationProcessor = $createNotificationProcessor;
}
/**
@@ -97,16 +90,6 @@ class ApproveIdentificationDocumentLogic extends AbstractControllerLogic
$this->updatesCompanyStatus->execute($document->owner, $status === 'approve' ? ApprovalStatus::APPROVED : ApprovalStatus::REJECTED);
// $object = new NotificationObject(
// 'ID Verification ' . ( $status === 'approve' ? 'Approved' : 'Rejected' ),
// ( $status === 'approve' ? 'Dear user, congratulations that your ' : 'Dear user, we are sorry to inform you that your ' ) . ( $document->type === 'IDENTITY_CARD' ? 'IC' : 'SSM' ) . ( $status === 'approve' ? ' has been approved. Start your first order now!' : ' has been rejected due to ' . ( $request->input('rejectRemark') ?? '' ) . ', please resubmit it for further action.' ),
// $document->owner,
// $document->owner->companyModules()->first()->employees()->first(),
// $document,
// );
//
// $this->createNotificationProcessor->execute($object);
if($status === 'approve'){
$orders = $this->updatesOrdersStatus->execute($document->owner, ApprovalStatus::APPROVED);
}
@@ -1,61 +0,0 @@
<?php
namespace App\Classes\Modules\Companies\ControllersLogic;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Companies\Services\ListsCompanyModules;
use App\Classes\Modules\Companies\Standards\Rules\CanListCompanies;
use App\Http\Resources\CompanyModuleResource;
use ErrorException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class ListCompanyModulesLogic extends AbstractControllerLogic
{
/**
* @return array
*/
protected function notification():array {
return [
'title' => 'Retrieved Company Moduels',
'message' => 'You have successfully retrieved a list of Companies'
];
}
/** @var CanListCompanies */
private $canListCompanies;
/** @var ListsCompanyModules */
private $listsCompanyModules;
/**
* ListCompaniesControllersLogic constructor.
* @param CanListCompanies $canListCompanies
* @param ListsCompanyModules $listsCompanyModules
*/
public function __construct(CanListCompanies $canListCompanies, ListsCompanyModules $listsCompanyModules)
{
$this->canListCompanies = $canListCompanies;
$this->listsCompanyModules = $listsCompanyModules;
}
/**
* @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
{
$this->canListCompanies->passes();
$query = $this->listsCompanyModules->execute($this->listsCompanyModules->deserializeFilters($request->input('filters')));
return $this->collectionResponse(CompanyModuleResource::collection($query));
}
}
@@ -10,9 +10,6 @@ class CompanyConnectionObject implements DataTransferObject
/** @var CompanyModule */
private $invitee;
/** @var CompanyModule */
private $inviter;
/** @var string */
private $inviterReference;
@@ -23,14 +20,12 @@ class CompanyConnectionObject implements DataTransferObject
/**
* CompanyConnectionObject constructor.
* @param CompanyModule $invitee
* @param CompanyModule $inviter
* @param string $inviterReference
* @param string $inviteeReference
*/
public function __construct(CompanyModule $invitee, CompanyModule $inviter, string $inviteeReference, string $inviterReference)
public function __construct(CompanyModule $invitee, string $inviterReference, string $inviteeReference)
{
$this->invitee = $invitee;
$this->inviter = $inviter;
$this->inviterReference = $inviterReference;
$this->inviteeReference = $inviteeReference;
}
@@ -43,14 +38,6 @@ class CompanyConnectionObject implements DataTransferObject
return $this->invitee;
}
/**
* @return CompanyModule
*/
public function getInviter(): CompanyModule
{
return $this->inviter;
}
/**
* @return string
*/
@@ -4,7 +4,6 @@ namespace App\Classes\Modules\Companies\Services;
use App\Classes\Exceptions\MalformedRequestException;
use App\Classes\General\Eloquent\AbstractUpdateRecord;
use App\Classes\ValueObjects\Constants\BusinessType;
use App\Models\Company;
use App\Models\Segment;
use Illuminate\Database\QueryException;
@@ -20,9 +19,8 @@ class AssignsCompanyToSegment extends AbstractUpdateRecord
public function execute(Company $company, Segment $segment)
{
try {
$companyModule = $company->companyModules()->where('type', BusinessType::IMPORTER)->first();
$connection = $companyModule->connections()->where('inviter_reference', 'CIEF');
$connection->segments()->attach($segment);
$company->segments()->attach($segment);
return $company;
@@ -30,8 +30,10 @@ class CreatesCompanyConnection extends AbstractUpdateRecord
public function execute(CompanyConnectionObject $object)
{
$companyModule = $this->fetchesCompany->execute(['id', 1])->companyModules()->first();
$connection = new CompanyConnection();
$connection->inviter_id = $object->getInviter()->id;
$connection->inviter_id = $companyModule->id;
$connection->invitee_id = $object->getInvitee()->id;
$connection->inviter_reference = $object->getInviterReference();
$connection->invitee_reference = $object->getInviteeReference();
@@ -1,33 +0,0 @@
<?php
namespace App\Classes\Modules\Companies\Services;
use App\Classes\General\Eloquent\AbstractListRecord;
use Illuminate\Database\Eloquent\Builder;
use App\Models\CompanyModule;
class ListsCompanyModules extends AbstractListRecord
{
/** @var CompanyModule */
private $repository;
/**
* ListsCompanyModules constructor.
* @param CompanyModule $repository
*/
public function __construct(CompanyModule $repository)
{
$this->repository = $repository;
}
/**
* @return Builder
*/
function getRepository(): Builder
{
return $this->repository->newQuery();
}
}
@@ -1,58 +0,0 @@
<?php
namespace App\Classes\Modules\Delivery\ControllersLogic;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Orders\Services\CancelsOrder;
use App\Classes\Modules\Orders\Services\FetchesOrder;
use App\Http\Resources\DeliveryOrderResource;
use App\Models\Order;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class CancelDeliveryOrderLogic extends AbstractControllerLogic
{
/**
* @return array
*/
protected function notification(): array
{
return [
'title' => 'Cancelled Order',
'message' => 'You have successfully cancelled an order'
];
}
/** @var CancelsOrder */
private $cancelsOrder;
/** @var FetchesOrder */
private $fetchesOrder;
/**
* CancelDeliveryOrderLogic constructor.
* @param CancelsOrder $cancelsOrder
* @param FetchesOrder $fetchesOrder
*/
public function __construct(CancelsOrder $cancelsOrder, FetchesOrder $fetchesOrder)
{
$this->cancelsOrder = $cancelsOrder;
$this->fetchesOrder = $fetchesOrder;
}
/**
* @param Request $request
* @return JsonResponse
* @throws \App\Classes\Exceptions\MalformedRequestException
*/
public function logic(Request $request): JsonResponse
{
/** @var Order $order */
$order = $this->fetchesOrder->execute(['id' => $request->route('id')]);
return $this->resourceResponse(new DeliveryOrderResource($this->cancelsOrder->execute($order)));
}
}
@@ -1,150 +0,0 @@
<?php
namespace App\Classes\Modules\Delivery\ControllersLogic;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\General\Services\GeneratesInitials;
use App\Classes\Modules\Accounts\Processors\AuthenticationProcessor;
use App\Classes\Modules\Accounts\Processors\CreateUserProcessor;
use App\Classes\Modules\Accounts\Processors\GenerateEmailVerificationAttemptProcessor;
use App\Classes\Modules\Companies\DataTransferObjects\CompanyConnectionObject;
use App\Classes\Modules\Companies\Processors\AssignEmployeeProcessor;
use App\Classes\Modules\Companies\Processors\CreateCompanyProcessor;
use App\Classes\Modules\Companies\Processors\CreateCompanyModuleProcessor;
use App\Classes\Modules\Companies\DataTransferObjects\EmploymentObject;
use App\Classes\Modules\Companies\Services\ApprovesCompanyConnection;
use App\Classes\Modules\Companies\Services\CreatesCompanyConnection;
use App\Classes\Modules\Contacts\DataTransferObjects\ContactObject;
use App\Classes\Modules\Contacts\Processors\CreateContactProcessor;
use App\Classes\Modules\Documents\Processors\UploadIdentityDocumentProcessor;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\BusinessType;
use App\Classes\ValueObjects\Constants\CompanyType;
use App\Classes\ValueObjects\Constants\RoleTypes;
use App\Models\Company;
use App\Models\CompanyModule;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use App\Classes\Modules\Companies\Services\FetchesCompanyModule;
use Illuminate\Support\Facades\Log;
class CreateDeliveryCustomerLogic extends AbstractControllerLogic
{
/**
* @return array
*/
protected function notification(): array
{
return [
'title' => 'Created User',
'message' => 'You have successfully created a new User'
];
}
/** @var CreateUserProcessor */
private $createUserProcessor;
/** @var CreateCompanyProcessor */
private $createCompanyProcessor;
/** @var CreateCompanyModuleProcessor */
private $createCompanyModuleProcessor;
/** @var CreateContactProcessor */
private $createContactProcessor;
/** @var CreatesCompanyConnection */
private $createsCompanyConnection;
/** @var ApprovesCompanyConnection */
private $approvesCompanyConnection;
/** @var AssignEmployeeProcessor */
private $assignEmployeeProcessor;
/** @var UploadIdentityDocumentProcessor */
private $uploadIdentityDocumentProcessor;
/** @var AuthenticationProcessor */
private $authenticationProcessor;
/** @var GenerateEmailVerificationAttemptProcessor */
private $generateEmailVerificationAttemptProcessor;
/** @var FetchesCompanyModule */
private $fetchesCompanyModule;
/**
* CreateDeliveryCustomerLogic constructor.
* @param CreateUserProcessor $createUserProcessor
* @param CreateCompanyProcessor $createCompanyProcessor
* @param CreateCompanyModuleProcessor $createCompanyModuleProcessor
* @param CreateContactProcessor $createContactProcessor
* @param CreatesCompanyConnection $createsCompanyConnection
* @param ApprovesCompanyConnection $approvesCompanyConnection
* @param AssignEmployeeProcessor $assignEmployeeProcessor
* @param UploadIdentityDocumentProcessor $uploadIdentityDocumentProcessor
* @param AuthenticationProcessor $authenticationProcessor
* @param GenerateEmailVerificationAttemptProcessor $generateEmailVerificationAttemptProcessor
* @param FetchesCompanyModule $fetchesCompanyModule
*/
public function __construct(CreateUserProcessor $createUserProcessor, CreateCompanyProcessor $createCompanyProcessor, CreateCompanyModuleProcessor $createCompanyModuleProcessor, CreateContactProcessor $createContactProcessor, CreatesCompanyConnection $createsCompanyConnection, ApprovesCompanyConnection $approvesCompanyConnection, AssignEmployeeProcessor $assignEmployeeProcessor, UploadIdentityDocumentProcessor $uploadIdentityDocumentProcessor, AuthenticationProcessor $authenticationProcessor, GenerateEmailVerificationAttemptProcessor $generateEmailVerificationAttemptProcessor, FetchesCompanyModule $fetchesCompanyModule)
{
$this->createUserProcessor = $createUserProcessor;
$this->createCompanyProcessor = $createCompanyProcessor;
$this->createCompanyModuleProcessor = $createCompanyModuleProcessor;
$this->createContactProcessor = $createContactProcessor;
$this->createsCompanyConnection = $createsCompanyConnection;
$this->approvesCompanyConnection = $approvesCompanyConnection;
$this->assignEmployeeProcessor = $assignEmployeeProcessor;
$this->uploadIdentityDocumentProcessor = $uploadIdentityDocumentProcessor;
$this->authenticationProcessor = $authenticationProcessor;
$this->generateEmailVerificationAttemptProcessor = $generateEmailVerificationAttemptProcessor;
$this->fetchesCompanyModule = $fetchesCompanyModule;
}
/**
* @param Request $request
* @return JsonResponse
* @throws \App\Classes\Exceptions\AccessForbiddenException
* @throws \App\Classes\Exceptions\AccessUnauthorisedException
* @throws \App\Classes\Exceptions\MalformedRequestException
* @throws \App\Classes\Exceptions\RequestValidationException
*/
public function logic(Request $request): JsonResponse
{
/** @var User $user */
$user = $this->createUserProcessor->execute($request, RoleTypes::USER, !App::environment(['production']) ? ApprovalStatus::APPROVED : ApprovalStatus::PENDING_VERIFICATION);
/** @var Company $company */
$company = $this->createCompanyProcessor->execute($request->input('name'), CompanyType::PERSONAL_BUSINESS, ApprovalStatus::PENDING_SUBMISSION);
$contactObject = new ContactObject($request->input('name'), $request->input('phone'), $request->input('contact_email'), $request->input('wechat_id'));
$this->createContactProcessor->execute($contactObject, $company);
/** @var CompanyModule $companyModule */
$companyModule = $this->createCompanyModuleProcessor->execute($company, BusinessType::ONLINE_SELLER);
$inviter = $this->fetchesCompanyModule->execute(['reference'=>'HWT']);
$connectionObject = new CompanyConnectionObject($companyModule, $inviter, mt_rand(1000, 9999).(new GeneratesInitials())->name($company->name)->length(3)->generate(), 'HWT');
$connection = $this->createsCompanyConnection->execute($connectionObject);
$this->approvesCompanyConnection->execute($connection);
$Object = new EmploymentObject($companyModule, $user);
$this->assignEmployeeProcessor->execute($Object);
return $this->response($this->authenticationProcessor->execute($request));
}
}
@@ -1,178 +0,0 @@
<?php
namespace App\Classes\Modules\Delivery\ControllersLogic;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Addresses\DataTransferObjects\AddressObject;
use App\Classes\Modules\Addresses\Services\CreatesAddress;
use App\Classes\Modules\Addresses\Services\FetchesAddress;
use App\Classes\Modules\Companies\Services\FetchesCompany;
use App\Classes\Modules\Contacts\DataTransferObjects\ContactObject;
use App\Classes\Modules\Contacts\Processors\CreateContactProcessor;
use App\Classes\Modules\Orders\DataTransferObjects\OrderObject;
use App\Classes\Modules\Orders\Services\CreatesOrder;
use App\Classes\Modules\Orders\Services\GeneratesOrderNumber;
use App\Classes\Modules\Orders\Standards\Rules\CanCreateOrder;
use App\Classes\Modules\PackingLists\DataTransferObjects\PackageObject;
use App\Classes\Modules\PackingLists\DataTransferObjects\PackingListObject;
use App\Classes\Modules\PackingLists\Services\CreatesPackingList;
use App\Classes\Modules\PackingLists\Services\Packages\CreatesPackage;
use App\Classes\Modules\Remarks\DataTransferObjects\RemarkObject;
use App\Classes\Modules\Remarks\Processors\CreateRemarkProcessor;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\BusinessType;
use App\Classes\ValueObjects\Constants\OrderType;
use App\Classes\ValueObjects\Constants\PackingListType;
use App\Http\Resources\DeliveryOrderResource;
use App\Models\Address;
use App\Models\CompanyModule;
use App\Models\Order;
use App\Models\PackingList;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class CreateDeliveryOrderLogic extends AbstractControllerLogic
{
/**
* @return array
*/
protected function notification(): array
{
return [
'title' => 'Created Order',
'message' => 'You have successfully created a new Order'
];
}
/** @var FetchesCompany */
private $fetchesCompany;
/** @var fetchesAddress */
private $fetchesAddress;
/** @var CanCreateOrder */
private $canCreateOrder;
/** @var CreatesOrder */
private $createsOrder;
/** @var CreatesAddress */
private $createAddress;
/** @var CreateContactProcessor */
private $createContactProcessor;
/** @var CreateRemarkProcessor */
private $createRemarkProcessor;
/** @var GeneratesOrderNumber */
private $generatesOrderNumber;
/** @var CreatesPackingList */
private $createsPackingList;
/** @var CreatesPackage */
private $createsPackage;
/**
* CreateDeliveryOrderLogic constructor.
* @param FetchesCompany $fetchesCompany
* @param FetchesAddress $fetchesAddress
* @param CanCreateOrder $canCreateOrder
* @param CreatesOrder $createsOrder
* @param CreatesAddress $createAddress
* @param CreateContactProcessor $createContactProcessor
* @param CreateRemarkProcessor $createRemarkProcessor
* @param GeneratesOrderNumber $generatesOrderNumber
* @param CreatesPackingList $createsPackingList
* @param CreatesPackage $createPackage
*/
public function __construct(FetchesCompany $fetchesCompany, FetchesAddress $fetchesAddress, CanCreateOrder $canCreateOrder, CreatesOrder $createsOrder, CreatesAddress $createAddress, CreateContactProcessor $createContactProcessor, CreateRemarkProcessor $createRemarkProcessor, GeneratesOrderNumber $generatesOrderNumber, CreatesPackingList $createsPackingList, CreatesPackage $createsPackage)
{
$this->fetchesCompany = $fetchesCompany;
$this->fetchesAddress = $fetchesAddress;
$this->canCreateOrder = $canCreateOrder;
$this->createsOrder = $createsOrder;
$this->createAddress = $createAddress;
$this->createContactProcessor = $createContactProcessor;
$this->createRemarkProcessor = $createRemarkProcessor;
$this->generatesOrderNumber = $generatesOrderNumber;
$this->createsPackingList = $createsPackingList;
$this->createsPackage = $createsPackage;
}
/**
* @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
{
$company = $this->fetchesCompany->execute(['id' => $request->input('company_id')]);
$senderAddress = $this->fetchesAddress->execute(['id' => $request->input('sender_address_id')]);
$deliveryAddress = $this->fetchesAddress->execute(['id' => $request->input('delivery_address_id')]);
/** @var CompanyModule $companyModule */
$companyModule = $company->companyModules()->where('type', BusinessType::ONLINE_SELLER)->first();
$orderObject = new OrderObject($this->generatesOrderNumber->execute('168M', 7), OrderType::LAST_MILE_DELIVERY, ApprovalStatus::APPROVED);
$this->canCreateOrder->passes($orderObject);
/** @var Order $order */
$order = $this->createsOrder->execute($companyModule, $orderObject);
$senderAddressObject = new AddressObject($senderAddress->street_one, $senderAddress->street_two, $senderAddress->country_id, $senderAddress->state_id, $senderAddress->district_id, $senderAddress->postcode, $senderAddress->type, ApprovalStatus::APPROVED, $senderAddress->reference);
$deliveryAddressObject = new AddressObject($deliveryAddress->street_one, $deliveryAddress->street_two, $deliveryAddress->country_id, $deliveryAddress->state_id, $deliveryAddress->district_id, $deliveryAddress->postcode, $deliveryAddress->type, ApprovalStatus::APPROVED, $deliveryAddress->reference);
/** @var Address $orderSenderAddress */
$orderSenderAddress = $this->createAddress->execute($order, $senderAddressObject);
/** @var Address $orderDeliveryAddress */
$orderDeliveryAddress = $this->createAddress->execute($order, $deliveryAddressObject);
$senderContact = $senderAddress->contacts()->first();
$deliveryContact = $deliveryAddress->contacts()->first();
$contactObject = new ContactObject($senderContact->reference, $senderContact->phone, '','');
$this->createContactProcessor->execute($contactObject, $orderSenderAddress);
$contactObject = new ContactObject($deliveryContact->reference, $deliveryContact->phone, '','');
$this->createContactProcessor->execute($contactObject, $orderDeliveryAddress);
$senderRemark = $senderAddress->remarks()->first();
$deliveryRemark = $deliveryAddress->remarks()->first();
if ($senderRemark){
$remarkObject = new RemarkObject($senderRemark->content, Auth()->user()->id);
if($remarkObject->getContent()){
$this->createRemarkProcessor->execute($orderSenderAddress, $remarkObject);
}
}
if ($deliveryRemark){
$remarkObject = new RemarkObject($deliveryRemark->content, Auth()->user()->id);
if($remarkObject->getContent()){
$this->createRemarkProcessor->execute($orderDeliveryAddress, $remarkObject);
}
}
$packingListObject = new PackingListObject($order->reference, $companyModule->id, PackingListType::DELIVERY_PACKING_LIST, ApprovalStatus::PENDING_VERIFICATION);
/** @var PackingList $packingList */
$packingList = $this->createsPackingList->execute($packingListObject, $order);
$packageObject = new PackageObject($request->input('packing_list.type'), $request->input('packing_list.description'), (float) 1, (float) 1, (float) 1, $request->input('packing_list.weight'), (float) $request->input('packing_list.quantity'), ApprovalStatus::APPROVED);
$this->createsPackage->execute($packageObject, $packingList);
return $this->resourceResponse(new DeliveryOrderResource($order));
}
}
@@ -1,57 +0,0 @@
<?php
namespace App\Classes\Modules\Delivery\ControllersLogic;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Orders\Services\ListsOrders;
use App\Classes\Modules\Orders\Standards\Rules\CanListOrders;
use App\Classes\ValueObjects\Constants\OrderType;
use App\Http\Resources\DeliveryOrderResource;
use App\Http\Resources\OrderResource;
use ErrorException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class ListOrdersLogic extends AbstractControllerLogic
{
/**
* @return array
*/
protected function notification():array {
return [
'title' => 'Retrieved Orders',
'message' => 'You have successfully retrieved a list of Orders'
];
}
/** @var CanListOrders */
private $canListOrders;
/** @var ListsOrders */
private $listsOrders;
/**
* ListOrdersLogic constructor.
* @param CanListOrders $canListOrders
* @param ListsOrders $listsOrders
*/
public function __construct(CanListOrders $canListOrders, ListsOrders $listsOrders)
{
$this->canListOrders = $canListOrders;
$this->listsOrders = $listsOrders;
}
public function logic(Request $request) : JsonResponse
{
$this->canListOrders->passes();
$query = $this->listsOrders->execute(array_merge($this->listsOrders->deserializeFilters($request->input('filters')), ['with_parcels' => true, 'type_in' => [OrderType::LAST_MILE_DELIVERY]]));
return $this->collectionResponse(DeliveryOrderResource::collection($query));
}
}
@@ -1,73 +0,0 @@
<?php
namespace App\Classes\Modules\Exports\Services;
use App\Models\Order;
use App\Models\PackingList;
use Carbon\Carbon;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use App\Classes\ValueObjects\Constants\OrderRoleTypes;
class ExportsArrivedParcel implements WithHeadings, WithHeadingRow, WithMapping, ShouldAutoSize, FromQuery
{
use Exportable;
public function headings(): array
{
return [
'ORDER NUMBER',
'Marking',
'Warehouse',
'Cbm',
'Description',
'quantity',
'Received Date',
'Remarks'
];
}
/**
* @return \Illuminate\Support\Collection|mixed
*/
public function query()
{
return PackingList::where('type', '=', 1)->where('status', '=', 2)->where('owner_type', Order::class);
}
/**
* @param $packingList
* @return array
*/
public function map($packingList): array
{
$order = $packingList->owner;
$connection = $order->companyModule()->first()->inviters()->withPivot('invitee_reference')->first();
$marking = $connection ? $connection->pivot->invitee_reference:'';
$warehouse = $order->orderRoles()->where('role_id', '=', OrderRoleTypes::ORIGIN_WAREHOUSE)->first()->appointee;
$cbm = $packingList->packages->sum(function($package){
return (($package->width / 100) * ($package->height / 100) * ($package->length / 100)) * $package->quantity;
});
$arrival_date = $packingList->transports()->first()->drop_date->format('d-m-Y');
return [
$packingList->owner->reference,
$marking,
$warehouse->reference,
$cbm,
$packingList->packages->implode('description', ', '),
$packingList->packages->sum('quantity'),
$arrival_date,
''
];
}
}
@@ -1,91 +0,0 @@
<?php
namespace App\Classes\Modules\Exports\Services;
use App\Models\Container;
use App\Models\Package;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Carbon\Carbon;
class ExportsCompanyModuleSummary implements FromCollection, WithHeadings, WithHeadingRow, WithMapping, ShouldAutoSize
{
use Exportable;
protected $companyModuleId, $containerIds;
public function headings(): array
{
return [
'Date',
'Full Marking',
'Container',
'Description',
'Ctns',
'L (cm)',
'H (cm)',
'W (cm)',
'CBM'
];
}
public function setParameters($companyModuleId, $containerIds)
{
$this->companyModuleId = $companyModuleId;
$this->containerIds = $containerIds;
}
/**
* @return \Illuminate\Support\Collection|mixed
*/
public function collection()
{
$packagesArray = collect();
$containers = Container::whereIn('reference', explode(',', $this->containerIds))->get();
foreach ($containers as $container){
$company_module_id = $this->companyModuleId;
$packingLists = $container->packingLists()->get()->filter(function ($packingList) use ($company_module_id) {
return $packingList->owner->company_module_id == $company_module_id;
});
foreach ($packingLists as $packingList){
if($packingList->packingLists->first()){
$packingList = $packingList->packingLists->first();
}
$packages = $packingList->packages;
foreach ($packages as $package){
$packagesArray->push($package);
}
}
}
return $packagesArray;
}
/**
* @param Package $package
*
* @return array
*/
public function map($package): array
{
$connection = $package->packingList->owner->companyModule->inviters()->withPivot('invitee_reference')->first();
$marking = $connection ? $connection->pivot->invitee_reference:'';
return [
Carbon::parse($package->created_at)->format('d-m-Y'),
$marking,
$package->packingList->containers()->first()->reference,
$package->description,
$package->quantity,
$package->length,
$package->height,
$package->width,
((($package->length / 100) * ($package->height / 100) * ($package->width / 100)) * $package->quantity)
];
}
}
@@ -1,120 +0,0 @@
<?php
namespace App\Classes\Modules\Exports\Services;
use App\Classes\ValueObjects\Constants\AddressType;
use App\Classes\ValueObjects\Constants\OrderType;
use App\Classes\ValueObjects\Constants\PackageType;
use App\Models\Order;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Concerns\WithTitle;
class ExportsDeliveryOrders implements FromQuery, WithHeadings, WithHeadingRow, WithMapping, ShouldAutoSize, WithTitle
{
use Exportable;
private $request;
public function __construct(Request $request)
{
$this->request = $request;
}
public function headings(): array
{
return [
'Types_Of_Services',
'Service_Type',
'Sender_Name',
'Sender_Company_Name',
'Sender_Building_Unit',
'Sender_Address',
'Sender_Address_2',
'Sender_Postal_Code',
'Sender_Phone_Number',
'Delivery_Name',
'Delivery Company Name',
'Delivery_Building_Unit',
'Delivery_Address',
'Delivery_Address_2',
'Delivery_Postal_Code',
'Delivery_Phone_Number',
'Shipment_Type',
'Mode',
'Pickup_Address_Type',
'Reference_Number',
'Quantity',
'Weight',
'Length',
'Width',
'Height',
'COD_Amount',
'DO_Numbers'
];
}
/**
* @return \Illuminate\Support\Collection|mixed
*/
public function query()
{
$selectedIds = array_map(function($value){
return ['id' => $value];
}, json_decode($this->request->input('ids')));
return Order::where('type', OrderType::LAST_MILE_DELIVERY)->whereIn('id', $selectedIds);
}
public function title(): string
{
return 'bulk-shipment';
}
/**
* @param Order $order
*
* @return array
*/
public function map($order): array
{
$senderAddress = $order->addresses()->where('type', AddressType::PICK_UP)->first();
$deliveryAddress = $order->addresses()->where('type', AddressType::DELIVERY)->first();
$package = $order->packingLists()->first()->packages()->first();
return [
'Domestic Shipment',
'ST00000020',
$senderAddress->contacts()->first()->reference,
$senderAddress->reference ? $senderAddress->reference : $order->companyModule->name,
$senderAddress->street_one,
$senderAddress->street_two.' '.$senderAddress->district->name.' '.$senderAddress->postcode.' '.$senderAddress->state->name.' '.$senderAddress->country->name,
'',
$senderAddress->postcode,
$senderAddress->contacts()->first()->phone,
$deliveryAddress->contacts()->first()->reference,
$deliveryAddress->reference,
$deliveryAddress->street_one,
$deliveryAddress->street_two.' '.$deliveryAddress->district->name.' '.$deliveryAddress->postcode.' '.$deliveryAddress->state->name.' '.$deliveryAddress->country->name,
'',
$deliveryAddress->postcode,
$deliveryAddress->contacts()->first()->phone,
$package->type === PackageType::CARTON ? 'Package' : ($package->type === PackageType::PALLET ? 'Pallet' : 'Documents'),
'Pick Up',
'Default',
$order->reference,
$package->quantity,
$package->weight * $package->quantity,
1,
1,
1,
'',
''
];
}
}
@@ -1,74 +0,0 @@
<?php
namespace App\Classes\Modules\Exports\Services;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\FromCollection;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Concerns\WithTitle;
class ExportsDeliveryValidValues implements WithHeadings, WithHeadingRow, WithMapping, ShouldAutoSize, WithTitle, FromCollection
{
use Exportable;
private $request;
/**
* ExportsDeliveryValidValues constructor.
* @param Request $request
*/
public function __construct(Request $request)
{
$this->request = $request;
}
public function headings(): array
{
return [
'Types_Of_Services',
'Service_Type',
'Mode',
'Flag',
'Pickup Address'
];
}
/**
* @return \Illuminate\Support\Collection|mixed
*/
public function collection()
{
$returnArray = collect();
$returnArray->push(['Domestic Shipment', 'Package', 'Pick Up', 'Yes', 'Default']);
$returnArray->push(['', 'Documents', 'Lodge In / Walk In', 'No', 'Sender']);
$returnArray->push(['', 'Pallet', '', '', '']);
return $returnArray;
}
public function title(): string
{
return 'valid-values';
}
/**
* @param ReturnArray $returnArray
*
* @return array
*/
public function map($returnArray): array
{
return [
$returnArray[0],
$returnArray[1],
$returnArray[2],
$returnArray[3],
$returnArray[4],
];
}
}
@@ -1,38 +0,0 @@
<?php
namespace App\Classes\Modules\Exports\Services;
use App\Classes\Modules\Exports\Services\ExportsDeliveryOrders;
use App\Classes\Modules\Exports\Services\ExportsDeliveryValidValues;
use App\Models\Order;
use Maatwebsite\Excel\Concerns\Exportable;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Concerns\WithMultipleSheets;
class ExportsMultipleDeliveryOrders implements WithMultipleSheets
{
use Exportable;
protected $request;
/**
* ExportsMultipleDeliveryOrders constructor.
* @param Request $request
*/
public function __construct(Request $request)
{
$this->request = $request;
}
/**
* @return array
*/
public function sheets(): array
{
$sheets = [];
$sheets[] = new ExportsDeliveryOrders($this->request);
$sheets[] = new ExportsDeliveryValidValues($this->request);
return $sheets;
}
}
@@ -1,61 +0,0 @@
<?php
namespace App\Classes\Modules\Exports\Services;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Models\Order;
use App\Models\PackingList;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Carbon\Carbon;
class ExportsOnHoldPackingList implements FromQuery, WithHeadings, WithHeadingRow, WithMapping, ShouldAutoSize
{
use Exportable;
public function headings(): array
{
return [
'Container Ref.',
'ETA',
'Unstuffing',
'Marking',
'Order Number'
];
}
/**
* @return \Illuminate\Support\Collection|mixed
*/
public function query()
{
return PackingList::where('type', '=', 2)->whereIn('status', [4, 5])->whereHas('containers');
}
/**
* @param PackingList $packingList
*
* @return array
*/
public function map($packingList): array
{
$container = $packingList->containers()->first();
$ContainerTransport = $container->transports()->first();
$order = $packingList->owner;
if(!$order instanceof Order)return [];
$marking = $order->companyModule->inviters()->withPivot('invitee_reference')->first()->pivot->invitee_reference;
return [
$container->reference,
$ContainerTransport ? $ContainerTransport->schedules()->where('status', '=', ApprovalStatus::APPROVED)->first()->eta : 'n/a',
$ContainerTransport ? $ContainerTransport->drop_date : 'n/a',
$marking,
$order->reference,
];
}
}
@@ -1,85 +0,0 @@
<?php
namespace App\Classes\Modules\Exports\Services;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Models\PackingList;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Carbon\Carbon;
class ExportsPendingArrangementDeliveryList implements FromQuery, WithHeadings, WithHeadingRow, WithMapping, ShouldAutoSize
{
use Exportable;
public function headings(): array
{
return [
'Container Ref.',
'ETA',
'Unstuffing',
'Marking',
'Order Number',
'status',
'Delay Days / delivery date',
'Quantity',
'State',
'Postcode',
'Address',
'PIC',
'Phone',
'Remark'
];
}
/**
* @return \Illuminate\Support\Collection|mixed
*/
public function query()
{
return PackingList::where('type', '=', 2)->whereHas('containers', function ($query){
$query->where('containers.status', ApprovalStatus::COMPLETED);
});
}
/**
* @param PackingList $packingList
*
* @return array
*/
public function map($packingList): array
{
$container = $packingList->containers()->first();
$ContainerTransport = $container->transports()->first();
$order = $packingList->owner;
$inviter = $order->companyModule ? $order->companyModule->inviters()->withPivot('invitee_reference')->first() : null;
$marking = $inviter ? $inviter->pivot->invitee_reference : 'Unclaimed';
$address = $order->addresses()->where('status', ApprovalStatus::APPROVED)->first();
$contacts = $address->contacts->first() ? $address->contacts->first(): '';
$originalPackingList = $packingList->owner instanceof PackingList ? $packingList->owner : $packingList;
$transport = $originalPackingList->containers()->first()->transports()->first();
$deliveryTransport = $originalPackingList->transports()->first();
return [
$container->reference,
$ContainerTransport->schedules()->where('status', '=', ApprovalStatus::APPROVED)->first()->eta,
$ContainerTransport->drop_date,
$marking,
$order->reference,
$deliveryTransport ? (Carbon::parse($deliveryTransport->schedules()->first()->eta) < Carbon::now() ? 'Delivered' : 'Pending Delivery') : 'Pending Arrangement',
$deliveryTransport ? $deliveryTransport->schedules()->first()->eta : ($transport ? Carbon::now()->diffInDays($transport->drop_date, false) . ' Days' : ''),
$packingList->packages()->sum('quantity'),
$address->state->name,
$address->postcode,
$address->street_one.', '.$address->street_two.' '.$address->district->name.' '.$address->postcode.' '.$address->state->name.' '.$address->country->name,
$address->remarks->first() ? $address->remarks->first()->content: '',
$contacts ? $contacts ->reference : '',
$contacts ? $contacts ->phone : '',
];
}
}
@@ -1,61 +0,0 @@
<?php
namespace App\Classes\Modules\Notifications\ControllersLogic;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Notifications\Services\ListsNotification;
use App\Http\Resources\NotificationResource;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class ListNotificationsLogic extends AbstractControllerLogic
{
/**
* @return array
*/
protected function notification():array {
return [
'title' => 'Retrieve Notifications',
'message' => 'You have successfully retrieved a list of Notifications'
];
}
/** @var ListsNotification */
private $listsNotification;
/**
* ListNotificationsLogic constructor.
* @param ListsNotification $listsNotification
*/
public function __construct(
ListsNotification $listsNotification
)
{
$this->listsNotification = $listsNotification;
}
/**
* @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
{
$filters = [
// 'target_id'=>auth()->user()->id,
// 'per_page'=>$request->route('per_page')
];
$notifications = $this->listsNotification->execute($filters);
return $this->collectionResponse(NotificationResource::collection($notifications));
}
}
@@ -1,101 +0,0 @@
<?php
namespace App\Classes\Modules\Notifications\DataTransferObjects;
use App\Classes\General\Interfaces\Notifiable;
use App\Classes\General\Interfaces\DataTransferObject;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
class NotificationObject implements DataTransferObject
{
/** @var string */
private $title;
/** @var string */
private $description;
/** @var Notifiable */
private $subject;
/** @var Notifiable */
private $target;
/** @var Notifiable */
private $causer;
/** @var int|null */
private $status;
/**
* OrderObject constructor.
* @param string $reference
* @param int $type
* @param int|null $status
*/
public function __construct(
string $title,
string $description,
Notifiable $subject,
Notifiable $target,
Notifiable $causer,
?int $status = ApprovalStatus::PENDING_VERIFICATION
)
{
$this->title = $title;
$this->description = $description;
$this->subject = $subject;
$this->target = $target;
$this->causer = $causer;
$this->status = $status;
}
/**
* @return int
*/
public function getTitle(): string
{
return $this->title;
}
/**
* @return int
*/
public function getDescription(): string
{
return $this->description;
}
/**
* @return Notifiable
*/
public function getSubject(): Notifiable
{
return $this->subject;
}
/**
* @return Notifiable
*/
public function getTarget(): Notifiable
{
return $this->target;
}
/**
* @return Notifiable
*/
public function getCauser(): Notifiable
{
return $this->causer;
}
/**
* @return int
*/
public function getStatus(): int
{
return $this->status;
}
}
@@ -1,27 +0,0 @@
<?php
namespace App\Classes\Modules\Notifications\Processors;
use App\Classes\Modules\Notifications\DataTransferObjects\NotificationObject;
use App\Classes\Modules\Notifications\Services\CreatesNotification;
class CreateNotificationProcessor
{
/** @var CreatesNotification */
private $createsNotification;
/**
* CreateNotificationProcessor constructor.
* @param CreatesNotification $createsNotification
*/
public function __construct(CreatesNotification $createsNotification)
{
$this->createsNotification = $createsNotification;
}
public function execute(NotificationObject $object)
{
$notification = $this->createsNotification->execute($object);
return $notification;
}
}
@@ -1,30 +0,0 @@
<?php
namespace App\Classes\Modules\Notifications\Services;
use App\Classes\Modules\Notifications\DataTransferObjects\NotificationObject;
use App\Models\Notification;
class CreatesNotification
{
/**
* @param NotificationObject $object
* @return \Illuminate\Database\Eloquent\Model
* @throws \App\Classes\Exceptions\MalformedRequestException
*/
public function execute(NotificationObject $object) {
$model = new Notification();
$model->title = $object->getTitle();
$model->description = $object->getDescription();
$model->status = $object->getStatus();
$model->subject_type = get_class($object->getSubject());
$model->subject_id = $object->getSubject()->id;
$model->target_type = get_class($object->getTarget());
$model->target_id = $object->getTarget()->id;
$model->causer_type = get_class($object->getCauser());
$model->causer_id = $object->getCauser()->id;
$model->save();
return $model;
}
}
@@ -1,33 +0,0 @@
<?php
namespace App\Classes\Modules\Notifications\Services;
use App\Classes\General\Eloquent\AbstractListRecord;
use Illuminate\Database\Eloquent\Builder;
use App\Models\Notification;
class ListsNotification extends AbstractListRecord
{
/** @var Bank */
private $repository;
/**
* ListsBank constructor.
* @param Notification $repository
*/
public function __construct(Notification $repository)
{
$this->repository = $repository;
}
/**
* @return Builder
*/
function getRepository(): Builder
{
return $this->repository->newQuery();
}
}
@@ -63,12 +63,10 @@ class CreateOrderLogic extends AbstractControllerLogic
$company = $this->fetchesCompany->execute(['id' => $request->input('company_id')]);
$address = $this->fetchesAddress->execute(['id' => $request->input('address_id')]);
$originWarehouse = $this->fetchesCompanyModule->execute(['id' => $request->input('warehouse_id')]);
if(!in_array($company->companyModules()->importers()->first()->id, WarehouseReferences::YD_EXEMPT_LIST)){
$originWarehouse = $this->fetchesCompanyModule->execute(['reference' => $originWarehouse->reference === WarehouseReferences::VT_GUANG_ZHOU ? WarehouseReferences::YD_GUANG_ZHOU : WarehouseReferences::YD_YIWU]);
}
$originWarehouse = $originWarehouse->reference === WarehouseReferences::VT_GUANG_ZHOU ? $this->fetchesCompanyModule->execute(['reference' => in_array($company->id, [2376]) ? WarehouseReferences::VT_GUANG_ZHOU : WarehouseReferences::YD_GUANG_ZHOU]) : $this->fetchesCompanyModule->execute(['reference' => WarehouseReferences::YD_YIWU]);
if($originWarehouse->reference === WarehouseReferences::YD_YIWU && in_array($address->state_id, [5, 13, 14])) {
throw new RequestValidationException('Our Yiwu warehouse is unable to ship goods to Sabah & Sarawak at the moment. you can select our Guangzhou warehouse as an alternative.');
@@ -0,0 +1,60 @@
<?php
namespace App\Classes\Modules\Orders\ControllersLogic;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Orders\Services\FetchesOrder;
use App\Classes\Modules\Remarks\DataTransferObjects\RemarkObject;
use App\Classes\Modules\Remarks\Processors\CreateRemarkProcessor;
use App\Http\Resources\OrderResource;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class CreateOrderRemarkLogic extends AbstractControllerLogic
{
/**
* @return array
*/
protected function notification():array {
return [
'title' => 'Created Order',
'message' => 'You have successfully created a new Order'
];
}
/** @var FetchesOrder */
private $fetchesOrder;
/** @var CreateRemarkProcessor */
private $createRemarkProcessor;
/**
* CreateOrderRemarkLogic constructor.
* @param FetchesOrder $fetchesOrder
* @param CreateRemarkProcessor $createRemarkProcessor
*/
public function __construct(FetchesOrder $fetchesOrder, CreateRemarkProcessor $createRemarkProcessor)
{
$this->fetchesOrder = $fetchesOrder;
$this->createRemarkProcessor = $createRemarkProcessor;
}
/**
* @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
{
$order = $this->fetchesOrder->execute(['id' => $request->route('id')]);
$object = new RemarkObject($request->input('content'), auth()->user()->id);
$this->createRemarkProcessor->execute($order, $object);
return $this->resourceResponse(new OrderResource($order));
}
}
@@ -6,7 +6,6 @@ namespace App\Classes\Modules\Orders\ControllersLogic;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Orders\Services\ListsOrders;
use App\Classes\Modules\Orders\Standards\Rules\CanListOrders;
use App\Classes\ValueObjects\Constants\OrderType;
use App\Http\Resources\OrderResource;
use ErrorException;
use Illuminate\Http\JsonResponse;
@@ -45,7 +44,7 @@ class ListOrdersLogic extends AbstractControllerLogic
{
$this->canListOrders->passes();
$query = $this->listsOrders->execute(array_merge($this->listsOrders->deserializeFilters($request->input('filters')), ['with_parcels' => true, 'type_in' => [OrderType::SHARED_CONTAINER, OrderType::DEDICATED_CONTAINER]]));
$query = $this->listsOrders->execute(array_merge($this->listsOrders->deserializeFilters($request->input('filters')), ['with_parcels' => true]));
return $this->collectionResponse(OrderResource::collection($query));
@@ -9,7 +9,7 @@ use App\Classes\ValueObjects\Constants\ApprovalStatus;
class OrderObject implements DataTransferObject
{
/** @var string */
/** @var int */
private $reference;
/** @var int */
@@ -20,11 +20,11 @@ class OrderObject implements DataTransferObject
/**
* OrderObject constructor.
* @param string $reference
* @param int $reference
* @param int $type
* @param int|null $status
*/
public function __construct(string $reference, int $type, ?int $status)
public function __construct(int $reference, int $type, ?int $status = ApprovalStatus::PENDING_VERIFICATION)
{
$this->reference = $reference;
$this->type = $type;
@@ -32,9 +32,9 @@ class OrderObject implements DataTransferObject
}
/**
* @return string
* @return int
*/
public function getReference(): string
public function getReference(): int
{
return $this->reference;
}
@@ -48,13 +48,12 @@ class OrderObject implements DataTransferObject
}
/**
* @return int|null
* @return int
*/
public function getStatus(): ?int
public function getStatus(): int
{
return $this->status;
}
}
@@ -7,7 +7,6 @@ use App\Classes\Modules\Orders\Standards\Rules\CanApproveChangeOrderAddress;
use App\Classes\Modules\Orders\Services\UpdatesOrdersAddress;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\OrderRoleTypes;
use App\Classes\ValueObjects\Constants\PackingListType;
use Illuminate\Http\Request;
class ApproveChangeOrderAddressProcessor
@@ -66,11 +65,7 @@ class ApproveChangeOrderAddressProcessor
$address->owner->addresses()->update(['status' => ApprovalStatus::EXPIRED]);
$appointee = $address->owner->orderRoles()->where('role_id', '=', OrderRoleTypes::ORIGIN_FREIGHT_FORWARDER)->first()->appointee->id;
if($appointee === 2) {
foreach($address->owner->packingLists()->where('type', PackingListType::SHIPPING_PACKING_LIST) as $packingList){
$this->updateDoFromVTPortalProcessor->execute($packingList);
}
}
$appointee === 2 ? $this->updateDoFromVTPortalProcessor->execute($address) : $this->updateDoFromYDPortalProcessor->execute($address);
}
@@ -84,7 +84,7 @@ class CreateOrderProcessor
/** @var Order $order */
$order = $this->createsOrder->execute($importer, $orderObject);
$addressObject = new AddressObject($address->street_one, $address->street_two, $address->country_id, $address->state_id, $address->district_id, $address->postcode, $address->type, ApprovalStatus::APPROVED, $address->reference);
$addressObject = new AddressObject($address->street_one, $address->street_two, $address->country_id, $address->state_id, $address->district_id, $address->postcode,$address->reference);
/** @var Address $order_address */
$order_address = $this->createAddress->execute($order, $addressObject);
@@ -8,7 +8,6 @@ use App\Classes\Modules\Addresses\Services\CreatesAddress;
use App\Classes\Modules\Addresses\Services\FetchesAddress;
use App\Classes\Modules\Addresses\Services\DeletesAddress;
use App\Classes\Modules\Addresses\DataTransferObjects\AddressObject;
use App\Classes\ValueObjects\Constants\AddressType;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\Modules\Contacts\DataTransferObjects\ContactObject;
use App\Classes\Modules\Remarks\DataTransferObjects\RemarkObject;
@@ -77,7 +76,7 @@ class RequestChangeOrderAddressProcessor
}
$address = $this->fetchesAddress->execute(['id' => $request->get('address_id')]);
$addressObject = new AddressObject($address->street_one, $address->street_two, $address->country_id, $address->state_id, $address->district_id, $address->postcode, AddressType::DELIVERY, ApprovalStatus::PENDING_VERIFICATION, $address->reference);
$addressObject = new AddressObject($address->street_one, $address->street_two, $address->country_id, $address->state_id, $address->district_id, $address->postcode, $address->reference, ApprovalStatus::PENDING_VERIFICATION);
$order_address = $this->createsAddress->execute($order, $addressObject);
$contact = $address->contacts()->first();
@@ -6,9 +6,23 @@ use App\Classes\Exceptions\InternalServerErrorException;
use App\Classes\Modules\Orders\Services\FetchesDataFromVTPortal;
use App\Classes\Modules\Addresses\Services\FetchesAddress;
use App\Classes\Modules\Schedules\DataTransferObjects\ScheduleObject;
use App\Classes\Modules\Schedules\Services\CreatesSchedule;
use App\Classes\Modules\Transports\DataTransferObjects\TransportObject;
use App\Classes\Modules\Transports\Services\CreatesTransport;
use App\Classes\Modules\Unity\Services\UpdatesContractObligation;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\OrderRoleTypes;
use App\Classes\ValueObjects\Constants\PackingListType;
use App\Classes\ValueObjects\Constants\TransportType;
use App\Models\PackingList;
use App\Models\Transport;
use Carbon\Carbon;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\Log;
use Illuminate\Http\Request;
class UpdateDoFromVTPortalProcessor
{
/** @var FetchesDataFromVTPortal */
@@ -29,20 +43,19 @@ class UpdateDoFromVTPortalProcessor
}
/**
* @param PackingList $packing_list
* @param $address
* @return array
* @throws GuzzleException
* @throws InternalServerErrorException
*/
public function execute(PackingList $packing_list) {
public function execute($address) {
if(!app()->environment(['production'])){
return [];
}
try {
$address= $packing_list->owner->addresses()->where('status', ApprovalStatus::APPROVED)->first();
$order = $packing_list->owner;
$order = $address->owner()->orderBy('id', 'desc')->first();
$packing_list = $order->packingLists()->orderBy('id', 'desc')->first();
if ($packing_list) {
$contact = $address->contacts()->first();
@@ -54,7 +67,7 @@ class UpdateDoFromVTPortalProcessor
$status = 'On Hold';
if (in_array($packing_list->status, [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED])) {
if (in_array($packing_list->status, [ApprovalStatus::PENDING_VERIFICATION, ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED])) {
$status = 'Release';
}
@@ -64,7 +77,6 @@ class UpdateDoFromVTPortalProcessor
if ($vt_do) {
foreach ($vt_do->Rows as $key => $row) {
if($row[4] !== $packing_list->containers()->first()->reference) continue;
$vt_do_update = $this->fetchesDataFRomVTPortal->clientRequest(
'http://portal.vtnation.com.my/Services/DataControllerService.asmx/Execute',
'POST',
@@ -129,7 +141,7 @@ class UpdateDoFromVTPortalProcessor
}
} catch (\Exception $exception){
throw new InternalServerErrorException('failed to approve address due to an error related to VT portal: '.$exception->getMessage());
return [];
}
}
@@ -8,7 +8,6 @@ use App\Classes\Modules\Addresses\Services\FetchesAddress;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\PackingListType;
use App\Models\PackingList;
use Illuminate\Support\Facades\Log;
class UpdateDoFromYDPortalProcessor
@@ -31,34 +30,36 @@ class UpdateDoFromYDPortalProcessor
}
/**
* @param PackingList $packingList
* @param $address
* @return void
* @throws InternalServerErrorException
*/
public function execute(PackingList $packingList) {
if(!app()->environment(['production'])){
return;
}
public function execute($address) {
try {
$address = $packingList->owner->addresses()->where('status', ApprovalStatus::APPROVED)->first();
$order = $address->owner()->orderBy('id', 'desc')->first();
$packing_lists = $order->packingLists()
->where('type', PackingListType::SHIPPING_PACKING_LIST)
->where('status', '!=', ApprovalStatus::SUSPENDED)
->orderBy('id', 'desc')->get();
if (!in_array($packingList->status, [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED])) {
return;
}
$contact = $address->contacts()->first();
$remark = $address->remarks()->first();
foreach ($packing_lists as $key => $row) {
if ($row->status === ApprovalStatus::SUSPENDED) {
continue;
}
$phone = $contact ? $contact->phone : null;
$reference = $contact ? $contact->reference : null;
$remark = $remark ? $remark->content : 'URGENT!!! PLEASE CALL BEFORE ONE DAY DELIVERY.';
$contact = $address->contacts()->first();
$remark = $address->remarks()->first();
$this->fetchesDataFRomYDPortal->clientRequest(
'http://www.yd-wl.com/api/UpdateOrderAddress.ashx',
'POST',
$phone = $contact ? $contact->phone : null;
$reference = $contact ? $contact->reference : null;
$remark = $remark ? $remark->content : 'URGENT!!! PLEASE CALL BEFORE ONE DAY DELIVERY.';
$this->fetchesDataFRomYDPortal->clientRequest(
'http://www.yd-wl.com/api/UpdateOrderAddress.ashx',
'POST',
[
'expressno' => $packingList->reference,
'expressno' => $row->reference,
'customers_name' => $reference,
'cellphone' => $phone,
'postcode' => $address->postcode,
@@ -67,6 +68,8 @@ class UpdateDoFromYDPortalProcessor
]);
}
} catch (\Exception $exception){
throw new InternalServerErrorException('failed to approve address due to an error related to YD portal');
}
@@ -21,7 +21,7 @@ class ChecksIfOrderNumberExists
$this->repository = $repository;
}
public function execute(string $orderNumber): bool {
public function execute(int $orderNumber): bool {
return $this->repository->where('reference', $orderNumber)->exists();
}
@@ -20,13 +20,11 @@ class GeneratesOrderNumber
/**
* @param null|string $prefix
* @param int|null $length
* @return string
* @return int
*/
public function execute(?string $prefix = '', ?int $length = 9): string {
public function execute(): int {
$reference = $prefix.rand((int)('1'.str_repeat(0, $length - 2).'1'), (int) str_repeat(9, $length));
$reference = rand(100000001, 999999999);
return !$this->checkIfOrderNumberExists->execute($reference) ? $reference : self::execute();
}
@@ -2,7 +2,6 @@
namespace App\Classes\Modules\PackingLists\ControllersLogic;
use App\Classes\Exceptions\ResourceNotFoundException;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\PackingLists\Services\FetchesPackingList;
use App\Classes\Modules\Orders\Services\FetchesOrder;
@@ -73,16 +72,8 @@ class AssignPackingListOrderLogic extends AbstractControllerLogic
/**
* CreateRemarkLogic constructor.
* @param FetchesPackingList $fetchesPackingList
* @param FetchesOrder $fetchesOrder
* @param UpdatesPackingListOwner $updatesPackingListOwner
* @param UpdatesTransportStatus $updatesTransportStatus
* @param CreatesContract $unityCreateContract
* @param ActivateContractProcessor $unityActivateContract
* @param CreateContractEntityProcessor $unityCreateContractEntity
* @param AssignContractEntityProcessor $unityAssignContractEntity
* @param UpdatesPackingListContractReference $updatesPackingListContractReference
* @param CreatesStep $createsStep
* @param CanCreateRemark $canCreateRemark
* @param CreatesPackingListRemark $createsPackingListRemark
*/
public function __construct(FetchesPackingList $fetchesPackingList, FetchesOrder $fetchesOrder, UpdatesPackingListOwner $updatesPackingListOwner, UpdatesTransportStatus $updatesTransportStatus, CreatesContract $unityCreateContract, ActivateContractProcessor $unityActivateContract, CreateContractEntityProcessor $unityCreateContractEntity, AssignContractEntityProcessor $unityAssignContractEntity, UpdatesPackingListContractReference $updatesPackingListContractReference, CreatesStep $createsStep)
{
@@ -135,25 +126,20 @@ class AssignPackingListOrderLogic extends AbstractControllerLogic
$this->unityAssignContractEntity->execute($supervisorContractEntity->hash_id, $contractObligations);
try {
$packing_list = $this->fetchesPackingList->execute([
'reference' => $warehouse_packing_list->reference,
'type' => PackingListType::SHIPPING_PACKING_LIST
]);
$packing_list = $this->fetchesPackingList->execute([
'reference' => $warehouse_packing_list->reference,
'type' => PackingListType::SHIPPING_PACKING_LIST
]);
$warehouse_packing_list = $this->updatesPackingListOwner->execute($packing_list, $order);
$this->updatesPackingListContractReference->execute($packing_list, $contractReference);
foreach($contractObligations as $obligation) {
$stepObject = new StepsObject($order->orderRoles()->where('role_id', '=', OrderRoleTypes::SUPERVISOR)->first()->appointee->id, $obligation->reference, $obligation->sequence, $obligation->hash_id);
$this->createsStep->execute($packing_list, $stepObject);
}
} catch (ResourceNotFoundException $exception) {
$warehouse_packing_list = $this->updatesPackingListOwner->execute($packing_list, $order);
$this->updatesPackingListContractReference->execute($packing_list, $contractReference);
foreach($contractObligations as $obligation) {
$stepObject = new StepsObject($order->orderRoles()->where('role_id', '=', OrderRoleTypes::SUPERVISOR)->first()->appointee->id, $obligation->reference, $obligation->sequence, $obligation->hash_id);
$this->createsStep->execute($packing_list, $stepObject);
}
return $this->resourceResponse(new PackingListResource($warehouse_packing_list));
}
}
@@ -20,8 +20,8 @@ class CreateContainerRemarkLogic extends AbstractControllerLogic
*/
protected function notification():array {
return [
'title' => 'Created Container Remark',
'message' => 'You have successfully created a new Container Remark'
'title' => 'Created Container',
'message' => 'You have successfully created a new Container'
];
}
@@ -7,7 +7,6 @@ use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\PackingLists\Services\DeletesPackingList;
use App\Classes\Modules\PackingLists\Services\FetchesPackingList;
use App\Classes\Modules\PackingLists\Standards\Rules\CanDeletePackingList;
use App\Classes\ValueObjects\Constants\PackingListType;
use ErrorException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
@@ -59,11 +58,9 @@ class DeletePackingListLogic extends AbstractControllerLogic
$this->canDeletePackingList->passes();
$warehouseList = $this->fetchesPackingList->execute(['id' => $request->route('id')]);
$packingList = $this->fetchesPackingList->execute(['reference' => $warehouseList->reference, 'type' => PackingListType::SHIPPING_PACKING_LIST]);
$query = $this->fetchesPackingList->execute(['id' => $request->route('id')]);
$this->deletesPackingList->execute($warehouseList);
$this->deletesPackingList->execute($packingList);
$this->deletesPackingList->execute($query);
return $this->response([]);
@@ -7,13 +7,9 @@ use App\Classes\Modules\PackingLists\Services\FetchesPackingList;
use App\Classes\Modules\Schedules\Services\CreatesSchedule;
use App\Classes\Modules\Schedules\Services\UpdatesScheduleStatus;
use App\Classes\Modules\Schedules\DataTransferObjects\ScheduleObject;
use App\Classes\Modules\Transports\DataTransferObjects\TransportObject;
use App\Classes\Modules\Transports\Services\CreatesTransport;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\TransportType;
use App\Http\Resources\PackingListResource;
use App\Models\Transport;
use ErrorException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
@@ -21,8 +17,6 @@ use Carbon\Carbon;
class ReschedulePackingListLogic extends AbstractControllerLogic
{
/**
* @return array
*/
@@ -39,57 +33,51 @@ class ReschedulePackingListLogic extends AbstractControllerLogic
/** @var UpdatesScheduleStatus */
private $updatesScheduleStatus;
/** @var CreatesTransport */
private $createsTransport;
/** @var CreatesSchedule */
private $createsSchedule;
/**
* ReschedulePackingListLogic constructor.
* DeleteContainerControllersLogic constructor.
* @param FetchesPackingList $fetchesPackingList
* @param UpdatesScheduleStatus $updatesScheduleStatus
* @param CreatesTransport $createsTransport
* @param CreatesSchedule $createsSchedule
*/
public function __construct(FetchesPackingList $fetchesPackingList, UpdatesScheduleStatus $updatesScheduleStatus, CreatesTransport $createsTransport, CreatesSchedule $createsSchedule)
public function __construct(FetchesPackingList $fetchesPackingList, UpdatesScheduleStatus $updatesScheduleStatus, CreatesSchedule $createsSchedule)
{
$this->fetchesPackingList = $fetchesPackingList;
$this->updatesScheduleStatus = $updatesScheduleStatus;
$this->createsTransport = $createsTransport;
$this->createsSchedule = $createsSchedule;
}
/**
* @param Request $request
* @return JsonResponse
* @throws \App\Classes\Exceptions\MalformedRequestException
* @throws ErrorException
*/
public function logic(Request $request) : JsonResponse
{
$packing_list = $this->fetchesPackingList->execute(['id' => $request->route('id')]);
try {
$packing_list = $this->fetchesPackingList->execute(['id' => $request->route('id')]);
$transport = $packing_list->transports()->first();
$transport = $packing_list->transports()->first();
if(!$transport) {
$object = new TransportObject(TransportType::LAND, null, '', Carbon::parse($request->input('etd')), Carbon::parse($request->input('eta')),ApprovalStatus::APPROVED);
/** @var Transport $transport */
$transport = $this->createsTransport->execute($object, $packing_list);
$old_sechedule = $transport->schedules()->first();
$this->updatesScheduleStatus->execute($old_sechedule, ApprovalStatus::REJECTED);
$scheduleObject = new ScheduleObject(
Carbon::parse($request->input('eta')),
Carbon::parse($request->input('etd')),
ApprovalStatus::APPROVED
);
$schedule = $this->createsSchedule->execute($transport, $scheduleObject);
return $this->resourceResponse(new PackingListResource($packing_list));
} catch (\Exception $exception){
throw new ErrorException($exception->getMessage(), $exception->getCode());
}
$transport->schedules()->update([
'status' => ApprovalStatus::REJECTED
]);
$scheduleObject = new ScheduleObject(
Carbon::parse($request->input('eta')),
Carbon::parse($request->input('etd')),
ApprovalStatus::APPROVED
);
$schedule = $this->createsSchedule->execute($transport, $scheduleObject);
return $this->resourceResponse(new PackingListResource($packing_list));
}
}
@@ -14,7 +14,6 @@ use App\Classes\Modules\Orders\Processors\UpdateDoFromVTPortalProcessor;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\OrderRoleTypes;
use App\Http\Resources\PackingListResource;
use App\Models\PackingList;
use ErrorException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
@@ -71,16 +70,16 @@ class UpdatePackingListStatusLogic extends AbstractControllerLogic
{
$packingList = $this->fetchesPackingList->execute(['id' => $request->route('id')]);
/** @var PackingList $packingList */
$packingList = $this->updatesPackingListStatus->execute($packingList, $request->route('status'));
$packing_list = $this->updatesPackingListStatus->execute($packingList, $request->route('status'));
$address = $packing_list->owner()->first()->addresses()->where('status', ApprovalStatus::APPROVED)->first();
// $appointee = $address->owner->orderRoles()->where('role_id', '=', OrderRoleTypes::ORIGIN_FREIGHT_FORWARDER)->first()->appointee->id;
$this->updateDoFromVTPortalProcessor->execute($packingList);
$this->updateDoFromYDPortalProcessor->execute($packingList);
$this->updateDoFromVTPortalProcessor->execute($address);
$this->updateDoFromYDPortalProcessor->execute($address);
return $this->resourceResponse(new PackingListResource($packingList));
return $this->resourceResponse(new PackingListResource($packing_list));
}
}
@@ -6,8 +6,6 @@ namespace App\Classes\Modules\PackingLists\Processors;
use App\Classes\Modules\PackingLists\DataTransferObjects\PackageObject;
use App\Classes\Modules\PackingLists\Services\Packages\CreatesPackage;
use App\Classes\Modules\PackingLists\Standards\Rules\Packages\CanCreatePackage;
use App\Classes\ValueObjects\Constants\WarehouseReferences;
use App\Models\Order;
use App\Models\PackingList;
class CreatePackageProcessor
@@ -50,11 +48,6 @@ class CreatePackageProcessor
if($replica) {
$modificationValue = 1;
if($replica->owner->owner instanceof Order){
$modificationValue = in_array( $replica->owner->owner->companyModule->id, WarehouseReferences::REPLICA_WHITE_LIST) ? 0 : 1;
}
$packageObject = new PackageObject($object->getType(), $object->getDescription(), $object->getWidth() + $modificationValue, $object->getHeight() + $modificationValue, $object->getLength() + $modificationValue, $object->getWeight(), $object->getQuantity(), $object->getStatus());
$package = $this->createsPackage->execute($packageObject, $replica);
}
@@ -10,10 +10,7 @@ use App\Classes\Modules\PackingLists\Standards\Rules\CanCreatePackingList;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\OrderRoleTypes;
use App\Classes\ValueObjects\Constants\PackingListType;
use App\Classes\ValueObjects\Constants\WarehouseReferences;
use App\Models\Order;
use App\Models\PackingList;
use function PHPUnit\Framework\isInstanceOf;
class CreatePackingListProcessor
{
@@ -54,7 +51,6 @@ class CreatePackingListProcessor
$appointee_id = $packingList->owner_id == 1 ? 2037 : $packingList->owner->orderRoles()->where('role_id', '=', OrderRoleTypes::ORIGIN_FREIGHT_FORWARDER)->first()->appointee->id;
$type = $object->getType() === PackingListType::SHIPPING_PACKING_LIST ? PackingListType::SHIPPING_PACKING_LIST_REPLICA : PackingListType::WAREHOUSE_RECEIVE_LIST_REPLICA;
/** create packing list replica */
$object = new PackingListObject($object->getReference().'_01', $appointee_id, $type, ApprovalStatus::PENDING_SUBMISSION);
$this->createsPackingList->execute($object, $packingList);
@@ -91,6 +91,7 @@ class FetchDeliveryListFromVTPortalProcessor
$deliveryStep->update(['status' => ApprovalStatus::COMPLETED]);
} catch (GuzzleException $exception) {
dd($exception);
continue;
}
@@ -7,15 +7,12 @@ use App\Classes\Modules\Companies\Services\FetchesCompanyModule;
use App\Classes\Modules\Orders\Services\FetchesDataFromVTPortal;
use App\Classes\Modules\Orders\Services\FetchesOrder;
use App\Classes\Modules\PackingLists\DataTransferObjects\ContainerObject;
use App\Classes\Modules\PackingLists\DataTransferObjects\PackageObject;
use App\Classes\Modules\PackingLists\DataTransferObjects\PackingListObject;
use App\Classes\Modules\PackingLists\Services\Containers\FetchesContainer;
use App\Classes\Modules\PackingLists\Services\FetchesPackingList;
use App\Classes\Modules\Schedules\DataTransferObjects\ScheduleObject;
use App\Classes\Modules\Schedules\Services\CreatesSchedule;
use App\Classes\Modules\Steps\DataTransferObjects\StepsObject;
use App\Classes\Modules\Steps\Services\CreatesStep;
use App\Classes\Modules\Transports\DataTransferObjects\TransportObject;
use App\Classes\Modules\Transports\Services\CreatesTransport;
use App\Classes\Modules\Unity\Processors\ActivateContractProcessor;
use App\Classes\Modules\Unity\Processors\AssignContractEntityProcessor;
@@ -24,13 +21,10 @@ use App\Classes\Modules\Unity\Services\CreatesContract;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\ContainerTypes;
use App\Classes\ValueObjects\Constants\OrderRoleTypes;
use App\Classes\ValueObjects\Constants\PackageType;
use App\Classes\ValueObjects\Constants\RoleTypes;
use App\Classes\ValueObjects\Constants\PackingListType;
use App\Classes\ValueObjects\Constants\TransportType;
use App\Models\Order;
use App\Models\PackingList;
use App\Models\Transport;
use Carbon\Carbon;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\DB;
@@ -130,8 +124,9 @@ class FetchLoadedContainersFromVTPortalProcessor
*/
public function execute(?Carbon $start = null, ?Carbon $end = null){
DB::beginTransaction();
try {
$start = $start ? $start : Carbon::today()->subDays(5);
$start = $start ? $start : Carbon::now()->subDays(10);
$startLimit = Carbon::parse('11-08-2021');
@@ -139,162 +134,85 @@ class FetchLoadedContainersFromVTPortalProcessor
$start = $startLimit;
}
$end = $end ? $end : Carbon::today()->addDay();
$end = $end ? $end : Carbon::now();
$filter = '["LoadedTime:$between$%js%\"'.$start->format('Y-m-d').'T00:00:00.000\"$and$%js%\"'.$end->format('Y-m-d').'T00:00:00.000\"\u0000"]';
$containersRequest = $this->fetchesDataFRomVTPortal->clientRequest('http://portal.vtnation.com.my/Services/DataControllerService.asmx/GetPage', 'POST', json_decode('{"controller":"VCustomercontainer","view":"grid1","request":{"PageIndex":-1,"PageSize":10000,"SortExpression":"LoadedTime asc","Filter":'.$filter.'}}'), '');
$containers = $this->fetchesDataFRomVTPortal->getResponseBody($containersRequest);
foreach ($containers->Rows as $container){
$filter = '["ContainerID:=%js%'.$container[12].'"]';
$containerDetailRequest = $this->fetchesDataFRomVTPortal->clientRequest('http://portal.vtnation.com.my/Services/DataControllerService.asmx/GetPage', 'POST', json_decode('{"controller":"ParcelInContainer","view":"grid1","request":{"PageIndex":-1,"PageSize":10000,"SortExpression":null,"Filter":'.$filter.'}}'), '');
$filter = '["ContainerID:=%js%'.$container[11].'"]';
$containerDetailRequest = $this->fetchesDataFRomVTPortal->clientRequest('http://portal.vtnation.com.my/Services/DataControllerService.asmx/GetPage', 'POST', json_decode('{"controller":"VPodetailparcel","view":"grid1","request":{"PageIndex":-1,"PageSize":10000,"SortExpression":"CreatedOn asc","Filter":'.$filter.'}}'), '');
$containerDetail = $this->fetchesDataFRomVTPortal->getResponseBody($containerDetailRequest);
$containerObject = new ContainerObject($container[0], str_replace(' ', '', $container[24]), str_replace(' ', '', $container[16]), ContainerTypes::FORTY_FEET_DRY_CONTAINER, Carbon::parse($container[6]), ApprovalStatus::PENDING_VERIFICATION);
$containerInfo = $container;
$containerObject = new ContainerObject($container[0], str_replace(' ', '', $container[24]), str_replace(' ', '', $container[15]), ContainerTypes::FORTY_FEET_DRY_CONTAINER, Carbon::parse($container[5]), ApprovalStatus::PENDING_VERIFICATION);
try {
$container = $this->fetchesContainer->execute(['reference' => $containerObject->getReference()]);
} catch (ResourceNotFoundException $exception){
$warehouseId = $container[13];
$warehouseId = $container[12];
$originWarehouse = $this->fetchesCompanyModule->execute(['id' => $warehouseId === 11 ? 3 : 4]);
$container = $this->createContainerProcessor->execute($containerObject, $originWarehouse);
}
$eta = Carbon::parse($containerInfo[4]);
$etd = Carbon::parse($eta)->subDays(5);
$delayDate = $containerInfo[7];
$containerStatus = $containerInfo[10];
$unstuffingDate = $containerInfo[8];
$transport = $container->transports()->first();
if(!$transport || $eta !== $transport->eta){
$container->transports()->delete();
$transportObject = new TransportObject(TransportType::SEA, null, null, $etd, null, ApprovalStatus::APPROVED);
/** @var Transport $transport */
$transport = $this->createsTransport->execute($transportObject, $container);
$this->createsSchedule->execute($transport, new ScheduleObject($etd, $eta, ApprovalStatus::APPROVED));
}
if($delayDate){
$delayDate = Carbon::parse($delayDate);
$transport = $container->transports()->first();
if(!$transport->schedules()->where('eta', '=', $delayDate)->first()) {
$etd = $transport->schedules()->where('status', '=', ApprovalStatus::APPROVED)->first()->etd;
$transport->schedules()->update(['status' => ApprovalStatus::EXPIRED]);
$this->createsSchedule->execute($transport, new ScheduleObject($etd, $delayDate, ApprovalStatus::APPROVED));
}
}
if($containerStatus === 'Unstuffing'){
$container->update(['status' => ApprovalStatus::COMPLETED]);
$container->transports()->first()->update(['drop_date' => Carbon::parse($unstuffingDate)->subDay(), 'status' => ApprovalStatus::COMPLETED]);
/** @var PackingList $packingList */
foreach($container->packingLists as $packingList){
if($packingList->status === ApprovalStatus::PENDING_VERIFICATION){
$packingList->status = ApprovalStatus::APPROVED;
$packingList->save();
}
}
}
foreach($containerDetail->Rows as $packingList){
$marking = preg_split('(-|\(|\)|\/)', str_replace("/YW","", $packingList[39]));
$marking = explode('/', explode('CIEF/', $packingList[13])[1]);
$orderNumber = $marking[array_key_last($marking)];
if(!$packingList[11]){
if(!array_key_exists(1, $marking)){
continue;
}
$allow_contract = true;
$orderNumber = $marking[1];
try {
$warehousePackingList = $this->fetchesPackingList->execute(['reference' => $packingList[3]]);
if(!$warehousePackingList->owner instanceof Order) throw new ResourceNotFoundException;
$order = $warehousePackingList->owner;
} catch (ResourceNotFoundException $exception) {
try {
$order = $this->fetchesOrder->execute(['reference' => $orderNumber]);
} catch (ResourceNotFoundException $exception) {
try {
$order = $this->fetchesOrder->execute(['reference' => substr($orderNumber, -9)]);
} catch (ResourceNotFoundException $exception) {
$order = $this->fetchesCompanyModule->execute(['id' => 1]);
$allow_contract = false;
}
}
if(!$packingList[22]){
continue;
}
$packingListReference = $packingList[3];
$package = $packingList;
$deliveryDate = $package[1] ? Carbon::parse($package[1]) : null;
try {
$packingList = $this->fetchesPackingList->execute(['reference' => $packingListReference, 'type' => PackingListType::SHIPPING_PACKING_LIST]);
/** @var Order $order */
$order = $this->fetchesOrder->execute(['reference' => $orderNumber]);
} catch (ResourceNotFoundException $exception){
if ($allow_contract) {
$appointee_id = $order->orderRoles()->where('role_id', '=', OrderRoleTypes::ORIGIN_FREIGHT_FORWARDER)->first()->appointee->id;
// $contract = $this->unityCreateContract->execute();
// $contractReference = $contract->hash_id;
// $contractObligations = $contract->contract_obligation_list;
//
// $this->unityActivateContract->execute($contractReference);
//
// $supervisorHashId = $order->orderRoles()->where('role_id', '=', OrderRoleTypes::SUPERVISOR)->first()->appointee->unity_hash_id;
//
// $supervisorContractEntity = $this->unityCreateContractEntity->execute($contractReference, $supervisorHashId);
// $order->orderRoles()->where('role_id', '=', OrderRoleTypes::SUPERVISOR)->first()->update(['entity_hash_id' => $supervisorContractEntity->hash_id, 'entity_signature' => $supervisorContractEntity->entity_signature_hash_id]);
//
// $importerContractEntity = $this->unityCreateContractEntity->execute($contractReference, $order->orderRoles()->where('role_id', '=', OrderRoleTypes::IMPORTER)->first()->appointee->unity_hash_id);
// $order->orderRoles()->where('role_id', '=', OrderRoleTypes::IMPORTER)->first()->update(['entity_hash_id' => $importerContractEntity->hash_id, 'entity_signature' => $importerContractEntity->entity_signature_hash_id]);
//
// $this->unityAssignContractEntity->execute($supervisorContractEntity->hash_id, $contractObligations);
} else {
$appointee_id = 2037;
}
continue;
}
$packingListObject = new PackingListObject($packingListReference, $appointee_id, PackingListType::SHIPPING_PACKING_LIST, ApprovalStatus::SUSPENDED, null);
$packingListReference = $packingList[16];
try{
$this->fetchesPackingList->execute(['reference' => $packingListReference]);
} catch (ResourceNotFoundException $exception){
$contract = $this->unityCreateContract->execute();
$contractReference = $contract->hash_id;
$contractObligations = $contract->contract_obligation_list;
$this->unityActivateContract->execute($contractReference);
$supervisorHashId = $order->orderRoles()->where('role_id', '=', OrderRoleTypes::SUPERVISOR)->first()->appointee->unity_hash_id;
$supervisorContractEntity = $this->unityCreateContractEntity->execute($contractReference, $supervisorHashId);
$order->orderRoles()->where('role_id', '=', OrderRoleTypes::SUPERVISOR)->first()->update(['entity_hash_id' => $supervisorContractEntity->hash_id, 'entity_signature' => $supervisorContractEntity->entity_signature_hash_id]);
$importerContractEntity = $this->unityCreateContractEntity->execute($contractReference, $order->orderRoles()->where('role_id', '=', OrderRoleTypes::IMPORTER)->first()->appointee->unity_hash_id);
$order->orderRoles()->where('role_id', '=', OrderRoleTypes::IMPORTER)->first()->update(['entity_hash_id' => $importerContractEntity->hash_id, 'entity_signature' => $importerContractEntity->entity_signature_hash_id]);
$this->unityAssignContractEntity->execute($supervisorContractEntity->hash_id, $contractObligations);
$connection = $order->companyModule->connections()->first();
$marking = $connection->invitee_reference;
$packingListObject = new PackingListObject($packingListReference, $order->orderRoles()->where('role_id', '=', OrderRoleTypes::ORIGIN_FREIGHT_FORWARDER)->first()->appointee->id, PackingListType::SHIPPING_PACKING_LIST, ApprovalStatus::SUSPENDED, $contractReference);
/** @var PackingList $packingList */
$packingList = $this->createPackingListProcessor->execute($packingListObject, $order);
}
$container->packingLists()->attach($packingList);
$container->packingLists()->detach($packingList);
$container->packingLists()->attach($packingList);
$packingList->packages()->delete();
$replica = $packingList->packingLists()->where('type', PackingListType::SHIPPING_PACKING_LIST_REPLICA)->first();
if($replica) $replica->packages()->delete();
$packageObject = new PackageObject(PackageType::CARTON, $package[8], $package[21], $package[22], $package[20], 0, $package[11], ApprovalStatus::APPROVED);
$this->createPackageProcessor->execute($packageObject, $packingList);
if($containerStatus === 'Unstuffing'){
$packingList->transports()->delete();
if($deliveryDate) {
// && !$packingList->transports()->exists()
$packingList->status = ApprovalStatus::COMPLETED;
$packingList->save();
$transportObject = new TransportObject(TransportType::LAND, null, null, $deliveryDate, $deliveryDate, ApprovalStatus::APPROVED);
/** @var Transport $transport */
$transport = $this->createsTransport->execute($transportObject, $packingList);
$this->createsSchedule->execute($transport, new ScheduleObject($deliveryDate, $deliveryDate, ApprovalStatus::APPROVED));
foreach($contractObligations as $obligation) {
$stepObject = new StepsObject($order->orderRoles()->where('role_id', '=', OrderRoleTypes::SUPERVISOR)->first()->appointee->id, $obligation->reference, $obligation->sequence, $obligation->hash_id);
$this->createsStep->execute($packingList, $stepObject);
}
}
}
@@ -304,6 +222,8 @@ class FetchLoadedContainersFromVTPortalProcessor
Log::error($exception);
}
DB::commit();
return [];
}
@@ -36,7 +36,6 @@ use App\Models\Transport;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
class FetchOrderListsFromYdPortalProcessor
{
@@ -132,12 +131,11 @@ class FetchOrderListsFromYdPortalProcessor
* @param Carbon|null $start
* @param Carbon|null $end
* @return void
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function execute(?Carbon $start = null, ?Carbon $end = null)
{
try {
$start = $start ? $start : Carbon::today()->subMonths(1);
$start = $start ? $start : Carbon::now()->subMonths(2);
$startLimit = Carbon::parse('01-12-2021');
@@ -145,7 +143,7 @@ class FetchOrderListsFromYdPortalProcessor
$start = $startLimit;
}
$end = $end ? $end : Carbon::today()->addDay();
$end = $end ? $end : Carbon::now();
$orderRequest = $this->fetchesDataFRomYDPortal->clientRequest('http://www.yd-wl.com/api/GetOrderList.ashx', 'GET', [
'begintime' => $start->timestamp,
@@ -170,10 +168,6 @@ class FetchOrderListsFromYdPortalProcessor
$rows = $this->fetchesDataFRomYDPortal->getResponseBody($trackingRequest);
if(!$rows){
continue;
}
foreach (array_reverse($rows->data) as $trackingRow) {
if ($trackingRow->tracking === '货物已送达仓库准备入库中') {
$receiveDate = Carbon::parse($trackingRow->trackingtime);
@@ -187,66 +181,25 @@ class FetchOrderListsFromYdPortalProcessor
$eta = Carbon::parse($tracking[2]);
}
$rescheduleETD = strpos($trackingRow->remark, '') || strpos($trackingRow->remark, '到港');
$rescheduleETA = strpos($trackingRow->remark, '到港');
if (($rescheduleETD !== false || $rescheduleETA !== false) && strpos($trackingRow->tracking, '货物装柜完成。') === false) {
preg_match_all('/([0-9]+.{3})/', $trackingRow->remark, $matches);
$dates = collect();
foreach($matches[0] as $date){
try {
$dates->push(Carbon::parse(str_replace('.', '/', $date).Carbon::now()->format('Y')));
} catch (\Exception $exception) {
continue;
}
}
$rescheduleDate = $dates->sortDesc()->first();
if(!$delayDate || $rescheduleDate > $delayDate){
/** @var Carbon $delayDate */
$delayDate = $rescheduleDate;
if($rescheduleETA === false && $delayDate) {
$delayDate = $delayDate->addDays('5');
}
}
if (strpos($trackingRow->tracking, '预计船时间为') !== false) {
$tracking = explode('预计船时间为', $trackingRow->tracking);
$delayDate = Carbon::parse(explode('日', $tracking[1])[0]);
}
if ($trackingRow->tracking === '到港') {
$delayDate = Carbon::parse($trackingRow->trackingtime);
}
if ($trackingRow->tracking === '已开船') {
$delayDate = Carbon::parse($trackingRow->trackingtime)->addDays('5');
if (strpos($trackingRow->tracking, '预计开船为') !== false) {
$tracking = explode('预计开船为', $trackingRow->tracking);
$delayDate = Carbon::parse(explode('日', $tracking[1])[0]);
}
if ($trackingRow->tracking === '货物已进目的港仓库') {
$unstuffingDate = Carbon::parse($trackingRow->trackingtime);
}
if (Str::contains($trackingRow->tracking, ['派送中', '签收完成', ' 第三方提货', '货物已派送完成'])) {
if ($trackingRow->tracking === '货物已派送完成') {
$deliveryDate = Carbon::parse($trackingRow->trackingtime);
}
}
$client = new \GuzzleHttp\Client(['cookies' => true, 'headers' => ['Cookie' => 'utc_offset=480']]);
$request = $client->request('get', 'https://main.universe.com.my/Tracking/User/Paging?sEcho=1&sTrackingNo='.$row->expressno.'&sOrgId=sti');
$deliveryTracking = json_decode($request->getBody()->getContents());
foreach (array_reverse($deliveryTracking->aaData) as $trackingRow) {
$trackingDate = Carbon::createFromFormat('d/m/y H:i', $trackingRow->LocalDateTime);
if (Str::contains($trackingRow->PublicDescription, ['accepted/picked'])){
$unstuffingDate = $trackingDate;
}
if (Str::contains($trackingRow->PublicDescription, ['delivered'])) {
$deliveryDate = $trackingDate;
}
}
$customerno = preg_split('(-|\(|\)|\/)', $row->customerno);
$orderNumber = $customerno[array_key_last($customerno)];
@@ -264,6 +217,8 @@ class FetchOrderListsFromYdPortalProcessor
}
DB::beginTransaction();
$packingListReference = $row->expressno;
try{
@@ -333,13 +288,6 @@ class FetchOrderListsFromYdPortalProcessor
$this->createPackageProcessor->execute($packageObject, $packingList);
}
if(!count($row->deliverysize)){
$measurement = round(((float) $row->volume / (float) $row->goodcount) ** (1/3) * 100, 2);
$packageObject = new PackageObject(PackageType::CARTON, $row->goodname, (float) $measurement, (float) $measurement, (float) $measurement, 0, (float) $row->goodcount, ApprovalStatus::APPROVED);
$this->createPackageProcessor->execute($packageObject, $warehouseReceiveList);
$this->createPackageProcessor->execute($packageObject, $packingList);
}
$weightCbm = (float) $row->weight / 500;
$overWeightCbm = $weightCbm - $packingList->packages()->sum(DB::raw('(width/100) * (height/100) * (length/100) * quantity'));
@@ -351,7 +299,7 @@ class FetchOrderListsFromYdPortalProcessor
if($order instanceof Order){
$marking = $order->companyModule->inviters()->withPivot('invitee_reference')->first()->pivot->invitee_reference;
if(!in_array($marking, ['2192KAA', '2353GFE', '6866DTR', '153DSR', '1291NSC', '8288MIB', '1152AAT', '962LOW', '3992WHE', '1290CSW', '9493TYS', '3397GSH'])){
if(!in_array($marking, ['2192KAA', '2353GFE', '6866DTR', '153DSR', '1291NSC', '8288MIB'])){
$this->fetchesDataFRomYDPortal->clientRequest('http://www.yd-wl.com/api/confirmsendorder.ashx', 'GET', [
'expressno' => $row->expressno
]);
@@ -362,8 +310,7 @@ class FetchOrderListsFromYdPortalProcessor
if($containerReference) {
try {
$container = $this->fetchesContainer->execute(['reference' => $containerReference]);
$container->packingLists()->detach($packingList);
$container->packingLists()->attach($packingList);
$container->packingLists()->syncWithoutDetaching([$packingList->id]);
} catch (ResourceNotFoundException $exception){
if (!$allow_contract) {
@@ -379,8 +326,8 @@ class FetchOrderListsFromYdPortalProcessor
/** @var Container $container */
$container = $this->createContainerProcessor->execute($containerObject, $originWarehouse);
$container->packingLists()->detach($packingList);
$container->packingLists()->attach($packingList);
$container->packingLists()->detach($packingList);
$container->packingLists()->attach($packingList);
$transport = $container->transports()->first();
@@ -396,7 +343,7 @@ class FetchOrderListsFromYdPortalProcessor
$transport = $container->transports()->first();
if(!$transport->schedules()->whereDate('eta', '>=', $delayDate)->first()) {
if(!$transport->schedules()->where('eta', '=', $delayDate)->first()) {
$etd = $transport->schedules()->where('status', '=', ApprovalStatus::APPROVED)->first()->etd;
$transport->schedules()->update(['status' => ApprovalStatus::EXPIRED]);
$this->createsSchedule->execute($transport, new ScheduleObject($etd, $delayDate, ApprovalStatus::APPROVED));
@@ -416,19 +363,21 @@ class FetchOrderListsFromYdPortalProcessor
$packingList->save();
}
if ($allow_contract) {
$signature = $packingList->owner->orderRoles()->where('role_id', '=', OrderRoleTypes::SUPERVISOR)->first()->appointee->entity_sigiture;
foreach($packingList->steps()->where('reference', '!=', 'DELIVERY')->get() as $step){
$this->updatesContractObligations->execute($signature, $step->obligation_hash_id);
$step->update(['status' => ApprovalStatus::COMPLETED]);
}
$signature = $packingList->owner->orderRoles()->where('role_id', '=', OrderRoleTypes::SUPERVISOR)->first()->appointee->entity_sigiture;
foreach($packingList->steps()->where('reference', '!=', 'DELIVERY')->get() as $step){
$this->updatesContractObligations->execute($signature, $step->obligation_hash_id);
$step->update(['status' => ApprovalStatus::COMPLETED]);
}
}
}
}
if($deliveryDate && !$packingList->transports()->exists()){
if($deliveryDate){
if($packingList->transports){
continue;
}
$packingList->status = ApprovalStatus::COMPLETED;
$packingList->save();
@@ -438,16 +387,13 @@ class FetchOrderListsFromYdPortalProcessor
$transport = $this->createsTransport->execute($transportObject, $packingList);
$this->createsSchedule->execute($transport, new ScheduleObject($deliveryDate, $deliveryDate, ApprovalStatus::APPROVED));
if ($allow_contract) {
$deliveryStep = $packingList->steps()->where('reference', '=', 'LAST_MILE_DELIVERY')->first();
$signature = $packingList->owner->orderRoles()->where('role_id', '=', OrderRoleTypes::SUPERVISOR)->first()->appointee->entity_sigiture;
$this->updatesContractObligations->execute($signature, $deliveryStep->obligation_hash_id);
$deliveryStep->update(['status' => ApprovalStatus::COMPLETED]);
}
$deliveryStep = $packingList->steps()->where('reference', '=', 'LAST_MILE_DELIVERY')->first();
$signature = $packingList->owner->orderRoles()->where('role_id', '=', OrderRoleTypes::SUPERVISOR)->first()->appointee->entity_sigiture;
$this->updatesContractObligations->execute($signature, $deliveryStep->obligation_hash_id);
$deliveryStep->update(['status' => ApprovalStatus::COMPLETED]);
}
DB::commit();
echo 'successful';
}
@@ -46,28 +46,42 @@ class FetchPackingListFromVTPortalProcessor
*/
public function execute(){
$packingLists = PackingList::where('type', '=', PackingListType::SHIPPING_PACKING_LIST)->where('reference', 'not like', '%PO%')->whereIn('claimant_id', [2])->whereIn('status', [ApprovalStatus::PENDING_VERIFICATION, ApprovalStatus::SUSPENDED])->whereDoesntHave('containers', function($query){
$packingLists = PackingList::where('type', '=', PackingListType::SHIPPING_PACKING_LIST)->whereIn('status', [ApprovalStatus::PENDING_VERIFICATION, ApprovalStatus::SUSPENDED])->whereDoesntHave('containers', function($query){
$query->where('status', '=', ApprovalStatus::COMPLETED);
})->limit(10)->get();
})->get();
foreach($packingLists as $packingList){
try {
DB::beginTransaction();
$filter = '["PoID:=%js%'.$packingList->reference.'"]';
$filter = '["PoNumber:=%js%\"'.$packingList->reference.'\"\u0000"]';
$shippingPackingListsRequest = $this->fetchesDataFRomVTPortal->clientRequest('http://portal.vtnation.com.my/Services/DataControllerService.asmx/GetPage', 'POST', json_decode('{"controller":"Po","view":"grid1","request":{"PageIndex":-1,"PageSize":1000,"Filter":'.$filter.'}}'), '');
$shippingPackingListsRequest = $this->fetchesDataFRomVTPortal->clientRequest('http://portal.vtnation.com.my/Services/DataControllerService.asmx/GetPage', 'POST', json_decode('{"controller":"VPodetailparcel","view":"grid1","request":{"PageIndex":-1,"PageSize":10000,"SortExpression":"CreatedOn asc","Filter":'.$filter.'}}'), '');
$shippingPackingLists = $this->fetchesDataFRomVTPortal->getResponseBody($shippingPackingListsRequest);
if(count($shippingPackingLists->Rows)) {
} else {
dump($packingList->reference);
$packingList->packages()->delete();
$replica = $packingList->packingLists()->where('type', PackingListType::SHIPPING_PACKING_LIST_REPLICA)->first();
if($replica) $replica->packages()->delete();
foreach($shippingPackingLists->Rows as $shippingPackingList){
if(!$shippingPackingList[22]) {
continue;
}
$packageObject = new PackageObject(PackageType::CARTON, $shippingPackingList[19], $shippingPackingList[31], $shippingPackingList[30], $shippingPackingList[29], 0, $shippingPackingList[22], ApprovalStatus::APPROVED);
$this->createPackageProcessor->execute($packageObject, $packingList);
}
}
DB::commit();
} catch (GuzzleException $exception) {
dd($exception);
Log::error($exception);
continue;
}
@@ -116,7 +116,7 @@ class FetchWarehouseReceiveListFromVTPortalProcessor
try {
$start = $start ? $start : Carbon::today()->subDays(5);
$start = $start ? $start : Carbon::now()->subMonth();
$startLimit = Carbon::parse('11-08-2021');
@@ -124,40 +124,82 @@ class FetchWarehouseReceiveListFromVTPortalProcessor
$start = $startLimit;
}
$end = $end ? $end : Carbon::today()->addDay();
$end = $end ? $end : Carbon::now();
$filter = '["ParcelDate:$between$%js%\"'.$start->format('Y-m-d').'T00:00:00.000\"$and$%js%\"'.$end->format('Y-m-d').'T00:00:00.000\"\u0000"]';
$warehouseListRequest = $this->fetchesDataFRomVTPortal->clientRequest('http://portal.vtnation.com.my/Services/DataControllerService.asmx/GetPage', 'POST', json_decode('{"controller":"Parcel","view":"grid1","request":{"PageIndex":-1,"PageSize":10000,"SortExpression":"ParcelDate asc","Filter":'.$filter.'}}'), '');
$warehouseListRequest = $this->fetchesDataFRomVTPortal->clientRequest('http://portal.vtnation.com.my/Services/DataControllerService.asmx/GetPage', 'POST', json_decode('{"controller":"WarehouseList","view":"grid1","request":{"PageIndex":-1,"PageSize":10000,"SortExpression":"ParcelDate asc","Filter":'.$filter.'}}'), '');
$response = $this->fetchesDataFRomVTPortal->getResponseBody($warehouseListRequest);
foreach ($response->Rows as $parcel){
$allow_contract = true;
$marking = preg_split('(-|\(|\)|\/)', str_replace("/YW","", $parcel[11]));
$orderNumber = $marking[array_key_last($marking)];
$quantity = $parcel[16];
if(!$quantity){
$marking = explode('/', explode('CIEF/', $parcel[5])[1]);
if(!array_key_exists(1, $marking)){
continue;
}
try {
$order = $this->fetchesOrder->execute(['reference' => $orderNumber]);
$appointee_id = $order->orderRoles()->where('role_id', '=', OrderRoleTypes::ORIGIN_FREIGHT_FORWARDER)->first()->appointee->id;
} catch (ResourceNotFoundException $exception) {
$allow_contract = false;
$order = $this->fetchesCompanyModule->execute(['id' => 1]);
$appointee_id = 2037;
$orderNumber = $marking[1];
if(!$parcel[9]){
continue;
}
$packingListReference = $parcel[0];
// $measurement = round(($parcel[10]/$quantity) ** (1/3) * 100, 2);
$description = $parcel[13];
$tracking = $parcel[37];
try {
$order = $this->fetchesOrder->execute(['reference' => $orderNumber]);
} catch (ResourceNotFoundException $exception) {
$oldOrder = OldOrders::where('marking', '=', $orderNumber)->first();
if(!$oldOrder){
continue;
}
$customerMarking = str_replace('/', '', str_replace(' ', '', explode('CIEF/', $oldOrder->company->marking)[1]));
$companyModule = CompanyModule::whereHas('inviters', function($query) use ($customerMarking) {
return $query->where('invitee_reference', '=', $customerMarking);
})->first();
if(!$companyModule){
log::error('unknown customer: '.$customerMarking);
continue;
}
if(!$oldOrder->address) {
continue;
}
/** @var Address $address */
$address = $this->createAddressFromOldAddressProcessor->execute($oldOrder->address, $companyModule);
if(!$address){
continue;
}
$warehouseId = $parcel[0];
$originWarehouse = $this->fetchesCompanyModule->execute(['id' => $warehouseId === 11 ? 3 : 4]);
$order = $this->createOrderProcessor->execute($companyModule->company, $originWarehouse, $address, $orderNumber);
$order->created_at = Carbon::parse($parcel[1]);
$order->save();
}
$packingListReference = $parcel[17];
$quantity = $parcel[9];
$measurement = round(($parcel[10]/$quantity) ** (1/3) * 100, 2);
$description = $parcel[7];
$tracking = $parcel[6];
$receiveDate = $parcel[1];
$packingListObject = new PackingListObject($packingListReference, $appointee_id, PackingListType::WAREHOUSE_RECEIVE_LIST, $allow_contract ? ApprovalStatus::APPROVED : ApprovalStatus::REJECTED);
$packingListObject = new PackingListObject($packingListReference, $order->orderRoles()->where('role_id', '=', OrderRoleTypes::ORIGIN_WAREHOUSE)->first()->appointee->id, PackingListType::WAREHOUSE_RECEIVE_LIST, ApprovalStatus::APPROVED);
/** @var PackingList $packingList */
$packingList = $order->packingLists()->where('reference', '=', $packingListReference)->first();
@@ -180,7 +222,7 @@ class FetchWarehouseReceiveListFromVTPortalProcessor
$packingList->packages()->delete();
if($replica) $replica->packages()->delete();
$packageObject = new PackageObject(PackageType::CARTON, $description, $parcel[23], $parcel[22], $parcel[21], 0, $quantity, ApprovalStatus::APPROVED);
$packageObject = new PackageObject(PackageType::CARTON, $description, $measurement, $measurement, $measurement, 0, $quantity, ApprovalStatus::APPROVED);
$this->createPackageProcessor->execute($packageObject, $packingList);
}
} catch (\Exception $exception){
@@ -12,12 +12,14 @@ class UpdatesPackingListOwner extends AbstractUpdateRelationshipRecord
/**
* @param PackingList $model
* @param Packable $packable
* @param int $status
* @return \Illuminate\Database\Eloquent\Model
* @throws \App\Classes\Exceptions\MalformedRequestException
*/
public function execute(PackingList $model, Packable $packable) {
$model->status = ApprovalStatus::APPROVED;
return $this->handler($packable->packingLists(), $model);
}
@@ -4,16 +4,18 @@ namespace App\Classes\Modules\Remarks\ControllersLogic;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Remarks\Services\CreatesRemark;
use App\Classes\Modules\Remarks\Standards\Rules\CanCreateRemark;
use App\Classes\Modules\Remarks\DataTransferObjects\RemarkObject;
use App\Classes\Modules\Remarks\Processors\CreateRemarkProcessor;
use App\Classes\Modules\Accounts\Services\FetchesUser;
use App\Http\Resources\RemarkResource;
use ErrorException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use App\Classes\Exceptions\MalformedRequestException;
use App\Http\Resources\RemarkResource;
class CreateRemarkLogic extends AbstractControllerLogic
{
/**
* @return array
*/
@@ -24,16 +26,25 @@ class CreateRemarkLogic extends AbstractControllerLogic
];
}
/** @var CreateRemarkProcessor */
private $createRemarkProcessor;
/** @var CanCreateRemark */
private $canCreateRemark;
/** @var CreatesRemark */
private $createsRemark;
/** @var FetchesUser */
private $fetchesUser;
/**
* CreateRemarkLogic constructor.
* @param CreateRemarkProcessor $createRemarkProcessor
* @param CanCreateRemark $canCreateRemark
* @param CreatesRemark $createsRemark
*/
public function __construct(CreateRemarkProcessor $createRemarkProcessor)
public function __construct(CanCreateRemark $canCreateRemark, CreatesRemark $createsRemark, FetchesUser $fetchesUser)
{
$this->createRemarkProcessor = $createRemarkProcessor;
$this->canCreateRemark = $canCreateRemark;
$this->createsRemark = $createsRemark;
$this->fetchesUser = $fetchesUser;
}
/**
@@ -45,18 +56,15 @@ class CreateRemarkLogic extends AbstractControllerLogic
*/
public function logic(Request $request) : JsonResponse
{
$classs = '\\App\\Models\\' . Str::studly($request->input('model_type'));
if (!class_exists($classs)) {
throw new MalformedRequestException('Unable to process this entity');
}
$remarkOwner = $classs::find($request->route('id'));
$object = new RemarkObject($request->input('content'), $request->input('commenter_id'));
$remarkObject = new RemarkObject($request->input('content'), auth()->user()->id);
$this->canCreateRemark->passes($object);
$remmark = $this->createRemarkProcessor->execute($remarkOwner, $remarkObject);
$query = $this->createsRemark->execute($this->fetchesUser->execute(['id' => $request->input('commenter_id')]), $object);
return $this->resourceResponse(new RemarkResource($query));
return $this->resourceResponse(new RemarkResource($remmark));
}
}
@@ -1,121 +0,0 @@
<?php
namespace App\Classes\Modules\Segments\ControllersLogic;
use App\Classes\Exceptions\ResourceNotFoundException;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Segments\DataTransferObjects\ConstantObject;
use App\Classes\Modules\Segments\Services\UpdatesBasePriceConstantByDates;
use App\Classes\Modules\Segments\Services\CreatesConstant;
use App\Classes\Modules\Segments\Services\FetchesConstant;
use App\Classes\Modules\Segments\Services\FetchesSegment;
use App\Classes\Modules\Segments\Standards\Rules\CanCreateConstant;
use App\Classes\Modules\Segments\Standards\Rules\CanUpdateConstant;
use App\Classes\Modules\Segments\Services\UpdatesConstant;
use App\Classes\ValueObjects\Constants\SegmentConstants;
use App\Http\Resources\ConstantResource;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class CreateBasePriceLogic extends AbstractControllerLogic
{
/**
* @return array
*/
protected function notification():array {
return [
'title' => 'Create Base Price',
'message' => 'You have successfully created a Base Price'
];
}
/** @var CanUpdateConstant */
private $canUpdateConstant;
/** @var UpdatesConstant */
private $updatesConstant;
/** @var FetchesSegment */
private $fetchesSegment;
/** @var FetchesConstant */
private $fetchesConstant;
/** @var CanCreateConstant */
private $canCreateConstant;
/** @var CreatesConstant */
private $createsConstant;
/** @var UpdatesBasePriceConstantByDates */
private $updatesBasePriceConstantByDates;
/**
* UpdateConstantLogic constructor.
* @param CanUpdateConstant $canUpdateConstant
* @param UpdatesConstant $updatesConstant
* @param FetchesSegment $fetchesSegment
* @param FetchesConstant $fetchesConstant
* @param CanCreateConstant $canCreateConstant
* @param CreatesConstant $createsConstant
* @param UpdatesBasePriceConstantByDates $updatesBasePriceConstantByDates
*/
public function __construct(
CanUpdateConstant $canUpdateConstant,
UpdatesConstant $updatesConstant,
FetchesSegment $fetchesSegment,
FetchesConstant $fetchesConstant,
CanCreateConstant $canCreateConstant,
CreatesConstant $createsConstant,
UpdatesBasePriceConstantByDates $updatesBasePriceConstantByDates
)
{
$this->canUpdateConstant = $canUpdateConstant;
$this->updatesConstant = $updatesConstant;
$this->fetchesSegment = $fetchesSegment;
$this->fetchesConstant = $fetchesConstant;
$this->canCreateConstant = $canCreateConstant;
$this->createsConstant = $createsConstant;
$this->updatesBasePriceConstantByDates = $updatesBasePriceConstantByDates;
}
/**
* @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
{
$segment = $this->fetchesSegment->execute(['id' => $request->route('id')]);
try {
$constant = $this->fetchesConstant->execute(['segment_id' => $segment->id, 'reference' => SegmentConstants::BASE_PRICE]);
} catch (ResourceNotFoundException $exception){
$constantObject = [];
$object = new ConstantObject(
SegmentConstants::BASE_PRICE,
$constantObject
);
$constant = $this->createsConstant->execute($segment, $object);
}
$constantValue = $this->updatesBasePriceConstantByDates->execute($constant->value, $request->input('dateFrom'), $request->input('dateTo'), $request->input('rate'));
$object = new ConstantObject(SegmentConstants::BASE_PRICE, $constantValue);
$this->canUpdateConstant->passes($object);
$constant = $this->updatesConstant->execute($constant, $object);
return $this->resourceResponse(new ConstantResource($constant));
}
}
@@ -1,68 +0,0 @@
<?php
namespace App\Classes\Modules\Segments\ControllersLogic;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Segments\Services\FetchesConstant;
use App\Classes\ValueObjects\Constants\SegmentConstants;
use App\Http\Resources\ConstantResource;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Carbon\CarbonPeriod;
class FetchBasePriceLogic extends AbstractControllerLogic
{
/**
* @return array
*/
protected function notification():array {
return [
'title' => 'Retrieved Base Price',
'message' => 'You have successfully retrieved the Base Price'
];
}
/** @var FetchesConstant */
private $fetchesConstant;
/**
* FetchConstantLogic constructor.
* @param FetchesConstant $fetchesConstant
*/
public function __construct(FetchesConstant $fetchesConstant)
{
$this->fetchesConstant = $fetchesConstant;
}
/**
* @param Request $request
* @return JsonResponse
*/
public function logic(Request $request) : JsonResponse
{
$constant = $this->fetchesConstant->execute(['segment_id' => $request->route('id'), 'reference' => SegmentConstants::BASE_PRICE]);
$constantObject = (array) $constant->value;
if ($request->input('dateFrom') !== null && $request->input('dateTo') !== null) {
$period = CarbonPeriod::create($request->input('dateFrom'), $request->input('dateTo'));
$returnObject = [];
foreach ($period as $date) {
array_key_exists($date->format('Y-m-d'), $constantObject) === true ? $returnObject[$date->format('Y-m-d')] = $constantObject[$date->format('Y-m-d')] : '';
}
$constant->value = json_encode($returnObject);
}
return $this->resourceResponse(new ConstantResource($constant));
}
}
@@ -1,178 +0,0 @@
<?php
namespace App\Classes\Modules\Segments\ControllersLogic;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Segments\Services\ListsSegments;
use App\Http\Resources\AirShipmentItemPriceResource;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class ListAirShipmentPriceLogic extends AbstractControllerLogic
{
/**
* @return array
*/
protected function notification():array {
return [
'title' => 'Retrieved Air Shipment Price List',
'message' => 'You have successfully retrieved a list of Air Shipment Price'
];
}
/** @var ListsSegments */
private $listsSegments;
/**
* ListSegmentLogic constructor.
* @param ListsSegments $listsSegments
*/
public function __construct(ListsSegments $listsSegments)
{
$this->listsSegments = $listsSegments;
}
/**
* @param Request $request
* @return JsonResponse
* @throws \App\Classes\Exceptions\MalformedRequestException
*/
public function logic(Request $request) : JsonResponse
{
// $query = $this->listsSegments->execute($this->listsSegments->deserializeFilters($request->input('filters')));
// category - Dimension / perKg
$price = array(
[
'details' => json_encode([
'name' => 'Sound system speakers - MINI',
'pricePerKg' => '',
'pricePerPcs' => '',
'isProhibited' => '',
'hasGram' => '',
'hasDimensionCharges' => '',
'tax' => '50',
])
],
[
'details' => json_encode([
'name' => 'Sound system speakers - SMALL',
'pricePerKg' => '',
'pricePerPcs' => '',
'isProhibited' => '',
'hasGram' => '',
'hasDimensionCharges' => '',
'tax' => '200',
])
],
[
'details' => json_encode([
'name' => 'Sound system speakers - LARGE',
'pricePerKg' => '',
'pricePerPcs' => '',
'isProhibited' => '',
'hasGram' => '',
'hasDimensionCharges' => '',
'tax' => '400',
])
],
[
'details' => json_encode([
'name' => 'Washing Machine - Dimension',
'pricePerKg' => '',
'pricePerPcs' => '',
'isProhibited' => '',
'hasGram' => '',
'hasDimensionCharges' => 'true',
'tax' => '',
])
],
[
'details' => json_encode([
'name' => 'Oven, Balnder - perPcs',
'pricePerKg' => '',
'pricePerPcs' => '20',
'isProhibited' => '',
'hasGram' => '',
'hasDimensionCharges' => '',
'tax' => '',
])
],
[
'details' => json_encode([
'name' => 'Perfume - perKg',
'pricePerKg' => '33',
'pricePerPcs' => '',
'isProhibited' => '',
'hasGram' => '',
'hasDimensionCharges' => '',
'tax' => '',
])
],
[
'details' => json_encode([
'name' => 'Gold - Prohibited',
'pricePerKg' => '',
'pricePerPcs' => '',
'isProhibited' => 'true',
'hasGram' => '',
'hasDimensionCharges' => '',
'tax' => '',
])
],
[
'details' => json_encode([
'name' => 'Food - hasGram',
'pricePerKg' => '',
'pricePerPcs' => '',
'isProhibited' => '',
'hasGram' => 'true',
'hasDimensionCharges' => '',
'tax' => '',
])
],
[
'details' => json_encode([
'name' => 'TV 30" - 36"',
'pricePerKg' => 28,
'pricePerPcs' => '',
'isProhibited' => '',
'hasGram' => 'true',
'hasDimensionCharges' => "true",
'tax' => 500,
])
],
[
'details' => json_encode([
'name' => 'TV 37" - 42"',
'pricePerKg' => 28,
'pricePerPcs' => '',
'isProhibited' => '',
'hasGram' => 'true',
'hasDimensionCharges' => "true",
'tax' => 1000,
])
],
[
'details' => json_encode([
'name' => 'TV 43"+"',
'pricePerKg' => 28,
'pricePerPcs' => '',
'isProhibited' => '',
'hasGram' => 'true',
'hasDimensionCharges' => "true",
'tax' => 1500,
])
]
);
return $this->collectionResponse(AirShipmentItemPriceResource::collection($price));
}
}
@@ -5,9 +5,7 @@ namespace App\Classes\Modules\Segments\ControllersLogic;
use App\Classes\Exceptions\ResourceNotFoundException;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Segments\DataTransferObjects\ConstantObject;
use App\Classes\Modules\Segments\DataTransferObjects\SegmentObject;
use App\Classes\Modules\Segments\Services\CreatesConstant;
use App\Classes\Modules\Segments\Services\CreatesSegment;
use App\Classes\Modules\Segments\Services\FetchesConstant;
use App\Classes\Modules\Segments\Services\FetchesSegment;
use App\Classes\Modules\Segments\Standards\Rules\CanCreateConstant;
@@ -17,7 +15,6 @@ use App\Http\Resources\ConstantResource;
use App\Models\SegmentConstant;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use App\Classes\Modules\Segments\Services\UpdatesConstantValue;
class UpdateConstantLogic extends AbstractControllerLogic
{
@@ -50,11 +47,6 @@ class UpdateConstantLogic extends AbstractControllerLogic
/** @var CreatesConstant */
private $createsConstant;
/** @var CreatesSegment */
private $createsSegment;
/** @var UpdatesConstantValue */
private $updatesConstantValue;
/**
* UpdateConstantLogic constructor.
@@ -64,19 +56,8 @@ class UpdateConstantLogic extends AbstractControllerLogic
* @param FetchesConstant $fetchesConstant
* @param CanCreateConstant $canCreateConstant
* @param CreatesConstant $createsConstant
* @param UpdatesConstantValueByState $updatesConstantValueByState
* @param CreatesSegment $createsSegment
*/
public function __construct(
CanUpdateConstant $canUpdateConstant,
UpdatesConstant $updatesConstant,
FetchesSegment $fetchesSegment,
FetchesConstant $fetchesConstant,
CanCreateConstant $canCreateConstant,
CreatesConstant $createsConstant,
UpdatesConstantValue $updatesConstantValue,
CreatesSegment $createsSegment
)
public function __construct(CanUpdateConstant $canUpdateConstant, UpdatesConstant $updatesConstant, FetchesSegment $fetchesSegment, FetchesConstant $fetchesConstant, CanCreateConstant $canCreateConstant, CreatesConstant $createsConstant)
{
$this->canUpdateConstant = $canUpdateConstant;
$this->updatesConstant = $updatesConstant;
@@ -84,8 +65,6 @@ class UpdateConstantLogic extends AbstractControllerLogic
$this->fetchesConstant = $fetchesConstant;
$this->canCreateConstant = $canCreateConstant;
$this->createsConstant = $createsConstant;
$this->updatesConstantValue = $updatesConstantValue;
$this->createsSegment = $createsSegment;
}
/**
* @param Request $request
@@ -96,33 +75,28 @@ class UpdateConstantLogic extends AbstractControllerLogic
*/
public function logic(Request $request) : JsonResponse
{
$object = new ConstantObject($request->input('name'), $request->input('reference'), $request->input('detail'));
$segment = $this->fetchesSegment->execute(['id' => $request->route('id')]);
try {
$constant = $this->fetchesConstant->execute(['segment_id' => $segment->id, 'reference' => $request->input('reference')]);
$constantValue = $this->updatesConstantValue->execute($constant->value, $request->input('id'), $request->input('value'));
$object = new ConstantObject($request->input('reference'), $constantValue);
$constant = $this->fetchesConstant->execute(['segment_id' => $segment->id, 'reference' => $object->getReference()]);
$this->canUpdateConstant->passes($object);
/** @var SegmentConstant $constant */
$constant = $this->updatesConstant->execute($constant, $object);
} catch (ResourceNotFoundException $exception){
$constantObject = [];
$constantObject[$request->input('id')] = $request->input('value');
$object = new ConstantObject(
$request->input('reference'),
$constantObject
);
$this->canCreateConstant->passes($object);
/** @var SegmentConstant $constant */
$constant = $this->createsConstant->execute($segment, $object);
}
$constant = $this->updatesConstant->execute($constant, $object);
return $this->resourceResponse(new ConstantResource($constant));
}
@@ -1,131 +0,0 @@
<?php
namespace App\Classes\Modules\Segments\ControllersLogic;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Resources\ConstantResource;
use App\Classes\ValueObjects\Constants\SegmentConstants;
use App\Classes\Modules\Segments\Services\FetchesSegment;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Segments\Services\FetchesConstant;
use App\Classes\Modules\Segments\Services\UpdatesConstant;
use App\Classes\Modules\Segments\Standards\Rules\CanUpdateConstant;
use App\Classes\Modules\Segments\DataTransferObjects\ConstantObject;
use App\Classes\Modules\Segments\Services\AddItemToConstantValueArray;
use App\Classes\Modules\Segments\Services\RemoveItemFromConstantValueArray;
use App\Classes\Exceptions\ResourceNotFoundException;
use App\Classes\Modules\Segments\Services\CreatesConstant;
class UpdateConstantPostcodeLogic extends AbstractControllerLogic
{
/**
* @return array
*/
protected function notification():array {
return [
'title' => 'Updated Segment Constant',
'message' => 'You have successfully updated the Segment Constant'
];
}
/** @var CanUpdateConstant */
private $canUpdateConstant;
/** @var UpdatesConstant */
private $updatesConstant;
/** @var FetchesSegment */
private $fetchesSegment;
/** @var FetchesConstant */
private $fetchesConstant;
/** @var AddItemToConstantValueArray */
private $addItemToConstantValueArray;
/** @var RemoveItemFromConstantValueArray */
private $removeItemFromConstantValueArray;
/** @var CreatesConstant */
private $createsConstant;
/**
* UpdateConstantLogic constructor.
* @param CanUpdateConstant $canUpdateConstant
* @param UpdatesConstant $updatesConstant
* @param FetchesSegment $fetchesSegment
* @param FetchesConstant $fetchesConstant
* @param AddItemToConstantValueArray $addItemToConstantValueArray
* @param CreatesConstant $createsConstant
* @param RemoveItemFromConstantValueArray $removeItemFromConstantValueArray
*/
public function __construct(
CanUpdateConstant $canUpdateConstant,
UpdatesConstant $updatesConstant,
FetchesSegment $fetchesSegment,
FetchesConstant $fetchesConstant,
AddItemToConstantValueArray $addItemToConstantValueArray,
RemoveItemFromConstantValueArray $removeItemFromConstantValueArray,
CreatesConstant $createsConstant
)
{
$this->canUpdateConstant = $canUpdateConstant;
$this->updatesConstant = $updatesConstant;
$this->fetchesSegment = $fetchesSegment;
$this->fetchesConstant = $fetchesConstant;
$this->addItemToConstantValueArray = $addItemToConstantValueArray;
$this->removeItemFromConstantValueArray = $removeItemFromConstantValueArray;
$this->createsConstant = $createsConstant;
}
/**
* @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
{
$segment = $this->fetchesSegment->execute(['id' => $request->route('id')]);
try {
$constant = $this->fetchesConstant->execute(['segment_id' => $segment->id, 'reference' => $request->input('reference')]);
$constantValue = $this->addItemToConstantValueArray->execute($constant->value, $request->input('postcode'));
$object = new ConstantObject($request->input('reference'), $constantValue);
} catch (ResourceNotFoundException $exception){
$constantObject = [$request->input('postcode')];
$object = new ConstantObject(
$request->input('reference'),
$constantObject
);
$constant = $this->createsConstant->execute($segment, $object);
}
try {
// check if postcode exist in the opposite constant, and delete it
$oppositeConstant = $this->fetchesConstant->execute(['segment_id' => $segment->id, 'reference' => $request->input('reference') == SegmentConstants::CENTER_POSTCODE ? SegmentConstants::OUTSTATION_POSTCODE : SegmentConstants::CENTER_POSTCODE]);
$oppositeConstantValue = $this->removeItemFromConstantValueArray->execute($oppositeConstant->value, $request->input('postcode'));
$oppositeObject = new ConstantObject($request->input('reference') == SegmentConstants::CENTER_POSTCODE ? SegmentConstants::OUTSTATION_POSTCODE : SegmentConstants::CENTER_POSTCODE, $oppositeConstantValue);
$this->updatesConstant->execute($oppositeConstant, $oppositeObject);
} catch (ResourceNotFoundException $exception){
// if opposite constant does not exist, do nothing
}
$constant = $this->updatesConstant->execute($constant, $object);
return $this->resourceResponse(new ConstantResource($constant));
}
}
@@ -7,22 +7,34 @@ use App\Classes\General\Interfaces\DataTransferObject;
class ConstantObject implements DataTransferObject
{
/** @var string */
private $name;
/** @var string */
private $reference;
/** @var array */
private $value;
private $detail;
/**
* ConstantObject constructor.
* @param string $name
* @param string $reference
* @param array $value
* @param array $detail
*/
public function __construct(string $reference, array $value)
public function __construct(string $name, string $reference, array $detail)
{
$this->name = $name;
$this->reference = $reference;
$this->value = $value;
$this->detail = $detail;
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
@@ -36,9 +48,9 @@ class ConstantObject implements DataTransferObject
/**
* @return array
*/
public function getValue(): array
public function getDetail(): array
{
return $this->value;
return $this->detail;
}
@@ -1,19 +0,0 @@
<?php
namespace App\Classes\Modules\Segments\Services;
class AddItemToConstantValueArray
{
/**
* @param array $array
* @param $item
* @return array
*/
public function execute($array, $item): array {
$array[] = $item;
sort($array);
return $array;
}
}
@@ -27,11 +27,11 @@ class ConvertsConstantDetailsToResource
public function execute(SegmentConstant $constant){
// if($constant->reference === SegmentConstants::SUPPLIER_CURRENCIES) {
// return property_exists($constant->detail, 'id') ? new CurrencyResource($this->fetchesCurrency->execute(['id' => $constant->detail->id])) : '';
// }
if($constant->reference === SegmentConstants::SUPPLIER_CURRENCIES) {
return property_exists($constant->detail, 'id') ? new CurrencyResource($this->fetchesCurrency->execute(['id' => $constant->detail->id])) : '';
}
return $constant->value;
return $constant->detail;
}
@@ -18,8 +18,9 @@ class CreatesConstant extends AbstractUpdateRelationshipRecord
public function execute(Segment $segment, ConstantObject $object)
{
$model = new SegmentConstant();
$model->name = $object->getName();
$model->reference = $object->getReference();
$model->value = json_encode($object->getValue());
$model->detail = json_encode($object->getDetail());
return $this->handler($segment->constants(), $model);
}
@@ -1,22 +0,0 @@
<?php
namespace App\Classes\Modules\Segments\Services;
class RemoveItemFromConstantValueArray
{
/**
* @param array $array
* @param $item
* @return array
*/
public function execute($array, $item): array {
foreach($array as $key => $value){
if($array[$key] == $item){
unset($array[$key]);
}
}
return array_values($array);
}
}
@@ -1,29 +0,0 @@
<?php
namespace App\Classes\Modules\Segments\Services;
use Carbon\CarbonPeriod;
class UpdatesBasePriceConstantByDates
{
/**
* @param $json
* @param int $status_id
* @param Array $rate
* @return Array
*/
public function execute($json, String $date_from, String $date_to, String $rate) {
$objectArray = (array) $json;
$period = CarbonPeriod::create($date_from, $date_to);
foreach ($period as $date) {
$objectArray[$date->format('Y-m-d')] = $rate;
}
return $objectArray;
}
}
@@ -17,8 +17,9 @@ class UpdatesConstant extends AbstractUpdateRecord
*/
public function execute(SegmentConstant $model, ConstantObject $object)
{
$model->name = $object->getName();
$model->reference = $object->getReference();
$model->value = json_encode($object->getValue());
$model->detail = json_encode($object->getDetail());
return $this->handler($model);
}
@@ -1,23 +0,0 @@
<?php
namespace App\Classes\Modules\Segments\Services;
class UpdatesConstantValue
{
/**
* @param $json
* @param int $state_id
* @param array $rate
* @return array
*/
public function execute($json, int $state_id, Array $rate) {
$objectArray = (array) $json;
$objectArray[$state_id] = $rate;
return $objectArray;
}
}
@@ -15,8 +15,9 @@ class ConstantValidation extends AbstractValidation
protected function data($object): array {
$data = [
'name' => $object->getName(),
'reference' => $object->getReference(),
'value' => $object->getValue()
'detail' => $object->getDetail()
];
return $data;
@@ -27,8 +28,9 @@ class ConstantValidation extends AbstractValidation
*/
protected function rules(): array {
return [
'name' => 'required',
'reference' => 'required',
'value' => 'required'
'detail' => 'required'
];
}
@@ -1,81 +0,0 @@
<?php
namespace App\Classes\Modules\Transactions\ControllersLogic;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Documents\Services\ApprovesDocument;
use App\Classes\Modules\Documents\Services\FetchesDocument;
use App\Classes\Modules\Documents\Services\RejectsDocument;
use App\Classes\Modules\Transactions\Services\FetchesTransaction;
use App\Classes\Modules\Transactions\Services\UpdatesTransactionStatus;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class ApprovePaymentTransactionLogic extends AbstractControllerLogic
{
/**
* ApprovePaymentVerificationLogic constructor.
* @param FetchesTransaction $fetchesTransaction
* @param UpdatesTransactionStatus $updatesTransactionStatus
* @param ApprovesDocument $approvesDocument
* @param RejectsDocument $rejectsDocument
* @param FetchesDocument $fetchesDocument
* @param CreateInvoiceTransactionProcessor $createInvoiceTransactionProcessor
*/
public function __construct(FetchesTransaction $fetchesTransaction, UpdatesTransactionStatus $updatesTransactionStatus, ApprovesDocument $approvesDocument, RejectsDocument $rejectsDocument, FetchesDocument $fetchesDocument)
{
$this->fetchesTransaction = $fetchesTransaction;
$this->updatesTransactionStatus = $updatesTransactionStatus;
$this->approvesDocument = $approvesDocument;
$this->rejectsDocument = $rejectsDocument;
}
/**
* @return array
*/
protected function notification():array {
return [
'title' => 'Payment Status',
'message' => 'You have successfully updated the payment status'
];
}
/** @var FetchesTransaction */
private $fetchesTransaction;
/** @var UpdatesTransactionStatus */
private $updatesTransactionStatus;
/** @var ApprovesDocument */
private $approvesDocument;
/** @var RejectsDocument */
private $rejectsDocument;
/**
* @param Request $request
* @return JsonResponse
* @throws \App\Classes\Exceptions\MalformedRequestException
*/
public function logic(Request $request) : JsonResponse
{
$status = $request->route('status');
$transaction = $this->fetchesTransaction->execute(['id' => $request->route('transaction_id')]);
$status === 'approve' ? $this->approvesDocument->execute($transaction->documents()->first()) : $this->rejectsDocument->execute($transaction->documents()->first());
$this->updatesTransactionStatus->execute($transaction, $status === 'approve' ? ApprovalStatus::APPROVED : ApprovalStatus::REJECTED);
// $this->createInvoiceTransactionProcessor->execute($transaction->booking);
return $this->response([]);
}
}
@@ -1,94 +0,0 @@
<?php
namespace App\Classes\Modules\Transactions\ControllersLogic;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Meneses\LaravelMpdf\Facades\LaravelMpdf;
use App\Classes\ValueObjects\Constants\DocumentType;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\TransactionType;
use App\Classes\Modules\Documents\Services\CreatesFiles;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Documents\Services\CreatesDocument;
use App\Classes\Modules\Documents\DataTransferObjects\DocumentObject;
use App\Classes\Modules\PackingLists\Services\FetchesPackingList;
use App\Classes\Modules\Transactions\Services\UpdatesTransactionStatus;
use App\Classes\Modules\Transactions\ControllersLogic\Document;
class ApproveShippingInvoiceTransactionLogic extends AbstractControllerLogic
{
/**
* @return array
*/
protected function notification():array {
return [
'title' => 'Shipping Invoice Status',
'message' => 'You have successfully updated the shipping invoice status'
];
}
/** @var FetchesPackingList */
private $fetchesPackingList;
/** @var UpdatesTransactionStatus */
private $updatesTransactionStatus;
/** @var CreatesDocument */
private $createsDocument;
/** @var CreatesFiles */
private $createsFiles;
/**
* ApprovePaymentVerificationLogic constructor.
* @param FetchesPackingList $fetchesPackingList
* @param UpdatesTransactionStatus $updatesTransactionStatus
* @param CreatesDocument $createsDocument
* @param CreatesFiles $createsFiles
* @param CreateInvoiceTransactionProcessor $createInvoiceTransactionProcessor
*/
public function __construct(FetchesPackingList $fetchesPackingList, UpdatesTransactionStatus $updatesTransactionStatus, CreatesDocument $createsDocument, CreatesFiles $createsFiles)
{
$this->fetchesPackingList = $fetchesPackingList;
$this->updatesTransactionStatus = $updatesTransactionStatus;
$this->createsDocument = $createsDocument;
$this->createsFiles = $createsFiles;
}
/**
* @param Request $request
* @return JsonResponse
* @throws \App\Classes\Exceptions\MalformedRequestException
*/
public function logic(Request $request) : JsonResponse
{
$packing_list = $this->fetchesPackingList->execute(['id' => $request->route('id')]);
$invoice_transaction = $packing_list->transactions->where('type', TransactionType::SHIPPING_INVOICE)->first();
$this->updatesTransactionStatus->execute($invoice_transaction, ApprovalStatus::APPROVED);
$transaction_invoice_pdf = LaravelMpdf::loadView('pages.pdfs.shipping_invoice', ['invoice_transaction' => $invoice_transaction]);
$document_object = new DocumentObject(
DocumentType::SHIPPING_INVOICE,
[chunk_split('data:application/pdf;base64,'.base64_encode($transaction_invoice_pdf->output()))],
'',
ApprovalStatus::COMPLETED,
'shipping_invoice'
);
/** @var Document $document */
$document = $this->createsDocument->execute($invoice_transaction, $document_object);
$this->createsFiles->execute($document, $document_object);
return $this->response([]);
}
}
@@ -1,124 +0,0 @@
<?php
namespace App\Classes\Modules\Transactions\ControllersLogic;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Transactions\Services\FetchesTransaction;
use App\Classes\Modules\Transactions\Services\GeneratesTransactionBillNumber;
use App\Classes\Modules\Transactions\Services\CreatesPaymentTransaction;
use App\Classes\Modules\Transactions\Services\CreatesTransactionDetail;
use App\Classes\Modules\Billplzs\Services\CreatesBillplzBill;
use App\Classes\Modules\Transactions\DataTransferObjects\TransactionObject;
use App\Classes\Modules\Transactions\DataTransferObjects\TransactionDetailObject;
use App\Classes\ValueObjects\Constants\OrderRoleTypes;
use App\Classes\ValueObjects\Constants\TransactionType;
use App\Classes\ValueObjects\Constants\PaymentMethodType;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Meneses\LaravelMpdf\Facades\LaravelMpdf;
class CreatePaymentTransactionLogic extends AbstractControllerLogic
{
/**
* @return array
*/
protected function notification():array {
return [
'title' => 'Create Payment Transactions',
'message' => 'You have successfully created currency supplier transactions'
];
}
/** @var FetchesTransaction */
private $fetchesTransaction;
/** @var FetchesSegmentConstant */
private $fetchesSegmentConstant;
/** @var GeneratesTransactionBillNumber */
private $generatesTransactionBillNumber;
/** @var CreatesPaymentTransaction */
private $createsPaymentTransaction;
/** @var CreatesBillplzBill */
private $createsBillplzBill;
/** @var CreatesTransactionDetail */
private $createsTransactionDetail;
public function __construct(
FetchesTransaction $fetchesTransaction,
GeneratesTransactionBillNumber $generatesTransactionBillNumber,
CreatesPaymentTransaction $createsPaymentTransaction,
CreatesTransactionDetail $createsTransactionDetail,
CreatesBillplzBill $createsBillplzBill
)
{
$this->fetchesTransaction = $fetchesTransaction;
$this->generatesTransactionBillNumber = $generatesTransactionBillNumber;
$this->createsPaymentTransaction = $createsPaymentTransaction;
$this->createsTransactionDetail = $createsTransactionDetail;
$this->createsBillplzBill = $createsBillplzBill;
}
public function logic(Request $request) : JsonResponse
{
$invoice_transaction = $this->fetchesTransaction->execute(['id' => $request->input('transaction_id')]);
$amount = $request->input('amount');
$company_module = $invoice_transaction->owner()->first()->owner()->first()->companyModule()->first();
$billNumber = $this->generatesTransactionBillNumber->execute('PYMT-');
$payment_reference = null;
if ($request->input('payment_method') == 5) {
$payment_method = PaymentMethodType::PAYMENT_GATEWAY;
$billPlzBill = $this->createsBillplzBill->execute(
$company_module->name,
$company_module->employees()->first()->email,
'This payment is for the invoice number . ' . $invoice_transaction->bill_no,
$amount,
$billNumber,
$request->input('bank_code'),
true
);
$payment_reference = $billPlzBill->id;
}
else {
$payment_method = PaymentMethodType::CASH;
}
$object = new TransactionObject(
$billNumber,
TransactionType::PAYMENT,
$company_module->id,
1,
1,
$payment_method,
$request->input('amount'),
$request->input('amount'),
1,
1,
0,
0,
0,
null,
ApprovalStatus::PENDING_SUBMISSION,
null,
$payment_reference
);
$payment_transaction = $this->createsPaymentTransaction->execute($invoice_transaction, $object);
return $this->response([]);
}
}
@@ -6,40 +6,36 @@ namespace App\Classes\Modules\Transactions\ControllersLogic;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\PackingLists\Services\FetchesPackingList;
use App\Classes\Modules\SegmentConstants\Services\FetchesSegmentConstant;
use App\Classes\Modules\Segments\Services\ListsConstants;
use App\Classes\Modules\Segments\Services\ListsSegments;
use App\Classes\Modules\Transactions\Services\GeneratesTransactionBillNumber;
use App\Classes\Modules\Transactions\Services\CreatesTransaction;
use App\Classes\Modules\Transactions\Services\CreatesTransactionDetail;
use App\Classes\Modules\Documents\Services\CreatesDocument;
use App\Classes\Modules\Documents\Services\CreatesFiles;
use App\Classes\Modules\Transactions\DataTransferObjects\TransactionObject;
use App\Classes\Modules\Transactions\DataTransferObjects\TransactionDetailObject;
use App\Classes\Modules\Documents\DataTransferObjects\DocumentObject;
use App\Classes\ValueObjects\Constants\OrderRoleTypes;
use App\Classes\ValueObjects\Constants\TransactionType;
use App\Classes\ValueObjects\Constants\PaymentMethodType;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\DocumentType;
use App\Classes\ValueObjects\Constants\PackageType;
use App\Classes\ValueObjects\Constants\SegmentConstants;
use App\Classes\ValueObjects\Constants\TransactionDetailType;
use App\Http\Resources\PackingListResource;
use App\Models\Document;
use App\Models\PackingList;
use App\Models\Transaction;
use Carbon\Carbon;
// use App\Classes\Modules\Documents\DataTransferObjects\DocumentObject;
// use App\Classes\Modules\Transactions\Services\FetchesTransaction;
// use App\Classes\Modules\Transactions\Services\UpdatesTransactionStatus;
// use App\Classes\Modules\Documents\Services\CreatesDocument;
// use App\Classes\Modules\Documents\Services\CreatesFiles;
// use App\Classes\ValueObjects\Constants\DocumentType;
// use App\Models\Document;
// use App\Models\Transaction;
// use Barryvdh\DomPDF\PDF;
// use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Meneses\LaravelMpdf\Facades\LaravelMpdf;
// use Meneses\LaravelLaravelMpdf\Facades\LaravelLaravelMpdf;
// use Meneses\LaravelMpdf\Facades\LaravelMpdf;
class CreateShippingInvoiceTransactionLogic extends AbstractControllerLogic
{
/**
* @return array
*/
@@ -56,109 +52,120 @@ class CreateShippingInvoiceTransactionLogic extends AbstractControllerLogic
/** @var FetchesSegmentConstant */
private $fetchesSegmentConstant;
/** @var ListsConstants */
private $listsConstants;
/** @var GeneratesTransactionBillNumber */
private $generatesTransactionBillNumber;
/** @var CreatesTransaction */
private $createsTransaction;
/** @var CreatesTransactionDetail */
private $createsTransactionDetail;
/** @var CreatesDocument */
private $createsDocument;
/** @var CreatesFiles */
private $createsFile;
// /** @var FetchesTransaction */
// private $fetchesTransaction;
// /** @var UpdatesTransactionStatus */
// private $updatesTransactionStatus;
// /** @var CreatesDocument */
// private $createsDocument;
// /** @var CreatesFiles */
// private $createsFile;
// /** @var PDF */
// private $pdf;
/**
* CreateShippingInvoiceTransactionLogic constructor.
* CreateSupplierTransactionLogic constructor.
* @param FetchesPackingList $fetchesPackingList
* @param FetchesSegmentConstant $fetchesSegmentConstant
* @param ListsConstants $listsConstants
* @param GeneratesTransactionBillNumber $generatesTransactionBillNumber
* @param CreatesTransaction $createsTransaction
* @param CreatesTransactionDetail $createsTransactionDetail
* @param CreatesDocument $createsDocument
* @param CreatesFiles $createsFile
* @param FetchesTransaction $fetchesTransaction
* @param UpdatesTransactionStatus $updatesTransactionStatus
* @param PDF $pdf
*/
public function __construct(FetchesPackingList $fetchesPackingList, FetchesSegmentConstant $fetchesSegmentConstant, ListsConstants $listsConstants, GeneratesTransactionBillNumber $generatesTransactionBillNumber, CreatesTransaction $createsTransaction, CreatesTransactionDetail $createsTransactionDetail, CreatesDocument $createsDocument, CreatesFiles $createsFile)
public function __construct(
FetchesPackingList $fetchesPackingList,
FetchesSegmentConstant $fetchesSegmentConstant,
GeneratesTransactionBillNumber $generatesTransactionBillNumber,
CreatesTransaction $createsTransaction
// UpdatesTransactionStatus $updatesTransactionStatus,
// CreatesDocument $createsDocument,
// CreatesFiles $createsFile,
// PDF $pdf
)
{
$this->fetchesPackingList = $fetchesPackingList;
$this->fetchesSegmentConstant = $fetchesSegmentConstant;
$this->listsConstants = $listsConstants;
$this->generatesTransactionBillNumber = $generatesTransactionBillNumber;
$this->createsTransaction = $createsTransaction;
$this->createsTransactionDetail = $createsTransactionDetail;
$this->createsDocument = $createsDocument;
$this->createsFile = $createsFile;
}
// $this->updatesTransactionStatus = $updatesTransactionStatus;
// $this->createsDocument = $createsDocument;
// $this->createsFile = $createsFile;
// $this->pdf = $pdf;
}
public function logic(Request $request) : JsonResponse
{
$packing_list = $this->fetchesPackingList->execute(['id' => $request->input('packing_list_id')]);
$cbm = $packing_list->packages->where('type', '!=', PackageType::OVER_WEIGHT)->sum(function($package) {
$cbm = $packing_list->packages->sum(function($package) {
return ($package->width / 100) * ($package->height / 100) *($package->length / 100) * ($package->quantity);
});
$over_weight_cbm = $packing_list->packages->where('type', PackageType::OVER_WEIGHT)->sum(function($package) {
return ($package->width / 100) * ($package->height / 100) *($package->length / 100) * ($package->quantity);
});
$minimum_charges = ($cbm + $over_weight_cbm) < 0.3 ? (0.3 - ($cbm + $over_weight_cbm)) : 0;
$order = $packing_list->owner;
$order = $packing_list->owner()->first();
$address = $order->addresses()->first();
$segments = $order->companyModule->connections->first()->segments->pluck('id');
$base_price_constant = $this->fetchesSegmentConstant->execute(['id' => 1]);
$warehouse_rate_constant = $this->fetchesSegmentConstant->execute(['id' => 2]);
$state_rate_constant = $this->fetchesSegmentConstant->execute(['id' => 3]);
$center_postcode_constant = $this->fetchesSegmentConstant->execute(['id' => 4]);
$outstation_postcode_constant = $this->fetchesSegmentConstant->execute(['id' => 5]);
$segment_price = 0;
$base_price_constant = $this->fetchesSegmentConstant->execute(['segment_id' => 1, 'reference' => SegmentConstants::BASE_PRICE]);
if(count($segments)){
$segment_price_constants = $this->listsConstants->execute(['segment_id_in' => $segments, 'reference' => SegmentConstants::CUSTOM_PRICE]);
$segment_price_constant = $segment_price_constants->sortBy(function ($constant){
return $constant->value[0];
})->first();
$segment_price = $segment_price_constant->value[0];
$base_price = 0;
$warehouse_rate = 0;
$state_rate = 0;
$state_select = [];
$with_out = false;
if ($base_price_constant) {
$base_price = $base_price_constant->value->price;
}
$warehouse_rate_constant = $this->fetchesSegmentConstant->execute(['segment_id' => 1, 'reference' => SegmentConstants::WAREHOUSE_RATE]);
$state_rate_constant = $this->fetchesSegmentConstant->execute(['segment_id' => 1, 'reference' => SegmentConstants::STATE_RATE]);
$center_postcode_constant = $this->fetchesSegmentConstant->execute(['segment_id' => 1, 'reference' => SegmentConstants::CENTER_POSTCODE]);
$outstation_postcode_constant = $this->fetchesSegmentConstant->execute(['segment_id' => 1, 'reference' => SegmentConstants::OUTSTATION_POSTCODE]);
$state_select = '';
if ($warehouse_rate_constant) {
$package_warehouse = $order->OrderRoles()->where('role_id', '=', OrderRoleTypes::ORIGIN_WAREHOUSE)->first()->appointee->reference;
foreach ($warehouse_rate_constant->value->config as $key_warehouse => $row_warehouse) {
if ($row_warehouse->warehouse_name == $package_warehouse) {
$warehouse_rate = $row_warehouse->rate;
}
}
}
$packing_list_drop_date = Carbon::parse(PackingList::where('reference', $packing_list->reference)->where('type', 1)->first()->transports->first()->drop_date)->format('Y-m-d');
$base_price = $this->getConstantByKey($base_price_constant, $packing_list_drop_date);
$warehouseId = $order->orderRoles()->where('role_id', OrderRoleTypes::ORIGIN_WAREHOUSE)->first()->company_module_id;
$selected_warehouse_rate = $this->getConstantByKey($warehouse_rate_constant, $warehouseId);
$warehouse_rate = is_object($selected_warehouse_rate) ? $selected_warehouse_rate->amount : 0;
if ($state_rate_constant) {
foreach ($state_rate_constant->value->config as $key_state => $row_state) {
if ($row_state->status_id == $address->state_id) {
$state_select = $row_state;
}
}
}
$stateId = $address->state_id;
$state_rate_constant = $this->getConstantByKey($state_rate_constant, $stateId);
if ($outstation_postcode_constant) {
foreach ($outstation_postcode_constant->value as $key_out => $row_out) {
// get $state_rate
$postcode = $address->postcode;
$this->checkPostcodeExistInConstant($center_postcode_constant, $postcode) === true ? $state_select = 'center' : '' ;
$this->checkPostcodeExistInConstant($outstation_postcode_constant, $postcode) === true ? $state_select = 'outstation' : '' ;
$state_rate_constant = (array)$state_rate_constant;
$state_rate = $state_select == '' ? 0 : $state_rate_constant['center'] + ($state_select === 'outstation' ? $state_rate_constant['outstation'] : 0);
if($row_out == $address->postcode) {
$with_out = true;
}
}
}
$price_cbm = $base_price + $segment_price + $warehouse_rate + $state_rate;
if (!empty($state_select)) {
$state_rate = $state_select->rate;
if ($with_out) {
$state_rate = $state_select->rate + $state_select->outstation_rate;
}
}
$total_cbm = $price_cbm * ($cbm + $over_weight_cbm);
$price_cbm = $base_price + $warehouse_rate + $state_rate;
$total_cbm = $price_cbm * $cbm;
$billNumber = $this->generatesTransactionBillNumber->execute('SI-');
$billNumber = $this->generatesTransactionBillNumber->execute('SHIP-');
$object = new TransactionObject(
$billNumber,
@@ -178,47 +185,8 @@ class CreateShippingInvoiceTransactionLogic extends AbstractControllerLogic
ApprovalStatus::PENDING_SUBMISSION
);
/** @var Transaction $invoice_transaction */
$invoice_transaction = $this->createsTransaction->execute($packing_list, $object);
$transactions = $this->createsTransaction->execute($packing_list, $object);
$object_detail = new TransactionDetailObject(
'SHIPPING_FEE',
TransactionDetailType::SHIPPING_FEE.'<br>'.round($packing_list->packages->sum('quantity'), 3).' CTNS - '.$cbm.' CBM',
$cbm,
$price_cbm
);
$this->createsTransactionDetail->execute($invoice_transaction, $object_detail);
if ($over_weight_cbm > 0) {
$object_detail = new TransactionDetailObject(
'OVER_WEIGHT_CHARGES',
TransactionDetailType::OVER_WEIGHT_CHARGES,
$over_weight_cbm,
$price_cbm
);
$this->createsTransactionDetail->execute($invoice_transaction, $object_detail);
}
return $this->resourceResponse(new PackingListResource($packing_list));
return $this->response([]);
}
function getConstantByKey($segmentConstantObject, $key) {
if ($segmentConstantObject) {
$base_rate = (array) $segmentConstantObject->value;
$base_rate = array_key_exists($key, $base_rate) === true ? $base_rate[$key] : 0;
return $base_rate;
}
}
function checkPostcodeExistInConstant($segmentConstantObject, $postcode) {
$segmentConstantObject = $segmentConstantObject->value;
if (!empty($segmentConstantObject)) {
return in_array($postcode, $segmentConstantObject);
} else {
return false;
}
}
}
@@ -1,92 +0,0 @@
<?php
namespace App\Classes\Modules\Transactions\ControllersLogic;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\SegmentConstants\Services\FetchesSegmentConstant;
use App\Classes\ValueObjects\Constants\SegmentConstants;
use App\Models\District;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use App\Classes\General\Helper;
class ShippingEstimationCalculatorLogic extends AbstractControllerLogic
{
/** @var FetchesSegmentConstant */
private $fetchesSegmentConstant;
/**
* @return array
*/
protected function notification():array {
return [
'title' => 'Shipping estimation',
'message' => 'You have successfully calculate the Shipping Estimation'
];
}
public function __construct(
FetchesSegmentConstant $fetchesSegmentConstant
){
$this->fetchesSegmentConstant = $fetchesSegmentConstant;
}
public function logic(Request $request) : JsonResponse
{
$base_price = $warehouse_rate = $state_rate = 0;
$width = $request->input('width') / 100; // metre
$length = $request->input('length') / 100; // metre
$height = $request->input('height') / 100; // metre
$cbm = (float) ($width * $length * $height);
// calculate base price
$base_prices = $this->getSegmentConstantData(SegmentConstants::BASE_PRICE);
$base_price = $this->getConstantDataUsingKey($base_prices, date('Y-m-d'));
// calculate warehouse rate
$warehouse_prices = $this->getSegmentConstantData(SegmentConstants::WAREHOUSE_RATE);
$warehouse_rate = $this->getConstantDataUsingKey($warehouse_prices, $request->input('warehouse_id'), 'amount');
// calculate applied state rate
$state_prices = $this->getSegmentConstantData(SegmentConstants::STATE_RATE);
$outstation_postcodes = $this->getSegmentConstantData(SegmentConstants::OUTSTATION_POSTCODE);
$district = District::where('postcode','LIKE','%'.$request->input('postcode').'%')->first();
if(array_search($request->input('postcode'), $outstation_postcodes)!==false){
$state_rate = $this->getConstantDataUsingKey($state_prices, $district->state_id, 'outstation');
}
$price_cbm = $base_price + $warehouse_rate + $state_rate;
$total_price_cbm = $price_cbm * $cbm;
return $this->response([
'cbm' => $cbm, 'base_price' => $base_price, 'warehouse_rate' => $warehouse_rate,
'state_rate' => $state_rate, 'total_price_cbm' => $total_price_cbm
]);
}
private function getConstantDataUsingKey($data, $search_key, $field='')
{
if(array_key_exists($search_key, $data) !== true) {
return 0;
} else {
if($field!=''){
return $data[$search_key]->$field;
} else {
return $data[$search_key];
}
}
}
private function getSegmentConstantData($reference)
{
$data = $this->fetchesSegmentConstant->execute(['segment_id' => 1, 'reference' => $reference]);
return (array) $data->value;
}
}
@@ -1,149 +0,0 @@
<?php
namespace App\Classes\Modules\Transactions\ControllersLogic;
use App\Models\Transaction;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Storage;
use Meneses\LaravelMpdf\Facades\LaravelMpdf;
use App\Classes\ValueObjects\Constants\DocumentType;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\TransactionType;
use App\Classes\ValueObjects\Constants\PaymentMethodType;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\ValueObjects\Constants\TransactionDetailType;
use App\Classes\Modules\Documents\DataTransferObjects\FileObject;
use App\Classes\Modules\PackingLists\Services\FetchesPackingList;
use App\Classes\Modules\Transactions\Services\UpdatesTransaction;
use App\Classes\Modules\Transactions\Services\CreatesTransactionDetail;
use App\Classes\Modules\Transactions\Services\FetchesTransactionDetail;
use App\Classes\Modules\Transactions\Services\UpdatesTransactionDetail;
use App\Classes\Modules\Transactions\Services\DeletesTransactionDetails;
use App\Classes\Modules\Transactions\DataTransferObjects\TransactionObject;
use App\Classes\Modules\Transactions\DataTransferObjects\TransactionDetailObject;
use App\Classes\Modules\Transactions\Services\FetchesTransaction;
class UpdateShippingInvoiceTransactionLogic extends AbstractControllerLogic
{
/**
* @return array
*/
protected function notification():array {
return [
'title' => 'Update Shipping Invoice Transaction',
'message' => 'You have successfully update shipping invoice transaction'
];
}
/** @var FetchesPackingList */
private $fetchesPackingList;
/** @var FetchesTransaction */
private $fetchesTransaction;
/** @var UpdatesTransaction */
private $updatesTransaction;
/** @var FetchesTransactionDetail */
private $fetchesTransactionDetail;
/** @var CreatesTransactionDetail */
private $createsTransactionDetail;
/** @var UpdatesTransactionDetail */
private $updatesTransactionDetail;
/** @var DeletesTransactionDetails */
private $deletesTransactionDetails;
public function __construct(
FetchesPackingList $fetchesPackingList,
FetchesTransaction $fetchesTransaction,
UpdatesTransaction $updatesTransaction,
FetchesTransactionDetail $fetchesTransactionDetail,
CreatesTransactionDetail $createsTransactionDetail,
UpdatesTransactionDetail $updatesTransactionDetail,
DeletesTransactionDetails $deletesTransactionDetails
)
{
$this->fetchesPackingList = $fetchesPackingList;
$this->fetchesTransaction = $fetchesTransaction;
$this->updatesTransaction = $updatesTransaction;
$this->fetchesTransactionDetail = $fetchesTransactionDetail;
$this->createsTransactionDetail = $createsTransactionDetail;
$this->updatesTransactionDetail = $updatesTransactionDetail;
$this->deletesTransactionDetails = $deletesTransactionDetails;
}
public function logic(Request $request) : JsonResponse
{
$invoice_transaction = $this->fetchesTransaction->execute(['id' => $request->route('id')]);
$old_transaction_details = $invoice_transaction->transactionDetails->whereNotIn('reference', ['SHIPPING_FEE', 'OVER_WEIGHT_CHARGES'])->pluck('id')->toArray();
$new_transaction_details = collect($request->input('transaction_details'));
$total_cbm = $invoice_transaction->amount;
foreach($old_transaction_details as $old_transaction_detail_id){
$old_transaction_detail = $this->fetchesTransactionDetail->execute(['id' => $old_transaction_detail_id]);
$total_cbm -= $old_transaction_detail->price;
if(!$new_transaction_details->contains('id', $old_transaction_detail_id)){
$this->deletesTransactionDetails->execute($old_transaction_detail);
}
}
foreach($new_transaction_details as $transaction_detail){
$transaction_detail = (object) $transaction_detail;
if(!in_array($transaction_detail->reference, ['SHIPPING_FEE', 'OVER_WHEIGHT_CHARGES'])){
$object_detail = new TransactionDetailObject(
'CUSTOM_CHARGES',
isset($transaction_detail->name) ? $transaction_detail->name : TransactionDetailType::CUSTOM_CHARGES,
$transaction_detail->quantity,
$transaction_detail->price
);
if(isset($transaction_detail->id)){
$new_transaction_detail = $this->updatesTransactionDetail->execute($this->fetchesTransactionDetail->execute(['id' => $transaction_detail->id]), $object_detail);
}else{
$new_transaction_detail = $this->createsTransactionDetail->execute($invoice_transaction, $object_detail);
}
$total_cbm += $new_transaction_detail->amount;
}
}
$object = new TransactionObject(
$invoice_transaction->bill_no,
TransactionType::SHIPPING_INVOICE,
1,
$invoice_transaction->issuer,
1,
PaymentMethodType::CASH,
$total_cbm,
$total_cbm,
1,
1,
0,
0,
0,
null,
ApprovalStatus::PENDING_VERIFICATION
);
/** @var Transaction $invoice_transaction */
$invoice_transaction = $this->updatesTransaction->execute($invoice_transaction, $object);
return $this->response([]);
}
}
@@ -1,87 +0,0 @@
<?php
namespace App\Classes\Modules\Transactions\ControllersLogic;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Companies\Services\FetchesCompany;
use App\Classes\Modules\Companies\Services\UpdatesCompanyStatus;
use App\Classes\Modules\Documents\DataTransferObjects\DocumentObject;
use App\Classes\Modules\Documents\Services\CreatesDocument;
use App\Classes\Modules\Documents\Services\CreatesFiles;
use App\Classes\Modules\Transactions\Services\FetchesTransaction;
use App\Classes\Modules\Transactions\Services\UpdatesTransactionStatus;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\CompanyType;
use App\Classes\ValueObjects\Constants\DocumentType;
use App\Models\Company;
use App\Models\Document;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class UploadPaymentVerificationDocumentLogic extends AbstractControllerLogic
{
/**
* @return array
*/
protected function notification():array {
return [
'title' => 'Payment Verify Document',
'message' => 'You have successfully submitted your payment verify document'
];
}
/** @var FetchesTransaction */
private $fetchesTransaction;
/** @var CreatesDocument */
private $createsDocument;
/** @var CreatesFiles */
private $createsFile;
/** @var UpdatesTransactionStatus */
private $updatesTransactionStatus;
/**
* CreatePaymentVerificationDocumentLogic constructor.
* @param FetchesTransaction $fetchesTransaction
* @param CreatesDocument $createsDocument
* @param CreatesFiles $createsFile
* @param UpdatesTransactionStatus $updatesTransactionStatus
*/
public function __construct(FetchesTransaction $fetchesTransaction, CreatesDocument $createsDocument, CreatesFiles $createsFile, UpdatesTransactionStatus $updatesTransactionStatus)
{
$this->fetchesTransaction = $fetchesTransaction;
$this->createsDocument = $createsDocument;
$this->createsFile = $createsFile;
$this->updatesTransactionStatus = $updatesTransactionStatus;
}
/**
* @param Request $request
* @return JsonResponse
* @throws \App\Classes\Exceptions\MalformedRequestException
*/
public function logic(Request $request) : JsonResponse
{
$transaction = $this->fetchesTransaction->execute(['id' => $request->route('transaction_id')]);
$object = new DocumentObject(
DocumentType::CUSTOMER_PAYMENT_PROOF,
$request->input('files'),
'',
ApprovalStatus::PENDING_VERIFICATION,
'payments'
);
/** @var Document $document */
$document = $this->createsDocument->execute($transaction, $object);
$this->createsFile->execute($document, $object);
$this->updatesTransactionStatus->execute($transaction, ApprovalStatus::PENDING_VERIFICATION);
return $this->response([]);
}
}
@@ -12,7 +12,7 @@ class TransactionDetailObject implements DataTransferObject
/** @var string|null */
private $name;
/** @var float|null */
/** @var int|null */
private $quantity;
/** @var float|null */
@@ -22,10 +22,10 @@ class TransactionDetailObject implements DataTransferObject
* TransactionDetailObject constructor.
* @param string $reference
* @param string $name
* @param float $quantity
* @param int $quantity
* @param float $price
*/
public function __construct(?string $reference, ?string $name , ?float $quantity, ?float $price)
public function __construct(?string $reference, ?string $name , ?int $quantity, ?float $price)
{
$this->reference = $reference;
$this->name = $name;
@@ -50,9 +50,9 @@ class TransactionDetailObject implements DataTransferObject
}
/**
* @return float
* @return int
*/
public function getQuantity(): ?float
public function getQuantity(): ?int
{
return $this->quantity;
}
@@ -57,9 +57,6 @@ class TransactionObject implements DataTransferObject
/** @var array|null */
private $details;
/** @var string */
private $paymentReference;
/**
* TransactionObject constructor.
* @param string $billNo
@@ -95,8 +92,7 @@ class TransactionObject implements DataTransferObject
float $serviceCharge,
?Carbon $expiresOn,
?int $status = ApprovalStatus::PENDING_SUBMISSION,
?array $details = [],
?string $paymentReference = null
?array $details = []
)
{
$this->billNo = $billNo;
@@ -115,7 +111,6 @@ class TransactionObject implements DataTransferObject
$this->expiresOn = $expiresOn;
$this->status = $status;
$this->details = $details;
$this->paymentReference = $paymentReference;
}
/**
@@ -248,11 +243,7 @@ class TransactionObject implements DataTransferObject
}, $this->details);
}
/**
* @return string|null
*/
public function getPaymentReference(): ?string
{
return $this->paymentReference;
}
}
@@ -1,37 +0,0 @@
<?php
namespace App\Classes\Modules\Transactions\Services;
use App\Classes\General\Eloquent\AbstractUpdateRecord;
use App\Classes\General\Eloquent\AbstractUpdateRelationshipRecord;
use App\Classes\Modules\Transactions\DataTransferObjects\TransactionObject;
use App\Models\Transaction;
class CreatesPaymentTransaction extends AbstractUpdateRelationshipRecord
{
/**
* @param TransactionObject $object
* @return \Illuminate\Database\Eloquent\Model
* @throws \App\Classes\Exceptions\MalformedRequestException
*/
public function execute(Transaction $transaction, TransactionObject $object) {
$model = new Transaction();
$model->bill_no = $object->getBillNo();
$model->type = $object->getTransactionType();
$model->issuer = $object->getIssuer();
$model->receiver = $object->getReceiver();
$model->recipient_bank_account_id = $object->getRecipientBankAccountId();
$model->payment_method = $object->getPaymentMethod();
$model->amount = $object->getAmount();
$model->original_amount = $object->getOriginalAmount();
$model->currency_id = $object->getCurrencyId();
$model->original_currency_id = $object->getOriginalCurrencyId();
$model->currency_rate = $object->getCurrencyRate();
$model->tax = $object->getTax();
$model->service_charge = $object->getServiceCharge();
$model->expires_on = $object->getExpiresOn();
$model->status = $object->getStatus();
return $this->handler($transaction->transactions(), $model);
}
}
@@ -18,8 +18,8 @@ class CreatesTransactionDetail extends AbstractUpdateRelationshipRecord
*/
public function execute(Transaction $transaction, TransactionDetailObject $object) {
$model = new TransactionDetail();
$model->reference = $object->getReference();
$model->name = $object->getName();
$model->product_code = $object->getCode();
$model->product_name = $object->getName();
$model->quantity = $object->getQuantity();
$model->price = $object->getPrice();
$model->amount = $object->getAmount();
@@ -3,17 +3,17 @@
namespace App\Classes\Modules\Transactions\Services;
use App\Classes\General\Eloquent\AbstractDeleteRecord;
use App\Models\TransactionDetail;
use App\Models\Transaction;
class DeletesTransactionDetails extends AbstractDeleteRecord
{
/**
* @param TransactionDetail $model
* @param Transaction $model
* @return mixed
*/
public function execute(TransactionDetail $model) {
return $model->delete();
public function execute(Transaction $model) {
return $model->transactionDetails()->delete();
}
}
@@ -1,27 +0,0 @@
<?php
namespace App\Classes\Modules\Transactions\Services;
use App\Classes\General\Eloquent\AbstractUpdateRecord;
use App\Classes\Modules\Transactions\DataTransferObjects\TransactionDetailObject;
use App\Models\TransactionDetail;
class UpdatesTransactionDetail extends AbstractUpdateRecord
{
/**
* @param TransactionDetail $transactionDetail
* @param TransactionDetailObject $object
* @return \Illuminate\Database\Eloquent\Model
* @throws \App\Classes\Exceptions\MalformedRequestException
*/
public function execute(TransactionDetail $transactionDetail, TransactionDetailObject $object) {
$transactionDetail->reference = $object->getReference();
$transactionDetail->name = $object->getName();
$transactionDetail->quantity = $object->getQuantity();
$transactionDetail->price = $object->getPrice();
$transactionDetail->amount = $object->getAmount();
return $this->handler($transactionDetail);
}
}
@@ -8,6 +8,4 @@ final class AddressType {
public const DELIVERY = 2;
public const PICK_UP = 3;
}
@@ -18,7 +18,4 @@ final class BusinessType {
public const CURRENCY_VENDOR = 6;
public const ONLINE_SELLER = 7;
public const LAST_MILE_DELIVERY_AGENT = 8;
}
@@ -21,8 +21,4 @@ final class DocumentType {
public const DELIVER_ORDER = 'DELIVER_ORDER';
public const INVOICE = 'INVOICE';
public const SUPPLIER_DELIVER_ORDER = 'SUPPLIER_DELIVER_ORDER';
public const SHIPPING_INVOICE = 'SHIPPING_INVOICE';
}

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