Compare commits

..

2 Commits

Author SHA1 Message Date
edmondlang ac8ec13433 push branch 2022-12-26 15:56:09 +08:00
94924240Jeko! c73e86e2cf multiple invoices with one payment SDEV-421 2022-12-20 21:14:09 +03:00
154 changed files with 4930 additions and 3240 deletions
+807
View File
File diff suppressed because one or more lines are too long
+1
View File
@@ -0,0 +1 @@
yarnPath: ".yarn/releases/yarn-berry.cjs"
@@ -95,4 +95,4 @@ abstract class AbstractControllerLogic
return $this->response(json_decode($collection->response()->getContent(), true));
}
}
}
@@ -18,7 +18,10 @@ abstract class AbstractUpdateRecord
public function handler(Model $model){
try{
if($model->save()){ return $model; }
if($model->save()) {
return $model;
}
} catch (QueryException $exception){
throw new MalformedRequestException($exception);
@@ -1,21 +0,0 @@
<?php
namespace App\Classes\General\Eloquent\Filters;
use App\Models\Order;
use Illuminate\Database\Eloquent\Builder;
class OrderMarkingIn implements Filter
{
/**
* @param Builder $builder
* @param $value
* @return mixed
*/
public static function apply(Builder $builder, $value)
{
return $builder->whereHas('owner', function($query) use ($value) {
$query->where('reference', 'LIKE', '%' . $value . '%');
});
}
}
@@ -1,20 +0,0 @@
<?php
namespace App\Classes\General\Eloquent\Filters;
use Illuminate\Database\Eloquent\Builder;
class Receiver implements Filter
{
/**
* @param Builder $builder
* @param $value
* @return Builder|mixed
*/
public static function apply(Builder $builder, $value)
{
return $builder->where('receiver', '=', $value);
}
}
+36
View File
@@ -0,0 +1,36 @@
<?php
namespace App\Classes\General\Eloquent;
use Illuminate\Support\Facades\Schema;
use DB;
trait logData
{
public static function boot()
{
parent::boot();
static::updating(function($model)
{
if (!Schema::hasTable(''.$model->table.'log')) {
DB::statement('CREATE TABLE '.$model->table.'log LIKE '.$model->table);
DB::statement('ALTER TABLE '.$model->table.'log DROP COLUMN id');
DB::statement('ALTER TABLE '.$model->table.'log ADD id INTEGER FIRST');
}
DB::table(''.$model->table.'log')->insert($model->getRawOriginal());
});
}
public function logs($model){
$result = DB::table(''.$model->table.'log')
->where('id', $model->id)
->get();
return $result;
}
}
-47
View File
@@ -1,47 +0,0 @@
<?php
namespace App\Classes\General\Traits;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
trait LogData
{
public static function boot()
{
parent::boot();
static::updating(function($model)
{
$tableName = Str::singular($model->table).'_logs';
$relationshipColumn = Str::singular($model->table).'_id';
$originalData = $model->getRawOriginal();
$originalData[$relationshipColumn] = $originalData['id'];
unset($originalData['id']);
if (!Schema::hasTable($tableName)) {
DB::statement('CREATE TABLE '.$tableName.' LIKE '.$model->table);
$indexs = DB::select('SHOW INDEX FROM '.$tableName.';');
$removedIndexes = [];
foreach ($indexs as $index){
if($index->Column_name === 'id' || in_array($index->Key_name, $removedIndexes)) continue;
DB::statement('ALTER TABLE '.$tableName.' drop index '.$index->Key_name);
$removedIndexes[] = $index->Key_name;
}
DB::statement('ALTER TABLE '.$tableName.' ADD COLUMN `'.$relationshipColumn.'` BIGINT NOT NULL AFTER `id`');
}
DB::table($tableName)->insert($originalData);
});
}
}
@@ -2,12 +2,8 @@
namespace App\Classes\Jobs;
use App\Classes\Modules\PackingLists\Processors\FetchContainersFromYdPortalProcessor;
use App\Classes\Modules\PackingLists\Processors\FetchContainersUpdatesFromYdPortalProcessor;
use App\Classes\Modules\PackingLists\Processors\FetchDeliveryUpdatesFromYdPortalProcessor;
use App\Classes\Modules\PackingLists\Processors\FetchOrderListsFromYdPortalProcessor;
use App\Classes\Modules\PackingLists\Processors\FetchPackingListsFromYdPortalProcessor;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
@@ -29,12 +25,8 @@ class FetchOrdersFromYDPortalJob implements ShouldQueue
*/
public function handle()
{
(App()->make(FetchPackingListsFromYdPortalProcessor::class))->execute();
(App()->make(FetchContainersFromYdPortalProcessor::class))->execute();
(App()->make(FetchContainersUpdatesFromYdPortalProcessor::class))->execute();
(App()->make(FetchDeliveryUpdatesFromYdPortalProcessor::class))->execute();
// (App()->make(FetchOrderListsFromYdPortalProcessor::class))->execute();
(App()->make(FetchOrderListsFromYdPortalProcessor::class))->execute();
}
}
@@ -1,63 +0,0 @@
<?php
namespace App\Classes\Modules\Accounts\ControllersLogic;
use App\Classes\Modules\Accounts\Services\FetchesUser;
use App\Classes\Modules\Accounts\Standards\Rules\CanFetchUser;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Http\Resources\UserCompanyResource;
use ErrorException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class FetchUserByEmailLogic extends AbstractControllerLogic
{
/**
* @return array
*/
protected function notification():array {
return [
'title' => 'Fetch Users',
'message' => 'You have successfully retrieved the user by email'
];
}
/** @var CanFetchUser */
private $canFetchUser;
/** @var FetchesUser */
private $fetchesUser;
/**
* FetchUserByEmailLogic constructor.
* @param CanFetchUser $canFetchUser
* @param FetchesUser $fetchessUser
*/
public function __construct(CanFetchUser $canFetchUser, FetchesUser $fetchesUser)
{
$this->canFetchUser = $canFetchUser;
$this->fetchesUser = $fetchesUser;
}
/**
* @param Request $request
* @return JsonResponse
* @throws ErrorException
*/
public function logic(Request $request) : JsonResponse
{
try {
$this->canFetchUser->passes();
$query = $this->fetchesUser->execute(['email' => $request->route('email')]);
return $this->resourceResponse(new UserCompanyResource($query));
} catch (\Exception $exception){
throw new ErrorException($exception->getMessage(), $exception->getCode());
}
}
}
@@ -6,6 +6,8 @@ use App\Classes\Modules\Orders\Processors\UpdateDoFromVTPortalProcessor;
use App\Classes\Modules\Orders\Processors\UpdateDoFromYDPortalProcessor;
use App\Classes\Modules\Wallets\DataTransferObjects\WalletObject;
use App\Classes\Modules\Wallets\Services\UpdatesWallet;
use App\Classes\Modules\Transactions\ControllersLogic\multipleInvoicesWithOnePaymentLogic;
use App\Classes\Exceptions\ResourceNotFoundException;
use App\Classes\Modules\Wallets\Services\UpdatesWalletBalance;
@@ -44,6 +46,10 @@ class CallbackBillplzLogic
/** @var UpdateDoFromYDPortalProcessor */
private $updateDoFromYDPortalProcessor ;
/** @var UpdateDoFromYDPortalProcessor */
private $multipleInvoicesWithOnePaymentLogic ;
/**
* CallbackBillplzLogic constructor.
* @param GetBillplzBill $getBillplzBill
@@ -52,13 +58,14 @@ class CallbackBillplzLogic
* @param UpdateDoFromVTPortalProcessor $updateDoFromVTPortalProcessor
* @param UpdateDoFromYDPortalProcessor $updateDoFromYDPortalProcessor
*/
public function __construct(GetBillplzBill $getBillplzBill, FetchesTransaction $fetchesTransaction, UpdatesTransactionStatus $updatesTransactionStatus, UpdateDoFromVTPortalProcessor $updateDoFromVTPortalProcessor, UpdateDoFromYDPortalProcessor $updateDoFromYDPortalProcessor)
public function __construct(GetBillplzBill $getBillplzBill, FetchesTransaction $fetchesTransaction, UpdatesTransactionStatus $updatesTransactionStatus, UpdateDoFromVTPortalProcessor $updateDoFromVTPortalProcessor, UpdateDoFromYDPortalProcessor $updateDoFromYDPortalProcessor,multipleInvoicesWithOnePaymentLogic $multipleInvoicesWithOnePaymentLogic)
{
$this->getBillplzBill = $getBillplzBill;
$this->fetchesTransaction = $fetchesTransaction;
$this->updatesTransactionStatus = $updatesTransactionStatus;
$this->updateDoFromVTPortalProcessor = $updateDoFromVTPortalProcessor;
$this->updateDoFromYDPortalProcessor = $updateDoFromYDPortalProcessor;
$this->multipleInvoicesWithOnePaymentLogic= $multipleInvoicesWithOnePaymentLogic;
}
@@ -84,12 +91,19 @@ class CallbackBillplzLogic
$transaction = $this->fetchesTransaction->execute(['payment_reference' => $billplzXSignatureObject->getBillPlzId()]);
if ($transaction->type == 'topUp') {
$this->updatesTransactionStatus->execute($transaction, ApprovalStatus::APPROVED);
$this->multipleInvoicesWithOnePaymentLogic->verifypayment($transaction->id, $transaction->amount);
}
$invoice = $transaction->owner;
$packingList = $invoice->owner;
$order = $packingList->owner;
$status = ApprovalStatus::PENDING_VERIFICATION;
if($billPlz->state === 'paid') {
$status = ApprovalStatus::APPROVED;
}
@@ -118,6 +132,7 @@ class CallbackBillplzLogic
return $request->method() === 'POST' ? true : view('pages.payments_redirect', ['marking' => $order->reference, 'transaction' => $transaction, 'status' => $status]);
}
}
@@ -1,88 +0,0 @@
<?php
namespace App\Classes\Modules\Companies\ControllersLogic;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Companies\Services\UpdatesCompany;
use App\Classes\Modules\Companies\Services\UpdatesCompanyModuleName;
use App\Classes\Modules\Companies\Services\FetchesCompany;
use App\Classes\Modules\Companies\Standards\Rules\CanUpdateCompany;
use App\Classes\Modules\Companies\DataTransferObjects\CompanyObject;
use App\Classes\Modules\Companies\Services\UpdatesCompanyDebtor;
use App\Http\Resources\CompanyResource;
use ErrorException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class UpdateCompanyNameAndDebtorLogic extends AbstractControllerLogic
{
/**
* @return array
*/
protected function notification():array {
return [
'title' => 'Updated Company Name and Debtor',
'message' => 'You have successfully updated the Company'
];
}
/** @var CanUpdateCompany */
private $canUpdateCompany;
/** @var UpdatesCompany */
private $updatesCompany;
/** @var FetchesCompany */
private $fetchesCompany;
/** @var UpdatesCompanyDebtor */
private $updatesCompanyDebtor;
/** @var UpdatesCompanyModuleName */
private $updatesCompanyModuleName;
/**
* UpdateCompanyControllersLogic constructor.
* @param CanUpdateCompany $canUpdateCompany
* @param UpdatesCompany $updatesCompany
* @param FetchesCompany $fetchesCompany
* @param UpdatesCompanyDebtor $updatesCompanyDebtor
* @param UpdatesCompanyModuleName $updatesCompanyModuleName
*/
public function __construct(CanUpdateCompany $canUpdateCompany, UpdatesCompany $updatesCompany, FetchesCompany $fetchesCompany, UpdatesCompanyDebtor $updatesCompanyDebtor, UpdatesCompanyModuleName $updatesCompanyModuleName)
{
$this->canUpdateCompany = $canUpdateCompany;
$this->updatesCompany = $updatesCompany;
$this->fetchesCompany = $fetchesCompany;
$this->updatesCompanyDebtor = $updatesCompanyDebtor;
$this->updatesCompanyModuleName = $updatesCompanyModuleName;
}
/**
* @param Request $request
* @return JsonResponse
* @throws ErrorException
*/
public function logic(Request $request) : JsonResponse
{
$object = new CompanyObject($request->input('name'), $request->input('reference'), $request->input('type'));
$this->canUpdateCompany->passes($object);
$query = $this->fetchesCompany->execute(['id' => $request->route('id')]);
$this->updatesCompanyModuleName->execute($query->companyModules()->first(), $object->getName());
$query = $this->updatesCompany->execute($query, $object);
if ($request->input('debtor') || $query->first()->debtor !== null) {
$this->updatesCompanyDebtor->execute($query, $request->input('debtor'));
}
return $this->resourceResponse(new CompanyResource($query));
}
}
@@ -1,24 +0,0 @@
<?php
namespace App\Classes\Modules\Companies\Services;
use App\Classes\General\Eloquent\AbstractUpdateRecord;
use App\Classes\Modules\Companies\DataTransferObjects\CompanyObject;
use App\Models\Company;
class UpdatesCompanyDebtor extends AbstractUpdateRecord
{
/**
* @param Company $model
* @param CompanyObject $object
* @return \Illuminate\Database\Eloquent\Model
* @throws \App\Classes\Exceptions\MalformedRequestException
*/
public function execute(Company $model, ?string $debtor)
{
$model->debtor = $debtor;
return $this->handler($model);
}
}
@@ -1,84 +0,0 @@
<?php
namespace App\Classes\Modules\Exports\Services;
use App\Classes\ValueObjects\Constants\PackingListType;
use App\Models\CompanyModule;
use App\Models\Company;
use App\Models\PackingList;
use Carbon\Carbon;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use Illuminate\Http\Request;
class ExportsCustomerTotalOrderByYear implements FromCollection, WithHeadings, WithHeadingRow, WithMapping, ShouldAutoSize
{
use Exportable;
private $request;
public function __construct(Request $request)
{
$this->request = $request;
}
public function headings(): array
{
return [
'CompanyId',
'CompanyName',
'CompanyReference',
'TotalCbm'
];
}
/**
* @return \Illuminate\Support\Collection|mixed
*/
public function collection()
{
$packingLists = PackingList::where('type', PackingListType::SHIPPING_PACKING_LIST)->whereHas('containers', function($container){
return $container->where('loading_date', '>=', Carbon::parse('01-01-' . $this->request->route('year')))
->where('loading_date', '<=', Carbon::parse('31-12-' . $this->request->route('year')));
})->get();
$packingLists = $packingLists->groupBy(function ($packingList){
return $packingList->owner->company_module_id;
})->sortByDesc(function($companyModule){
return $companyModule->sum(function($packingList){
return $packingList->packages->sum(function ($package){
return (($package->width / 100) * ($package->height / 100) * ($package->length / 100)) * $package->quantity;
});
});
})->take(10);
return $packingLists;
}
/**
* @param $row
* @return array
*/
public function map($row): array
{
$companyModule = $row[0]->owner->companyModule;
$marking = $companyModule->inviters()->withPivot('invitee_reference')->first()->pivot->invitee_reference;
$cbm = $row->sum(function($packingList){
return $packingList->packages->sum(function ($package){
return (($package->width / 100) * ($package->height / 100) * ($package->length / 100)) * $package->quantity;
});
});
return [
$companyModule->company_id,
$companyModule->name,
$marking,
$cbm
];
}
}
@@ -1,108 +0,0 @@
<?php
namespace App\Classes\Modules\Exports\Services;
use App\Models\CompanyConnection;
use App\Models\Container;
use App\Models\Order;
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 ExportsOrderSummaryByMarking implements FromCollection, WithHeadings, WithHeadingRow, WithMapping, ShouldAutoSize
{
use Exportable;
protected $customerMarking;
protected $dateFrom;
protected $dateTo;
public function headings(): array
{
return [
'Date',
'Container',
'Order Marking',
'Packing List Reference',
'Description',
'Quantity',
'L (cm)',
'H (cm)',
'W (cm)',
'CBM'
];
}
public function setParameters($customerMarking, $dateFrom, $dateTo)
{
$this->customerMarking = $customerMarking;
$this->dateFrom = $dateFrom;
$this->dateTo = $dateTo;
}
/**
* @return \Illuminate\Support\Collection|mixed
*/
public function collection()
{
$connection = CompanyConnection::where('invitee_reference', $this->customerMarking)->first();
$company_id = $connection->invitee->company->id;
$company_module_id = $connection->invitee->id;
$packagesArray = collect();
$orders = Order::where('company_module_id', $company_module_id);
if (isset($this->dateFrom) && isset($this->dateTo)) {
$from = Carbon::createFromFormat('d-m-Y', $this->dateFrom);
$to = Carbon::createFromFormat('d-m-Y', $this->dateTo);
$orders = $orders->whereBetween('created_at', [$from, $to]);
}
$orders = $orders->get();
foreach ($orders as $order){
$packingLists = $order->packingLists;
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
{
$packinglist = ($package->packingList()->first()->owner->owner_type == Order::class) ? $package->packingList()->first(): $package->packingList->owner;
$order = $packinglist->owner;
return [
Carbon::parse($package->created_at)->format('d-m-Y'),
'',
$order->reference,
$package->packingList->reference,
$package->description,
$package->quantity,
$package->length,
$package->height,
$package->width,
((($package->length / 100) * ($package->height / 100) * ($package->width / 100)) * $package->quantity)
];
}
}
@@ -1,58 +0,0 @@
<?php
namespace App\Classes\Modules\Exports\Services;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\PackingListType;
use App\Models\Order;
use App\Models\State;
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 ExportsWarehousePackingList implements FromQuery, WithHeadings, WithHeadingRow, WithMapping, ShouldAutoSize
{
use Exportable;
public function headings(): array
{
return [
'Customer Marking',
'Order Number'
];
}
/**
* @return \Illuminate\Support\Collection|mixed
*/
public function query()
{
$johor_state_id = State::where('name', 'johor')->first()->id;
return Order::whereHas('addresses', function($address) use ($johor_state_id){
$address->where('status', ApprovalStatus::APPROVED)->where('state_id', $johor_state_id);
})->whereHas('packingLists', function($packingLists) {
$packingLists->where('type', PackingListType::SHIPPING_PACKING_LIST)->whereDoesntHave('transports');
});
}
/**
* @param Order $order
*
* @return array
*/
public function map($order): array
{
$marking = $order->companyModule->inviters()->withPivot('invitee_reference')->first()->pivot->invitee_reference;
return [
$marking,
$order->reference,
];
}
}
@@ -0,0 +1,19 @@
<?php
namespace App\Classes\Modules\Imports\Services;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use App\Classes\Modules\PackingLists\Processors\FetchOrderListsFromExcel;
class Importorder implements ToCollection
{
/**
* @param Collection $collection
*/
public function collection(Collection $collection)
{
// dd($collection);
(App()->make(FetchOrderListsFromExcel::class))->execute($collection);
}
}
@@ -14,11 +14,12 @@ class FetchesDataFromYDPortal
* @return \Psr\Http\Message\ResponseInterface
*/
public function clientRequest(string $url, string $method, $body){
$client = new \GuzzleHttp\Client();
$body['apicode'] = env('YD_API_CODE');
$request = $client->requestAsync($method, $url, ['query' => $body, 'timeout' => 15]);
$request = $client->requestAsync($method, $url, ['query' => $body]);
return $request->wait();
}
@@ -31,7 +32,6 @@ class FetchesDataFromYDPortal
$content = $request->getBody()->getContents();
$content = str_replace("\r",'', $content);
$content = str_replace("\n",'', $content);
$content = str_replace("\t",'', $content);
return json_decode($content);
}
}
}
@@ -51,15 +51,15 @@ class CreatePackingListProcessor
/** @var PackingList $packingList */
$packingList = $this->createsPackingList->execute($object, $packable);
$appointee_id = $packingList->owner_id == 1 ? 2307 : $packingList->owner->orderRoles()->where('role_id', '=', OrderRoleTypes::ORIGIN_FREIGHT_FORWARDER)->first()->appointee->id;
$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);
return $packingList;
}
}
}
@@ -1,213 +0,0 @@
<?php
namespace App\Classes\Modules\PackingLists\Processors;
use App\Classes\Exceptions\MalformedRequestException;
use App\Classes\Exceptions\ResourceNotFoundException;
use App\Classes\Modules\Companies\Services\FetchesCompanyModule;
use App\Classes\Modules\Orders\Services\FetchesDataFromYDPortal;
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;
use App\Classes\Modules\Unity\Processors\CreateContractEntityProcessor;
use App\Classes\Modules\Unity\Services\CreatesContract;
use App\Classes\Modules\Unity\Services\UpdatesContractObligation;
use App\Classes\Notifications\ShipmentDepartureEmail;
use App\Classes\Notifications\ShipmentRescheduleEmail;
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\PackingListType;
use App\Classes\ValueObjects\Constants\TransportType;
use App\Classes\ValueObjects\Constants\WarehouseReferences;
use App\Models\Container;
use App\Models\Order;
use App\Models\PackingList;
use App\Models\Transport;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
class FetchContainersFromYdPortalProcessor
{
/** @var FetchesDataFromYDPortal */
private $fetchesDataFRomYDPortal;
/** @var FetchesOrder */
private $fetchesOrder;
/** @var UpdatesContractObligation */
private $updatesContractObligations;
/** @var CreatePackingListProcessor */
private $createPackingListProcessor;
/** @var CreatePackageProcessor */
private $createPackageProcessor;
/** @var CreatesTransport */
private $createsTransport;
/** @var CreatesSchedule */
private $createsSchedule;
/** @var FetchesContainer */
private $fetchesContainer;
/** @var FetchesPackingList */
private $fetchesPackingList;
/** @var FetchesCompanyModule */
private $fetchesCompanyModule;
/** @var CreateContainerProcessor */
private $createContainerProcessor;
/** @var CreatesContract */
private $unityCreateContract;
/** @var AssignContractEntityProcessor */
private $unityAssignContractEntity;
/** @var CreateContractEntityProcessor */
private $unityCreateContractEntity;
/** @var CreatesStep */
private $createsStep;
/** @var ActivateContractProcessor */
private $unityActivateContract;
/**
* FetchOrderListsFromYdPortalProcessor constructor.
* @param FetchesDataFromYDPortal $fetchesDataFRomYDPortal
* @param FetchesOrder $fetchesOrder
* @param UpdatesContractObligation $updatesContractObligations
* @param CreatePackingListProcessor $createPackingListProcessor
* @param CreatePackageProcessor $createPackageProcessor
* @param CreatesTransport $createsTransport
* @param CreatesSchedule $createsSchedule
* @param FetchesContainer $fetchesContainer
* @param FetchesPackingList $fetchesPackingList
* @param FetchesCompanyModule $fetchesCompanyModule
* @param CreateContainerProcessor $createContainerProcessor
* @param CreatesContract $unityCreateContract
* @param AssignContractEntityProcessor $unityAssignContractEntity
* @param CreateContractEntityProcessor $unityCreateContractEntity
* @param CreatesStep $createsStep
* @param ActivateContractProcessor $unityActivateContract
*/
public function __construct(FetchesDataFromYDPortal $fetchesDataFRomYDPortal, FetchesOrder $fetchesOrder, UpdatesContractObligation $updatesContractObligations, CreatePackingListProcessor $createPackingListProcessor, CreatePackageProcessor $createPackageProcessor, CreatesTransport $createsTransport, CreatesSchedule $createsSchedule, FetchesContainer $fetchesContainer, FetchesPackingList $fetchesPackingList, FetchesCompanyModule $fetchesCompanyModule, CreateContainerProcessor $createContainerProcessor, CreatesContract $unityCreateContract, AssignContractEntityProcessor $unityAssignContractEntity, CreateContractEntityProcessor $unityCreateContractEntity, CreatesStep $createsStep, ActivateContractProcessor $unityActivateContract)
{
$this->fetchesDataFRomYDPortal = $fetchesDataFRomYDPortal;
$this->fetchesOrder = $fetchesOrder;
$this->updatesContractObligations = $updatesContractObligations;
$this->createPackingListProcessor = $createPackingListProcessor;
$this->createPackageProcessor = $createPackageProcessor;
$this->createsTransport = $createsTransport;
$this->createsSchedule = $createsSchedule;
$this->fetchesContainer = $fetchesContainer;
$this->fetchesPackingList = $fetchesPackingList;
$this->fetchesCompanyModule = $fetchesCompanyModule;
$this->createContainerProcessor = $createContainerProcessor;
$this->unityCreateContract = $unityCreateContract;
$this->unityAssignContractEntity = $unityAssignContractEntity;
$this->unityCreateContractEntity = $unityCreateContractEntity;
$this->createsStep = $createsStep;
$this->unityActivateContract = $unityActivateContract;
}
/**
* @param Carbon|null $start
* @param Carbon|null $end
* @return void
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function execute()
{
$packingLists = PackingList::where('type', PackingListType::SHIPPING_PACKING_LIST)->doesntHave('containers')->get();
foreach ($packingLists as $packingList) {
$time_start = microtime(true);
$containerReference = null;
$loadingDate = null;
$etd = null;
$eta = null;
$trackingRequest = $this->fetchesDataFRomYDPortal->clientRequest('http://www.yd-wl.com/api/ApiTracking.ashx', 'GET', [
'trakingno' => $packingList->reference
]);
$rows = $this->fetchesDataFRomYDPortal->getResponseBody($trackingRequest);
if(!$rows->data){
continue;
}
foreach (array_reverse($rows->data) as $trackingRow) {
if (strpos($trackingRow->tracking, '货物装柜完成。') !== false) {
$tracking = explode(':', $trackingRow->tracking);
$containerReference = explode('预计到港时间', $tracking[1])[0];
$loadingDate = Carbon::parse($trackingRow->trackingtime);
$etd = Carbon::parse($tracking[2])->subDays(5);
$eta = Carbon::parse($tracking[2])->addDays(2);
}
}
if($containerReference) {
try {
$container = $this->fetchesContainer->execute(['reference' => $containerReference]);
$container->packingLists()->detach($packingList);
$container->packingLists()->attach($packingList);
} catch (ResourceNotFoundException $exception){
if(!($packingList->owner instanceof Order)) continue;
$originWarehouse = $packingList->owner->orderRoles()->where('role_id', '=', OrderRoleTypes::ORIGIN_WAREHOUSE)->first()->appointee;
$containerObject = new ContainerObject($containerReference, '', '', ContainerTypes::FORTY_FEET_DRY_CONTAINER, $loadingDate, ApprovalStatus::PENDING_VERIFICATION);
/** @var Container $container */
$container = $this->createContainerProcessor->execute($containerObject, $originWarehouse);
$container->packingLists()->detach($packingList);
$container->packingLists()->attach($packingList);
$transport = $container->transports()->first();
if(!$transport){
$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));
}
}
}
$time_end = microtime(true);
$execution_time = ($time_end - $time_start)/60;
echo 'successful => <b>Total Execution Time:</b> '.$execution_time.' Mins<br>';
}
}
}
@@ -1,162 +0,0 @@
<?php
namespace App\Classes\Modules\PackingLists\Processors;
use App\Classes\Exceptions\MalformedRequestException;
use App\Classes\Modules\Orders\Services\FetchesDataFromYDPortal;
use App\Classes\Modules\Schedules\DataTransferObjects\ScheduleObject;
use App\Classes\Modules\Schedules\Services\CreatesSchedule;
use App\Classes\Modules\Unity\Services\UpdatesContractObligation;
use App\Classes\Notifications\ShipmentRescheduleEmail;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\OrderRoleTypes;
use App\Models\Container;
use App\Models\Order;
use App\Models\PackingList;
use Carbon\Carbon;
class FetchContainersUpdatesFromYdPortalProcessor
{
/** @var FetchesDataFromYDPortal */
private $fetchesDataFRomYDPortal;
/** @var UpdatesContractObligation */
private $updatesContractObligations;
/** @var CreatesSchedule */
private $createsSchedule;
/**
* @param FetchesDataFromYDPortal $fetchesDataFRomYDPortal
* @param UpdatesContractObligation $updatesContractObligations
* @param CreatesSchedule $createsSchedule
*/
public function __construct(FetchesDataFromYDPortal $fetchesDataFRomYDPortal, UpdatesContractObligation $updatesContractObligations, CreatesSchedule $createsSchedule)
{
$this->fetchesDataFRomYDPortal = $fetchesDataFRomYDPortal;
$this->updatesContractObligations = $updatesContractObligations;
$this->createsSchedule = $createsSchedule;
}
/**
* @return void
* @throws MalformedRequestException
*/
public function execute()
{
$containers = Container::where('status', ApprovalStatus::PENDING_VERIFICATION)->get();
foreach ($containers as $container) {
$time_start = microtime(true);
$packingList = $container->packingLists()->first();
$trackingRequest = $this->fetchesDataFRomYDPortal->clientRequest('http://www.yd-wl.com/api/ApiTracking.ashx', 'GET', [
'trakingno' => $packingList->reference
]);
$rows = $this->fetchesDataFRomYDPortal->getResponseBody($trackingRequest);
if(!$rows->data){
continue;
}
$unstuffingDate = null;
$delayDate = null;
foreach (array_reverse($rows->data) as $trackingRow) {
$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 ($trackingRow->tracking === '到港') {
$delayDate = Carbon::parse($trackingRow->trackingtime);
}
if ($trackingRow->tracking === '已开船') {
$delayDate = Carbon::parse($trackingRow->trackingtime)->addDays('5');
}
if ($trackingRow->tracking === '货物已进目的港仓库') {
$unstuffingDate = Carbon::parse($trackingRow->trackingtime);
}
}
if($delayDate){
$delayDate = $delayDate->addDays(2);
$transport = $container->transports()->first();
if(!$transport->schedules()->whereDate('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));
foreach ($container->packingLists as $packingList){
if(!($packingList->owner instanceof Order)) continue;
$user = $packingList->owner->companyModule->employees()->first();
if(app()->environment(['production'])) {
$user->notify(new ShipmentRescheduleEmail($user, $packingList));
}
}
}
}
if($unstuffingDate){
$container->update(['status' => ApprovalStatus::COMPLETED]);
$container->transports()->first()->update(['drop_date' => $unstuffingDate, 'status' => ApprovalStatus::COMPLETED]);
/** @var PackingList $packingList */
foreach($container->packingLists as $packingList){
if($packingList->status === ApprovalStatus::PENDING_VERIFICATION){
$packingList->status = ApprovalStatus::APPROVED;
$packingList->save();
}
if(!($packingList->owner instanceof Order)) continue;
$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]);
}
}
}
$time_end = microtime(true);
$execution_time = ($time_end - $time_start)/60;
echo 'successful => <b>Total Execution Time:</b> '.$execution_time.' Mins<br>';
}
}
}
@@ -1,115 +0,0 @@
<?php
namespace App\Classes\Modules\PackingLists\Processors;
use App\Classes\Exceptions\MalformedRequestException;
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\Classes\ValueObjects\Constants\WarehouseReferences;
use App\Models\CompanyModule;
use App\Models\Order;
use App\Models\PackingList;
use App\Models\Transport;
use Carbon\Carbon;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
class FetchDeliveryUpdatesFromYdPortalProcessor
{
/** @var UpdatesContractObligation */
private $updatesContractObligations;
/** @var CreatesTransport */
private $createsTransport;
/** @var CreatesSchedule */
private $createsSchedule;
/**
* @param UpdatesContractObligation $updatesContractObligations
* @param CreatesTransport $createsTransport
* @param CreatesSchedule $createsSchedule
*/
public function __construct(UpdatesContractObligation $updatesContractObligations, CreatesTransport $createsTransport, CreatesSchedule $createsSchedule)
{
$this->updatesContractObligations = $updatesContractObligations;
$this->createsTransport = $createsTransport;
$this->createsSchedule = $createsSchedule;
}
/**
* @return void
* @throws MalformedRequestException
* @throws GuzzleException
*/
public function execute()
{
$packingLists = PackingList::where('type', PackingListType::SHIPPING_PACKING_LIST)->whereRaw('LENGTH(reference) > 12')->whereHas('containers', function ($container){
return $container->where('status', 3);
})->doesntHave('transports')->get()->reverse();
foreach ($packingLists->chunk(50) as $chunk) {
foreach ($chunk as $packingList){
if(!$packingList->reference) continue;
$time_start = microtime(true);
$deliveryDate = null;
try {
$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='.$packingList->reference.'&sOrgId=sti', ['timeout' => 3]);
$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, ['delivered'])) {
$deliveryDate = $trackingDate;
}
}
} catch (\Exception $exception){
dump($exception);
Log::debug('failed to fetch delivery tracking');
}
if($deliveryDate){
$packingList->status = ApprovalStatus::COMPLETED;
$packingList->save();
$deliveryDate = Carbon::parse($deliveryDate);
$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));
if(!($packingList->owner instanceof Order)) continue;
$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]);
}
$time_end = microtime(true);
$execution_time = ($time_end - $time_start)/60;
echo 'successful => <b>Total Execution Time:</b> '.$execution_time.' Mins<br>';
}
}
}
}
@@ -264,7 +264,7 @@ class FetchLoadedContainersFromVTPortalProcessor
//
// $this->unityAssignContractEntity->execute($supervisorContractEntity->hash_id, $contractObligations);
} else {
$appointee_id = 2307;
$appointee_id = 2037;
}
$packingListObject = new PackingListObject($packingListReference, $appointee_id, PackingListType::SHIPPING_PACKING_LIST, ApprovalStatus::SUSPENDED, null);
@@ -0,0 +1,488 @@
<?php
namespace App\Classes\Modules\PackingLists\Processors;
use App\Classes\Exceptions\MalformedRequestException;
use App\Classes\Exceptions\ResourceNotFoundException;
use App\Classes\Modules\Companies\Services\FetchesCompanyModule;
use App\Classes\Modules\Orders\Services\FetchesDataFromYDPortal;
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;
use App\Classes\Modules\Unity\Processors\CreateContractEntityProcessor;
use App\Classes\Modules\Unity\Services\CreatesContract;
use App\Classes\Modules\Unity\Services\UpdatesContractObligation;
use App\Classes\Notifications\ShipmentDepartureEmail;
use App\Classes\Notifications\ShipmentRescheduleEmail;
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\PackingListType;
use App\Classes\ValueObjects\Constants\TransportType;
use App\Models\Container;
use App\Models\Order;
use App\Models\PackingList;
use App\Models\Transport;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
class FetchOrderListsFromExcel
{
/** @var FetchesDataFromYDPortal */
private $fetchesDataFRomYDPortal;
/** @var FetchesOrder */
private $fetchesOrder;
/** @var UpdatesContractObligation */
private $updatesContractObligations;
/** @var CreatePackingListProcessor */
private $createPackingListProcessor;
/** @var CreatePackageProcessor */
private $createPackageProcessor;
/** @var CreatesTransport */
private $createsTransport;
/** @var CreatesSchedule */
private $createsSchedule;
/** @var FetchesContainer */
private $fetchesContainer;
/** @var FetchesPackingList */
private $fetchesPackingList;
/** @var FetchesCompanyModule */
private $fetchesCompanyModule;
/** @var CreateContainerProcessor */
private $createContainerProcessor;
/** @var CreatesContract */
private $unityCreateContract;
/** @var AssignContractEntityProcessor */
private $unityAssignContractEntity;
/** @var CreateContractEntityProcessor */
private $unityCreateContractEntity;
/** @var CreatesStep */
private $createsStep;
/** @var ActivateContractProcessor */
private $unityActivateContract;
/**
* FetchOrderListsFromYdPortalProcessor constructor.
* @param FetchesDataFromYDPortal $fetchesDataFRomYDPortal
* @param FetchesOrder $fetchesOrder
* @param UpdatesContractObligation $updatesContractObligations
* @param CreatePackingListProcessor $createPackingListProcessor
* @param CreatePackageProcessor $createPackageProcessor
* @param CreatesTransport $createsTransport
* @param CreatesSchedule $createsSchedule
* @param FetchesContainer $fetchesContainer
* @param FetchesPackingList $fetchesPackingList
* @param FetchesCompanyModule $fetchesCompanyModule
* @param CreateContainerProcessor $createContainerProcessor
* @param CreatesContract $unityCreateContract
* @param AssignContractEntityProcessor $unityAssignContractEntity
* @param CreateContractEntityProcessor $unityCreateContractEntity
* @param CreatesStep $createsStep
* @param ActivateContractProcessor $unityActivateContract
*/
public function __construct(FetchesDataFromYDPortal $fetchesDataFRomYDPortal , FetchesOrder $fetchesOrder, UpdatesContractObligation $updatesContractObligations, CreatePackingListProcessor $createPackingListProcessor, CreatePackageProcessor $createPackageProcessor, CreatesTransport $createsTransport, CreatesSchedule $createsSchedule, FetchesContainer $fetchesContainer, FetchesPackingList $fetchesPackingList, FetchesCompanyModule $fetchesCompanyModule, CreateContainerProcessor $createContainerProcessor, CreatesContract $unityCreateContract, AssignContractEntityProcessor $unityAssignContractEntity, CreateContractEntityProcessor $unityCreateContractEntity, CreatesStep $createsStep, ActivateContractProcessor $unityActivateContract)
{
$this->fetchesDataFRomYDPortal = $fetchesDataFRomYDPortal;
$this->fetchesOrder = $fetchesOrder;
$this->updatesContractObligations = $updatesContractObligations;
$this->createPackingListProcessor = $createPackingListProcessor;
$this->createPackageProcessor = $createPackageProcessor;
$this->createsTransport = $createsTransport;
$this->createsSchedule = $createsSchedule;
$this->fetchesContainer = $fetchesContainer;
$this->fetchesPackingList = $fetchesPackingList;
$this->fetchesCompanyModule = $fetchesCompanyModule;
$this->createContainerProcessor = $createContainerProcessor;
$this->unityCreateContract = $unityCreateContract;
$this->unityAssignContractEntity = $unityAssignContractEntity;
$this->unityCreateContractEntity = $unityCreateContractEntity;
$this->createsStep = $createsStep;
$this->unityActivateContract = $unityActivateContract;
}
/**
* @param Carbon|null $start
* @param Carbon|null $end
* @return void
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function execute( $excelData )
{
try {
// dd($start);
// $start = $start ? $start : Carbon::today()->subDays(30);
// $startLimit = Carbon::parse('01-12-2021');
// if($start->isBefore($startLimit)){
// $start = $startLimit;
// }
// $end = $end ? $end : Carbon::today()->addDay();
// $orderRequest = $this->fetchesDataFRomYDPortal->clientRequest('http://www.yd-wl.com/api/GetOrderList.ashx', 'GET', [
// 'begintime' => $start->timestamp,
// 'endtime' => $end->timestamp,
// ]);
// $rows = $this->fetchesDataFRomYDPortal->getResponseBody($orderRequest);
foreach($excelData as $row){
if("expressno"!= $row[0] && $row[0] != null){
// dd($row[0]);
$containerReference = null;
$loadingDate = null;
$unstuffingDate = null;
$deliveryDate = null;
$etd = null;
$eta = null;
$delayDate = null;
$trackingRequest = $this->fetchesDataFRomYDPortal->clientRequest('http://www.yd-wl.com/api/ApiTracking.ashx', 'GET', [
'trakingno' => $row[0]
]);
$rows = $this->fetchesDataFRomYDPortal->getResponseBody($trackingRequest);
if($rows->data == null){
continue;
}else{
dd($rows);
}
}else{
continue;
}
if(!$rows){
continue;
}
foreach (array_reverse($rows->data) as $trackingRow) {
if ($trackingRow->tracking === '货物已送达仓库准备入库中') {
$receiveDate = Carbon::parse($trackingRow->trackingtime);
}
if (strpos($trackingRow->tracking, '货物装柜完成。') !== false) {
$tracking = explode(':', $trackingRow->tracking);
$containerReference = explode('预计到港时间', $tracking[1])[0];
$loadingDate = Carbon::parse($trackingRow->trackingtime);
$etd = Carbon::parse($tracking[2])->subDays(5);
$eta = Carbon::parse($tracking[2])->addDays(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 ($trackingRow->tracking === '到港') {
$delayDate = Carbon::parse($trackingRow->trackingtime);
}
if ($trackingRow->tracking === '已开船') {
$delayDate = Carbon::parse($trackingRow->trackingtime)->addDays('5');
}
if ($trackingRow->tracking === '货物已进目的港仓库') {
$unstuffingDate = Carbon::parse($trackingRow->trackingtime);
}
if (Str::contains($trackingRow->tracking, ['派送中', '已签收', '签收完成', ' 第三方提货', '货物已派送完成', '派送', 'delivery', 'delivered'])) {
$deliveryDate = Carbon::parse($trackingRow->trackingtime);
}
}
$client = new \GuzzleHttp\Client(['cookies' => true, 'headers' => ['Cookie' => 'utc_offset=480']]);
try {
$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;
}
}
} catch (\Exception $exception){
Log::debug('failed to fetch delivery tracking');
}
$customerno = preg_split('(-|\(|\)|\/)', $row->customerno);
$orderNumber = $customerno[array_key_last($customerno)];
$allow_contract = true;
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;
}
}
$packingListReference = $row->expressno;
try{
$packingList = $this->fetchesPackingList->execute(['reference' => $row->expressno, 'type' => PackingListType::SHIPPING_PACKING_LIST]);
$packingList->packages()->delete();
$replica = $packingList->packingLists()->where('type', PackingListType::SHIPPING_PACKING_LIST_REPLICA)->first();
if($replica) $replica->packages()->delete();
$warehouseReceiveList = $this->fetchesPackingList->execute(['reference' => $row->expressno, 'type' => PackingListType::WAREHOUSE_RECEIVE_LIST]);
$warehouseReceiveList->packages()->delete();
$replica = $warehouseReceiveList->packingLists()->where('type', PackingListType::WAREHOUSE_RECEIVE_LIST_REPLICA)->first();
if($replica) $replica->packages()->delete();
} catch (ResourceNotFoundException $exception) {
if (!$allow_contract) {
$appointee_id = 2037;
} else {
$appointee_id = $order->orderRoles()->where('role_id', '=', OrderRoleTypes::ORIGIN_FREIGHT_FORWARDER)->first()->appointee->id;
}
$warehouseReceiveObject = new PackingListObject($packingListReference, $appointee_id, PackingListType::WAREHOUSE_RECEIVE_LIST, $allow_contract ? ApprovalStatus::APPROVED : ApprovalStatus::REJECTED);
/** @var PackingList $warehouseReceiveList */
$warehouseReceiveList = $this->createPackingListProcessor->execute($warehouseReceiveObject, $order);
$transportObject = new TransportObject(TransportType::LAND, null, $row->kuaidilist, Carbon::parse($receiveDate), Carbon::parse($receiveDate), $allow_contract ? ApprovalStatus::APPROVED : ApprovalStatus::REJECTED);
$transport = $this->createsTransport->execute($transportObject, $warehouseReceiveList);
if ($allow_contract) {
$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);
}
$packingListObject = new PackingListObject($packingListReference, $appointee_id, PackingListType::SHIPPING_PACKING_LIST, ApprovalStatus::SUSPENDED, !$allow_contract ? null : $contractReference);
/** @var PackingList $packingList */
$packingList = $this->createPackingListProcessor->execute($packingListObject, $order);
if ($allow_contract) {
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);
}
}
}
foreach($row->deliverysize as $package) {
$packageObject = new PackageObject(PackageType::CARTON, $row->goodname, (float) $package->width, (float) $package->height, (float) $package->length, 0, (float) $package->num, ApprovalStatus::APPROVED);
$this->createPackageProcessor->execute($packageObject, $warehouseReceiveList);
$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'));
if($overWeightCbm > 0){
$measurement = round($overWeightCbm ** (1/3) * 100, 2);
$packageObject = new PackageObject(PackageType::OVER_WEIGHT, 'Overweight CBM', (float) $measurement, (float) $measurement, (float) $measurement, 0, 1, ApprovalStatus::APPROVED);
$this->createPackageProcessor->execute($packageObject, $packingList);
}
if($order instanceof Order){
$marking = $order->companyModule->inviters()->withPivot('invitee_reference')->first()->pivot->invitee_reference;
if(!in_array($marking, ['1290CSW', '8997ITB', '3992WHE', '962LOW', '1152AAT'])){
$this->fetchesDataFRomYDPortal->clientRequest('http://www.yd-wl.com/api/confirmsendorder.ashx', 'GET', [
'expressno' => $row->expressno
]);
}
}
if($containerReference) {
try {
$container = $this->fetchesContainer->execute(['reference' => $containerReference]);
$container->packingLists()->detach($packingList);
$container->packingLists()->attach($packingList);
} catch (ResourceNotFoundException $exception){
if (!$allow_contract) {
$appointee_id = 2037;
}
else {
$appointee_id = $order->orderRoles()->where('role_id', '=', OrderRoleTypes::ORIGIN_WAREHOUSE)->first()->appointee->id;
}
$originWarehouse = $this->fetchesCompanyModule->execute(['id' => $appointee_id]);
$containerObject = new ContainerObject($containerReference, '', '', ContainerTypes::FORTY_FEET_DRY_CONTAINER, $loadingDate, ApprovalStatus::PENDING_VERIFICATION);
/** @var Container $container */
$container = $this->createContainerProcessor->execute($containerObject, $originWarehouse);
$container->packingLists()->detach($packingList);
$container->packingLists()->attach($packingList);
$transport = $container->transports()->first();
if(!$transport){
$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 = $delayDate->addDays(2);
$transport = $container->transports()->first();
if(!$transport->schedules()->whereDate('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));
foreach ($container->packingLists as $packingList){
if(!($packingList->owner instanceof Order)) continue;
$user = $packingList->owner->companyModule->employees()->first();
if(app()->environment(['production'])) {
$user->notify(new ShipmentRescheduleEmail($user, $packingList));
}
}
}
}
if($unstuffingDate && $container->status !== ApprovalStatus::COMPLETED){
$container->update(['status' => ApprovalStatus::COMPLETED]);
$container->transports()->first()->update(['drop_date' => $unstuffingDate, 'status' => ApprovalStatus::COMPLETED]);
/** @var PackingList $packingList */
foreach($container->packingLists as $packingList){
if($packingList->status === ApprovalStatus::PENDING_VERIFICATION){
$packingList->status = ApprovalStatus::APPROVED;
$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]);
}
}
}
}
}
if($deliveryDate && !$packingList->transports()->exists()){
$packingList->status = ApprovalStatus::COMPLETED;
$packingList->save();
$deliveryDate = Carbon::parse($deliveryDate);
$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));
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]);
}
}
echo 'successful';
}
} catch (\Exception $exception) {
Log::debug($exception);
}
}
}
@@ -139,360 +139,336 @@ class FetchOrderListsFromYdPortalProcessor
*/
public function execute(?Carbon $start = null, ?Carbon $end = null)
{
ini_set('max_execution_time', '900');
// $missingOrders = ['M202302161513122', 'YW202302161027442', 'YW202302151637022', 'M202302151605025', 'M202302151527103', 'M202302151527356', 'M202302151556019', 'YW202302151520241', 'YW202302151445068', 'M202302151359169', 'YW202302151349223', 'YW202302151336520', 'M202302151334316', 'YW202302151148129', 'M202302151145379', 'M202302151142411', 'M202302151037036', 'M202302151036398', 'M202302150919406', 'M202302141535009', 'YW202302141532318', 'M202302141319463', 'M202302141319045', 'YW202302141405471', 'M202302141334494', 'YW202302141321569', 'YW202302141323005', 'M202302141309053', 'M202302140905116', 'M202302141039558', 'M202302141022333', 'YW202302140943182', 'YW202302140923485', 'YW202302131728233', 'YW202302131702040', 'M202302131649417', 'M202302131638056', 'YW202302131601110', 'YW202302131530436', 'YW202302131411338', 'YW202302131355161', 'YW202302131312526', 'M202302130859076', 'M202302111708070', 'M202302111455134', 'M202302111457501', 'M202302111444041', 'M202302111506514', 'M202302111440286', 'M202302111354585', 'M202302111055551', 'M202302110900216', 'YW202302101743112', 'M202302091559443', 'M202302101716374', 'M202302101700402', 'M202302101633570', 'M202302101612095', 'M202302101611408', 'M202302101542340', 'M202302101408370', 'M202302101323341', 'M202302101129532', 'M202302101025109', 'M202302101006595', 'M202302091706357', 'YW202302091255022', 'YW202302091448196', 'YW202302091446431', 'M202302091138154', 'M202302091129396', 'YW202302091028175', 'M202302091006545', 'YW202302090942033', 'YW202302081743094', 'M202302081530599', 'M202302081531210', 'M202302081508571', 'YW202302081530492', 'M202302081500361', 'M202302081253105', 'M202302081303370', 'M202302071636303', 'M202302071741187', 'YW202302071735407', 'M202302071706323', 'M202302071537501', 'M202302071538092', 'YW202302071516453', 'M202302071311314', 'M202302071148154', 'YW202302071136018', 'M202302071036027', 'M202302071008010', 'M202302061742178', 'M202302061615198', 'M202302061502093', 'M202302061458532', 'M202302061552141', 'M202302061548431', 'M202302061555033', 'YW202302061404567', 'M202302061322463', 'M202302061042556', 'M202302061021277', 'M202302060917276', 'M202302041551570', 'M202302041552382', 'YW202302041515257', 'M202302041405502', 'M202302041030185', 'YW202302041215576', 'YW202302041058469', 'YW202302041024459', 'YW202302040939568', 'M202302031701053', 'M202302031700316', 'M202302031430562', 'M202302031431535', 'M202302031147213', 'YW202302031406529', 'YW202302031322256', 'M202302021718554', 'M202302021417415', 'YW202302021404542', 'M202302021055324', 'YW202302021037462', 'M202302011613381', 'M202302011347586', 'M202302011348245', 'M202301151635132', 'M202301141803516', 'YW202301141653536', 'M202301131504477', 'M202301131538220', 'M202301121327453', 'YW202301111153183', 'M202301091649543', 'M202212311641071', 'YW202212211532191', 'YW202212191605226'];
try {
$start = $start ? $start : Carbon::today()->subDays(30);
$from = $end ? Carbon::today()->diff($end)->days : 0;
$to = $start ? Carbon::today()->diff($start)->days : 10;
$startLimit = Carbon::parse('01-12-2021');
for ($x = $from; $x <= $to; $x++) {
try {
$startDate = Carbon::today()->subDays($x);
if($start->isBefore($startLimit)){
$start = $startLimit;
}
$startLimit = Carbon::parse('01-12-2021');
$end = $end ? $end : Carbon::today()->addDay();
if($startDate->isBefore($startLimit)){
$startDate = $startLimit;
}
$orderRequest = $this->fetchesDataFRomYDPortal->clientRequest('http://www.yd-wl.com/api/GetOrderList.ashx', 'GET', [
'begintime' => $start->timestamp,
'endtime' => $end->timestamp,
]);
$endDate = Carbon::today()->subDays($x - 1);
$rows = $this->fetchesDataFRomYDPortal->getResponseBody($orderRequest);
$orderRequest = $this->fetchesDataFRomYDPortal->clientRequest('http://www.yd-wl.com/api/GetOrderList.ashx', 'GET', [
'begintime' => $startDate->timestamp,
'endtime' => $endDate->timestamp,
foreach($rows->data as $row){
$containerReference = null;
$loadingDate = null;
$unstuffingDate = null;
$deliveryDate = null;
$etd = null;
$eta = null;
$delayDate = null;
$trackingRequest = $this->fetchesDataFRomYDPortal->clientRequest('http://www.yd-wl.com/api/ApiTracking.ashx', 'GET', [
'trakingno' => $row->expressno
]);
$rows = $this->fetchesDataFRomYDPortal->getResponseBody($orderRequest);
$rows = $this->fetchesDataFRomYDPortal->getResponseBody($trackingRequest);
if(!$rows->data) continue;
if(!$rows){
continue;
}
foreach($rows->data as $row){
$time_start = microtime(true);
$containerReference = null;
$loadingDate = null;
$unstuffingDate = null;
$deliveryDate = null;
$etd = null;
$eta = null;
$delayDate = null;
$status = $row->status;
if($status >= 3){
$trackingRequest = $this->fetchesDataFRomYDPortal->clientRequest('http://www.yd-wl.com/api/ApiTracking.ashx', 'GET', [
'trakingno' => $row->expressno
]);
$rows = $this->fetchesDataFRomYDPortal->getResponseBody($trackingRequest);
if(!$rows){
continue;
}
foreach (array_reverse($rows->data) as $trackingRow) {
if ($trackingRow->tracking === '货物已送达仓库准备入库中') {
$receiveDate = Carbon::parse($trackingRow->trackingtime);
}
if (strpos($trackingRow->tracking, '货物装柜完成。') !== false) {
$tracking = explode(':', $trackingRow->tracking);
$containerReference = explode('预计到港时间', $tracking[1])[0];
$loadingDate = Carbon::parse($trackingRow->trackingtime);
$etd = Carbon::parse($tracking[2])->subDays(5);
$eta = Carbon::parse($tracking[2])->addDays(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 ($trackingRow->tracking === '到港') {
$delayDate = Carbon::parse($trackingRow->trackingtime);
}
if ($trackingRow->tracking === '已开船') {
$delayDate = Carbon::parse($trackingRow->trackingtime)->addDays('5');
}
if ($trackingRow->tracking === '货物已进目的港仓库') {
$unstuffingDate = Carbon::parse($trackingRow->trackingtime);
}
if (Str::contains($trackingRow->tracking, ['派送中', '已签收', '签收完成', ' 第三方提货', '货物已派送完成', '派送', 'delivery', 'delivered'])) {
$deliveryDate = Carbon::parse($trackingRow->trackingtime);
}
}
foreach (array_reverse($rows->data) as $trackingRow) {
if ($trackingRow->tracking === '货物已送达仓库准备入库中') {
$receiveDate = Carbon::parse($trackingRow->trackingtime);
}
if($status >= 5){
$client = new \GuzzleHttp\Client(['cookies' => true, 'headers' => ['Cookie' => 'utc_offset=480']]);
try {
$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;
}
}
} catch (\Exception $exception){
Log::debug('failed to fetch delivery tracking');
}
if (strpos($trackingRow->tracking, '货物装柜完成。') !== false) {
$tracking = explode(':', $trackingRow->tracking);
$containerReference = explode('预计到港时间', $tracking[1])[0];
$loadingDate = Carbon::parse($trackingRow->trackingtime);
$etd = Carbon::parse($tracking[2])->subDays(5);
$eta = Carbon::parse($tracking[2])->addDays(2);
}
$customerno = preg_split('(-|\(|\)|\/)', $row->customerno);
$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();
$orderNumber = $customerno[array_key_last($customerno)];
$allow_contract = true;
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 ($trackingRow->tracking === '到港') {
$delayDate = Carbon::parse($trackingRow->trackingtime);
}
if ($trackingRow->tracking === '已开船') {
$delayDate = Carbon::parse($trackingRow->trackingtime)->addDays('5');
}
if ($trackingRow->tracking === '货物已进目的港仓库') {
$unstuffingDate = Carbon::parse($trackingRow->trackingtime);
}
if (Str::contains($trackingRow->tracking, ['派送中', '已签收', '签收完成', ' 第三方提货', '货物已派送完成', '派送', 'delivery', 'delivered'])) {
$deliveryDate = Carbon::parse($trackingRow->trackingtime);
}
}
$client = new \GuzzleHttp\Client(['cookies' => true, 'headers' => ['Cookie' => 'utc_offset=480']]);
try {
$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;
}
}
} catch (\Exception $exception){
Log::debug('failed to fetch delivery tracking');
}
$customerno = preg_split('(-|\(|\)|\/)', $row->customerno);
$orderNumber = $customerno[array_key_last($customerno)];
$allow_contract = true;
try {
$order = $this->fetchesOrder->execute(['reference' => $orderNumber]);
} catch (ResourceNotFoundException $exception) {
try {
$order = $this->fetchesOrder->execute(['reference' => $orderNumber]);
$order = $this->fetchesOrder->execute(['reference' => substr($orderNumber, -9)]);
} catch (ResourceNotFoundException $exception) {
try {
$order = $this->fetchesOrder->execute(['reference' => substr($orderNumber, -9)]);
} catch (ResourceNotFoundException $exception) {
$order = $this->fetchesCompanyModule->execute(['id' => 1]);
$allow_contract = false;
}
$order = $this->fetchesCompanyModule->execute(['id' => 1]);
$allow_contract = false;
}
$packingListReference = $row->expressno;
try{
$packingList = $this->fetchesPackingList->execute(['reference' => $row->expressno, 'type' => PackingListType::SHIPPING_PACKING_LIST]);
$packingList->packages()->delete();
$replica = $packingList->packingLists()->where('type', PackingListType::SHIPPING_PACKING_LIST_REPLICA)->first();
if($replica) $replica->packages()->delete();
$warehouseReceiveList = $this->fetchesPackingList->execute(['reference' => $row->expressno, 'type' => PackingListType::WAREHOUSE_RECEIVE_LIST]);
$warehouseReceiveList->packages()->delete();
$replica = $warehouseReceiveList->packingLists()->where('type', PackingListType::WAREHOUSE_RECEIVE_LIST_REPLICA)->first();
if($replica) $replica->packages()->delete();
} catch (ResourceNotFoundException $exception) {
if (!$allow_contract) {
$appointee_id = 2307;
} else {
$appointee_id = $order->orderRoles()->where('role_id', '=', OrderRoleTypes::ORIGIN_FREIGHT_FORWARDER)->first()->appointee->id;
}
$warehouseReceiveObject = new PackingListObject($packingListReference, $appointee_id, PackingListType::WAREHOUSE_RECEIVE_LIST, $allow_contract ? ApprovalStatus::APPROVED : ApprovalStatus::REJECTED);
/** @var PackingList $warehouseReceiveList */
$warehouseReceiveList = $this->createPackingListProcessor->execute($warehouseReceiveObject, $order);
$transportObject = new TransportObject(TransportType::LAND, null, $row->kuaidilist, Carbon::parse($receiveDate), Carbon::parse($receiveDate), $allow_contract ? ApprovalStatus::APPROVED : ApprovalStatus::REJECTED);
$transport = $this->createsTransport->execute($transportObject, $warehouseReceiveList);
if ($allow_contract) {
$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);
}
$packingListObject = new PackingListObject($packingListReference, $appointee_id, PackingListType::SHIPPING_PACKING_LIST, ApprovalStatus::SUSPENDED, !$allow_contract ? null : $contractReference);
/** @var PackingList $packingList */
$packingList = $this->createPackingListProcessor->execute($packingListObject, $order);
if ($allow_contract) {
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);
}
}
}
foreach($row->deliverysize as $package) {
$packageObject = new PackageObject(PackageType::CARTON, $row->goodname, (float) $package->width, (float) $package->height, (float) $package->length, 0, (float) $package->num, ApprovalStatus::APPROVED);
$this->createPackageProcessor->execute($packageObject, $warehouseReceiveList);
$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'));
if($overWeightCbm > 0){
$measurement = round($overWeightCbm ** (1/3) * 100, 2);
$packageObject = new PackageObject(PackageType::OVER_WEIGHT, 'Overweight CBM', (float) $measurement, (float) $measurement, (float) $measurement, 0, 1, ApprovalStatus::APPROVED);
$this->createPackageProcessor->execute($packageObject, $packingList);
}
if($order instanceof Order){
$marking = $order->companyModule->inviters()->withPivot('invitee_reference')->first()->pivot->invitee_reference;
if(!in_array($marking, ['1290CSW', '8997ITB', '3992WHE', '962LOW', '1152AAT'])){
$this->fetchesDataFRomYDPortal->clientRequest('http://www.yd-wl.com/api/confirmsendorder.ashx', 'GET', [
'expressno' => $row->expressno
]);
}
}
if($containerReference) {
try {
$container = $this->fetchesContainer->execute(['reference' => $containerReference]);
$container->packingLists()->detach($packingList);
$container->packingLists()->attach($packingList);
} catch (ResourceNotFoundException $exception){
if (!$allow_contract) {
$appointee_id = 2307;
}
else {
$appointee_id = $order->orderRoles()->where('role_id', '=', OrderRoleTypes::ORIGIN_WAREHOUSE)->first()->appointee->id;
}
$originWarehouse = $this->fetchesCompanyModule->execute(['id' => $appointee_id]);
$containerObject = new ContainerObject($containerReference, '', '', ContainerTypes::FORTY_FEET_DRY_CONTAINER, $loadingDate, ApprovalStatus::PENDING_VERIFICATION);
/** @var Container $container */
$container = $this->createContainerProcessor->execute($containerObject, $originWarehouse);
$container->packingLists()->detach($packingList);
$container->packingLists()->attach($packingList);
$transport = $container->transports()->first();
if(!$transport){
$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 = $delayDate->addDays(2);
$transport = $container->transports()->first();
if(!$transport->schedules()->whereDate('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));
foreach ($container->packingLists as $packingList){
if(!($packingList->owner instanceof Order)) continue;
$user = $packingList->owner->companyModule->employees()->first();
if(app()->environment(['production'])) {
$user->notify(new ShipmentRescheduleEmail($user, $packingList));
}
}
}
}
if($unstuffingDate && $container->status !== ApprovalStatus::COMPLETED){
$container->update(['status' => ApprovalStatus::COMPLETED]);
$container->transports()->first()->update(['drop_date' => $unstuffingDate, 'status' => ApprovalStatus::COMPLETED]);
/** @var PackingList $packingList */
foreach($container->packingLists as $packingList){
if($packingList->status === ApprovalStatus::PENDING_VERIFICATION){
$packingList->status = ApprovalStatus::APPROVED;
$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]);
}
}
}
}
}
if($deliveryDate && !$packingList->transports()->exists()){
$packingList->status = ApprovalStatus::COMPLETED;
$packingList->save();
$deliveryDate = Carbon::parse($deliveryDate);
$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));
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]);
}
}
$time_end = microtime(true);
$execution_time = ($time_end - $time_start)/60;
echo '<b>Total Execution Time:</b> '.$execution_time.' Mins';
echo 'successful';
}
} catch (\Exception $exception) {
Log::debug($exception);
}
}
$packingListReference = $row->expressno;
try{
$packingList = $this->fetchesPackingList->execute(['reference' => $row->expressno, 'type' => PackingListType::SHIPPING_PACKING_LIST]);
$packingList->packages()->delete();
$replica = $packingList->packingLists()->where('type', PackingListType::SHIPPING_PACKING_LIST_REPLICA)->first();
if($replica) $replica->packages()->delete();
$warehouseReceiveList = $this->fetchesPackingList->execute(['reference' => $row->expressno, 'type' => PackingListType::WAREHOUSE_RECEIVE_LIST]);
$warehouseReceiveList->packages()->delete();
$replica = $warehouseReceiveList->packingLists()->where('type', PackingListType::WAREHOUSE_RECEIVE_LIST_REPLICA)->first();
if($replica) $replica->packages()->delete();
} catch (ResourceNotFoundException $exception) {
if (!$allow_contract) {
$appointee_id = 2037;
} else {
$appointee_id = $order->orderRoles()->where('role_id', '=', OrderRoleTypes::ORIGIN_FREIGHT_FORWARDER)->first()->appointee->id;
}
$warehouseReceiveObject = new PackingListObject($packingListReference, $appointee_id, PackingListType::WAREHOUSE_RECEIVE_LIST, $allow_contract ? ApprovalStatus::APPROVED : ApprovalStatus::REJECTED);
/** @var PackingList $warehouseReceiveList */
$warehouseReceiveList = $this->createPackingListProcessor->execute($warehouseReceiveObject, $order);
$transportObject = new TransportObject(TransportType::LAND, null, $row->kuaidilist, Carbon::parse($receiveDate), Carbon::parse($receiveDate), $allow_contract ? ApprovalStatus::APPROVED : ApprovalStatus::REJECTED);
$transport = $this->createsTransport->execute($transportObject, $warehouseReceiveList);
if ($allow_contract) {
$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);
}
$packingListObject = new PackingListObject($packingListReference, $appointee_id, PackingListType::SHIPPING_PACKING_LIST, ApprovalStatus::SUSPENDED, !$allow_contract ? null : $contractReference);
/** @var PackingList $packingList */
$packingList = $this->createPackingListProcessor->execute($packingListObject, $order);
if ($allow_contract) {
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);
}
}
}
foreach($row->deliverysize as $package) {
$packageObject = new PackageObject(PackageType::CARTON, $row->goodname, (float) $package->width, (float) $package->height, (float) $package->length, 0, (float) $package->num, ApprovalStatus::APPROVED);
$this->createPackageProcessor->execute($packageObject, $warehouseReceiveList);
$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'));
if($overWeightCbm > 0){
$measurement = round($overWeightCbm ** (1/3) * 100, 2);
$packageObject = new PackageObject(PackageType::OVER_WEIGHT, 'Overweight CBM', (float) $measurement, (float) $measurement, (float) $measurement, 0, 1, ApprovalStatus::APPROVED);
$this->createPackageProcessor->execute($packageObject, $packingList);
}
if($order instanceof Order){
$marking = $order->companyModule->inviters()->withPivot('invitee_reference')->first()->pivot->invitee_reference;
if(!in_array($marking, ['1290CSW', '8997ITB', '3992WHE', '962LOW', '1152AAT'])){
$this->fetchesDataFRomYDPortal->clientRequest('http://www.yd-wl.com/api/confirmsendorder.ashx', 'GET', [
'expressno' => $row->expressno
]);
}
}
if($containerReference) {
try {
$container = $this->fetchesContainer->execute(['reference' => $containerReference]);
$container->packingLists()->detach($packingList);
$container->packingLists()->attach($packingList);
} catch (ResourceNotFoundException $exception){
if (!$allow_contract) {
$appointee_id = 2037;
}
else {
$appointee_id = $order->orderRoles()->where('role_id', '=', OrderRoleTypes::ORIGIN_WAREHOUSE)->first()->appointee->id;
}
$originWarehouse = $this->fetchesCompanyModule->execute(['id' => $appointee_id]);
$containerObject = new ContainerObject($containerReference, '', '', ContainerTypes::FORTY_FEET_DRY_CONTAINER, $loadingDate, ApprovalStatus::PENDING_VERIFICATION);
/** @var Container $container */
$container = $this->createContainerProcessor->execute($containerObject, $originWarehouse);
$container->packingLists()->detach($packingList);
$container->packingLists()->attach($packingList);
$transport = $container->transports()->first();
if(!$transport){
$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 = $delayDate->addDays(2);
$transport = $container->transports()->first();
if(!$transport->schedules()->whereDate('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));
foreach ($container->packingLists as $packingList){
if(!($packingList->owner instanceof Order)) continue;
$user = $packingList->owner->companyModule->employees()->first();
if(app()->environment(['production'])) {
$user->notify(new ShipmentRescheduleEmail($user, $packingList));
}
}
}
}
if($unstuffingDate && $container->status !== ApprovalStatus::COMPLETED){
$container->update(['status' => ApprovalStatus::COMPLETED]);
$container->transports()->first()->update(['drop_date' => $unstuffingDate, 'status' => ApprovalStatus::COMPLETED]);
/** @var PackingList $packingList */
foreach($container->packingLists as $packingList){
if($packingList->status === ApprovalStatus::PENDING_VERIFICATION){
$packingList->status = ApprovalStatus::APPROVED;
$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]);
}
}
}
}
}
if($deliveryDate && !$packingList->transports()->exists()){
$packingList->status = ApprovalStatus::COMPLETED;
$packingList->save();
$deliveryDate = Carbon::parse($deliveryDate);
$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));
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]);
}
}
echo 'successful';
}
} catch (\Exception $exception) {
Log::debug($exception);
}
}
}
@@ -66,6 +66,7 @@ class FetchPackingListFromVTPortalProcessor
}
} catch (GuzzleException $exception) {
dd($exception);
Log::error($exception);
continue;
}
@@ -1,267 +0,0 @@
<?php
namespace App\Classes\Modules\PackingLists\Processors;
use App\Classes\Exceptions\ResourceNotFoundException;
use App\Classes\Modules\Companies\Services\FetchesCompanyModule;
use App\Classes\Modules\Orders\Services\FetchesDataFromYDPortal;
use App\Classes\Modules\Orders\Services\FetchesOrder;
use App\Classes\Modules\PackingLists\DataTransferObjects\PackageObject;
use App\Classes\Modules\PackingLists\DataTransferObjects\PackingListObject;
use App\Classes\Modules\PackingLists\Services\FetchesPackingList;
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;
use App\Classes\Modules\Unity\Processors\CreateContractEntityProcessor;
use App\Classes\Modules\Unity\Services\CreatesContract;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\OrderRoleTypes;
use App\Classes\ValueObjects\Constants\PackageType;
use App\Classes\ValueObjects\Constants\PackingListType;
use App\Classes\ValueObjects\Constants\TransportType;
use App\Models\Order;
use App\Models\PackingList;
use Carbon\Carbon;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class FetchPackingListsFromYdPortalProcessor
{
/** @var FetchesDataFromYDPortal */
private $fetchesDataFRomYDPortal;
/** @var FetchesOrder */
private $fetchesOrder;
/** @var CreatePackingListProcessor */
private $createPackingListProcessor;
/** @var CreatePackageProcessor */
private $createPackageProcessor;
/** @var CreatesTransport */
private $createsTransport;
/** @var FetchesPackingList */
private $fetchesPackingList;
/** @var FetchesCompanyModule */
private $fetchesCompanyModule;
/** @var CreatesContract */
private $unityCreateContract;
/** @var AssignContractEntityProcessor */
private $unityAssignContractEntity;
/** @var CreateContractEntityProcessor */
private $unityCreateContractEntity;
/** @var CreatesStep */
private $createsStep;
/** @var ActivateContractProcessor */
private $unityActivateContract;
/**
* @param FetchesDataFromYDPortal $fetchesDataFRomYDPortal
* @param FetchesOrder $fetchesOrder
* @param CreatePackingListProcessor $createPackingListProcessor
* @param CreatePackageProcessor $createPackageProcessor
* @param CreatesTransport $createsTransport
* @param FetchesPackingList $fetchesPackingList
* @param FetchesCompanyModule $fetchesCompanyModule
* @param CreatesContract $unityCreateContract
* @param AssignContractEntityProcessor $unityAssignContractEntity
* @param CreateContractEntityProcessor $unityCreateContractEntity
* @param CreatesStep $createsStep
* @param ActivateContractProcessor $unityActivateContract
*/
public function __construct(FetchesDataFromYDPortal $fetchesDataFRomYDPortal, FetchesOrder $fetchesOrder, CreatePackingListProcessor $createPackingListProcessor, CreatePackageProcessor $createPackageProcessor, CreatesTransport $createsTransport, FetchesPackingList $fetchesPackingList, FetchesCompanyModule $fetchesCompanyModule, CreatesContract $unityCreateContract, AssignContractEntityProcessor $unityAssignContractEntity, CreateContractEntityProcessor $unityCreateContractEntity, CreatesStep $createsStep, ActivateContractProcessor $unityActivateContract)
{
$this->fetchesDataFRomYDPortal = $fetchesDataFRomYDPortal;
$this->fetchesOrder = $fetchesOrder;
$this->createPackingListProcessor = $createPackingListProcessor;
$this->createPackageProcessor = $createPackageProcessor;
$this->createsTransport = $createsTransport;
$this->fetchesPackingList = $fetchesPackingList;
$this->fetchesCompanyModule = $fetchesCompanyModule;
$this->unityCreateContract = $unityCreateContract;
$this->unityAssignContractEntity = $unityAssignContractEntity;
$this->unityCreateContractEntity = $unityCreateContractEntity;
$this->createsStep = $createsStep;
$this->unityActivateContract = $unityActivateContract;
}
/**
* @param Carbon|null $start
* @param Carbon|null $end
* @return void
* @throws GuzzleException
*/
public function execute(?Carbon $start = null, ?Carbon $end = null)
{
$from = $end ? Carbon::today()->diff($end)->days : 0;
$to = $start ? Carbon::today()->diff($start)->days : 10;
for ($x = $from; $x <= $to; $x++) {
try {
$startDate = Carbon::today()->subDays($x);
$startLimit = Carbon::parse('01-12-2021');
if($startDate->isBefore($startLimit)){
$startDate = $startLimit;
}
$endDate = Carbon::today()->subDays($x - 1);
$orderRequest = $this->fetchesDataFRomYDPortal->clientRequest('http://www.yd-wl.com/api/GetOrderList.ashx', 'GET', [
'begintime' => $startDate->timestamp,
'endtime' => $endDate->timestamp,
]);
$rows = $this->fetchesDataFRomYDPortal->getResponseBody($orderRequest);
if(!$rows->data) continue;
foreach($rows->data as $row){
$time_start = microtime(true);
$receiveDate = Carbon::parse(substr(preg_replace("/[^0-9]/", "", $row->expressno), 0, 8));
$customerno = preg_split('(-|\(|\)|\/)', $row->customerno);
$orderNumber = $customerno[array_key_last($customerno)];
$allow_contract = true;
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;
}
}
$packingListReference = $row->expressno;
try{
$packingList = $this->fetchesPackingList->execute(['reference' => $row->expressno, 'type' => PackingListType::SHIPPING_PACKING_LIST]);
$packingList->packages()->delete();
$replica = $packingList->packingLists()->where('type', PackingListType::SHIPPING_PACKING_LIST_REPLICA)->first();
if($replica) $replica->packages()->delete();
$warehouseReceiveList = $this->fetchesPackingList->execute(['reference' => $row->expressno, 'type' => PackingListType::WAREHOUSE_RECEIVE_LIST]);
$warehouseReceiveList->packages()->delete();
$replica = $warehouseReceiveList->packingLists()->where('type', PackingListType::WAREHOUSE_RECEIVE_LIST_REPLICA)->first();
if($replica) $replica->packages()->delete();
} catch (ResourceNotFoundException $exception) {
if (!$allow_contract) {
$appointee_id = 2307;
} else {
$appointee_id = $order->orderRoles()->where('role_id', '=', OrderRoleTypes::ORIGIN_FREIGHT_FORWARDER)->first()->appointee->id;
}
$warehouseReceiveObject = new PackingListObject($packingListReference, $appointee_id, PackingListType::WAREHOUSE_RECEIVE_LIST, $allow_contract ? ApprovalStatus::APPROVED : ApprovalStatus::REJECTED);
/** @var PackingList $warehouseReceiveList */
$warehouseReceiveList = $this->createPackingListProcessor->execute($warehouseReceiveObject, $order);
$transportObject = new TransportObject(TransportType::LAND, null, $row->kuaidilist, Carbon::parse($receiveDate), Carbon::parse($receiveDate), $allow_contract ? ApprovalStatus::APPROVED : ApprovalStatus::REJECTED);
$transport = $this->createsTransport->execute($transportObject, $warehouseReceiveList);
if ($allow_contract) {
$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);
}
$packingListObject = new PackingListObject($packingListReference, $appointee_id, PackingListType::SHIPPING_PACKING_LIST, ApprovalStatus::SUSPENDED, !$allow_contract ? null : $contractReference);
/** @var PackingList $packingList */
$packingList = $this->createPackingListProcessor->execute($packingListObject, $order);
if ($allow_contract) {
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);
}
}
}
foreach($row->deliverysize as $package) {
$packageObject = new PackageObject(PackageType::CARTON, $row->goodname, (float) $package->width, (float) $package->height, (float) $package->length, 0, (float) $package->num, ApprovalStatus::APPROVED);
$this->createPackageProcessor->execute($packageObject, $warehouseReceiveList);
$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'));
if($overWeightCbm > 0){
$measurement = round($overWeightCbm ** (1/3) * 100, 2);
$packageObject = new PackageObject(PackageType::OVER_WEIGHT, 'Overweight CBM', (float) $measurement, (float) $measurement, (float) $measurement, 0, 1, ApprovalStatus::APPROVED);
$this->createPackageProcessor->execute($packageObject, $packingList);
}
if($order instanceof Order){
$marking = $order->companyModule->inviters()->withPivot('invitee_reference')->first()->pivot->invitee_reference;
if(!in_array($marking, ['1290CSW', '8997ITB', '3992WHE', '962LOW', '1152AAT'])){
$this->fetchesDataFRomYDPortal->clientRequest('http://www.yd-wl.com/api/confirmsendorder.ashx', 'GET', [
'expressno' => $row->expressno
]);
}
}
$time_end = microtime(true);
$execution_time = ($time_end - $time_start)/60;
echo 'successful => <b>Total Execution Time:</b> '.$execution_time.' Mins<br>';
}
} catch (\Exception $exception) {
Log::debug($exception);
}
}
}
}
@@ -152,7 +152,7 @@ class FetchWarehouseReceiveListFromVTPortalProcessor
} catch (ResourceNotFoundException $exception) {
$allow_contract = false;
$order = $this->fetchesCompanyModule->execute(['id' => 1]);
$appointee_id = 2307;
$appointee_id = 2037;
}
$packingListReference = $parcel[0];
@@ -3,13 +3,12 @@
namespace App\Classes\Modules\Transactions\ControllersLogic;
use App\Classes\Modules\Transactions\Processors\ApproveShippingInvoiceTransactionProcessor;
use App\Classes\Notifications\InvoiceIssuedEmail;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Mccarlosen\LaravelMpdf\Facades\LaravelMpdf;
use Meneses\LaravelMpdf\Facades\LaravelMpdf;
use App\Classes\ValueObjects\Constants\DocumentType;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\TransactionType;
@@ -37,17 +36,29 @@ class ApproveShippingInvoiceTransactionLogic extends AbstractControllerLogic
/** @var FetchesPackingList */
private $fetchesPackingList;
/** @var ApproveShippingInvoiceTransactionProcessor */
private $approveShippingInvoiceTransactionProcessor;
/** @var UpdatesTransactionStatus */
private $updatesTransactionStatus;
/** @var CreatesDocument */
private $createsDocument;
/** @var CreatesFiles */
private $createsFiles;
/**
* ApprovePaymentVerificationLogic constructor.
* @param FetchesPackingList $fetchesPackingList
* @param ApproveShippingInvoiceTransactionProcessor $approveShippingInvoiceTransactionProcessor
* @param UpdatesTransactionStatus $updatesTransactionStatus
* @param CreatesDocument $createsDocument
* @param CreatesFiles $createsFiles
* @param CreateInvoiceTransactionProcessor $createInvoiceTransactionProcessor
*/
public function __construct(FetchesPackingList $fetchesPackingList, ApproveShippingInvoiceTransactionProcessor $approveShippingInvoiceTransactionProcessor)
public function __construct(FetchesPackingList $fetchesPackingList, UpdatesTransactionStatus $updatesTransactionStatus, CreatesDocument $createsDocument, CreatesFiles $createsFiles)
{
$this->fetchesPackingList = $fetchesPackingList;
$this->approveShippingInvoiceTransactionProcessor = $approveShippingInvoiceTransactionProcessor;
$this->updatesTransactionStatus = $updatesTransactionStatus;
$this->createsDocument = $createsDocument;
$this->createsFiles = $createsFiles;
}
/**
@@ -58,8 +69,29 @@ class ApproveShippingInvoiceTransactionLogic extends AbstractControllerLogic
public function logic(Request $request) : JsonResponse
{
$packing_list = $this->fetchesPackingList->execute(['id' => $request->route('id')]);
$this->approveShippingInvoiceTransactionProcessor->execute($packing_list);
$invoice_transaction = $packing_list->transactions()->where('transactions.type', TransactionType::SHIPPING_INVOICE)->whereIn('status', [ApprovalStatus::PENDING_VERIFICATION, ApprovalStatus::PENDING_SUBMISSION])->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);
$user = $packing_list->owner->companyModule->employees()->first();
if(app()->environment(['production'])) {
$user->notify(new InvoiceIssuedEmail($user, $packing_list));
}
return $this->response([]);
}
@@ -23,7 +23,7 @@ use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Mccarlosen\LaravelMpdf\Facades\LaravelMpdf;
use Meneses\LaravelMpdf\Facades\LaravelMpdf;
class CreatePaymentTransactionLogic extends AbstractControllerLogic
{
@@ -5,15 +5,40 @@ namespace App\Classes\Modules\Transactions\ControllersLogic;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\PackingLists\Services\FetchesPackingList;
use App\Classes\Modules\Transactions\Processors\CreateInvoiceTransactionProcessor;
use App\Classes\Modules\SegmentConstants\Services\FetchesSegmentConstant;
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\PackingListType;
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\Models\Document;
use App\Models\PackingList;
use App\Models\Transaction;
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;
class CreateShippingInvoiceTransactionLogic extends AbstractControllerLogic
{
/**
* @return array
*/
@@ -27,26 +52,217 @@ class CreateShippingInvoiceTransactionLogic extends AbstractControllerLogic
/** @var FetchesPackingList */
private $fetchesPackingList;
/** @var CreateInvoiceTransactionProcessor */
private $createInvoiceTransactionProcessor;
/** @var FetchesSegmentConstant */
private $fetchesSegmentConstant;
/**
* @param FetchesPackingList $fetchesPackingList
* @param CreateInvoiceTransactionProcessor $createInvoiceTransactionProcessor
*/
public function __construct(FetchesPackingList $fetchesPackingList, CreateInvoiceTransactionProcessor $createInvoiceTransactionProcessor)
/** @var GeneratesTransactionBillNumber */
private $generatesTransactionBillNumber;
/** @var CreatesTransaction */
private $createsTransaction;
/** @var CreatesTransactionDetail */
private $createsTransactionDetail;
/** @var CreatesDocument */
private $createsDocument;
/** @var CreatesFiles */
private $createsFile;
public function __construct(
FetchesPackingList $fetchesPackingList,
FetchesSegmentConstant $fetchesSegmentConstant,
GeneratesTransactionBillNumber $generatesTransactionBillNumber,
CreatesTransaction $createsTransaction,
CreatesTransactionDetail $createsTransactionDetail,
CreatesDocument $createsDocument,
CreatesFiles $createsFile
)
{
$this->fetchesPackingList = $fetchesPackingList;
$this->createInvoiceTransactionProcessor = $createInvoiceTransactionProcessor;
$this->fetchesSegmentConstant = $fetchesSegmentConstant;
$this->generatesTransactionBillNumber = $generatesTransactionBillNumber;
$this->createsTransaction = $createsTransaction;
$this->createsTransactionDetail = $createsTransactionDetail;
$this->createsDocument = $createsDocument;
$this->createsFile = $createsFile;
}
public function logic(Request $request) : JsonResponse
{
$packing_list = $this->fetchesPackingList->execute(['id' => $request->input('packing_list_id')]);
$this->createInvoiceTransactionProcessor->execute($packing_list);
$packing_list = PackingList::where('reference', $packing_list->reference)->where('type', PackingListType::SHIPPING_PACKING_LIST)->first();
$billable_packing_list = $packing_list->packingLists()->first();
$billable_packing_list = $billable_packing_list ? $billable_packing_list : $packing_list;
$cbm = round($billable_packing_list->packages->where('type', '!=', PackageType::OVER_WEIGHT)->sum(function($package) {
return ($package->width / 100) * ($package->height / 100) *($package->length / 100) * ($package->quantity);
}), 3);
$over_weight_cbm = round($billable_packing_list->packages->where('type', PackageType::OVER_WEIGHT)->sum(function($package) {
return ($package->width / 100) * ($package->height / 100) *($package->length / 100) * ($package->quantity);
}), 3);
$order = $packing_list->owner;
$companyModule = $order->companyModule;
$connection = $companyModule->connections()->first();
$address = $order->addresses()->first();
$base_price_constant = $this->fetchesSegmentConstant->execute(['segment_id' => 1, 'reference' => SegmentConstants::BASE_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]);
$noMinimumCharge = $connection->segments()->where('segments.id', 2)->first();
$base_price = 0;
$warehouse_rate = 0;
$state_rate = 0;
$minimum_cbm = 0.3;
$segment_price = 0;
$state_select = '';
$segment_price = $connection->segments()->whereHas('constants', function($query){
return $query->where('reference', SegmentConstants::CUSTOM_PRICE);
})->get()->map(function($segment){
return (float) $segment->constants()->first()->value[0];
})->sort()->first();
$segment_price = $segment_price ? $segment_price : 0;
$packing_list_drop_date = 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;
$stateId = $address->state_id;
$state_rate_constant = $this->getConstantByKey($state_rate_constant, $stateId);
// 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[$state_select];
$container = $packing_list->containers()->first();
$containerPackingLists = collect();
$hasMinimumCharge = null;
foreach ($container->packingLists as $packingList){
if($packingList->owner->companyModule->id !== $companyModule->id) continue;
$containerPackingLists->push($packingList);
if(!$hasMinimumCharge) {
$hasMinimumCharge = $packingList->transactions()->whereHas('transactionDetails', function ($query){
$query->where('reference', 'MIN_CBM_CHARGES');
})->first();
}
}
$totalContainerCbm = $containerPackingLists->sum(function($packingList){
$billable_packing_list = $packingList->packingLists()->first();
$billable_packing_list = $billable_packing_list ? $billable_packing_list : $packingList;
return $billable_packing_list->packages->where('type', '!=', PackageType::OVER_WEIGHT)->sum(function($package) {
return ($package->width / 100) * ($package->height / 100) *($package->length / 100) * ($package->quantity);
});
});
$minimum_charge = $minimum_cbm - $totalContainerCbm;
$minimum_charge = $minimum_charge < 0 ? 0 : $minimum_charge;
$minimum_charge = $noMinimumCharge ? 0 : $minimum_charge;
$minimum_charge = $noMinimumCharge ? 0 : round($minimum_charge, 3);
if($hasMinimumCharge) {
$minimum_charge = 0;
}
$price_cbm = $base_price + $segment_price + $warehouse_rate + $state_rate;
$total_cbm = $price_cbm * ($cbm + $minimum_charge + $over_weight_cbm);
$billNumber = $this->generatesTransactionBillNumber->execute('SHIP-');
$object = new TransactionObject(
$billNumber,
TransactionType::SHIPPING_INVOICE,
1,
$order->company_module_id,
1,
PaymentMethodType::CASH,
$total_cbm,
$total_cbm,
1,
1,
0,
0,
0,
null,
ApprovalStatus::PENDING_SUBMISSION
);
/** @var Transaction $invoice_transaction */
$invoice_transaction = $this->createsTransaction->execute($packing_list, $object);
$object_detail = new TransactionDetailObject(
'SHIPPING_FEE',
TransactionDetailType::SHIPPING_FEE.'<br>'.round($packing_list->packages->where('type', '!=', PackageType::OVER_WEIGHT)->sum('quantity'), 3).' CTNS - '.round($cbm, 3).' 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);
}
if ($minimum_charge > 0) {
$object_detail = new TransactionDetailObject(
'MIN_CBM_CHARGES',
TransactionDetailType::MIN_CBM_CHARGES,
$minimum_charge,
$price_cbm
);
$this->createsTransactionDetail->execute($invoice_transaction, $object_detail);
}
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;
}
}
}
@@ -27,7 +27,7 @@ use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Meneses\LaravelLaravelMpdf\Facades\LaravelLaravelMpdf;
use Mccarlosen\LaravelMpdf\Facades\LaravelMpdf;
use Meneses\LaravelMpdf\Facades\LaravelMpdf;
class CreateSupplierTransactionLogic extends AbstractControllerLogic
{
@@ -7,7 +7,7 @@ use App\Models\Transaction;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Storage;
use Mccarlosen\LaravelMpdf\Facades\LaravelMpdf;
use Meneses\LaravelMpdf\Facades\LaravelMpdf;
use App\Classes\ValueObjects\Constants\DocumentType;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\TransactionType;
@@ -0,0 +1,204 @@
<?php
namespace App\Classes\Modules\Transactions\ControllersLogic;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Transactions\Standards\Rules\CanCreateTransaction;
use App\Classes\Modules\Transactions\Standards\Rules\CanCreateTransactionDetail;
use App\Classes\Modules\Transactions\DataTransferObjects\TransactionObject;
use App\Classes\Modules\Transactions\DataTransferObjects\TransactionDetailObject;
use App\Classes\Modules\Transactions\Services\CreatesTransaction;
use App\Classes\Modules\Transactions\Services\CreatesTransactionDetail;
use App\Classes\Modules\Transactions\Services\GeneratesTransactionBillNumber;
use App\Http\Resources\TransactionResource;
use App\Http\Resources\TransactionDetailResource;
use App\Classes\Modules\Receipts\Standards\Rules\CanCreateReceipt;
use App\Classes\Modules\Receipts\Standards\Rules\CanCreateReceiptDetail;
use App\Classes\Modules\Receipts\DataTransferObjects\ReceiptObject;
use App\Classes\Modules\Receipts\DataTransferObjects\ReceiptDetailObject;
use App\Classes\Modules\Receipts\Services\CreatesReceipt;
use App\Classes\Modules\Receipts\Services\CreatesReceiptDetail;
use App\Classes\Modules\Receipts\Services\GeneratesReceiptBillNo;
use App\Classes\Modules\Currencies\Services\FetchesCurrency;
use App\Classes\Modules\Currencies\Services\RateCalculatesCurrency;
use App\Classes\Modules\Transactions\Services\FetchesTransaction;
use App\Classes\Modules\Transactions\Services\FetchesTransactionDetail;
use App\Classes\Modules\Companies\Services\FetchesCompany;
use ErrorException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\Transaction;
use App\Models\multipleInvoicesWithOnePayment;
use App\Classes\ValueObjects\Constants\TransactionType;
use App\Classes\Modules\Wallets\Services\UpdatesWalletBalance;
use App\Classes\ValueObjects\Constants\PaymentMethodType;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\Modules\Billplzs\Services\CreatesBillplzBill;
use App\Classes\Modules\Wallets\DataTransferObjects\WalletObject;
use App\Classes\Modules\Wallets\Services\GeneratesWalletCode;
use App\Classes\Modules\Wallets\Services\CreatesWallet;
use APP\models\PackingList;
class multipleInvoicesWithOnePaymentLogic extends AbstractControllerLogic
{
/**
* @return array
*/
protected function notification():array {
return [
'title' => 'Created Transaction',
'message' => 'You have successfully created a transaction'
];
}
/** @var GeneratesTransactionBillNumber */
private $generatesTransactionBillNo;
/** @var CanCreateTransaction */
private $canCreateTransaction;
private $fetchesCurrency;
private $rateCalculatesCurrency;
private $fetchesCompany;
private $createsTransaction;
private $canCreateTransactionDetail;
private $createsTransactionDetail;
private $fetchesTransaction;
private $fetchesTransactionDetail;
private $generatesReceiptBillNo;
/** @var CanCreateReceipt */
private $canCreateReceipt;
private $createsReceipt;
private $canCreateReceiptDetail;
private $createsReceiptDetail;
public function __construct(
GeneratesTransactionBillNumber $generatesTransactionBillNo, CanCreateTransaction $canCreateTransaction,
FetchesCurrency $fetchesCurrency, RateCalculatesCurrency $rateCalculatesCurrency, FetchesCompany $fetchesCompany,
CreatesTransaction $createsTransaction,
CanCreateTransactionDetail $canCreateTransactionDetail, CreatesTransactionDetail $createsTransactionDetail,
FetchesTransaction $fetchesTransaction , FetchesTransactionDetail $fetchesTransactionDetail,
GeneratesReceiptBillNo $generatesReceiptBillNo, CanCreateReceipt $canCreateReceipt,
CreatesReceipt $createsReceipt,
CanCreateReceiptDetail $canCreateReceiptDetail, CreatesReceiptDetail $createsReceiptDetail
){
$this->generatesTransactionBillNo = $generatesTransactionBillNo;
$this->canCreateTransaction = $canCreateTransaction;
$this->fetchesCurrency = $fetchesCurrency;
$this->rateCalculatesCurrency = $rateCalculatesCurrency;
$this->fetchesCompany = $fetchesCompany;
$this->createsTransaction =$createsTransaction;
$this->canCreateTransactionDetail =$canCreateTransactionDetail;
$this->createsTransactionDetail = $createsTransactionDetail;
$this->fetchesTransaction = $fetchesTransaction;
$this->fetchesTransactionDetail = $fetchesTransactionDetail;
$this->generatesReceiptBillNo = $generatesReceiptBillNo;
$this->canCreateReceipt = $canCreateReceipt;
$this->createsReceipt =$createsReceipt;
$this->canCreateReceiptDetail =$canCreateReceiptDetail;
$this->createsReceiptDetail = $createsReceiptDetail;
}
/**
* @param Request $request
* @return JsonResponse
* @throws ErrorException
*/
public function logic( $transactionsArray) : JsonResponse
{
// dd($request);
try {
// dd(json_decode($transactionsArray));
$transactions = Transaction::whereIn('id', json_decode($transactionsArray))->where('type', TransactionType::SHIPPING_INVOICE)->get();
$total = $transactions->sum('amount');
$packingList =$transactions[1]->owner;
$order = $packingList->owner;
$companyModule = $order->companyModule;
$company = $companyModule->company;
$wallet = $company->wallets()->first();
if (!$wallet) {
$object = new WalletObject($company->id, 1, (App()->make(GeneratesWalletCode::class))->execute());
/** @var Wallet $wallet */
$wallet = (App()->make(CreatesWallet::class))->execute($object, $company);
}
$billNumber = (App()->make(GeneratesTransactionBillNumber::class))->execute('TOPUP-');
if($total < 0) {
throw new MalformedRequestException('Top up credit value must be greater than zero.');
}
$billPlzBill = (App()->make(CreatesBillplzBill::class))->execute($company->name, 'example@gmail.com', 'This payment is credit topup for company ref. ' . $company->reference, $total, $billNumber, 'bank code', true);
$transaction_object = new TransactionObject($billNumber, TransactionType::TOP_UP, 1, $company->id, 1, PaymentMethodType::PAYMENT_GATEWAY, $total, $total, 1, 1, 1, 0, 0, null, ApprovalStatus::PENDING_SUBMISSION, [], 'test');
// $transaction = $this->createsTransaction->execute($wallet, $transaction_object);
$transaction = (App()->make(CreatesTransaction::class))->execute($wallet, $transaction_object);
$result= (App()->make(UpdatesWalletBalance::class))->execute($wallet, $total);
foreach ($transactions as $key => $value) {
multipleInvoicesWithOnePayment::create([ 'topUp_request_id' => $transaction->id, 'transaction_id' => $value->id ]);
}
return $this->response([]); ;
} catch (\Exception $exception) {
throw new ErrorException($exception->getMessage(), $exception->getCode());
}
}
public function verifypayment( $topUp_transaction_id, $amount) : JsonResponse
{
$totalamount =0;
$topup = multipleInvoicesWithOnePayment::where('topUp_request_id',$topUp_transaction_id)->get();
foreach ($topup as $key => $value) {
$transaction = Transaction::where('id',$value->transaction_id)->frist();
$totalamount += $transaction->amount;
(App()->make(updatesTransactionStatus::class))->execute($transaction, ApprovalStatus::APPROVED);
$transaction_object = new TransactionObject($transaction->bill_no, TransactionType::PAYMENT, 1, $topUp_transaction_id, 1, PaymentMethodType::PAYMENT_GATEWAY, $transaction->amount, $transaction->amount, 1, 1, 1, 0, 0, null, ApprovalStatus::APPROVED, [], 'test');
$transaction = (App()->make(CreatesTransaction::class))->execute($transaction, $transaction_object);
}
$amount = $amount - $totalamount;
Transaction::where('id', $topUp_transaction_id)->update(['amount'=> $amount]);
}
}
@@ -1,78 +0,0 @@
<?php
namespace App\Classes\Modules\Transactions\Processors;
use App\Classes\Exceptions\MalformedRequestException;
use App\Classes\Notifications\InvoiceIssuedEmail;
use App\Models\Document;
use App\Models\PackingList;
use App\Models\Transaction;
use Mccarlosen\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\Modules\Documents\Services\CreatesDocument;
use App\Classes\Modules\Documents\DataTransferObjects\DocumentObject;
use App\Classes\Modules\Transactions\Services\UpdatesTransactionStatus;
class ApproveShippingInvoiceTransactionProcessor
{
/** @var UpdatesTransactionStatus */
private $updatesTransactionStatus;
/** @var CreatesDocument */
private $createsDocument;
/** @var CreatesFiles */
private $createsFiles;
/**
* @param UpdatesTransactionStatus $updatesTransactionStatus
* @param CreatesDocument $createsDocument
* @param CreatesFiles $createsFiles
*/
public function __construct(UpdatesTransactionStatus $updatesTransactionStatus, CreatesDocument $createsDocument, CreatesFiles $createsFiles)
{
$this->updatesTransactionStatus = $updatesTransactionStatus;
$this->createsDocument = $createsDocument;
$this->createsFiles = $createsFiles;
}
/**
* @param PackingList $packingList
* @throws MalformedRequestException
*/
public function execute(PackingList $packingList)
{
/** @var Transaction $invoice_transaction */
$invoice_transaction = $packingList->transactions()->where('transactions.type', TransactionType::SHIPPING_INVOICE)->whereIn('status', [ApprovalStatus::PENDING_VERIFICATION, ApprovalStatus::PENDING_SUBMISSION])->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);
$user = $packingList->owner->companyModule->employees()->first();
if(app()->environment(['production'])) {
$user->notify(new InvoiceIssuedEmail($user, $packingList));
}
return;
}
}
@@ -1,247 +1,229 @@
<?php
namespace App\Classes\Modules\Transactions\Processors;
use App\Classes\Exceptions\MalformedRequestException;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\PackingLists\Services\FetchesPackingList;
use App\Classes\Modules\SegmentConstants\Services\FetchesSegmentConstant;
use App\Classes\Modules\Transactions\Services\GeneratesTransactionBillNumber;
use App\Classes\Modules\Bookings\Services\CalculatesBookingTransferredAmount;
use App\Classes\Modules\ServiceTypes\Services\FetchesServiceConfigurations;
use App\Classes\Modules\Transactions\Services\ListsTransactions;
use App\Classes\Modules\Transactions\Services\CreatesTransaction;
use App\Classes\Modules\Transactions\Services\CreatesTransactionDetail;
use App\Classes\Modules\Transactions\Services\GeneratesTransactionBillNumber;
use App\Classes\Modules\Bookings\Services\CalculatesBookingPaidAmount;
use App\Classes\Modules\Bookings\Services\CalculatesBookingCurrencyAverageRate;
use App\Classes\Modules\Companies\Services\FetchesCompany;
use App\Classes\Modules\Documents\Services\CreatesDocument;
use App\Classes\Modules\Documents\Services\CreatesFiles;
use App\Classes\Modules\Bookings\Services\UpdatesBookingStatus;
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\PackingListType;
use App\Classes\ValueObjects\Constants\TransactionType;
use App\Classes\ValueObjects\Constants\PaymentMethodType;
use App\Classes\Modules\Documents\DataTransferObjects\DocumentObject;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\PackageType;
use App\Classes\ValueObjects\Constants\SegmentConstants;
use App\Classes\ValueObjects\Constants\TransactionDetailType;
use App\Models\CompanyModule;
use App\Classes\ValueObjects\Constants\TransactionType;
use App\Classes\ValueObjects\Constants\DocumentType;
use App\Models\Booking;
use App\Models\Document;
use App\Models\PackingList;
use App\Models\Transaction;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Mccarlosen\LaravelMpdf\Facades\LaravelMpdf;
use App\Models\SegmentConstant;
use Meneses\LaravelMpdf\Facades\LaravelMpdf;
class CreateInvoiceTransactionProcessor
{
/** @var FetchesPackingList */
private $fetchesPackingList;
/** @var FetchesSegmentConstant */
private $fetchesSegmentConstant;
/** @var GeneratesTransactionBillNumber */
private $generatesTransactionBillNumber;
/** @var ListsTransactions */
private $listsTransactions;
/** @var CreatesTransaction */
private $createsTransaction;
/** @var CreatesTransactionDetail */
private $createsTransactionDetail;
/** @var GeneratesTransactionBillNumber */
private $generatesTransactionBillNumber;
/** @var CalculatesBookingPaidAmount */
private $calculatesBookingPaidAmount;
/** @var CalculatesBookingTransferredAmount */
private $calculatesBookingTransferredAmount;
/** @var FetchesServiceConfigurations */
private $fetchesServiceConfigurations;
/** @var CalculatesBookingCurrencyAverageRate */
private $calculatesBookingCurrencyAverageRate;
/** @var FetchesCompany */
private $fetchesCompany;
/** @var CreatesDocument */
private $createsDocument;
/** @var CreatesFiles */
private $createsFile;
/** @var UpdatesBookingStatus */
private $updatesBookingStatus;
/**
* @param FetchesPackingList $fetchesPackingList
* @param FetchesSegmentConstant $fetchesSegmentConstant
* @param GeneratesTransactionBillNumber $generatesTransactionBillNumber
* CreateInvoiceTransactionProcessor constructor.
* @param ListsTransactions $listsTransactions
* @param CreatesTransaction $createsTransaction
* @param CreatesTransactionDetail $createsTransactionDetail
* @param GeneratesTransactionBillNumber $generatesTransactionBillNumber
* @param CalculatesBookingPaidAmount $calculatesBookingPaidAmount
* @param CalculatesBookingTransferredAmount $calculatesBookingTransferredAmount
* @param FetchesServiceConfigurations $fetchesServiceConfigurations
* @param CalculatesBookingCurrencyAverageRate $calculatesBookingCurrencyAverageRate
* @param FetchesCompany $fetchesCompany
* @param CreatesDocument $createsDocument
* @param CreatesFiles $createsFile
* @param UpdatesBookingStatus $updatesBookingStatus
*/
public function __construct(FetchesPackingList $fetchesPackingList, FetchesSegmentConstant $fetchesSegmentConstant, GeneratesTransactionBillNumber $generatesTransactionBillNumber, CreatesTransaction $createsTransaction, CreatesTransactionDetail $createsTransactionDetail)
public function __construct(ListsTransactions $listsTransactions, CreatesTransaction $createsTransaction, GeneratesTransactionBillNumber $generatesTransactionBillNumber, CalculatesBookingPaidAmount $calculatesBookingPaidAmount, CalculatesBookingTransferredAmount $calculatesBookingTransferredAmount, FetchesServiceConfigurations $fetchesServiceConfigurations, CalculatesBookingCurrencyAverageRate $calculatesBookingCurrencyAverageRate, FetchesCompany $fetchesCompany, CreatesDocument $createsDocument, CreatesFiles $createsFile, UpdatesBookingStatus $updatesBookingStatus)
{
$this->fetchesPackingList = $fetchesPackingList;
$this->fetchesSegmentConstant = $fetchesSegmentConstant;
$this->generatesTransactionBillNumber = $generatesTransactionBillNumber;
$this->listsTransactions = $listsTransactions;
$this->createsTransaction = $createsTransaction;
$this->createsTransactionDetail = $createsTransactionDetail;
$this->generatesTransactionBillNumber = $generatesTransactionBillNumber;
$this->calculatesBookingPaidAmount = $calculatesBookingPaidAmount;
$this->calculatesBookingTransferredAmount = $calculatesBookingTransferredAmount;
$this->fetchesServiceConfigurations = $fetchesServiceConfigurations;
$this->calculatesBookingCurrencyAverageRate = $calculatesBookingCurrencyAverageRate;
$this->fetchesCompany = $fetchesCompany;
$this->createsDocument = $createsDocument;
$this->createsFile = $createsFile;
$this->updatesBookingStatus = $updatesBookingStatus;
}
/**
* @throws MalformedRequestException
* @param Booking $booking
* @return void
* @throws \App\Classes\Exceptions\MalformedRequestException
*/
public function execute(PackingList $packingList)
public function execute(Booking $booking)
{
$packing_list = PackingList::where('reference', $packingList->reference)->where('type', PackingListType::SHIPPING_PACKING_LIST)->first();
$billable_packing_list = $packing_list->packingLists()->first();
$billable_packing_list = $billable_packing_list ? $billable_packing_list : $packing_list;
$cbm = round($billable_packing_list->packages->where('type', '!=', PackageType::OVER_WEIGHT)->sum(function($package) {
return ($package->width / 100) * ($package->height / 100) *($package->length / 100) * ($package->quantity);
}), 3);
$over_weight_cbm = round($billable_packing_list->packages->where('type', PackageType::OVER_WEIGHT)->sum(function($package) {
return ($package->width / 100) * ($package->height / 100) *($package->length / 100) * ($package->quantity);
}), 3);
$order = $packing_list->owner;
$companyModule = $order->companyModule;
$connection = $companyModule->connections()->first();
$address = $order->addresses()->first();
$base_price_constant = $this->fetchesSegmentConstant->execute(['segment_id' => 1, 'reference' => SegmentConstants::BASE_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]);
$noMinimumCharge = $connection->segments()->where('segments.id', 2)->first();
$minimum_cbm = 0.3;
$state_select = '';
$segment_price = $connection->segments()->whereHas('constants', function($query){
return $query->where('reference', SegmentConstants::CUSTOM_PRICE);
})->get()->map(function($segment){
return (float) $segment->constants()->first()->value[0];
})->sort()->first();
$segment_price = $segment_price ? $segment_price : 0;
$arrivalTransport = PackingList::where('reference', $packing_list->reference)->where('type', 1)->first()->transports->first();
if(!$arrivalTransport) {
throw new MalformedRequestException('Arrival date is unknow can\'t generate invoice');
}
$packing_list_drop_date = $arrivalTransport->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;
$stateId = $address->state_id;
$state_rate_constant = $this->getConstantByKey($state_rate_constant, $stateId);
// 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[$state_select];
$container = $packing_list->containers()->first();
$containerPackingLists = collect();
$hasMinimumCharge = null;
foreach ($container->packingLists as $packingList){
if($packingList->owner instanceof CompanyModule) continue;
if($packingList->owner->companyModule->id !== $companyModule->id) continue;
$containerPackingLists->push($packingList);
if(!$hasMinimumCharge) {
$hasMinimumCharge = $packingList->transactions()->whereHas('transactionDetails', function ($query){
$query->where('reference', 'MIN_CBM_CHARGES');
})->first();
}
$payment_amount = $this->calculatesBookingTransferredAmount->execute($booking, $booking->fix_currency_id);
$booking_amount = $booking->fix_amount;
if ((float) $booking_amount !== (float) $payment_amount) {
return;
}
$totalContainerCbm = $containerPackingLists->sum(function($packingList){
$billable_packing_list = $packingList->packingLists()->first();
$billable_packing_list = $billable_packing_list ? $billable_packing_list : $packingList;
return $billable_packing_list->packages->sum(function($package) {
return ($package->width / 100) * ($package->height / 100) *($package->length / 100) * ($package->quantity);
});
});
$po_order_transaction = $booking->transactions()
->where('type', TransactionType::PURCHASE_ORDER)
->complete()
->first();
$minimum_charge = $minimum_cbm - $totalContainerCbm;
$minimum_charge = ($minimum_charge < 0) ? 0 : $minimum_charge;
$minimum_charge = $noMinimumCharge ? 0 : $minimum_charge;
$constants = SegmentConstant::where('reference', SegmentConstants::SERVICE_TYPE)->where('detail->id', $booking->service->id)->first();
$minimum_charge = $noMinimumCharge ? 0 : round($minimum_charge, 3);
if($hasMinimumCharge) {
$minimum_charge = 0;
if($constants->detail->is_billable && !$po_order_transaction) {
return;
}
$price_cbm = $base_price + $segment_price + $warehouse_rate + $state_rate;
$transaction = $booking->transactions()
->where('type', TransactionType::PAYMENT)
->first();
$total_cbm = $price_cbm * ($cbm + $minimum_charge + $over_weight_cbm);
$billNumber = $this->generatesTransactionBillNumber->execute('INV-');
$billNumber = $this->generatesTransactionBillNumber->execute('SHIP-');
$booking_currency_average_rate = $this->calculatesBookingCurrencyAverageRate->execute($booking, TransactionType::PAYMENT);
$object = new TransactionObject(
$total_service_charge = $booking->transactions()
->where('type', TransactionType::PAYMENT)
->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED])
->sum('service_charge');
$total_tax = $booking->transactions()
->where('type', TransactionType::PAYMENT)
->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED])
->sum('tax');
$transaction_object = new TransactionObject(
$billNumber,
TransactionType::SHIPPING_INVOICE,
1,
$order->company_module_id,
1,
PaymentMethodType::CASH,
$total_cbm,
$total_cbm,
1,
1,
0,
0,
0,
TransactionType::INVOICE,
$transaction->issuer,
$transaction->receiver,
$transaction->recipient_bank_account_id,
$transaction->payment_method,
$payment_amount,
$booking_amount,
$transaction->currency_id,
$transaction->original_currency_id,
$booking_currency_average_rate,
$total_tax,
$total_service_charge,
null,
ApprovalStatus::PENDING_SUBMISSION
ApprovalStatus::APPROVED
);
$invoice_transaction = $this->createsTransaction->execute($po_order_transaction->booking, $transaction_object);
$supplier = $this->fetchesCompany->execute(['id' => $transaction->receiver]);
$purchase_order_pdf = LaravelMpdf::loadView('pages.pdfs.purchase_order', ['invoice_transaction' => $invoice_transaction, 'po_order_transaction' => $po_order_transaction, 'supplier' => $supplier]);
$document_object = new DocumentObject(
DocumentType::PURCHASE_ORDER,
[chunk_split('data:application/pdf;base64,'.base64_encode($purchase_order_pdf->output()))],
'',
ApprovalStatus::COMPLETED,
'purchase_orders'
);
$document = $this->createsDocument->execute($po_order_transaction->booking, $document_object);
$this->createsFile->execute($document, $document_object);
$deliver_order_pdf = LaravelMpdf::loadView('pages.pdfs.deliver_order', ['invoice_transaction' => $invoice_transaction, 'po_order_transaction' => $po_order_transaction, 'supplier' => $supplier]);
$document_object = new DocumentObject(
DocumentType::DELIVER_ORDER,
[chunk_split('data:application/pdf;base64,'.base64_encode($deliver_order_pdf->output()))],
'',
ApprovalStatus::COMPLETED,
'delivery_orders'
);
/** @var Transaction $invoice_transaction */
$invoice_transaction = $this->createsTransaction->execute($packing_list, $object);
/** @var Document $document */
$document = $this->createsDocument->execute($po_order_transaction->booking, $document_object);
$this->createsFile->execute($document, $document_object);
$object_detail = new TransactionDetailObject(
'SHIPPING_FEE',
TransactionDetailType::SHIPPING_FEE.'<br>'.round($packing_list->packages->where('type', '!=', PackageType::OVER_WEIGHT)->sum('quantity'), 3).' CTNS - '.round($cbm, 3).' CBM',
$cbm,
$price_cbm
$invoice_pdf = LaravelMpdf::loadView('pages.pdfs.invoice', ['invoice_transaction' => $invoice_transaction, 'po_order_transaction' => $po_order_transaction, 'supplier' => $supplier]);
$document_object = new DocumentObject(
DocumentType::INVOICE,
[chunk_split('data:application/pdf;base64,'.base64_encode($invoice_pdf->output()))],
'',
ApprovalStatus::COMPLETED,
'invoices'
);
$document = $this->createsDocument->execute($po_order_transaction->booking, $document_object);
$this->createsFile->execute($document, $document_object);
$this->createsTransactionDetail->execute($invoice_transaction, $object_detail);
$billNumber = $this->generatesTransactionBillNumber->execute('SPDO-');
if ($over_weight_cbm > 0) {
$object_detail = new TransactionDetailObject(
'OVER_WEIGHT_CHARGES',
TransactionDetailType::OVER_WEIGHT_CHARGES,
$over_weight_cbm,
$price_cbm
);
$booking_currency_average_rate = $this->calculatesBookingCurrencyAverageRate->execute($booking, TransactionType::BILL);
$this->createsTransactionDetail->execute($invoice_transaction, $object_detail);
}
$transaction_object = new TransactionObject(
$billNumber,
TransactionType::SUPPLIER_DELIVER,
$transaction->issuer,
$transaction->receiver,
$transaction->recipient_bank_account_id,
$transaction->payment_method,
$payment_amount,
$booking_amount,
$transaction->currency_id,
$transaction->original_currency_id,
$booking_currency_average_rate,
$total_tax,
$total_service_charge,
null,
ApprovalStatus::APPROVED
);
$supplier_deliver_order_transaction = $this->createsTransaction->execute($po_order_transaction->booking, $transaction_object);
if ($minimum_charge > 0) {
$object_detail = new TransactionDetailObject(
'MIN_CBM_CHARGES',
TransactionDetailType::MIN_CBM_CHARGES,
$minimum_charge,
$price_cbm
);
$supplier_order_pdf = LaravelMpdf::loadView('pages.pdfs.supplier_deliver_order', ['supplier_deliver_order_transaction' => $supplier_deliver_order_transaction, 'po_order_transaction' => $po_order_transaction, 'supplier' => $supplier]);
$document_object = new DocumentObject(
DocumentType::SUPPLIER_DELIVER_ORDER,
[chunk_split('data:application/pdf;base64,'.base64_encode($supplier_order_pdf->output()))],
'',
ApprovalStatus::COMPLETED,
'supplier_delivery_orders'
);
$document = $this->createsDocument->execute($po_order_transaction->booking, $document_object);
$this->createsFile->execute($document, $document_object);
$this->createsTransactionDetail->execute($invoice_transaction, $object_detail);
}
return;
$this->updatesBookingStatus->execute($booking, ApprovalStatus::COMPLETED);
}
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;
}
}
}
@@ -15,7 +15,7 @@ class CreatesTransaction extends AbstractUpdateRelationshipRecord
* @return \Illuminate\Database\Eloquent\Model
* @throws \App\Classes\Exceptions\MalformedRequestException
*/
public function execute(PackingList $packing_list, TransactionObject $object) {
public function execute( $packing_list, TransactionObject $object) {
$model = new Transaction();
$model->bill_no = $object->getBillNo();
$model->type = $object->getTransactionType();
@@ -0,0 +1,76 @@
<?php
namespace App\Classes\Modules\Wallets\ControllersLogic;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Wallets\DataTransferObjects\WalletObject;
use App\Classes\Modules\Wallets\Services\CreatesWallet;
use App\Classes\Modules\Wallets\Services\GeneratesWalletCode;
use App\Classes\Modules\Wallets\Standards\Rules\CanCreateCompanyWallet;
use App\Http\Resources\WalletResource;
use App\Classes\Modules\Companies\Services\FetchesCompany;
use ErrorException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class CreateWalletLogic extends AbstractControllerLogic
{
/**
* @return array
*/
protected function notification():array {
return [
'title' => 'Created Company Wallet',
'message' => 'You have successfully created a company wallet'
];
}
/** @var CreatesWallet */
private $createsWallet;
/** @var GeneratesWalletCode */
private $generatesWalletCode;
/** @var CanCreateCompanyWallet */
private $canCreateCompanyWallet;
/** @var FetchesCompany */
private $fetchesCompany;
/**
* CreateWalletLogic constructor.
* @param CreatesWallet $createsWallet
* @param GeneratesWalletCode $generatesWalletCode
* @param CanCreateCompanyWallet $canCreateCompanyWallet
*/
public function __construct(CreatesWallet $createsWallet, GeneratesWalletCode $generatesWalletCode, CanCreateCompanyWallet $canCreateCompanyWallet, FetchesCompany $fetchesCompany)
{
$this->fetchesCompany = $fetchesCompany;
$this->createsWallet = $createsWallet;
$this->generatesWalletCode = $generatesWalletCode;
$this->canCreateCompanyWallet = $canCreateCompanyWallet;
}
/**
* @param Request $request
* @return JsonResponse
* @throws ErrorException
*/
public function logic(Request $request) : JsonResponse
{
$object = new WalletObject($request->input('company_id'), $request->input('currency_id'), $this->generatesWalletCode->execute());
$this->canCreateCompanyWallet->passes($object);
$company = $this->fetchesCompany->execute(['id' => $request->input('company_id')]);
$wallet = $this->createsWallet->execute($object, $company);
return $this->resourceResponse(new WalletResource($wallet));
}
}
@@ -0,0 +1,132 @@
<?php
namespace App\Classes\Modules\Wallets\ControllersLogic;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Wallets\Standards\Rules\CanCreateWalletTransaction;
use App\Classes\Modules\Wallets\DataTransferObjects\WalletTransactionObject;
use App\Classes\Modules\Wallets\Services\CreatesWalletTransaction;
use App\Classes\Modules\Wallets\Services\GeneratesWalletTransactionBillNo;
use App\Http\Resources\WalletTransactionResource;
use App\Classes\Modules\Wallets\Services\FetchesWallet;
use App\Classes\Modules\Currencies\Services\FetchesCurrency;
use App\Classes\Modules\Currencies\Services\RateCalculatesCurrency;
/*
use App\Classes\Modules\Accounts\Standards\Rules\CanCreateUser;
use App\Classes\Modules\Accounts\Services\CreatesUser;
use App\Classes\Modules\Accounts\DataTransferObjects\UserObject;
use App\Http\Resources\UserResource;
use App\Classes\Modules\Companies\Standards\Rules\CanCreateCompany;
use App\Classes\Modules\Companies\Services\CreatesCompany;
use App\Classes\Modules\Companies\DataTransferObjects\CompanyObject;
use App\Classes\Modules\Contacts\Standards\Rules\CanCreateContact;
use App\Classes\Modules\Contacts\Services\CreatesContact;
use App\Classes\Modules\Contacts\DataTransferObjects\ContactObject;
use App\Classes\Modules\Companies\Standards\Rules\CanCreateCompanyEmployee;
use App\Classes\Modules\Companies\Services\CreatesCompanyEmployee;
use App\Classes\Modules\Companies\DataTransferObjects\CompanyEmployeeObject;
use App\Classes\Modules\SegmentCompanies\Standards\Rules\CanCreateSegmentCompany;
use App\Classes\Modules\SegmentCompanies\Services\CreatesSegmentCompany;
use App\Classes\Modules\SegmentCompanies\DataTransferObjects\SegmentCompanyObject;
*/
use ErrorException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class CreateWalletTransactionLogic extends AbstractControllerLogic
{
/**
* @return array
*/
protected function notification():array {
return [
'title' => 'Created Wallet Transaction',
'message' => 'You have successfully created a wallet transaction'
];
}
/** @var CreatesWalletTransaction */
private $createsWalletTransaction;
/** @var GeneratesWalletTransactionBillNo */
private $generatesWalletTransactionBillNo;
/** @var CanCreateWalletTransaction */
private $canCreateWalletTransaction;
private $fetchesCurrency;
private $rateCalculatesCurrency;
private $fetchesWallet;
/**
* CreateWalletLogic constructor.
* @param CreatesWalletTransaction $createsWalletTransaction
* @param GeneratesWalletTransactionBillNo $generatesWalletTransactionBillNo
* @param CanCreateWalletTransaction $canCreateWalletTransaction
* @param FetchesCurrency $fetchesCurrency
* @param RateCalculatesCurrency $rateCalculatesCurrency
* @param FetchesWallet $fetchesWallet
*/
public function __construct(
CreatesWalletTransaction $createsWalletTransaction, GeneratesWalletTransactionBillNo $generatesWalletTransactionBillNo, CanCreateWalletTransaction $canCreateWalletTransaction,
FetchesCurrency $fetchesCurrency,RateCalculatesCurrency $rateCalculatesCurrency, FetchesWallet $fetchesWallet
)
{
$this->createsWalletTransaction = $createsWalletTransaction;
$this->generatesWalletTransactionBillNo = $generatesWalletTransactionBillNo;
$this->canCreateWalletTransaction = $canCreateWalletTransaction;
$this->fetchesCurrency = $fetchesCurrency;
$this->rateCalculatesCurrency = $rateCalculatesCurrency;
$this->fetchesWallet = $fetchesWallet;
}
/**
* @param Request $request
* @return JsonResponse
* @throws ErrorException
*/
public function logic(Request $request) : JsonResponse
{
try {
DB::beginTransaction();
$wallet = $this->fetchesWallet->execute(['id' => $request->route('id')]);
$conversion_currency = $this->fetchesCurrency->execute(['id' => $request->input('currency_id')]);
$convertable_currency = $this->fetchesCurrency->execute(['id' => $wallet->currency_id]);//MYR
$convert_amount = $this->rateCalculatesCurrency->execute($conversion_currency, $convertable_currency, $request->input('amount'));
$convert_rate = $this->rateCalculatesCurrency->execute_rate($conversion_currency, $convertable_currency);
$object = new WalletTransactionObject(
$wallet->id, $this->generatesWalletTransactionBillNo->execute(),$request->input('trans_type'),
number_format( (float) $convert_amount, 5, '.', ''), $wallet->currency_id , number_format( (float) $request->input('amount'), 5, '.', ''),
$request->input('currency_id'),number_format( (float) $convert_rate, 5, '.', '')
);
$this->canCreateWalletTransaction->passes($object);
$wallet_transaction = $this->createsWalletTransaction->execute($object);
DB::commit();
return $this->resourceResponse(new WalletTransactionResource($wallet_transaction));
} catch (\Exception $exception) {
throw new ErrorException($exception->getMessage(), $exception->getCode());
}
}
}
@@ -0,0 +1,101 @@
<?php
namespace App\Classes\Modules\Wallets\ControllersLogic;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Resources\WalletResource;
use App\Classes\Modules\Wallets\Services\CreatesWallet;
use App\Classes\Modules\Wallets\Services\UpdatesWallet;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Companies\Services\FetchesCompany;
use App\Classes\Modules\Wallets\Services\GeneratesWalletCode;
use App\Classes\Modules\Transactions\Services\CreatesTransaction;
use App\Classes\Modules\Wallets\Processors\CreditWalletProcessor;
use App\Classes\Modules\Transactions\Services\GeneratesTransactionBillNumber;
class CreditWalletLogic extends AbstractControllerLogic
{
/**
* @return array
*/
protected function notification():array {
return [
'title' => 'Credit into Company Wallet',
'message' => 'You have successfully credit company wallet'
];
}
/** @var FetchesCompany */
private $fetchesCompany;
/** @var GeneratesWalletCode */
private $generatesWalletCode;
/** @var CreatesWallet */
private $createsWallet;
/** @var GeneratesTransactionBillNumber */
private $generatesTransactionBillNumber;
/** @var CreatesTransaction */
private $createsTransaction;
/** @var UpdatesWallet */
private $updatesWallet;
/** @var CreditWalletProcessor */
private $creditWalletProcessor;
/**
* CreateWalletLogic constructor.
* @param FetchesCompany $fetchesCompany
* @param GeneratesWalletCode $generatesWalletCode
* @param CreatesWallet $createsWallet
* @param GeneratesTransactionBillNumber $generatesTransactionBillNumber
* @param CreatesTransaction $createsTransaction
* @param UpdatesWallet $updatesWallet
* @param CreditWalletProcessor $creditWalletProcessor
*/
public function __construct(
FetchesCompany $fetchesCompany,
GeneratesWalletCode $generatesWalletCode,
CreatesWallet $createsWallet,
GeneratesTransactionBillNumber $generatesTransactionBillNumber,
CreatesTransaction $createsTransaction,
UpdatesWallet $updatesWallet,
CreditWalletProcessor $creditWalletProcessor
)
{
$this->fetchesCompany = $fetchesCompany;
$this->generatesWalletCode = $generatesWalletCode;
$this->createsWallet = $createsWallet;
$this->generatesTransactionBillNumber = $generatesTransactionBillNumber;
$this->createsTransaction = $createsTransaction;
$this->updatesWallet = $updatesWallet;
$this->creditWalletProcessor = $creditWalletProcessor;
}
/**
* @param Request $request
* @return JsonResponse
* @throws \App\Classes\Exceptions\MalformedRequestException
*/
public function logic(Request $request) : JsonResponse
{
$amount = floatval(str_replace(',', '', $request->input('amount')));
$company = $this->fetchesCompany->execute(['id' => $request->input('company_id')]);
$reference = $request->input('reference');
$type = $request->input('transaction_type');
$wallet = $this->creditWalletProcessor->execute($company, $type, $amount, $reference);
return $this->resourceResponse(new WalletResource($wallet));
}
}
@@ -0,0 +1,117 @@
<?php
namespace App\Classes\Modules\Wallets\ControllersLogic;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Wallets\DataTransferObjects\WalletObject;
use App\Classes\Modules\Transactions\DataTransferObjects\TransactionObject;
use App\Classes\Modules\Companies\Services\FetchesCompany;
use App\Classes\Modules\Transactions\Services\GeneratesTransactionBillNumber;
use App\Classes\Modules\Transactions\Services\CreatesTransaction;
use App\Classes\Modules\Wallets\Services\UpdatesWallet;
use App\Classes\ValueObjects\Constants\TransactionType;
use App\Classes\ValueObjects\Constants\PaymentMethodType;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Http\Resources\WalletResource;
use ErrorException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class DebitWalletLogic extends AbstractControllerLogic
{
/**
* @return array
*/
protected function notification():array {
return [
'title' => 'Debit into Company Wallet',
'message' => 'You have successfully debit company wallet'
];
}
/** @var FetchesCompany */
private $fetchesCompany;
/** @var GeneratesTransactionBillNumber */
private $generatesTransactionBillNumber;
/** @var CreatesTransaction */
private $createsTransaction;
/** @var UpdatesWallet */
private $updatesWallet;
/**
* CreateWalletLogic constructor.
* @param FetchesCompany $fetchesCompany
* @param GeneratesTransactionBillNumber $generatesTransactionBillNumber
* @param CreatesTransaction $createsTransaction
* @param UpdatesWallet $updatesWallet
*/
public function __construct(
FetchesCompany $fetchesCompany,
GeneratesTransactionBillNumber $generatesTransactionBillNumber,
CreatesTransaction $createsTransaction,
UpdatesWallet $updatesWallet
)
{
$this->fetchesCompany = $fetchesCompany;
$this->generatesTransactionBillNumber = $generatesTransactionBillNumber;
$this->createsTransaction = $createsTransaction;
$this->updatesWallet = $updatesWallet;
}
/**
* @param Request $request
* @return JsonResponse
* @throws \App\Classes\Exceptions\MalformedRequestException
*/
public function logic(Request $request) : JsonResponse
{
$amount = floatval(str_replace(',', '', $request->input('amount')));
$company = $this->fetchesCompany->execute(['id' => $request->input('company_id')]);
$reference = $request->input('reference');
if (!$company->wallets()->first()) {
$object = new WalletObject($company->id, 1, $this->generatesWalletCode->execute());
$wallet = $this->createsWallet->execute($object, $company);
}
$wallet = $company->wallets()->first();
$billNumber = $this->generatesTransactionBillNumber->execute('DEBIT-NOTE-');
$transaction_object = new TransactionObject(
$billNumber,
TransactionType::DEBIT_NOTE,
1,
$wallet->company->id,
1,
PaymentMethodType::CASH,
$amount,
$amount,
1,
1,
1,
0,
0,
null,
ApprovalStatus::APPROVED,
[],
$reference
);
$transaction = $this->createsTransaction->execute($wallet, $transaction_object);
$updateWalletAmount = $wallet->amount - $transaction->amount;
$walletOject = new WalletObject($wallet->company->id, $wallet->currency_id, $wallet->code, $updateWalletAmount);
$wallet = $this->updatesWallet->execute($wallet, $walletOject);
return $this->resourceResponse(new WalletResource($wallet));
}
}
@@ -0,0 +1,60 @@
<?php
namespace App\Classes\Modules\Wallets\ControllersLogic;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Wallets\DataTransferObjects\WalletObject;
use App\Classes\Modules\Wallets\Services\ListsWallet;
use App\Classes\Modules\Wallets\Standards\Rules\CanListWallet;
use App\Http\Resources\WalletResource;
use ErrorException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class ListWalletLogic extends AbstractControllerLogic
{
/**
* @return array
*/
protected function notification():array {
return [
'title' => 'List Company Wallet',
'message' => 'You have successfully list company wallet'
];
}
/** @var ListWallet */
private $listsWallet;
/** @var CanCreateCompanyWallet */
private $canListWallet;
/**
* CreateWalletLogic constructor.
* @param CreatesWallet $createsWallet
* @param GeneratesWalletCode $generatesWalletCode
* @param CanCreateCompanyWallet $canCreateCompanyWallet
*/
public function __construct(CanListWallet $canListWallet, ListsWallet $listsWallet)
{
$this->canListWallet = $canListWallet;
$this->listsWallet = $listsWallet;
}
/**
* @param Request $request
* @return JsonResponse
* @throws ErrorException
*/
public function logic(Request $request) : JsonResponse
{
//$this->canListWallet->passes();
$query = $this->listsWallet->execute($this->listsWallet->deserializeFilters($request->input('filters')));
return $this->collectionResponse(WalletResource::collection($query));
}
}
@@ -0,0 +1,113 @@
<?php
namespace App\Classes\Modules\Wallets\ControllersLogic;
use App\Classes\Exceptions\MalformedRequestException;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Wallets\DataTransferObjects\WalletObject;
use App\Classes\Modules\Transactions\DataTransferObjects\TransactionObject;
use App\Classes\Modules\Companies\Services\FetchesCompany;
use App\Classes\Modules\Wallets\Services\CreatesWallet;
use App\Classes\Modules\Wallets\Services\CreatesWalletTransaction;
use App\Classes\Modules\Wallets\Services\GeneratesWalletCode;
use App\Classes\Modules\Transactions\Services\GeneratesTransactionBillNumber;
use App\Classes\Modules\Billplzs\Services\CreatesBillplzBill;
use App\Classes\Modules\Transactions\Services\CreatesTransaction;
use App\Classes\ValueObjects\Constants\TransactionType;
use App\Classes\ValueObjects\Constants\PaymentMethodType;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Http\Resources\WalletResource;
use App\Http\Resources\WalletTransactionResource;
use App\Models\Wallet;
use ErrorException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class TopUpWalletLogic extends AbstractControllerLogic
{
/**
* @return array
*/
protected function notification():array {
return [
'title' => 'TopUp into Company Wallet',
'message' => 'You have successfully created a topup request for company\'s wallet'
];
}
/** @var FetchesCompany */
private $fetchesCompany;
/** @var GeneratesWalletCode */
private $generatesWalletCode;
/** @var CreatesWallet */
private $createsWallet;
/** @var GeneratesTransactionBillNumber */
private $generatesTransactionBillNumber;
/** @var CreatesBillplzBill */
private $createsBillplzBill;
/** @var CreatesTransaction */
private $createsTransaction;
/**
* TopUpWalletLogic constructor.
* @param FetchesCompany $fetchesCompany
* @param GeneratesWalletCode $generatesWalletCode
* @param CreatesWallet $createsWallet
* @param GeneratesTransactionBillNumber $generatesTransactionBillNumber
* @param CreatesBillplzBill $createsBillplzBill
* @param CreatesTransaction $createsTransaction
*/
public function __construct(FetchesCompany $fetchesCompany, GeneratesWalletCode $generatesWalletCode, CreatesWallet $createsWallet, GeneratesTransactionBillNumber $generatesTransactionBillNumber, CreatesBillplzBill $createsBillplzBill, CreatesTransaction $createsTransaction)
{
$this->fetchesCompany = $fetchesCompany;
$this->generatesWalletCode = $generatesWalletCode;
$this->createsWallet = $createsWallet;
$this->generatesTransactionBillNumber = $generatesTransactionBillNumber;
$this->createsBillplzBill = $createsBillplzBill;
$this->createsTransaction = $createsTransaction;
}
/**
* @param Request $request
* @return JsonResponse
* @throws \App\Classes\Exceptions\MalformedRequestException
*/
public function logic(Request $request) : JsonResponse
{
$amount = floatval(str_replace(',', '', $request->input('amount')));
$company = $this->fetchesCompany->execute(['id' => $request->input('company_id')]);
/** @var Wallet $wallet */
$wallet = $company->wallets()->first();
if (!$wallet) {
$object = new WalletObject($company->id, 1, $this->generatesWalletCode->execute());
/** @var Wallet $wallet */
$wallet = $this->createsWallet->execute($object, $company);
}
$user = $company->employees()->first();
$billNumber = $this->generatesTransactionBillNumber->execute('TOPUP-');
if($amount < 0) {
throw new MalformedRequestException('Top up credit value must be greater than zero.');
}
$billPlzBill = $this->createsBillplzBill->execute($company->name, $user->email, 'This payment is credit topup for company ref. ' . $company->reference, $amount, $billNumber, $request->input('bank_code'), true);
$transaction_object = new TransactionObject($billNumber, TransactionType::TOP_UP, 1, $company->id, 1, PaymentMethodType::PAYMENT_GATEWAY, $amount, $amount, 1, 1, 1, 0, 0, null, ApprovalStatus::PENDING_SUBMISSION, [], $billPlzBill->id);
$transaction = $this->createsTransaction->execute($wallet, $transaction_object);
return $this->resourceResponse(new WalletTransactionResource($transaction));
}
}
@@ -0,0 +1,69 @@
<?php
namespace App\Classes\Modules\Wallets\ControllersLogic;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Wallets\DataTransferObjects\WalletObject;
use App\Classes\Modules\Wallets\Services\ListsWallet;
use App\Classes\Modules\Wallets\Services\FetchesWallet;
use App\Classes\ValueObjects\Constants\TransactionType;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\Modules\Wallets\Standards\Rules\CanListWallet;
use App\Http\Resources\WalletResource;
use App\Classes\Modules\Transactions\Processors\UpdateWalletTransactionProcessor;
use ErrorException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class UpdateStatusWalletLogic extends AbstractControllerLogic
{
/**
* @return array
*/
protected function notification():array {
return [
'title' => 'Update Status Transaction Company Wallet',
'message' => 'You have successfully status transaction company wallet'
];
}
/** @var ListWallet */
private $fetchesWallet;
/** @var CanCreateCompanyWallet */
private $canListWallet;
/** @var UpdateWalletTransactionProcessor */
private $updateWalletTransactionProcessor;
/**
* CreateWalletLogic constructor.
* @param CreatesWallet $createsWallet
* @param GeneratesWalletCode $generatesWalletCode
* @param CanCreateCompanyWallet $canCreateCompanyWallet
*/
public function __construct(FetchesWallet $fetchesWallet, UpdateWalletTransactionProcessor $updateWalletTransactionProcessor)
{
$this->fetchesWallet = $fetchesWallet;
$this->updateWalletTransactionProcessor = $updateWalletTransactionProcessor;
}
/**
* @param Request $request
* @return JsonResponse
* @throws ErrorException
*/
public function logic(Request $request) : JsonResponse
{
$status = ($request->route('status')=='approve') ? 2 : 4;
$wallet = $this->updateWalletTransactionProcessor->execute($request->route('transaction_id'), $status);
return $this->resourceResponse(new WalletResource($wallet));
}
}
@@ -0,0 +1,72 @@
<?php
namespace App\Classes\Modules\Wallets\ControllersLogic;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Wallets\DataTransferObjects\WalletObject;
use App\Classes\Modules\Wallets\Services\ListsWallet;
use App\Classes\Modules\Wallets\Services\FetchesWallet;
use App\Classes\ValueObjects\Constants\TransactionType;
use App\Classes\Modules\Wallets\Standards\Rules\CanWithdrawWallet;
use App\Http\Resources\WalletResource;
use App\Classes\Modules\Transactions\Processors\CreateWalletTransactionProcessor;
use ErrorException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class WithdrawWalletLogic extends AbstractControllerLogic
{
/**
* @return array
*/
protected function notification():array {
return [
'title' => 'Withdraw from Company Wallet',
'message' => 'You have successfully withdraw company wallet'
];
}
/** @var FetchesWallet */
private $fetchesWallet;
/** @var CanWithdrawWallet */
private $canWithdrawWallet;
/** @var CreateWalletTransactionProcessor */
private $createWalletTransactionProcessor;
/**
* CreateWalletLogic constructor.
* @param CreatesWallet $createsWallet
* @param GeneratesWalletCode $generatesWalletCode
* @param CanCreateCompanyWallet $canCreateCompanyWallet
*/
public function __construct(CanWithdrawWallet $canWithdrawWallet, FetchesWallet $fetchesWallet, CreateWalletTransactionProcessor $createWalletTransactionProcessor)
{
$this->canWithdrawWallet = $canWithdrawWallet;
$this->fetchesWallet = $fetchesWallet;
$this->createWalletTransactionProcessor = $createWalletTransactionProcessor;
}
/**
* @param Request $request
* @return JsonResponse
* @throws ErrorException
*/
public function logic(Request $request) : JsonResponse
{
$wallet = $this->fetchesWallet->execute(['id' => $request->input('wallet_id')]);
$walletOject = new WalletObject( $wallet->company->id, $wallet->currency_id, $wallet->code, $request->input('amount'));
$this->canWithdrawWallet->passes($walletOject);
$transaction = $this->createWalletTransactionProcessor->execute($wallet, $walletOject, TransactionType::WITHDRAW);
return $this->resourceResponse(new WalletResource($wallet));
}
}
@@ -0,0 +1,65 @@
<?php
namespace App\Classes\Modules\Wallets\DataTransferObjects;
use App\Classes\General\Interfaces\DataTransferObject;
class WalletObject implements DataTransferObject
{
/** @var int */
private $company_id;
/** @var int */
private $currency_id;
/** @var int */
private $code;
private $amount;
/**
* WalletObject constructor.
* @param int $company_id
* @param int $currency
* @param int $code
*/
public function __construct(int $company_id, int $currency, int $code, float $amount=0)
{
$this->company_id = $company_id;
$this->currency_id = $currency;
$this->code = $code;
$this->amount = $amount;
}
/**
* @return int
*/
public function getCompanyId(): int
{
return $this->company_id;
}
/**
* @return int
*/
public function getCurrency(): int
{
return $this->currency_id;
}
/**
* @return int
*/
public function getCode(): int
{
return $this->code;
}
public function getAmount(): float
{
return $this->amount;
}
}
@@ -0,0 +1,94 @@
<?php
namespace App\Classes\Modules\Wallets\DataTransferObjects;
use App\Classes\General\Interfaces\DataTransferObject;
class WalletTransactionObject implements DataTransferObject
{
private $wallet_id;
private $bill_no;
private $trans_type;
private $amount;
private $currency_id;
private $original_amount;
private $original_currency_id;
private $currency_rate;
public function __construct(
int $wallet_id, int $bill_no,int $trans_type,
float $amount, int $currency_id, int $original_amount,
int $original_currency_id, float $currency_rate
){
$this->wallet_id = $wallet_id;
$this->bill_no = $bill_no;
$this->trans_type = $trans_type;
$this->amount= $amount;
$this->currency_id = $currency_id;
$this->original_amount = $original_amount;
$this->original_currency_id = $original_currency_id;
$this->currency_rate = $currency_rate;
}
/**
* @return int
*/
public function getWalletId(): int
{
return $this->wallet_id;
}
/**
* @return int
*/
public function getBillNo(): int
{
return $this->bill_no;
}
/**
* @return int
*/
public function getTransType(): int
{
return $this->trans_type;
}
public function getAmount(): float
{
return $this->amount;
}
/**
* @return int
*/
public function getCurrency(): int
{
return $this->currency_id;
}
public function getOriginalAmount(): float
{
return $this->original_amount;
}
public function getOriginalCurrency(): int
{
return $this->original_currency_id;
}
public function getCurrencyRate(): float
{
return $this->currency_rate;
}
}
@@ -0,0 +1,90 @@
<?php
namespace App\Classes\Modules\Wallets\Processors;
use App\Models\Wallet;
use App\Models\Company;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\Modules\Wallets\Services\CreatesWallet;
use App\Classes\Modules\Wallets\Services\UpdatesWallet;
use App\Classes\ValueObjects\Constants\TransactionType;
use App\Classes\ValueObjects\Constants\PaymentMethodType;
use App\Classes\Modules\Wallets\Services\GeneratesWalletCode;
use App\Classes\Modules\Transactions\Services\CreatesTransaction;
use App\Classes\Modules\Wallets\DataTransferObjects\WalletObject;
use App\Classes\Modules\Transactions\DataTransferObjects\TransactionObject;
use App\Classes\Modules\Transactions\Services\GeneratesTransactionBillNumber;
class CreditWalletProcessor
{
/** @var GeneratesWalletCode */
private $generatesWalletCode;
/** @var CreatesWallet */
private $createsWallet;
/** @var GeneratesTransactionBillNumber */
private $generatesTransactionBillNumber;
/** @var CreatesTransaction */
private $createsTransaction;
/** @var UpdatesWallet */
private $updatesWallet;
/**
* CreateWalletLogic constructor.
* @param GeneratesWalletCode $generatesWalletCode
* @param CreatesWallet $createsWallet
* @param GeneratesTransactionBillNumber $generatesTransactionBillNumber
* @param CreatesTransaction $createsTransaction
* @param UpdatesWallet $updatesWallet
*/
public function __construct(
GeneratesWalletCode $generatesWalletCode,
CreatesWallet $createsWallet,
GeneratesTransactionBillNumber $generatesTransactionBillNumber,
CreatesTransaction $createsTransaction,
UpdatesWallet $updatesWallet
)
{
$this->generatesWalletCode = $generatesWalletCode;
$this->createsWallet = $createsWallet;
$this->generatesTransactionBillNumber = $generatesTransactionBillNumber;
$this->createsTransaction = $createsTransaction;
$this->updatesWallet = $updatesWallet;
}
/**
* @param Company $company
* @param int $transactionType
* @param float $amount
* @param string $reference
* @return \Illuminate\Database\Eloquent\Model
* @throws \App\Classes\Exceptions\MalformedRequestException
*/
public function execute(Company $company, int $transactionType, float $amount, string $reference)
{
if (!$company->wallets()->first()) {
$object = new WalletObject($company->id, 1, $this->generatesWalletCode->execute());
$this->createsWallet->execute($object, $company);
}
/** @var Wallet $wallet */
$wallet = $company->wallets()->first();
$billNumber = $this->generatesTransactionBillNumber->execute($transactionType === 2 ? 'DEBIT-NOTE-' : 'CREDIT-NOTE-');
$transaction_object = new TransactionObject($billNumber, $transactionType === 2 ? TransactionType::DEBIT_NOTE : TransactionType::CREDIT_NOTE, 1, $wallet->owner->id, 1, PaymentMethodType::CASH, $amount, $amount, 1, 1, 1, 0, 0, null, ApprovalStatus::APPROVED, [], $reference);
$transaction = $this->createsTransaction->execute($wallet, $transaction_object);
$updateWalletAmount = $transactionType === 2 ? ($wallet->amount - $transaction->amount) : ($wallet->amount + $transaction->amount);
$walletObject = new WalletObject($wallet->owner->id, $wallet->currency_id, $wallet->code, $updateWalletAmount);
$wallet = $this->updatesWallet->execute($wallet, $walletObject);
return $wallet;
}
}
@@ -0,0 +1,28 @@
<?php
namespace App\Classes\Modules\Wallets\Services;
use App\Models\Wallet;
class ChecksIfWalletCodeExists
{
/** @var wallet */
private $repository;
/**
* ChecksIfWalletCodeExists constructor.
* @param Wallet $repository
*/
public function __construct(wallet $repository)
{
$this->repository = $repository;
}
public function execute(int $code): bool {
return $this->repository->where('code', $code)->exists();
}
}
@@ -0,0 +1,22 @@
<?php
namespace App\Classes\Modules\Wallets\Services;
use App\Models\WalletTransaction;
class ChecksIfWalletTransactionBillNoExists
{
private $repository;
public function __construct(WalletTransaction $repository)
{
$this->repository = $repository;
}
public function execute(int $bill_no): bool {
return $this->repository->where('bill_no', $bill_no)->exists();
}
}
@@ -0,0 +1,26 @@
<?php
namespace App\Classes\Modules\Wallets\Services;
use App\Classes\General\Eloquent\AbstractUpdateRecord;
use App\Classes\General\Eloquent\AbstractUpdateRelationshipRecord;
use App\Classes\Modules\Wallets\DataTransferObjects\WalletObject;
use App\Models\Wallet;
use App\Models\Company;
class CreatesWallet extends AbstractUpdateRelationshipRecord
{
/**
* @param WalletObject $object
* @return \Illuminate\Database\Eloquent\Model
* @throws \App\Classes\Exceptions\MalformedRequestException
*/
public function execute(WalletObject $object, Company $company) {
$model = new Wallet();
//$model->company_id = $object->getCompanyId();
$model->code = $object->getCode();
$model->currency_id = $object->getCurrency();
return $this->handler($company->wallets(), $model);
}
}
@@ -0,0 +1,30 @@
<?php
namespace App\Classes\Modules\Wallets\Services;
use App\Classes\General\Eloquent\AbstractUpdateRecord;
use App\Classes\Modules\Wallets\DataTransferObjects\WalletTransactionObject;
use App\Models\WalletTransaction;
class CreatesWalletTransaction extends AbstractUpdateRecord
{
/**
* @param WalletTransactionObject $object
* @return \Illuminate\Database\Eloquent\Model
* @throws \App\Classes\Exceptions\MalformedRequestException
*/
public function execute(WalletTransactionObject $object) {
$model = new WalletTransaction();
$model->wallet_id = $object->getWalletId();
$model->bill_no = $object->getBillNo();
$model->trans_type = $object->getTransType();
$model->amount = $object->getAmount();
$model->currency_id = $object->getCurrency();
$model->original_amount = $object->getOriginalAmount();
$model->original_currency_id = $object->getOriginalCurrency();
$model->currency_rate = $object->getCurrencyRate();
return $this->handler($model);
}
}
@@ -0,0 +1,34 @@
<?php
namespace App\Classes\Modules\Wallets\Services;
use App\Classes\General\Eloquent\AbstractFetchRecord;
use Illuminate\Database\Eloquent\Builder;
use App\Models\Wallet;
class FetchesWallet extends AbstractFetchRecord
{
/** @var Wallet */
private $repository;
/**
* FetchesWallet constructor.
* @param Wallet $repository
*/
public function __construct(Wallet $repository)
{
$this->repository = $repository;
}
/**
* @return Builder
*/
public function getRepository(): Builder
{
return $this->repository->newQuery();
}
}
@@ -0,0 +1,32 @@
<?php
namespace App\Classes\Modules\Wallets\Services;
class GeneratesWalletCode
{
/** @var ChecksIfWalletCodeExists */
private $walletCodeExists;
/**
* GeneratesWalletCode constructor.
* @param ChecksIfWalletCodeExists $walletCodeExists
*/
public function __construct(ChecksIfWalletCodeExists $walletCodeExists)
{
$this->walletCodeExists = $walletCodeExists;
}
/**
* @return int
*/
public function execute(): int {
$code = mt_rand(100000001, 999999999);
return !$this->walletCodeExists->execute($code) ? $code : self::execute();
}
}
@@ -0,0 +1,27 @@
<?php
namespace App\Classes\Modules\Wallets\Services;
class GeneratesWalletTransactionBillNo
{
private $walletTransationBillNoExists;
public function __construct(ChecksIfWalletTransactionBillNoExists $walletTransationBillNoExists)
{
$this->walletTransationBillNoExists = $walletTransationBillNoExists;
}
public function execute(): int {
$code = mt_rand(100000001, 999999999);
return !$this->walletTransationBillNoExists->execute($code) ? $code : self::execute();
}
}
@@ -0,0 +1,30 @@
<?php
namespace App\Classes\Modules\Wallets\Services;
use Illuminate\Database\Eloquent\Builder;
use App\Classes\General\Eloquent\AbstractListRecord;
use App\Models\Wallet;
class ListsWallet extends AbstractListRecord
{
/** @var Booking */
private $repository;
/**
* ListsBookings constructor.
* @param Booking $repository
*/
public function __construct(Wallet $repository)
{
$this->repository = $repository;
}
/**
* @return Builder
*/
public function getRepository(): Builder
{
return $this->repository->newQuery();
}
}
@@ -0,0 +1,27 @@
<?php
namespace App\Classes\Modules\Wallets\Services;
use App\Classes\General\Eloquent\AbstractUpdateRecord;
use App\Classes\General\Eloquent\AbstractUpdateRelationshipRecord;
use App\Classes\Modules\Wallets\DataTransferObjects\WalletObject;
use App\Models\Wallet;
use App\Models\Company;
class UpdatesWallet extends AbstractUpdateRecord
{
/**
* @param WalletObject $object
* @return \Illuminate\Database\Eloquent\Model
* @throws \App\Classes\Exceptions\MalformedRequestException
*/
public function execute(Wallet $model, WalletObject $object) {
$model->amount = $object->getAmount();
$model->code = $object->getCode();
$model->currency_id = $object->getCurrency();
return $this->handler($model);
}
}
@@ -0,0 +1,25 @@
<?php
namespace App\Classes\Modules\Wallets\Services;
use App\Classes\General\Eloquent\AbstractUpdateRecord;
use App\Classes\General\Eloquent\AbstractUpdateRelationshipRecord;
use App\Classes\Modules\Wallets\DataTransferObjects\WalletObject;
use App\Models\Wallet;
use App\Models\Company;
class UpdatesWalletBalance extends AbstractUpdateRecord
{
/**
* @param Wallet $model
* @param $amount
* @return \Illuminate\Database\Eloquent\Model
* @throws \App\Classes\Exceptions\MalformedRequestException
*/
public function execute(Wallet $model, $amount) {
$model->amount = $model->amount + $amount;
return $this->handler($model);
}
}
@@ -0,0 +1,55 @@
<?php
namespace App\Classes\Modules\Wallets\Standards\Rules;
use App\Classes\General\Abstracts\AbstractRule;
use App\Classes\Modules\Wallets\DataTransferObjects\WalletObject;
use App\Classes\Modules\Wallets\Standards\Validators\CompanyWalletValidation;
class CanCreateCompanyWallet extends AbstractRule
{
/** @var CompanyWalletValidation */
private $companyWalletValidation;
/**
* CanCreateCompanyWallet constructor.
* @param CompanyWalletValidation $companyWalletValidation
*/
public function __construct(CompanyWalletValidation $companyWalletValidation)
{
$this->companyWalletValidation = $companyWalletValidation;
}
/**
* @return bool
*/
protected function authorized(): bool
{
// TODO Set Authorization rules
return true;
}
/**
* @param WalletObject $object
* @return bool
* @throws \App\Classes\Exceptions\RequestValidationException
*/
protected function validators($object): bool
{
return $this->companyWalletValidation->validate($object);
}
/**
* @param WalletObject $object
* @return bool
*/
protected function criteria($object): bool
{
return true;
}
}
@@ -0,0 +1,51 @@
<?php
namespace App\Classes\Modules\Wallets\Standards\Rules;
use App\Classes\General\Abstracts\AbstractRule;
use App\Classes\Modules\Wallets\DataTransferObjects\WalletTransactionObject;
use App\Classes\Modules\Wallets\Standards\Validators\WalletTransactionValidation;
class CanCreateWalletTransaction extends AbstractRule
{
/** @var WalletTransactionValidation */
private $walletTransactionValidation;
public function __construct(WalletTransactionValidation $walletTransactionValidation)
{
$this->walletTransactionValidation = $walletTransactionValidation;
}
/**
* @return bool
*/
protected function authorized(): bool
{
// TODO Set Authorization rules
return true;
}
/**
* @param WalletTransactionObject $object
* @return bool
* @throws \App\Classes\Exceptions\RequestValidationException
*/
protected function validators($object): bool
{
return $this->walletTransactionValidation->validate($object);
}
/**
* @param WalletTransactionObject $object
* @return bool
*/
protected function criteria($object): bool
{
return true;
}
}
@@ -0,0 +1,51 @@
<?php
namespace App\Classes\Modules\Wallets\Standards\Rules;
use App\Classes\General\Abstracts\AbstractRule;
use App\Classes\Modules\Wallets\DataTransferObjects\WalletObject;
use App\Classes\Modules\Wallets\Standards\Validators\ListWalletValidation;
class CanListWallet extends AbstractRule
{
/** @var ListWalletValidation */
private $listWalletValidation;
public function __construct(ListWalletValidation $listWalletValidation)
{
$this->listWalletValidation = $listWalletValidation;
}
/**
* @return bool
*/
protected function authorized(): bool
{
// TODO Set Authorization rules
return true;
}
/**
* @param WalletObject $object
* @return bool
* @throws \App\Classes\Exceptions\RequestValidationException
*/
protected function validators($object): bool
{
return $this->listWalletValidation->validate($object);
}
/**
* @param WalletTransactionObject $object
* @return bool
*/
protected function criteria($object): bool
{
return true;
}
}
@@ -0,0 +1,51 @@
<?php
namespace App\Classes\Modules\Wallets\Standards\Rules;
use App\Classes\General\Abstracts\AbstractRule;
use App\Classes\Modules\Wallets\DataTransferObjects\WalletObject;
use App\Classes\Modules\Wallets\Standards\Validators\TopUpWalletValidation;
class CanTopUpWallet extends AbstractRule
{
/** @var TopUpWalletValidation */
private $topUpWalletValidation;
public function __construct(TopUpWalletValidation $topUpWalletValidation)
{
$this->topUpWalletValidation = $topUpWalletValidation;
}
/**
* @return bool
*/
protected function authorized(): bool
{
// TODO Set Authorization rules
return true;
}
/**
* @param WalletObject $object
* @return bool
* @throws \App\Classes\Exceptions\RequestValidationException
*/
protected function validators($object): bool
{
return $this->topUpWalletValidation->validate($object);
}
/**
* @param WalletTransactionObject $object
* @return bool
*/
protected function criteria($object): bool
{
return true;
}
}
@@ -0,0 +1,51 @@
<?php
namespace App\Classes\Modules\Wallets\Standards\Rules;
use App\Classes\General\Abstracts\AbstractRule;
use App\Classes\Modules\Wallets\DataTransferObjects\WalletObject;
use App\Classes\Modules\Wallets\Standards\Validators\WithdrawWalletValidation;
class CanWithdrawWallet extends AbstractRule
{
/** @var WithdrawWalletValidation */
private $witdrawWalletValidation;
public function __construct(WithdrawWalletValidation $witdrawWalletValidation)
{
$this->witdrawWalletValidation = $witdrawWalletValidation;
}
/**
* @return bool
*/
protected function authorized(): bool
{
// TODO Set Authorization rules
return true;
}
/**
* @param WalletObject $object
* @return bool
* @throws \App\Classes\Exceptions\RequestValidationException
*/
protected function validators($object): bool
{
return $this->witdrawWalletValidation->validate($object);
}
/**
* @param WalletTransactionObject $object
* @return bool
*/
protected function criteria($object): bool
{
return true;
}
}
@@ -0,0 +1,40 @@
<?php
namespace App\Classes\Modules\Wallets\Standards\Validators;
use App\Classes\General\Abstracts\AbstractValidation;
use App\Classes\Modules\Wallets\DataTransferObjects\WalletObject;
class CompanyWalletValidation extends AbstractValidation
{
/**
* @param WalletObject $object
* @return array
*/
protected function data($object): array
{
return [
'company_id' => $object->getCompanyId(),
'currency_id' => $object->getCurrency(),
];
}
/**
* @return array
*/
protected function rules(): array
{
return [
'company_id' => 'required',
'currency_id' => 'required',
];
}
/**
* @return array
*/
protected function messages(): array
{
return [];
}
}
@@ -0,0 +1,30 @@
<?php
namespace App\Classes\Modules\Wallets\Standards\Validators;
use App\Classes\General\Abstracts\AbstractValidation;
class ListWalletValidation extends AbstractValidation
{
protected function data($object): array
{
return [];
}
/**
* @return array
*/
protected function rules(): array
{
return [];
}
/**
* @return array
*/
protected function messages(): array
{
return [];
}
}
@@ -0,0 +1,30 @@
<?php
namespace App\Classes\Modules\Wallets\Standards\Validators;
use App\Classes\General\Abstracts\AbstractValidation;
class TopUpWalletValidation extends AbstractValidation
{
protected function data($object): array
{
return [];
}
/**
* @return array
*/
protected function rules(): array
{
return [];
}
/**
* @return array
*/
protected function messages(): array
{
return [];
}
}
@@ -0,0 +1,40 @@
<?php
namespace App\Classes\Modules\Wallets\Standards\Validators;
use App\Classes\General\Abstracts\AbstractValidation;
class WalletTransactionValidation extends AbstractValidation
{
protected function data($object): array
{
return [
'wallet_id' => $object->getWalletId(),
'currency_id' => $object->getCurrency(),
'amount' => $object->getAmount(),
'trans_type'=>$object->getTransType()
];
}
/**
* @return array
*/
protected function rules(): array
{
return [
'wallet_id' => 'required',
'currency_id' => 'required',
'amount' => 'required',
'trans_type'=>'required'
];
}
/**
* @return array
*/
protected function messages(): array
{
return [];
}
}
@@ -0,0 +1,30 @@
<?php
namespace App\Classes\Modules\Wallets\Standards\Validators;
use App\Classes\General\Abstracts\AbstractValidation;
class WithdrawWalletValidation extends AbstractValidation
{
protected function data($object): array
{
return [];
}
/**
* @return array
*/
protected function rules(): array
{
return [];
}
/**
* @return array
*/
protected function messages(): array
{
return [];
}
}
@@ -17,7 +17,7 @@ final class TransactionType {
// public const PERFORMA = 4;
// public const TOP_UP = 5;
public const TOP_UP = 3;
// public const REFUND = 6;
@@ -1,22 +0,0 @@
<?php
namespace App\Http\Controllers\Accounts;
use App\Classes\Modules\Accounts\ControllersLogic\FetchUserByEmailLogic;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class FetchUserByEmailController
{
/**
* @param Request $request
* @param FetchUserByEmailLogic $logic
* @return JsonResponse
*/
public function fetch(Request $request, FetchUserByEmailLogic $logic): JsonResponse {
return $logic->execute($request);
}
}
@@ -1,21 +0,0 @@
<?php
namespace App\Http\Controllers\Companies;
use App\Classes\Modules\Companies\ControllersLogic\UpdateCompanyNameAndDebtorLogic;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class UpdateCompanyNameAndDebtorController extends Controller
{
/**
* @param Request $request
* @param UpdateCompanyLogic $logic
* @return JsonResponse
*/
public function update(Request $request, UpdateCompanyNameAndDebtorLogic $logic): JsonResponse
{
return $logic->execute($request);
}
}
@@ -4,7 +4,6 @@ namespace App\Http\Controllers\Exports;
use App\Classes\Modules\Exports\Services\ExportsArrivedParcel;
use App\Classes\Modules\Exports\Services\ExportsParcel;
use App\Classes\Modules\Exports\Services\ExportsWarehousePackingList;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
@@ -35,11 +34,4 @@ class ExportArrivedParcelController
ob_end_clean();
return $response;
}
public function guangZhou2ToJohor(Request $request) {
$exportsWarehousePackingList = new ExportsWarehousePackingList();
$response = $exportsWarehousePackingList->download('guangzhou2-to-johor-summary.xls', Excel::XLS, ['Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']);
ob_end_clean();
return $response;
}
}
@@ -3,7 +3,6 @@
namespace App\Http\Controllers\Exports;
use App\Classes\Modules\Exports\Services\ExportsCompanyModuleSummary;
use App\Classes\Modules\Exports\Services\ExportsOrderSummaryByMarking;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
@@ -28,13 +27,4 @@ class ExportCompanyModuleSummaryController
ob_end_clean();
return $response;
}
public function exportOrderSummaryByMarking(Request $request) {
$exportsOrderSummaryByMarking = new ExportsOrderSummaryByMarking($request);
$customer_marking = $request->route('marking');
$exportsOrderSummaryByMarking->setParameters($customer_marking, $request->input('dateFrom'), $request->input('dateTo'));
$response = $exportsOrderSummaryByMarking->download($customer_marking . '_order_summary.xls', Excel::XLS, ['Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']);
ob_end_clean();
return $response;
}
}
@@ -4,7 +4,6 @@ namespace App\Http\Controllers\Exports;
use App\Classes\Modules\Exports\Services\ExportsCustomersOrderLatestDate;
use App\Classes\Modules\Exports\Services\ExportsCustomerTotalOrderByYear;
use App\Classes\Modules\Exports\Services\ExportsPaymentTransactions;
use App\Models\User;
use Illuminate\Http\Request;
@@ -32,11 +31,4 @@ class ExportCustomersToExcelController
ob_end_clean();
return $response;
}
public function totalOrders(Request $request){
$exportsTotalOrders = new ExportsCustomerTotalOrderByYear($request);
$response = $exportsTotalOrders->download('total-orders-' . $request->route('year') . '.xls', Excel::XLS, ['Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']);
ob_end_clean();
return $response;
}
}
@@ -0,0 +1,76 @@
<?php
namespace App\Http\Controllers\Invoice;
use App\Http\Controllers\Controller;
use App\Classes\Modules\Transactions\ControllersLogic\multipleInvoicesWithOnePaymentLogic;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use App\Models\Transaction;
use App\Classes\ValueObjects\Constants\TransactionType;
use App\Classes\Modules\Wallets\Services\UpdatesWalletBalance;
use App\Classes\ValueObjects\Constants\PaymentMethodType;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\Modules\Transactions\DataTransferObjects\TransactionObject;
use App\Classes\Modules\Transactions\Services\CreatesTransaction;
use App\Classes\Modules\Transactions\Services\GeneratesTransactionBillNumber;
use App\Classes\Modules\Billplzs\Services\CreatesBillplzBill;
use App\Classes\Modules\Wallets\DataTransferObjects\WalletObject;
use App\Classes\Modules\Wallets\Services\GeneratesWalletCode;
use App\Classes\Modules\Wallets\Services\CreatesWallet;
use APP\models\PackingList;
use App\Models\multipleInvoicesWithOnePayment;
use DB;
class MultipleInvoiceOnePaymentController extends Controller
{
public function getallivoiceid1($transactionsArray, multipleInvoicesWithOnePaymentLogic $logic): JsonResponse {
return $logic->logic($transactionsArray);
}
public function getallivoiceid( $transactionsArray)
{
// dd(json_decode($transactionsArray));
$transactions = Transaction::whereIn('id', json_decode($transactionsArray))->where('type', TransactionType::SHIPPING_INVOICE)->get();
$total = $transactions->sum('amount');
$packingList =$transactions[1]->owner;
$order = $packingList->owner;
$companyModule = $order->companyModule;
$company = $companyModule->company;
$wallet = $company->wallets()->first();
if (!$wallet) {
$object = new WalletObject($company->id, 1, $this->generatesWalletCode->execute());
/** @var Wallet $wallet */
$wallet = $this->createsWallet->execute($object, $company);
}
$billNumber = (App()->make(GeneratesTransactionBillNumber::class))->execute('TOPUP-');
if($total < 0) {
throw new MalformedRequestException('Top up credit value must be greater than zero.');
}
$billPlzBill = (App()->make(CreatesBillplzBill::class))->execute($company->name, 'example@gmail.com', 'This payment is credit topup for company ref. ' . $company->reference, $total, $billNumber, 'bank code', true);
$transaction_object = new TransactionObject($billNumber, TransactionType::TOP_UP, 1, $company->id, 1, PaymentMethodType::PAYMENT_GATEWAY, $total, $total, 1, 1, 1, 0, 0, null, ApprovalStatus::PENDING_SUBMISSION, [], 'test');
// $transaction = $this->createsTransaction->execute($wallet, $transaction_object);
$transaction = (App()->make(CreatesTransaction::class))->execute($wallet, $transaction_object);
$result= (App()->make(UpdatesWalletBalance::class))->execute($wallet, $total);
foreach ($transactions as $key => $value) {
multipleInvoicesWithOnePayment::create([ 'topUp_request_id' => $transaction->id, 'transaction_id' => $value->id ]);
}
dd($transaction->id);
}
}
@@ -8,7 +8,7 @@ use App\Classes\ValueObjects\Constants\OrderRoleTypes;
use App\Classes\ValueObjects\Constants\WarehouseReferences;
use App\Models\Order;
use Illuminate\Http\Request;
use Mccarlosen\LaravelMpdf\Facades\LaravelMpdf;
use Meneses\LaravelMpdf\Facades\LaravelMpdf;
class DownloadOrderQrPdfController
{
@@ -51,12 +51,9 @@ class DownloadOrderQrPdfController
if(strtolower($deliveryAddress->state->name) === 'sarawak' && !in_array(strtolower($deliveryAddress->district->name), ['limbang', 'lawas'])) {
$warehousePrefix = 'KU/';
}
if(strtolower($deliveryAddress->state->name) === 'johor') {
$warehousePrefix = 'NX/';
}
}
$data = [
'order' => $order,
'marking' => $warehousePrefix.$deliveryPrefix.'CIEF/'.$customerMarking,
@@ -0,0 +1,25 @@
<?php
namespace App\Http\Controllers\Orders;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Classes\Modules\Imports\Services\Importorder;
use Maatwebsite\Excel\Facades\Excel;
class OrderFromExcelController extends Controller
{
public function importView(){
return view('importFile');
}
public function import(Request $request){
Excel::import(new Importorder,
$request->file('file')->store('files'));
return redirect()->back();
}
}
@@ -6,7 +6,7 @@ use Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Mccarlosen\LaravelMpdf\Facades\LaravelMpdf;
use Meneses\LaravelMpdf\Facades\LaravelMpdf;
class TestController extends Controller
{
@@ -0,0 +1,15 @@
<?php
namespace App\Http\Controllers\Wallets;
use App\Classes\Modules\Wallets\ControllersLogic\CreateWalletLogic;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class CreateWalletController
{
public function create(Request $request, CreateWalletLogic $logic): JsonResponse {
return $logic->execute($request);
}
}
@@ -0,0 +1,15 @@
<?php
namespace App\Http\Controllers\Wallets;
use App\Classes\Modules\Wallets\ControllersLogic\CreateWalletTransactionLogic;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class CreateWalletTransactionController
{
public function create(Request $request, CreateWalletTransactionLogic $logic): JsonResponse {
return $logic->execute($request);
}
}
@@ -0,0 +1,15 @@
<?php
namespace App\Http\Controllers\Wallets;
use App\Classes\Modules\Wallets\ControllersLogic\CreditWalletLogic;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class CreditWalletController
{
public function credit(Request $request, CreditWalletLogic $logic): JsonResponse {
return $logic->execute($request);
}
}
@@ -0,0 +1,15 @@
<?php
namespace App\Http\Controllers\Wallets;
use App\Classes\Modules\Wallets\ControllersLogic\DebitWalletLogic;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class DebitWalletController
{
public function debit(Request $request, DebitWalletLogic $logic): JsonResponse {
return $logic->execute($request);
}
}
@@ -0,0 +1,14 @@
<?php
namespace App\Http\Controllers\Wallets;
use App\Classes\Modules\Wallets\ControllersLogic\ListWalletLogic;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class ListWalletController
{
public function list(Request $request, ListWalletLogic $logic): JsonResponse {
return $logic->execute($request);
}
}
@@ -0,0 +1,15 @@
<?php
namespace App\Http\Controllers\Wallets;
use App\Classes\Modules\Wallets\ControllersLogic\TopUpWalletLogic;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class TopUpWalletController
{
public function topUp(Request $request, TopUpWalletLogic $logic): JsonResponse {
return $logic->execute($request);
}
}
@@ -0,0 +1,14 @@
<?php
namespace App\Http\Controllers\Wallets;
use App\Classes\Modules\Wallets\ControllersLogic\UpdateStatusWalletLogic;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class UpdateStatusWalletController
{
public function updateStatus(Request $request, UpdateStatusWalletLogic $logic): JsonResponse {
return $logic->execute($request);
}
}
@@ -0,0 +1,29 @@
<?php
namespace App\Http\Controllers\Wallets;
use App\Classes\ValueObjects\Response\ApiResponseObject;
use App\Classes\ValueObjects\Constants\HttpStatus;
use App\Classes\ValueObjects\Constants\TransactionType;
use App\Models\Transaction;
use App\Models\Wallet;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class WalletReportController
{
public function walletsReport(Request $request): JsonResponse
{
return (new ApiResponseObject(
'fetch service report Successful',
'',
HttpStatus::OK_WITH_MESSAGE,
['data' => [
'walletSum' => (float) Wallet::all()->sum('amount'),
'outgoingSum' => (float) Transaction::where('type', TransactionType::PAYMENT)->where('owner_type', Wallet::class)->sum('amount'),
'incomingSum' => (float) Transaction::whereIn('type', [TransactionType::TOP_UP, TransactionType::CREDIT_NOTE])->where('owner_type', Wallet::class)->sum('amount'),
]]
))->handler();
}
}
@@ -0,0 +1,15 @@
<?php
namespace App\Http\Controllers\Wallets;
use App\Classes\Modules\Wallets\ControllersLogic\WithdrawWalletLogic;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class WithdrawWalletController
{
public function withdraw(Request $request, WithdrawWalletLogic $logic): JsonResponse {
return $logic->execute($request);
}
}
-1
View File
@@ -23,7 +23,6 @@ class CompanyResource extends JsonResource
'id' => $this->id,
'hash_id' => Crypt::encryptString($this->id),
'name' => $this->name,
'debtor' => $this->debtor,
'reference' => $this->reference,
'type' => (int) $this->type,
'business_type' => (int) $this->business_type,
-1
View File
@@ -29,7 +29,6 @@ class PackageResource extends JsonResource
'weight' => $this->weight,
'quantity' => $this->quantity,
'cbm' => (($this->width / 100) * ($this->height / 100) * ($this->length / 100)) * $this->quantity,
'reference' => $this->packingList->reference,
'status' => $this->status,
$this->mergeWhen($originalPackingList->owner instanceof Order, [
'order' => New OrderResource($originalPackingList->owner)
@@ -1,26 +0,0 @@
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class UserCompanyResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'reference' => $this->companyModule()->first()->inviters()->withPivot('invitee_reference')->first()->pivot->invitee_reference,
'type' => (int) $this->type,
'status' => (int) $this->status,
'email' => $this->email
];
}
}
+7
View File
@@ -102,4 +102,11 @@ class Company extends AbstractModel implements Documentable, Contactable
return $this->hasManyDeep(Package::class, [CompanyModule::class, Order::class, PackingList::class], ['company_id', 'company_module_id', ['owner_type', 'owner_id'], 'packing_list_id'], ['id', 'id', null, 'id']);
}
public function wallets(): morphMany
{
return $this->morphMany(Wallet::class, 'owner');
}
}
-2
View File
@@ -4,7 +4,6 @@ namespace App\Models;
use App\Classes\General\Interfaces\Remarkable;
use App\Classes\General\Interfaces\Transportable;
use App\Classes\General\Traits\LogData;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Relations\MorphMany;
@@ -15,7 +14,6 @@ class Container extends AbstractModel implements Transportable, Remarkable
{
use HasRelationships;
use SoftDeletes;
use LogData;
protected $table = 'containers';
-2
View File
@@ -7,7 +7,6 @@ use App\Classes\General\Interfaces\Transportable;
use App\Classes\General\Interfaces\Packable;
use App\Classes\General\Interfaces\Transactionable;
use App\Classes\General\Traits\LogData;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
@@ -24,7 +23,6 @@ class PackingList extends AbstractModel implements Transportable, Steppable, Pac
use HasTableAlias;
use HasRelationships;
use SoftDeletes;
use LogData;
protected $table = 'packing_lists';
+4 -2
View File
@@ -5,7 +5,6 @@ namespace App\Models;
use App\Classes\General\Interfaces\Documentable;
use App\Classes\General\Interfaces\Remarkable;
use App\Classes\General\Interfaces\Transactionable;
use App\Classes\General\Traits\LogData;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\TransactionType;
use Carbon\Carbon;
@@ -15,7 +14,7 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\Classes\General\Eloquent\LogData;
class Transaction extends AbstractModel implements Documentable, Transactionable, Remarkable
{
use SoftDeletes;
@@ -136,4 +135,7 @@ class Transaction extends AbstractModel implements Documentable, Transactionable
{
return $this->morphMany(Remark::class, 'owner');
}
}
+31
View File
@@ -0,0 +1,31 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class TransactionLog extends Model
{
use HasFactory;
protected $fillable = [
'owner',
'type',
'issuer',
'receiver',
'recipient_bank_account_id',
'payment_method',
'payment_reference',
'bill_no',
'amount',
'original_amount',
'currency_id',
'original_currency_id',
'currency_rate',
'tax',
'service_charge',
'expires_on',
'status',
];
}
+32
View File
@@ -0,0 +1,32 @@
<?php
namespace App\Models;
use App\Classes\General\Interfaces\Transactionable;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\MorphMany;
class Wallet extends AbstractModel implements Transactionable
{
use SoftDeletes;
protected $table = 'wallets';
/**
* @return \Illuminate\Database\Eloquent\Relations\MorphTo
*/
public function owner(): morphTo
{
return $this->morphTo();
}
/**
* @return morphMany
*/
public function transactions(): morphMany
{
return $this->morphMany(Transaction::class, 'owner');
}
}
+32
View File
@@ -0,0 +1,32 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Relations\HasOne;
class WalletTransaction extends AbstractModel
{
protected $table = 'wallet_transaction';
public function wallet(): HasOne
{
return $this->hasOne(Wallet::class, 'wallet_id', 'id');
}
public function transaction(): HasOne
{
return $this->hasOne(Transaction::class, 'transaction_id', 'id');
}
public function currency(): HasOne
{
return $this->hasOne(Currency::class, 'currency_id', 'id');
}
public function original_currency(): HasOne
{
return $this->hasOne(Currency::class, 'original_currency_id', 'id');
}
}
@@ -0,0 +1,19 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class multipleInvoicesWithOnePayment extends AbstractModel
{
use HasFactory;
protected $table = 'multiple_invoice_one_payments';
protected $fillable =[
'topUp_request_id',
'transaction_id'
];
}
Executable → Regular
View File
+2 -1
View File
@@ -64,7 +64,8 @@
"config": {
"optimize-autoloader": true,
"preferred-install": "dist",
"sort-packages": true
"sort-packages": true,
"platform-check": false
},
"minimum-stability": "dev",
"prefer-stable": true

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