Compare commits

..

1 Commits

Author SHA1 Message Date
Cleison Freitas 27c3cd4275 FetchInvoice API to multiple payments 2022-12-27 12:34:29 -03:00
67 changed files with 1225 additions and 2942 deletions
@@ -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);
}
}
@@ -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());
}
}
}
@@ -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,
];
}
}
@@ -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);
@@ -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,41 @@ 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\CompanyModule;
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 +53,214 @@ 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();
$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;
$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 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();
}
}
$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);
});
});
$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
{
@@ -0,0 +1,55 @@
<?php
namespace App\Classes\Modules\Transactions\ControllersLogic;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Transactions\Services\FetchPayments;
use App\Classes\Modules\Transactions\Services\ListsTransactions;
use App\Http\Resources\InvoiceResource;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class FetchInvoiceLogic extends AbstractControllerLogic
{
/**
* ListTransactionsLogic constructor.
* @param FetchPayments $fetchPayments
*/
public function __construct(FetchPayments $fetchPayments)
{
$this->fetchPayments = $fetchPayments;
}
/**
* @return array
*/
protected function notification():array {
return [
'title' => 'Retrieved Transactions',
'message' => 'You have successfully retrieved a list of transactions'
];
}
/** @var FetchPayments */
private $fetchPayments;
public function logic(Request $request) : JsonResponse
{
$query = $this->fetchPayments->execute($this->fetchPayments->deserializeFilters($request->input('filters')));
return $this->collectionResponse(InvoiceResource::collection($query));
}
}
?>
@@ -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;
@@ -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;
}
}
}
@@ -0,0 +1,31 @@
<?php
namespace App\Classes\Modules\Transactions\Services;
use App\Models\Transaction;
use Illuminate\Database\Eloquent\Builder;
use App\Classes\General\Eloquent\AbstractListRecord;
class FetchPayments extends AbstractListRecord
{
/** @var Transaction */
private $repository;
/**
* ListsBookings constructor.
* @param Transaction $repository
*/
public function __construct(Transaction $repository)
{
$this->repository = $repository;
}
/**
* @return Builder
*/
public function getRepository(): Builder
{
return $this->repository->newQuery();
}
}
@@ -1,82 +0,0 @@
<?php
namespace App\Console\Commands;
use App\Classes\Modules\PackingLists\Services\ListsPackingLists;
use App\Classes\Modules\Transactions\Processors\CreateInvoiceTransactionProcessor;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Models\Order;
use Carbon\Carbon;
use Exception;
use Illuminate\Console\Command;
class AutoGenerateInvoice extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'invoice:generate';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Auto generate invoice';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
$packingLists = (App()->make(ListsPackingLists::class))->execute(['does_not_have_transaction_type' => 1, 'type' => 2]);
if (count($packingLists)) {
$this->info(Carbon::now() . ' : Auto generate invoice cron started.');
$start = new Carbon();
foreach ($packingLists as $packingList) {
$order = $packingList->owner;
if (!($order instanceof Order)) {
$this->info('Failed to generate invoice for reference' . $order->reference . '. It is not an instance of Order.');
continue;
}
$companyModule = $order->companyModule;
$billingAddress = $companyModule->addresses()->where('type', \App\Classes\ValueObjects\Constants\AddressType::BILLING)->first();
$deliveryAddress = $order->addresses()->where('status', ApprovalStatus::APPROVED)->first();
$postCodes = \App\Models\SegmentConstant::whereIn('reference', ['CENTER_POSTCODE', 'OUTSTATION_POSTCODE'])->get()->pluck('value')->flatten();
if (!!$billingAddress && in_array($deliveryAddress->postcode, $postCodes->toArray())) {
try {
(App()->make(CreateInvoiceTransactionProcessor::class))->execute($packingList);
$this->info('Invoice generated for reference ' . $order->reference . '.');
} catch (Exception $exception) {
$this->info('Failed to generate invoice for reference ' . $order->reference . '. Exception: ' . $exception->getMessage());
}
}
$this->info('Failed to generate invoice for reference ' . $order->reference . '. Billing Address is not defined / Postcode area is not defined.');
}
$end = new Carbon();
$elapsedTime = $start->diff($end)->format('%H:%I:%S');
$this->info(Carbon::now() . ' : Done generating invoice. ElapsedTime: ' . $elapsedTime . '.');
}
}
}
+1 -4
View File
@@ -43,10 +43,7 @@ class Kernel extends ConsoleKernel
->withoutOverlapping()
->appendOutputTo (storage_path().'/logs/departure_email.log');
$schedule->command('invoice:generate')
->hourly()
->withoutOverlapping()
->appendOutputTo (storage_path().'/logs/auto_generate_invoice.log');
}
/**
@@ -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;
}
}
@@ -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,20 @@
<?php
namespace App\Http\Controllers\Orders;
use App\Classes\Modules\Orders\ControllersLogic\FetchOrderLogic;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class FetchMultipleOrderController
{
/**
* @param Request $request
* @param FetchOrderLogic $logic
* @return JsonResponse
*/
public function fetch(Request $request, FetchOrderLogic $logic): JsonResponse
{
return $logic->execute($request);
}
}
@@ -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,32 @@
<?php
namespace App\Http\Controllers\Transactions;
use App\Classes\Modules\Transactions\ControllersLogic\FetchInvoiceLogic;
use App\Classes\Modules\Transactions\ControllersLogic\ListTransactionsLogic;
use App\Http\Controllers\Controller;
use App\Http\Resources\InvoiceResource;
use App\Models\Order;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class FetchInvoiceController extends Controller
{
public function list(Request $request)
{
try{
return InvoiceResource::collection(Order::Paginate(10,['*'],'page',2));
}catch(\Exception $ex) {
return response()->json(['error' => [$ex->getMessage()]],404);
}
}
/**
* @param Request $request
* @param FetchInvoiceLogic $logic
* @return JsonResponse
*/
public function fetch(Request $request, FetchInvoiceLogic $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,
+28
View File
@@ -0,0 +1,28 @@
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class InvoiceResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
*/
public function toArray($request)
{
return [
'invoice_id' => $this->reference,
'carrier_tracking_number' => '1zbr06tw403742920',
'this_package_was_delivered' => '1zbr06tw403742920',
'due_date' => '11.04.2021',
'date_paid' => '21.01.2021',
'outstanding' => 92.01
];
}
}
-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
];
}
}
+2 -2
View File
@@ -178,7 +178,7 @@ return [
// Third Parties
Spatie\Permission\PermissionServiceProvider::class,
Barryvdh\DomPDF\ServiceProvider::class,
Mccarlosen\LaravelMpdf\LaravelMpdfServiceProvider::class,
Meneses\LaravelMpdf\LaravelMpdfServiceProvider::class,
Maatwebsite\Excel\ExcelServiceProvider::class,
],
@@ -233,7 +233,7 @@ return [
'Validator' => Illuminate\Support\Facades\Validator::class,
'View' => Illuminate\Support\Facades\View::class,
'PDF' => Barryvdh\DomPDF\Facade::class,
'MPDF' => Mccarlosen\LaravelMpdf\Facades\LaravelMpdf::class,
'MPDF' => Meneses\LaravelMpdf\Facades\LaravelMpdf::class,
'Excel' => Maatwebsite\Excel\Facades\Excel::class,
],
@@ -208,12 +208,12 @@
<input class="form-control" v-model="parameters.email">
</validation-wrapper-component>
</div>
<!-- <div class="col-4 p-l-5">
<div class="col-4 p-l-5">
<validation-wrapper-component :validator="$v.parameters.wechat_id">
<label>WeChat ID</label>
<input class="form-control" v-model="parameters.wechat_id">
</validation-wrapper-component>
</div> -->
</div>
</div>
<div class="row m-b-15">
@@ -13,14 +13,7 @@
<div class="col-auto">
<div class="row">
<div class="col">
<modal-component class="animate__animated animate__fast animate__fadeIn" styleType="fill-in" type="changeCustomerName">
<change-customer-name-form-component :section="'customerProfileSection'" :data="item"></change-customer-name-form-component>
</modal-component>
<div class="font-heading fs-20 light">{{item.name}}
<div class="btn btn-xs b-rad-none pointer requestModal d-inline rounded no-border hover-primary" data-type="changeCustomerName" >
<i class="fa fa-edit pointer fa-fw fs-15 m-l-5"></i>
</div>
</div>
<div class="font-heading fs-20 light">{{item.name}}</div>
</div>
</div>
<div class="row">
@@ -39,12 +32,6 @@
</div>
<div class="col-auto">
<div class="row align-items-center parentContainer">
<div class="col-auto padding-5 b-a b-grey b-rad-lg pointer m-r-15" @click="hrefPaymenBillingPage">
<svg xmlns="http://www.w3.org/2000/svg" x="0px" y="0px"
width="35" height="35"
viewBox="0 0 172 172"
style=" fill:#000000;"><defs><linearGradient x1="69.875" y1="96.52694" x2="69.875" y2="108.37075" gradientUnits="userSpaceOnUse" id="color-1_44039_gr1"><stop offset="0" stop-color="#4ec9ff"></stop><stop offset="1" stop-color="#2bffe6"></stop></linearGradient><linearGradient x1="86" y1="21.05119" x2="86" y2="153.19019" gradientUnits="userSpaceOnUse" id="color-2_44039_gr2"><stop offset="0" stop-color="#009add"></stop><stop offset="1" stop-color="#00baa4"></stop></linearGradient><linearGradient x1="80.625" y1="21.05119" x2="80.625" y2="153.19019" gradientUnits="userSpaceOnUse" id="color-3_44039_gr3"><stop offset="0" stop-color="#009add"></stop><stop offset="1" stop-color="#00baa4"></stop></linearGradient><linearGradient x1="75.25" y1="21.05119" x2="75.25" y2="153.19019" gradientUnits="userSpaceOnUse" id="color-4_44039_gr4"><stop offset="0" stop-color="#009add"></stop><stop offset="1" stop-color="#00baa4"></stop></linearGradient><linearGradient x1="69.875" y1="21.05119" x2="69.875" y2="153.19019" gradientUnits="userSpaceOnUse" id="color-5_44039_gr5"><stop offset="0" stop-color="#009add"></stop><stop offset="1" stop-color="#00baa4"></stop></linearGradient><linearGradient x1="129" y1="21.05119" x2="129" y2="153.19019" gradientUnits="userSpaceOnUse" id="color-6_44039_gr6"><stop offset="0" stop-color="#009add"></stop><stop offset="1" stop-color="#00baa4"></stop></linearGradient><linearGradient x1="139.75" y1="21.05119" x2="139.75" y2="153.19019" gradientUnits="userSpaceOnUse" id="color-7_44039_gr7"><stop offset="0" stop-color="#009add"></stop><stop offset="1" stop-color="#00baa4"></stop></linearGradient><linearGradient x1="118.25" y1="21.05119" x2="118.25" y2="153.19019" gradientUnits="userSpaceOnUse" id="color-8_44039_gr8"><stop offset="0" stop-color="#009add"></stop><stop offset="1" stop-color="#00baa4"></stop></linearGradient></defs><g fill="none" fill-rule="nonzero" stroke="none" stroke-width="1" stroke-linecap="butt" stroke-linejoin="miter" stroke-miterlimit="10" stroke-dasharray="" stroke-dashoffset="0" font-family="none" font-weight="none" font-size="none" text-anchor="none" style="mix-blend-mode: normal"><path d="M0,172v-172h172v172z" fill="none"></path><g><path d="M86,104.8125c0,1.4835 -1.204,2.6875 -2.6875,2.6875h-26.875c-1.4835,0 -2.6875,-1.204 -2.6875,-2.6875v-5.375c0,-1.4835 1.204,-2.6875 2.6875,-2.6875h26.875c1.4835,0 2.6875,1.204 2.6875,2.6875z" fill="url(#color-1_44039_gr1)"></path><path d="M154.0045,83.57856c-1.58025,-1.87856 -3.913,-2.95356 -6.407,-2.95356h-5.16v-8.0625c0,-4.44513 -4.03125,-8.0625 -8.0625,-8.0625v-26.875c0,-2.96431 -2.41069,-5.375 -5.375,-5.375h-38.65162l-3.88881,-7.77762c-0.91375,-1.83288 -2.75469,-2.97237 -4.80794,-2.97237h-18.17825h-1.66088h-18.8125c-2.96431,0 -5.375,2.41069 -5.375,5.375v96.75h-21.5v13.4375c0,7.40944 6.02806,13.4375 13.4375,13.4375h91.375c7.40944,0 13.4375,-6.02806 13.4375,-13.4375v-18.8125h4.74344c6.80475,0 12.55869,-4.71119 13.68475,-11.20419l2.95625,-17.02263c0.39775,-2.29512 -0.23919,-4.644 -1.75494,-6.44463zM137.0625,72.5625v8.0625h-16.125v-8.0625c0,-1.4835 1.20669,-2.6875 2.6875,-2.6875h10.75c1.4835,0 2.6875,1.204 2.6875,2.6875zM129,43h-5.375v-5.375h5.375zM81.65163,26.875l2.6875,5.375h-15.49344l-2.6875,-5.375zM60.15163,26.875l3.88881,7.78031c0.91913,1.83019 2.76275,2.96969 4.81063,2.96969h49.39894v5.375h-75.25v-16.125zM29.5625,145.125c-4.44513,0 -8.0625,-3.61469 -8.0625,-8.0625v-8.0625h86v8.0625c0,3.02344 1.00244,5.375 2.69288,8.0625zM129,137.0625c0,4.44512 -3.61738,8.0625 -8.0625,8.0625c-4.44512,0 -8.0625,-3.61738 -8.0625,-8.0625v-13.4375h-69.875v-75.25h86v16.125h-5.375c-4.44512,0 -8.0625,3.61737 -8.0625,8.0625v8.0625h-5.16c-2.494,0 -4.82675,1.075 -6.407,2.95356c-1.51306,1.80062 -2.15269,4.1495 -1.75225,6.44194l2.95625,17.02531c1.12606,6.493 6.87731,11.20419 13.68475,11.20419h10.11575zM150.46237,89.10138l-2.95625,17.02531c-0.67725,3.91031 -4.20325,6.74831 -8.38769,6.74831h-20.23419c-4.18444,0 -7.71044,-2.838 -8.38769,-6.74831l-2.95625,-17.028c-0.172,-0.99706 0.28219,-1.72 0.57244,-2.064c0.55362,-0.65575 1.38675,-1.03469 2.28975,-1.03469h37.195c0.903,0 1.73613,0.37894 2.29244,1.03738c0.28756,0.344 0.74444,1.06425 0.57244,2.064z" fill="url(#color-2_44039_gr2)"></path><path d="M53.75,59.125h53.75v5.375h-53.75z" fill="url(#color-3_44039_gr3)"></path><path d="M53.75,69.875h43v5.375h-43z" fill="url(#color-4_44039_gr4)"></path><path d="M53.75,80.625h32.25v5.375h-32.25z" fill="url(#color-5_44039_gr5)"></path><path d="M126.3125,91.375h5.375v16.125h-5.375z" fill="url(#color-6_44039_gr6)"></path><path d="M137.0625,91.375h5.375v10.75h-5.375z" fill="url(#color-7_44039_gr7)"></path><path d="M115.5625,91.375h5.375v10.75h-5.375z" fill="url(#color-8_44039_gr8)"></path></g></g></svg>
</div>
<div class="col-auto padding-5 b-a b-grey b-rad-lg pointer requestModal" data-type="assignSegment">
<svg xmlns="http://www.w3.org/2000/svg" x="0px" y="0px"
width="30" height="30"
@@ -194,10 +181,7 @@
delay: 1000
});
$(this.$refs.copyButton).tooltip('show');
},
hrefPaymenBillingPage(){
window.location.href = route('customer.payment-and-billing', this.item.company_module.marking);
},
}
},
mixins: [componentHandler]
}
@@ -1,39 +0,0 @@
<template>
<div class="row m-b-15 align-items-end">
<div class="col-auto">
<div class="row">
<div class="col">
<div class="font-heading fs-10 muted all-caps">Name</div>
</div>
</div>
<div class="row">
<div class="col">
<div class="font-heading all-caps fs-11">{{this.item.name}}</div>
</div>
</div>
</div>
<div class="col-2 text-right">
<div class="row">
<div class="col">
<div class="font-heading fs-10 muted all-caps">Reference</div>
</div>
</div>
<div class="row">
<div class="col">
<div class="font-heading all-caps fs-11">{{this.item.reference}}</div>
</div>
</div>
</div>
<div class="col-auto">
<a :href="route('customer.profile', this.item.reference)" target="_blank">
<button type="button" class="btn btn-xs btn-primary fs-11">Open in new tab</button>
</a>
</div>
</div>
</template>
<script>
import componentHandler from '../../../general/mixins/componentHandler';
export default {
mixins: [componentHandler]
}
</script>
File diff suppressed because one or more lines are too long
@@ -20,15 +20,15 @@
</div>
<div class="col-auto">
<p class="no-margin fs-10 all-caps">ETD</p>
<p class="no-margin">{{item.transport ? (item.transport.current_schedule ? item.transport.current_schedule.etd : 'n/a') : 'n/a'}}</p>
<p class="no-margin">{{item.transport ? item.transport.current_schedule.etd : 'n/a'}}</p>
</div>
<div class="col-auto">
<p class="no-margin fs-10 all-caps">ETA</p>
<p class="no-margin">{{item.transport ? (item.transport.current_schedule ? item.transport.current_schedule.eta : 'n/a') : 'n/a'}}</p>
<p class="no-margin">{{item.transport ? item.transport.current_schedule.eta : 'n/a'}}</p>
</div>
<div class="col">
<div class="row hide" v-if="item.transport">
<div class="col" v-if="item.transport.current_schedule">
<div class="col">
<p class="no-margin fs-10 all-caps">Days Ago</p>
<p class="no-margin" :class="[{'text-success': item.transport.current_schedule.billing_days_left.value === '+'}, {'text-danger': item.transport.current_schedule.billing_days_left.value === '-'}]">
{{item.transport.current_schedule.billing_days_left.value}}
@@ -19,12 +19,6 @@
<p class="bold m-b-5 fs-12">{{item.description}}</p>
</div>
</div>
<div class="row m-b-10 align-items-center" v-if="$store.getters.isAdmin">
<div class="col-auto">
<p class="no-margin all-caps fs-10 lh-10 light">Reference</p>
<p class="no-margin fs-12">{{item.reference}}</p>
</div>
</div>
<div class="row b-t b-b b-grey m-b-15">
<div class="col">
<div class="row">
@@ -180,4 +174,4 @@
},
mixins: [componentHandler]
}
</script>
</script>
@@ -67,14 +67,6 @@
<p class="no-margin bold text-info fs-12"><a :href="route('customer.profile', item.order.company_module.marking)">{{item.order.company_module.marking}}</a></p>
</div>
</div>
<div class="row m-b-5" v-if="$store.getters.isAdmin">
<div class="col-auto p-r-5">
<p class="no-margin all-caps fs-10 light">Reference</p>
</div>
<div class="col p-l-5">
<p class="no-margin bold text-info fs-12">{{item.reference}}</p>
</div>
</div>
<div class="row m-b-5">
<div class="col-auto p-r-5">
<p class="no-margin all-caps fs-10 light">Order Number</p>
@@ -1,73 +0,0 @@
<template>
<div class="row" style="width: 450px; margin: auto;" @keyup.enter="submitForm">
<div class="col bg-white padding-40 b-rad-lg">
<div class="row m-b-10">
<div class="col text-center">
<h3>Edit Company Details</h3>
</div>
</div>
<div class="row">
<div class="col">
<validation-wrapper-component class="m-b-15" :validator="$v.parameters.name">
<label class="text-primary">Name</label>
<input class="form-control" v-model="parameters.name">
</validation-wrapper-component>
</div>
</div>
<div class="row">
<div class="col">
<validation-wrapper-component class="m-b-15" :validator="$v.parameters.debtor">
<label class="text-primary">Debtor Code</label>
<input class="form-control" v-model="parameters.debtor">
</validation-wrapper-component>
</div>
</div>
<div class="row m-t-15">
<div class="col-auto p-r-5">
<div class="btn btn-lg btn-default b-rad-none" data-dismiss="modal">Cancel</div>
</div>
<div class="col p-l-5">
<div class="btn btn-primary w-100 btn-lg" @click="submitForm">Confirm</div>
</div>
</div>
</div>
</div>
</template>
<script>
import modalFormHandler from '../../../general/mixins/modalFormHandler';
import { required, minLength } from "vuelidate/lib/validators";
export default {
data() {
return {
parameters: {
id: this.data.id,
name: this.data.name,
debtor: this.data.debtor,
reference: this.data.reference,
type: this.data.type,
}
};
},
validations: {
parameters: {
name: {
required,
// minLength: minLength(8)
},
debtor: {
},
}
},
methods: {
successHandler(response) {
window.location.replace(this.route('customers', response.payload.data.reference));
},
submitForm() {
this.submit(this.route('api.company.update.nameAndDebtor', this.data.id), 'put', this.section, true, true)
}
},
mixins: [modalFormHandler]
}
</script>
@@ -51,9 +51,11 @@
</div>
</div>
</div>
<div class="row text-center justify-content-center d-none">
<div class="row text-center justify-content-center">
<div class="col-8">
<!-- set warning text here -->
<p class="m-b-0 text-danger m-t-15" v-if="parameters.warehouse_id === 3">疫情因管控松动飙升其中几位仓库人员也不幸感染整个操作可能会受到影响我们会尽快跟进并恢复<br>The pandemic spread due to the loosening of movement controls. Some warehouse employees were unfortunately infected and the entire operation may be disrupted. We will do our best to follow up and revert as soon as possible.</p>
<p class="m-b-0 text-danger m-t-15" v-if="false">由于义乌船期不稳定建议发广州仓库<br>Due to unexpected shipping delays for Yiwu warehouse, you may select an alternative warehouse.</p>
<p class="m-b-0 text-danger m-t-15" v-if="parameters.warehouse_id === 4">由于义乌船期不稳定建议发广州仓库<br>Due to unexpected shipping delays for Yiwu warehouse, you may select an alternative warehouse.</p>
</div>
</div>
</div>
@@ -1,43 +1,113 @@
<template>
<div class="row m-b-15 m-l-5 m-r-10">
<div class="col bg-white rounded b-a" :class="{'b-white': !selected, 'b-primary': selected, 'bg-primary-lighter': selected}">
<div class="col bg-master-lightest rounded" :class="{'b-gray': !selected, 'b-primary': selected, 'bg-primary-lighter': selected}">
<div class="row">
<div class="col padding-20">
<div class="row align-items-center">
<div class="col-auto pointer align-items-center" @click="activate()">
<div class="col-auto pointer align-items-center" @click="selected = !selected">
<i class="fa fs-30 fa-fw" :class="{'fa-square-o': !selected, 'fa-check-square': selected, 'text-primary':selected}" ></i>
</div>
<div class="col">
<p class="no-margin fs-10 all-caps">Invoice No</p>
<div>{{ item.bill_no }}</div>
<h5 class="no-margin">{{item.country.id}}05052021</h5>
</div>
<div class="col">
<p class="no-margin fs-10 all-caps">Order</p>
<div><a :href="route('order.show', item.order.reference)">{{item.order.reference}}</a></div>
<h5 class="no-margin">Invoice Date Invoice Date</h5>
</div>
<div class="col">
<p class="no-margin fs-10 all-caps">Invoice Date</p>
<div>{{ item.created_at }}</div>
<h5 class="no-margin">Status</h5>
</div>
<div class="col">
<p class="no-margin fs-10 all-caps">Amount</p>
<div>MYR {{ item.amount.toFixed(2) }}</div>
<h5 class="no-margin">Amount</h5>
</div>
<div class="col-auto">
<div v-if="item.documents.length">
<div v-for="file in item.documents[0].files" v-bind:key="file.id" class="col-auto no-padding">
<document-file-viewer-component :file="file">
<template slot="button">
<div class="btn btn-success no-border muted">
<i class="fa fa-file-pdf-o"></i>
</div>
</template>
</document-file-viewer-component>
<div class="btn bg-grey no-border" @click="expanded = !expanded">
<i class="fa" :class="{'fa-angle-down': !expanded, 'fa-angle-up': expanded}" ></i>
</div>
</div>
</div>
</div>
</div>
<div class="row b-t b-grey p-t-10" v-show="expanded">
<div class="col p-b-10">
<div class="row">
<div class="col p-l-20 p-r-20 p-t-10 p-b-10">
<div class="row align-items-center">
<div class="col-auto invisible">
<i class="fa fs-30 fa-fw" :class="{'fa-square-o': !selected, 'fa-check-square': selected, 'text-primary':selected}" ></i>
</div>
<div class="col">
<div class="row">
<div class="col">
<h5 class="m-b-0">Carrier Tracking Number</h5>
</div>
</div>
<div class="row">
<div class="col">
<h5 class="semi-bold m-t-0 m-b-0 large-text">#1zbr06tw403742920</h5>
</div>
</div>
</div>
<div class="col">
<div class="row">
<div class="col">
<h5 class="m-b-0">Due Date</h5>
</div>
</div>
<div class="row">
<div class="col">
<h5 class="semi-bold m-t-0 m-b-0 large-text">11.04.2021</h5>
</div>
</div>
</div>
<div class="col">
<div class="row">
<div class="col">
<h5 class="semi-bold m-t-0 m-b-0 large-text">Outstanding</h5>
</div>
</div>
<div class="row">
<div class="col">
<h5 class="semi-bold m-t-0 m-b-0 large-text">RM0.00</h5>
</div>
</div>
</div>
</div>
<div v-else>
<div class="btn bg-grey no-border muted invisible">
<i class="fa fa-file-pdf-o"></i>
</div>
</div>
<div class="row">
<div class="col p-l-20 p-r-20 p-t-10 p-b-10">
<div class="row align-items-center">
<div class="col-auto invisible">
<i class="fa fs-30 fa-fw" :class="{'fa-square-o': !selected, 'fa-check-square': selected, 'text-primary':selected}" ></i>
</div>
<div class="col">
<div class="row">
<div class="col">
<h5 class="m-b-0 normal-text">This package was delivered by</h5>
</div>
</div>
<div class="row">
<div class="col">
<h5 class="semi-bold m-t-0 m-b-0 large-text">#1zbr06tw403742920</h5>
</div>
</div>
</div>
<div class="col">
<div class="row">
<div class="col">
<h5 class="m-b-0">Date Paid</h5>
</div>
</div>
<div class="row">
<div class="col">
<h5 class="semi-bold m-t-0 m-b-0 large-text">21.01.2021</h5>
</div>
</div>
</div>
<div class="col">
<div class="btn btn-outline-complete btn-lg">
Invoice Detail
</div>
</div>
</div>
</div>
@@ -50,33 +120,10 @@
<script>
import componentHandler from '../../../general/mixins/componentHandler';
export default {
props: {
selectedInvoice: {
type: Array,
required: false,
}
},
data(){
return {
expanded: false,
selectedValue: false,
}
},
methods: {
activate(){
this.select = !this.select;
this.$emit('input', this.data);
}
},
computed: {
selected() {
var response = false;
this.selectedInvoice.forEach((value, index) => {
if (value.id == this.item.id) {
response = true;
}
});
return response;
selected: false,
}
},
mixins: [componentHandler]
@@ -1,82 +0,0 @@
<template>
<div class="row" @keyup.enter="fetchReport">
<div class="col">
<div class="row m-b-15">
<div class="col-8 p-r-0">
<div class="row">
<div class="col p-r-0">
<div class="form-group no-margin form-group-default b-rad-none">
<label class="text-primary">Email</label>
<input type="text" class="form-control" v-model="email" />
</div>
</div>
</div>
</div>
<div class="col p-l-0">
<div class="btn btn-primary b-rad-none" @click="fetchReport()">
<i class="fa fa-search lh-40"></i>
</div>
<div class="btn btn-secondary b-rad-none" @click="resetSearch()">
<i class="fa fa-remove lh-40"></i>
</div>
</div>
</div>
<div class="row" v-if="search">
<div class="col bg-white padding-25">
<p v-if="!userCompany">{{ message }}</p>
<loading-component v-if="isLoading"></loading-component>
<user-company-component v-if="userCompany" :data="userCompany"></user-company-component>
</div>
</div>
</div>
</div>
</template>
<script>
import LoadingComponent from "../../general/elements/LoadingComponent";
export default {
components: {LoadingComponent},
data(){
return {
section: 'searchUserCompanyByEmailSection',
isLoading: false,
search: false,
email: '',
userCompany: null,
message: 'Searching...'
}
},
validations: {
marking: {},
},
methods: {
fetchReport(){
this.isLoading = true;
this.search = true;
this.userCompany = null;
this.message = 'Searching...';
this.submit(route('api.account.user.company', this.email), 'get', this.section, false, false);
},
successHandler(response){
this.isLoading = false;
this.report = response.payload.data;
if(response.payload.data != undefined)
this.userCompany = response.payload.data;
else
this.message = 'Customer not found';
},
errorHandler(response){
this.isLoading = false;
this.userCompany = null;
this.message = 'Customer not found';
},
resetSearch() {
this.userCompany = null;
this.search = false;
this.email = '';
message: 'Searching...';
}
}
}
</script>
@@ -17,9 +17,9 @@ export default {
required: requiredIf(function () { return this.step === 2 }),
numeric
},
// wechat_id: {
// required: requiredIf(function () { return this.step === 2 }),
// },
wechat_id: {
required: requiredIf(function () { return this.step === 2 }),
},
password: {
required: requiredIf(function () { return this.step === 2 }),
},
@@ -3,7 +3,6 @@
<div class="row" :class="[{'d-flex': $store.getters.isAdmin}]" v-if="$store.getters.isAdmin">
<div class="col">
<customer-activity-report-section-component></customer-activity-report-section-component>
<search-customer-by-email-component></search-customer-by-email-component>
<div class="row" v-show="!$store.getters.isShowing('customerActivityReportSection')">
<div class="col">
<customer-report-section-component></customer-report-section-component>
@@ -51,7 +51,7 @@
<h6>Unclaimed Packing Lists</h6>
</div>
</div>
<list-component section="unclaimedPackingListSection" :endpoint="route('api.packing_list.list')" :options="{claimant_id: 2307, owner_id: 1}">
<list-component section="unclaimedPackingListSection" :endpoint="route('api.packing_list.list')" :options="{claimant_id: 2037, owner_id: 1}">
<template slot="list" slot-scope="{data}">
<unclaimed-packinglist-component :data="data"></unclaimed-packinglist-component>
</template>
@@ -62,4 +62,4 @@
</div>
</div>
</div>
</div>
</div>
@@ -1,4 +0,0 @@
@extends('layouts.base_portal')
@section('inner_content')
<customer-payment-billing-section-component :company_module_id={{$company_module_id}}></customer-payment-billing-section-component>
@endsection
@@ -5,9 +5,135 @@
<br><br>
<div class="separator"><strong><i>{{ $invoice_transaction->bill_no }}</i></strong></div>
</htmlpageheader>
<table>
<tr>
<td class="header-logo">
<img src="{{ asset('images/ri_1.png') }}" alt="logo" id="logo" class="logo">
</td>
<td class="header-cief-address">
<span class="company-name">
<strong>
CIEF WORLDWIDE SDN BHD
</strong>
</span>
<span class="company-reg">(1134596-M)</span><br>
No. 72-3, Jalan Jalil 1,<br>
The Earth Bukit Jalil,<br>
57000 Kuala Lumpur<br>
Tel: 03-8082 1252
</td>
<td class="header-details">
<div class="title" style="font-size: 20px; text-transform: uppercase;">
<strong>
Invoice
</strong>
</div>
@include('pages.pdfs.shipping_invoice_inner', ['invoice_transaction' => $invoice_transaction])
<div class="number">Invoice No: {{ $invoice_transaction->bill_no }}</div>
@php
$companyModule = $invoice_transaction->owner->owner->companyModule;
@endphp
<div class="date">Date: {{ $invoice_transaction->created_at }}</div>
<div class="ref">Order No: {{ $invoice_transaction->owner->owner->reference }}</div>
<div class="ref">Container Ref: {{ $invoice_transaction->owner->containers()->first()->reference }}</div>
{{--<div class="d-none">{{ $companyModule->inviters()->withPivot('invitee_reference')->first()->pivot->invitee_reference }}</div>--}}
<div>&nbsp;</div>
</div>
</td>
</tr>
<tr>
<td colspan="3" class="bill-to">
<span class="sub-title">
Bill To
</span>
</td>
</tr>
<tr>
<td colspan="3" class="address">
<div class="label">
{{ $companyModule->name }}
</div>
<div class="address">
@php
$addresses = $companyModule->addresses()->where('status', '=', \App\Classes\ValueObjects\Constants\ApprovalStatus::APPROVED)->where('type', '=', \App\Classes\ValueObjects\Constants\AddressType::BILLING)->first();
@endphp
{{ $addresses->street_one }}
{{ $addresses->street_two }} ,
{{ $addresses->district()->first()->name }},
{{ $addresses->postcode }}
{{ $addresses->state()->first()->name }},
{{ $addresses->country()->first()->name }}
</div>
<div>
@php
$contact = $companyModule->contacts()->first();
@endphp
Phone: {{ $contact ? $contact->phone : '' }}
</div>
</td>
</tr>
</table>
<br>
<br>
<table class="line-table" style="overflow: wrap" autosize="1">
<thead>
<tr>
<th width="5%">No</th>
<th class="description">Description</th>
<th width="15%">Quantity</th>
<th width="20%">Unit Price (RM)</th>
<th width="20%">Total Amount<br>(RM)</th>
</tr>
</thead>
<tbody>
@foreach ($invoice_transaction->transactionDetails as $key => $transaction_detail)
<tr>
<td width="5%" class="center top">{{ $key + 1 }}</td>
<td class="description">{!! $transaction_detail->name !!}</td>
<td width="15%" class="center top" style="text-align: center">{{ round($transaction_detail->quantity, 3) }}</td>
<td width="20%" class="center top" style="text-align: center">
{{ round($transaction_detail->price, 2) }}
</td>
<td width="20%" class="right top">
{{ round($transaction_detail->amount, 2) }}
</td>
</tr>
@endforeach
</tbody>
<tfoot>
<tr class="subtotal">
<td colspan="3"></td>
<td class="right middle">Subtotal</td>
<td class="right middle">
{{ round($invoice_transaction->amount, 2) }}
</td>
</tr>
<tr class="billingcharges">
<td colspan="3"></td>
<td class="right">Service Charges</td>
<td class="right">
{{ round($invoice_transaction->service_charge, 2) }}
</td>
</tr>
@if($invoice_transaction->tax > 0)
<tr class="billingcharges">
<td colspan="3"></td>
<td class="right">Tax</td>
<td class="right">{{ number_format($invoice_transaction->tax, 2) }}</td>
</tr>
@endif
<tr>
<td colspan="3"></td>
<td class="right middle">Total</td>
<td class="total right middle">
{{ round($invoice_transaction->amount, 2) }}
</td>
</tr>
</tfoot>
</table>
<htmlpagefooter name="page-footer">
<table width="100%">
<tr>
@@ -1,129 +0,0 @@
<table>
<tr>
<td class="header-logo">
<img src="{{ asset('images/ri_1.png') }}" alt="logo" id="logo" class="logo">
</td>
<td class="header-cief-address">
<span class="company-name">
<strong>
CIEF WORLDWIDE SDN BHD
</strong>
</span>
<span class="company-reg">(1134596-M)</span><br>
No. 72-3, Jalan Jalil 1,<br>
The Earth Bukit Jalil,<br>
57000 Kuala Lumpur<br>
Tel: 03-8082 1252
</td>
<td class="header-details">
<div class="title" style="font-size: 20px; text-transform: uppercase;">
<strong>
Invoice
</strong>
</div>
<div class="number">Invoice No: {{ $invoice_transaction->bill_no }}</div>
@php
$companyModule = $invoice_transaction->owner->owner->companyModule;
@endphp
<div class="date">Date: {{ $invoice_transaction->created_at }}</div>
<div class="ref">Order No: {{ $invoice_transaction->owner->owner->reference }}</div>
<div class="ref">Container Ref: {{ $invoice_transaction->owner->containers()->first()->reference }}</div>
{{--<div class="d-none">{{ $companyModule->inviters()->withPivot('invitee_reference')->first()->pivot->invitee_reference }}</div>--}}
<div>&nbsp;</div>
</div>
</td>
</tr>
<tr>
<td colspan="3" class="bill-to">
<span class="sub-title">
Bill To
</span>
</td>
</tr>
<tr>
<td colspan="3" class="address">
<div class="label">
{{ $companyModule->name }}
</div>
<div class="address">
@php
$addresses = $companyModule->addresses()->where('status', '=', \App\Classes\ValueObjects\Constants\ApprovalStatus::APPROVED)->where('type', '=', \App\Classes\ValueObjects\Constants\AddressType::BILLING)->first();
@endphp
{{ $addresses->street_one }}
{{ $addresses->street_two }} ,
{{ $addresses->district()->first()->name }},
{{ $addresses->postcode }}
{{ $addresses->state()->first()->name }},
{{ $addresses->country()->first()->name }}
</div>
<div>
@php
$contact = $companyModule->contacts()->first();
@endphp
Phone: {{ $contact ? $contact->phone : '' }}
</div>
</td>
</tr>
</table>
<br>
<br>
<table class="line-table" style="overflow: wrap" autosize="1">
<thead>
<tr>
<th width="5%">No</th>
<th class="description">Description</th>
<th width="15%">Quantity</th>
<th width="20%">Unit Price (RM)</th>
<th width="20%">Total Amount<br>(RM)</th>
</tr>
</thead>
<tbody>
@foreach ($invoice_transaction->transactionDetails as $key => $transaction_detail)
<tr>
<td width="5%" class="center top">{{ $key + 1 }}</td>
<td class="description">{!! $transaction_detail->name !!}</td>
<td width="15%" class="center top" style="text-align: center">{{ round($transaction_detail->quantity, 3) }}</td>
<td width="20%" class="center top" style="text-align: center">
{{ round($transaction_detail->price, 2) }}
</td>
<td width="20%" class="right top">
{{ round($transaction_detail->amount, 2) }}
</td>
</tr>
@endforeach
</tbody>
<tfoot>
<tr class="subtotal">
<td colspan="3"></td>
<td class="right middle">Subtotal</td>
<td class="right middle">
{{ round($invoice_transaction->amount, 2) }}
</td>
</tr>
<tr class="billingcharges">
<td colspan="3"></td>
<td class="right">Service Charges</td>
<td class="right">
{{ round($invoice_transaction->service_charge, 2) }}
</td>
</tr>
@if($invoice_transaction->tax > 0)
<tr class="billingcharges">
<td colspan="3"></td>
<td class="right">Tax</td>
<td class="right">{{ number_format($invoice_transaction->tax, 2) }}</td>
</tr>
@endif
<tr>
<td colspan="3"></td>
<td class="right middle">Total</td>
<td class="total right middle">
{{ round($invoice_transaction->amount, 2) }}
</td>
</tr>
</tfoot>
</table>
@@ -1,143 +0,0 @@
@extends('layouts.base_pdf')
@section('inner_content')
@php
$grandTotal = 0;
$grandSubTotal = 0;
@endphp
<table>
<tr>
<td class="header-logo">
<img src="{{ asset('images/ri_1.png') }}" alt="logo" id="logo" class="logo">
</td>
<td class="header-cief-address">
<span class="company-name">
<strong>
CIEF WORLDWIDE SDN BHD
</strong>
</span>
<span class="company-reg">(1134596-M)</span><br>
No. 72-3, Jalan Jalil 1,<br>
The Earth Bukit Jalil,<br>
57000 Kuala Lumpur<br>
Tel: 03-8082 1252
</td>
<td class="header-details">
<div class="title" style="font-size: 20px; text-transform: uppercase;">
<strong>
Summary
</strong>
</div>
@php
$companyModule = $invoice_transactions[0]->owner->owner->companyModule;
@endphp
{{-- <div class="date">Date: {{ $invoice_transactions[0]->created_at }}</div> --}}
<div class="date">Date: {{ \Carbon\Carbon::now() }}</div>
<div>&nbsp;</div>
</div>
</td>
</tr>
<tr>
<td colspan="3" class="bill-to">
<span class="sub-title">
Bill To
</span>
</td>
</tr>
<tr>
<td colspan="3" class="address">
<div class="label">
{{ $companyModule->name }}
</div>
<div class="address">
@php
$addresses = $companyModule->addresses()->where('status', '=', \App\Classes\ValueObjects\Constants\ApprovalStatus::APPROVED)->where('type', '=', \App\Classes\ValueObjects\Constants\AddressType::BILLING)->first();
@endphp
{{ $addresses->street_one }}
{{ $addresses->street_two }} ,
{{ $addresses->district()->first()->name }},
{{ $addresses->postcode }}
{{ $addresses->state()->first()->name }},
{{ $addresses->country()->first()->name }}
</div>
<div>
@php
$contact = $companyModule->contacts()->first();
@endphp
Phone: {{ $contact ? $contact->phone : '' }}
</div>
</td>
</tr>
</table>
<br>
<br>
<table class="line-table" style="overflow: wrap" autosize="1">
<thead>
<tr>
<th width="5%">No</th>
<th class="description">Invoice No</th>
<th class="description">Description</th>
<th width="15%">Quantity</th>
<th width="20%">Unit Price (RM)</th>
<th width="20%">Total Amount<br>(RM)</th>
</tr>
</thead>
<tbody>
@foreach ($invoice_transactions as $key => $invoice_transaction)
@foreach ($invoice_transaction->transactionDetails as $transaction_detail)
<tr>
<td width="5%" class="center top">{{ $key + 1 }}</td>
<td width="15%" class="center top">{{ $invoice_transaction->bill_no }}</td>
<td class="description">{!! $transaction_detail->name !!}</td>
<td width="15%" class="center top" style="text-align: center">{{ round($transaction_detail->quantity, 3) }}</td>
<td width="15%" class="center top" style="text-align: center">
{{ round($transaction_detail->price, 2) }}
</td>
<td width="15%" class="right top">
{{ round($transaction_detail->amount, 2) }}
</td>
</tr>
@endforeach
@php
$grandSubTotal = $grandSubTotal + round($invoice_transaction->amount, 2);
$grandTotal = $grandTotal + round($invoice_transaction->amount, 2);
@endphp
@endforeach
</tbody>
<tfoot>
<tr class="subtotal">
<td colspan="4"></td>
<td class="right middle">Subtotal</td>
<td class="right middle">
{{ round($grandSubTotal, 2) }}
</td>
</tr>
<tr>
<td colspan="4"></td>
<td class="right middle">Total</td>
<td class="total right middle">
{{ round($grandTotal, 2) }}
</td>
</tr>
</tfoot>
</table>
@foreach ($invoice_transactions as $transaction)
<pagebreak />
@include('pages.pdfs.shipping_invoice_inner', ['invoice_transaction' => $transaction])
@endforeach
<htmlpagefooter name="page-footer">
<table width="100%">
<tr>
<td style="text-align: right; ">This is generated by computer. No signature required.</td>
<td style="text-align: right; ">Page {PAGENO} of {nbpg}</td>
</tr>
</table>
</htmlpagefooter>
@endsection
File diff suppressed because one or more lines are too long
-1
View File
@@ -35,7 +35,6 @@ Route::group(['prefix' => 'account', 'namespace' => 'Accounts', 'as' => 'account
});
Route::group(['middleware' => 'valid.token', 'prefix' => 'user', 'as' => 'user.'], function () {
Route::get('/{email}', 'FetchUserByEmailController@fetch')->name('company');
Route::post('/show', 'FetchUserController@fetch')->name('show');
Route::get('/list', 'ListUsersController@list')->name('list');
Route::put('/update/{id}', 'UpdateUserController@update')->name('update');
+2 -2
View File
@@ -24,12 +24,12 @@ Route::group(['middleware' => 'api', 'prefix' => 'v1', 'as' => 'api.'], function
require __DIR__ . '/delivery.php';
Route::group(['middleware' => 'valid.token'], function () {
Route::group([/*'middleware' => 'valid.token'*/], function () {
Route::get('/storage/{fileName}/fetch', 'Documents\RenderDocumentController@fileStorageServe')->where(['fileName' => '.*'])->name('storage.document.file');
Route::post('online_payment/callback', 'Billplz\CallbackBillplzController@callback')->name('online_payment.callback');
Route::post('/import/update-debtor/f614e339d7058904a831aad742e24d55', 'Imports\ImportUpdateDebtorController@import')->name('debtor.import');
require __DIR__ . '/company.php';
-1
View File
@@ -8,7 +8,6 @@ Route::group(['prefix' => 'company', 'as' => 'company.', 'namespace' => 'Compani
Route::post('/create', 'CreateCompanyController@create')->name('create');
Route::put('/update/{id}', 'UpdateCompanyController@update')->name('update');
Route::delete('/delete/{id}', 'DeleteCompanyController@destroy')->name('delete');
Route::put('/name-and-debtor/update/{id}', 'UpdateCompanyNameAndDebtorController@update')->name('update.nameAndDebtor');
Route::post('/team/create', 'AddNewMemberController@create')->name('team.create');
+2
View File
@@ -1,5 +1,6 @@
<?php
use App\Http\Controllers\Transactions\FetchInvoiceController;
use Illuminate\Support\Facades\Route;
Route::group(['prefix' => 'order', 'as' => 'order.', 'namespace' => 'Orders'], function () {
@@ -18,4 +19,5 @@ Route::group(['prefix' => 'order', 'as' => 'order.', 'namespace' => 'Orders'], f
Route::put('/assign-remark/{id}', 'AssignOrderRemarkController@create')->name('assign.remark');
Route::get('/{id}/shipping-cost', 'ShippingCostController@calculate')->name('shipping.cost');
Route::get('/payments_billings' , [FetchInvoiceController::class,'fetch'])->name('shipping.invoice');
});
+48 -197
View File
@@ -7,43 +7,20 @@ use App\Classes\Jobs\FetchLoadedContainersFromVTPortalJob;
use App\Classes\Jobs\FetchOrdersFromYDPortalJob;
use App\Classes\Jobs\FetchPackingListFromVTPortalJob;
use App\Classes\Jobs\FetchWarehouseReceiveListFromVTPortalJob;
use App\Classes\Modules\Documents\DataTransferObjects\DocumentObject;
use App\Classes\Modules\Documents\Services\CreatesDocument;
use App\Classes\Modules\Documents\Services\CreatesFiles;
use App\Classes\Modules\Orders\Processors\UpdateDoFromVTPortalProcessor;
use App\Classes\Modules\Orders\Processors\UpdateDoFromYDPortalProcessor;
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\FetchLoadedContainersFromVTPortalProcessor;
use App\Classes\Modules\PackingLists\Processors\FetchOrderListsFromYdPortalProcessor;
use App\Classes\Modules\PackingLists\Processors\FetchPackingListFromVTPortalProcessor;
use App\Classes\Modules\PackingLists\Processors\FetchPackingListsFromYdPortalProcessor;
use App\Classes\Modules\PackingLists\Services\ListsPackingLists;
use App\Classes\Modules\Transactions\Processors\ApproveShippingInvoiceTransactionProcessor;
use App\Classes\Modules\Transactions\Processors\CreateInvoiceTransactionProcessor;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\BusinessType;
use App\Classes\ValueObjects\Constants\DocumentType;
use App\Classes\ValueObjects\Constants\OrderRoleTypes;
use App\Classes\ValueObjects\Constants\PackageType;
use App\Classes\ValueObjects\Constants\PackingListType;
use App\Classes\ValueObjects\Constants\PaymentMethodType;
use App\Classes\ValueObjects\Constants\TransactionType;
use App\Models\CompanyConnection;
use App\Models\CompanyModule;
use App\Models\Document;
use App\Models\Order;
use App\Models\PackingList;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;
use App\Models\Container;
use App\Models\Transaction;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Route;
use Mccarlosen\LaravelMpdf\Facades\LaravelMpdf;
/*
|--------------------------------------------------------------------------
@@ -183,16 +160,10 @@ Route::get('/customer/{marking}/details', function ($marking) {
return view('pages.customers.profile_details', ['id' => $id]);
})->name('customer.profile.details');
Route::get('/customer/{marking}/payment-and-billing', function ($marking) {
$connection = CompanyConnection::where('invitee_reference', $marking)->first();
$company_module_id = $connection->invitee->id;
return view('pages.customers.paymentsBilling', ['company_module_id' => $company_module_id]);
})->name('customer.payment-and-billing');
Route::get('/orders/refresh', function(Request $request){
$packingLists = PackingList::where('type', PackingListType::WAREHOUSE_RECEIVE_LIST)->has('containers')->get();
Route::get('/orders/refresh', function(\Illuminate\Http\Request $request){
$packingLists = \App\Models\PackingList::where('type', \App\Classes\ValueObjects\Constants\PackingListType::WAREHOUSE_RECEIVE_LIST)->has('containers')->get();
dd($packingLists);
$packingLists->each(function (PackingList $packingList) {
$packingLists->each(function (\App\Models\PackingList $packingList) {
$packingList->containers()->detach();
});
FetchWarehouseReceiveListFromVTPortalJob::withChain([
@@ -206,7 +177,7 @@ Route::get('/orders/refresh', function(Request $request){
Route::get('/containers/refresh', function(){
dd((App()->make(FetchLoadedContainersFromVTPortalProcessor::class))->execute());
dd((App()->make(\App\Classes\Modules\PackingLists\Processors\FetchLoadedContainersFromVTPortalProcessor::class))->execute());
// FetchLoadedContainersFromVTPortalJob::dispatch();
// FetchContainersStatusUpdateFromVTPortalJob::dispatch();
@@ -227,9 +198,9 @@ Route::get('/order/{id}/download', 'Orders\DownloadOrderQrPdfController@download
Route::get('/report/customclearance/{orderid}', 'Reports\CustomcClearanceReportController@download')->name('report.customclearance');
Route::group(['prefix' => 'template', 'as' => 'template.'], function () {
Route::get('/payment-and-billing', function () {
Route::get('/payments-and-billing', function () {
return view('pages.templates.paymentsBilling');
})->name('payment-and-billing');
})->name('payments-and-billing');
Route::get('/shipping-queue', function () {
return view('pages.templates.shippingQueue');
@@ -237,8 +208,8 @@ Route::group(['prefix' => 'template', 'as' => 'template.'], function () {
});
Route::get('/yiwu', function () {
$orders = Order::whereHas('OrderRoles', function($query){
return $query->where('role_id', OrderRoleTypes::ORIGIN_WAREHOUSE)->where('company_module_id', 2358);
$orders = \App\Models\Order::whereHas('OrderRoles', function($query){
return $query->where('role_id', \App\Classes\ValueObjects\Constants\OrderRoleTypes::ORIGIN_WAREHOUSE)->where('company_module_id', 2358);
})->get();
foreach ($orders as $order){
@@ -248,10 +219,10 @@ Route::get('/yiwu', function () {
});
Route::get('/guangzhou', function () {
$orders = Order::whereHas('OrderRoles', function($query){
return $query->where('role_id', OrderRoleTypes::ORIGIN_WAREHOUSE)->where('company_module_id', 3);
$orders = \App\Models\Order::whereHas('OrderRoles', function($query){
return $query->where('role_id', \App\Classes\ValueObjects\Constants\OrderRoleTypes::ORIGIN_WAREHOUSE)->where('company_module_id', 3);
})->whereHas('addresses', function($query){
return $query->where('status', ApprovalStatus::APPROVED)->whereIn('state_id', [5, 13, 14]);
return $query->where('status', \App\Classes\ValueObjects\Constants\ApprovalStatus::APPROVED)->whereIn('state_id', [5, 13, 14]);
})->get();
foreach ($orders as $order){
@@ -261,7 +232,7 @@ Route::get('/guangzhou', function () {
});
Route::get('/debug', function (){
$orders = Order::all();
$orders = \App\Models\Order::all();
$issues = [];
foreach ($orders as $order){
@@ -279,39 +250,18 @@ Route::get('/debug', function (){
dd($issues);
});
Route::group(['prefix' => 'yd', 'as' => 'yd.'], function () {
Route::get('/packingLists', function (Request $request){
$start = $request->input('start_date') ? Carbon::parse($request->input('start_date')): null;
$end = $request->input('end_date') ? Carbon::parse($request->input('end_date')): null;
(App()->make(FetchPackingListsFromYdPortalProcessor::class))->execute($start, $end);
});
Route::get('/containers', function (){
(App()->make(FetchContainersFromYdPortalProcessor::class))->execute();
(App()->make(FetchContainersUpdatesFromYdPortalProcessor::class))->execute();
});
Route::get('/deliveries', function (){
(App()->make(FetchDeliveryUpdatesFromYdPortalProcessor::class))->execute();
});
});
Route::get('/yd', function (Request $request){
// $start = $request->input('start_date') ? Carbon::parse($request->input('start_date')): null;
// $end = $request->input('end_date') ? Carbon::parse($request->input('end_date')): null;
// (App()->make(FetchOrderListsFromYdPortalProcessor::class))->execute($start, $end);
// (App()->make(\App\Classes\Modules\PackingLists\Processors\FetchPackingListsFromYdPortalProcessor::class))->execute($start, $end);
// (App()->make(\App\Classes\Modules\PackingLists\Processors\FetchContainersFromYdPortalProcessor::class))->execute();
// (App()->make(\App\Classes\Modules\PackingLists\Processors\FetchContainersUpdatesFromYdPortalProcessor::class))->execute();
// (App()->make(FetchDeliveryUpdatesFromYdPortalProcessor::class))->execute();
// (App()->make(FetchPackingListFromVTPortalProcessor::class))->execute();
Route::get('/yd', function (\Illuminate\Http\Request $request){
$start = $request->input('start_date') ? \Carbon\Carbon::parse($request->input('start_date')): null;
$end = $request->input('end_date') ? \Carbon\Carbon::parse($request->input('end_date')): null;
(App()->make(FetchOrderListsFromYdPortalProcessor::class))->execute($start, $end);
(App()->make(FetchPackingListFromVTPortalProcessor::class))->execute();
})->name('yd.refresh');
Route::get('/container/{reference}/refresh/', function (string $reference){
$container = Container::where('reference', $reference)->first();
$supplier = in_array($container->owner_id, [3, 4]) ? 'VT' : 'YD';
$arrivalDates = PackingList::whereIn('reference', $container->packingLists->pluck('reference'))->where('type', PackingListType::WAREHOUSE_RECEIVE_LIST)->get()->map(function($packingList){
$arrivalDates = \App\Models\PackingList::whereIn('reference', $container->packingLists->pluck('reference'))->where('type', \App\Classes\ValueObjects\Constants\PackingListType::WAREHOUSE_RECEIVE_LIST)->get()->map(function($packingList){
return $packingList->transports()->first()->drop_date;
})->sortBy(function($date){
return $date;
@@ -321,7 +271,7 @@ Route::get('/container/{reference}/refresh/', function (string $reference){
$endDate = $arrivalDates->last()->addDay()->format('d-m-Y');
if($supplier === 'VT'){
return (App()->make(FetchLoadedContainersFromVTPortalProcessor::class))->execute(Carbon::parse($endDate), Carbon::parse($endDate)->addDays(5));
return (App()->make(\App\Classes\Modules\PackingLists\Processors\FetchLoadedContainersFromVTPortalProcessor::class))->execute(\Carbon\Carbon::parse($endDate), \Carbon\Carbon::parse($endDate)->addDays(5));
}
if($supplier === 'YD'){
@@ -331,10 +281,10 @@ Route::get('/container/{reference}/refresh/', function (string $reference){
})->name('container.refresh');
Route::get('/min_cbm', function (){
$companies = CompanyModule::where('type', BusinessType::IMPORTER)->whereHas('orders', function ($query){
$companies = CompanyModule::where('type', \App\Classes\ValueObjects\Constants\BusinessType::IMPORTER)->whereHas('orders', function ($query){
return $query->whereHas('packingLists')->whereDoesntHave('packingLists', function($query){
return $query->whereHas('packages', function($query){
return $query->selectRaw('sum((width/100) * (height/100) * (length/100) * quantity) as cbm')->where('type', PackingListType::SHIPPING_PACKING_LIST)->where('status', '!=', 5)->having('cbm', '>', 0.3);
return $query->selectRaw('sum((width/100) * (height/100) * (length/100) * quantity) as cbm')->where('type', \App\Classes\ValueObjects\Constants\PackingListType::SHIPPING_PACKING_LIST)->where('status', '!=', 5)->having('cbm', '>', 0.3);
});
});
})->limit(1)->get();
@@ -362,8 +312,6 @@ Route::get('/export/on-hold-packing-list', 'Exports\ExportPendingArrangementPack
Route::get('/export/arrived-parcel', 'Exports\ExportArrivedParcelController@export')->name('packing_list.arrived_parcel.export');
Route::get('/export/parcel-summary', 'Exports\ExportArrivedParcelController@summary');
Route::get('/export/parcel-postcode', 'Exports\ExportParcelPostcodesController@export');
Route::get('/export/{year}/customer-total-order', 'Exports\ExportCustomersToExcelController@totalOrders');
Route::get('/export/packing-list-warehouse/guangzhou2-to-johor', 'Exports\ExportArrivedParcelController@guangZhou2ToJohor');
Route::get('/settings', function () {
return view('pages.settings');
@@ -373,17 +321,12 @@ Route::get('/settings', function () {
})->name('settings');
Route::get('/customer/{company_module_id}/summary', 'Exports\ExportCompanyModuleSummaryController@export')->name('customer.summary.export');
Route::get('/export-customer-order/{marking}', 'Exports\ExportCompanyModuleSummaryController@exportorderSummaryByMarking')->name('customer.orderSummary.export');
Route::get('/customer/summary/monthly', function () {
// $containers = Container::whereMonth('loading_date', '>=', ((float)Carbon::now()->format('m') - 2))->whereYear('loading_date', (float)Carbon::now()->format('Y'))->get();
$containers = Container::whereMonth('loading_date', '>=', 9)->whereYear('loading_date', 2022)->get();
$marking = '769SMC';
$connection = CompanyConnection::where('invitee_reference', $marking)->first();
$companyModuleId = $connection->invitee->id;
$containers = Container::whereMonth('loading_date', '>=', ((float)\Carbon\Carbon::now()->format('m') - 2))->whereYear('loading_date', (float)\Carbon\Carbon::now()->format('Y'))->get();
foreach ($containers as $container){
$packingLists = $container->packingLists()->get()->filter(function ($packingList) use ($companyModuleId){
return $packingList->owner->company_module_id === $companyModuleId;
$packingLists = $container->packingLists()->get()->filter(function ($packingList) {
return $packingList->owner->company_module_id === 248;
});
if (!count($packingLists)) continue;
@@ -408,7 +351,7 @@ Route::get('/customer/summary/monthly', function () {
foreach ($packages as $package){
echo '<tr>
<td>'.$container->loading_date->format('d-m-Y').'</td>
<td>MS/CIEF/769SMC/'.$packingList->owner->owner->reference.'</td>
<td>MS/CIEF/769SMC/'.$packingList->owner->reference.'</td>
<td>'.$container->reference.'</td>
<td>'.$package->description.'</td>
<td>'.$package->quantity.'</td>
@@ -427,19 +370,19 @@ Route::get('/customer/summary/monthly', function () {
});
Route::get('/customers/active/{active_start}/{active_end}/{inactive_start?}/{inactive_end?}/{with_cbm?}', function ($active_start, $active_end, $inactive_start=null, $inactive_end=null, $with_cbm = false) {
$activeCompanies = CompanyModule::where('type', BusinessType::IMPORTER)->whereHas('orderPackingLists', function($query) use($inactive_start, $inactive_end) {
return $query->where('packing_lists.type', PackingListType::WAREHOUSE_RECEIVE_LIST)->whereHas('transports', function ($query) use ($inactive_start, $inactive_end) {
return $query->where('drop_date', '>=', Carbon::parse($inactive_start))->where('drop_date', '<=', Carbon::parse($inactive_end)->addDay());
$activeCompanies = CompanyModule::where('type', \App\Classes\ValueObjects\Constants\BusinessType::IMPORTER)->whereHas('orderPackingLists', function($query) use($inactive_start, $inactive_end) {
return $query->where('packing_lists.type', \App\Classes\ValueObjects\Constants\PackingListType::WAREHOUSE_RECEIVE_LIST)->whereHas('transports', function ($query) use ($inactive_start, $inactive_end) {
return $query->where('drop_date', '>=', \Carbon\Carbon::parse($inactive_start))->where('drop_date', '<=', \Carbon\Carbon::parse($inactive_end)->addDay());
});
})->pluck('id');
$companies = CompanyModule::where('type', BusinessType::IMPORTER)->whereHas('orderPackingLists', function($query) use($active_start, $active_end) {
return $query->where('packing_lists.type', PackingListType::WAREHOUSE_RECEIVE_LIST)->whereHas('transports', function ($query) use ($active_start, $active_end) {
return $query->whereDate('drop_date', '>=', Carbon::parse($active_start))->whereDate('drop_date', '<=', Carbon::parse($active_end)->addDay());
$companies = CompanyModule::where('type', \App\Classes\ValueObjects\Constants\BusinessType::IMPORTER)->whereHas('orderPackingLists', function($query) use($active_start, $active_end) {
return $query->where('packing_lists.type', \App\Classes\ValueObjects\Constants\PackingListType::WAREHOUSE_RECEIVE_LIST)->whereHas('transports', function ($query) use ($active_start, $active_end) {
return $query->whereDate('drop_date', '>=', \Carbon\Carbon::parse($active_start))->whereDate('drop_date', '<=', \Carbon\Carbon::parse($active_end)->addDay());
});
})->whereNotIn('id', $activeCompanies)->get();
echo '<h4>List of customers active between <span style="color: green; font-weight: bold">'. Carbon::parse($active_start)->format('d/m/Y'). ' - '. Carbon::parse($active_end)->format('d/m/Y').'</span> & inactive between <span style="color: red; font-weight: bold">'. Carbon::parse($inactive_start)->format('d/m/Y'). ' - '. Carbon::parse($inactive_end)->format('d/m/Y').'</span></h4>';
echo '<h4>List of customers active between <span style="color: green; font-weight: bold">'.\Carbon\Carbon::parse($active_start)->format('d/m/Y'). ' - '.\Carbon\Carbon::parse($active_end)->format('d/m/Y').'</span> & inactive between <span style="color: red; font-weight: bold">'.\Carbon\Carbon::parse($inactive_start)->format('d/m/Y'). ' - '.\Carbon\Carbon::parse($inactive_end)->format('d/m/Y').'</span></h4>';
echo '<table>
<tr>
<th>#</th>
@@ -453,7 +396,7 @@ Route::get('/customers/active/{active_start}/{active_end}/{inactive_start?}/{ina
$packingList = collect();
$totalCbm = 0;
if($with_cbm){
$packingList = $company->orderPackingLists()->where('packing_lists.type', PackingListType::SHIPPING_PACKING_LIST)->get();
$packingList = $company->orderPackingLists()->where('packing_lists.type', \App\Classes\ValueObjects\Constants\PackingListType::SHIPPING_PACKING_LIST)->get();
$totalCbm = $packingList->flatMap(function ($packingList) {
return $packingList->packages;
})->sum(function($package){
@@ -493,7 +436,7 @@ Route::get('/export/payment-transactions/f614e339d7058904a831aad742e24d55', 'Exp
Route::get('/delayed_container/customers', function(){
$containers = Container::whereHas('transports', function($query){
return $query->whereHas('Schedules', function($query){
return $query->where('etd', '>', Carbon::parse('15-10-2022'));
return $query->where('etd', '>', \Carbon\Carbon::parse('15-10-2022'));
});
})->get();
@@ -515,7 +458,7 @@ Route::get('/delayed_container/customers', function(){
Route::get('/container/billing/{month}/{year}', function($month, $year){
$containers = Container::whereDate('loading_date', '>=', Carbon::parse('01-'.$month.'-'.$year))->whereDate('loading_date', '<', Carbon::parse('01-'.$month.'-'.$year)->addMonth())->get();
$containers = Container::whereDate('loading_date', '>=', \Carbon\Carbon::parse('01-'.$month.'-'.$year))->whereDate('loading_date', '<', \Carbon\Carbon::parse('01-'.$month.'-'.$year)->addMonth())->get();
$totalBillable = 0;
$billed = 0;
@@ -548,7 +491,7 @@ Route::get('/container/billing/{month}/{year}', function($month, $year){
foreach ($packingLists as $packingList) {
$invoice = $packingList->transactions()
->where('type', TransactionType::SHIPPING_INVOICE)->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED])
->where('type', \App\Classes\ValueObjects\Constants\TransactionType::SHIPPING_INVOICE)->whereIn('status', [\App\Classes\ValueObjects\Constants\ApprovalStatus::APPROVED, \App\Classes\ValueObjects\Constants\ApprovalStatus::COMPLETED])
->first();
@@ -560,7 +503,7 @@ Route::get('/container/billing/{month}/{year}', function($month, $year){
}
$order = $packingList->owner;
$address = $order->addresses()->where('status', ApprovalStatus::APPROVED)->first();
$address = $order->addresses()->where('status', \App\Classes\ValueObjects\Constants\ApprovalStatus::APPROVED)->first();
$warehouseId = $order->orderRoles()->where('role_id', OrderRoleTypes::ORIGIN_WAREHOUSE)->first()->company_module_id;
$cbm = round($packingList->packages->where('type', '!=', PackageType::OVER_WEIGHT)->sum(function($package) {
@@ -574,14 +517,14 @@ Route::get('/container/billing/{month}/{year}', function($month, $year){
if($warehouseId === 2358){
$price += $yiwuCost;
if($packing_list_drop_date >= Carbon::parse('19-9-2022')){
if($packing_list_drop_date >= \Carbon\Carbon::parse('19-9-2022')){
$price += $yiwuDiscount;
}
} else {
if($cbm >= 2 && in_array($address->state_id, [4, 15])){
$price += $bigParcelDiscount;
}
if($packing_list_drop_date >= Carbon::parse('19-9-2022')){
if($packing_list_drop_date >= \Carbon\Carbon::parse('19-9-2022')){
$price += $discount;
}
}
@@ -607,7 +550,7 @@ Route::get('/container/billing/{month}/{year}', function($month, $year){
}
$payments = $invoice->transactions()
->where('type', TransactionType::PAYMENT)->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED])
->where('type', \App\Classes\ValueObjects\Constants\TransactionType::PAYMENT)->whereIn('status', [\App\Classes\ValueObjects\Constants\ApprovalStatus::APPROVED, \App\Classes\ValueObjects\Constants\ApprovalStatus::COMPLETED])
->get();
$billed += 1;
@@ -640,14 +583,14 @@ Route::get('/container/billing/{month}/{year}', function($month, $year){
});
Route::get('/yd/fix', function(){
$packingLists = PackingList::where('type', PackingListType::SHIPPING_PACKING_LIST)->where('status', ApprovalStatus::APPROVED)->where('claimant_id', 2307)->get();
$packingLists = \App\Models\PackingList::where('type', \App\Classes\ValueObjects\Constants\PackingListType::SHIPPING_PACKING_LIST)->where('status', \App\Classes\ValueObjects\Constants\ApprovalStatus::APPROVED)->where('claimant_id', 2307)->get();
$i = 0;
echo count($packingLists).'<br><br>';
foreach ($packingLists as $packingList){
try {
(App()->make(UpdateDoFromYDPortalProcessor::class))->execute($packingList);
echo 'success'.'<br>';
} catch (Exception $exception){
} catch (\Exception $exception){
echo '<span style="color:red;">'.$packingList->reference.'</span>';
}
@@ -655,7 +598,7 @@ Route::get('/yd/fix', function(){
});
Route::get('/billplz/fix', function(){
$payments = Transaction::where('type', TransactionType::PAYMENT)->where('payment_method', PaymentMethodType::PAYMENT_GATEWAY)->get();
$payments = \App\Models\Transaction::where('type', \App\Classes\ValueObjects\Constants\TransactionType::PAYMENT)->where('payment_method',\App\Classes\ValueObjects\Constants\PaymentMethodType::PAYMENT_GATEWAY)->get();
echo '<h3>fixed orders</h3>';
foreach ($payments as $payment){
$response = Http::withBasicAuth(config('billplz.api_key').':', '')->get(config('billplz.base_url').'/api/v3/bills/'.$payment->payment_reference);
@@ -670,19 +613,19 @@ Route::get('/billplz/fix', function(){
$order = $packingList->owner;
$orderNumber = $order->reference;
if(!$data['paid'] && $payment->status === ApprovalStatus::APPROVED) {
if(!$data['paid'] && $payment->status === \App\Classes\ValueObjects\Constants\ApprovalStatus::APPROVED) {
echo '<br><span style="color: red">Fraude: <a href="'.route('order.show', $orderNumber).'" target="_blank">'.$orderNumber.'</a></span><br>';
continue;
}
if($data['paid']){
if($payment->status !== ApprovalStatus::APPROVED){
if($payment->status !== \App\Classes\ValueObjects\Constants\ApprovalStatus::APPROVED){
echo '<a href="'.route('order.show', $orderNumber).'" target="_blank">'.$orderNumber.'</a><br>';
}
$payment->status = ApprovalStatus::APPROVED;
$payment->status = \App\Classes\ValueObjects\Constants\ApprovalStatus::APPROVED;
$payment->save();
$invoice->status = ApprovalStatus::COMPLETED;
$invoice->status = \App\Classes\ValueObjects\Constants\ApprovalStatus::COMPLETED;
$invoice->save();
$packingList = $payment->owner->owner;
@@ -690,7 +633,7 @@ Route::get('/billplz/fix', function(){
try {
(App()->make(UpdateDoFromVTPortalProcessor::class))->execute($packingList);
(App()->make(UpdateDoFromYDPortalProcessor::class))->execute($packingList);
} catch (Exception $exception){
} catch (\Exception $exception){
echo '<br><span style="color: red">Malformed Address: <a href="'.route('order.show', $orderNumber).'" target="_blank">'.$orderNumber.'</a></span><br>';
}
}
@@ -703,96 +646,4 @@ Route::get('/billplz/fix', function(){
});
Route::get('/invoices/fix/{company_module_id}', function($company_module_id) {
$orders = Order::whereIn('company_module_id', json_decode($company_module_id))->get();
foreach ($orders as $order){
$invoices = $order->transactions()->where('transactions.type', TransactionType::SHIPPING_INVOICE)->get();
foreach ($invoices as $invoice){
$invoice->documents()->delete();
$transaction_invoice_pdf = LaravelMpdf::loadView('pages.pdfs.shipping_invoice', ['invoice_transaction' => $invoice]);
$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 = (App()->make(CreatesDocument::class))->execute($invoice, $document_object);
(App()->make(CreatesFiles::class))->execute($document, $document_object);
}
}
});
Route::get('/invoices/combine/{ids}', function($ids){
$ids = json_decode($ids);
$transactions = Transaction::whereIn('id', $ids)->get();
$pdf = LaravelMpdf::loadView('pages.pdfs.shipping_invoices_combined', ['invoice_transactions' => $transactions]);
return $pdf->download('combined_invoice_.pdf');
})->name('invoice.combined_summary');
Route::get('/generate/invoices', function(){
$packingLists = (App()->make(ListsPackingLists::class))->execute(['does_not_have_transaction_type' => 1, 'type' => 2]);
foreach ($packingLists as $packingList){
$order = $packingList->owner;
if(!($order instanceof Order)) {
echo '<span style="color: red;">failed to generate...</span><br>';
continue;
}
$companyModule = $order->companyModule;
$billingAddress = $companyModule->addresses()->where('type', \App\Classes\ValueObjects\Constants\AddressType::BILLING)->first();
$deliveryAddress = $order->addresses()->where('status', ApprovalStatus::APPROVED)->first();
$postCodes = \App\Models\SegmentConstant::whereIn('reference', ['CENTER_POSTCODE', 'OUTSTATION_POSTCODE'])->get()->pluck('value')->flatten();
if(!!$billingAddress && in_array($deliveryAddress->postcode, $postCodes->toArray())){
try {
(App()->make(CreateInvoiceTransactionProcessor::class))->execute($packingList);
echo '<span style="color: green;">Invoice Generated...</span><br>';
} catch (Exception $exception){
echo '<span style="color: red;">failed to generate...</span><br>';
}
}
echo '<span style="color: red;">failed to generate...</span><br>';
}
})->name('generate.invoices');
Route::get('/invoices/approve', function(Request $request){
// whereDoesntHave
$invoices = Transaction::where('type', TransactionType::SHIPPING_INVOICE)->where('status', ApprovalStatus::PENDING_SUBMISSION)->get();
foreach ($invoices as $invoice) {
$packingList = $invoice->owner;
$order = $packingList->owner;
if(in_array($order->reference, json_decode($request->input('exclude')))){
continue;
}
try {
(App()->make(ApproveShippingInvoiceTransactionProcessor::class))->execute($packingList);
echo '<span style="color: green;">Invoice Approved...</span><br>';
} catch (Exception $exception){
echo '<span style="color: red;">failed to approve...</span><br>';
}
}
})->name('invoices.approve');