php-cs-fixer

This commit is contained in:
David Bomba 2024-06-14 17:09:44 +10:00
parent 9c288cd452
commit 72aadc0c16
232 changed files with 1436 additions and 1417 deletions

View File

@ -480,8 +480,7 @@ class CheckData extends Command
try { try {
$entity->service()->createInvitations()->save(); $entity->service()->createInvitations()->save();
} } catch(\Exception $e) {
catch(\Exception $e){
} }

View File

@ -15,7 +15,6 @@ use App\DataMapper\InvoiceItem;
class PayPalBalanceAffecting class PayPalBalanceAffecting
{ {
private array $key_map = [ private array $key_map = [
'Date' => 'date', 'Date' => 'date',
'Time' => 'time', 'Time' => 'time',
@ -106,7 +105,9 @@ class PayPalBalanceAffecting
public $creditTransactionalFee; public $creditTransactionalFee;
public $originalInvoiceId; public $originalInvoiceId;
public function __construct(private array $import_row){} public function __construct(private array $import_row)
{
}
public function run(): self public function run(): self
{ {
@ -154,7 +155,7 @@ class PayPalBalanceAffecting
public function getInvoice(): array public function getInvoice(): array
{ {
$item = new InvoiceItem; $item = new InvoiceItem();
$item->cost = $this->gross ?? 0; $item->cost = $this->gross ?? 0;
$item->product_key = $this->itemId ?? ''; $item->product_key = $this->itemId ?? '';
$item->notes = $this->subject ?? $this->itemDetails; $item->notes = $this->subject ?? $this->itemDetails;
@ -174,12 +175,10 @@ class PayPalBalanceAffecting
{ {
$name_parts = explode(" ", $this->name ?? ''); $name_parts = explode(" ", $this->name ?? '');
if(count($name_parts) == 2) if(count($name_parts) == 2) {
{
$contact['first_name'] = $name_parts[0]; $contact['first_name'] = $name_parts[0];
$contact['last_name'] = $name_parts[1]; $contact['last_name'] = $name_parts[1];
} } else {
else {
$contact['first_name'] = $this->name ?? ''; $contact['first_name'] = $this->name ?? '';
} }
@ -203,13 +202,15 @@ class PayPalBalanceAffecting
private function returnShippingAddress(): array private function returnShippingAddress(): array
{ {
if(strlen($this->shippingAddress ?? '') <3) if(strlen($this->shippingAddress ?? '') < 3) {
return []; return [];
}
$ship_parts = explode(",", $this->shippingAddress); $ship_parts = explode(",", $this->shippingAddress);
if(count($ship_parts) != 7) if(count($ship_parts) != 7) {
return []; return [];
}
return [ return [
'shipping_address1' => $ship_parts[2], 'shipping_address1' => $ship_parts[2],

View File

@ -127,8 +127,9 @@ class ClientExport extends BaseExport
->withTrashed() ->withTrashed()
->where('company_id', $this->company->id); ->where('company_id', $this->company->id);
if(!$this->input['include_deleted'] ?? false) if(!$this->input['include_deleted'] ?? false) {
$query->where('is_deleted', 0); $query->where('is_deleted', 0);
}
$query = $this->addDateRange($query); $query = $this->addDateRange($query);

View File

@ -146,12 +146,11 @@ class ProductSalesExport extends BaseExport
->each(function ($invoice) use ($product_keys) { ->each(function ($invoice) use ($product_keys) {
foreach ($invoice->line_items as $item) { foreach ($invoice->line_items as $item) {
if($product_keys) if($product_keys) {
{ if(in_array($item->product_key, $product_keys)) {
if(in_array($item->product_key, $product_keys))
$this->csv->insertOne($this->buildRow($invoice, $item)); $this->csv->insertOne($this->buildRow($invoice, $item));
} }
else { } else {
$this->csv->insertOne($this->buildRow($invoice, $item)); $this->csv->insertOne($this->buildRow($invoice, $item));
} }
@ -185,7 +184,8 @@ class ProductSalesExport extends BaseExport
})->reject(function ($value) { })->reject(function ($value) {
return $value === false; return $value === false;
});; });
;
$this->csv->insertOne([]); $this->csv->insertOne([]);
$this->csv->insertOne([]); $this->csv->insertOne([]);

View File

@ -72,8 +72,9 @@ class PurchaseOrderExport extends BaseExport
$clients = &$this->input['client_id']; $clients = &$this->input['client_id'];
if($clients) if($clients) {
$query = $this->addClientFilter($query, $clients); $query = $this->addClientFilter($query, $clients);
}
$query = $this->addPurchaseOrderStatusFilter($query, $this->input['status'] ?? ''); $query = $this->addPurchaseOrderStatusFilter($query, $this->input['status'] ?? '');

View File

@ -78,13 +78,15 @@ class TaskExport extends BaseExport
$clients = &$this->input['client_id']; $clients = &$this->input['client_id'];
if($clients) if($clients) {
$query = $this->addClientFilter($query, $clients); $query = $this->addClientFilter($query, $clients);
}
$document_attachments = &$this->input['document_email_attachment']; $document_attachments = &$this->input['document_email_attachment'];
if($document_attachments) if($document_attachments) {
$this->queueDocuments($query); $this->queueDocuments($query);
}
return $query; return $query;

View File

@ -124,8 +124,9 @@ class BankTransactionFilters extends QueryFilters
*/ */
public function bank_integration_ids(string $ids = ''): Builder public function bank_integration_ids(string $ids = ''): Builder
{ {
if(strlen($ids) == 0) if(strlen($ids) == 0) {
return $this->builder; return $this->builder;
}
$ids = $this->transformKeys(explode(",", $ids)); $ids = $this->transformKeys(explode(",", $ids));

View File

@ -160,8 +160,9 @@ class ClientFilters extends QueryFilters
return $this->builder; return $this->builder;
} }
if($sort_col[0] == 'documents') if($sort_col[0] == 'documents') {
return $this->builder; return $this->builder;
}
if ($sort_col[0] == 'display_name') { if ($sort_col[0] == 'display_name') {
$sort_col[0] = 'name'; $sort_col[0] = 'name';

View File

@ -59,8 +59,9 @@ class DesignFilters extends QueryFilters
public function entities(string $entities = ''): Builder public function entities(string $entities = ''): Builder
{ {
if(stripos($entities, 'statement') !== false) if(stripos($entities, 'statement') !== false) {
$entities = 'client'; $entities = 'client';
}
if (strlen($entities) == 0 || str_contains($entities, ',')) { if (strlen($entities) == 0 || str_contains($entities, ',')) {
return $this->builder; return $this->builder;

View File

@ -74,8 +74,7 @@ class DocumentFilters extends QueryFilters
{ {
$types = explode(',', $types); $types = explode(',', $types);
foreach ($types as $type) foreach ($types as $type) {
{
match($type) { match($type) {
'private' => $this->builder->where('is_public', 0), 'private' => $this->builder->where('is_public', 0),
'public' => $this->builder->where('is_public', 1), 'public' => $this->builder->where('is_public', 1),

View File

@ -230,8 +230,7 @@ class InvoiceFilters extends QueryFilters
try { try {
$date = Carbon::parse($date); $date = Carbon::parse($date);
} } catch(\Exception $e) {
catch(\Exception $e){
return $this->builder; return $this->builder;
} }
} }

View File

@ -152,8 +152,9 @@ class Nordigen
{ {
$cache_key = "email_quota:{$bank_integration->company->company_key}:{$bank_integration->id}"; $cache_key = "email_quota:{$bank_integration->company->company_key}:{$bank_integration->id}";
if(Cache::has($cache_key)) if(Cache::has($cache_key)) {
return; return;
}
App::setLocale($bank_integration->company->getLocale()); App::setLocale($bank_integration->company->getLocale());

View File

@ -71,7 +71,7 @@ class TransactionTransformer implements BankRevenueInterface
private Company $company; private Company $company;
function __construct(Company $company) public function __construct(Company $company)
{ {
$this->company = $company; $this->company = $company;
} }

View File

@ -35,7 +35,8 @@ trait CustomValuer
return 0; return 0;
} }
public function multiInclusiveTax($custom_value, $has_custom_invoice_taxes) { public function multiInclusiveTax($custom_value, $has_custom_invoice_taxes)
{
if (isset($custom_value) && is_numeric($custom_value) && $has_custom_invoice_taxes !== false) { if (isset($custom_value) && is_numeric($custom_value) && $has_custom_invoice_taxes !== false) {

View File

@ -247,8 +247,7 @@ class InvoiceSum
{ {
if($this->invoice->status_id == Invoice::STATUS_CANCELLED) { if($this->invoice->status_id == Invoice::STATUS_CANCELLED) {
$this->invoice->balance = 0; $this->invoice->balance = 0;
} } elseif ($this->invoice->status_id != Invoice::STATUS_DRAFT) {
elseif ($this->invoice->status_id != Invoice::STATUS_DRAFT) {
if ($this->invoice->amount != $this->invoice->balance) { if ($this->invoice->amount != $this->invoice->balance) {
$this->invoice->balance = Number::roundValue($this->getTotal(), $this->precision) - $this->invoice->paid_to_date; //21-02-2024 cannot use the calculated $paid_to_date here as it could send the balance backward. $this->invoice->balance = Number::roundValue($this->getTotal(), $this->precision) - $this->invoice->paid_to_date; //21-02-2024 cannot use the calculated $paid_to_date here as it could send the balance backward.
} else { } else {
@ -269,7 +268,7 @@ class InvoiceSum
} }
function roundRappen($value): float public function roundRappen($value): float
{ {
return round($value / .05, 0) * .05; return round($value / .05, 0) * .05;
} }

View File

@ -281,8 +281,7 @@ class InvoiceSumInclusive
/* If amount != balance then some money has been paid on the invoice, need to subtract this difference from the total to set the new balance */ /* If amount != balance then some money has been paid on the invoice, need to subtract this difference from the total to set the new balance */
if($this->invoice->status_id == Invoice::STATUS_CANCELLED) { if($this->invoice->status_id == Invoice::STATUS_CANCELLED) {
$this->invoice->balance = 0; $this->invoice->balance = 0;
} } elseif ($this->invoice->status_id != Invoice::STATUS_DRAFT) {
elseif ($this->invoice->status_id != Invoice::STATUS_DRAFT) {
if ($this->invoice->amount != $this->invoice->balance) { if ($this->invoice->amount != $this->invoice->balance) {
$this->invoice->balance = $this->formatValue($this->getTotal(), $this->precision) - $this->invoice->paid_to_date; $this->invoice->balance = $this->formatValue($this->getTotal(), $this->precision) - $this->invoice->paid_to_date;
} else { } else {
@ -303,7 +302,7 @@ class InvoiceSumInclusive
return $this; return $this;
} }
function roundRappen($value): float public function roundRappen($value): float
{ {
return round($value / .05, 0) * .05; return round($value / .05, 0) * .05;
} }

View File

@ -310,7 +310,7 @@ class YodleeController extends BaseController
private function transformSummary($summary): array private function transformSummary($summary): array
{ {
$dto = new \stdClass; $dto = new \stdClass();
$dto->id = $summary['id'] ?? 0; $dto->id = $summary['id'] ?? 0;
$dto->account_type = $summary['CONTAINER'] ?? ''; $dto->account_type = $summary['CONTAINER'] ?? '';

View File

@ -351,8 +351,9 @@ class ClientController extends BaseController
return response()->json(['message' => "Client not found"], 400); return response()->json(['message' => "Client not found"], 400);
} }
if($m_client->id == $client->id) if($m_client->id == $client->id) {
return response()->json(['message' => "Attempting to merge the same client is not possible."], 400); return response()->json(['message' => "Attempting to merge the same client is not possible."], 400);
}
$merged_client = $client->service()->merge($m_client)->save(); $merged_client = $client->service()->merge($m_client)->save();

View File

@ -720,13 +720,11 @@ class CompanyController extends BaseController
if ($response->successful()) { if ($response->successful()) {
$logo = $response->body(); $logo = $response->body();
} } else {
else {
$logo = base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII='); $logo = base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=');
} }
} } catch(\Exception $e) {
catch(\Exception $e){
$logo = base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII='); $logo = base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=');

View File

@ -567,8 +567,9 @@ class CompanyGatewayController extends BaseController
{ {
//Throttle here //Throttle here
if (Cache::has("throttle_polling:import_customers:{$company_gateway->company->company_key}:{$company_gateway->hashed_id}")) if (Cache::has("throttle_polling:import_customers:{$company_gateway->company->company_key}:{$company_gateway->hashed_id}")) {
return response()->json(['message' => 'Please wait whilst your previous attempts complete.'], 200); return response()->json(['message' => 'Please wait whilst your previous attempts complete.'], 200);
}
dispatch(function () use ($company_gateway) { dispatch(function () use ($company_gateway) {
MultiDB::setDb($company_gateway->company->db); MultiDB::setDb($company_gateway->company->db);

View File

@ -146,8 +146,7 @@ class PreviewController extends BaseController
if (request()->has('entity') && if (request()->has('entity') &&
request()->has('entity_id') && request()->has('entity_id') &&
! empty(request()->input('entity')) && ! empty(request()->input('entity')) &&
! empty(request()->input('entity_id'))) ! empty(request()->input('entity_id'))) {
{
$design_object = json_decode(json_encode(request()->input('design'))); $design_object = json_decode(json_encode(request()->input('design')));
@ -174,8 +173,7 @@ class PreviewController extends BaseController
if($entity_obj->client) { if($entity_obj->client) {
$html = new HtmlEngine($entity_obj->invitations()->first()); $html = new HtmlEngine($entity_obj->invitations()->first());
} } else {
else {
$html = new VendorHtmlEngine($entity_obj->invitations()->first()); $html = new VendorHtmlEngine($entity_obj->invitations()->first());
} }

View File

@ -66,8 +66,7 @@ class TaskReportController extends BaseController
/** @var \App\Models\User $user */ /** @var \App\Models\User $user */
$user = auth()->user(); $user = auth()->user();
if ($request->has('send_email') && $request->get('send_email') && $request->missing('output')) if ($request->has('send_email') && $request->get('send_email') && $request->missing('output')) {
{
SendToAdmin::dispatch($user->company(), $request->all(), TaskExport::class, $this->filename); SendToAdmin::dispatch($user->company(), $request->all(), TaskExport::class, $this->filename);
return response()->json(['message' => 'working...'], 200); return response()->json(['message' => 'working...'], 200);

View File

@ -62,8 +62,9 @@ class SelfUpdateController extends BaseController
$file_headers = @get_headers($this->getDownloadUrl()); $file_headers = @get_headers($this->getDownloadUrl());
if(!is_array($file_headers)) if(!is_array($file_headers)) {
return response()->json(['message' => 'There was a problem reaching the update server, please try again in a little while.'], 410); return response()->json(['message' => 'There was a problem reaching the update server, please try again in a little while.'], 410);
}
if (stripos($file_headers[0], "404 Not Found") > 0 || (stripos($file_headers[0], "302 Found") > 0 && stripos($file_headers[7], "404 Not Found") > 0)) { if (stripos($file_headers[0], "404 Not Found") > 0 || (stripos($file_headers[0], "302 Found") > 0 && stripos($file_headers[7], "404 Not Found") > 0)) {
return response()->json(['message' => 'Download not yet available. Please try again shortly.'], 410); return response()->json(['message' => 'Download not yet available. Please try again shortly.'], 410);
@ -100,8 +101,9 @@ class SelfUpdateController extends BaseController
} }
} }
if(Storage::disk('base')->directoryExists('resources/lang')) if(Storage::disk('base')->directoryExists('resources/lang')) {
Storage::disk('base')->deleteDirectory('resources/lang'); Storage::disk('base')->deleteDirectory('resources/lang');
}
nlog('Removing cache files'); nlog('Removing cache files');

View File

@ -18,7 +18,6 @@ use Illuminate\Support\Facades\Mail;
class SmtpController extends BaseController class SmtpController extends BaseController
{ {
public function __construct() public function __construct()
{ {
parent::__construct(); parent::__construct();

View File

@ -78,13 +78,11 @@ class QueryLogging
if ($request->hasHeader('X-CLIENT-PLATFORM')) { if ($request->hasHeader('X-CLIENT-PLATFORM')) {
$platform = $request->header('X-CLIENT-PLATFORM'); $platform = $request->header('X-CLIENT-PLATFORM');
} } elseif($request->hasHeader('X-React')) {
elseif($request->hasHeader('X-React')){
$platform = 'react'; $platform = 'react';
} }
if ($request->hasHeader('X-CLIENT-VERSION')) if ($request->hasHeader('X-CLIENT-VERSION')) {
{
$client_version = $request->header('X-CLIENT-VERSION'); $client_version = $request->header('X-CLIENT-VERSION');
} }

View File

@ -48,8 +48,7 @@ class StoreClientRequest extends Request
$rules['documents.*'] = $this->fileValidation(); $rules['documents.*'] = $this->fileValidation();
} elseif ($this->file('documents')) { } elseif ($this->file('documents')) {
$rules['documents'] = $this->fileValidation(); $rules['documents'] = $this->fileValidation();
} } else {
else {
$rules['documents'] = 'bail|sometimes|array'; $rules['documents'] = 'bail|sometimes|array';
} }
@ -133,11 +132,9 @@ class StoreClientRequest extends Request
} else { } else {
$input['settings']['currency_id'] = (string) $user->company()->settings->currency_id; $input['settings']['currency_id'] = (string) $user->company()->settings->currency_id;
} }
} } elseif (! array_key_exists('currency_id', $input['settings'])) {
elseif (! array_key_exists('currency_id', $input['settings'])) {
$input['settings']['currency_id'] = (string) $user->company()->settings->currency_id; $input['settings']['currency_id'] = (string) $user->company()->settings->currency_id;
} } elseif (empty($input['settings']['currency_id']) ?? true) {
elseif (empty($input['settings']['currency_id']) ?? true) {
$input['settings']['currency_id'] = (string) $user->company()->settings->currency_id; $input['settings']['currency_id'] = (string) $user->company()->settings->currency_id;
} }

View File

@ -105,8 +105,7 @@ class UpdateClientRequest extends Request
/* If the user removes the currency we must always set the default */ /* If the user removes the currency we must always set the default */
if (array_key_exists('settings', $input) && ! array_key_exists('currency_id', $input['settings'])) { if (array_key_exists('settings', $input) && ! array_key_exists('currency_id', $input['settings'])) {
$input['settings']['currency_id'] = (string) $user->company()->settings->currency_id; $input['settings']['currency_id'] = (string) $user->company()->settings->currency_id;
} } elseif (empty($input['settings']['currency_id']) ?? true) {
elseif (empty($input['settings']['currency_id']) ?? true) {
$input['settings']['currency_id'] = (string) $user->company()->settings->currency_id; $input['settings']['currency_id'] = (string) $user->company()->settings->currency_id;
} }

View File

@ -100,8 +100,9 @@ class StoreCompanyRequest extends Request
$input['smtp_port'] = (int) $input['smtp_port']; $input['smtp_port'] = (int) $input['smtp_port'];
} }
if(isset($input['smtp_verify_peer']) && is_string($input['smtp_verify_peer'])) if(isset($input['smtp_verify_peer']) && is_string($input['smtp_verify_peer'])) {
$input['smtp_verify_peer'] == 'true' ? true : false; $input['smtp_verify_peer'] == 'true' ? true : false;
}
$this->replace($input); $this->replace($input);
} }

View File

@ -145,8 +145,9 @@ class UpdateCompanyRequest extends Request
$settings['email_style_custom'] = str_replace(['{!!','!!}','{{','}}','@checked','@dd', '@dump', '@if', '@if(','@endif','@isset','@unless','@auth','@empty','@guest','@env','@section','@switch', '@foreach', '@while', '@include', '@each', '@once', '@push', '@use', '@forelse', '@verbatim', '<?php', '@php', '@for','@class','</sc','<sc','html;base64', '@elseif', '@else', '@endunless', '@endisset', '@endempty', '@endauth', '@endguest', '@endproduction', '@endenv', '@hasSection', '@endhasSection', '@sectionMissing', '@endsectionMissing', '@endfor', '@endforeach', '@empty', '@endforelse', '@endwhile', '@continue', '@break', '@includeIf', '@includeWhen', '@includeUnless', '@includeFirst', '@component', '@endcomponent', '@endsection', '@yield', '@show', '@append', '@overwrite', '@stop', '@extends', '@endpush', '@stack', '@prepend', '@endprepend', '@slot', '@endslot', '@endphp', '@method', '@csrf', '@error', '@enderror', '@json', '@endverbatim', '@inject'], '', $settings['email_style_custom']); $settings['email_style_custom'] = str_replace(['{!!','!!}','{{','}}','@checked','@dd', '@dump', '@if', '@if(','@endif','@isset','@unless','@auth','@empty','@guest','@env','@section','@switch', '@foreach', '@while', '@include', '@each', '@once', '@push', '@use', '@forelse', '@verbatim', '<?php', '@php', '@for','@class','</sc','<sc','html;base64', '@elseif', '@else', '@endunless', '@endisset', '@endempty', '@endauth', '@endguest', '@endproduction', '@endenv', '@hasSection', '@endhasSection', '@sectionMissing', '@endsectionMissing', '@endfor', '@endforeach', '@empty', '@endforelse', '@endwhile', '@continue', '@break', '@includeIf', '@includeWhen', '@includeUnless', '@includeFirst', '@component', '@endcomponent', '@endsection', '@yield', '@show', '@append', '@overwrite', '@stop', '@extends', '@endpush', '@stack', '@prepend', '@endprepend', '@slot', '@endslot', '@endphp', '@method', '@csrf', '@error', '@enderror', '@json', '@endverbatim', '@inject'], '', $settings['email_style_custom']);
} }
if(isset($settings['company_logo']) && strlen($settings['company_logo']) > 2) if(isset($settings['company_logo']) && strlen($settings['company_logo']) > 2) {
$settings['company_logo'] = $this->forceScheme($settings['company_logo']); $settings['company_logo'] = $this->forceScheme($settings['company_logo']);
}
if (! $account->isFreeHostedClient()) { if (! $account->isFreeHostedClient()) {
return $settings; return $settings;
@ -173,7 +174,8 @@ class UpdateCompanyRequest extends Request
return rtrim($url, '/'); return rtrim($url, '/');
} }
private function forceScheme($url){ private function forceScheme($url)
{
return stripos($url, 'http') !== false ? $url : "https://{$url}"; return stripos($url, 'http') !== false ? $url : "https://{$url}";
} }

View File

@ -40,8 +40,9 @@ class UpdateCompanyUserRequest extends Request
{ {
$input = $this->all(); $input = $this->all();
if(isset($input['company_user']['user'])) if(isset($input['company_user']['user'])) {
unset($input['company_user']['user']); unset($input['company_user']['user']);
}
$this->replace($input); $this->replace($input);
} }

View File

@ -122,9 +122,10 @@ class StoreInvoiceRequest extends Request
if((isset($input['partial_due_date']) && strlen($input['partial_due_date']) > 1) && (!array_key_exists('due_date', $input) || (empty($input['due_date']) && empty($this->invoice->due_date)))) { if((isset($input['partial_due_date']) && strlen($input['partial_due_date']) > 1) && (!array_key_exists('due_date', $input) || (empty($input['due_date']) && empty($this->invoice->due_date)))) {
$client = \App\Models\Client::withTrashed()->find($input['client_id']); $client = \App\Models\Client::withTrashed()->find($input['client_id']);
if($client) if($client) {
$input['due_date'] = \Illuminate\Support\Carbon::parse($input['date'])->addDays($client->getSetting('payment_terms'))->format('Y-m-d'); $input['due_date'] = \Illuminate\Support\Carbon::parse($input['date'])->addDays($client->getSetting('payment_terms'))->format('Y-m-d');
} }
}
$this->replace($input); $this->replace($input);
} }

View File

@ -45,8 +45,9 @@ class ConnectNordigenBankIntegrationRequest extends Request
$context = $this->getTokenContent(); $context = $this->getTokenContent();
if(isset($context['institution_id'])) if(isset($context['institution_id'])) {
$input['institution_id'] = $context['institution_id']; $input['institution_id'] = $context['institution_id'];
}
$input["redirect"] = isset($context["is_react"]) && $context['is_react'] ? config('ninja.react_url') . "/#/settings/bank_accounts" : config('ninja.app_url'); $input["redirect"] = isset($context["is_react"]) && $context['is_react'] ? config('ninja.react_url') . "/#/settings/bank_accounts" : config('ninja.app_url');

View File

@ -75,8 +75,9 @@ class StoreProjectRequest extends Request
$input['color'] = ''; $input['color'] = '';
} }
if(array_key_exists('budgeted_hours', $input) && empty($input['budgeted_hours'])) if(array_key_exists('budgeted_hours', $input) && empty($input['budgeted_hours'])) {
$input['budgeted_hours'] = 0; $input['budgeted_hours'] = 0;
}
$this->replace($input); $this->replace($input);
} }

View File

@ -98,8 +98,9 @@ class StoreQuoteRequest extends Request
$input['partial_due_date'] = null; $input['partial_due_date'] = null;
} }
if(!isset($input['date'])) if(!isset($input['date'])) {
$input['date'] = now()->addSeconds($user->company()->utc_offset())->format('Y-m-d'); $input['date'] = now()->addSeconds($user->company()->utc_offset())->format('Y-m-d');
}
if(isset($input['partial_due_date']) && (!isset($input['due_date']) || strlen($input['due_date']) <= 1)) { if(isset($input['partial_due_date']) && (!isset($input['due_date']) || strlen($input['due_date']) <= 1)) {
$client = \App\Models\Client::withTrashed()->find($input['client_id']); $client = \App\Models\Client::withTrashed()->find($input['client_id']);

View File

@ -17,7 +17,6 @@ use Illuminate\Auth\Access\AuthorizationException;
class ProfitLossRequest extends Request class ProfitLossRequest extends Request
{ {
private string $error_message = ''; private string $error_message = '';
/** /**

View File

@ -33,8 +33,9 @@ class Request extends FormRequest
public function fileValidation() public function fileValidation()
{ {
if(config('ninja.upload_extensions')) if(config('ninja.upload_extensions')) {
return $this->file_validation. ",".config('ninja.upload_extensions'); return $this->file_validation. ",".config('ninja.upload_extensions');
}
return $this->file_validation; return $this->file_validation;
@ -46,8 +47,9 @@ class Request extends FormRequest
foreach ($this->all() as $key => $value) { foreach ($this->all() as $key => $value) {
if($key == 'user') if($key == 'user') {
continue; continue;
}
if (method_exists($this, $key)) { if (method_exists($this, $key)) {
$merge_rules = $this->{$key}($rules); $merge_rules = $this->{$key}($rules);

View File

@ -64,8 +64,7 @@ class CheckSmtpRequest extends Request
if(isset($input['smtp_host']) && strlen($input['smtp_host']) >= 3) { if(isset($input['smtp_host']) && strlen($input['smtp_host']) >= 3) {
} } else {
else {
$input['smtp_host'] = $company->smtp_host; $input['smtp_host'] = $company->smtp_host;
} }

View File

@ -40,5 +40,3 @@ class TwigLint implements ValidationRule
} }
} }

View File

@ -71,8 +71,9 @@ class LockedInvoiceRule implements Rule
//if now is greater than the end of month the invoice was dated - do not modify //if now is greater than the end of month the invoice was dated - do not modify
case 'end_of_month': case 'end_of_month':
if(\Carbon\Carbon::parse($this->invoice->date)->setTimezone($this->invoice->company->timezone()->name)->endOfMonth()->lte(now())) if(\Carbon\Carbon::parse($this->invoice->date)->setTimezone($this->invoice->company->timezone()->name)->endOfMonth()->lte(now())) {
return false; return false;
}
return true; return true;
default: default:

View File

@ -255,8 +255,9 @@ class BaseImport
unset($record['']); unset($record['']);
if(!is_array($record)) if(!is_array($record)) {
continue; continue;
}
try { try {
$entity = $this->transformer->transform($record); $entity = $this->transformer->transform($record);

View File

@ -102,16 +102,14 @@ class InvoiceTransformer extends BaseTransformer
'amount' => $this->getFloat($invoice_data, 'Payments'), 'amount' => $this->getFloat($invoice_data, 'Payments'),
], ],
]; ];
} } elseif(isset($invoice_data['AmountPaidAmount']) && isset($invoice_data['DatePaid'])) {
elseif(isset($invoice_data['AmountPaidAmount']) && isset($invoice_data['DatePaid'])){
$transformed['payments'] = [ $transformed['payments'] = [
[ [
'date' => $this->parseDate($invoice_data['DatePaid']), 'date' => $this->parseDate($invoice_data['DatePaid']),
'amount' => $this->getFloat($invoice_data, 'AmountPaidAmount'), 'amount' => $this->getFloat($invoice_data, 'AmountPaidAmount'),
] ]
]; ];
} } elseif(isset($invoice_data['DocumentStatus']) && $invoice_data['DocumentStatus'] == 'fully_paid') {
elseif(isset($invoice_data['DocumentStatus']) && $invoice_data['DocumentStatus'] == 'fully_paid'){
$transformed['payments'] = [ $transformed['payments'] = [
[ [
@ -125,7 +123,8 @@ class InvoiceTransformer extends BaseTransformer
} }
private function harvestAddresses($invoice_data) { private function harvestAddresses($invoice_data)
{
$address = $invoice_data['DocumentRecipientAddress']; $address = $invoice_data['DocumentRecipientAddress'];
$lines = explode("\n", $address); $lines = explode("\n", $address);
@ -208,8 +207,7 @@ class InvoiceTransformer extends BaseTransformer
$line_items = []; $line_items = [];
foreach($processed as $item) foreach($processed as $item) {
{
$_item['cost'] = $item['unit_price']; $_item['cost'] = $item['unit_price'];
$_item['quantity'] = $item['qty'] ?? 1; $_item['quantity'] = $item['qty'] ?? 1;
$_item['discount'] = $item['discount_percentage'] > $item['discount_amount'] ? $item['discount_percentage'] : $item['discount_amount']; $_item['discount'] = $item['discount_percentage'] > $item['discount_amount'] ? $item['discount_percentage'] : $item['discount_amount'];
@ -230,8 +228,9 @@ class InvoiceTransformer extends BaseTransformer
private function parseTaxes($ninja_item, $i2g_item): array private function parseTaxes($ninja_item, $i2g_item): array
{ {
if(is_string($i2g_item['applied_taxes'])) if(is_string($i2g_item['applied_taxes'])) {
return $ninja_item; return $ninja_item;
}
$ninja_item['tax_name1'] = 'Tax'; $ninja_item['tax_name1'] = 'Tax';
$ninja_item['tax_rate1'] = $i2g_item['applied_taxes']['rate']; $ninja_item['tax_rate1'] = $i2g_item['applied_taxes']['rate'];
@ -241,7 +240,7 @@ class InvoiceTransformer extends BaseTransformer
} }
function parseCsvWithNestedCsv($csvString, $delimiter = ',', $enclosure = '"', $lineEnding = ';') public function parseCsvWithNestedCsv($csvString, $delimiter = ',', $enclosure = '"', $lineEnding = ';')
{ {
// Regular expression to find nested CSVs // Regular expression to find nested CSVs
$nestedCsvPattern = '/"([^"]*(?:""[^"]*)*)"/'; $nestedCsvPattern = '/"([^"]*(?:""[^"]*)*)"/';

View File

@ -36,7 +36,10 @@ use Turbo124\Beacon\Facades\LightLogs;
class ProcessBrevoWebhook implements ShouldQueue class ProcessBrevoWebhook implements ShouldQueue
{ {
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; use Dispatchable;
use InteractsWithQueue;
use Queueable;
use SerializesModels;
public $tries = 1; public $tries = 1;

View File

@ -350,12 +350,14 @@ class CompanyImport implements ShouldQueue
} }
} }
if(file_exists($tmp_file)) if(file_exists($tmp_file)) {
unlink($tmp_file); unlink($tmp_file);
}
if(Storage::exists($this->file_location)) if(Storage::exists($this->file_location)) {
unlink(Storage::path($this->file_location)); unlink(Storage::path($this->file_location));
} }
}
// //
private function postImportCleanup() private function postImportCleanup()
@ -513,8 +515,7 @@ class CompanyImport implements ShouldQueue
$settings->email_style_custom = str_replace(['{!!','!!}','{{','}}','@dd', '@dump', '@if', '@if(','@endif','@isset','@unless','@auth','@empty','@guest','@env','@section','@switch', '@foreach', '@while', '@include', '@each', '@once', '@push', '@use', '@forelse', '@verbatim', '<?php', '@php', '@for','@class','</s','<s','html;base64'], '', $settings->email_style_custom); $settings->email_style_custom = str_replace(['{!!','!!}','{{','}}','@dd', '@dump', '@if', '@if(','@endif','@isset','@unless','@auth','@empty','@guest','@env','@section','@switch', '@foreach', '@while', '@include', '@each', '@once', '@push', '@use', '@forelse', '@verbatim', '<?php', '@php', '@for','@class','</s','<s','html;base64'], '', $settings->email_style_custom);
$settings->company_logo = (strlen($settings->company_logo) > 2 && stripos($settings->company_logo, 'http') !== false) ? $settings->company_logo : "https://{$settings->company_logo}"; $settings->company_logo = (strlen($settings->company_logo) > 2 && stripos($settings->company_logo, 'http') !== false) ? $settings->company_logo : "https://{$settings->company_logo}";
foreach($this->protected_input as $protected_var) foreach($this->protected_input as $protected_var) {
{
$settings->{$protected_var} = str_replace("script", "", $settings->{$protected_var}); $settings->{$protected_var} = str_replace("script", "", $settings->{$protected_var});
} }

View File

@ -59,8 +59,9 @@ class CreateEDocument implements ShouldQueue
App::setLocale($settings_entity->locale()); App::setLocale($settings_entity->locale());
/* Set customized translations _NOW_ */ /* Set customized translations _NOW_ */
if($this->document->client ?? false) if($this->document->client ?? false) {
$t->replace(Ninja::transformTranslations($this->document->client->getMergedSettings())); $t->replace(Ninja::transformTranslations($this->document->client->getMergedSettings()));
}
$e_document_type = strlen($settings_entity->getSetting('e_invoice_type')) > 2 ? $settings_entity->getSetting('e_invoice_type') : "XInvoice_3_0"; $e_document_type = strlen($settings_entity->getSetting('e_invoice_type')) > 2 ? $settings_entity->getSetting('e_invoice_type') : "XInvoice_3_0";
$e_quote_type = strlen($settings_entity->getSetting('e_quote_type')) > 2 ? $settings_entity->getSetting('e_quote_type') : "OrderX_Extended"; $e_quote_type = strlen($settings_entity->getSetting('e_quote_type')) > 2 ? $settings_entity->getSetting('e_quote_type') : "OrderX_Extended";
@ -95,8 +96,7 @@ class CreateEDocument implements ShouldQueue
return $this->returnObject ? $zugferd : $zugferd->getXml(); return $this->returnObject ? $zugferd : $zugferd->getXml();
} }
} } elseif ($this->document instanceof Quote) {
elseif ($this->document instanceof Quote){
switch ($e_quote_type) { switch ($e_quote_type) {
case "OrderX_Basic": case "OrderX_Basic":
case "OrderX_Comfort": case "OrderX_Comfort":
@ -107,8 +107,7 @@ class CreateEDocument implements ShouldQueue
$orderx = (new OrderXDocument($this->document))->run(); $orderx = (new OrderXDocument($this->document))->run();
return $this->returnObject ? $orderx->orderxdocument : $orderx->getXml(); return $this->returnObject ? $orderx->orderxdocument : $orderx->getXml();
} }
} } elseif ($this->document instanceof PurchaseOrder) {
elseif ($this->document instanceof PurchaseOrder){
switch ($e_quote_type) { switch ($e_quote_type) {
case "OrderX_Basic": case "OrderX_Basic":
case "OrderX_Comfort": case "OrderX_Comfort":
@ -119,8 +118,7 @@ class CreateEDocument implements ShouldQueue
$orderx = (new OrderXDocument($this->document))->run(); $orderx = (new OrderXDocument($this->document))->run();
return $this->returnObject ? $orderx->orderxdocument : $orderx->getXml(); return $this->returnObject ? $orderx->orderxdocument : $orderx->getXml();
} }
} } elseif ($this->document instanceof Credit) {
elseif ($this->document instanceof Credit) {
switch ($e_document_type) { switch ($e_document_type) {
case "EN16931": case "EN16931":
case "XInvoice_3_0": case "XInvoice_3_0":
@ -138,8 +136,7 @@ class CreateEDocument implements ShouldQueue
$zugferd = (new ZugferdEDokument($this->document))->run(); $zugferd = (new ZugferdEDokument($this->document))->run();
return $this->returnObject ? $zugferd : $zugferd->getXml(); return $this->returnObject ? $zugferd : $zugferd->getXml();
} }
} } else {
else{
return ""; return "";
} }
} }

View File

@ -53,10 +53,8 @@ class MergeEDocument implements ShouldQueue
return $this->pdf_file; return $this->pdf_file;
} }
} } else {
else{
return $this->pdf_file; return $this->pdf_file;
} }
} }
} }

View File

@ -153,22 +153,19 @@ class NinjaMailerJob implements ShouldQueue
LightLogs::create(new EmailSuccess($this->nmo->company->company_key, $this->nmo->mailable->subject)) LightLogs::create(new EmailSuccess($this->nmo->company->company_key, $this->nmo->mailable->subject))
->send(); ->send();
} } catch (\Symfony\Component\Mime\Exception\RfcComplianceException $e) {
catch (\Symfony\Component\Mime\Exception\RfcComplianceException $e) {
nlog("Mailer failed with a Logic Exception {$e->getMessage()}"); nlog("Mailer failed with a Logic Exception {$e->getMessage()}");
$this->fail(); $this->fail();
$this->cleanUpMailers(); $this->cleanUpMailers();
$this->logMailError($e->getMessage(), $this->company->clients()->first()); $this->logMailError($e->getMessage(), $this->company->clients()->first());
return; return;
} } catch (\Symfony\Component\Mime\Exception\LogicException $e) {
catch (\Symfony\Component\Mime\Exception\LogicException $e) {
nlog("Mailer failed with a Logic Exception {$e->getMessage()}"); nlog("Mailer failed with a Logic Exception {$e->getMessage()}");
$this->fail(); $this->fail();
$this->cleanUpMailers(); $this->cleanUpMailers();
$this->logMailError($e->getMessage(), $this->company->clients()->first()); $this->logMailError($e->getMessage(), $this->company->clients()->first());
return; return;
} } catch(\Google\Service\Exception $e) {
catch(\Google\Service\Exception $e){
if ($e->getCode() == '429') { if ($e->getCode() == '429') {
@ -179,8 +176,7 @@ class NinjaMailerJob implements ShouldQueue
} }
} } catch (\Exception $e) {
catch (\Exception $e) {
nlog("Mailer failed with {$e->getMessage()}"); nlog("Mailer failed with {$e->getMessage()}");
$message = $e->getMessage(); $message = $e->getMessage();
@ -258,8 +254,9 @@ class NinjaMailerJob implements ShouldQueue
private function incrementEmailCounter(): void private function incrementEmailCounter(): void
{ {
if(in_array($this->mailer, ['default','mailgun','postmark'])) if(in_array($this->mailer, ['default','mailgun','postmark'])) {
Cache::increment("email_quota".$this->company->account->key); Cache::increment("email_quota".$this->company->account->key);
}
} }
/** /**
@ -400,8 +397,7 @@ class NinjaMailerJob implements ShouldQueue
if(strlen($smtp_host) <= 1 || if(strlen($smtp_host) <= 1 ||
strlen($smtp_username) <= 1 || strlen($smtp_username) <= 1 ||
strlen($smtp_password) <= 1 strlen($smtp_password) <= 1
) ) {
{
$this->nmo->settings->email_sending_method = 'default'; $this->nmo->settings->email_sending_method = 'default';
return $this->setMailDriver(); return $this->setMailDriver();
} }
@ -813,8 +809,7 @@ class NinjaMailerJob implements ShouldQueue
'refresh_token' => $user->oauth_user_refresh_token 'refresh_token' => $user->oauth_user_refresh_token
], ],
])->getBody()->getContents()); ])->getBody()->getContents());
} } catch(\Exception $e) {
catch(\Exception $e){
nlog("Problem getting new Microsoft token for User: {$user->email}"); nlog("Problem getting new Microsoft token for User: {$user->email}");
} }

View File

@ -92,8 +92,7 @@ class BankTransactionSync implements ShouldQueue
$account->bank_integrations()->where('integration_type', BankIntegration::INTEGRATION_TYPE_NORDIGEN)->where('auto_sync', true)->where('disabled_upstream', 0)->cursor()->each(function ($bank_integration) { $account->bank_integrations()->where('integration_type', BankIntegration::INTEGRATION_TYPE_NORDIGEN)->where('auto_sync', true)->where('disabled_upstream', 0)->cursor()->each(function ($bank_integration) {
try { try {
(new ProcessBankTransactionsNordigen($bank_integration))->handle(); (new ProcessBankTransactionsNordigen($bank_integration))->handle();
} } catch(\Exception $e) {
catch(\Exception $e) {
sleep(20); sleep(20);
} }

View File

@ -405,8 +405,7 @@ class ProcessPostmarkWebhook implements ShouldQueue
try { try {
$messageDetail = $postmark->getOutboundMessageDetails($this->request['MessageID']); $messageDetail = $postmark->getOutboundMessageDetails($this->request['MessageID']);
} } catch(\Exception $e) {
catch(\Exception $e){
$postmark_secret = config('services.postmark-outlook.token'); $postmark_secret = config('services.postmark-outlook.token');
$postmark = new PostmarkClient($postmark_secret); $postmark = new PostmarkClient($postmark_secret);

View File

@ -57,8 +57,7 @@ class SendToAdmin implements ShouldQueue
$csv = $export->run(); $csv = $export->run();
$user = $this->company->owner(); $user = $this->company->owner();
if(isset($this->request['user_id'])) if(isset($this->request['user_id'])) {
{
$user = User::find($this->request['user_id']) ?? $this->company->owner(); $user = User::find($this->request['user_id']) ?? $this->company->owner();
} }

View File

@ -232,12 +232,14 @@ class RequiredClientInfo extends Component
$this->invoice_terms = $invoice->terms; $this->invoice_terms = $invoice->terms;
} }
if(!$this->company_gateway->always_show_required_fields || $this->is_subscription) if(!$this->company_gateway->always_show_required_fields || $this->is_subscription) {
$this->checkFields(); $this->checkFields();
}
if($this->unfilled_fields > 0 || ($this->company_gateway->always_show_required_fields || $this->is_subscription)) if($this->unfilled_fields > 0 || ($this->company_gateway->always_show_required_fields || $this->is_subscription)) {
$this->show_form = true; $this->show_form = true;
} }
}
#[Computed] #[Computed]
public function contact() public function contact()

View File

@ -154,8 +154,9 @@ class TemplateEmail extends Mailable
} }
} }
if(!$this->invitation) if(!$this->invitation) {
return $this; return $this;
}
if ($this->invitation->invoice && $settings->ubl_email_attachment && $this->company->account->hasFeature(Account::FEATURE_PDF_ATTACHMENT)) { if ($this->invitation->invoice && $settings->ubl_email_attachment && $this->company->account->hasFeature(Account::FEATURE_PDF_ATTACHMENT)) {
$ubl_string = (new CreateUbl($this->invitation->invoice))->handle(); $ubl_string = (new CreateUbl($this->invitation->invoice))->handle();
@ -175,8 +176,7 @@ class TemplateEmail extends Mailable
} }
} }
} } elseif ($this->invitation->credit) {
elseif ($this->invitation->credit){
if ($this->invitation->credit->client->getSetting('enable_e_invoice') && $this->company->account->hasFeature(Account::FEATURE_PDF_ATTACHMENT)) { if ($this->invitation->credit->client->getSetting('enable_e_invoice') && $this->company->account->hasFeature(Account::FEATURE_PDF_ATTACHMENT)) {
$xml_string = $this->invitation->credit->service()->getECredit($this->invitation->contact); $xml_string = $this->invitation->credit->service()->getECredit($this->invitation->contact);
@ -185,8 +185,7 @@ class TemplateEmail extends Mailable
} }
} }
} } elseif ($this->invitation->quote) {
elseif ($this->invitation->quote){
if ($this->invitation->quote->client->getSetting('enable_e_invoice') && $this->company->account->hasFeature(Account::FEATURE_PDF_ATTACHMENT)) { if ($this->invitation->quote->client->getSetting('enable_e_invoice') && $this->company->account->hasFeature(Account::FEATURE_PDF_ATTACHMENT)) {
$xml_string = $this->invitation->quote->service()->getEQuote($this->invitation->contact); $xml_string = $this->invitation->quote->service()->getEQuote($this->invitation->contact);
@ -195,8 +194,7 @@ class TemplateEmail extends Mailable
} }
} }
} } elseif ($this->invitation->purchase_order) {
elseif ($this->invitation->purchase_order){
if ($this->invitation->purchase_order->vendor->getSetting('enable_e_invoice') && $this->company->account->hasFeature(Account::FEATURE_PDF_ATTACHMENT)) { if ($this->invitation->purchase_order->vendor->getSetting('enable_e_invoice') && $this->company->account->hasFeature(Account::FEATURE_PDF_ATTACHMENT)) {
$xml_string = $this->invitation->purchase_order->service()->getEPurchaseOrder($this->invitation->contact); $xml_string = $this->invitation->purchase_order->service()->getEPurchaseOrder($this->invitation->contact);

View File

@ -495,8 +495,9 @@ class Account extends BaseModel
return 0; return 0;
} }
if($this->email_quota) if($this->email_quota) {
return (int)$this->email_quota; return (int)$this->email_quota;
}
if (Carbon::createFromTimestamp($this->created_at)->diffInWeeks() <= 1) { if (Carbon::createFromTimestamp($this->created_at)->diffInWeeks() <= 1) {
return 20; return 20;

View File

@ -355,12 +355,13 @@ class RecurringInvoice extends BaseModel
public function calculateStatus(bool $new_model = false) //15-02-2024 - $new_model needed public function calculateStatus(bool $new_model = false) //15-02-2024 - $new_model needed
{ {
if($this->remaining_cycles == 0) if($this->remaining_cycles == 0) {
return self::STATUS_COMPLETED; return self::STATUS_COMPLETED;
elseif ($new_model && $this->status_id == self::STATUS_ACTIVE && Carbon::parse($this->next_send_date)->isFuture()) } elseif ($new_model && $this->status_id == self::STATUS_ACTIVE && Carbon::parse($this->next_send_date)->isFuture()) {
return self::STATUS_PENDING; return self::STATUS_PENDING;
elseif($this->remaining_cycles != 0 && ($this->status_id == self::STATUS_COMPLETED)) } elseif($this->remaining_cycles != 0 && ($this->status_id == self::STATUS_COMPLETED)) {
return self::STATUS_ACTIVE; return self::STATUS_ACTIVE;
}
return $this->status_id; return $this->status_id;

View File

@ -170,8 +170,9 @@ class AuthorizePaymentMethod
$billto->setState(substr($this->authorize->client->state, 0, 40)); $billto->setState(substr($this->authorize->client->state, 0, 40));
$billto->setZip(substr($this->authorize->client->postal_code, 0, 20)); $billto->setZip(substr($this->authorize->client->postal_code, 0, 20));
if(isset($contact->email) && str_contains($contact->email, '@')) if(isset($contact->email) && str_contains($contact->email, '@')) {
$billto->setEmail($contact->email); $billto->setEmail($contact->email);
}
if ($this->authorize->client->country_id) { if ($this->authorize->client->country_id) {
$billto->setCountry($this->authorize->client->country->name); $billto->setCountry($this->authorize->client->country->name);

View File

@ -43,7 +43,7 @@ class BTCPayPaymentDriver extends BaseDriver
GatewayType::CRYPTO => BTCPay::class, //maps GatewayType => Implementation class GatewayType::CRYPTO => BTCPay::class, //maps GatewayType => Implementation class
]; ];
const SYSTEM_LOG_TYPE = SystemLog::TYPE_CHECKOUT; //define a constant for your gateway ie TYPE_YOUR_CUSTOM_GATEWAY - set the const in the SystemLog model public const SYSTEM_LOG_TYPE = SystemLog::TYPE_CHECKOUT; //define a constant for your gateway ie TYPE_YOUR_CUSTOM_GATEWAY - set the const in the SystemLog model
public $btcpay_url = ""; public $btcpay_url = "";
public $api_key = ""; public $api_key = "";

View File

@ -572,8 +572,7 @@ class BaseDriver extends AbstractPaymentDriver
$nmo->company = $this->client->company; $nmo->company = $this->client->company;
$nmo->settings = $this->client->company->settings; $nmo->settings = $this->client->company->settings;
if($this->payment_hash) if($this->payment_hash) {
{
$invoices = Invoice::query()->whereIn('id', $this->transformKeys(array_column($this->payment_hash->invoices(), 'invoice_id')))->withTrashed()->get(); $invoices = Invoice::query()->whereIn('id', $this->transformKeys(array_column($this->payment_hash->invoices(), 'invoice_id')))->withTrashed()->get();
$invoices->first()->invitations->each(function ($invitation) use ($nmo) { $invoices->first()->invitations->each(function ($invitation) use ($nmo) {

View File

@ -338,20 +338,19 @@ class BraintreePaymentDriver extends BaseDriver
$ct = $this->init()->gateway->clientToken()->generate(); $ct = $this->init()->gateway->clientToken()->generate();
return true; return true;
} } catch(\Exception $e) {
catch(\Exception $e) {
} }
return false; return false;
} }
private function find(string $customer_id = '') { private function find(string $customer_id = '')
{
try { try {
return $this->init()->gateway->customer()->find($customer_id); return $this->init()->gateway->customer()->find($customer_id);
} } catch(\Exception $e) {
catch(\Exception $e){
return false; return false;
} }
@ -375,7 +374,8 @@ class BraintreePaymentDriver extends BaseDriver
} }
private function findClient(string $email) { private function findClient(string $email)
{
return ClientContact::where('company_id', $this->company_gateway->company_id) return ClientContact::where('company_id', $this->company_gateway->company_id)
->where('email', $email) ->where('email', $email)
->first()->client ?? false; ->first()->client ?? false;
@ -388,8 +388,9 @@ class BraintreePaymentDriver extends BaseDriver
foreach($cards as $card) { foreach($cards as $card) {
if($this->getToken($card->token, $card->customerId) || Carbon::createFromDate($card->expirationYear, $card->expirationMonth, '1')->lt(now())) if($this->getToken($card->token, $card->customerId) || Carbon::createFromDate($card->expirationYear, $card->expirationMonth, '1')->lt(now())) {
continue; continue;
}
$payment_meta = new \stdClass(); $payment_meta = new \stdClass();
$payment_meta->exp_month = (string) $card->expirationMonth; $payment_meta->exp_month = (string) $card->expirationMonth;
@ -505,8 +506,9 @@ class BraintreePaymentDriver extends BaseDriver
// nlog(count($customer->creditCards). " Exists for {$c->id}"); // nlog(count($customer->creditCards). " Exists for {$c->id}");
if(!$customer) if(!$customer) {
continue; continue;
}
$client = $this->findClient($customer->email); $client = $this->findClient($customer->email);

View File

@ -541,8 +541,7 @@ class CheckoutComPaymentDriver extends BaseDriver
try { try {
$this->init()->gateway->getCustomersClient('x'); $this->init()->gateway->getCustomersClient('x');
return true; return true;
} } catch(\Exception $e) {
catch(\Exception $e){
} }
return false; return false;
@ -575,13 +574,13 @@ class CheckoutComPaymentDriver extends BaseDriver
->cursor() ->cursor()
->each(function ($client) { ->each(function ($client) {
if(!str_contains($client->present()->email(), "@")) if(!str_contains($client->present()->email(), "@")) {
return; return;
}
try { try {
$customer = $this->gateway->getCustomersClient()->get($client->present()->email()); $customer = $this->gateway->getCustomersClient()->get($client->present()->email());
} } catch(\Exception $e) {
catch(\Exception $e) {
nlog("Checkout: Customer not found"); nlog("Checkout: Customer not found");
return; return;
} }
@ -590,14 +589,14 @@ class CheckoutComPaymentDriver extends BaseDriver
nlog($customer['instruments']); nlog($customer['instruments']);
foreach($customer['instruments'] as $card) foreach($customer['instruments'] as $card) {
{
if( if(
$card['type'] != 'card' || $card['type'] != 'card' ||
Carbon::createFromDate($card['expiry_year'], $card['expiry_month'], '1')->lt(now()) || Carbon::createFromDate($card['expiry_year'], $card['expiry_month'], '1')->lt(now()) ||
$this->getToken($card['id'], $customer['id']) $this->getToken($card['id'], $customer['id'])
) ) {
continue; continue;
}
$payment_meta = new \stdClass(); $payment_meta = new \stdClass();
$payment_meta->exp_month = (string) $card['expiry_month']; $payment_meta->exp_month = (string) $card['expiry_month'];

View File

@ -17,7 +17,6 @@ use App\Models\Company;
class ForteCustomerFactory class ForteCustomerFactory
{ {
public function convertToNinja(array $customer, Company $company): array public function convertToNinja(array $customer, Company $company): array
{ {
return return
@ -51,8 +50,9 @@ class ForteCustomerFactory
foreach($customer['addresses'] as $address) { foreach($customer['addresses'] as $address) {
if($address['address_token'] != $customer['default_billing_address_token']) if($address['address_token'] != $customer['default_billing_address_token']) {
continue; continue;
}
return [ return [
'address1' => $address['physical_address']['street_line1'], 'address1' => $address['physical_address']['street_line1'],

View File

@ -17,7 +17,6 @@ use App\Models\GatewayType;
class SquareCustomerFactory class SquareCustomerFactory
{ {
/* /*
{ {
"id": "A537H7KAQWSAF8M8EM1Y23E16M", "id": "A537H7KAQWSAF8M8EM1Y23E16M",
@ -85,7 +84,7 @@ class SquareCustomerFactory
foreach($customer->getCards() ?? [] as $card) { foreach($customer->getCards() ?? [] as $card) {
$meta = new \stdClass; $meta = new \stdClass();
$meta->exp_month = $card->getExpMonth(); $meta->exp_month = $card->getExpMonth();
$meta->exp_year = $card->getExpYear(); $meta->exp_year = $card->getExpYear();
$meta->last4 = $card->getLast4(); $meta->last4 = $card->getLast4();

View File

@ -260,8 +260,9 @@ class FortePaymentDriver extends BaseDriver
->withQueryParameters(['page_size' => 10000]) ->withQueryParameters(['page_size' => 10000])
->get("{$this->baseUri()}/organizations/{$this->getOrganisationId()}/locations/{$this->getLocationId()}"); ->get("{$this->baseUri()}/organizations/{$this->getOrganisationId()}/locations/{$this->getLocationId()}");
if($response->successful()) if($response->successful()) {
return $response->json(); return $response->json();
}
return false; return false;
} }
@ -270,8 +271,7 @@ class FortePaymentDriver extends BaseDriver
{ {
$response = $this->getLocation(); $response = $this->getLocation();
if($response) if($response) {
{
$body = $response['services']; $body = $response['services'];
$fees_and_limits = $this->company_gateway->fees_and_limits; $fees_and_limits = $this->company_gateway->fees_and_limits;
@ -306,16 +306,16 @@ class FortePaymentDriver extends BaseDriver
if($response->successful()) { if($response->successful()) {
foreach($response->json()['results'] as $customer) foreach($response->json()['results'] as $customer) {
{
$client_repo = new ClientRepository(new ClientContactRepository()); $client_repo = new ClientRepository(new ClientContactRepository());
$factory = new ForteCustomerFactory(); $factory = new ForteCustomerFactory();
$data = $factory->convertToNinja($customer, $this->company_gateway->company); $data = $factory->convertToNinja($customer, $this->company_gateway->company);
if(strlen($data['email']) == 0 || $this->getClient($data['email'])) if(strlen($data['email']) == 0 || $this->getClient($data['email'])) {
continue; continue;
}
$client_repo->save($data, ClientFactory::create($this->company_gateway->company_id, $this->company_gateway->user_id)); $client_repo->save($data, ClientFactory::create($this->company_gateway->company_id, $this->company_gateway->user_id));

View File

@ -564,8 +564,7 @@ class GoCardlessPaymentDriver extends BaseDriver
try { try {
$customers = $this->init()->gateway->customers()->list(); $customers = $this->init()->gateway->customers()->list();
return true; return true;
} } catch(\Exception $e) {
catch(\Exception $e){
} }

View File

@ -428,8 +428,7 @@ class MolliePaymentDriver extends BaseDriver
try { try {
$p = $this->gateway->payments->page(); $p = $this->gateway->payments->page();
return true; return true;
} } catch(\Exception $e) {
catch(\Exception $e){
} }

View File

@ -83,8 +83,9 @@ class PayPalBasePaymentDriver extends BaseDriver
/** Parse funding options and remove card option if advanced cards is enabled. */ /** Parse funding options and remove card option if advanced cards is enabled. */
if(in_array(1, $funding_options) && in_array(29, $funding_options)) { if(in_array(1, $funding_options) && in_array(29, $funding_options)) {
if (($key = array_search(1, $funding_options)) !== false) if (($key = array_search(1, $funding_options)) !== false) {
unset($funding_options[$key]); unset($funding_options[$key]);
}
} }
@ -189,8 +190,9 @@ class PayPalBasePaymentDriver extends BaseDriver
$cgt = ClientGatewayToken::where('company_gateway_id', $this->company_gateway->id) $cgt = ClientGatewayToken::where('company_gateway_id', $this->company_gateway->id)
->where('client_id', $this->client->id) ->where('client_id', $this->client->id)
->first(); ->first();
if(!$cgt) if(!$cgt) {
return ''; return '';
}
$client_reference = $cgt->gateway_customer_reference; $client_reference = $cgt->gateway_customer_reference;
@ -329,15 +331,13 @@ class PayPalBasePaymentDriver extends BaseDriver
"postal_code" => $this->client->shipping_postal_code, "postal_code" => $this->client->shipping_postal_code,
"country_code" => $this->client->present()->shipping_country_code(), "country_code" => $this->client->present()->shipping_country_code(),
]; ];
} } elseif(
elseif(
strlen($this->client->address1 ?? '') > 2 && strlen($this->client->address1 ?? '') > 2 &&
strlen($this->client->city ?? '') > 2 && strlen($this->client->city ?? '') > 2 &&
strlen($this->client->state ?? '') >= 2 && strlen($this->client->state ?? '') >= 2 &&
strlen($this->client->postal_code ?? '') > 2 && strlen($this->client->postal_code ?? '') > 2 &&
strlen($this->client->country->iso_3166_2 ?? '') >= 2 strlen($this->client->country->iso_3166_2 ?? '') >= 2
) ) {
{
$order['paypal']['address'] = [ $order['paypal']['address'] = [
"address_line_1" => $this->client->address1, "address_line_1" => $this->client->address1,
"address_line_2" => $this->client->address2, "address_line_2" => $this->client->address2,
@ -450,7 +450,8 @@ class PayPalBasePaymentDriver extends BaseDriver
} }
} }
public function handleRetry($response, $request) { public function handleRetry($response, $request)
{
return response()->json($response->json()); return response()->json($response->json());
} }
@ -497,8 +498,7 @@ class PayPalBasePaymentDriver extends BaseDriver
try { try {
$this->init()->getClientToken(); $this->init()->getClientToken();
return true; return true;
} } catch(\Exception $e) {
catch(\Exception $e) {
} }

View File

@ -103,10 +103,11 @@ class PayPalPPCPPaymentDriver extends PayPalBasePaymentDriver
$data['identifier'] = "s:INN_".$this->company_gateway->getConfigField('merchantId')."_CHCK"; $data['identifier'] = "s:INN_".$this->company_gateway->getConfigField('merchantId')."_CHCK";
$data['pp_client_reference'] = $this->getClientHash(); $data['pp_client_reference'] = $this->getClientHash();
if($this->gateway_type_id == 29) if($this->gateway_type_id == 29) {
return render('gateways.paypal.ppcp.card', $data); return render('gateways.paypal.ppcp.card', $data);
else } else {
return render('gateways.paypal.ppcp.pay', $data); return render('gateways.paypal.ppcp.pay', $data);
}
} }
@ -320,7 +321,8 @@ class PayPalPPCPPaymentDriver extends PayPalBasePaymentDriver
* @param array $response * @param array $response
* @return void * @return void
*/ */
public function processTokenPayment($request, array $response) { public function processTokenPayment($request, array $response)
{
/** @var \App\Models\ClientGatewayToken $cgt */ /** @var \App\Models\ClientGatewayToken $cgt */
$cgt = ClientGatewayToken::where('client_id', $this->client->id) $cgt = ClientGatewayToken::where('client_id', $this->client->id)

View File

@ -49,14 +49,11 @@ class PayPalRestPaymentDriver extends PayPalBasePaymentDriver
$data['identifier'] = "s:INN_ACDC_CHCK"; $data['identifier'] = "s:INN_ACDC_CHCK";
$data['pp_client_reference'] = $this->getClientHash(); $data['pp_client_reference'] = $this->getClientHash();
nlog($data['guid']); if($this->gateway_type_id == 29) {
nlog($data['order_id']);
if($this->gateway_type_id == 29)
return render('gateways.paypal.ppcp.card', $data); return render('gateways.paypal.ppcp.card', $data);
else } else {
return render('gateways.paypal.pay', $data); return render('gateways.paypal.pay', $data);
}
} }
@ -77,8 +74,9 @@ class PayPalRestPaymentDriver extends PayPalBasePaymentDriver
nlog($response); nlog($response);
if($request->has('token') && strlen($request->input('token')) > 2) if($request->has('token') && strlen($request->input('token')) > 2) {
return $this->processTokenPayment($request, $response); return $this->processTokenPayment($request, $response);
}
//capture //capture
@ -116,8 +114,7 @@ class PayPalRestPaymentDriver extends PayPalBasePaymentDriver
} }
} } catch(\Exception $e) {
catch(\Exception $e) {
//Rescue for duplicate invoice_id //Rescue for duplicate invoice_id
if(stripos($e->getMessage(), 'DUPLICATE_INVOICE_ID') !== false) { if(stripos($e->getMessage(), 'DUPLICATE_INVOICE_ID') !== false) {
@ -163,7 +160,8 @@ class PayPalRestPaymentDriver extends PayPalBasePaymentDriver
private function createNinjaPayment($request, $response) { private function createNinjaPayment($request, $response)
{
$data = [ $data = [
'payment_type' => $this->getPaymentMethod($request->gateway_type_id), 'payment_type' => $this->getPaymentMethod($request->gateway_type_id),
@ -268,8 +266,9 @@ class PayPalRestPaymentDriver extends PayPalBasePaymentDriver
$order['purchase_units'][0]["shipping"] = $shipping; $order['purchase_units'][0]["shipping"] = $shipping;
} }
if(isset($data['payment_source'])) if(isset($data['payment_source'])) {
$order['payment_source'] = $data['payment_source']; $order['payment_source'] = $data['payment_source'];
}
$r = $this->gatewayRequest('/v2/checkout/orders', 'post', $order); $r = $this->gatewayRequest('/v2/checkout/orders', 'post', $order);
@ -293,8 +292,9 @@ class PayPalRestPaymentDriver extends PayPalBasePaymentDriver
} }
if(!isset($response['id'])) if(!isset($response['id'])) {
$this->handleProcessingFailure($response); $this->handleProcessingFailure($response);
}
$this->payment_hash->withData("orderID", $response['id']); $this->payment_hash->withData("orderID", $response['id']);
@ -317,7 +317,8 @@ class PayPalRestPaymentDriver extends PayPalBasePaymentDriver
* @param mixed $request * @param mixed $request
* @param array $response * @param array $response
*/ */
public function processTokenPayment($request, array $response) { public function processTokenPayment($request, array $response)
{
/** @var \App\Models\ClientGatewayToken $cgt */ /** @var \App\Models\ClientGatewayToken $cgt */
$cgt = ClientGatewayToken::where('client_id', $this->client->id) $cgt = ClientGatewayToken::where('client_id', $this->client->id)
@ -327,7 +328,6 @@ class PayPalRestPaymentDriver extends PayPalBasePaymentDriver
$orderId = $response['orderID']; $orderId = $response['orderID'];
$r = $this->gatewayRequest("/v1/checkout/orders/{$orderId}/", 'delete', ['body' => '']); $r = $this->gatewayRequest("/v1/checkout/orders/{$orderId}/", 'delete', ['body' => '']);
nlog("token payyy");
nlog($r->body()); nlog($r->body());
$data['amount_with_fee'] = $this->payment_hash->data->amount_with_fee; $data['amount_with_fee'] = $this->payment_hash->data->amount_with_fee;
@ -372,10 +372,6 @@ class PayPalRestPaymentDriver extends PayPalBasePaymentDriver
} }
$response = $r->json(); $response = $r->json();
$data = [ $data = [

View File

@ -270,8 +270,7 @@ class PaytracePaymentDriver extends BaseDriver
try { try {
$this->init()->generateAuthHeaders() && strlen($this->company_gateway->getConfigField('integratorId')) > 2; $this->init()->generateAuthHeaders() && strlen($this->company_gateway->getConfigField('integratorId')) > 2;
return true; return true;
} } catch(\Exception $e) {
catch(\Exception $e){
} }
@ -295,27 +294,27 @@ class PaytracePaymentDriver extends BaseDriver
$client_repo = new ClientRepository(new ClientContactRepository()); $client_repo = new ClientRepository(new ClientContactRepository());
$factory = new PaytraceCustomerFactory(); $factory = new PaytraceCustomerFactory();
foreach($response->customers as $customer) foreach($response->customers as $customer) {
{
$data = $factory->convertToNinja($customer, $this->company_gateway->company); $data = $factory->convertToNinja($customer, $this->company_gateway->company);
$client = false; $client = false;
if(str_contains($data['contacts'][0]['email'], "@")) if(str_contains($data['contacts'][0]['email'], "@")) {
{
$client = ClientContact::query() $client = ClientContact::query()
->where('company_id', $this->company_gateway->company_id) ->where('company_id', $this->company_gateway->company_id)
->where('email', $data['contacts'][0]['email']) ->where('email', $data['contacts'][0]['email'])
->first()->client ?? false; ->first()->client ?? false;
} }
if(!$client) if(!$client) {
$client = $client_repo->save($data, ClientFactory::create($this->company_gateway->company_id, $this->company_gateway->user_id)); $client = $client_repo->save($data, ClientFactory::create($this->company_gateway->company_id, $this->company_gateway->user_id));
}
$this->client = $client; $this->client = $client;
if(ClientGatewayToken::query()->where('client_id', $client->id)->where('token',$data['card']['token'])->exists()) if(ClientGatewayToken::query()->where('client_id', $client->id)->where('token', $data['card']['token'])->exists()) {
continue; continue;
}
$cgt = []; $cgt = [];
$cgt['token'] = $data['card']['token']; $cgt['token'] = $data['card']['token'];

View File

@ -456,7 +456,8 @@ class SquarePaymentDriver extends BaseDriver
$api_response = $this->init() $api_response = $this->init()
->square ->square
->getCustomersApi() ->getCustomersApi()
->listCustomers(null, ->listCustomers(
null,
$limit, $limit,
'DEFAULT', 'DEFAULT',
'DESC' 'DESC'
@ -470,21 +471,22 @@ class SquarePaymentDriver extends BaseDriver
$client_repo = new ClientRepository(new ClientContactRepository()); $client_repo = new ClientRepository(new ClientContactRepository());
foreach($customers as $customer) foreach($customers as $customer) {
{
$data = (new SquareCustomerFactory())->convertToNinja($customer, $this->company_gateway->company); $data = (new SquareCustomerFactory())->convertToNinja($customer, $this->company_gateway->company);
$client = ClientContact::where('company_id', $this->company_gateway->company_id)->where('email', $customer->getEmailAddress())->first()->client ?? false; $client = ClientContact::where('company_id', $this->company_gateway->company_id)->where('email', $customer->getEmailAddress())->first()->client ?? false;
if(!$client) if(!$client) {
$client = $client_repo->save($data, ClientFactory::create($this->company_gateway->company_id, $this->company_gateway->user_id)); $client = $client_repo->save($data, ClientFactory::create($this->company_gateway->company_id, $this->company_gateway->user_id));
}
$this->client = $client; $this->client = $client;
foreach($data['cards'] as $card) { foreach($data['cards'] as $card) {
if(ClientGatewayToken::where('company_id', $this->company_gateway->company_id)->where('token', $card['token'])->exists()) if(ClientGatewayToken::where('company_id', $this->company_gateway->company_id)->where('token', $card['token'])->exists()) {
continue; continue;
}
$this->storeGatewayToken($card); $this->storeGatewayToken($card);
@ -558,8 +560,9 @@ class SquarePaymentDriver extends BaseDriver
public function findOrCreateClient() public function findOrCreateClient()
{ {
if($customer_id = $this->findClient()) if($customer_id = $this->findClient()) {
return $customer_id; return $customer_id;
}
return $this->createClient(); return $this->createClient();
} }

View File

@ -134,8 +134,9 @@ class ACH
->with('message', __('texts.payment_method_verified')); ->with('message', __('texts.payment_method_verified'));
} }
if($token->meta->next_action) if($token->meta->next_action) {
return redirect($token->meta->next_action); return redirect($token->meta->next_action);
}
} }

View File

@ -67,11 +67,13 @@ class PaymentIntentFailureWebhook implements ShouldQueue
->where('company_id', $company->id) ->where('company_id', $company->id)
->where(function ($query) use ($transaction) { ->where(function ($query) use ($transaction) {
if(isset($transaction['payment_intent'])) if(isset($transaction['payment_intent'])) {
$query->where('transaction_reference', $transaction['payment_intent']); $query->where('transaction_reference', $transaction['payment_intent']);
}
if(isset($transaction['payment_intent']) && isset($transaction['id'])) if(isset($transaction['payment_intent']) && isset($transaction['id'])) {
$query->orWhere('transaction_reference', $transaction['id']); $query->orWhere('transaction_reference', $transaction['id']);
}
if(!isset($transaction['payment_intent']) && isset($transaction['id'])) { if(!isset($transaction['payment_intent']) && isset($transaction['id'])) {
$query->where('transaction_reference', $transaction['id']); $query->where('transaction_reference', $transaction['id']);

View File

@ -100,8 +100,9 @@ class PaymentIntentWebhook implements ShouldQueue
$company_gateway = CompanyGateway::query()->find($this->company_gateway_id); $company_gateway = CompanyGateway::query()->find($this->company_gateway_id);
if(!$company_gateway) if(!$company_gateway) {
return; return;
}
$stripe_driver = $company_gateway->driver()->init(); $stripe_driver = $company_gateway->driver()->init();

View File

@ -1010,8 +1010,7 @@ class StripePaymentDriver extends BaseDriver
try { try {
$this->verifyConnect(); $this->verifyConnect();
return true; return true;
} } catch(\Exception $e) {
catch(\Exception $e) {
} }

View File

@ -122,7 +122,7 @@ class AppServiceProvider extends ServiceProvider
}); });
Mail::extend('brevo', function () { Mail::extend('brevo', function () {
return (new BrevoTransportFactory)->create( return (new BrevoTransportFactory())->create(
new Dsn( new Dsn(
'brevo+api', 'brevo+api',
'default', 'default',
@ -133,7 +133,7 @@ class AppServiceProvider extends ServiceProvider
Mailer::macro('brevo_config', function (string $brevo_key) { Mailer::macro('brevo_config', function (string $brevo_key) {
// @phpstan-ignore /** @phpstan-ignore-next-line **/ // @phpstan-ignore /** @phpstan-ignore-next-line **/
Mailer::setSymfonyTransport( Mailer::setSymfonyTransport(
(new BrevoTransportFactory)->create( (new BrevoTransportFactory())->create(
new Dsn( new Dsn(
'brevo+api', 'brevo+api',
'default', 'default',

View File

@ -129,14 +129,15 @@ class SubscriptionRepository extends BaseRepository
*/ */
private function convertV3Bundle($bundle): array private function convertV3Bundle($bundle): array
{ {
if(is_object($bundle)) if(is_object($bundle)) {
$bundle = json_decode(json_encode($bundle), 1); $bundle = json_decode(json_encode($bundle), 1);
}
$items = []; $items = [];
foreach($bundle['recurring_products'] as $key => $value) { foreach($bundle['recurring_products'] as $key => $value) {
$line_item = new \stdClass; $line_item = new \stdClass();
$line_item->product_key = $value['product']['product_key']; $line_item->product_key = $value['product']['product_key'];
$line_item->qty = (float) $value['quantity']; $line_item->qty = (float) $value['quantity'];
$line_item->unit_cost = (float) $value['product']['price']; $line_item->unit_cost = (float) $value['product']['price'];
@ -147,7 +148,7 @@ class SubscriptionRepository extends BaseRepository
foreach($bundle['recurring_products'] as $key => $value) { foreach($bundle['recurring_products'] as $key => $value) {
$line_item = new \stdClass; $line_item = new \stdClass();
$line_item->product_key = $value['product']['product_key']; $line_item->product_key = $value['product']['product_key'];
$line_item->qty = (float) $value['quantity']; $line_item->qty = (float) $value['quantity'];
$line_item->unit_cost = (float) $value['product']['price']; $line_item->unit_cost = (float) $value['product']['price'];
@ -163,8 +164,9 @@ class SubscriptionRepository extends BaseRepository
public function generateBundleLineItems($bundle, $is_recurring = false, $is_credit = false) public function generateBundleLineItems($bundle, $is_recurring = false, $is_credit = false)
{ {
if(isset($bundle->recurring_products)) if(isset($bundle->recurring_products)) {
$bundle = $this->convertV3Bundle($bundle); $bundle = $this->convertV3Bundle($bundle);
}
$multiplier = $is_credit ? -1 : 1; $multiplier = $is_credit ? -1 : 1;

View File

@ -111,8 +111,7 @@ class TaskRepository extends BaseRepository
$key_values = array_column($time_log, 0); $key_values = array_column($time_log, 0);
array_multisort($key_values, SORT_ASC, $time_log); array_multisort($key_values, SORT_ASC, $time_log);
foreach($time_log as $key => $value) foreach($time_log as $key => $value) {
{
$time_log[$key][1] = $this->roundTimeLog($time_log[$key][0], $time_log[$key][1]); $time_log[$key][1] = $this->roundTimeLog($time_log[$key][0], $time_log[$key][1]);
} }
@ -254,16 +253,19 @@ class TaskRepository extends BaseRepository
public function roundTimeLog(int $start_time, int $end_time): int public function roundTimeLog(int $start_time, int $end_time): int
{ {
if($this->task_round_to_nearest == 1 || $end_time == 0) if($this->task_round_to_nearest == 1 || $end_time == 0) {
return $end_time; return $end_time;
}
$interval = $end_time - $start_time; $interval = $end_time - $start_time;
if($this->task_round_up) if($this->task_round_up) {
return $start_time + (int)ceil($interval / $this->task_round_to_nearest) * $this->task_round_to_nearest; return $start_time + (int)ceil($interval / $this->task_round_to_nearest) * $this->task_round_to_nearest;
}
if($interval <= $this->task_round_to_nearest) if($interval <= $this->task_round_to_nearest) {
return $start_time; return $start_time;
}
return $start_time + (int)floor($interval / $this->task_round_to_nearest) * $this->task_round_to_nearest; return $start_time + (int)floor($interval / $this->task_round_to_nearest) * $this->task_round_to_nearest;

View File

@ -137,10 +137,12 @@ class FatturaPA extends AbstractService
$datiAnagrafici->setRegimeFiscale("RF01"); //swap this out with the custom settings. $datiAnagrafici->setRegimeFiscale("RF01"); //swap this out with the custom settings.
$cedentePrestatore->setDatiAnagrafici($datiAnagrafici); $cedentePrestatore->setDatiAnagrafici($datiAnagrafici);
$sede = new Sede(Indirizzo: $this->invoice->company->settings->address1, $sede = new Sede(
Indirizzo: $this->invoice->company->settings->address1,
CAP: (int)$this->invoice->company->settings->postal_code, CAP: (int)$this->invoice->company->settings->postal_code,
Comune: $this->invoice->company->settings->city, Comune: $this->invoice->company->settings->city,
Provincia: $this->invoice->company->settings->state); Provincia: $this->invoice->company->settings->state
);
$cedentePrestatore->setSede($sede); $cedentePrestatore->setSede($sede);
$fatturaHeader->setCedentePrestatore($cedentePrestatore); $fatturaHeader->setCedentePrestatore($cedentePrestatore);
@ -155,10 +157,12 @@ class FatturaPA extends AbstractService
$anagrafica = new Anagrafica(Denominazione: $this->invoice->client->present()->name()); $anagrafica = new Anagrafica(Denominazione: $this->invoice->client->present()->name());
$datiAnagrafici->setAnagrafica($anagrafica); $datiAnagrafici->setAnagrafica($anagrafica);
$sede = new Sede(Indirizzo: $this->invoice->client->address1, $sede = new Sede(
Indirizzo: $this->invoice->client->address1,
CAP: (int)$this->invoice->client->postal_code, CAP: (int)$this->invoice->client->postal_code,
Comune: $this->invoice->client->city, Comune: $this->invoice->client->city,
Provincia: $this->invoice->client->state); Provincia: $this->invoice->client->state
);
$cessionarioCommittente = new CessionarioCommittente($datiAnagrafici, $sede); $cessionarioCommittente = new CessionarioCommittente($datiAnagrafici, $sede);
@ -228,8 +232,7 @@ $datiGenerali->setDatiGeneraliDocumento($datiGeneraliDocument);
$datiBeniServizi = new DatiBeniServizi(); $datiBeniServizi = new DatiBeniServizi();
$tax_rate_level = 0; $tax_rate_level = 0;
//line items //line items
foreach ($this->invoice->line_items as $key => $item) foreach ($this->invoice->line_items as $key => $item) {
{
$numero = $key + 1; $numero = $key + 1;
$dettaglioLinee = new DettaglioLinee( $dettaglioLinee = new DettaglioLinee(

View File

@ -102,7 +102,7 @@ class FatturaPANew extends AbstractService
{ {
$this->CedentePrestatore->DatiAnagrafici = $this->DatiAnagrafici; $this->CedentePrestatore->DatiAnagrafici = $this->DatiAnagrafici;
$sede = new Sede; $sede = new Sede();
$sede->Indirizzo = $this->invoice->company->settings->address1; $sede->Indirizzo = $this->invoice->company->settings->address1;
$sede->CAP = (int)$this->invoice->company->settings->postal_code; $sede->CAP = (int)$this->invoice->company->settings->postal_code;
$sede->Comune = $this->invoice->company->settings->city; $sede->Comune = $this->invoice->company->settings->city;
@ -132,20 +132,20 @@ class FatturaPANew extends AbstractService
$anagrafica->Denominazione = $this->invoice->client->present()->name(); $anagrafica->Denominazione = $this->invoice->client->present()->name();
$datiAnagrafici->Anagrafica = $anagrafica; $datiAnagrafici->Anagrafica = $anagrafica;
$idFiscale = new IdFiscaleIVA; $idFiscale = new IdFiscaleIVA();
$idFiscale->IdCodice = $this->invoice->client->vat_number; $idFiscale->IdCodice = $this->invoice->client->vat_number;
$idFiscale->IdPaese = $this->invoice->client->country->iso_3166_2; $idFiscale->IdPaese = $this->invoice->client->country->iso_3166_2;
$datiAnagrafici->IdFiscaleIVA = $idFiscale; $datiAnagrafici->IdFiscaleIVA = $idFiscale;
$sede = new Sede; $sede = new Sede();
$sede->Indirizzo = $this->invoice->client->address1; $sede->Indirizzo = $this->invoice->client->address1;
$sede->CAP = (int)$this->invoice->client->postal_code; $sede->CAP = (int)$this->invoice->client->postal_code;
$sede->Comune = $this->invoice->client->city; $sede->Comune = $this->invoice->client->city;
$sede->Provincia = $this->invoice->client->state; $sede->Provincia = $this->invoice->client->state;
$sede->Nazione = $this->invoice->client->country->iso_3166_2; $sede->Nazione = $this->invoice->client->country->iso_3166_2;
$cessionarioCommittente = new CessionarioCommittente; $cessionarioCommittente = new CessionarioCommittente();
$cessionarioCommittente->DatiAnagrafici = $datiAnagrafici; $cessionarioCommittente->DatiAnagrafici = $datiAnagrafici;
$cessionarioCommittente->Sede = $sede; $cessionarioCommittente->Sede = $sede;
@ -199,7 +199,7 @@ class FatturaPANew extends AbstractService
$this->DettaglioPagamento->DataScadenzaPagamento = new \DateTime($this->invoice->due_date ?? $this->invoice->date); $this->DettaglioPagamento->DataScadenzaPagamento = new \DateTime($this->invoice->due_date ?? $this->invoice->date);
$this->DettaglioPagamento->ImportoPagamento = (string) sprintf('%0.2f', $this->invoice->balance); $this->DettaglioPagamento->ImportoPagamento = (string) sprintf('%0.2f', $this->invoice->balance);
$DatiPagamento = new DatiPagamento; $DatiPagamento = new DatiPagamento();
$DatiPagamento->CondizioniPagamento = "TP02"; $DatiPagamento->CondizioniPagamento = "TP02";
$DatiPagamento->DettaglioPagamento[] = $this->DettaglioPagamento; $DatiPagamento->DettaglioPagamento[] = $this->DettaglioPagamento;
@ -219,7 +219,7 @@ class FatturaPANew extends AbstractService
foreach ($this->invoice->line_items as $key => $item) { foreach ($this->invoice->line_items as $key => $item) {
$numero = $key + 1; $numero = $key + 1;
$dettaglioLinee = new DettaglioLinee; $dettaglioLinee = new DettaglioLinee();
$dettaglioLinee->NumeroLinea = "{$numero}"; $dettaglioLinee->NumeroLinea = "{$numero}";
$dettaglioLinee->Descrizione = $item->notes ?? 'Descrizione'; $dettaglioLinee->Descrizione = $item->notes ?? 'Descrizione';
$dettaglioLinee->Quantita = sprintf('%0.2f', $item->quantity); $dettaglioLinee->Quantita = sprintf('%0.2f', $item->quantity);
@ -244,7 +244,7 @@ class FatturaPANew extends AbstractService
$subtotal = sprintf('%0.2f', $calc->getSubTotal()); $subtotal = sprintf('%0.2f', $calc->getSubTotal());
$taxes = sprintf('%0.2f', $calc->getTotalTaxes()); $taxes = sprintf('%0.2f', $calc->getTotalTaxes());
$datiRiepilogo = new DatiRiepilogo; $datiRiepilogo = new DatiRiepilogo();
$datiRiepilogo->AliquotaIVA = "{$tax_rate_level}"; $datiRiepilogo->AliquotaIVA = "{$tax_rate_level}";
$datiRiepilogo->ImponibileImporto = "{$subtotal}"; $datiRiepilogo->ImponibileImporto = "{$subtotal}";
$datiRiepilogo->Imposta = "{$taxes}"; $datiRiepilogo->Imposta = "{$taxes}";
@ -269,18 +269,18 @@ class FatturaPANew extends AbstractService
private function init(): self private function init(): self
{ {
$this->FatturaElettronica = new FatturaElettronica; $this->FatturaElettronica = new FatturaElettronica();
$this->FatturaElettronicaBody = new FatturaElettronicaBody; $this->FatturaElettronicaBody = new FatturaElettronicaBody();
$this->FatturaElettronicaHeader = new FatturaElettronicaHeader; $this->FatturaElettronicaHeader = new FatturaElettronicaHeader();
$this->DatiTrasmissione = new DatiTrasmissione; $this->DatiTrasmissione = new DatiTrasmissione();
$this->IdTrasmittente = new IdTrasmittente; $this->IdTrasmittente = new IdTrasmittente();
$this->CedentePrestatore = new CedentePrestatore; $this->CedentePrestatore = new CedentePrestatore();
$this->DatiAnagrafici = new DatiAnagrafici; $this->DatiAnagrafici = new DatiAnagrafici();
$this->IdFiscaleIVA = new IdFiscaleIVA; $this->IdFiscaleIVA = new IdFiscaleIVA();
$this->Anagrafica = new Anagrafica; $this->Anagrafica = new Anagrafica();
$this->DatiGeneraliDocumento = new DatiGeneraliDocumento; $this->DatiGeneraliDocumento = new DatiGeneraliDocumento();
$this->DatiGenerali = new DatiGenerali; $this->DatiGenerali = new DatiGenerali();
$this->DettaglioPagamento = new DettaglioPagamento; $this->DettaglioPagamento = new DettaglioPagamento();
return $this; return $this;

View File

@ -43,7 +43,6 @@ use InvoiceNinja\EInvoice\Models\Peppol\TaxTotal as PeppolTaxTotal;
class Peppol extends AbstractService class Peppol extends AbstractService
{ {
private array $InvoiceTypeCodes = [ private array $InvoiceTypeCodes = [
"380" => "Commercial invoice", "380" => "Commercial invoice",
"381" => "Credit note", "381" => "Credit note",
@ -68,7 +67,7 @@ class Peppol extends AbstractService
*/ */
public function __construct(public Invoice $invoice) public function __construct(public Invoice $invoice)
{ {
$this->p_invoice = new \InvoiceNinja\EInvoice\Models\Peppol\Invoice; $this->p_invoice = new \InvoiceNinja\EInvoice\Models\Peppol\Invoice();
$this->calc = $this->invoice->calc(); $this->calc = $this->invoice->calc();
} }
@ -105,24 +104,24 @@ class Peppol extends AbstractService
{ {
$taxable = $this->getTaxable(); $taxable = $this->getTaxable();
$lmt = new LegalMonetaryTotal; $lmt = new LegalMonetaryTotal();
$lea = new LineExtensionAmount; $lea = new LineExtensionAmount();
$lea->currencyID = $this->invoice->client->currency()->code; $lea->currencyID = $this->invoice->client->currency()->code;
$lea->amount = $taxable; $lea->amount = $taxable;
$lmt->LineExtensionAmount = $lea; $lmt->LineExtensionAmount = $lea;
$tea = new TaxExclusiveAmount; $tea = new TaxExclusiveAmount();
$tea->currencyID = $this->invoice->client->currency()->code; $tea->currencyID = $this->invoice->client->currency()->code;
$tea->amount = $taxable; $tea->amount = $taxable;
$lmt->TaxExclusiveAmount = $tea; $lmt->TaxExclusiveAmount = $tea;
$tia = new TaxInclusiveAmount; $tia = new TaxInclusiveAmount();
$tia->currencyID = $this->invoice->client->currency()->code; $tia->currencyID = $this->invoice->client->currency()->code;
$tia->amount = $this->invoice->amount; $tia->amount = $this->invoice->amount;
$lmt->TaxInclusiveAmount = $tia; $lmt->TaxInclusiveAmount = $tia;
$pa = new PayableAmount; $pa = new PayableAmount();
$pa->currencyID = $this->invoice->client->currency()->code; $pa->currencyID = $this->invoice->client->currency()->code;
$pa->amount = $this->invoice->amount; $pa->amount = $this->invoice->amount;
$lmt->PayableAmount = $pa; $lmt->PayableAmount = $pa;
@ -136,8 +135,7 @@ class Peppol extends AbstractService
$type_id = $this->invoice->line_items[0]->type_id; $type_id = $this->invoice->line_items[0]->type_id;
if( strlen($this->invoice->tax_name1 ?? '') > 1) if(strlen($this->invoice->tax_name1 ?? '') > 1) {
{
$tax_amount = new TaxAmount(); $tax_amount = new TaxAmount();
$tax_amount->currencyID = $this->invoice->client->currency()->code; $tax_amount->currencyID = $this->invoice->client->currency()->code;
@ -162,7 +160,7 @@ $tax_subtotal->TaxableAmount = $taxable_amount;
$tc->TaxScheme = $ts; $tc->TaxScheme = $ts;
$tax_subtotal->TaxCategory = $tc; $tax_subtotal->TaxCategory = $tc;
$tax_total = new TaxTotal; $tax_total = new TaxTotal();
$tax_total->TaxAmount = $tax_amount; $tax_total->TaxAmount = $tax_amount;
$tax_total->TaxSubtotal = $tax_subtotal; $tax_total->TaxSubtotal = $tax_subtotal;
@ -242,18 +240,17 @@ $tax_subtotal->TaxableAmount = $taxable_amount;
{ {
$lines = []; $lines = [];
foreach($this->invoice->line_items as $key => $item) foreach($this->invoice->line_items as $key => $item) {
{
$_item = new Item; $_item = new Item();
$_item->Name = $item->product_key; $_item->Name = $item->product_key;
$_item->Description = $item->notes; $_item->Description = $item->notes;
$line = new InvoiceLine; $line = new InvoiceLine();
$line->ID = $key + 1; $line->ID = $key + 1;
$line->InvoicedQuantity = $item->quantity; $line->InvoicedQuantity = $item->quantity;
$lea = new LineExtensionAmount; $lea = new LineExtensionAmount();
$lea->currencyID = $this->invoice->client->currency()->code; $lea->currencyID = $this->invoice->client->currency()->code;
$lea->amount = $item->line_total; $lea->amount = $item->line_total;
$line->LineExtensionAmount = $lea; $line->LineExtensionAmount = $lea;
@ -265,11 +262,12 @@ $tax_subtotal->TaxableAmount = $taxable_amount;
// $tt->TaxAmount = $ta; // $tt->TaxAmount = $ta;
$item_taxes = $this->getItemTaxes($item); $item_taxes = $this->getItemTaxes($item);
if(count($item_taxes) > 0) if(count($item_taxes) > 0) {
$line->TaxTotal = $item_taxes; $line->TaxTotal = $item_taxes;
}
$price = new Price; $price = new Price();
$pa = new PriceAmount; $pa = new PriceAmount();
$pa->currencyID = $this->invoice->client->currency()->code; $pa->currencyID = $this->invoice->client->currency()->code;
$pa->amount = $this->costWithDiscount($item); $pa->amount = $this->costWithDiscount($item);
$price->PriceAmount = $pa; $price->PriceAmount = $pa;
@ -301,23 +299,22 @@ $tax_subtotal->TaxableAmount = $taxable_amount;
{ {
$item_taxes = []; $item_taxes = [];
if(strlen($item->tax_name1 ?? '') > 1) if(strlen($item->tax_name1 ?? '') > 1) {
{
$tax_amount = new TaxAmount; $tax_amount = new TaxAmount();
$tax_amount->currencyID = $this->invoice->client->currency()->code; $tax_amount->currencyID = $this->invoice->client->currency()->code;
$tax_amount->amount = round(($item->line_total * (1 / $item->tax_rate1)), 2); $tax_amount->amount = round(($item->line_total * (1 / $item->tax_rate1)), 2);
$tax_subtotal = new TaxSubtotal; $tax_subtotal = new TaxSubtotal();
$tax_subtotal->TaxAmount = $tax_amount; $tax_subtotal->TaxAmount = $tax_amount;
$taxable_amount = new TaxableAmount; $taxable_amount = new TaxableAmount();
$taxable_amount->currencyID = $this->invoice->client->currency()->code; $taxable_amount->currencyID = $this->invoice->client->currency()->code;
$taxable_amount->amount = $item->line_total; $taxable_amount->amount = $item->line_total;
$tax_subtotal->TaxableAmount = $taxable_amount; $tax_subtotal->TaxableAmount = $taxable_amount;
$tc = new TaxCategory; $tc = new TaxCategory();
$tc->ID = $item->type_id == '2' ? 'HUR' : 'C62'; $tc->ID = $item->type_id == '2' ? 'HUR' : 'C62';
$tc->Percent = $item->tax_rate1; $tc->Percent = $item->tax_rate1;
$ts = new PeppolTaxScheme; $ts = new PeppolTaxScheme();
$ts->ID = $item->tax_name1; $ts->ID = $item->tax_name1;
$tc->TaxScheme = $ts; $tc->TaxScheme = $ts;
$tax_subtotal->TaxCategory = $tc; $tax_subtotal->TaxCategory = $tc;
@ -404,7 +401,7 @@ $item_taxes[] = $tax_total;
$asp = new AccountingSupplierParty(); $asp = new AccountingSupplierParty();
$party = new Party(); $party = new Party();
$party_name = new PartyName; $party_name = new PartyName();
$party_name->Name = $this->invoice->company->present()->name(); $party_name->Name = $this->invoice->company->present()->name();
$party->PartyName[] = $party_name; $party->PartyName[] = $party_name;

View File

@ -44,7 +44,6 @@ use App\Models\Product;
*/ */
class RoEInvoice extends AbstractService class RoEInvoice extends AbstractService
{ {
private array $countrySubEntity = [ private array $countrySubEntity = [
'RO-AB' => 'Alba', 'RO-AB' => 'Alba',
'RO-AG' => 'Argeș', 'RO-AG' => 'Argeș',

View File

@ -125,9 +125,9 @@ class ZugferdEDokument extends AbstractService
//Payment Means - Switcher //Payment Means - Switcher
if($company->settings->custom_value1 == '42') { if($company->settings->custom_value1 == '42') {
$this->xdocument->addDocumentPaymentMean(typecode: 42, payeeIban: $company->settings->custom_value2, payeeAccountName: $company->settings->custom_value4, payeeBic: $company->settings->custom_value3); $this->xdocument->addDocumentPaymentMean(typecode: 42, payeeIban: $company->settings->custom_value2, payeeAccountName: $company->settings->custom_value4, payeeBic: $company->settings->custom_value3);
} } else {
else
$this->xdocument->addDocumentPaymentMean(68, ctrans("texts.xinvoice_online_payment")); $this->xdocument->addDocumentPaymentMean(68, ctrans("texts.xinvoice_online_payment"));
}
if (str_contains($company->getSetting('vat_number'), "/")) { if (str_contains($company->getSetting('vat_number'), "/")) {
$this->xdocument->addDocumentSellerTaxRegistration("FC", $company->getSetting('vat_number')); $this->xdocument->addDocumentSellerTaxRegistration("FC", $company->getSetting('vat_number'));

View File

@ -250,9 +250,10 @@ class Email implements ShouldQueue
private function incrementEmailCounter(): void private function incrementEmailCounter(): void
{ {
if(in_array($this->mailer, ['default','mailgun','postmark'])) if(in_array($this->mailer, ['default','mailgun','postmark'])) {
Cache::increment("email_quota".$this->company->account->key); Cache::increment("email_quota".$this->company->account->key);
} }
}
/** /**
* Attempts to send the email * Attempts to send the email
@ -302,8 +303,7 @@ class Email implements ShouldQueue
$this->cleanUpMailers(); $this->cleanUpMailers();
$this->logMailError($e->getMessage(), $this->company->clients()->first()); $this->logMailError($e->getMessage(), $this->company->clients()->first());
return; return;
} } catch(\Google\Service\Exception $e) {
catch(\Google\Service\Exception $e){
if ($e->getCode() == '429') { if ($e->getCode() == '429') {
@ -314,9 +314,7 @@ class Email implements ShouldQueue
$message = null; $message = null;
} }
} } catch (\Exception | \RuntimeException $e) {
catch (\Exception | \RuntimeException $e) {
nlog("Mailer failed with {$e->getMessage()}"); nlog("Mailer failed with {$e->getMessage()}");
$message = $e->getMessage(); $message = $e->getMessage();
@ -949,8 +947,7 @@ class Email implements ShouldQueue
'refresh_token' => $user->oauth_user_refresh_token 'refresh_token' => $user->oauth_user_refresh_token
], ],
])->getBody()->getContents()); ])->getBody()->getContents());
} } catch(\Exception $e) {
catch(\Exception $e){
nlog("Problem getting new Microsoft token for User: {$user->email}"); nlog("Problem getting new Microsoft token for User: {$user->email}");
} }

View File

@ -488,7 +488,8 @@ class InvoiceService
/*When a reminder is sent we want to touch the dates they were sent*/ /*When a reminder is sent we want to touch the dates they were sent*/
public function touchReminder(string $reminder_template) public function touchReminder(string $reminder_template)
{ nrlog(now()->format('Y-m-d h:i:s') . " INV #{$this->invoice->number} : Touching Reminder => {$reminder_template}"); {
nrlog(now()->format('Y-m-d h:i:s') . " INV #{$this->invoice->number} : Touching Reminder => {$reminder_template}");
switch ($reminder_template) { switch ($reminder_template) {
case 'reminder1': case 'reminder1':
$this->invoice->reminder1_sent = now(); $this->invoice->reminder1_sent = now();

View File

@ -60,9 +60,9 @@ class PurchaseOrderExpense
if($this->purchase_order->project_id) { if($this->purchase_order->project_id) {
$expense->project_id = $this->purchase_order->project_id; $expense->project_id = $this->purchase_order->project_id;
$expense->client_id = $this->purchase_order->project->client_id; $expense->client_id = $this->purchase_order->project->client_id;
} } elseif($this->purchase_order->client_id) {
elseif($this->purchase_order->client_id)
$expense->client_id = $this->purchase_order->client_id; $expense->client_id = $this->purchase_order->client_id;
}
$expense->saveQuietly(); $expense->saveQuietly();
event('eloquent.created: App\Models\Expense', $expense); event('eloquent.created: App\Models\Expense', $expense);

View File

@ -75,8 +75,9 @@ class ConvertQuote
$quote->status_id = Quote::STATUS_CONVERTED; $quote->status_id = Quote::STATUS_CONVERTED;
$quote->save(); $quote->save();
if($quote->documents()->count() > 0) if($quote->documents()->count() > 0) {
CopyDocs::dispatch($quote->documents()->pluck('id'), $invoice, $invoice->company->db); CopyDocs::dispatch($quote->documents()->pluck('id'), $invoice, $invoice->company->db);
}
return $invoice; return $invoice;
} }

View File

@ -288,8 +288,9 @@ class ProfitLoss
if ($pivot->paymentable_type == 'invoices') { if ($pivot->paymentable_type == 'invoices') {
$invoice = Invoice::query()->withTrashed()->find($pivot->paymentable_id); $invoice = Invoice::query()->withTrashed()->find($pivot->paymentable_id);
if(!$invoice) if(!$invoice) {
continue; continue;
}
$pivot_diff = $pivot->amount - $pivot->refunded; $pivot_diff = $pivot->amount - $pivot->refunded;
$amount_payment_paid += $pivot_diff; $amount_payment_paid += $pivot_diff;

View File

@ -27,7 +27,9 @@ class SubscriptionCalculator
{ {
use MakesHash; use MakesHash;
public function __construct(public Subscription $subscription){} public function __construct(public Subscription $subscription)
{
}
/** /**
* BuildPurchaseInvoice * BuildPurchaseInvoice
@ -75,8 +77,9 @@ class SubscriptionCalculator
foreach($recurring as $item) { foreach($recurring as $item) {
if($item['quantity'] < 1) if($item['quantity'] < 1) {
continue; continue;
}
$line_item = new InvoiceItem(); $line_item = new InvoiceItem();
$line_item->product_key = $item['product']['product_key']; $line_item->product_key = $item['product']['product_key'];
@ -191,7 +194,9 @@ class SubscriptionCalculator
return $this->subscription->price; return $this->subscription->price;
} }
public function executeUpgradePlan() {} public function executeUpgradePlan()
{
}
private function getRefundInvoice(Invoice $invoice) private function getRefundInvoice(Invoice $invoice)
{ {

View File

@ -145,12 +145,13 @@ class TemplateAction implements ShouldQueue
} }
if($first_entity instanceof Client) if($first_entity instanceof Client) {
$currency_code = $first_entity->currency()->code; $currency_code = $first_entity->currency()->code;
elseif($first_entity->client) } elseif($first_entity->client) {
$currency_code = $first_entity->client->currency()->code; $currency_code = $first_entity->client->currency()->code;
else } else {
$currency_code = $this->company->currency()->code; $currency_code = $this->company->currency()->code;
}
if($result->count() <= 1) { if($result->count() <= 1) {
$data[$key] = collect($result); $data[$key] = collect($result);

View File

@ -721,8 +721,9 @@ class TemplateService
private function getPaymentRefundActivity(Payment $payment): array private function getPaymentRefundActivity(Payment $payment): array
{ {
if(!is_array($payment->refund_meta)) if(!is_array($payment->refund_meta)) {
return []; return [];
}
return collect($payment->refund_meta) return collect($payment->refund_meta)
->map(function ($refund) use ($payment) { ->map(function ($refund) use ($payment) {

View File

@ -47,8 +47,9 @@ class ProjectTransformer extends EntityTransformer
{ {
$transformer = new DocumentTransformer($this->serializer); $transformer = new DocumentTransformer($this->serializer);
if($project->documents) if($project->documents) {
return $this->includeCollection($project->documents, $transformer, Document::class); return $this->includeCollection($project->documents, $transformer, Document::class);
}
return null; return null;
} }

View File

@ -111,8 +111,9 @@ class TaskTransformer extends EntityTransformer
{ {
$transformer = new ProjectTransformer($this->serializer); $transformer = new ProjectTransformer($this->serializer);
if ($task->project) if ($task->project) {
return $this->includeItem($task->project, $transformer, Project::class); return $this->includeItem($task->project, $transformer, Project::class);
}
return null; return null;
} }

View File

@ -111,8 +111,9 @@ class UserTransformer extends EntityTransformer
$cu = $user->company_users()->where('company_id', $user->company_id)->first(); $cu = $user->company_users()->where('company_id', $user->company_id)->first();
if(!$cu) if(!$cu) {
return null; return null;
}
return $this->includeItem($cu, $transformer, CompanyUser::class); return $this->includeItem($cu, $transformer, CompanyUser::class);
} }

View File

@ -561,10 +561,11 @@ class HtmlEngine
$data['$spc_qr_code'] = ['value' => $this->company->present()->getSpcQrCode($this->client->currency()->code, $this->entity->number, $this->entity->balance, $this->helpers->formatCustomFieldValue($this->company->custom_fields, 'company1', $this->settings->custom_value1, $this->client)), 'label' => '']; $data['$spc_qr_code'] = ['value' => $this->company->present()->getSpcQrCode($this->client->currency()->code, $this->entity->number, $this->entity->balance, $this->helpers->formatCustomFieldValue($this->company->custom_fields, 'company1', $this->settings->custom_value1, $this->client)), 'label' => ''];
if(Ninja::isHosted()) if(Ninja::isHosted()) {
$logo = $this->company->present()->logo($this->settings); $logo = $this->company->present()->logo($this->settings);
else } else {
$logo = $this->company->present()->logo_base64($this->settings); $logo = $this->company->present()->logo_base64($this->settings);
}
$logo_url = $this->company->present()->logo($this->settings); $logo_url = $this->company->present()->logo($this->settings);
@ -767,10 +768,12 @@ class HtmlEngine
return $data; return $data;
} }
private function getPaymentMeta(\App\Models\Payment $payment) { private function getPaymentMeta(\App\Models\Payment $payment)
{
if(!is_array($payment->refund_meta)) if(!is_array($payment->refund_meta)) {
return ''; return '';
}
return return
collect($payment->refund_meta) collect($payment->refund_meta)

View File

@ -89,8 +89,9 @@ class Number
public static function parseFloat($value) public static function parseFloat($value)
{ {
if(!$value) if(!$value) {
return 0; return 0;
}
//remove everything except for numbers, decimals, commas and hyphens //remove everything except for numbers, decimals, commas and hyphens
$value = preg_replace('/[^0-9.,-]+/', '', $value); $value = preg_replace('/[^0-9.,-]+/', '', $value);
@ -98,8 +99,9 @@ class Number
$decimal = strpos($value, '.'); $decimal = strpos($value, '.');
$comma = strpos($value, ','); $comma = strpos($value, ',');
if($comma === false) //no comma must be a decimal number already if($comma === false) { //no comma must be a decimal number already
return (float) $value; return (float) $value;
}
if(!$decimal && substr($value, -3, 1) != ",") { if(!$decimal && substr($value, -3, 1) != ",") {
$value = $value.".00"; $value = $value.".00";
@ -130,13 +132,15 @@ class Number
public static function parseFloatXX($value) public static function parseFloatXX($value)
{ {
if(!$value) if(!$value) {
return 0; return 0;
}
$multiplier = false; $multiplier = false;
if(substr($value, 0,1) == '-') if(substr($value, 0, 1) == '-') {
$multiplier = -1; $multiplier = -1;
}
$s = str_replace(',', '.', $value); $s = str_replace(',', '.', $value);
@ -148,8 +152,9 @@ class Number
$s = str_replace('.', '', substr($s, 0, -3)).substr($s, -3); $s = str_replace('.', '', substr($s, 0, -3)).substr($s, -3);
if($multiplier) if($multiplier) {
$s = floatval($s) * -1; $s = floatval($s) * -1;
}
return (float) $s; return (float) $s;
} }

View File

@ -106,8 +106,7 @@ trait CleanLineItems
{ {
$total = 0; $total = 0;
foreach($items as $item) foreach($items as $item) {
{
$total += ($item['cost'] * $item['quantity']); $total += ($item['cost'] * $item['quantity']);
} }

View File

@ -48,8 +48,9 @@ trait SubscriptionHooker
RequestOptions::JSON => ['body' => $body], RequestOptions::ALLOW_REDIRECTS => false, RequestOptions::JSON => ['body' => $body], RequestOptions::ALLOW_REDIRECTS => false,
]); ]);
if($response_body = json_decode($response->getBody(), true)) if($response_body = json_decode($response->getBody(), true)) {
return array_merge($body, $response_body); return array_merge($body, $response_body);
}
return array_merge($body, ['message' => 'Success', 'status_code' => 200]); return array_merge($body, ['message' => 'Success', 'status_code' => 200]);