diff --git a/app/Console/Commands/CheckData.php b/app/Console/Commands/CheckData.php index 3e4773e580c3..5ffb915c978a 100644 --- a/app/Console/Commands/CheckData.php +++ b/app/Console/Commands/CheckData.php @@ -172,18 +172,18 @@ class CheckData extends Command CompanyUser::query()->cursor()->each(function ($cu) { if (CompanyToken::where('user_id', $cu->user_id)->where('company_id', $cu->company_id)->where('is_system', 1)->doesntExist()) { - + if ($cu->company && $cu->user) { $this->logMessage("Creating missing company token for user # {$cu->user_id} for company id # {$cu->company_id}"); (new CreateCompanyToken($cu->company, $cu->user, 'System'))->handle(); - } - + } + if (!$cu->user) { $this->logMessage("No user found for company user - removing company user"); $cu->forceDelete(); } - + } }); } @@ -477,14 +477,13 @@ class CheckData extends Command } } else { $this->logMessage("No contact present, so cannot add invitation for {$entity_key} - {$entity->id}"); - - try{ + + try { $entity->service()->createInvitations()->save(); - } - catch(\Exception $e){ + } catch(\Exception $e) { } - + } try { @@ -949,12 +948,12 @@ class CheckData extends Command }); - Company::whereDoesntHave('company_users', function ($query){ - $query->where('is_owner', 1); + Company::whereDoesntHave('company_users', function ($query) { + $query->where('is_owner', 1); }) ->cursor() ->when(Ninja::isHosted()) - ->each(function ($c){ + ->each(function ($c) { $this->logMessage("Orphan Account # {$c->account_id}"); @@ -963,8 +962,8 @@ class CheckData extends Command CompanyUser::whereDoesntHave('tokens') ->cursor() ->when(Ninja::isHosted()) - ->each(function ($cu){ - + ->each(function ($cu) { + $this->logMessage("Missing tokens for Company User # {$cu->id}"); }); diff --git a/app/Console/Commands/CreateSingleAccount.php b/app/Console/Commands/CreateSingleAccount.php index d812ea5db63e..f2769de649a1 100644 --- a/app/Console/Commands/CreateSingleAccount.php +++ b/app/Console/Commands/CreateSingleAccount.php @@ -1016,7 +1016,7 @@ class CreateSingleAccount extends Command $cg->fees_and_limits = $fees_and_limits; $cg->save(); } - + if (config('ninja.testvars.eway') && ($this->gateway == 'all' || $this->gateway == 'eway')) { $cg = new CompanyGateway(); $cg->company_id = $company->id; @@ -1038,12 +1038,12 @@ class CreateSingleAccount extends Command $cg->save(); } - + if (config('ninja.testvars.gocardless') && ($this->gateway == 'all' || $this->gateway == 'gocardless')) { $c_settings = ClientSettings::defaults(); $c_settings->currency_id = '2'; - + $client = Client::factory()->create([ 'user_id' => $user->id, 'company_id' => $company->id, diff --git a/app/Console/Commands/ReactBuilder.php b/app/Console/Commands/ReactBuilder.php index 1a0a3b6a2458..d4c5b7533c7f 100644 --- a/app/Console/Commands/ReactBuilder.php +++ b/app/Console/Commands/ReactBuilder.php @@ -48,37 +48,37 @@ class ReactBuilder extends Command { if($this->option('type') == 'local') { - - $includes = ''; - $directoryIterator = false; + $includes = ''; - try { - $directoryIterator = new \RecursiveDirectoryIterator(public_path('react/v'.config('ninja.app_version').'/'), \RecursiveDirectoryIterator::SKIP_DOTS); - } catch (\Exception $e) { - $this->error('React files not found'); - return; - } + $directoryIterator = false; - foreach (new \RecursiveIteratorIterator($directoryIterator) as $file) { - if ($file->getExtension() == 'js') { - if (str_contains($file->getFileName(), 'index-')) { - $includes .= ''."\n"; - } else { - $includes .= ''."\n"; + try { + $directoryIterator = new \RecursiveDirectoryIterator(public_path('react/v'.config('ninja.app_version').'/'), \RecursiveDirectoryIterator::SKIP_DOTS); + } catch (\Exception $e) { + $this->error('React files not found'); + return; + } + + foreach (new \RecursiveIteratorIterator($directoryIterator) as $file) { + if ($file->getExtension() == 'js') { + if (str_contains($file->getFileName(), 'index-')) { + $includes .= ''."\n"; + } else { + $includes .= ''."\n"; + } + } + + if (str_contains($file->getFileName(), '.css')) { + $includes .= ''."\n"; } } - if (str_contains($file->getFileName(), '.css')) { - $includes .= ''."\n"; - } - } - - file_put_contents(resource_path('views/react/head.blade.php'), $includes); + file_put_contents(resource_path('views/react/head.blade.php'), $includes); } - + } } diff --git a/app/DataMapper/Analytics/DbQuery.php b/app/DataMapper/Analytics/DbQuery.php index 833aa9707e85..5b8dfeea9f7e 100644 --- a/app/DataMapper/Analytics/DbQuery.php +++ b/app/DataMapper/Analytics/DbQuery.php @@ -55,7 +55,7 @@ class DbQuery extends GenericMixedMetric public $string_metric8 = 'client_version'; public $string_metric9 = 'platform'; - + /** * The counter * set to 1. diff --git a/app/DataMapper/InvoiceItem.php b/app/DataMapper/InvoiceItem.php index de1b3338c752..9d217efb64c2 100644 --- a/app/DataMapper/InvoiceItem.php +++ b/app/DataMapper/InvoiceItem.php @@ -64,9 +64,9 @@ class InvoiceItem public $task_id = ''; public $expense_id = ''; - + public $unit_code = 'C62'; - + public static $casts = [ 'task_id' => 'string', 'expense_id' => 'string', diff --git a/app/DataMapper/Sources/PayPalBalanceAffecting.php b/app/DataMapper/Sources/PayPalBalanceAffecting.php index 2e547b706fd5..549423051026 100644 --- a/app/DataMapper/Sources/PayPalBalanceAffecting.php +++ b/app/DataMapper/Sources/PayPalBalanceAffecting.php @@ -15,7 +15,6 @@ use App\DataMapper\InvoiceItem; class PayPalBalanceAffecting { - private array $key_map = [ 'Date' => 'date', 'Time' => 'time', @@ -105,8 +104,10 @@ class PayPalBalanceAffecting public $discount; public $creditTransactionalFee; public $originalInvoiceId; - - public function __construct(private array $import_row){} + + public function __construct(private array $import_row) + { + } public function run(): self { @@ -116,11 +117,11 @@ class PayPalBalanceAffecting $prop = $this->key_map[$key] ?? false; - if($prop){ + if($prop) { echo "Setting {$prop} to {$value}".PHP_EOL; $this->{$prop} = $value; - + } } @@ -130,7 +131,7 @@ class PayPalBalanceAffecting private function cleanUp(): self { - foreach($this->key_map as $value){ + foreach($this->key_map as $value) { echo "Setting {$value} to null".PHP_EOL; $this->{$value} = null; } @@ -154,7 +155,7 @@ class PayPalBalanceAffecting public function getInvoice(): array { - $item = new InvoiceItem; + $item = new InvoiceItem(); $item->cost = $this->gross ?? 0; $item->product_key = $this->itemId ?? ''; $item->notes = $this->subject ?? $this->itemDetails; @@ -162,7 +163,7 @@ class PayPalBalanceAffecting return [ 'number' => trim($this->invoiceNumber ?? $this->transactionId), - 'date' => str_replace('/','-', $this->date ?? ''), + 'date' => str_replace('/', '-', $this->date ?? ''), 'line_items' => [$item], 'name' => $this->name ?? '', 'email' => $this->fromEmailAddress ?? '', @@ -174,12 +175,10 @@ class PayPalBalanceAffecting { $name_parts = explode(" ", $this->name ?? ''); - if(count($name_parts) == 2) - { + if(count($name_parts) == 2) { $contact['first_name'] = $name_parts[0]; $contact['last_name'] = $name_parts[1]; - } - else { + } else { $contact['first_name'] = $this->name ?? ''; } @@ -188,7 +187,7 @@ class PayPalBalanceAffecting return $contact; } - + private function returnAddress(): array { return [ @@ -203,13 +202,15 @@ class PayPalBalanceAffecting private function returnShippingAddress(): array { - if(strlen($this->shippingAddress ?? '') <3) + if(strlen($this->shippingAddress ?? '') < 3) { return []; + } $ship_parts = explode(",", $this->shippingAddress); - if(count($ship_parts) != 7) + if(count($ship_parts) != 7) { return []; + } return [ 'shipping_address1' => $ship_parts[2], diff --git a/app/Export/CSV/BaseExport.php b/app/Export/CSV/BaseExport.php index 31cfb9b05c04..11d92f15df94 100644 --- a/app/Export/CSV/BaseExport.php +++ b/app/Export/CSV/BaseExport.php @@ -838,12 +838,12 @@ class BaseExport return ''; } - + /** * Apply Product Filters * * @param Builder $query - * + * * @return Builder */ public function applyProductFilters(Builder $query): Builder @@ -863,13 +863,13 @@ class BaseExport return $query; } - + /** * Add Client Filter * * @param Builder $query * @param mixed $clients - * + * * @return Builder */ protected function addClientFilter(Builder $query, $clients): Builder @@ -886,13 +886,13 @@ class BaseExport return $query; } - + /** * Add Vendor Filter * * @param Builder $query * @param string $vendors - * + * * @return Builder */ protected function addVendorFilter(Builder$query, string $vendors): Builder @@ -910,13 +910,13 @@ class BaseExport return $query; } - + /** * AddProjectFilter * * @param Builder $query * @param string $projects - * + * * @return Builder */ protected function addProjectFilter(Builder $query, string $projects): Builder @@ -934,13 +934,13 @@ class BaseExport return $query; } - + /** * Add Category Filter * * @param Builder $query * @param string $expense_categories - * + * * @return Builder */ protected function addCategoryFilter(Builder $query, string $expense_categories): Builder @@ -959,13 +959,13 @@ class BaseExport return $query; } - + /** * Add Payment Status Filters * * @param Builder $query * @param string $status - * + * * @return Builder */ protected function addPaymentStatusFilters(Builder $query, string $status): Builder @@ -976,7 +976,7 @@ class BaseExport if(in_array('all', $status_parameters) || count($status_parameters) == 0) { return $query; } - + $query->where(function ($query) use ($status_parameters) { $payment_filters = []; @@ -1016,13 +1016,13 @@ class BaseExport return $query; } - + /** * Add RecurringInvoice Status Filter * * @param Builder $query * @param string $status - * + * * @return Builder */ protected function addRecurringInvoiceStatusFilter(Builder $query, string $status): Builder @@ -1030,7 +1030,7 @@ class BaseExport $status_parameters = explode(',', $status); - if (in_array('all', $status_parameters) || count($status_parameters) == 0){ + if (in_array('all', $status_parameters) || count($status_parameters) == 0) { return $query; } @@ -1060,7 +1060,7 @@ class BaseExport * * @param Builder $query * @param string $status - * + * * @return Builder */ protected function addQuoteStatusFilter(Builder $query, string $status): Builder @@ -1126,12 +1126,12 @@ class BaseExport * * @param Builder $query * @param string $status - * + * * @return Builder */ protected function addPurchaseOrderStatusFilter(Builder $query, string $status): Builder { - + $status_parameters = explode(',', $status); if (in_array('all', $status_parameters) || count($status_parameters) == 0) { @@ -1234,7 +1234,7 @@ class BaseExport return $query; } - + /** * Add Date Range * @@ -1578,7 +1578,7 @@ class BaseExport public function queueDocuments(Builder $query) { - + if($query->getModel() instanceof Document) { $documents = $query->pluck('id')->toArray(); } else { diff --git a/app/Export/CSV/ClientExport.php b/app/Export/CSV/ClientExport.php index de3ee42c0650..4b27fb45df62 100644 --- a/app/Export/CSV/ClientExport.php +++ b/app/Export/CSV/ClientExport.php @@ -127,8 +127,9 @@ class ClientExport extends BaseExport ->withTrashed() ->where('company_id', $this->company->id); - if(!$this->input['include_deleted'] ?? false) + if(!$this->input['include_deleted'] ?? false) { $query->where('is_deleted', 0); + } $query = $this->addDateRange($query); diff --git a/app/Export/CSV/ContactExport.php b/app/Export/CSV/ContactExport.php index b7e2c0e52dda..12ea78384c6e 100644 --- a/app/Export/CSV/ContactExport.php +++ b/app/Export/CSV/ContactExport.php @@ -59,7 +59,7 @@ class ContactExport extends BaseExport $query = ClientContact::query() ->where('company_id', $this->company->id) - ->whereHas('client', function ($q){ + ->whereHas('client', function ($q) { $q->where('is_deleted', false); }); diff --git a/app/Export/CSV/CreditExport.php b/app/Export/CSV/CreditExport.php index a549f274efb8..16ea287a0101 100644 --- a/app/Export/CSV/CreditExport.php +++ b/app/Export/CSV/CreditExport.php @@ -102,7 +102,7 @@ class CreditExport extends BaseExport $query = Credit::query() ->withTrashed() ->with('client') - ->whereHas('client', function ($q){ + ->whereHas('client', function ($q) { $q->where('is_deleted', false); }) ->where('company_id', $this->company->id) diff --git a/app/Export/CSV/ExpenseExport.php b/app/Export/CSV/ExpenseExport.php index abd6dc5d43b9..8610193e824a 100644 --- a/app/Export/CSV/ExpenseExport.php +++ b/app/Export/CSV/ExpenseExport.php @@ -83,9 +83,9 @@ class ExpenseExport extends BaseExport ->with('client') ->withTrashed() ->where('company_id', $this->company->id); - - - if(!$this->input['include_deleted'] ?? false){ + + + if(!$this->input['include_deleted'] ?? false) { $query->where('is_deleted', 0); } diff --git a/app/Export/CSV/InvoiceExport.php b/app/Export/CSV/InvoiceExport.php index b0435e3859fd..e8c096778313 100644 --- a/app/Export/CSV/InvoiceExport.php +++ b/app/Export/CSV/InvoiceExport.php @@ -57,13 +57,13 @@ class InvoiceExport extends BaseExport $query = Invoice::query() ->withTrashed() ->with('client') - ->whereHas('client', function ($q){ + ->whereHas('client', function ($q) { $q->where('is_deleted', false); }) ->where('company_id', $this->company->id); - - if(!$this->input['include_deleted'] ?? false){ + + if(!$this->input['include_deleted'] ?? false) { $query->where('is_deleted', 0); } diff --git a/app/Export/CSV/InvoiceItemExport.php b/app/Export/CSV/InvoiceItemExport.php index 20308854f2ac..7068a33170e1 100644 --- a/app/Export/CSV/InvoiceItemExport.php +++ b/app/Export/CSV/InvoiceItemExport.php @@ -70,12 +70,12 @@ class InvoiceItemExport extends BaseExport $query = Invoice::query() ->withTrashed() ->with('client') - ->whereHas('client', function ($q){ + ->whereHas('client', function ($q) { $q->where('is_deleted', false); }) ->where('company_id', $this->company->id); - - if(!$this->input['include_deleted'] ?? false){ + + if(!$this->input['include_deleted'] ?? false) { $query->where('is_deleted', 0); } diff --git a/app/Export/CSV/PaymentExport.php b/app/Export/CSV/PaymentExport.php index 18c25feb0298..02b519346964 100644 --- a/app/Export/CSV/PaymentExport.php +++ b/app/Export/CSV/PaymentExport.php @@ -56,7 +56,7 @@ class PaymentExport extends BaseExport $query = Payment::query() ->withTrashed() - ->whereHas('client', function ($q){ + ->whereHas('client', function ($q) { $q->where('is_deleted', false); }) ->where('company_id', $this->company->id) @@ -71,7 +71,7 @@ class PaymentExport extends BaseExport } $query = $this->addPaymentStatusFilters($query, $this->input['status'] ?? ''); - + if($this->input['document_email_attachment'] ?? false) { $this->queueDocuments($query); } diff --git a/app/Export/CSV/ProductExport.php b/app/Export/CSV/ProductExport.php index cd874d16eb92..a572825a3e72 100644 --- a/app/Export/CSV/ProductExport.php +++ b/app/Export/CSV/ProductExport.php @@ -74,9 +74,9 @@ class ProductExport extends BaseExport $query = Product::query() ->withTrashed() ->where('company_id', $this->company->id); - - - if(!$this->input['include_deleted'] ?? false){ + + + if(!$this->input['include_deleted'] ?? false) { $query->where('is_deleted', 0); } diff --git a/app/Export/CSV/ProductSalesExport.php b/app/Export/CSV/ProductSalesExport.php index db33e311352d..2504f17f36f9 100644 --- a/app/Export/CSV/ProductSalesExport.php +++ b/app/Export/CSV/ProductSalesExport.php @@ -80,20 +80,20 @@ class ProductSalesExport extends BaseExport public function filterByProducts($query) { - + $product_keys = &$this->input['product_key']; if ($product_keys && !empty($this->input['product_key'])) { $keys = explode(",", $product_keys); - $query->where(function ($q) use ($keys){ + $query->where(function ($q) use ($keys) { - foreach($keys as $key) { + foreach($keys as $key) { $q->orWhereJsonContains('line_items', ['product_key' => $key]); } }); - + } return $query; @@ -121,7 +121,7 @@ class ProductSalesExport extends BaseExport //insert the header $query = Invoice::query() ->withTrashed() - ->whereHas('client', function ($q){ + ->whereHas('client', function ($q) { $q->where('is_deleted', false); }) ->where('company_id', $this->company->id) @@ -138,30 +138,29 @@ class ProductSalesExport extends BaseExport $product_keys = &$this->input['product_key']; - if($product_keys){ + if($product_keys) { $product_keys = explode(",", $product_keys); } $query->cursor() - ->each(function ($invoice) use($product_keys) { + ->each(function ($invoice) use ($product_keys) { foreach ($invoice->line_items as $item) { - if($product_keys) - { - if(in_array($item->product_key, $product_keys)) - $this->csv->insertOne($this->buildRow($invoice, $item)); - } - else { - $this->csv->insertOne($this->buildRow($invoice, $item)); - } - + if($product_keys) { + if(in_array($item->product_key, $product_keys)) { + $this->csv->insertOne($this->buildRow($invoice, $item)); + } + } else { + $this->csv->insertOne($this->buildRow($invoice, $item)); + } + } }); - $grouped = $this->sales->groupBy('product_key')->map(function ($key, $value) use($product_keys){ + $grouped = $this->sales->groupBy('product_key')->map(function ($key, $value) use ($product_keys) { - if($product_keys && !in_array($value, $product_keys)){ + if($product_keys && !in_array($value, $product_keys)) { return false; } @@ -185,7 +184,8 @@ class ProductSalesExport extends BaseExport })->reject(function ($value) { return $value === false; - });; + }); + ; $this->csv->insertOne([]); $this->csv->insertOne([]); diff --git a/app/Export/CSV/PurchaseOrderExport.php b/app/Export/CSV/PurchaseOrderExport.php index cbe54e51b2c9..c09353387d15 100644 --- a/app/Export/CSV/PurchaseOrderExport.php +++ b/app/Export/CSV/PurchaseOrderExport.php @@ -58,12 +58,12 @@ class PurchaseOrderExport extends BaseExport $query = PurchaseOrder::query() ->withTrashed() ->with('vendor') - ->whereHas('vendor', function ($q){ + ->whereHas('vendor', function ($q) { $q->where('is_deleted', false); }) ->where('company_id', $this->company->id); - - if(!$this->input['include_deleted'] ?? false){ + + if(!$this->input['include_deleted'] ?? false) { $query->where('is_deleted', 0); } @@ -72,8 +72,9 @@ class PurchaseOrderExport extends BaseExport $clients = &$this->input['client_id']; - if($clients) + if($clients) { $query = $this->addClientFilter($query, $clients); + } $query = $this->addPurchaseOrderStatusFilter($query, $this->input['status'] ?? ''); diff --git a/app/Export/CSV/PurchaseOrderItemExport.php b/app/Export/CSV/PurchaseOrderItemExport.php index 96c4c03aff28..fcebc7810f5c 100644 --- a/app/Export/CSV/PurchaseOrderItemExport.php +++ b/app/Export/CSV/PurchaseOrderItemExport.php @@ -62,12 +62,12 @@ class PurchaseOrderItemExport extends BaseExport $query = PurchaseOrder::query() ->withTrashed() - ->whereHas('vendor', function ($q){ + ->whereHas('vendor', function ($q) { $q->where('is_deleted', false); }) ->with('vendor')->where('company_id', $this->company->id); - - if(!$this->input['include_deleted'] ?? false){ + + if(!$this->input['include_deleted'] ?? false) { $query->where('is_deleted', 0); } diff --git a/app/Export/CSV/QuoteExport.php b/app/Export/CSV/QuoteExport.php index 13c53cb0dc3a..6decca083870 100644 --- a/app/Export/CSV/QuoteExport.php +++ b/app/Export/CSV/QuoteExport.php @@ -64,12 +64,12 @@ class QuoteExport extends BaseExport $query = Quote::query() ->withTrashed() ->with('client') - ->whereHas('client', function ($q){ + ->whereHas('client', function ($q) { $q->where('is_deleted', false); }) ->where('company_id', $this->company->id); - - if(!$this->input['include_deleted'] ?? false){ + + if(!$this->input['include_deleted'] ?? false) { $query->where('is_deleted', 0); } diff --git a/app/Export/CSV/QuoteItemExport.php b/app/Export/CSV/QuoteItemExport.php index d3f8be4b91f8..04caacf613ad 100644 --- a/app/Export/CSV/QuoteItemExport.php +++ b/app/Export/CSV/QuoteItemExport.php @@ -65,12 +65,12 @@ class QuoteItemExport extends BaseExport $query = Quote::query() ->withTrashed() - ->whereHas('client', function ($q){ + ->whereHas('client', function ($q) { $q->where('is_deleted', false); }) ->with('client')->where('company_id', $this->company->id); - - if(!$this->input['include_deleted'] ?? false){ + + if(!$this->input['include_deleted'] ?? false) { $query->where('is_deleted', 0); } diff --git a/app/Export/CSV/RecurringInvoiceExport.php b/app/Export/CSV/RecurringInvoiceExport.php index 9c88f33f7ab9..500137b88683 100644 --- a/app/Export/CSV/RecurringInvoiceExport.php +++ b/app/Export/CSV/RecurringInvoiceExport.php @@ -56,12 +56,12 @@ class RecurringInvoiceExport extends BaseExport $query = RecurringInvoice::query() ->withTrashed() ->with('client') - ->whereHas('client', function ($q){ + ->whereHas('client', function ($q) { $q->where('is_deleted', false); }) ->where('company_id', $this->company->id); - - if(!$this->input['include_deleted'] ?? false){ + + if(!$this->input['include_deleted'] ?? false) { $query->where('is_deleted', 0); } diff --git a/app/Export/CSV/TaskExport.php b/app/Export/CSV/TaskExport.php index 5b1985ce4782..47423c23e2b3 100644 --- a/app/Export/CSV/TaskExport.php +++ b/app/Export/CSV/TaskExport.php @@ -69,22 +69,24 @@ class TaskExport extends BaseExport $query = Task::query() ->withTrashed() ->where('company_id', $this->company->id); - - if(!$this->input['include_deleted'] ?? false){ + + if(!$this->input['include_deleted'] ?? false) { $query->where('is_deleted', 0); } $query = $this->addDateRange($query); - + $clients = &$this->input['client_id']; - if($clients) + if($clients) { $query = $this->addClientFilter($query, $clients); + } $document_attachments = &$this->input['document_email_attachment']; - if($document_attachments) + if($document_attachments) { $this->queueDocuments($query); + } return $query; @@ -224,7 +226,7 @@ class TaskExport extends BaseExport } } - + /** * Add Task Status Filter * @@ -234,7 +236,7 @@ class TaskExport extends BaseExport */ protected function addTaskStatusFilter(Builder $query, string $status): Builder { - + $status_parameters = explode(',', $status); if (in_array('all', $status_parameters) || count($status_parameters) == 0) { diff --git a/app/Export/CSV/VendorExport.php b/app/Export/CSV/VendorExport.php index 187487a14765..c04f83e8c4c4 100644 --- a/app/Export/CSV/VendorExport.php +++ b/app/Export/CSV/VendorExport.php @@ -63,8 +63,8 @@ class VendorExport extends BaseExport $query = Vendor::query()->with('contacts') ->withTrashed() ->where('company_id', $this->company->id); - - if(!$this->input['include_deleted'] ?? false){ + + if(!$this->input['include_deleted'] ?? false) { $query->where('is_deleted', 0); } diff --git a/app/Export/Decorators/ContactDecorator.php b/app/Export/Decorators/ContactDecorator.php index 71707e9b0883..b6fa3edc72b3 100644 --- a/app/Export/Decorators/ContactDecorator.php +++ b/app/Export/Decorators/ContactDecorator.php @@ -25,7 +25,7 @@ class ContactDecorator implements DecoratorInterface $contact = $entity->contacts()->first(); } elseif($entity->client) { $contact = $entity->client->primary_contact->first() ?? $entity->client->contacts()->whereNotNull('email')->first(); - } elseif($entity->vendor) { + } elseif($entity->vendor) { $contact = $entity->vendor->primary_contact->first() ?? $entity->vendor->contacts()->whereNotNull('email')->first(); } diff --git a/app/Factory/CompanyFactory.php b/app/Factory/CompanyFactory.php index ef32ea77e069..96c515ca3868 100644 --- a/app/Factory/CompanyFactory.php +++ b/app/Factory/CompanyFactory.php @@ -56,7 +56,7 @@ class CompanyFactory $company->smtp_port = ''; $company->smtp_username = ''; $company->smtp_verify_peer = true; - + return $company; } } diff --git a/app/Factory/CompanyGatewayFactory.php b/app/Factory/CompanyGatewayFactory.php index ecb7b3934005..1e44477d6477 100644 --- a/app/Factory/CompanyGatewayFactory.php +++ b/app/Factory/CompanyGatewayFactory.php @@ -24,7 +24,7 @@ class CompanyGatewayFactory $company_gateway->require_shipping_address = false; $company_gateway->config = encrypt(json_encode(new \stdClass())); $company_gateway->always_show_required_fields = true; - + return $company_gateway; } } diff --git a/app/Factory/PurchaseOrderFactory.php b/app/Factory/PurchaseOrderFactory.php index 5803c25790a1..b2a3f837b294 100644 --- a/app/Factory/PurchaseOrderFactory.php +++ b/app/Factory/PurchaseOrderFactory.php @@ -52,7 +52,7 @@ class PurchaseOrderFactory $purchase_order->exchange_rate = 1; $purchase_order->total_taxes = 0; $purchase_order->uses_inclusive_taxes = false; - + return $purchase_order; } } diff --git a/app/Factory/SubscriptionFactory.php b/app/Factory/SubscriptionFactory.php index 8b904a28a743..0b8464c05f9e 100644 --- a/app/Factory/SubscriptionFactory.php +++ b/app/Factory/SubscriptionFactory.php @@ -23,7 +23,7 @@ class SubscriptionFactory $billing_subscription->company_id = $company_id; $billing_subscription->user_id = $user_id; $billing_subscription->steps = collect(Purchase::defaultSteps()) - ->map(fn($step) => StepService::mapClassNameToString($step)) + ->map(fn ($step) => StepService::mapClassNameToString($step)) ->implode(','); return $billing_subscription; diff --git a/app/Filters/BankTransactionFilters.php b/app/Filters/BankTransactionFilters.php index e3c62da1ef30..faaeaa7ade4a 100644 --- a/app/Filters/BankTransactionFilters.php +++ b/app/Filters/BankTransactionFilters.php @@ -115,7 +115,7 @@ class BankTransactionFilters extends QueryFilters return $this->builder; } - + /** * Filters the list based on Bank Accounts. * @@ -124,11 +124,12 @@ class BankTransactionFilters extends QueryFilters */ public function bank_integration_ids(string $ids = ''): Builder { - if(strlen($ids) == 0) + if(strlen($ids) == 0) { return $this->builder; + } $ids = $this->transformKeys(explode(",", $ids)); - + $this->builder->where(function ($query) use ($ids) { $query->whereIn('bank_integration_id', $ids); }); diff --git a/app/Filters/ClientFilters.php b/app/Filters/ClientFilters.php index ab56672f28eb..ffc3e4fd7717 100644 --- a/app/Filters/ClientFilters.php +++ b/app/Filters/ClientFilters.php @@ -160,8 +160,9 @@ class ClientFilters extends QueryFilters return $this->builder; } - if($sort_col[0] == 'documents') + if($sort_col[0] == 'documents') { return $this->builder; + } if ($sort_col[0] == 'display_name') { $sort_col[0] = 'name'; diff --git a/app/Filters/DesignFilters.php b/app/Filters/DesignFilters.php index 8d7ba26ea05e..f914bcc4ba46 100644 --- a/app/Filters/DesignFilters.php +++ b/app/Filters/DesignFilters.php @@ -58,10 +58,11 @@ class DesignFilters extends QueryFilters public function entities(string $entities = ''): Builder { - - if(stripos($entities, 'statement') !== false) + + if(stripos($entities, 'statement') !== false) { $entities = 'client'; - + } + if (strlen($entities) == 0 || str_contains($entities, ',')) { return $this->builder; } diff --git a/app/Filters/DocumentFilters.php b/app/Filters/DocumentFilters.php index 9973cbf51345..4623e25326e2 100644 --- a/app/Filters/DocumentFilters.php +++ b/app/Filters/DocumentFilters.php @@ -49,22 +49,22 @@ class DocumentFilters extends QueryFilters */ public function client_id(string $client_id = ''): Builder { - + return $this->builder->where(function ($query) use ($client_id) { $query->whereHasMorph('documentable', [ - \App\Models\Invoice::class, - \App\Models\Quote::class, - \App\Models\Credit::class, - \App\Models\Expense::class, - \App\Models\Payment::class, + \App\Models\Invoice::class, + \App\Models\Quote::class, + \App\Models\Credit::class, + \App\Models\Expense::class, + \App\Models\Payment::class, \App\Models\Task::class, \App\Models\RecurringExpense::class, \App\Models\RecurringInvoice::class, \App\Models\Project::class, ], function ($q2) use ($client_id) { - $q2->where('client_id', $this->decodePrimaryKey($client_id)); - })->orWhereHasMorph('documentable', [\App\Models\Client::class], function ($q3) use ($client_id) { - $q3->where('id', $this->decodePrimaryKey($client_id)); + $q2->where('client_id', $this->decodePrimaryKey($client_id)); + })->orWhereHasMorph('documentable', [\App\Models\Client::class], function ($q3) use ($client_id) { + $q3->where('id', $this->decodePrimaryKey($client_id)); }); }); @@ -74,8 +74,7 @@ class DocumentFilters extends QueryFilters { $types = explode(',', $types); - foreach ($types as $type) - { + foreach ($types as $type) { match($type) { 'private' => $this->builder->where('is_public', 0), 'public' => $this->builder->where('is_public', 1), @@ -87,7 +86,7 @@ class DocumentFilters extends QueryFilters } return $this->builder; - } + } /** * Sorts the list based on $sort. diff --git a/app/Filters/ExpenseFilters.php b/app/Filters/ExpenseFilters.php index 0d133e96ce12..108dc359d811 100644 --- a/app/Filters/ExpenseFilters.php +++ b/app/Filters/ExpenseFilters.php @@ -111,8 +111,8 @@ class ExpenseFilters extends QueryFilters }); } - if(in_array('uncategorized', $status_parameters)){ - $query->orWhere(function ($query){ + if(in_array('uncategorized', $status_parameters)) { + $query->orWhere(function ($query) { $query->whereNull('category_id'); }); } diff --git a/app/Filters/InvoiceFilters.php b/app/Filters/InvoiceFilters.php index 5f307de3079b..3ef024429485 100644 --- a/app/Filters/InvoiceFilters.php +++ b/app/Filters/InvoiceFilters.php @@ -228,10 +228,9 @@ class InvoiceFilters extends QueryFilters $date = Carbon::createFromTimestamp((int)$date); } else { - try{ + try { $date = Carbon::parse($date); - } - catch(\Exception $e){ + } catch(\Exception $e) { return $this->builder; } } @@ -339,7 +338,7 @@ class InvoiceFilters extends QueryFilters // return $this->builder->orderByRaw('CAST(number AS UNSIGNED), number ' . $dir); // return $this->builder->orderByRaw("number REGEXP '^[A-Za-z]+$',CAST(number as SIGNED INTEGER),CAST(REPLACE(number,'-','')AS SIGNED INTEGER) ,number"); // return $this->builder->orderByRaw('ABS(number) ' . $dir); - return $this->builder->orderByRaw("REGEXP_REPLACE(number,'[^0-9]+','')+0 " . $dir); + return $this->builder->orderByRaw("REGEXP_REPLACE(number,'[^0-9]+','')+0 " . $dir); } return $this->builder->orderBy($sort_col[0], $dir); diff --git a/app/Filters/RecurringInvoiceFilters.php b/app/Filters/RecurringInvoiceFilters.php index b9124c9168cb..56ac04619c99 100644 --- a/app/Filters/RecurringInvoiceFilters.php +++ b/app/Filters/RecurringInvoiceFilters.php @@ -133,7 +133,7 @@ class RecurringInvoiceFilters extends QueryFilters return $this->builder->orderByRaw("REGEXP_REPLACE(number,'[^0-9]+','')+0 " . $dir); } - if($sort_col[0] == 'next_send_datetime'){ + if($sort_col[0] == 'next_send_datetime') { $sort_col[0] = 'next_send_date'; } diff --git a/app/Helpers/Bank/Nordigen/Nordigen.php b/app/Helpers/Bank/Nordigen/Nordigen.php index 6f71155140a4..f12e0fbe5318 100644 --- a/app/Helpers/Bank/Nordigen/Nordigen.php +++ b/app/Helpers/Bank/Nordigen/Nordigen.php @@ -100,7 +100,7 @@ class Nordigen } catch (\Exception $e) { nlog("Nordigen getAccount() failed => {$account_id} => " . $e->getMessage()); - + return false; } @@ -151,9 +151,10 @@ class Nordigen public function disabledAccountEmail(BankIntegration $bank_integration): void { $cache_key = "email_quota:{$bank_integration->company->company_key}:{$bank_integration->id}"; - - if(Cache::has($cache_key)) + + if(Cache::has($cache_key)) { return; + } App::setLocale($bank_integration->company->getLocale()); @@ -168,7 +169,7 @@ class Nordigen $mo->email_template_subject = 'nordigen_requisition_subject'; Email::dispatch($mo, $bank_integration->company); - + Cache::put($cache_key, true, 60 * 60 * 24); } diff --git a/app/Helpers/Bank/Nordigen/Transformer/TransactionTransformer.php b/app/Helpers/Bank/Nordigen/Transformer/TransactionTransformer.php index b9fc87de4ba2..d2259150e181 100644 --- a/app/Helpers/Bank/Nordigen/Transformer/TransactionTransformer.php +++ b/app/Helpers/Bank/Nordigen/Transformer/TransactionTransformer.php @@ -71,7 +71,7 @@ class TransactionTransformer implements BankRevenueInterface private Company $company; - function __construct(Company $company) + public function __construct(Company $company) { $this->company = $company; } @@ -192,7 +192,7 @@ class TransactionTransformer implements BankRevenueInterface } try { - return Carbon::createFromFormat("d-m-Y", $input)->setTimezone($timezone_name)->format($date_format_default) ?? $input; + return Carbon::createFromFormat("d-m-Y", $input)->setTimezone($timezone_name)->format($date_format_default) ?? $input; } catch (\Exception $e) { return $input; } diff --git a/app/Helpers/Epc/EpcQrGenerator.php b/app/Helpers/Epc/EpcQrGenerator.php index b38dc7efcf5c..87bb585ba6e4 100644 --- a/app/Helpers/Epc/EpcQrGenerator.php +++ b/app/Helpers/Epc/EpcQrGenerator.php @@ -105,7 +105,7 @@ class EpcQrGenerator return implode("\n", $data); } - + // substr("{$this->invoice->number} {$this->invoice->client->number}", 0,139), diff --git a/app/Helpers/Invoice/CustomValuer.php b/app/Helpers/Invoice/CustomValuer.php index 7ef81f074f9d..cc79dd22e136 100644 --- a/app/Helpers/Invoice/CustomValuer.php +++ b/app/Helpers/Invoice/CustomValuer.php @@ -27,7 +27,7 @@ trait CustomValuer public function valuerTax($custom_value, $has_custom_invoice_taxes) { - + if (isset($custom_value) && is_numeric($custom_value) && $has_custom_invoice_taxes !== false) { return round($custom_value * ($this->invoice->tax_rate1 / 100), 2) + round($custom_value * ($this->invoice->tax_rate2 / 100), 2) + round($custom_value * ($this->invoice->tax_rate3 / 100), 2); } @@ -35,17 +35,18 @@ trait CustomValuer 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) { - $tax = 0; + $tax = 0; - $tax += $this->formatValue($custom_value - ($custom_value / (1 + ($this->invoice->tax_rate1 / 100))), 2); - $tax += $this->formatValue($custom_value - ($custom_value / (1 + ($this->invoice->tax_rate2 / 100))), 2); - $tax += $this->formatValue($custom_value - ($custom_value / (1 + ($this->invoice->tax_rate3 / 100))), 2); + $tax += $this->formatValue($custom_value - ($custom_value / (1 + ($this->invoice->tax_rate1 / 100))), 2); + $tax += $this->formatValue($custom_value - ($custom_value / (1 + ($this->invoice->tax_rate2 / 100))), 2); + $tax += $this->formatValue($custom_value - ($custom_value / (1 + ($this->invoice->tax_rate3 / 100))), 2); - return round($tax,2); + return round($tax, 2); } return 0; diff --git a/app/Helpers/Invoice/InvoiceItemSum.php b/app/Helpers/Invoice/InvoiceItemSum.php index 6e449252927d..dc946874f043 100644 --- a/app/Helpers/Invoice/InvoiceItemSum.php +++ b/app/Helpers/Invoice/InvoiceItemSum.php @@ -182,7 +182,7 @@ class InvoiceItemSum $class = "App\DataMapper\Tax\\".$this->client->company->country()->iso_3166_2."\\Rule"; $this->rule = new $class(); - + if($this->rule->regionWithNoTaxCoverage($this->client->country->iso_3166_2)) { return $this; } diff --git a/app/Helpers/Invoice/InvoiceSum.php b/app/Helpers/Invoice/InvoiceSum.php index 75a6139d92a0..32a821445d17 100644 --- a/app/Helpers/Invoice/InvoiceSum.php +++ b/app/Helpers/Invoice/InvoiceSum.php @@ -229,7 +229,7 @@ class InvoiceSum { // $this->invoice->amount = $this->formatValue($this->getTotal(), $this->precision); // $this->invoice->total_taxes = $this->getTotalTaxes(); - + $this->setCalculatedAttributes(); $this->invoice->balance = $this->invoice->amount; $this->invoice->saveQuietly(); @@ -245,10 +245,9 @@ class InvoiceSum */ private function setCalculatedAttributes(): self { - if($this->invoice->status_id == Invoice::STATUS_CANCELLED){ + if($this->invoice->status_id == Invoice::STATUS_CANCELLED) { $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) { $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 { @@ -258,7 +257,7 @@ class InvoiceSum /* Set new calculated total */ $this->invoice->amount = $this->formatValue($this->getTotal(), $this->precision); - if($this->rappen_rounding){ + if($this->rappen_rounding) { $this->invoice->amount = $this->roundRappen($this->invoice->amount); $this->invoice->balance = $this->roundRappen($this->invoice->balance); } @@ -269,7 +268,7 @@ class InvoiceSum } - function roundRappen($value): float + public function roundRappen($value): float { return round($value / .05, 0) * .05; } diff --git a/app/Helpers/Invoice/InvoiceSumInclusive.php b/app/Helpers/Invoice/InvoiceSumInclusive.php index bdc3eaacac4d..fe50d9cb1fb0 100644 --- a/app/Helpers/Invoice/InvoiceSumInclusive.php +++ b/app/Helpers/Invoice/InvoiceSumInclusive.php @@ -171,7 +171,7 @@ class InvoiceSumInclusive $this->total_taxes += $tax; $this->total_tax_map[] = ['name' => $this->invoice->tax_name3.' '.floatval($this->invoice->tax_rate3).'%', 'total' => $tax]; } - + return $this; } @@ -279,10 +279,9 @@ class InvoiceSumInclusive private function setCalculatedAttributes() { /* 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; - } - elseif ($this->invoice->status_id != Invoice::STATUS_DRAFT) { + } elseif ($this->invoice->status_id != Invoice::STATUS_DRAFT) { if ($this->invoice->amount != $this->invoice->balance) { $this->invoice->balance = $this->formatValue($this->getTotal(), $this->precision) - $this->invoice->paid_to_date; } else { @@ -302,8 +301,8 @@ class InvoiceSumInclusive return $this; } - - function roundRappen($value): float + + public function roundRappen($value): float { return round($value / .05, 0) * .05; } @@ -373,7 +372,7 @@ class InvoiceSumInclusive $this->total_taxes += $total_line_tax; } - + return $this; } diff --git a/app/Helpers/Mail/GmailTransport.php b/app/Helpers/Mail/GmailTransport.php index 0655c710cad8..020147807c9a 100644 --- a/app/Helpers/Mail/GmailTransport.php +++ b/app/Helpers/Mail/GmailTransport.php @@ -65,18 +65,18 @@ class GmailTransport extends AbstractTransport $body->setRaw($this->base64_encode($bcc_list.$message->toString())); // try { - $service->users_messages->send('me', $body, []); + $service->users_messages->send('me', $body, []); // } catch(\Google\Service\Exception $e) { // /* Need to slow down */ // if ($e->getCode() == '429') { // nlog("429 google - retrying "); // sleep(rand(3,8)); - + // try { // $service->users_messages->send('me', $body, []); // } catch(\Google\Service\Exception $e) { - + // } // } diff --git a/app/Helpers/Mail/Office365MailTransport.php b/app/Helpers/Mail/Office365MailTransport.php index 258ed9d0ff53..c5cf6fa91235 100644 --- a/app/Helpers/Mail/Office365MailTransport.php +++ b/app/Helpers/Mail/Office365MailTransport.php @@ -54,17 +54,17 @@ class Office365MailTransport extends AbstractTransport ->setReturnType(\Microsoft\Graph\Model\Message::class) ->execute(); } catch (\Exception $e) { - - sleep(rand(5,10)); + + sleep(rand(5, 10)); try { - $graphMessage = $graph->createRequest('POST', '/users/'.$symfony_message->getFrom()[0]->getAddress().'/sendmail') - ->attachBody(base64_encode($bcc_list.$message->toString())) - ->addHeaders(['Content-Type' => 'text/plain']) - ->setReturnType(\Microsoft\Graph\Model\Message::class) - ->execute(); + $graphMessage = $graph->createRequest('POST', '/users/'.$symfony_message->getFrom()[0]->getAddress().'/sendmail') + ->attachBody(base64_encode($bcc_list.$message->toString())) + ->addHeaders(['Content-Type' => 'text/plain']) + ->setReturnType(\Microsoft\Graph\Model\Message::class) + ->execute(); } catch (\Exception $e) { - + } } diff --git a/app/Http/Controllers/Auth/ContactLoginController.php b/app/Http/Controllers/Auth/ContactLoginController.php index 0c387a666405..e0f18daad76d 100644 --- a/app/Http/Controllers/Auth/ContactLoginController.php +++ b/app/Http/Controllers/Auth/ContactLoginController.php @@ -166,7 +166,7 @@ class ContactLoginController extends Controller private function setRedirectPath() { if (auth()->guard('contact')->user()->client->getSetting('enable_client_portal_dashboard') === true) { - $this->redirectTo = '/client/dashboard'; + $this->redirectTo = '/client/dashboard'; } elseif (auth()->guard('contact')->user()->company->enabled_modules & PortalComposer::MODULE_INVOICES) { $this->redirectTo = '/client/invoices'; } elseif (auth()->guard('contact')->user()->company->enabled_modules & PortalComposer::MODULE_RECURRING_INVOICES) { diff --git a/app/Http/Controllers/Auth/ContactRegisterController.php b/app/Http/Controllers/Auth/ContactRegisterController.php index bc3b20071433..3181021f9cf4 100644 --- a/app/Http/Controllers/Auth/ContactRegisterController.php +++ b/app/Http/Controllers/Auth/ContactRegisterController.php @@ -50,7 +50,7 @@ class ContactRegisterController extends Controller public function register(RegisterRequest $request) { $request->merge(['company' => $request->company()]); - + $service = new ClientRegisterService( company: $request->company(), ); diff --git a/app/Http/Controllers/Auth/LoginController.php b/app/Http/Controllers/Auth/LoginController.php index 3aefbab71132..d3bc62acc412 100644 --- a/app/Http/Controllers/Auth/LoginController.php +++ b/app/Http/Controllers/Auth/LoginController.php @@ -398,8 +398,8 @@ class LoginController extends BaseController $truth->setCompany($set_company); //21-03-2024 - $cu->each(function ($cu){ - if(CompanyToken::where('company_id', $cu->company_id)->where('user_id', $cu->user_id)->where('is_system', true)->doesntExist()){ + $cu->each(function ($cu) { + if(CompanyToken::where('company_id', $cu->company_id)->where('user_id', $cu->user_id)->where('is_system', true)->doesntExist()) { (new CreateCompanyToken($cu->company, $cu->user, request()->server('HTTP_USER_AGENT')))->handle(); } }); diff --git a/app/Http/Controllers/Bank/YodleeController.php b/app/Http/Controllers/Bank/YodleeController.php index 7fd789bdea7f..26977d49383e 100644 --- a/app/Http/Controllers/Bank/YodleeController.php +++ b/app/Http/Controllers/Bank/YodleeController.php @@ -310,7 +310,7 @@ class YodleeController extends BaseController private function transformSummary($summary): array { - $dto = new \stdClass; + $dto = new \stdClass(); $dto->id = $summary['id'] ?? 0; $dto->account_type = $summary['CONTAINER'] ?? ''; diff --git a/app/Http/Controllers/BaseController.php b/app/Http/Controllers/BaseController.php index 92f1d4a6c272..f91a91930490 100644 --- a/app/Http/Controllers/BaseController.php +++ b/app/Http/Controllers/BaseController.php @@ -460,7 +460,7 @@ class BaseController extends Controller } }, 'company.tasks' => function ($query) use ($updated_at, $user) { - $query->where('updated_at', '>=', $updated_at)->with('project','documents'); + $query->where('updated_at', '>=', $updated_at)->with('project', 'documents'); if (! $user->hasPermission('view_task')) { $query->whereNested(function ($query) use ($user) { @@ -798,7 +798,7 @@ class BaseController extends Controller } }, 'company.tasks' => function ($query) use ($created_at, $user) { - $query->where('created_at', '>=', $created_at)->with('project.documents','documents'); + $query->where('created_at', '>=', $created_at)->with('project.documents', 'documents'); if (! $user->hasPermission('view_task')) { $query->whereNested(function ($query) use ($user) { @@ -995,7 +995,7 @@ class BaseController extends Controller $response_data = Statics::company($user->getCompany()->getLocale()); - if(request()->has('einvoice')){ + if(request()->has('einvoice')) { $ro = new Schema(); $response_data['einvoice_schema'] = $ro('Peppol'); @@ -1003,7 +1003,7 @@ class BaseController extends Controller } $response['static'] = $response_data; - + } } diff --git a/app/Http/Controllers/ClientController.php b/app/Http/Controllers/ClientController.php index ffe011a6e3fc..8305c8782c9e 100644 --- a/app/Http/Controllers/ClientController.php +++ b/app/Http/Controllers/ClientController.php @@ -250,22 +250,22 @@ class ClientController extends BaseController return response()->json(['message' => $hash_or_response], 200); } - if($action == 'assign_group' && $user->can('edit', $clients->first())){ + if($action == 'assign_group' && $user->can('edit', $clients->first())) { $this->client_repo->assignGroup($clients, $request->group_settings_id); - + return $this->listResponse(Client::query()->withTrashed()->company()->whereIn('id', $request->ids)); } - if($action == 'bulk_update' && $user->can('edit', $clients->first())){ + if($action == 'bulk_update' && $user->can('edit', $clients->first())) { $clients = Client::withTrashed() ->company() ->whereIn('id', $request->ids); $this->client_repo->bulkUpdate($clients, $request->column, $request->new_value); - + return $this->listResponse(Client::query()->withTrashed()->company()->whereIn('id', $request->ids)); } @@ -351,9 +351,10 @@ class ClientController extends BaseController 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); - + } + $merged_client = $client->service()->merge($m_client)->save(); return $this->itemResponse($merged_client); diff --git a/app/Http/Controllers/ClientPortal/DashboardController.php b/app/Http/Controllers/ClientPortal/DashboardController.php index c8c53d3b8445..33b3e392b601 100644 --- a/app/Http/Controllers/ClientPortal/DashboardController.php +++ b/app/Http/Controllers/ClientPortal/DashboardController.php @@ -21,7 +21,7 @@ class DashboardController extends Controller { if (auth()->guard('contact')->user()->client->getSetting('enable_client_portal_dashboard') === false) { return redirect()->route('client.invoices.index'); - } + } $total_invoices = Invoice::withTrashed() ->where('client_id', auth()->guard('contact')->user()->client_id) diff --git a/app/Http/Controllers/ClientPortal/PrePaymentController.php b/app/Http/Controllers/ClientPortal/PrePaymentController.php index 7acd355a9bf0..6a666e9c7d9d 100644 --- a/app/Http/Controllers/ClientPortal/PrePaymentController.php +++ b/app/Http/Controllers/ClientPortal/PrePaymentController.php @@ -108,7 +108,7 @@ class PrePaymentController extends Controller return $invoice; }); - + $variables = false; if(($invitation = $invoices->first()->invitations()->first() ?? false) && $invoice->client->getSetting('show_accept_invoice_terms')) { diff --git a/app/Http/Controllers/ClientPortal/QuoteController.php b/app/Http/Controllers/ClientPortal/QuoteController.php index 52c5ccf58416..9dce7c6e3eab 100644 --- a/app/Http/Controllers/ClientPortal/QuoteController.php +++ b/app/Http/Controllers/ClientPortal/QuoteController.php @@ -178,7 +178,7 @@ class QuoteController extends Controller ->where('client_id', auth()->guard('contact')->user()->client->id) ->where('company_id', auth()->guard('contact')->user()->client->company_id) ->whereIn('status_id', [Quote::STATUS_DRAFT, Quote::STATUS_SENT]) - ->where(function ($q){ + ->where(function ($q) { $q->whereNull('due_date')->orWhere('due_date', '>=', now()); }) ->withTrashed() diff --git a/app/Http/Controllers/CompanyController.php b/app/Http/Controllers/CompanyController.php index 83ffb0a96f77..25fefb7b35ce 100644 --- a/app/Http/Controllers/CompanyController.php +++ b/app/Http/Controllers/CompanyController.php @@ -715,18 +715,16 @@ class CompanyController extends BaseController $logo = strlen($company->settings->company_logo) > 5 ? $company->settings->company_logo : 'https://pdf.invoicing.co/favicon-v2.png'; $headers = ['Content-Disposition' => 'inline']; - try{ + try { $response = \Illuminate\Support\Facades\Http::get($logo); if ($response->successful()) { $logo = $response->body(); - } - else { + } else { $logo = base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII='); } - } - catch(\Exception $e){ + } catch(\Exception $e) { $logo = base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII='); diff --git a/app/Http/Controllers/CompanyGatewayController.php b/app/Http/Controllers/CompanyGatewayController.php index fb3726be9d78..877cdc2b8153 100644 --- a/app/Http/Controllers/CompanyGatewayController.php +++ b/app/Http/Controllers/CompanyGatewayController.php @@ -232,7 +232,7 @@ class CompanyGatewayController extends BaseController } elseif($company_gateway->gateway_key == $this->checkout_key) { CheckoutSetupWebhook::dispatch($company_gateway->company->company_key, $company_gateway->id); } elseif($company_gateway->gateway_key == $this->forte_key) { - + dispatch(function () use ($company_gateway) { MultiDB::setDb($company_gateway->company->db); $company_gateway->driver()->updateFees(); @@ -420,8 +420,8 @@ class CompanyGatewayController extends BaseController if($company_gateway->gateway_key == $this->checkout_key) { CheckoutSetupWebhook::dispatch($company_gateway->company->company_key, $company_gateway->fresh()->id); - }elseif($company_gateway->gateway_key == $this->forte_key){ - + } elseif($company_gateway->gateway_key == $this->forte_key) { + dispatch(function () use ($company_gateway) { MultiDB::setDb($company_gateway->company->db); $company_gateway->driver()->updateFees(); @@ -565,12 +565,13 @@ class CompanyGatewayController extends BaseController public function importCustomers(TestCompanyGatewayRequest $request, CompanyGateway $company_gateway) { - - //Throttle here - 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); - dispatch(function () use($company_gateway) { + //Throttle here + 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); + } + + dispatch(function () use ($company_gateway) { MultiDB::setDb($company_gateway->company->db); $company_gateway->driver()->importCustomers(); })->afterResponse(); diff --git a/app/Http/Controllers/ImportController.php b/app/Http/Controllers/ImportController.php index 187e4a3ff476..a262c2459ab0 100644 --- a/app/Http/Controllers/ImportController.php +++ b/app/Http/Controllers/ImportController.php @@ -276,7 +276,7 @@ class ImportController extends Controller return $data; } - + /** * Returns the best delimiter @@ -302,7 +302,7 @@ class ImportController extends Controller } } - + /** @phpstan-ignore-next-line **/ return $bestDelimiter ?? ','; diff --git a/app/Http/Controllers/LogoutController.php b/app/Http/Controllers/LogoutController.php index 33b0091aae2a..f92bbcc92a66 100644 --- a/app/Http/Controllers/LogoutController.php +++ b/app/Http/Controllers/LogoutController.php @@ -64,11 +64,11 @@ class LogoutController extends BaseController ->tokens() ->where('is_system', true) ->cursor() - ->each(function ($ct){ + ->each(function ($ct) { $ct->token = \Illuminate\Support\Str::random(64); $ct->save(); }); - + return response()->json(['message' => 'All tokens deleted'], 200); } } diff --git a/app/Http/Controllers/PreviewController.php b/app/Http/Controllers/PreviewController.php index 8d47a49637b6..bbfa9b150368 100644 --- a/app/Http/Controllers/PreviewController.php +++ b/app/Http/Controllers/PreviewController.php @@ -146,8 +146,7 @@ class PreviewController extends BaseController if (request()->has('entity') && request()->has('entity_id') && ! empty(request()->input('entity')) && - ! empty(request()->input('entity_id'))) - { + ! empty(request()->input('entity_id'))) { $design_object = json_decode(json_encode(request()->input('design'))); @@ -172,10 +171,9 @@ class PreviewController extends BaseController App::setLocale($entity_obj->client->preferredLocale()); $t->replace(Ninja::transformTranslations($entity_obj->client->getMergedSettings())); - if($entity_obj->client){ + if($entity_obj->client) { $html = new HtmlEngine($entity_obj->invitations()->first()); - } - else { + } else { $html = new VendorHtmlEngine($entity_obj->invitations()->first()); } diff --git a/app/Http/Controllers/Reports/TaskReportController.php b/app/Http/Controllers/Reports/TaskReportController.php index b381a417e433..5a7c18572608 100644 --- a/app/Http/Controllers/Reports/TaskReportController.php +++ b/app/Http/Controllers/Reports/TaskReportController.php @@ -66,8 +66,7 @@ class TaskReportController extends BaseController /** @var \App\Models\User $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); return response()->json(['message' => 'working...'], 200); diff --git a/app/Http/Controllers/SelfUpdateController.php b/app/Http/Controllers/SelfUpdateController.php index de5808b0f120..c5c2f07f2398 100644 --- a/app/Http/Controllers/SelfUpdateController.php +++ b/app/Http/Controllers/SelfUpdateController.php @@ -62,8 +62,9 @@ class SelfUpdateController extends BaseController $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); + } 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); @@ -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'); + } nlog('Removing cache files'); diff --git a/app/Http/Controllers/SmtpController.php b/app/Http/Controllers/SmtpController.php index ce84282d8f28..3e1f7f6e378f 100644 --- a/app/Http/Controllers/SmtpController.php +++ b/app/Http/Controllers/SmtpController.php @@ -18,7 +18,6 @@ use Illuminate\Support\Facades\Mail; class SmtpController extends BaseController { - public function __construct() { parent::__construct(); @@ -51,7 +50,7 @@ class SmtpController extends BaseController 'timeout' => 5, ], ]); - + (new \Illuminate\Mail\MailServiceProvider(app()))->register(); try { @@ -60,7 +59,7 @@ class SmtpController extends BaseController $sending_user = (isset($company->settings->email_from_name) && strlen($company->settings->email_from_name) > 2) ? $company->settings->email_from_name : $user->name(); $mailable = new TestMailServer('Email Server Works!', $sending_email); - $mailable->from($sending_email,$sending_user); + $mailable->from($sending_email, $sending_user); Mail::mailer('smtp') ->to($user->email, $user->present()->name()) @@ -68,7 +67,7 @@ class SmtpController extends BaseController } catch (\Exception $e) { app('mail.manager')->forgetMailers(); - return response()->json(['message' => $e->getMessage()], 400); + return response()->json(['message' => $e->getMessage()], 400); } app('mail.manager')->forgetMailers(); @@ -77,4 +76,4 @@ class SmtpController extends BaseController } -} \ No newline at end of file +} diff --git a/app/Http/Controllers/StaticController.php b/app/Http/Controllers/StaticController.php index 0a8f584d1bf2..68cfa19be976 100644 --- a/app/Http/Controllers/StaticController.php +++ b/app/Http/Controllers/StaticController.php @@ -59,11 +59,11 @@ class StaticController extends BaseController $response_data = Statics::company($user->getLocale() ?? $user->company()->getLocale()); - if(request()->has('einvoice')){ - + if(request()->has('einvoice')) { + $schema = new Schema(); - $response_data['einvoice_schema'] = $schema('Peppol'); - + $response_data['einvoice_schema'] = $schema('Peppol'); + } return response()->json($response_data, 200, ['Content-type' => 'application/json; charset=utf-8'], JSON_PRETTY_PRINT); diff --git a/app/Http/Controllers/StripeConnectController.php b/app/Http/Controllers/StripeConnectController.php index 0ddc95b57e4c..3ef2c87c9af0 100644 --- a/app/Http/Controllers/StripeConnectController.php +++ b/app/Http/Controllers/StripeConnectController.php @@ -64,7 +64,7 @@ class StripeConnectController extends BaseController if ($request->has('error') && $request->error == 'access_denied') { return view('auth.connect.access_denied'); } - + $response = false; try { @@ -91,7 +91,7 @@ class StripeConnectController extends BaseController } catch (\Exception $e) { - + } if(!$response) { @@ -154,7 +154,7 @@ class StripeConnectController extends BaseController //response here return view('auth.connect.completed', ['url' => $redirect_uri]); - + } } diff --git a/app/Http/Controllers/SubscriptionStepsController.php b/app/Http/Controllers/SubscriptionStepsController.php index 81243ffbbba4..070960a04392 100644 --- a/app/Http/Controllers/SubscriptionStepsController.php +++ b/app/Http/Controllers/SubscriptionStepsController.php @@ -21,10 +21,10 @@ class SubscriptionStepsController extends BaseController public function index(): JsonResponse { $dependencies = collect(Purchase::$dependencies) - ->map(fn($dependency) => [ + ->map(fn ($dependency) => [ 'id' => $dependency['id'], 'dependencies' => collect($dependency['dependencies']) - ->map(fn($dependency) => Purchase::$dependencies[$dependency]['id']) + ->map(fn ($dependency) => Purchase::$dependencies[$dependency]['id']) ->toArray(), ]) ->toArray(); diff --git a/app/Http/Controllers/TwoFactorController.php b/app/Http/Controllers/TwoFactorController.php index 3d387bdf3f6a..1707ff2d9e30 100644 --- a/app/Http/Controllers/TwoFactorController.php +++ b/app/Http/Controllers/TwoFactorController.php @@ -72,7 +72,7 @@ class TwoFactorController extends BaseController return response()->json(['message' => ctrans('texts.enabled_two_factor')], 200); } elseif (! $secret || ! $google2fa->verifyKey($secret, $oneTimePassword)) { return response()->json(['message' => ctrans('texts.invalid_one_time_password')], 400); - }elseif (! $user->phone) { + } elseif (! $user->phone) { return response()->json(['message' => ctrans('texts.set_phone_for_two_factor')], 400); } elseif (! $user->isVerified()) { return response()->json(['message' => 'Please confirm your account first'], 400); diff --git a/app/Http/Controllers/UserController.php b/app/Http/Controllers/UserController.php index a1bf7bf17bf5..ad9c9835dd8b 100644 --- a/app/Http/Controllers/UserController.php +++ b/app/Http/Controllers/UserController.php @@ -260,7 +260,7 @@ class UserController extends BaseController /** @var \App\Models\User $logged_in_user */ $logged_in_user = auth()->user(); - $company_user = CompanyUser::where('user_id',$user->id) + $company_user = CompanyUser::where('user_id', $user->id) ->where('company_id', $logged_in_user->companyId()) ->withTrashed() ->first(); diff --git a/app/Http/Middleware/ContactKeyLogin.php b/app/Http/Middleware/ContactKeyLogin.php index ce3711dbccc0..a35c4f351642 100644 --- a/app/Http/Middleware/ContactKeyLogin.php +++ b/app/Http/Middleware/ContactKeyLogin.php @@ -162,7 +162,7 @@ class ContactKeyLogin private function setRedirectPath() { if (auth()->guard('contact')->user()->client->getSetting('enable_client_portal_dashboard') === true) { - return '/client/dashboard'; + return '/client/dashboard'; } elseif (auth()->guard('contact')->user()->company->enabled_modules & PortalComposer::MODULE_INVOICES) { return '/client/invoices'; } elseif (auth()->guard('contact')->user()->company->enabled_modules & PortalComposer::MODULE_RECURRING_INVOICES) { diff --git a/app/Http/Middleware/QueryLogging.php b/app/Http/Middleware/QueryLogging.php index efe0ef707702..2bafda5c41ec 100644 --- a/app/Http/Middleware/QueryLogging.php +++ b/app/Http/Middleware/QueryLogging.php @@ -78,13 +78,11 @@ class QueryLogging if ($request->hasHeader('X-CLIENT-PLATFORM')) { $platform = $request->header('X-CLIENT-PLATFORM'); - } - elseif($request->hasHeader('X-React')){ + } elseif($request->hasHeader('X-React')) { $platform = 'react'; } - if ($request->hasHeader('X-CLIENT-VERSION')) - { + if ($request->hasHeader('X-CLIENT-VERSION')) { $client_version = $request->header('X-CLIENT-VERSION'); } diff --git a/app/Http/Requests/BankTransaction/StoreBankTransactionRequest.php b/app/Http/Requests/BankTransaction/StoreBankTransactionRequest.php index 55deb420ab4a..80ecf6c6b36a 100644 --- a/app/Http/Requests/BankTransaction/StoreBankTransactionRequest.php +++ b/app/Http/Requests/BankTransaction/StoreBankTransactionRequest.php @@ -55,7 +55,7 @@ class StoreBankTransactionRequest extends Request $input['bank_integration_id'] = $this->decodePrimaryKey($input['bank_integration_id']); } - + $this->replace($input); } } diff --git a/app/Http/Requests/Client/BulkClientRequest.php b/app/Http/Requests/Client/BulkClientRequest.php index 31870f0e2752..7cab86724ca5 100644 --- a/app/Http/Requests/Client/BulkClientRequest.php +++ b/app/Http/Requests/Client/BulkClientRequest.php @@ -18,7 +18,7 @@ use Illuminate\Validation\Rule; class BulkClientRequest extends Request { use MakesHash; - + /** * Determine if the user is authorized to make this request. * diff --git a/app/Http/Requests/Client/StoreClientRequest.php b/app/Http/Requests/Client/StoreClientRequest.php index 72afa16e4bc5..f1d4c84518f4 100644 --- a/app/Http/Requests/Client/StoreClientRequest.php +++ b/app/Http/Requests/Client/StoreClientRequest.php @@ -48,8 +48,7 @@ class StoreClientRequest extends Request $rules['documents.*'] = $this->fileValidation(); } elseif ($this->file('documents')) { $rules['documents'] = $this->fileValidation(); - } - else { + } else { $rules['documents'] = 'bail|sometimes|array'; } @@ -133,11 +132,9 @@ class StoreClientRequest extends Request } else { $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; - } - elseif (empty($input['settings']['currency_id']) ?? true) { + } elseif (empty($input['settings']['currency_id']) ?? true) { $input['settings']['currency_id'] = (string) $user->company()->settings->currency_id; } diff --git a/app/Http/Requests/Client/UpdateClientRequest.php b/app/Http/Requests/Client/UpdateClientRequest.php index bf057bf113ea..1378b239ed41 100644 --- a/app/Http/Requests/Client/UpdateClientRequest.php +++ b/app/Http/Requests/Client/UpdateClientRequest.php @@ -105,8 +105,7 @@ class UpdateClientRequest extends Request /* 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'])) { $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; } diff --git a/app/Http/Requests/Company/StoreCompanyRequest.php b/app/Http/Requests/Company/StoreCompanyRequest.php index 7b87278183e6..6db6cce58c75 100644 --- a/app/Http/Requests/Company/StoreCompanyRequest.php +++ b/app/Http/Requests/Company/StoreCompanyRequest.php @@ -59,7 +59,7 @@ class StoreCompanyRequest extends Request $rules['smtp_host'] = 'sometimes|string|nullable'; $rules['smtp_port'] = 'sometimes|integer|nullable'; $rules['smtp_encryption'] = 'sometimes|string'; - $rules['smtp_local_domain'] = 'sometimes|string|nullable'; + $rules['smtp_local_domain'] = 'sometimes|string|nullable'; $rules['smtp_encryption'] = 'sometimes|string|nullable'; $rules['smtp_local_domain'] = 'sometimes|string|nullable'; @@ -100,8 +100,9 @@ class StoreCompanyRequest extends Request $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; + } $this->replace($input); } diff --git a/app/Http/Requests/Company/UpdateCompanyRequest.php b/app/Http/Requests/Company/UpdateCompanyRequest.php index dd4adc5ca8a7..be71818dd8d7 100644 --- a/app/Http/Requests/Company/UpdateCompanyRequest.php +++ b/app/Http/Requests/Company/UpdateCompanyRequest.php @@ -64,7 +64,7 @@ class UpdateCompanyRequest extends Request $rules['smtp_local_domain'] = 'sometimes|string|nullable'; // $rules['smtp_verify_peer'] = 'sometimes|string'; - + if (isset($input['portal_mode']) && ($input['portal_mode'] == 'domain' || $input['portal_mode'] == 'iframe')) { $rules['portal_domain'] = 'bail|nullable|sometimes|url'; } @@ -97,14 +97,14 @@ class UpdateCompanyRequest extends Request unset($input['e_invoice_certificate_passphrase']); } - if(isset($input['smtp_username']) && strlen(str_replace("*","", $input['smtp_username'])) < 2) { + if(isset($input['smtp_username']) && strlen(str_replace("*", "", $input['smtp_username'])) < 2) { unset($input['smtp_username']); } if(isset($input['smtp_password']) && strlen(str_replace("*", "", $input['smtp_password'])) < 2) { unset($input['smtp_password']); } - + if(isset($input['smtp_port'])) { $input['smtp_port'] = (int)$input['smtp_port']; } @@ -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', ' 2) + if(isset($settings['company_logo']) && strlen($settings['company_logo']) > 2) { $settings['company_logo'] = $this->forceScheme($settings['company_logo']); + } if (! $account->isFreeHostedClient()) { return $settings; @@ -173,7 +174,8 @@ class UpdateCompanyRequest extends Request return rtrim($url, '/'); } - private function forceScheme($url){ + private function forceScheme($url) + { return stripos($url, 'http') !== false ? $url : "https://{$url}"; } diff --git a/app/Http/Requests/CompanyUser/UpdateCompanyUserRequest.php b/app/Http/Requests/CompanyUser/UpdateCompanyUserRequest.php index 5c17f5ccd52a..b32cf382ed87 100644 --- a/app/Http/Requests/CompanyUser/UpdateCompanyUserRequest.php +++ b/app/Http/Requests/CompanyUser/UpdateCompanyUserRequest.php @@ -40,8 +40,9 @@ class UpdateCompanyUserRequest extends Request { $input = $this->all(); - if(isset($input['company_user']['user'])) + if(isset($input['company_user']['user'])) { unset($input['company_user']['user']); + } $this->replace($input); } diff --git a/app/Http/Requests/Credit/StoreCreditRequest.php b/app/Http/Requests/Credit/StoreCreditRequest.php index 8d6240c4c3bc..69f24d28ab19 100644 --- a/app/Http/Requests/Credit/StoreCreditRequest.php +++ b/app/Http/Requests/Credit/StoreCreditRequest.php @@ -50,7 +50,7 @@ class StoreCreditRequest extends Request $rules['documents.*'] = $this->fileValidation(); } elseif ($this->file('documents')) { $rules['documents'] = $this->fileValidation(); - }else { + } else { $rules['documents'] = 'bail|sometimes|array'; } @@ -78,7 +78,7 @@ class StoreCreditRequest extends Request $rules['exchange_rate'] = 'bail|sometimes|numeric'; $rules['amount'] = ['sometimes', 'bail', 'numeric', 'max:99999999999999']; -$rules['date'] = 'bail|sometimes|date:Y-m-d'; + $rules['date'] = 'bail|sometimes|date:Y-m-d'; if ($this->invoice_id) { $rules['invoice_id'] = new ValidInvoiceCreditRule(); diff --git a/app/Http/Requests/Credit/UpdateCreditRequest.php b/app/Http/Requests/Credit/UpdateCreditRequest.php index 91a1608fe04c..d7ece562fb6d 100644 --- a/app/Http/Requests/Credit/UpdateCreditRequest.php +++ b/app/Http/Requests/Credit/UpdateCreditRequest.php @@ -52,7 +52,7 @@ class UpdateCreditRequest extends Request $rules['documents.*'] = $this->fileValidation(); } elseif ($this->file('documents')) { $rules['documents'] = $this->fileValidation(); - }else { + } else { $rules['documents'] = 'bail|sometimes|array'; } diff --git a/app/Http/Requests/Expense/UpdateExpenseRequest.php b/app/Http/Requests/Expense/UpdateExpenseRequest.php index ced5c9bd1a70..812449e30b38 100644 --- a/app/Http/Requests/Expense/UpdateExpenseRequest.php +++ b/app/Http/Requests/Expense/UpdateExpenseRequest.php @@ -62,7 +62,7 @@ class UpdateExpenseRequest extends Request public function prepareForValidation() { - + /** @var \App\Models\User $user */ $user = auth()->user(); diff --git a/app/Http/Requests/Invoice/StoreInvoiceRequest.php b/app/Http/Requests/Invoice/StoreInvoiceRequest.php index 54dae6e20ba2..eb0395450ac9 100644 --- a/app/Http/Requests/Invoice/StoreInvoiceRequest.php +++ b/app/Http/Requests/Invoice/StoreInvoiceRequest.php @@ -47,7 +47,7 @@ class StoreInvoiceRequest extends Request $rules['documents.*'] = $this->fileValidation(); } elseif ($this->file('documents')) { $rules['documents'] = $this->fileValidation(); - }else { + } else { $rules['documents'] = 'bail|sometimes|array'; } @@ -80,7 +80,7 @@ class StoreInvoiceRequest extends Request $rules['partial'] = 'bail|sometimes|nullable|numeric|gte:0'; $rules['partial_due_date'] = ['bail', 'sometimes', 'exclude_if:partial,0', Rule::requiredIf(fn () => $this->partial > 0), 'date']; $rules['amount'] = ['sometimes', 'bail', 'numeric', 'max:99999999999999']; - + // $rules['amount'] = ['sometimes', 'bail', 'max:99999999999999']; // $rules['due_date'] = ['bail', 'sometimes', 'nullable', 'after:partial_due_date', Rule::requiredIf(fn () => strlen($this->partial_due_date) > 1), 'date']; @@ -122,8 +122,9 @@ 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)))) { $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'); + } } $this->replace($input); diff --git a/app/Http/Requests/Invoice/UpdateInvoiceRequest.php b/app/Http/Requests/Invoice/UpdateInvoiceRequest.php index 961fcb52ca68..f4ccb51684c9 100644 --- a/app/Http/Requests/Invoice/UpdateInvoiceRequest.php +++ b/app/Http/Requests/Invoice/UpdateInvoiceRequest.php @@ -49,7 +49,7 @@ class UpdateInvoiceRequest extends Request $rules['documents.*'] = $this->fileValidation(); } elseif ($this->file('documents')) { $rules['documents'] = $this->fileValidation(); - }else { + } else { $rules['documents'] = 'bail|sometimes|array'; } diff --git a/app/Http/Requests/Nordigen/ConnectNordigenBankIntegrationRequest.php b/app/Http/Requests/Nordigen/ConnectNordigenBankIntegrationRequest.php index 9852d8e60316..783480a5d188 100644 --- a/app/Http/Requests/Nordigen/ConnectNordigenBankIntegrationRequest.php +++ b/app/Http/Requests/Nordigen/ConnectNordigenBankIntegrationRequest.php @@ -45,8 +45,9 @@ class ConnectNordigenBankIntegrationRequest extends Request $context = $this->getTokenContent(); - if(isset($context['institution_id'])) + if(isset($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'); diff --git a/app/Http/Requests/Payment/StorePaymentRequest.php b/app/Http/Requests/Payment/StorePaymentRequest.php index 10fe585229b5..f3e8e33adfe8 100644 --- a/app/Http/Requests/Payment/StorePaymentRequest.php +++ b/app/Http/Requests/Payment/StorePaymentRequest.php @@ -44,11 +44,11 @@ class StorePaymentRequest extends Request $user = auth()->user(); $rules = [ - 'client_id' => ['bail','required',Rule::exists('clients','id')->where('company_id',$user->company()->id)->where('is_deleted', 0)], + 'client_id' => ['bail','required',Rule::exists('clients', 'id')->where('company_id', $user->company()->id)->where('is_deleted', 0)], 'invoices' => ['bail','sometimes', 'nullable', 'array', new ValidPayableInvoicesRule()], 'invoices.*.amount' => ['bail','required'], - 'invoices.*.invoice_id' => ['bail','required','distinct', new ValidInvoicesRules($this->all()),Rule::exists('invoices','id')->where('company_id', $user->company()->id)->where('client_id', $this->client_id)], - 'credits.*.credit_id' => ['bail','required','distinct', new ValidCreditsRules($this->all()),Rule::exists('credits','id')->where('company_id', $user->company()->id)->where('client_id', $this->client_id)], + 'invoices.*.invoice_id' => ['bail','required','distinct', new ValidInvoicesRules($this->all()),Rule::exists('invoices', 'id')->where('company_id', $user->company()->id)->where('client_id', $this->client_id)], + 'credits.*.credit_id' => ['bail','required','distinct', new ValidCreditsRules($this->all()),Rule::exists('credits', 'id')->where('company_id', $user->company()->id)->where('client_id', $this->client_id)], 'credits.*.amount' => ['bail','required', new CreditsSumRule($this->all())], 'amount' => ['bail', 'numeric', new PaymentAmountsBalanceRule(), 'max:99999999999999'], 'number' => ['bail', 'nullable', Rule::unique('payments')->where('company_id', $user->company()->id)], @@ -59,7 +59,7 @@ class StorePaymentRequest extends Request $rules['documents.*'] = $this->fileValidation(); } elseif ($this->file('documents')) { $rules['documents'] = $this->fileValidation(); - }else { + } else { $rules['documents'] = 'bail|sometimes|array'; } diff --git a/app/Http/Requests/Payment/UpdatePaymentRequest.php b/app/Http/Requests/Payment/UpdatePaymentRequest.php index 3c309af4c6f4..eba4d15c6cf9 100644 --- a/app/Http/Requests/Payment/UpdatePaymentRequest.php +++ b/app/Http/Requests/Payment/UpdatePaymentRequest.php @@ -40,14 +40,14 @@ class UpdatePaymentRequest extends Request /** @var \App\Models\User $user */ $user = auth()->user(); - + $rules = [ 'client_id' => ['sometimes', 'bail', Rule::in([$this->payment->client_id])], 'number' => ['sometimes', 'bail', Rule::unique('payments')->where('company_id', $user->company()->id)->ignore($this->payment->id)], 'invoices' => ['sometimes', 'bail', 'nullable', 'array', new PaymentAppliedValidAmount($this->all())], - 'invoices.*.invoice_id' => ['sometimes','distinct',Rule::exists('invoices','id')->where('company_id', $user->company()->id)->where('client_id', $this->payment->client_id)], + 'invoices.*.invoice_id' => ['sometimes','distinct',Rule::exists('invoices', 'id')->where('company_id', $user->company()->id)->where('client_id', $this->payment->client_id)], 'invoices.*.amount' => ['sometimes','numeric','min:0'], - 'credits.*.credit_id' => ['sometimes','bail','distinct',Rule::exists('credits','id')->where('company_id', $user->company()->id)->where('client_id', $this->payment->client_id)], + 'credits.*.credit_id' => ['sometimes','bail','distinct',Rule::exists('credits', 'id')->where('company_id', $user->company()->id)->where('client_id', $this->payment->client_id)], 'credits.*.amount' => ['required', 'bail'], ]; @@ -55,7 +55,7 @@ class UpdatePaymentRequest extends Request $rules['documents.*'] = $this->fileValidation(); } elseif ($this->file('documents')) { $rules['documents'] = $this->fileValidation(); - }else { + } else { $rules['documents'] = 'bail|sometimes|array'; } diff --git a/app/Http/Requests/Product/StoreProductRequest.php b/app/Http/Requests/Product/StoreProductRequest.php index 23f5339f2575..6984288cf859 100644 --- a/app/Http/Requests/Product/StoreProductRequest.php +++ b/app/Http/Requests/Product/StoreProductRequest.php @@ -35,7 +35,7 @@ class StoreProductRequest extends Request $rules['documents.*'] = $this->fileValidation(); } elseif ($this->file('documents')) { $rules['documents'] = $this->fileValidation(); - }else { + } else { $rules['documents'] = 'bail|sometimes|array'; } diff --git a/app/Http/Requests/Product/UpdateProductRequest.php b/app/Http/Requests/Product/UpdateProductRequest.php index cf82ee6a6aca..39b0b2a16767 100644 --- a/app/Http/Requests/Product/UpdateProductRequest.php +++ b/app/Http/Requests/Product/UpdateProductRequest.php @@ -25,7 +25,7 @@ class UpdateProductRequest extends Request */ public function authorize(): bool { - + /** @var \App\Models\User $user */ $user = auth()->user(); @@ -38,7 +38,7 @@ class UpdateProductRequest extends Request $rules['documents.*'] = $this->fileValidation(); } elseif ($this->file('documents')) { $rules['documents'] = $this->fileValidation(); - }else { + } else { $rules['documents'] = 'bail|sometimes|array'; } diff --git a/app/Http/Requests/Project/StoreProjectRequest.php b/app/Http/Requests/Project/StoreProjectRequest.php index d65baf75bbda..fdaca3b2db6a 100644 --- a/app/Http/Requests/Project/StoreProjectRequest.php +++ b/app/Http/Requests/Project/StoreProjectRequest.php @@ -54,7 +54,7 @@ class StoreProjectRequest extends Request $rules['documents.*'] = $this->fileValidation(); } elseif ($this->file('documents')) { $rules['documents'] = $this->fileValidation(); - }else { + } else { $rules['documents'] = 'bail|sometimes|array'; } @@ -75,8 +75,9 @@ class StoreProjectRequest extends Request $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; + } $this->replace($input); } diff --git a/app/Http/Requests/Project/UpdateProjectRequest.php b/app/Http/Requests/Project/UpdateProjectRequest.php index 77666948ca37..cab826e32ac6 100644 --- a/app/Http/Requests/Project/UpdateProjectRequest.php +++ b/app/Http/Requests/Project/UpdateProjectRequest.php @@ -51,7 +51,7 @@ class UpdateProjectRequest extends Request $rules['documents.*'] = $this->fileValidation(); } elseif ($this->file('documents')) { $rules['documents'] = $this->fileValidation(); - }else { + } else { $rules['documents'] = 'bail|sometimes|array'; } @@ -75,7 +75,7 @@ class UpdateProjectRequest extends Request if (array_key_exists('color', $input) && is_null($input['color'])) { $input['color'] = ''; } - + if(array_key_exists('budgeted_hours', $input) && empty($input['budgeted_hours'])) { $input['budgeted_hours'] = 0; } diff --git a/app/Http/Requests/PurchaseOrder/StorePurchaseOrderRequest.php b/app/Http/Requests/PurchaseOrder/StorePurchaseOrderRequest.php index 50ff98993f7a..3805ed73a9e3 100644 --- a/app/Http/Requests/PurchaseOrder/StorePurchaseOrderRequest.php +++ b/app/Http/Requests/PurchaseOrder/StorePurchaseOrderRequest.php @@ -50,7 +50,7 @@ class StorePurchaseOrderRequest extends Request $rules['number'] = ['nullable', Rule::unique('purchase_orders')->where('company_id', $user->company()->id)]; -$rules['discount'] = 'sometimes|numeric|max:99999999999999'; + $rules['discount'] = 'sometimes|numeric|max:99999999999999'; $rules['is_amount_discount'] = ['boolean']; $rules['line_items'] = 'array'; diff --git a/app/Http/Requests/PurchaseOrder/UpdatePurchaseOrderRequest.php b/app/Http/Requests/PurchaseOrder/UpdatePurchaseOrderRequest.php index c0ab87926983..5ae69e8d1598 100644 --- a/app/Http/Requests/PurchaseOrder/UpdatePurchaseOrderRequest.php +++ b/app/Http/Requests/PurchaseOrder/UpdatePurchaseOrderRequest.php @@ -53,14 +53,14 @@ class UpdatePurchaseOrderRequest extends Request $rules['line_items'] = 'array'; -$rules['discount'] = 'sometimes|numeric|max:99999999999999'; + $rules['discount'] = 'sometimes|numeric|max:99999999999999'; $rules['is_amount_discount'] = ['boolean']; if ($this->file('documents') && is_array($this->file('documents'))) { $rules['documents.*'] = $this->fileValidation(); } elseif ($this->file('documents')) { $rules['documents'] = $this->fileValidation(); - }else { + } else { $rules['documents'] = 'bail|sometimes|array'; } diff --git a/app/Http/Requests/Quote/StoreQuoteRequest.php b/app/Http/Requests/Quote/StoreQuoteRequest.php index c8d0a02035ae..f1e7ba47b74a 100644 --- a/app/Http/Requests/Quote/StoreQuoteRequest.php +++ b/app/Http/Requests/Quote/StoreQuoteRequest.php @@ -43,13 +43,13 @@ class StoreQuoteRequest extends Request $rules = []; - $rules['client_id'] = ['required', 'bail', Rule::exists('clients','id')->where('company_id', $user->company()->id)]; + $rules['client_id'] = ['required', 'bail', Rule::exists('clients', 'id')->where('company_id', $user->company()->id)]; if ($this->file('documents') && is_array($this->file('documents'))) { $rules['documents.*'] = $this->fileValidation(); } elseif ($this->file('documents')) { $rules['documents'] = $this->fileValidation(); - }else { + } else { $rules['documents'] = 'bail|sometimes|array'; } @@ -77,7 +77,7 @@ class StoreQuoteRequest extends Request { /** @var \App\Models\User $user */ $user = auth()->user(); - + $input = $this->all(); $input = $this->decodePrimaryKeys($input); @@ -98,12 +98,13 @@ class StoreQuoteRequest extends Request $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'); + } - 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']); - $valid_days = ($client && strlen($client->getSetting('valid_until')) >= 1) ? $client->getSetting('valid_until') : 7; + $valid_days = ($client && strlen($client->getSetting('valid_until')) >= 1) ? $client->getSetting('valid_until') : 7; $input['due_date'] = \Carbon\Carbon::parse($input['date'])->addDays($valid_days)->format('Y-m-d'); } diff --git a/app/Http/Requests/Quote/UpdateQuoteRequest.php b/app/Http/Requests/Quote/UpdateQuoteRequest.php index 4f9986df2e30..ce8c6eeeb273 100644 --- a/app/Http/Requests/Quote/UpdateQuoteRequest.php +++ b/app/Http/Requests/Quote/UpdateQuoteRequest.php @@ -46,7 +46,7 @@ class UpdateQuoteRequest extends Request $rules['documents.*'] = $this->fileValidation(); } elseif ($this->file('documents')) { $rules['documents'] = $this->fileValidation(); - }else { + } else { $rules['documents'] = 'bail|sometimes|array'; } diff --git a/app/Http/Requests/RecurringInvoice/StoreRecurringInvoiceRequest.php b/app/Http/Requests/RecurringInvoice/StoreRecurringInvoiceRequest.php index 5b56080959e0..7dc6ef5fdc7e 100644 --- a/app/Http/Requests/RecurringInvoice/StoreRecurringInvoiceRequest.php +++ b/app/Http/Requests/RecurringInvoice/StoreRecurringInvoiceRequest.php @@ -49,7 +49,7 @@ class StoreRecurringInvoiceRequest extends Request $rules['documents.*'] = $this->fileValidation(); } elseif ($this->file('documents')) { $rules['documents'] = $this->fileValidation(); - }else { + } else { $rules['documents'] = 'bail|sometimes|array'; } diff --git a/app/Http/Requests/RecurringInvoice/UpdateRecurringInvoiceRequest.php b/app/Http/Requests/RecurringInvoice/UpdateRecurringInvoiceRequest.php index 9e6238570955..db70ca922927 100644 --- a/app/Http/Requests/RecurringInvoice/UpdateRecurringInvoiceRequest.php +++ b/app/Http/Requests/RecurringInvoice/UpdateRecurringInvoiceRequest.php @@ -48,7 +48,7 @@ class UpdateRecurringInvoiceRequest extends Request $rules['documents.*'] = $this->fileValidation(); } elseif ($this->file('documents')) { $rules['documents'] = $this->fileValidation(); - }else { + } else { $rules['documents'] = 'bail|sometimes|array'; } diff --git a/app/Http/Requests/Report/GenericReportRequest.php b/app/Http/Requests/Report/GenericReportRequest.php index 1ebd60dc4321..c9d467423fca 100644 --- a/app/Http/Requests/Report/GenericReportRequest.php +++ b/app/Http/Requests/Report/GenericReportRequest.php @@ -68,8 +68,8 @@ class GenericReportRequest extends Request $input['user_id'] = auth()->user()->id; - if(!$this->checkAuthority()){ - $input['date_range'] = ''; + if(!$this->checkAuthority()) { + $input['date_range'] = ''; $input['start_date'] = ''; $input['end_date'] = ''; $input['send_email'] = true; @@ -85,7 +85,7 @@ class GenericReportRequest extends Request /** @var \App\Models\User $user */ $user = auth()->user(); - + return $user->isAdmin() || $user->hasPermission('view_reports'); } diff --git a/app/Http/Requests/Report/ProductSalesReportRequest.php b/app/Http/Requests/Report/ProductSalesReportRequest.php index d386f89b6b0f..aed50d82fb4d 100644 --- a/app/Http/Requests/Report/ProductSalesReportRequest.php +++ b/app/Http/Requests/Report/ProductSalesReportRequest.php @@ -34,7 +34,7 @@ class ProductSalesReportRequest extends Request public function rules() { - + /** @var \App\Models\User $user */ $user = auth()->user(); @@ -82,8 +82,8 @@ class ProductSalesReportRequest extends Request /** @var \App\Models\User $user */ $user = auth()->user(); - - if(Ninja::isHosted() && $user->account->isFreeHostedClient()){ + + if(Ninja::isHosted() && $user->account->isFreeHostedClient()) { $this->error_message = ctrans('texts.upgrade_to_view_reports'); return false; } diff --git a/app/Http/Requests/Report/ProfitLossRequest.php b/app/Http/Requests/Report/ProfitLossRequest.php index a62417d8c369..908abc092ecb 100644 --- a/app/Http/Requests/Report/ProfitLossRequest.php +++ b/app/Http/Requests/Report/ProfitLossRequest.php @@ -17,7 +17,6 @@ use Illuminate\Auth\Access\AuthorizationException; class ProfitLossRequest extends Request { - private string $error_message = ''; /** @@ -54,14 +53,14 @@ class ProfitLossRequest extends Request $this->replace($input); } - private function checkAuthority() + private function checkAuthority() { $this->error_message = ctrans('texts.authorization_failure'); /** @var \App\Models\User $user */ $user = auth()->user(); - - if(Ninja::isHosted() && $user->account->isFreeHostedClient()){ + + if(Ninja::isHosted() && $user->account->isFreeHostedClient()) { $this->error_message = ctrans('texts.upgrade_to_view_reports'); return false; } diff --git a/app/Http/Requests/Report/ReportPreviewRequest.php b/app/Http/Requests/Report/ReportPreviewRequest.php index 7757e57746a7..869f34cd7d17 100644 --- a/app/Http/Requests/Report/ReportPreviewRequest.php +++ b/app/Http/Requests/Report/ReportPreviewRequest.php @@ -45,8 +45,8 @@ class ReportPreviewRequest extends Request /** @var \App\Models\User $user */ $user = auth()->user(); - - if(Ninja::isHosted() && $user->account->isFreeHostedClient()){ + + if(Ninja::isHosted() && $user->account->isFreeHostedClient()) { $this->error_message = ctrans('texts.upgrade_to_view_reports'); return false; } diff --git a/app/Http/Requests/Request.php b/app/Http/Requests/Request.php index 3c42d83dc980..9617f48ab364 100644 --- a/app/Http/Requests/Request.php +++ b/app/Http/Requests/Request.php @@ -33,11 +33,12 @@ class Request extends FormRequest 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; - + } public function globalRules($rules) @@ -46,9 +47,10 @@ class Request extends FormRequest foreach ($this->all() as $key => $value) { - if($key == 'user') + if($key == 'user') { continue; - + } + if (method_exists($this, $key)) { $merge_rules = $this->{$key}($rules); } diff --git a/app/Http/Requests/Smtp/CheckSmtpRequest.php b/app/Http/Requests/Smtp/CheckSmtpRequest.php index df9cc98a360a..3a4ab408a579 100644 --- a/app/Http/Requests/Smtp/CheckSmtpRequest.php +++ b/app/Http/Requests/Smtp/CheckSmtpRequest.php @@ -24,7 +24,7 @@ class CheckSmtpRequest extends Request { /** @var \App\Models\User $user */ $user = auth()->user(); - + return $user->isAdmin(); } @@ -44,28 +44,27 @@ class CheckSmtpRequest extends Request } public function prepareForValidation() - { - + { + /** @var \App\Models\User $user */ $user = auth()->user(); $company = $user->company(); $input = $this->input(); - if(isset($input['smtp_username']) && $input['smtp_username'] == '********'){ + if(isset($input['smtp_username']) && $input['smtp_username'] == '********') { // unset($input['smtp_username']); $input['smtp_username'] = $company->smtp_username; } - if(isset($input['smtp_password'])&& $input['smtp_password'] == '********'){ + if(isset($input['smtp_password']) && $input['smtp_password'] == '********') { // unset($input['smtp_password']); $input['smtp_password'] = $company->smtp_password; } - 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; } diff --git a/app/Http/Requests/Task/StoreTaskRequest.php b/app/Http/Requests/Task/StoreTaskRequest.php index b9726331d3f7..f61bc4267a23 100644 --- a/app/Http/Requests/Task/StoreTaskRequest.php +++ b/app/Http/Requests/Task/StoreTaskRequest.php @@ -82,7 +82,7 @@ class StoreTaskRequest extends Request $rules['documents.*'] = $this->fileValidation(); } elseif ($this->file('documents')) { $rules['documents'] = $this->fileValidation(); - }else { + } else { $rules['documents'] = 'bail|sometimes|array'; } diff --git a/app/Http/Requests/Task/UpdateTaskRequest.php b/app/Http/Requests/Task/UpdateTaskRequest.php index 11bd12ee1d92..85b2c4de955b 100644 --- a/app/Http/Requests/Task/UpdateTaskRequest.php +++ b/app/Http/Requests/Task/UpdateTaskRequest.php @@ -88,7 +88,7 @@ class UpdateTaskRequest extends Request $rules['documents.*'] = $this->fileValidation(); } elseif ($this->file('documents')) { $rules['documents'] = $this->fileValidation(); - }else { + } else { $rules['documents'] = 'bail|sometimes|array'; } diff --git a/app/Http/Requests/TaskScheduler/StoreSchedulerRequest.php b/app/Http/Requests/TaskScheduler/StoreSchedulerRequest.php index 1825c9b2e34a..313b1926837f 100644 --- a/app/Http/Requests/TaskScheduler/StoreSchedulerRequest.php +++ b/app/Http/Requests/TaskScheduler/StoreSchedulerRequest.php @@ -27,7 +27,7 @@ class StoreSchedulerRequest extends Request 'logged', 'partial', 'applied', - 'active', + 'active', 'paused', 'completed', 'approved', diff --git a/app/Http/Requests/TaskScheduler/UpdateSchedulerRequest.php b/app/Http/Requests/TaskScheduler/UpdateSchedulerRequest.php index b3691fc717c0..f55cbe64e567 100644 --- a/app/Http/Requests/TaskScheduler/UpdateSchedulerRequest.php +++ b/app/Http/Requests/TaskScheduler/UpdateSchedulerRequest.php @@ -27,7 +27,7 @@ class UpdateSchedulerRequest extends Request 'logged', 'partial', 'applied', - 'active', + 'active', 'paused', 'completed', 'approved', @@ -92,8 +92,8 @@ class UpdateSchedulerRequest extends Request if(isset($input['parameters']['status'])) { - -$task_statuses = []; + + $task_statuses = []; if(isset($input['parameters']['report_name']) && $input['parameters']['report_name'] == 'task') { $task_statuses = array_diff(explode(",", $input['parameters']['status']), $this->client_statuses); diff --git a/app/Http/Requests/User/StoreUserRequest.php b/app/Http/Requests/User/StoreUserRequest.php index c3e87fe890a2..f47b1bd1a217 100644 --- a/app/Http/Requests/User/StoreUserRequest.php +++ b/app/Http/Requests/User/StoreUserRequest.php @@ -96,7 +96,7 @@ class StoreUserRequest extends Request } $input['id'] = null; - + $this->replace($input); } diff --git a/app/Http/Requests/Vendor/StoreVendorRequest.php b/app/Http/Requests/Vendor/StoreVendorRequest.php index d3af8fb39668..96006df89bd2 100644 --- a/app/Http/Requests/Vendor/StoreVendorRequest.php +++ b/app/Http/Requests/Vendor/StoreVendorRequest.php @@ -64,7 +64,7 @@ class StoreVendorRequest extends Request $rules['documents.*'] = $this->fileValidation(); } elseif ($this->file('documents')) { $rules['documents'] = $this->fileValidation(); - }else { + } else { $rules['documents'] = 'bail|sometimes|array'; } diff --git a/app/Http/Requests/Vendor/UpdateVendorRequest.php b/app/Http/Requests/Vendor/UpdateVendorRequest.php index 53e5ee2765b6..398492d84aa8 100644 --- a/app/Http/Requests/Vendor/UpdateVendorRequest.php +++ b/app/Http/Requests/Vendor/UpdateVendorRequest.php @@ -65,7 +65,7 @@ class UpdateVendorRequest extends Request $rules['documents.*'] = $this->fileValidation(); } elseif ($this->file('documents')) { $rules['documents'] = $this->fileValidation(); - }else { + } else { $rules['documents'] = 'bail|sometimes|array'; } diff --git a/app/Http/Requests/Webhook/StoreWebhookRequest.php b/app/Http/Requests/Webhook/StoreWebhookRequest.php index a116aae65fd7..c0a3c6632b72 100644 --- a/app/Http/Requests/Webhook/StoreWebhookRequest.php +++ b/app/Http/Requests/Webhook/StoreWebhookRequest.php @@ -45,7 +45,7 @@ class StoreWebhookRequest extends Request if (!isset($input['rest_method'])) { $input['rest_method'] = 'post'; } - + $this->replace($input); } } diff --git a/app/Http/ValidationRules/Design/TwigLint.php b/app/Http/ValidationRules/Design/TwigLint.php index f65fc328fc3c..187fd706b51e 100644 --- a/app/Http/ValidationRules/Design/TwigLint.php +++ b/app/Http/ValidationRules/Design/TwigLint.php @@ -37,8 +37,6 @@ class TwigLint implements ValidationRule } - + } } - - diff --git a/app/Http/ValidationRules/Invoice/LockedInvoiceRule.php b/app/Http/ValidationRules/Invoice/LockedInvoiceRule.php index 169df7757f15..cb0dcde42137 100644 --- a/app/Http/ValidationRules/Invoice/LockedInvoiceRule.php +++ b/app/Http/ValidationRules/Invoice/LockedInvoiceRule.php @@ -69,10 +69,11 @@ class LockedInvoiceRule implements Rule return true; - //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': - 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 true; default: diff --git a/app/Import/Providers/BaseImport.php b/app/Import/Providers/BaseImport.php index 38294e82a6f4..94670d2e9c08 100644 --- a/app/Import/Providers/BaseImport.php +++ b/app/Import/Providers/BaseImport.php @@ -255,8 +255,9 @@ class BaseImport unset($record['']); - if(!is_array($record)) + if(!is_array($record)) { continue; + } try { $entity = $this->transformer->transform($record); @@ -313,7 +314,7 @@ class BaseImport $count = 0; foreach ($data as $key => $record) { - + if(!is_array($record)) { continue; } @@ -380,7 +381,7 @@ class BaseImport $invoices = $this->groupInvoices($invoices, $invoice_number_key); foreach ($invoices as $raw_invoice) { - + if(!is_array($raw_invoice)) { continue; } @@ -472,7 +473,7 @@ class BaseImport foreach ($tasks as $raw_task) { $task_data = []; - + if(!is_array($raw_task)) { continue; } @@ -545,7 +546,7 @@ class BaseImport $invoices = $this->groupInvoices($invoices, $invoice_number_key); foreach ($invoices as $raw_invoice) { - + if(!is_array($raw_invoice)) { continue; } @@ -765,7 +766,7 @@ class BaseImport $quotes = $this->groupInvoices($quotes, $quote_number_key); foreach ($quotes as $raw_quote) { - + if(!is_array($raw_quote)) { continue; } @@ -976,5 +977,5 @@ class BaseImport return $data; } - + } diff --git a/app/Import/Providers/Wave.php b/app/Import/Providers/Wave.php index 8fdc56f984d9..89c3ef9931a2 100644 --- a/app/Import/Providers/Wave.php +++ b/app/Import/Providers/Wave.php @@ -232,7 +232,7 @@ class Wave extends BaseImport implements ImportInterface $expenses = $this->groupExpenses($data); foreach ($expenses as $raw_expense) { - + if(!is_array($raw_expense)) { continue; } diff --git a/app/Import/Transformer/BaseTransformer.php b/app/Import/Transformer/BaseTransformer.php index 4c6af4aee64d..32a333f66e98 100644 --- a/app/Import/Transformer/BaseTransformer.php +++ b/app/Import/Transformer/BaseTransformer.php @@ -65,7 +65,7 @@ class BaseTransformer return $parsed_date; } } - + public function parseDateOrNull($data, $field) { $date = &$data[$field]; @@ -345,10 +345,10 @@ class BaseTransformer { if (array_key_exists($field, $data)) { return Number::parseFloat($data[$field]); - } - + } + return 0; - + } /** diff --git a/app/Import/Transformer/Invoice2Go/InvoiceTransformer.php b/app/Import/Transformer/Invoice2Go/InvoiceTransformer.php index b3e7fc46155d..cf7771d63740 100644 --- a/app/Import/Transformer/Invoice2Go/InvoiceTransformer.php +++ b/app/Import/Transformer/Invoice2Go/InvoiceTransformer.php @@ -91,7 +91,7 @@ class InvoiceTransformer extends BaseTransformer ]; $addresses = $this->harvestAddresses($invoice_data); - + $transformed['client'] = array_merge($transformed['client'], $addresses); } @@ -102,17 +102,15 @@ class InvoiceTransformer extends BaseTransformer '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'] = [ [ 'date' => $this->parseDate($invoice_data['DatePaid']), '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'] = [ [ 'date' => isset($invoice_data['DatePaid']) ? $this->parseDate($invoice_data['DatePaid']) : ($this->parseDate($invoice_data['DocumentDate']) ?? now()->format('Y-m-d')), @@ -125,33 +123,34 @@ class InvoiceTransformer extends BaseTransformer } - private function harvestAddresses($invoice_data) { + private function harvestAddresses($invoice_data) + { $address = $invoice_data['DocumentRecipientAddress']; $lines = explode("\n", $address); $billing_address = []; - if(count($lines) == 2){ + if(count($lines) == 2) { $billing_address['address1'] = $lines[0]; - + $parts = explode(",", $lines[1]); - if(count($parts) == 3){ + if(count($parts) == 3) { $billing_address['city'] = $parts[0]; $billing_address['state'] = $parts[1]; $billing_address['postal_code'] = $parts[2]; } - + } - $shipaddress = $invoice_data['ShipAddress'] ?? ''; + $shipaddress = $invoice_data['ShipAddress'] ?? ''; $shipping_address = []; $lines = explode("\n", $shipaddress); if(count($lines) == 2) { $shipping_address['address1'] = $lines[0]; - + $parts = explode(",", $lines[1]); if(count($parts) == 3) { @@ -188,7 +187,7 @@ class InvoiceTransformer extends BaseTransformer private function harvestLineItems(array $invoice_data): array { - + $default_data = [ [ @@ -198,8 +197,8 @@ class InvoiceTransformer extends BaseTransformer 'is_amount_discount' => false, ], ]; - - if(!isset($invoice_data['Items'])){ + + if(!isset($invoice_data['Items'])) { return $default_data; } @@ -208,15 +207,14 @@ class InvoiceTransformer extends BaseTransformer $line_items = []; - foreach($processed as $item) - { + foreach($processed as $item) { $_item['cost'] = $item['unit_price']; $_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']; $_item['is_amount_discount'] = $item['discount_type'] == 'percentage' ? false : true; $_item['product_key'] = $item['code'] ?? ''; $_item['notes'] = $item['description'] ?? ''; - + $_item = $this->parseTaxes($_item, $item); $this->is_amount_discount = $_item['is_amount_discount']; @@ -230,18 +228,19 @@ class InvoiceTransformer extends BaseTransformer 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; - + } + $ninja_item['tax_name1'] = 'Tax'; $ninja_item['tax_rate1'] = $i2g_item['applied_taxes']['rate']; return $ninja_item; } - - function parseCsvWithNestedCsv($csvString, $delimiter = ',', $enclosure = '"', $lineEnding = ';') + + public function parseCsvWithNestedCsv($csvString, $delimiter = ',', $enclosure = '"', $lineEnding = ';') { // Regular expression to find nested CSVs $nestedCsvPattern = '/"([^"]*(?:""[^"]*)*)"/'; diff --git a/app/Jobs/Bank/MatchBankTransactions.php b/app/Jobs/Bank/MatchBankTransactions.php index 2dabff1e05c7..321f0aafc428 100644 --- a/app/Jobs/Bank/MatchBankTransactions.php +++ b/app/Jobs/Bank/MatchBankTransactions.php @@ -289,7 +289,7 @@ class MatchBankTransactions implements ShouldQueue private function createPayment($invoices, float $amount): void { - + $this->attachable_invoices = []; $this->available_balance = $amount; diff --git a/app/Jobs/Bank/ProcessBankTransactionsNordigen.php b/app/Jobs/Bank/ProcessBankTransactionsNordigen.php index 8ff86efd14a5..cc0d807e370c 100644 --- a/app/Jobs/Bank/ProcessBankTransactionsNordigen.php +++ b/app/Jobs/Bank/ProcessBankTransactionsNordigen.php @@ -86,7 +86,7 @@ class ProcessBankTransactionsNordigen implements ShouldQueue $this->bank_integration->company->notification(new GenericNinjaAdminNotification($content))->ninja(); sleep(5); - + throw $e; } if (!$this->nordigen_account) { diff --git a/app/Jobs/Brevo/ProcessBrevoWebhook.php b/app/Jobs/Brevo/ProcessBrevoWebhook.php index a4626b1bf89a..c8704cf163dd 100644 --- a/app/Jobs/Brevo/ProcessBrevoWebhook.php +++ b/app/Jobs/Brevo/ProcessBrevoWebhook.php @@ -36,7 +36,10 @@ use Turbo124\Beacon\Facades\LightLogs; class ProcessBrevoWebhook implements ShouldQueue { - use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; + use Dispatchable; + use InteractsWithQueue; + use Queueable; + use SerializesModels; public $tries = 1; diff --git a/app/Jobs/Company/CompanyImport.php b/app/Jobs/Company/CompanyImport.php index c6a1054f2eaa..3a60741a82d9 100644 --- a/app/Jobs/Company/CompanyImport.php +++ b/app/Jobs/Company/CompanyImport.php @@ -350,11 +350,13 @@ class CompanyImport implements ShouldQueue } } - if(file_exists($tmp_file)) + if(file_exists($tmp_file)) { unlink($tmp_file); + } - if(Storage::exists($this->file_location)) + if(Storage::exists($this->file_location)) { unlink(Storage::path($this->file_location)); + } } // @@ -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', 'email_style_custom); $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}); } diff --git a/app/Jobs/Credit/ApplyCreditPayment.php b/app/Jobs/Credit/ApplyCreditPayment.php index d2ebc361ef35..e9aab7c4a63e 100644 --- a/app/Jobs/Credit/ApplyCreditPayment.php +++ b/app/Jobs/Credit/ApplyCreditPayment.php @@ -78,7 +78,7 @@ class ApplyCreditPayment implements ShouldQueue $item->cost = $this->amount * -1; $item->notes = "{$item_date} - " . ctrans('texts.credit_payment', ['invoice_number' => $invoice_numbers]) . " ". Number::formatMoney($this->amount, $this->payment->client); $item->type_id = "1"; - + $line_items = $this->credit->line_items; $line_items[] = $item; $this->credit->line_items = $line_items; @@ -106,7 +106,7 @@ class ApplyCreditPayment implements ShouldQueue ->client ->service() ->adjustCreditBalance($this->amount * -1) - ->save(); + ->save(); /* Update Payment Applied Amount*/ $this->payment->save(); diff --git a/app/Jobs/Cron/SubscriptionCron.php b/app/Jobs/Cron/SubscriptionCron.php index e9d0d32b4838..1c4b7dbc16ad 100644 --- a/app/Jobs/Cron/SubscriptionCron.php +++ b/app/Jobs/Cron/SubscriptionCron.php @@ -44,11 +44,11 @@ class SubscriptionCron if (! config('ninja.db.multi_db_enabled')) { - nlog('Subscription Cron '. now()->toDateTimeString()); + nlog('Subscription Cron '. now()->toDateTimeString()); + + $this->timezoneAware(); - $this->timezoneAware(); - } else { //multiDB environment, need to foreach (MultiDB::$dbs as $db) { @@ -65,7 +65,7 @@ class SubscriptionCron //Requires the crons to be updated and set to hourly @ 00:01 private function timezoneAware() { - $grouped_company_ids = + $grouped_company_ids = Invoice::select('company_id') ->where('is_deleted', 0) @@ -77,7 +77,7 @@ class SubscriptionCron ->whereNotNull('subscription_id') ->groupBy('company_id') ->cursor() - ->each(function ($company_id){ + ->each(function ($company_id) { /** @var \App\Models\Company $company */ $company = Company::find($company_id); @@ -111,7 +111,7 @@ class SubscriptionCron $this->sendLoad($subscription, $body); //This will send the notification daily. //We'll need to handle this by performing some action on the invoice to either archive it or delete it? - }); + }); } diff --git a/app/Jobs/Cron/UpdateCalculatedFields.php b/app/Jobs/Cron/UpdateCalculatedFields.php index 6dde0e91b186..b25d88fa56f3 100644 --- a/app/Jobs/Cron/UpdateCalculatedFields.php +++ b/app/Jobs/Cron/UpdateCalculatedFields.php @@ -68,7 +68,7 @@ class UpdateCalculatedFields $project->current_hours = $this->calculateDuration($project); $project->save(); }); - + //Clean password resets table \DB::connection($db)->table('password_resets')->where('created_at', '<', now()->subHour())->delete(); diff --git a/app/Jobs/Document/CopyDocs.php b/app/Jobs/Document/CopyDocs.php index 98e5003a8d21..e0f091b3012c 100644 --- a/app/Jobs/Document/CopyDocs.php +++ b/app/Jobs/Document/CopyDocs.php @@ -32,7 +32,7 @@ class CopyDocs implements ShouldQueue public $tries = 1; /** - * + * */ public function __construct(private \Illuminate\Support\Collection $document_ids, private $entity, private string $db) { @@ -49,14 +49,14 @@ class CopyDocs implements ShouldQueue Document::whereIn('id', $this->document_ids) ->where('company_id', $this->entity->company_id) - ->each(function ($document){ + ->each(function ($document) { $file = $document->getFile(); - - $extension = pathinfo($document->name, PATHINFO_EXTENSION); + + $extension = pathinfo($document->name, PATHINFO_EXTENSION); $new_hash = \Illuminate\Support\Str::random(32) . "." . $extension; - + Storage::disk($document->disk)->put( "{$this->entity->company->company_key}/documents/{$new_hash}", $file, @@ -76,7 +76,7 @@ class CopyDocs implements ShouldQueue $new_doc->width = $document->width; $new_doc->height = $document->height; $new_doc->is_public = $document->is_public; - + $this->entity->documents()->save($new_doc); }); diff --git a/app/Jobs/EDocument/CreateEDocument.php b/app/Jobs/EDocument/CreateEDocument.php index c2e0b5a16f25..103ab05d9d2d 100644 --- a/app/Jobs/EDocument/CreateEDocument.php +++ b/app/Jobs/EDocument/CreateEDocument.php @@ -59,13 +59,14 @@ class CreateEDocument implements ShouldQueue App::setLocale($settings_entity->locale()); /* Set customized translations _NOW_ */ - if($this->document->client ?? false) + if($this->document->client ?? false) { $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_quote_type = strlen($settings_entity->getSetting('e_quote_type')) > 2 ? $settings_entity->getSetting('e_quote_type') : "OrderX_Extended"; - if ($this->document instanceof Invoice){ + if ($this->document instanceof Invoice) { switch ($e_document_type) { case "FACT1": return (new RoEInvoice($this->document))->generateXml(); @@ -95,9 +96,8 @@ class CreateEDocument implements ShouldQueue return $this->returnObject ? $zugferd : $zugferd->getXml(); } - } - elseif ($this->document instanceof Quote){ - switch ($e_quote_type){ + } elseif ($this->document instanceof Quote) { + switch ($e_quote_type) { case "OrderX_Basic": case "OrderX_Comfort": case "OrderX_Extended": @@ -107,9 +107,8 @@ class CreateEDocument implements ShouldQueue $orderx = (new OrderXDocument($this->document))->run(); return $this->returnObject ? $orderx->orderxdocument : $orderx->getXml(); } - } - elseif ($this->document instanceof PurchaseOrder){ - switch ($e_quote_type){ + } elseif ($this->document instanceof PurchaseOrder) { + switch ($e_quote_type) { case "OrderX_Basic": case "OrderX_Comfort": case "OrderX_Extended": @@ -119,8 +118,7 @@ class CreateEDocument implements ShouldQueue $orderx = (new OrderXDocument($this->document))->run(); return $this->returnObject ? $orderx->orderxdocument : $orderx->getXml(); } - } - elseif ($this->document instanceof Credit) { + } elseif ($this->document instanceof Credit) { switch ($e_document_type) { case "EN16931": case "XInvoice_3_0": @@ -138,8 +136,7 @@ class CreateEDocument implements ShouldQueue $zugferd = (new ZugferdEDokument($this->document))->run(); return $this->returnObject ? $zugferd : $zugferd->getXml(); } - } - else{ + } else { return ""; } } diff --git a/app/Jobs/EDocument/MergeEDocument.php b/app/Jobs/EDocument/MergeEDocument.php index 08eaf171124a..bf92e5fdcc97 100644 --- a/app/Jobs/EDocument/MergeEDocument.php +++ b/app/Jobs/EDocument/MergeEDocument.php @@ -35,7 +35,7 @@ class MergeEDocument implements ShouldQueue $e_document_type = strlen($settings_entity->getSetting('e_invoice_type')) > 2 ? $settings_entity->getSetting('e_invoice_type') : "XInvoice_3_0"; - if ($this->document instanceof Invoice){ + if ($this->document instanceof Invoice) { switch ($e_document_type) { case "EN16931": case "XInvoice_3_0": @@ -53,10 +53,8 @@ class MergeEDocument implements ShouldQueue return $this->pdf_file; } - } - else{ + } else { return $this->pdf_file; } } } - diff --git a/app/Jobs/Entity/CreateRawPdf.php b/app/Jobs/Entity/CreateRawPdf.php index 13e082215503..aa10bdf019d9 100644 --- a/app/Jobs/Entity/CreateRawPdf.php +++ b/app/Jobs/Entity/CreateRawPdf.php @@ -113,7 +113,7 @@ class CreateRawPdf } catch (\Exception) { throw new FilePermissionsFailure('Unable to generate the raw PDF'); } - if ($this->entity_string == "invoice" && $this->entity->client->getSetting("merge_e_invoice_to_pdf")){ + if ($this->entity_string == "invoice" && $this->entity->client->getSetting("merge_e_invoice_to_pdf")) { $pdf = (new MergeEDocument($this->entity, $pdf))->handle(); } return $pdf; diff --git a/app/Jobs/Ledger/ClientLedgerBalanceUpdate.php b/app/Jobs/Ledger/ClientLedgerBalanceUpdate.php index 7a8724ce15c8..a8171e517e5f 100644 --- a/app/Jobs/Ledger/ClientLedgerBalanceUpdate.php +++ b/app/Jobs/Ledger/ClientLedgerBalanceUpdate.php @@ -47,7 +47,7 @@ class ClientLedgerBalanceUpdate implements ShouldQueue */ public function handle(): void { - + MultiDB::setDb($this->company->db); CompanyLedger::query() diff --git a/app/Jobs/Mail/NinjaMailerJob.php b/app/Jobs/Mail/NinjaMailerJob.php index 841f6207fc80..dbcf47bf2068 100644 --- a/app/Jobs/Mail/NinjaMailerJob.php +++ b/app/Jobs/Mail/NinjaMailerJob.php @@ -96,7 +96,7 @@ class NinjaMailerJob implements ShouldQueue } $this->nmo->mailable->replyTo($this->nmo->settings->reply_to_email, $reply_to_name); - } elseif (isset ($this->nmo->invitation->user)) { + } elseif (isset($this->nmo->invitation->user)) { $this->nmo->mailable->replyTo($this->nmo->invitation->user->email, $this->nmo->invitation->user->present()->name()); } else { $this->nmo->mailable->replyTo($this->company->owner()->email, $this->company->owner()->present()->name()); @@ -153,34 +153,30 @@ class NinjaMailerJob implements ShouldQueue LightLogs::create(new EmailSuccess($this->nmo->company->company_key, $this->nmo->mailable->subject)) ->send(); - } - catch (\Symfony\Component\Mime\Exception\RfcComplianceException $e) { + } catch (\Symfony\Component\Mime\Exception\RfcComplianceException $e) { nlog("Mailer failed with a Logic Exception {$e->getMessage()}"); $this->fail(); $this->cleanUpMailers(); $this->logMailError($e->getMessage(), $this->company->clients()->first()); return; - } - catch (\Symfony\Component\Mime\Exception\LogicException $e) { + } catch (\Symfony\Component\Mime\Exception\LogicException $e) { nlog("Mailer failed with a Logic Exception {$e->getMessage()}"); $this->fail(); $this->cleanUpMailers(); $this->logMailError($e->getMessage(), $this->company->clients()->first()); return; - } - catch(\Google\Service\Exception $e){ + } catch(\Google\Service\Exception $e) { if ($e->getCode() == '429') { - + $message = "Google rate limiting triggered, we are queueing based on Gmail requirements."; $this->logMailError($message, $this->company->clients()->first()); sleep(rand(1, 2)); $this->release(900); } - - } - catch (\Exception $e) { + + } catch (\Exception $e) { nlog("Mailer failed with {$e->getMessage()}"); $message = $e->getMessage(); @@ -194,7 +190,7 @@ class NinjaMailerJob implements ShouldQueue $this->fail(); $this->logMailError($e->getMessage(), $this->company->clients()->first()); - + if ($this->nmo->entity) { $this->entityEmailFailed($message); } @@ -204,8 +200,8 @@ class NinjaMailerJob implements ShouldQueue return; } - if(stripos($e->getMessage(), 'Dsn') !== false){ - + if(stripos($e->getMessage(), 'Dsn') !== false) { + nlog("Incorrectly configured mail server - setting to default mail driver."); $this->nmo->settings->email_sending_method = 'default'; return $this->setMailDriver(); @@ -220,7 +216,7 @@ class NinjaMailerJob implements ShouldQueue $this->fail(); $this->logMailError($message, $this->company->clients()->first()); - + if ($this->nmo->entity) { $this->entityEmailFailed($message); } @@ -258,8 +254,9 @@ class NinjaMailerJob implements ShouldQueue 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); + } } /** @@ -400,8 +397,7 @@ class NinjaMailerJob implements ShouldQueue if(strlen($smtp_host) <= 1 || strlen($smtp_username) <= 1 || strlen($smtp_password) <= 1 - ) - { + ) { $this->nmo->settings->email_sending_method = 'default'; return $this->setMailDriver(); } @@ -428,7 +424,7 @@ class NinjaMailerJob implements ShouldQueue } $user = $this->resolveSendingUser(); - $sending_email = (isset ($this->nmo->settings->custom_sending_email) && stripos($this->nmo->settings->custom_sending_email, "@")) ? $this->nmo->settings->custom_sending_email : $user->email; + $sending_email = (isset($this->nmo->settings->custom_sending_email) && stripos($this->nmo->settings->custom_sending_email, "@")) ? $this->nmo->settings->custom_sending_email : $user->email; $this->nmo ->mailable @@ -546,8 +542,8 @@ class NinjaMailerJob implements ShouldQueue $user = $this->resolveSendingUser(); - $sending_email = (isset ($this->nmo->settings->custom_sending_email) && stripos($this->nmo->settings->custom_sending_email, "@")) ? $this->nmo->settings->custom_sending_email : $user->email; - $sending_user = (isset ($this->nmo->settings->email_from_name) && strlen($this->nmo->settings->email_from_name) > 2) ? $this->nmo->settings->email_from_name : $user->name(); + $sending_email = (isset($this->nmo->settings->custom_sending_email) && stripos($this->nmo->settings->custom_sending_email, "@")) ? $this->nmo->settings->custom_sending_email : $user->email; + $sending_user = (isset($this->nmo->settings->email_from_name) && strlen($this->nmo->settings->email_from_name) > 2) ? $this->nmo->settings->email_from_name : $user->name(); $this->nmo ->mailable @@ -569,8 +565,8 @@ class NinjaMailerJob implements ShouldQueue $user = $this->resolveSendingUser(); - $sending_email = (isset ($this->nmo->settings->custom_sending_email) && stripos($this->nmo->settings->custom_sending_email, "@")) ? $this->nmo->settings->custom_sending_email : $user->email; - $sending_user = (isset ($this->nmo->settings->email_from_name) && strlen($this->nmo->settings->email_from_name) > 2) ? $this->nmo->settings->email_from_name : $user->name(); + $sending_email = (isset($this->nmo->settings->custom_sending_email) && stripos($this->nmo->settings->custom_sending_email, "@")) ? $this->nmo->settings->custom_sending_email : $user->email; + $sending_user = (isset($this->nmo->settings->email_from_name) && strlen($this->nmo->settings->email_from_name) > 2) ? $this->nmo->settings->email_from_name : $user->name(); $this->nmo ->mailable @@ -592,8 +588,8 @@ class NinjaMailerJob implements ShouldQueue $user = $this->resolveSendingUser(); - $sending_email = (isset ($this->nmo->settings->custom_sending_email) && stripos($this->nmo->settings->custom_sending_email, "@")) ? $this->nmo->settings->custom_sending_email : $user->email; - $sending_user = (isset ($this->nmo->settings->email_from_name) && strlen($this->nmo->settings->email_from_name) > 2) ? $this->nmo->settings->email_from_name : $user->name(); + $sending_email = (isset($this->nmo->settings->custom_sending_email) && stripos($this->nmo->settings->custom_sending_email, "@")) ? $this->nmo->settings->custom_sending_email : $user->email; + $sending_user = (isset($this->nmo->settings->email_from_name) && strlen($this->nmo->settings->email_from_name) > 2) ? $this->nmo->settings->email_from_name : $user->name(); $this->nmo ->mailable @@ -802,7 +798,7 @@ class NinjaMailerJob implements ShouldQueue if (!$user->oauth_user_refresh_token || $user->oauth_user_refresh_token == '') { return false; } - + try { $token = json_decode($guzzle->post($url, [ 'form_params' => [ @@ -813,8 +809,7 @@ class NinjaMailerJob implements ShouldQueue 'refresh_token' => $user->oauth_user_refresh_token ], ])->getBody()->getContents()); - } - catch(\Exception $e){ + } catch(\Exception $e) { nlog("Problem getting new Microsoft token for User: {$user->email}"); } diff --git a/app/Jobs/Ninja/BankTransactionSync.php b/app/Jobs/Ninja/BankTransactionSync.php index bb8e33c21cc5..572860f9e88c 100644 --- a/app/Jobs/Ninja/BankTransactionSync.php +++ b/app/Jobs/Ninja/BankTransactionSync.php @@ -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) { try { (new ProcessBankTransactionsNordigen($bank_integration))->handle(); - } - catch(\Exception $e) { + } catch(\Exception $e) { sleep(20); } diff --git a/app/Jobs/Payment/EmailPayment.php b/app/Jobs/Payment/EmailPayment.php index 1d1c88313e02..1e93c099181d 100644 --- a/app/Jobs/Payment/EmailPayment.php +++ b/app/Jobs/Payment/EmailPayment.php @@ -116,7 +116,7 @@ class EmailPayment implements ShouldQueue $invoice->invitations->each(function ($invite) use ($email_builder) { - + $cloned_mailable = unserialize(serialize($email_builder)); $nmo = new NinjaMailerObject(); diff --git a/app/Jobs/PostMark/ProcessPostmarkWebhook.php b/app/Jobs/PostMark/ProcessPostmarkWebhook.php index 6e4ddd38191a..07ebd194bf85 100644 --- a/app/Jobs/PostMark/ProcessPostmarkWebhook.php +++ b/app/Jobs/PostMark/ProcessPostmarkWebhook.php @@ -405,8 +405,7 @@ class ProcessPostmarkWebhook implements ShouldQueue try { $messageDetail = $postmark->getOutboundMessageDetails($this->request['MessageID']); - } - catch(\Exception $e){ + } catch(\Exception $e) { $postmark_secret = config('services.postmark-outlook.token'); $postmark = new PostmarkClient($postmark_secret); diff --git a/app/Jobs/Report/SendToAdmin.php b/app/Jobs/Report/SendToAdmin.php index 8e24c5a3ff0f..60e7ebac0079 100644 --- a/app/Jobs/Report/SendToAdmin.php +++ b/app/Jobs/Report/SendToAdmin.php @@ -57,8 +57,7 @@ class SendToAdmin implements ShouldQueue $csv = $export->run(); $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(); } diff --git a/app/Jobs/Subscription/CleanStaleInvoiceOrder.php b/app/Jobs/Subscription/CleanStaleInvoiceOrder.php index 25528d29523f..c585aa33647a 100644 --- a/app/Jobs/Subscription/CleanStaleInvoiceOrder.php +++ b/app/Jobs/Subscription/CleanStaleInvoiceOrder.php @@ -65,7 +65,7 @@ class CleanStaleInvoiceOrder implements ShouldQueue ->whereJsonContains('line_items', ['type_id' => '3']) ->cursor() ->each(function ($invoice) { - $invoice->service()->removeUnpaidGatewayFees(); + $invoice->service()->removeUnpaidGatewayFees(); }); return; @@ -84,7 +84,7 @@ class CleanStaleInvoiceOrder implements ShouldQueue $invoice->is_proforma = false; $repo->delete($invoice); }); - + Invoice::query() ->withTrashed() ->where('status_id', Invoice::STATUS_SENT) diff --git a/app/Jobs/Util/Import.php b/app/Jobs/Util/Import.php index 396f4f0d8165..91d06f2b49be 100644 --- a/app/Jobs/Util/Import.php +++ b/app/Jobs/Util/Import.php @@ -1529,7 +1529,7 @@ class Import implements ShouldQueue } $entity = false; - + if (array_key_exists('expense_id', $resource) && $resource['expense_id'] && array_key_exists('expenses', $this->ids)) { $expense_id = $this->transformId('expenses', $resource['expense_id']); $entity = Expense::query()->where('id', $expense_id)->withTrashed()->first(); @@ -1740,7 +1740,7 @@ class Import implements ShouldQueue $modified['company_id'] = $this->company->id; $modified['user_id'] = $this->processUserId($resource); $modified['is_deleted'] = isset($modified['is_deleted']) ? (bool)$modified['is_deleted'] : false; - + /** @var \App\Models\ExpenseCategory $expense_category **/ $expense_category = ExpenseCategory::create($modified); diff --git a/app/Jobs/Util/ReminderJob.php b/app/Jobs/Util/ReminderJob.php index 86be2d258cb7..38b2009c4b2f 100644 --- a/app/Jobs/Util/ReminderJob.php +++ b/app/Jobs/Util/ReminderJob.php @@ -173,43 +173,43 @@ class ReminderJob implements ShouldQueue //2024-06-07 this early return prevented any reminders from sending for users who enabled lock_invoices. if ($amount > 0 || $percent > 0) { // return; - - $fee = $amount; - if ($over_due_invoice->partial > 0) { - $fee += round($over_due_invoice->partial * $percent / 100, 2); - } else { - $fee += round($over_due_invoice->balance * $percent / 100, 2); - } + $fee = $amount; - /** @var \App\Models\Invoice $invoice */ - $invoice = InvoiceFactory::create($over_due_invoice->company_id, $over_due_invoice->user_id); - $invoice->client_id = $over_due_invoice->client_id; - $invoice->date = now()->format('Y-m-d'); - $invoice->due_date = now()->format('Y-m-d'); + if ($over_due_invoice->partial > 0) { + $fee += round($over_due_invoice->partial * $percent / 100, 2); + } else { + $fee += round($over_due_invoice->balance * $percent / 100, 2); + } - $invoice_item = new InvoiceItem(); - $invoice_item->type_id = '5'; - $invoice_item->product_key = trans('texts.fee'); - $invoice_item->notes = ctrans('texts.late_fee_added_locked_invoice', ['invoice' => $over_due_invoice->number, 'date' => $this->translateDate(now()->startOfDay(), $over_due_invoice->client->date_format(), $over_due_invoice->client->locale())]); - $invoice_item->quantity = 1; - $invoice_item->cost = $fee; + /** @var \App\Models\Invoice $invoice */ + $invoice = InvoiceFactory::create($over_due_invoice->company_id, $over_due_invoice->user_id); + $invoice->client_id = $over_due_invoice->client_id; + $invoice->date = now()->format('Y-m-d'); + $invoice->due_date = now()->format('Y-m-d'); - $invoice_items = []; - $invoice_items[] = $invoice_item; + $invoice_item = new InvoiceItem(); + $invoice_item->type_id = '5'; + $invoice_item->product_key = trans('texts.fee'); + $invoice_item->notes = ctrans('texts.late_fee_added_locked_invoice', ['invoice' => $over_due_invoice->number, 'date' => $this->translateDate(now()->startOfDay(), $over_due_invoice->client->date_format(), $over_due_invoice->client->locale())]); + $invoice_item->quantity = 1; + $invoice_item->cost = $fee; - $invoice->line_items = $invoice_items; + $invoice_items = []; + $invoice_items[] = $invoice_item; - /**Refresh Invoice values*/ - $invoice = $invoice->calc()->getInvoice(); - $invoice->service() - ->createInvitations() - ->applyNumber() - ->markSent() - ->save(); + $invoice->line_items = $invoice_items; + + /**Refresh Invoice values*/ + $invoice = $invoice->calc()->getInvoice(); + $invoice->service() + ->createInvitations() + ->applyNumber() + ->markSent() + ->save(); } - if(!$invoice){ + if(!$invoice) { $invoice = $over_due_invoice; } diff --git a/app/Libraries/MultiDB.php b/app/Libraries/MultiDB.php index 8461db1445d1..712ed37184e4 100644 --- a/app/Libraries/MultiDB.php +++ b/app/Libraries/MultiDB.php @@ -538,7 +538,7 @@ class MultiDB $current_db = config('database.default'); - if(SMSNumbers::hasNumber($phone)){ + if(SMSNumbers::hasNumber($phone)) { return true; } diff --git a/app/Livewire/BillingPortal/Authentication/Login.php b/app/Livewire/BillingPortal/Authentication/Login.php index 3c24baae9562..ea471b117050 100644 --- a/app/Livewire/BillingPortal/Authentication/Login.php +++ b/app/Livewire/BillingPortal/Authentication/Login.php @@ -151,7 +151,7 @@ class Login extends Component ]); if ($attempt) { - + $this->dispatch('purchase.context', property: 'contact', value: auth()->guard('contact')->user()); $this->dispatch('purchase.next'); } @@ -171,4 +171,4 @@ class Login extends Component { return view('billing-portal.v3.authentication.login'); } -} \ No newline at end of file +} diff --git a/app/Livewire/BillingPortal/Authentication/Register.php b/app/Livewire/BillingPortal/Authentication/Register.php index 6e85cbc62201..33c8e3d1860a 100644 --- a/app/Livewire/BillingPortal/Authentication/Register.php +++ b/app/Livewire/BillingPortal/Authentication/Register.php @@ -81,7 +81,7 @@ class Register extends Component public function registerForm() { $count = collect($this->subscription->company->client_registration_fields ?? []) - ->filter(fn($field) => $field['required'] === true || $field['visible'] === true) + ->filter(fn ($field) => $field['required'] === true || $field['visible'] === true) ->count(); if ($count === 0) { diff --git a/app/Livewire/BillingPortal/Authentication/RegisterOrLogin.php b/app/Livewire/BillingPortal/Authentication/RegisterOrLogin.php index 4cbecca75207..100d1e6e174a 100644 --- a/app/Livewire/BillingPortal/Authentication/RegisterOrLogin.php +++ b/app/Livewire/BillingPortal/Authentication/RegisterOrLogin.php @@ -181,7 +181,7 @@ class RegisterOrLogin extends Component public function registerForm() { $count = collect($this->subscription->company->client_registration_fields ?? []) - ->filter(fn($field) => $field['required'] === true || $field['visible'] === true) + ->filter(fn ($field) => $field['required'] === true || $field['visible'] === true) ->count(); if ($count === 0) { diff --git a/app/Livewire/BillingPortal/Cart/Cart.php b/app/Livewire/BillingPortal/Cart/Cart.php index f8fae332df76..a63c10ebaf80 100644 --- a/app/Livewire/BillingPortal/Cart/Cart.php +++ b/app/Livewire/BillingPortal/Cart/Cart.php @@ -30,7 +30,7 @@ class Cart extends Component public function showOptionalProductsLabel() { $optional = [ - ...$this->context['bundle']['optional_recurring_products'] ?? [], + ...$this->context['bundle']['optional_recurring_products'] ?? [], ...$this->context['bundle']['optional_one_time_products'] ?? [], ]; diff --git a/app/Livewire/BillingPortal/Cart/OptionalRecurringProducts.php b/app/Livewire/BillingPortal/Cart/OptionalRecurringProducts.php index 9193ba59ae7c..846457d60b6f 100644 --- a/app/Livewire/BillingPortal/Cart/OptionalRecurringProducts.php +++ b/app/Livewire/BillingPortal/Cart/OptionalRecurringProducts.php @@ -25,7 +25,7 @@ class OptionalRecurringProducts extends Component { $this->dispatch('purchase.context', property: "bundle.optional_recurring_products.{$id}.quantity", value: $value); - + } public function render(): \Illuminate\View\View diff --git a/app/Livewire/BillingPortal/Example.php b/app/Livewire/BillingPortal/Example.php index 00cdba32fe2e..992f93bf20fb 100644 --- a/app/Livewire/BillingPortal/Example.php +++ b/app/Livewire/BillingPortal/Example.php @@ -21,7 +21,7 @@ class Example extends Component public function mount() { $this->dispatch('purchase.context', property: 'quantity', value: 1); - $this->dispatch('purchase.next'); + $this->dispatch('purchase.next'); } public function render() diff --git a/app/Livewire/BillingPortal/Purchase.php b/app/Livewire/BillingPortal/Purchase.php index bcad791b4ff2..5fb9c7c9c991 100644 --- a/app/Livewire/BillingPortal/Purchase.php +++ b/app/Livewire/BillingPortal/Purchase.php @@ -36,7 +36,7 @@ class Purchase extends Component public ?string $campaign; - // + // public int $step = 0; @@ -127,11 +127,11 @@ class Purchase extends Component public function mount() { - $classes = collect(self::$dependencies)->mapWithKeys(fn($dependency, $class) => [$dependency['id'] => $class])->toArray(); + $classes = collect(self::$dependencies)->mapWithKeys(fn ($dependency, $class) => [$dependency['id'] => $class])->toArray(); if ($this->subscription->steps) { $steps = collect(explode(',', $this->subscription->steps)) - ->map(fn($step) => $classes[$step]) + ->map(fn ($step) => $classes[$step]) ->toArray(); $this->steps = [ diff --git a/app/Livewire/BillingPortal/Setup.php b/app/Livewire/BillingPortal/Setup.php index bee2f4c21419..d8454257729a 100644 --- a/app/Livewire/BillingPortal/Setup.php +++ b/app/Livewire/BillingPortal/Setup.php @@ -21,7 +21,7 @@ class Setup extends Component public function mount() { $this->dispatch('purchase.context', property: 'quantity', value: 1); - $this->dispatch('purchase.next'); + $this->dispatch('purchase.next'); } public function render() diff --git a/app/Livewire/BillingPortal/Summary.php b/app/Livewire/BillingPortal/Summary.php index 25e7c86a7684..3e824f95efe4 100644 --- a/app/Livewire/BillingPortal/Summary.php +++ b/app/Livewire/BillingPortal/Summary.php @@ -139,7 +139,7 @@ class Summary extends Component } $products = []; - + foreach ($this->context['bundle']['recurring_products'] as $key => $item) { $products[] = [ 'product_key' => $item['product']['product_key'], diff --git a/app/Livewire/RequiredClientInfo.php b/app/Livewire/RequiredClientInfo.php index 3ff7d5374bba..0d17aacea702 100644 --- a/app/Livewire/RequiredClientInfo.php +++ b/app/Livewire/RequiredClientInfo.php @@ -232,11 +232,13 @@ class RequiredClientInfo extends Component $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(); + } - 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; + } } #[Computed] diff --git a/app/Mail/Admin/EntitySentObject.php b/app/Mail/Admin/EntitySentObject.php index 512a2878b3ad..9ee99cb99f5a 100644 --- a/app/Mail/Admin/EntitySentObject.php +++ b/app/Mail/Admin/EntitySentObject.php @@ -200,7 +200,7 @@ class EntitySentObject 'whitelabel' => $this->company->account->isPaid() ? true : false, 'text_body' => $content, 'template' => $this->company->account->isPremium() ? 'email.template.admin_premium' : 'email.template.admin', - + ]; } } diff --git a/app/Mail/Engine/CreditEmailEngine.php b/app/Mail/Engine/CreditEmailEngine.php index 2aafed3d1c1e..e774c6d658ce 100644 --- a/app/Mail/Engine/CreditEmailEngine.php +++ b/app/Mail/Engine/CreditEmailEngine.php @@ -119,9 +119,9 @@ class CreditEmailEngine extends BaseEmailEngine $pdf = ((new CreateRawPdf($this->invitation))->handle()); - if($this->client->getSetting('embed_documents') && ($this->credit->documents()->where('is_public', true)->count() > 0 || $this->credit->company->documents()->where('is_public', true)->count() > 0)) { - $pdf = $this->credit->documentMerge($pdf); - } + if($this->client->getSetting('embed_documents') && ($this->credit->documents()->where('is_public', true)->count() > 0 || $this->credit->company->documents()->where('is_public', true)->count() > 0)) { + $pdf = $this->credit->documentMerge($pdf); + } $this->setAttachments([['file' => base64_encode($pdf), 'name' => $this->credit->numberFormatter().'.pdf']]); } diff --git a/app/Mail/Engine/PaymentEmailEngine.php b/app/Mail/Engine/PaymentEmailEngine.php index c2d68aef570f..7fee5173eba3 100644 --- a/app/Mail/Engine/PaymentEmailEngine.php +++ b/app/Mail/Engine/PaymentEmailEngine.php @@ -30,7 +30,7 @@ class PaymentEmailEngine extends BaseEmailEngine { use MakesDates; use MakesHash; - + public $client; /** @var \App\Models\Payment $payment */ @@ -102,7 +102,7 @@ class PaymentEmailEngine extends BaseEmailEngine if ($this->client->getSetting('pdf_email_attachment') !== false && $this->company->account->hasFeature(Account::FEATURE_PDF_ATTACHMENT)) { $template_in_use = false; - + if($this->is_refund && \App\Models\Design::where('id', $this->decodePrimaryKey($this->payment->client->getSetting('payment_refund_design_id')))->where('is_template', true)->exists()) { $pdf = (new TemplateAction( [$this->payment->hashed_id], diff --git a/app/Mail/Engine/QuoteEmailEngine.php b/app/Mail/Engine/QuoteEmailEngine.php index d43592595080..9034af367d2a 100644 --- a/app/Mail/Engine/QuoteEmailEngine.php +++ b/app/Mail/Engine/QuoteEmailEngine.php @@ -118,9 +118,9 @@ class QuoteEmailEngine extends BaseEmailEngine if ($this->client->getSetting('pdf_email_attachment') !== false && $this->quote->company->account->hasFeature(Account::FEATURE_PDF_ATTACHMENT)) { $pdf = ((new CreateRawPdf($this->invitation))->handle()); - if($this->client->getSetting('embed_documents') && ($this->quote->documents()->where('is_public', true)->count() > 0 || $this->quote->company->documents()->where('is_public', true)->count() > 0)){ - $pdf = $this->quote->documentMerge($pdf); - } + if($this->client->getSetting('embed_documents') && ($this->quote->documents()->where('is_public', true)->count() > 0 || $this->quote->company->documents()->where('is_public', true)->count() > 0)) { + $pdf = $this->quote->documentMerge($pdf); + } $this->setAttachments([['file' => base64_encode($pdf), 'name' => $this->quote->numberFormatter().'.pdf']]); } diff --git a/app/Mail/TemplateEmail.php b/app/Mail/TemplateEmail.php index 3bce1cd84a1b..2eaa14389dae 100644 --- a/app/Mail/TemplateEmail.php +++ b/app/Mail/TemplateEmail.php @@ -154,8 +154,9 @@ class TemplateEmail extends Mailable } } - if(!$this->invitation) + if(!$this->invitation) { return $this; + } if ($this->invitation->invoice && $settings->ubl_email_attachment && $this->company->account->hasFeature(Account::FEATURE_PDF_ATTACHMENT)) { $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)) { $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)) { $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)) { $xml_string = $this->invitation->purchase_order->service()->getEPurchaseOrder($this->invitation->contact); diff --git a/app/Mail/VendorTemplateEmail.php b/app/Mail/VendorTemplateEmail.php index ff54cf4e1048..7adbcbcc743c 100644 --- a/app/Mail/VendorTemplateEmail.php +++ b/app/Mail/VendorTemplateEmail.php @@ -74,7 +74,7 @@ class VendorTemplateEmail extends Mailable if (in_array($this->build_email->getTemplate(), ['light', 'dark'])) { $template_name = 'email.template.client'; } - + if($this->build_email->getTemplate() == 'premium') { $template_name = 'email.template.client_premium'; } diff --git a/app/Models/Account.php b/app/Models/Account.php index 463af307ee30..d329961fa064 100644 --- a/app/Models/Account.php +++ b/app/Models/Account.php @@ -495,9 +495,10 @@ class Account extends BaseModel return 0; } - if($this->email_quota) + if($this->email_quota) { return (int)$this->email_quota; - + } + if (Carbon::createFromTimestamp($this->created_at)->diffInWeeks() <= 1) { return 20; } diff --git a/app/Models/Activity.php b/app/Models/Activity.php index 56eb2d490f76..97e561b41c97 100644 --- a/app/Models/Activity.php +++ b/app/Models/Activity.php @@ -258,7 +258,7 @@ class Activity extends StaticModel public const PAYMENT_EMAILED = 138; public const VENDOR_NOTIFICATION_EMAIL = 139; - + public const EMAIL_STATEMENT = 140; @@ -473,7 +473,7 @@ class Activity extends StaticModel ':ip' => $translation = [ 'ip' => $this->ip ?? ''], ':contact' => $translation = $this->resolveContact(), ':notes' => $translation = [ 'notes' => $this->notes ?? ''], - + default => $translation = [], }; diff --git a/app/Models/BaseModel.php b/app/Models/BaseModel.php index 19b443c476db..727b2adfe19d 100644 --- a/app/Models/BaseModel.php +++ b/app/Models/BaseModel.php @@ -78,7 +78,7 @@ class BaseModel extends Model use UserSessionAttributes; use HasFactory; use Excludable; - + public int $max_attachment_size = 3000000; protected $appends = [ @@ -340,7 +340,7 @@ class BaseModel extends Model return strtr($section, $variables['values']); } - + /** * Merged PDFs associated with the entity / company * into a single document diff --git a/app/Models/Client.php b/app/Models/Client.php index 66d04a14ade7..d67c3593f81a 100644 --- a/app/Models/Client.php +++ b/app/Models/Client.php @@ -421,7 +421,7 @@ class Client extends BaseModel implements HasLocalePreference // } return $date_formats->first(function ($item) { - + /** @var \stdClass $item */ return $item->id == $this->getSetting('date_format_id'); })->format; @@ -429,7 +429,7 @@ class Client extends BaseModel implements HasLocalePreference public function currency() { - + /** @var \Illuminate\Support\Collection $currencies */ $currencies = app('currencies'); // $currencies = Cache::get('currencies'); @@ -439,8 +439,8 @@ class Client extends BaseModel implements HasLocalePreference // } return $currencies->first(function ($item) { - - /** @var \stdClass $item */ + + /** @var \stdClass $item */ return $item->id == $this->getSetting('currency_id'); }); } diff --git a/app/Models/Company.php b/app/Models/Company.php index 815b21aa8ffc..c1c34080a5c9 100644 --- a/app/Models/Company.php +++ b/app/Models/Company.php @@ -647,7 +647,7 @@ class Company extends BaseModel // } return $countries->first(function ($item) { - + /** @var \stdClass $item */ return $item->id == $this->getSetting('country_id'); }); diff --git a/app/Models/Document.php b/app/Models/Document.php index e948e9c3e8cc..30e8f8f684d1 100644 --- a/app/Models/Document.php +++ b/app/Models/Document.php @@ -176,9 +176,9 @@ class Document extends BaseModel public function generateRoute($absolute = false) { - try{ - return route('api.documents.show', ['document' => $this->hashed_id]).'/download'; - }catch(\Exception $e){ + try { + return route('api.documents.show', ['document' => $this->hashed_id]).'/download'; + } catch(\Exception $e) { return ''; } } diff --git a/app/Models/GatewayType.php b/app/Models/GatewayType.php index f30d5c97cb14..1513550cf63d 100644 --- a/app/Models/GatewayType.php +++ b/app/Models/GatewayType.php @@ -92,7 +92,7 @@ class GatewayType extends StaticModel public const PAYLATER = 28; public const PAYPAL_ADVANCED_CARDS = 29; - + public function gateway() { return $this->belongsTo(Gateway::class); @@ -162,7 +162,7 @@ class GatewayType extends StaticModel return ctrans('texts.paypal_paylater'); case self::PAYPAL_ADVANCED_CARDS: return ctrans('texts.credit_card'); - + default: return ' '; } diff --git a/app/Models/License.php b/app/Models/License.php index 89127ed22bef..2de8088f298b 100644 --- a/app/Models/License.php +++ b/app/Models/License.php @@ -74,4 +74,4 @@ class License extends StaticModel $contact = $this->recurring_invoice->client->contacts()->where('email', $this->email)->first(); } -} \ No newline at end of file +} diff --git a/app/Models/Product.php b/app/Models/Product.php index 556488c8f58d..169a7abd8865 100644 --- a/app/Models/Product.php +++ b/app/Models/Product.php @@ -208,7 +208,7 @@ class Product extends BaseModel public static function markdownHelp(string $notes = '') { - + $converter = new CommonMarkConverter([ 'allow_unsafe_links' => false, 'renderer' => [ diff --git a/app/Models/Project.php b/app/Models/Project.php index 3e5b3dc81748..d341a3fb8569 100644 --- a/app/Models/Project.php +++ b/app/Models/Project.php @@ -136,7 +136,7 @@ class Project extends BaseModel { return $this->hasMany(Quote::class); } - + public function translate_entity() { diff --git a/app/Models/Quote.php b/app/Models/Quote.php index 71770a531f8a..ada153dc18f7 100644 --- a/app/Models/Quote.php +++ b/app/Models/Quote.php @@ -198,10 +198,10 @@ class Quote extends BaseModel return $this->dateMutator($value); } -// public function getDueDateAttribute($value) -// { -// return $value ? $this->dateMutator($value) : null; -// } + // public function getDueDateAttribute($value) + // { + // return $value ? $this->dateMutator($value) : null; + // } // public function getPartialDueDateAttribute($value) // { diff --git a/app/Models/RecurringExpense.php b/app/Models/RecurringExpense.php index 1be7816e2104..b8ba39ee7c55 100644 --- a/app/Models/RecurringExpense.php +++ b/app/Models/RecurringExpense.php @@ -221,7 +221,7 @@ class RecurringExpense extends BaseModel return $this->belongsTo(User::class, 'assigned_user_id', 'id'); } - public function company():\Illuminate\Database\Eloquent\Relations\BelongsTo + public function company(): \Illuminate\Database\Eloquent\Relations\BelongsTo { return $this->belongsTo(Company::class); } diff --git a/app/Models/RecurringInvoice.php b/app/Models/RecurringInvoice.php index a9953f3d85aa..975b0f638e65 100644 --- a/app/Models/RecurringInvoice.php +++ b/app/Models/RecurringInvoice.php @@ -341,12 +341,12 @@ class RecurringInvoice extends BaseModel return $this->status_id; } } - + /** * CalculateStatus * * Calculates the status of the Recurring Invoice. - * + * * We only apply the pending status on new models, we never revert an invoice back to * pending. * @param bool $new_model @@ -355,15 +355,16 @@ class RecurringInvoice extends BaseModel 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; - 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; - 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 $this->status_id; - + } public function nextSendDate(): ?Carbon diff --git a/app/Models/SystemLog.php b/app/Models/SystemLog.php index 5ef3305d525b..f61b6c4fbf45 100644 --- a/app/Models/SystemLog.php +++ b/app/Models/SystemLog.php @@ -151,7 +151,7 @@ class SystemLog extends Model public const TYPE_PAYPAL_PPCP = 323; public const TYPE_BTC_PAY = 324; - + public const TYPE_QUOTA_EXCEEDED = 400; public const TYPE_UPSTREAM_FAILURE = 401; diff --git a/app/PaymentDrivers/Authorize/AuthorizePaymentMethod.php b/app/PaymentDrivers/Authorize/AuthorizePaymentMethod.php index 529c4f64b4e0..61a10d27860f 100644 --- a/app/PaymentDrivers/Authorize/AuthorizePaymentMethod.php +++ b/app/PaymentDrivers/Authorize/AuthorizePaymentMethod.php @@ -169,9 +169,10 @@ class AuthorizePaymentMethod $billto->setCity(substr($this->authorize->client->city, 0, 40)); $billto->setState(substr($this->authorize->client->state, 0, 40)); $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); + } if ($this->authorize->client->country_id) { $billto->setCountry($this->authorize->client->country->name); @@ -183,7 +184,7 @@ class AuthorizePaymentMethod // Create a new Customer Payment Profile object $paymentprofile = new CustomerPaymentProfileType(); $paymentprofile->setCustomerType('individual'); - + if ($billto) { $paymentprofile->setBillTo($billto); } diff --git a/app/PaymentDrivers/Authorize/AuthorizeTransaction.php b/app/PaymentDrivers/Authorize/AuthorizeTransaction.php index 88b6c47d4739..fe187cab29aa 100644 --- a/app/PaymentDrivers/Authorize/AuthorizeTransaction.php +++ b/app/PaymentDrivers/Authorize/AuthorizeTransaction.php @@ -145,7 +145,7 @@ class AuthorizeTransaction nlog(' Description : '.$tresponse->getMessages()[0]->getDescription()); nlog(print_r($tresponse->getMessages()[0], 1)); - if($tresponse->getResponseCode() == "4"){ + if($tresponse->getResponseCode() == "4") { //notify user that this transaction is being held under FDS review: FDSReview::dispatch((string)$tresponse->getTransId(), $this->authorize->payment_hash, $this->authorize->company_gateway->company->db); } diff --git a/app/PaymentDrivers/Authorize/FDSReview.php b/app/PaymentDrivers/Authorize/FDSReview.php index 91f7401449a9..aede54529ea1 100644 --- a/app/PaymentDrivers/Authorize/FDSReview.php +++ b/app/PaymentDrivers/Authorize/FDSReview.php @@ -31,7 +31,7 @@ class FDSReview implements ShouldQueue use InteractsWithQueue; use Queueable; use SerializesModels; - + public $tries = 1; //number of retries public $deleteWhenMissingModels = true; @@ -43,11 +43,11 @@ class FDSReview implements ShouldQueue { MultiDB::setDB($this->db); - + $company = $this->payment_hash->fee_invoice->company; App::setLocale($company->getLocale()); - + $invoices_string = \implode(', ', collect($this->payment_hash->invoices())->pluck('invoice_number')->toArray()) ?: ''; $body = "Transaction {$this->transaction_reference} has been held for your review in Auth.net based on your Fraud Detection Settings.\n\n\nWe have marked invoices {$invoices_string} as paid in Invoice Ninja.\n\n\nPlease review this transaction in your auth.net account, and authorize if correct to ensure the transaction is finalized as expected.\n\n\nIf these charges need to be cancelled, you will need to delete the payments that have been created in Invoice Ninja."; diff --git a/app/PaymentDrivers/AuthorizePaymentDriver.php b/app/PaymentDrivers/AuthorizePaymentDriver.php index 465474a5d595..a34d29a63115 100644 --- a/app/PaymentDrivers/AuthorizePaymentDriver.php +++ b/app/PaymentDrivers/AuthorizePaymentDriver.php @@ -194,7 +194,7 @@ class AuthorizePaymentDriver extends BaseDriver public function import() { $this->init(); - + nlog("starting import auth.net"); return (new AuthorizeCustomer($this))->importCustomers(); diff --git a/app/PaymentDrivers/BTCPayPaymentDriver.php b/app/PaymentDrivers/BTCPayPaymentDriver.php index 7d5926ec408c..6d4d7ec3dd51 100644 --- a/app/PaymentDrivers/BTCPayPaymentDriver.php +++ b/app/PaymentDrivers/BTCPayPaymentDriver.php @@ -43,7 +43,7 @@ class BTCPayPaymentDriver extends BaseDriver 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 $api_key = ""; diff --git a/app/PaymentDrivers/BaseDriver.php b/app/PaymentDrivers/BaseDriver.php index 82f52215264f..78fbc57d79f2 100644 --- a/app/PaymentDrivers/BaseDriver.php +++ b/app/PaymentDrivers/BaseDriver.php @@ -572,8 +572,7 @@ class BaseDriver extends AbstractPaymentDriver $nmo->company = $this->client->company; $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->first()->invitations->each(function ($invitation) use ($nmo) { @@ -583,7 +582,7 @@ class BaseDriver extends AbstractPaymentDriver } }); } - + $message = [ 'server_response' => $response, 'data' => $this->payment_hash->data, @@ -815,6 +814,6 @@ class BaseDriver extends AbstractPaymentDriver public function importCustomers() { - + } } diff --git a/app/PaymentDrivers/BraintreePaymentDriver.php b/app/PaymentDrivers/BraintreePaymentDriver.php index 5ffdc7d5c3be..9fe58cf6b9e1 100644 --- a/app/PaymentDrivers/BraintreePaymentDriver.php +++ b/app/PaymentDrivers/BraintreePaymentDriver.php @@ -37,7 +37,7 @@ use App\PaymentDrivers\Braintree\CreditCard; class BraintreePaymentDriver extends BaseDriver { use GeneratesCounter; - + public $refundable = true; public $token_billing = true; @@ -296,14 +296,14 @@ class BraintreePaymentDriver extends BaseDriver public function getClientRequiredFields(): array { $fields = []; - - $fields[] = ['name' => 'contact_first_name', 'label' => ctrans('texts.first_name'), 'type' => 'text', 'validation' => 'required']; - $fields[] = ['name' => 'contact_last_name', 'label' => ctrans('texts.last_name'), 'type' => 'text', 'validation' => 'required']; - $fields[] = ['name' => 'contact_email', 'label' => ctrans('texts.email'), 'type' => 'text', 'validation' => 'required,email:rfc']; - $fields[] = ['name' => 'client_address_line_1', 'label' => ctrans('texts.address1'), 'type' => 'text', 'validation' => 'required']; - $fields[] = ['name' => 'client_city', 'label' => ctrans('texts.city'), 'type' => 'text', 'validation' => 'required']; - $fields[] = ['name' => 'client_state', 'label' => ctrans('texts.state'), 'type' => 'text', 'validation' => 'required']; - $fields[] = ['name' => 'client_country_id', 'label' => ctrans('texts.country'), 'type' => 'text', 'validation' => 'required']; + + $fields[] = ['name' => 'contact_first_name', 'label' => ctrans('texts.first_name'), 'type' => 'text', 'validation' => 'required']; + $fields[] = ['name' => 'contact_last_name', 'label' => ctrans('texts.last_name'), 'type' => 'text', 'validation' => 'required']; + $fields[] = ['name' => 'contact_email', 'label' => ctrans('texts.email'), 'type' => 'text', 'validation' => 'required,email:rfc']; + $fields[] = ['name' => 'client_address_line_1', 'label' => ctrans('texts.address1'), 'type' => 'text', 'validation' => 'required']; + $fields[] = ['name' => 'client_city', 'label' => ctrans('texts.city'), 'type' => 'text', 'validation' => 'required']; + $fields[] = ['name' => 'client_state', 'label' => ctrans('texts.state'), 'type' => 'text', 'validation' => 'required']; + $fields[] = ['name' => 'client_country_id', 'label' => ctrans('texts.country'), 'type' => 'text', 'validation' => 'required']; return $fields; } @@ -333,25 +333,24 @@ class BraintreePaymentDriver extends BaseDriver public function auth(): bool { - + try { - $ct =$this->init()->gateway->clientToken()->generate(); - + $ct = $this->init()->gateway->clientToken()->generate(); + return true; - } - catch(\Exception $e) { + } catch(\Exception $e) { } - + return false; } - private function find(string $customer_id = '') { - + private function find(string $customer_id = '') + { + try { return $this->init()->gateway->customer()->find($customer_id); - } - catch(\Exception $e){ + } catch(\Exception $e) { 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) ->where('email', $email) ->first()->client ?? false; @@ -383,13 +383,14 @@ class BraintreePaymentDriver extends BaseDriver private function addClientCards(Client $client, array $cards) { - + $this->client = $client; 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; + } $payment_meta = new \stdClass(); $payment_meta->exp_month = (string) $card->expirationMonth; @@ -405,7 +406,7 @@ class BraintreePaymentDriver extends BaseDriver ]; $this->storeGatewayToken($data, ['gateway_customer_reference' => $card->customerId]); - + nlog("adding card to customer payment profile"); } @@ -423,7 +424,7 @@ class BraintreePaymentDriver extends BaseDriver if($b_business_address) { - $braintree_address = + $braintree_address = [ 'address1' => $b_business_address->extendedAddress ?? '', 'address2' => $b_business_address->streetAddress ?? '', @@ -438,7 +439,7 @@ class BraintreePaymentDriver extends BaseDriver if($b_shipping_address) { - $braintree_shipping_address = + $braintree_shipping_address = [ 'shipping_address1' => $b_shipping_address->extendedAddress ?? '', 'shipping_address2' => $b_shipping_address->streetAddress ?? '', @@ -498,15 +499,16 @@ class BraintreePaymentDriver extends BaseDriver public function importCustomers() { $customers = $this->init()->gateway->customer()->all(); - - foreach($customers as $c){ + + foreach($customers as $c) { $customer = $this->find($c->id); // nlog(count($customer->creditCards). " Exists for {$c->id}"); - if(!$customer) + if(!$customer) { continue; + } $client = $this->findClient($customer->email); @@ -515,7 +517,7 @@ class BraintreePaymentDriver extends BaseDriver $client = $this->createNinjaClient($customer); // nlog("Creating new Client"); } - + $this->addClientCards($client, $customer->creditCards); // nlog("Adding Braintree Client: {$c->id} => {$client->id}"); diff --git a/app/PaymentDrivers/CheckoutComPaymentDriver.php b/app/PaymentDrivers/CheckoutComPaymentDriver.php index 8b615b2283d0..03b161d076af 100644 --- a/app/PaymentDrivers/CheckoutComPaymentDriver.php +++ b/app/PaymentDrivers/CheckoutComPaymentDriver.php @@ -538,11 +538,10 @@ class CheckoutComPaymentDriver extends BaseDriver public function auth(): bool { - try{ + try { $this->init()->gateway->getCustomersClient('x'); return true; - } - catch(\Exception $e){ + } catch(\Exception $e) { } return false; @@ -556,65 +555,65 @@ class CheckoutComPaymentDriver extends BaseDriver ->where('token', $token) ->first(); } - + /** * ImportCustomers * - * Only their methods because checkout.com + * Only their methods because checkout.com * does not have a list route for customers - * + * * @return void */ public function importCustomers() { $this->init(); - + $this->company_gateway ->company ->clients() ->cursor() - ->each(function ($client){ + ->each(function ($client) { - if(!str_contains($client->present()->email(), "@")) - return; + if(!str_contains($client->present()->email(), "@")) { + return; + } - try{ - $customer = $this->gateway->getCustomersClient()->get($client->present()->email()); - } - catch(\Exception $e) { - nlog("Checkout: Customer not found"); - return; - } + try { + $customer = $this->gateway->getCustomersClient()->get($client->present()->email()); + } catch(\Exception $e) { + nlog("Checkout: Customer not found"); + return; + } - $this->client = $client; + $this->client = $client; - nlog($customer['instruments']); + nlog($customer['instruments']); - foreach($customer['instruments'] as $card) - { - if( - $card['type'] != 'card' || - Carbon::createFromDate($card['expiry_year'], $card['expiry_month'], '1')->lt(now()) || - $this->getToken($card['id'], $customer['id']) - ) - continue; - - $payment_meta = new \stdClass(); - $payment_meta->exp_month = (string) $card['expiry_month']; - $payment_meta->exp_year = (string) $card['expiry_year']; - $payment_meta->brand = (string) $card['scheme']; - $payment_meta->last4 = (string) $card['last4']; - $payment_meta->type = (int) GatewayType::CREDIT_CARD; + foreach($customer['instruments'] as $card) { + if( + $card['type'] != 'card' || + Carbon::createFromDate($card['expiry_year'], $card['expiry_month'], '1')->lt(now()) || + $this->getToken($card['id'], $customer['id']) + ) { + continue; + } - $data = [ - 'payment_meta' => $payment_meta, - 'token' => $card['id'], - 'payment_method_id' => GatewayType::CREDIT_CARD, - ]; + $payment_meta = new \stdClass(); + $payment_meta->exp_month = (string) $card['expiry_month']; + $payment_meta->exp_year = (string) $card['expiry_year']; + $payment_meta->brand = (string) $card['scheme']; + $payment_meta->last4 = (string) $card['last4']; + $payment_meta->type = (int) GatewayType::CREDIT_CARD; - $this->storeGatewayToken($data, ['gateway_customer_reference' => $customer['id']]); + $data = [ + 'payment_meta' => $payment_meta, + 'token' => $card['id'], + 'payment_method_id' => GatewayType::CREDIT_CARD, + ]; - } + $this->storeGatewayToken($data, ['gateway_customer_reference' => $customer['id']]); + + } }); } diff --git a/app/PaymentDrivers/EwayPaymentDriver.php b/app/PaymentDrivers/EwayPaymentDriver.php index a416cea387c2..2222b071a78d 100644 --- a/app/PaymentDrivers/EwayPaymentDriver.php +++ b/app/PaymentDrivers/EwayPaymentDriver.php @@ -215,12 +215,12 @@ class EwayPaymentDriver extends BaseDriver public function auth(): bool { - $response =$this->init()->eway->queryTransaction('xx'); + $response = $this->init()->eway->queryTransaction('xx'); return (bool) count($response->getErrors()) == 0; } - + /** * importCustomers * diff --git a/app/PaymentDrivers/Factory/ForteCustomerFactory.php b/app/PaymentDrivers/Factory/ForteCustomerFactory.php index eb6336d778fb..613870fe42e2 100644 --- a/app/PaymentDrivers/Factory/ForteCustomerFactory.php +++ b/app/PaymentDrivers/Factory/ForteCustomerFactory.php @@ -17,23 +17,22 @@ use App\Models\Company; class ForteCustomerFactory { - public function convertToNinja(array $customer, Company $company): array { - return + return collect([ - 'name' => $customer['company_name'] ?? $customer['first_name'], - 'contacts' => [ - [ - 'first_name' => $customer['first_name'], - 'last_name' => $customer['last_name'], - 'email' => $this->getBillingAddress($customer)['email'], - 'phone' => $this->getBillingAddress($customer)['phone'], - ] - ], - 'settings' => [ - 'currency_id' => $company->settings->currency_id, - ], + 'name' => $customer['company_name'] ?? $customer['first_name'], + 'contacts' => [ + [ + 'first_name' => $customer['first_name'], + 'last_name' => $customer['last_name'], + 'email' => $this->getBillingAddress($customer)['email'], + 'phone' => $this->getBillingAddress($customer)['phone'], + ] + ], + 'settings' => [ + 'currency_id' => $company->settings->currency_id, + ], ])->merge($this->getShippingAddress($customer)) ->merge($this->getBillingAddress($customer)) ->toArray(); @@ -42,7 +41,7 @@ class ForteCustomerFactory // public function convertToGateway(Client $client): array // { - + // } private function getBillingAddress(array $customer): array @@ -51,8 +50,9 @@ class ForteCustomerFactory foreach($customer['addresses'] as $address) { - if($address['address_token'] != $customer['default_billing_address_token']) + if($address['address_token'] != $customer['default_billing_address_token']) { continue; + } return [ 'address1' => $address['physical_address']['street_line1'], @@ -114,8 +114,8 @@ class ForteCustomerFactory } - if(isset($customer['addresses'][1])){ - + if(isset($customer['addresses'][1])) { + $address = $customer['addresses'][1]; return [ diff --git a/app/PaymentDrivers/Factory/PaytraceCustomerFactory.php b/app/PaymentDrivers/Factory/PaytraceCustomerFactory.php index 731a6c7085f6..3f05dbf84d06 100644 --- a/app/PaymentDrivers/Factory/PaytraceCustomerFactory.php +++ b/app/PaymentDrivers/Factory/PaytraceCustomerFactory.php @@ -21,7 +21,7 @@ class PaytraceCustomerFactory return collect([ 'name' => $customer->billing_address->name ?? $customer->shipping_address->name, - 'contacts' => [ + 'contacts' => [ [ 'first_name' => $customer->billing_address->name ?? $customer->shipping_address->name, 'last_name' => '', @@ -55,5 +55,5 @@ class PaytraceCustomerFactory ->toArray(); } - + } diff --git a/app/PaymentDrivers/Factory/SquareCustomerFactory.php b/app/PaymentDrivers/Factory/SquareCustomerFactory.php index fa3d9ad71bfd..c62eac3d8055 100644 --- a/app/PaymentDrivers/Factory/SquareCustomerFactory.php +++ b/app/PaymentDrivers/Factory/SquareCustomerFactory.php @@ -17,7 +17,6 @@ use App\Models\GatewayType; class SquareCustomerFactory { - /* { "id": "A537H7KAQWSAF8M8EM1Y23E16M", @@ -83,9 +82,9 @@ class SquareCustomerFactory $cards = []; - foreach($customer->getCards() ?? [] as $card){ - - $meta = new \stdClass; + foreach($customer->getCards() ?? [] as $card) { + + $meta = new \stdClass(); $meta->exp_month = $card->getExpMonth(); $meta->exp_year = $card->getExpYear(); $meta->last4 = $card->getLast4(); @@ -101,7 +100,7 @@ class SquareCustomerFactory } $address = $customer->getAddress(); - + return collect([ 'name' => $customer->getCompanyName() ?? ($customer->getGivenName() ?? '' ." " . $customer->getFamilyName() ?? ''), diff --git a/app/PaymentDrivers/FortePaymentDriver.php b/app/PaymentDrivers/FortePaymentDriver.php index 0cbf1e3883df..902b4a62e46f 100644 --- a/app/PaymentDrivers/FortePaymentDriver.php +++ b/app/PaymentDrivers/FortePaymentDriver.php @@ -194,7 +194,7 @@ class FortePaymentDriver extends BaseDriver /////////////////////////////////////////// public function auth(): bool { - + $forte_base_uri = "https://sandbox.forte.net/api/v3/"; if ($this->company_gateway->getConfigField('testMode') == false) { $forte_base_uri = "https://api.forte.net/v3/"; @@ -204,13 +204,13 @@ class FortePaymentDriver extends BaseDriver $forte_auth_organization_id = $this->company_gateway->getConfigField('authOrganizationId'); $forte_organization_id = $this->company_gateway->getConfigField('organizationId'); $forte_location_id = $this->company_gateway->getConfigField('locationId'); - + $response = Http::withBasicAuth($forte_api_access_id, $forte_secure_key) ->withHeaders(['X-Forte-Auth-Organization-Id' => $forte_organization_id]) ->get("{$forte_base_uri}/organizations/{$forte_organization_id}/locations/{$forte_location_id}/customers/"); return $response->successful(); - + } public function baseUri(): string @@ -236,7 +236,7 @@ class FortePaymentDriver extends BaseDriver public function stubRequest() { - + $forte_api_access_id = $this->company_gateway->getConfigField('apiAccessId'); $forte_secure_key = $this->company_gateway->getConfigField('secureKey'); $forte_auth_organization_id = $this->company_gateway->getConfigField('authOrganizationId'); @@ -255,13 +255,14 @@ class FortePaymentDriver extends BaseDriver public function getLocation() { - + $response = $this->stubRequest() ->withQueryParameters(['page_size' => 10000]) ->get("{$this->baseUri()}/organizations/{$this->getOrganisationId()}/locations/{$this->getLocationId()}"); - if($response->successful()) + if($response->successful()) { return $response->json(); + } return false; } @@ -270,18 +271,17 @@ class FortePaymentDriver extends BaseDriver { $response = $this->getLocation(); - if($response) - { + if($response) { $body = $response['services']; - + $fees_and_limits = $this->company_gateway->fees_and_limits; - if($body['card']['service_fee_percentage'] > 0 || $body['card']['service_fee_additional_amount'] > 0){ + if($body['card']['service_fee_percentage'] > 0 || $body['card']['service_fee_additional_amount'] > 0) { $fees_and_limits->{1}->fee_amount = $body['card']['service_fee_additional_amount']; $fees_and_limits->{1}->fee_percent = $body['card']['service_fee_percentage']; } - + if($body['debit']['service_fee_percentage'] > 0 || $body['debit']['service_fee_additional_amount'] > 0) { $fees_and_limits->{2}->fee_amount = $body['debit']['service_fee_additional_amount']; @@ -290,7 +290,7 @@ class FortePaymentDriver extends BaseDriver $this->company_gateway->fees_and_limits = $fees_and_limits; $this->company_gateway->save(); - + } return false; @@ -303,26 +303,26 @@ class FortePaymentDriver extends BaseDriver $response = $this->stubRequest() ->withQueryParameters(['page_size' => 10000]) ->get("{$this->baseUri()}/organizations/{$this->getOrganisationId()}/locations/{$this->getLocationId()}/customers"); - - if($response->successful()){ - - foreach($response->json()['results'] as $customer) - { + + if($response->successful()) { + + foreach($response->json()['results'] as $customer) { $client_repo = new ClientRepository(new ClientContactRepository()); $factory = new ForteCustomerFactory(); $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; + } $client_repo->save($data, ClientFactory::create($this->company_gateway->company_id, $this->company_gateway->user_id)); //persist any payment methods here! } } - + } - + } diff --git a/app/PaymentDrivers/GoCardlessPaymentDriver.php b/app/PaymentDrivers/GoCardlessPaymentDriver.php index 2906a589fa3b..6985ac144f9d 100644 --- a/app/PaymentDrivers/GoCardlessPaymentDriver.php +++ b/app/PaymentDrivers/GoCardlessPaymentDriver.php @@ -564,8 +564,7 @@ class GoCardlessPaymentDriver extends BaseDriver try { $customers = $this->init()->gateway->customers()->list(); return true; - } - catch(\Exception $e){ + } catch(\Exception $e) { } diff --git a/app/PaymentDrivers/MolliePaymentDriver.php b/app/PaymentDrivers/MolliePaymentDriver.php index 172c7906517d..0f02d33e12f3 100644 --- a/app/PaymentDrivers/MolliePaymentDriver.php +++ b/app/PaymentDrivers/MolliePaymentDriver.php @@ -428,8 +428,7 @@ class MolliePaymentDriver extends BaseDriver try { $p = $this->gateway->payments->page(); return true; - } - catch(\Exception $e){ + } catch(\Exception $e) { } diff --git a/app/PaymentDrivers/PayPal/PayPalBasePaymentDriver.php b/app/PaymentDrivers/PayPal/PayPalBasePaymentDriver.php index 6d3e2588ff76..e5ecf60aa426 100644 --- a/app/PaymentDrivers/PayPal/PayPalBasePaymentDriver.php +++ b/app/PaymentDrivers/PayPal/PayPalBasePaymentDriver.php @@ -71,8 +71,8 @@ class PayPalBasePaymentDriver extends BaseDriver public function gatewayTypes() { - $funding_options = - + $funding_options = + collect($this->company_gateway->fees_and_limits) ->filter(function ($fee) { return $fee->is_enabled; @@ -81,10 +81,11 @@ class PayPalBasePaymentDriver extends BaseDriver })->toArray(); /** 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]); + } } @@ -141,7 +142,7 @@ class PayPalBasePaymentDriver extends BaseDriver * getFundingOptions * * Hosted fields requires this. - * + * * @return string */ public function getFundingOptions(): string @@ -189,22 +190,23 @@ class PayPalBasePaymentDriver extends BaseDriver $cgt = ClientGatewayToken::where('company_gateway_id', $this->company_gateway->id) ->where('client_id', $this->client->id) ->first(); - if(!$cgt) + if(!$cgt) { return ''; - + } + $client_reference = $cgt->gateway_customer_reference; $secret = $this->company_gateway->getConfigField('secret'); $client_id = $this->company_gateway->getConfigField('clientId'); - $response = Http::withBasicAuth($client_id, $secret) - ->withHeaders(['Content-Type' => 'application/x-www-form-urlencoded']) - ->withQueryParameters(['grant_type' => 'client_credentials','response_type' => 'id_token', 'target_customer_id' => $client_reference]) - ->post("{$this->api_endpoint_url}/v1/oauth2/token"); + $response = Http::withBasicAuth($client_id, $secret) + ->withHeaders(['Content-Type' => 'application/x-www-form-urlencoded']) + ->withQueryParameters(['grant_type' => 'client_credentials','response_type' => 'id_token', 'target_customer_id' => $client_reference]) + ->post("{$this->api_endpoint_url}/v1/oauth2/token"); if($response->successful()) { - - $data =$response->json(); + + $data = $response->json(); return $data['id_token'] ?? ''; @@ -233,7 +235,7 @@ class PayPalBasePaymentDriver extends BaseDriver return $r; } - + public function getShippingAddress(): ?array { return $this->company_gateway->require_shipping_address ? @@ -269,7 +271,7 @@ class PayPalBasePaymentDriver extends BaseDriver "country_code" => $this->client->country->iso_3166_2, ]; } - + public function getPaymentSource(): array { //@todo - roll back here for advanced payments vs hosted card fields. @@ -293,7 +295,7 @@ class PayPalBasePaymentDriver extends BaseDriver // "payment_initiator" => "MERCHANT", //"CUSTOMER" who initiated the transaction? "payment_initiator" => "CUSTOMER", //"" who initiated the transaction? "payment_type" => "UNSCHEDULED", //UNSCHEDULED - "usage"=> "DERIVED", + "usage" => "DERIVED", ], ], ]; @@ -329,15 +331,13 @@ class PayPalBasePaymentDriver extends BaseDriver "postal_code" => $this->client->shipping_postal_code, "country_code" => $this->client->present()->shipping_country_code(), ]; - } - elseif( + } elseif( strlen($this->client->address1 ?? '') > 2 && strlen($this->client->city ?? '') > 2 && strlen($this->client->state ?? '') >= 2 && strlen($this->client->postal_code ?? '') > 2 && strlen($this->client->country->iso_3166_2 ?? '') >= 2 - ) - { + ) { $order['paypal']['address'] = [ "address_line_1" => $this->client->address1, "address_line_2" => $this->client->address2, @@ -351,7 +351,7 @@ class PayPalBasePaymentDriver extends BaseDriver return $order; } - + /** * Payment method setter * @@ -402,8 +402,8 @@ class PayPalBasePaymentDriver extends BaseDriver ->withHeaders($this->getHeaders($headers)) ->{$verb}("{$this->api_endpoint_url}{$uri}", $data); - if($r->status() <= 422){ - // if($r->successful()) { + if($r->status() <= 422) { + // if($r->successful()) { return $r; } @@ -420,13 +420,13 @@ class PayPalBasePaymentDriver extends BaseDriver $this->client->company ?? $this->company_gateway->company, ); - + return response()->json(['message' => "Gateway failure - {$r->body()}"], 401); // throw new PaymentFailed("Gateway failure - {$r->body()}", 401); } - + public function handleProcessingFailure(array $response) { @@ -443,14 +443,15 @@ class PayPalBasePaymentDriver extends BaseDriver case 'NOT_AUTHORIZED': throw new PaymentFailed("There was a permissions issue processing this payment, please contact the merchant. ", 401); break; - + default: throw new PaymentFailed("Unknown error occurred processing payment. Please contact merchant.", 500); break; } } - public function handleRetry($response, $request) { + public function handleRetry($response, $request) + { return response()->json($response->json()); } @@ -497,8 +498,7 @@ class PayPalBasePaymentDriver extends BaseDriver try { $this->init()->getClientToken(); return true; - } - catch(\Exception $e) { + } catch(\Exception $e) { } @@ -508,7 +508,7 @@ class PayPalBasePaymentDriver extends BaseDriver public function importCustomers() { return true; - } + } public function processWebhookRequest(Request $request) { @@ -517,5 +517,5 @@ class PayPalBasePaymentDriver extends BaseDriver PayPalWebhook::dispatch($request->all(), $request->headers->all(), $this->access_token); } - -} \ No newline at end of file + +} diff --git a/app/PaymentDrivers/PayPal/PayPalWebhook.php b/app/PaymentDrivers/PayPal/PayPalWebhook.php index fa08542af0e1..e4ba19d442fd 100644 --- a/app/PaymentDrivers/PayPal/PayPalWebhook.php +++ b/app/PaymentDrivers/PayPal/PayPalWebhook.php @@ -459,4 +459,4 @@ class PayPalWebhook implements ShouldQueue } ] } - */ \ No newline at end of file + */ diff --git a/app/PaymentDrivers/PayPalPPCPPaymentDriver.php b/app/PaymentDrivers/PayPalPPCPPaymentDriver.php index 45d356c239ad..3c9e7c1cd052 100644 --- a/app/PaymentDrivers/PayPalPPCPPaymentDriver.php +++ b/app/PaymentDrivers/PayPalPPCPPaymentDriver.php @@ -30,26 +30,26 @@ use App\PaymentDrivers\PayPal\PayPalBasePaymentDriver; class PayPalPPCPPaymentDriver extends PayPalBasePaymentDriver { use MakesHash; - -///v1/customer/partners/merchant-accounts/{merchant_id}/capabilities - test if advanced cards is available. -// { -// "capabilities": [ -// { -// "name": "ADVANCED_CARD_PAYMENTS", -// "status": "ENABLED" -// }, -// { -// "name": "VAULTING", -// "status": "ENABLED" -// } -// ] -// } + + ///v1/customer/partners/merchant-accounts/{merchant_id}/capabilities - test if advanced cards is available. + // { + // "capabilities": [ + // { + // "name": "ADVANCED_CARD_PAYMENTS", + // "status": "ENABLED" + // }, + // { + // "name": "VAULTING", + // "status": "ENABLED" + // } + // ] + // } public const SYSTEM_LOG_TYPE = SystemLog::TYPE_PAYPAL_PPCP; - + /** * Checks whether payments are enabled on the merchant account - * + * * @return self */ private function checkPaymentsReceivable(): self @@ -81,7 +81,7 @@ class PayPalPPCPPaymentDriver extends PayPalBasePaymentDriver * Presents the Payment View to the client * * @param array $data - * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View + * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function processPaymentView($data) { @@ -103,10 +103,11 @@ class PayPalPPCPPaymentDriver extends PayPalBasePaymentDriver $data['identifier'] = "s:INN_".$this->company_gateway->getConfigField('merchantId')."_CHCK"; $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); - else + } else { return render('gateways.paypal.ppcp.pay', $data); + } } @@ -120,7 +121,7 @@ class PayPalPPCPPaymentDriver extends PayPalBasePaymentDriver nlog("response"); $r = false; - + $request['gateway_response'] = str_replace("Error: ", "", $request['gateway_response']); $response = json_decode($request['gateway_response'], true); @@ -159,7 +160,7 @@ class PayPalPPCPPaymentDriver extends PayPalBasePaymentDriver if($r->status() == 422) { //handle conditions where the client may need to try again. // return $this->handleRetry($r, $request); - + $r = $this->handleDuplicateInvoiceId($orderID); } @@ -197,7 +198,7 @@ class PayPalPPCPPaymentDriver extends PayPalBasePaymentDriver $this->client, $this->client->company, ); - + return response()->json(['redirect' => route('client.payments.show', ['payment' => $this->encodePrimaryKey($payment->id)], false)]); // return redirect()->route('client.payments.show', ['payment' => $this->encodePrimaryKey($payment->id)]); @@ -301,7 +302,7 @@ class PayPalPPCPPaymentDriver extends PayPalBasePaymentDriver $r = $this->gatewayRequest('/v2/checkout/orders', 'post', $order); $this->payment_hash->withData("orderID", $r->json()['id']); - + return $r->json()['id']; } @@ -309,18 +310,19 @@ class PayPalPPCPPaymentDriver extends PayPalBasePaymentDriver /** * processTokenPayment * - * With PayPal and token payments, the order needs to be + * With PayPal and token payments, the order needs to be * deleted and then created with the payment source that * has been selected by the client. - * - * This method handle the deletion of the current paypal order, + * + * This method handle the deletion of the current paypal order, * and the automatic payment of the order with the selected payment source. - * + * * @param mixed $request * @param array $response * @return void */ - public function processTokenPayment($request, array $response) { + public function processTokenPayment($request, array $response) + { /** @var \App\Models\ClientGatewayToken $cgt */ $cgt = ClientGatewayToken::where('client_id', $this->client->id) @@ -336,18 +338,18 @@ class PayPalPPCPPaymentDriver extends PayPalBasePaymentDriver "vault_id" => $cgt->token, "stored_credential" => [ "payment_initiator" => "MERCHANT", - "payment_type" => "UNSCHEDULED", + "payment_type" => "UNSCHEDULED", "usage" => "SUBSEQUENT", ], ], ]; - + $orderId = $this->createOrder($data); - + $r = $this->gatewayRequest("/v2/checkout/orders/{$orderId}", 'get', ['body' => '']); - + $response = $r->json(); - + $data = [ 'payment_type' => $this->getPaymentMethod($request->gateway_type_id), 'amount' => $response['purchase_units'][0]['payments']['captures'][0]['amount']['value'], @@ -437,5 +439,5 @@ class PayPalPPCPPaymentDriver extends PayPalBasePaymentDriver } - -} \ No newline at end of file + +} diff --git a/app/PaymentDrivers/PayPalRestPaymentDriver.php b/app/PaymentDrivers/PayPalRestPaymentDriver.php index d79d719579dc..6f4a6844a4d3 100644 --- a/app/PaymentDrivers/PayPalRestPaymentDriver.php +++ b/app/PaymentDrivers/PayPalRestPaymentDriver.php @@ -31,7 +31,7 @@ class PayPalRestPaymentDriver extends PayPalBasePaymentDriver public function processPaymentView($data) { - + $this->init(); $data['gateway'] = $this; @@ -49,18 +49,15 @@ class PayPalRestPaymentDriver extends PayPalBasePaymentDriver $data['identifier'] = "s:INN_ACDC_CHCK"; $data['pp_client_reference'] = $this->getClientHash(); - nlog($data['guid']); - nlog($data['order_id']); - - - if($this->gateway_type_id == 29) + if($this->gateway_type_id == 29) { return render('gateways.paypal.ppcp.card', $data); - else + } else { return render('gateways.paypal.pay', $data); + } } - - + + /** * processPaymentResponse * @@ -71,14 +68,15 @@ class PayPalRestPaymentDriver extends PayPalBasePaymentDriver nlog("response"); $this->init(); $r = false; - + $request['gateway_response'] = str_replace("Error: ", "", $request['gateway_response']); $response = json_decode($request['gateway_response'], true); - + 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); + } //capture @@ -104,11 +102,11 @@ class PayPalRestPaymentDriver extends PayPalBasePaymentDriver } - try{ - + try { + $r = $this->gatewayRequest("/v2/checkout/orders/{$orderID}/capture", 'post', ['body' => '']); - if($r->status() == 422){ + if($r->status() == 422) { //handle conditions where the client may need to try again. $r = $this->handleDuplicateInvoiceId($orderID); @@ -116,13 +114,12 @@ class PayPalRestPaymentDriver extends PayPalBasePaymentDriver } - } - catch(\Exception $e) { + } catch(\Exception $e) { //Rescue for duplicate invoice_id - if(stripos($e->getMessage(), 'DUPLICATE_INVOICE_ID') !== false){ + if(stripos($e->getMessage(), 'DUPLICATE_INVOICE_ID') !== false) { + - $r = $this->handleDuplicateInvoiceId($orderID); } @@ -136,7 +133,7 @@ class PayPalRestPaymentDriver extends PayPalBasePaymentDriver if(isset($response['status']) && $response['status'] == 'COMPLETED' && isset($response['purchase_units'])) { - return $this->createNinjaPayment($request, $response); + return $this->createNinjaPayment($request, $response); } else { @@ -161,9 +158,10 @@ class PayPalRestPaymentDriver extends PayPalBasePaymentDriver } - - private function createNinjaPayment($request, $response) { + + private function createNinjaPayment($request, $response) + { $data = [ 'payment_type' => $this->getPaymentMethod($request->gateway_type_id), @@ -268,15 +266,16 @@ class PayPalRestPaymentDriver extends PayPalBasePaymentDriver $order['purchase_units'][0]["shipping"] = $shipping; } - if(isset($data['payment_source'])) + if(isset($data['payment_source'])) { $order['payment_source'] = $data['payment_source']; + } $r = $this->gatewayRequest('/v2/checkout/orders', 'post', $order); nlog($r->json()); $response = $r->json(); - + if($r->status() == 422) { //handle conditions where the client may need to try again. @@ -293,8 +292,9 @@ class PayPalRestPaymentDriver extends PayPalBasePaymentDriver } - if(!isset($response['id'])) + if(!isset($response['id'])) { $this->handleProcessingFailure($response); + } $this->payment_hash->withData("orderID", $response['id']); @@ -307,17 +307,18 @@ class PayPalRestPaymentDriver extends PayPalBasePaymentDriver /** * processTokenPayment * - * With PayPal and token payments, the order needs to be + * With PayPal and token payments, the order needs to be * deleted and then created with the payment source that * has been selected by the client. - * - * This method handle the deletion of the current paypal order, + * + * This method handle the deletion of the current paypal order, * and the automatic payment of the order with the selected payment source. - * + * * @param mixed $request * @param array $response */ - public function processTokenPayment($request, array $response) { + public function processTokenPayment($request, array $response) + { /** @var \App\Models\ClientGatewayToken $cgt */ $cgt = ClientGatewayToken::where('client_id', $this->client->id) @@ -327,7 +328,6 @@ class PayPalRestPaymentDriver extends PayPalBasePaymentDriver $orderId = $response['orderID']; $r = $this->gatewayRequest("/v1/checkout/orders/{$orderId}/", 'delete', ['body' => '']); - nlog("token payyy"); nlog($r->body()); $data['amount_with_fee'] = $this->payment_hash->data->amount_with_fee; @@ -336,16 +336,16 @@ class PayPalRestPaymentDriver extends PayPalBasePaymentDriver "vault_id" => $cgt->token, "stored_credential" => [ "payment_initiator" => "MERCHANT", - "payment_type" => "UNSCHEDULED", + "payment_type" => "UNSCHEDULED", "usage" => "SUBSEQUENT", ], ], ]; - + $orderId = $this->createOrder($data); - + // $r = $this->gatewayRequest("/v2/checkout/orders/{$orderId}", 'get', ['body' => '']); - + try { $r = $this->gatewayRequest("/v2/checkout/orders/{$orderId}", 'get', ['body' => '']); @@ -372,12 +372,8 @@ class PayPalRestPaymentDriver extends PayPalBasePaymentDriver } - - - - $response = $r->json(); - + $data = [ 'payment_type' => $this->getPaymentMethod($request->gateway_type_id), 'amount' => $response['purchase_units'][0]['payments']['captures'][0]['amount']['value'], @@ -420,7 +416,7 @@ class PayPalRestPaymentDriver extends PayPalBasePaymentDriver $orderId = $this->createOrder($data); $r = false; - + try { $r = $this->gatewayRequest("/v2/checkout/orders/{$orderId}", 'get', ['body' => '']); diff --git a/app/PaymentDrivers/PaytracePaymentDriver.php b/app/PaymentDrivers/PaytracePaymentDriver.php index 2b7ac2677bfe..bb0348d0a5dd 100644 --- a/app/PaymentDrivers/PaytracePaymentDriver.php +++ b/app/PaymentDrivers/PaytracePaymentDriver.php @@ -270,8 +270,7 @@ class PaytracePaymentDriver extends BaseDriver try { $this->init()->generateAuthHeaders() && strlen($this->company_gateway->getConfigField('integratorId')) > 2; return true; - } - catch(\Exception $e){ + } catch(\Exception $e) { } @@ -291,31 +290,31 @@ class PaytracePaymentDriver extends BaseDriver nlog($response); if ($response && $response->success) { - + $client_repo = new ClientRepository(new ClientContactRepository()); $factory = new PaytraceCustomerFactory(); - foreach($response->customers as $customer) - { + foreach($response->customers as $customer) { $data = $factory->convertToNinja($customer, $this->company_gateway->company); - + $client = false; - if(str_contains($data['contacts'][0]['email'], "@")) - { + if(str_contains($data['contacts'][0]['email'], "@")) { $client = ClientContact::query() ->where('company_id', $this->company_gateway->company_id) ->where('email', $data['contacts'][0]['email']) ->first()->client ?? false; } - if(!$client) + if(!$client) { $client = $client_repo->save($data, ClientFactory::create($this->company_gateway->company_id, $this->company_gateway->user_id)); - + } + $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; + } $cgt = []; $cgt['token'] = $data['card']['token']; @@ -331,7 +330,7 @@ class PaytracePaymentDriver extends BaseDriver $cgt['payment_meta'] = $payment_meta; $token = $this->storeGatewayToken($cgt, []); - + } } diff --git a/app/PaymentDrivers/Square/CreditCard.php b/app/PaymentDrivers/Square/CreditCard.php index d44f69b77d6c..7a31ad38c90c 100644 --- a/app/PaymentDrivers/Square/CreditCard.php +++ b/app/PaymentDrivers/Square/CreditCard.php @@ -238,5 +238,5 @@ class CreditCard implements MethodInterface return false; } - + } diff --git a/app/PaymentDrivers/SquarePaymentDriver.php b/app/PaymentDrivers/SquarePaymentDriver.php index d8ef5633f450..8e590059e515 100644 --- a/app/PaymentDrivers/SquarePaymentDriver.php +++ b/app/PaymentDrivers/SquarePaymentDriver.php @@ -450,66 +450,68 @@ class SquarePaymentDriver extends BaseDriver public function importCustomers() { - + $limit = 100; $api_response = $this->init() ->square ->getCustomersApi() - ->listCustomers(null, + ->listCustomers( + null, $limit, 'DEFAULT', 'DESC' ); if ($api_response->isSuccess()) { - - while ($api_response->getResult()->getCustomers()) { - $customers = $api_response->getResult()->getCustomers(); + while ($api_response->getResult()->getCustomers()) { - $client_repo = new ClientRepository(new ClientContactRepository()); + $customers = $api_response->getResult()->getCustomers(); - foreach($customers as $customer) - { + $client_repo = new ClientRepository(new ClientContactRepository()); - $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; + foreach($customers as $customer) { - if(!$client) - $client = $client_repo->save($data, ClientFactory::create($this->company_gateway->company_id, $this->company_gateway->user_id)); + $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; - $this->client = $client; + if(!$client) { + $client = $client_repo->save($data, ClientFactory::create($this->company_gateway->company_id, $this->company_gateway->user_id)); + } - foreach($data['cards'] as $card) { - - if(ClientGatewayToken::where('company_id', $this->company_gateway->company_id)->where('token', $card['token'])->exists()) - continue; + $this->client = $client; - $this->storeGatewayToken($card); + foreach($data['cards'] as $card) { + if(ClientGatewayToken::where('company_id', $this->company_gateway->company_id)->where('token', $card['token'])->exists()) { + continue; + } + + $this->storeGatewayToken($card); + + } } - } - - $c = $api_response->getCursor(); - if ($c) { - $api_response = $this->init() - ->square - ->getCustomersApi() - ->listCustomers( + $c = $api_response->getCursor(); + if ($c) { + + $api_response = $this->init() + ->square + ->getCustomersApi() + ->listCustomers( $c, $limit, 'DEFAULT', 'DESC' ); - } else { - break; + } else { + break; + } + + } - - } - } } @@ -558,8 +560,9 @@ class SquarePaymentDriver extends BaseDriver public function findOrCreateClient() { - if($customer_id = $this->findClient()) + if($customer_id = $this->findClient()) { return $customer_id; + } return $this->createClient(); } diff --git a/app/PaymentDrivers/Stripe/ACH.php b/app/PaymentDrivers/Stripe/ACH.php index 6e43f04784cf..b21641609476 100644 --- a/app/PaymentDrivers/Stripe/ACH.php +++ b/app/PaymentDrivers/Stripe/ACH.php @@ -113,10 +113,10 @@ class ACH //double check here if we need to show the verification view. $this->stripe->init(); - if(substr($token->token,0,2) == 'pm'){ + if(substr($token->token, 0, 2) == 'pm') { $pm = $this->stripe->getStripePaymentMethod($token->token); - - if(!$pm->customer){ + + if(!$pm->customer) { $meta = $token->meta; $meta->state = 'unauthorized'; @@ -134,8 +134,9 @@ class ACH ->with('message', __('texts.payment_method_verified')); } - if($token->meta->next_action) + if($token->meta->next_action) { return redirect($token->meta->next_action); + } } @@ -340,7 +341,7 @@ class ACH $data['message'] = 'Too many requests made to the API too quickly'; break; case $e instanceof InvalidRequestException: - + return redirect()->route('client.payment_methods.verification', ['payment_method' => $cgt->hashed_id, 'method' => GatewayType::BANK_TRANSFER]); $data['message'] = 'Invalid parameters were supplied to Stripe\'s API'; diff --git a/app/PaymentDrivers/Stripe/Jobs/PaymentIntentFailureWebhook.php b/app/PaymentDrivers/Stripe/Jobs/PaymentIntentFailureWebhook.php index 1c5a9b24b5b8..28b4db9d7bec 100644 --- a/app/PaymentDrivers/Stripe/Jobs/PaymentIntentFailureWebhook.php +++ b/app/PaymentDrivers/Stripe/Jobs/PaymentIntentFailureWebhook.php @@ -66,12 +66,14 @@ class PaymentIntentFailureWebhook implements ShouldQueue $payment = Payment::query() ->where('company_id', $company->id) ->where(function ($query) use ($transaction) { - - if(isset($transaction['payment_intent'])) + + if(isset($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']); + } if(!isset($transaction['payment_intent']) && isset($transaction['id'])) { $query->where('transaction_reference', $transaction['id']); diff --git a/app/PaymentDrivers/Stripe/Jobs/PaymentIntentProcessingWebhook.php b/app/PaymentDrivers/Stripe/Jobs/PaymentIntentProcessingWebhook.php index c277bb221fd4..3b0c3b30982a 100644 --- a/app/PaymentDrivers/Stripe/Jobs/PaymentIntentProcessingWebhook.php +++ b/app/PaymentDrivers/Stripe/Jobs/PaymentIntentProcessingWebhook.php @@ -64,7 +64,7 @@ class PaymentIntentProcessingWebhook implements ShouldQueue $company = Company::query()->where('company_key', $this->company_key)->first(); foreach ($this->stripe_request as $transaction) { - + $payment = Payment::query() ->where('company_id', $company->id) diff --git a/app/PaymentDrivers/Stripe/Jobs/PaymentIntentWebhook.php b/app/PaymentDrivers/Stripe/Jobs/PaymentIntentWebhook.php index 3cb0d6d403ec..367a99c24206 100644 --- a/app/PaymentDrivers/Stripe/Jobs/PaymentIntentWebhook.php +++ b/app/PaymentDrivers/Stripe/Jobs/PaymentIntentWebhook.php @@ -63,7 +63,7 @@ class PaymentIntentWebhook implements ShouldQueue $company = Company::query()->where('company_key', $this->company_key)->first(); foreach ($this->stripe_request as $transaction) { - + $payment = Payment::query() ->where('company_id', $company->id) ->where(function ($query) use ($transaction) { @@ -100,8 +100,9 @@ class PaymentIntentWebhook implements ShouldQueue $company_gateway = CompanyGateway::query()->find($this->company_gateway_id); - if(!$company_gateway) + if(!$company_gateway) { return; + } $stripe_driver = $company_gateway->driver()->init(); diff --git a/app/PaymentDrivers/StripePaymentDriver.php b/app/PaymentDrivers/StripePaymentDriver.php index d5f8e689dad7..32a1d3fe552e 100644 --- a/app/PaymentDrivers/StripePaymentDriver.php +++ b/app/PaymentDrivers/StripePaymentDriver.php @@ -263,7 +263,7 @@ class StripePaymentDriver extends BaseDriver && in_array($this->client->country->iso_3166_3, ['AUT','BEL','DNK','FIN','FRA','DEU','IRL','ITA','NLD','NOR','ESP','SWE','GBR','USA'])) { $types[] = GatewayType::KLARNA; } - + if ( $this->client && isset($this->client->country) @@ -330,12 +330,12 @@ class StripePaymentDriver extends BaseDriver } // if ($this->company_gateway->require_contact_name) { - $fields[] = ['name' => 'contact_first_name', 'label' => ctrans('texts.first_name'), 'type' => 'text', 'validation' => 'required']; - $fields[] = ['name' => 'contact_last_name', 'label' => ctrans('texts.last_name'), 'type' => 'text', 'validation' => 'required']; + $fields[] = ['name' => 'contact_first_name', 'label' => ctrans('texts.first_name'), 'type' => 'text', 'validation' => 'required']; + $fields[] = ['name' => 'contact_last_name', 'label' => ctrans('texts.last_name'), 'type' => 'text', 'validation' => 'required']; // } // if ($this->company_gateway->require_contact_email) { - $fields[] = ['name' => 'contact_email', 'label' => ctrans('texts.email'), 'type' => 'text', 'validation' => 'required,email:rfc']; + $fields[] = ['name' => 'contact_email', 'label' => ctrans('texts.email'), 'type' => 'text', 'validation' => 'required,email:rfc']; // } if ($this->company_gateway->require_client_phone) { @@ -680,7 +680,7 @@ class StripePaymentDriver extends BaseDriver } if ($request->type === 'payment_intent.processing') { - PaymentIntentProcessingWebhook::dispatch($request->data, $request->company_key, $this->company_gateway->id)->delay(now()->addSeconds(rand(10,12))); + PaymentIntentProcessingWebhook::dispatch($request->data, $request->company_key, $this->company_gateway->id)->delay(now()->addSeconds(rand(10, 12))); return response()->json([], 200); } @@ -705,26 +705,26 @@ class StripePaymentDriver extends BaseDriver if ($request->type === 'charge.succeeded') { foreach ($request->data as $transaction) { - - $payment = Payment::query() - ->where('company_id', $this->company_gateway->company_id) - ->where(function ($query) use ($transaction) { - if(isset($transaction['payment_intent'])) { - $query->where('transaction_reference', $transaction['payment_intent']); - } + $payment = Payment::query() + ->where('company_id', $this->company_gateway->company_id) + ->where(function ($query) use ($transaction) { - if(isset($transaction['payment_intent']) && isset($transaction['id'])) { - $query->orWhere('transaction_reference', $transaction['id']); - } + if(isset($transaction['payment_intent'])) { + $query->where('transaction_reference', $transaction['payment_intent']); + } - if(!isset($transaction['payment_intent']) && isset($transaction['id'])) { - $query->where('transaction_reference', $transaction['id']); - } + if(isset($transaction['payment_intent']) && isset($transaction['id'])) { + $query->orWhere('transaction_reference', $transaction['id']); + } - }) - ->first(); + if(!isset($transaction['payment_intent']) && isset($transaction['id'])) { + $query->where('transaction_reference', $transaction['id']); + } + + }) + ->first(); if ($payment) { @@ -752,26 +752,26 @@ class StripePaymentDriver extends BaseDriver ], $this->stripe_connect_auth); if ($charge->captured) { - - $payment = Payment::query() - ->where('company_id', $this->company_gateway->company_id) - ->where(function ($query) use ($transaction) { - if(isset($transaction['payment_intent'])) { - $query->where('transaction_reference', $transaction['payment_intent']); - } + $payment = Payment::query() + ->where('company_id', $this->company_gateway->company_id) + ->where(function ($query) use ($transaction) { - if(isset($transaction['payment_intent']) && isset($transaction['id'])) { - $query->orWhere('transaction_reference', $transaction['id']); - } + if(isset($transaction['payment_intent'])) { + $query->where('transaction_reference', $transaction['payment_intent']); + } - if(!isset($transaction['payment_intent']) && isset($transaction['id'])) { - $query->where('transaction_reference', $transaction['id']); - } + if(isset($transaction['payment_intent']) && isset($transaction['id'])) { + $query->orWhere('transaction_reference', $transaction['id']); + } - }) - ->first(); + if(!isset($transaction['payment_intent']) && isset($transaction['id'])) { + $query->where('transaction_reference', $transaction['id']); + } + + }) + ->first(); @@ -1010,9 +1010,8 @@ class StripePaymentDriver extends BaseDriver try { $this->verifyConnect(); return true; - } - catch(\Exception $e) { - + } catch(\Exception $e) { + } return false; diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index f90a4a9e4a48..ec849224b615 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -122,7 +122,7 @@ class AppServiceProvider extends ServiceProvider }); Mail::extend('brevo', function () { - return (new BrevoTransportFactory)->create( + return (new BrevoTransportFactory())->create( new Dsn( 'brevo+api', 'default', @@ -133,7 +133,7 @@ class AppServiceProvider extends ServiceProvider Mailer::macro('brevo_config', function (string $brevo_key) { // @phpstan-ignore /** @phpstan-ignore-next-line **/ Mailer::setSymfonyTransport( - (new BrevoTransportFactory)->create( + (new BrevoTransportFactory())->create( new Dsn( 'brevo+api', 'default', diff --git a/app/Providers/StaticServiceProvider.php b/app/Providers/StaticServiceProvider.php index 4327edb1682d..523a92e08c0b 100644 --- a/app/Providers/StaticServiceProvider.php +++ b/app/Providers/StaticServiceProvider.php @@ -34,7 +34,7 @@ class StaticServiceProvider extends ServiceProvider public function register() { - + app()->singleton('currencies', function ($app) { return Currency::query()->orderBy('name')->get(); }); @@ -128,4 +128,4 @@ class StaticServiceProvider extends ServiceProvider { } -} \ No newline at end of file +} diff --git a/app/Repositories/BankTransactionRepository.php b/app/Repositories/BankTransactionRepository.php index f7d275ae9057..8488f12938f8 100644 --- a/app/Repositories/BankTransactionRepository.php +++ b/app/Repositories/BankTransactionRepository.php @@ -42,7 +42,7 @@ class BankTransactionRepository extends BaseRepository $data['transactions'] = $bank_transactions->map(function ($bt) { return ['id' => $bt->id, 'invoice_ids' => $bt->invoice_ids, 'ninja_category_id' => $bt->ninja_category_id]; })->toArray(); - + $bts = (new MatchBankTransactions($user->company()->id, $user->company()->db, $data))->handle(); } diff --git a/app/Repositories/BaseRepository.php b/app/Repositories/BaseRepository.php index ff2c6e1f8816..24248c58b08f 100644 --- a/app/Repositories/BaseRepository.php +++ b/app/Repositories/BaseRepository.php @@ -380,7 +380,7 @@ class BaseRepository return $model->fresh(); } - public function bulkUpdate(\Illuminate\Database\Eloquent\Builder $model, string $column, mixed $new_value) :void + public function bulkUpdate(\Illuminate\Database\Eloquent\Builder $model, string $column, mixed $new_value): void { $model->update([$column => $new_value]); } diff --git a/app/Repositories/ClientRepository.php b/app/Repositories/ClientRepository.php index f9c25a2e3ab0..8c52b83f9572 100644 --- a/app/Repositories/ClientRepository.php +++ b/app/Repositories/ClientRepository.php @@ -126,7 +126,7 @@ class ClientRepository extends BaseRepository ClientFactory::create($user->company()->id, $user->id) ); } - + /** * Bulk assign clients to a group. * @@ -144,7 +144,7 @@ class ClientRepository extends BaseRepository public function purge($client) { - + nlog("Purging client id => {$client->id}"); $client->contacts()->forceDelete(); diff --git a/app/Repositories/SubscriptionRepository.php b/app/Repositories/SubscriptionRepository.php index fc668600cd91..e340b0e78d51 100644 --- a/app/Repositories/SubscriptionRepository.php +++ b/app/Repositories/SubscriptionRepository.php @@ -118,25 +118,26 @@ class SubscriptionRepository extends BaseRepository return $line_items; } - + /** * ConvertV3Bundle * * Removing the nested keys of the items array - * + * * @param array $bundle * @return array */ private function convertV3Bundle($bundle): array { - if(is_object($bundle)) - $bundle = json_decode(json_encode($bundle),1); + if(is_object($bundle)) { + $bundle = json_decode(json_encode($bundle), 1); + } $items = []; 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->qty = (float) $value['quantity']; $line_item->unit_cost = (float) $value['product']['price']; @@ -147,7 +148,7 @@ class SubscriptionRepository extends BaseRepository 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->qty = (float) $value['quantity']; $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) { - if(isset($bundle->recurring_products)) + if(isset($bundle->recurring_products)) { $bundle = $this->convertV3Bundle($bundle); + } $multiplier = $is_credit ? -1 : 1; diff --git a/app/Repositories/TaskRepository.php b/app/Repositories/TaskRepository.php index 36097917be28..0da689a3bfd5 100644 --- a/app/Repositories/TaskRepository.php +++ b/app/Repositories/TaskRepository.php @@ -111,8 +111,7 @@ class TaskRepository extends BaseRepository $key_values = array_column($time_log, 0); 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]); } @@ -254,25 +253,28 @@ class TaskRepository extends BaseRepository 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; + } $interval = $end_time - $start_time; - - if($this->task_round_up) - return $start_time + (int)ceil($interval/$this->task_round_to_nearest)*$this->task_round_to_nearest; - if($interval <= $this->task_round_to_nearest) + if($this->task_round_up) { + return $start_time + (int)ceil($interval / $this->task_round_to_nearest) * $this->task_round_to_nearest; + } + + if($interval <= $this->task_round_to_nearest) { 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; } public function stop(Task $task) { $this->init($task); - + $log = json_decode($task->time_log, true); $last = end($log); @@ -305,7 +307,7 @@ class TaskRepository extends BaseRepository private function init(Task $task): self { - + $this->task_round_up = $task->client ? $task->client->getSetting('task_round_up') : $task->company->getSetting('task_round_up'); $this->task_round_to_nearest = $task->client ? $task->client->getSetting('task_round_to_nearest') : $task->company->getSetting('task_round_to_nearest'); diff --git a/app/Repositories/UserRepository.php b/app/Repositories/UserRepository.php index 4334b87cea70..d155c133bd3b 100644 --- a/app/Repositories/UserRepository.php +++ b/app/Repositories/UserRepository.php @@ -207,7 +207,7 @@ class UserRepository extends BaseRepository $cu->restore(); $cu->tokens()->restore(); - + event(new UserWasRestored($user, auth()->user(), auth()->user()->company, Ninja::eventVars(auth()->user() ? auth()->user()->id : null))); } diff --git a/app/Services/Client/Statement.php b/app/Services/Client/Statement.php index a1a93fc900f4..9b574e0674dd 100644 --- a/app/Services/Client/Statement.php +++ b/app/Services/Client/Statement.php @@ -63,10 +63,10 @@ class Statement $variables = []; $variables = $html->generateLabelsAndValues(); - + $option_template = &$this->options['template']; - $custom_statement_template = \App\Models\Design::where('id', $this->decodePrimaryKey($this->client->getSetting('statement_design_id')))->where('is_template',true)->first(); + $custom_statement_template = \App\Models\Design::where('id', $this->decodePrimaryKey($this->client->getSetting('statement_design_id')))->where('is_template', true)->first(); if($custom_statement_template || $option_template && $option_template != '') { diff --git a/app/Services/ClientPortal/InstantPayment.php b/app/Services/ClientPortal/InstantPayment.php index 3bbb8489e42b..aea285866945 100644 --- a/app/Services/ClientPortal/InstantPayment.php +++ b/app/Services/ClientPortal/InstantPayment.php @@ -45,7 +45,7 @@ class InstantPayment public function run() { nlog($this->request->all()); - + /** @var \App\Models\ClientContact $cc */ $cc = auth()->guard('contact')->user(); diff --git a/app/Services/Credit/CreditService.php b/app/Services/Credit/CreditService.php index 8c6f1929345d..9474058f85f9 100644 --- a/app/Services/Credit/CreditService.php +++ b/app/Services/Credit/CreditService.php @@ -47,7 +47,7 @@ class CreditService { return $this->getECredit($contact); } - + /** * Applies the invoice number. * @return $this InvoiceService object diff --git a/app/Services/EDocument/Standards/FatturaPA.php b/app/Services/EDocument/Standards/FatturaPA.php index 24da1fc4794e..626c67d26dc1 100644 --- a/app/Services/EDocument/Standards/FatturaPA.php +++ b/app/Services/EDocument/Standards/FatturaPA.php @@ -51,12 +51,12 @@ class FatturaPA extends AbstractService /** * File Types - * + * * EI01 => FILE VUOTO * EI02 => SERVIZIO NON DISPONIBILE * EI03 => UTENTE NON ABILITATO */ - + /** Formato Trasmissione * FPA12: This is the format used for FatturaPA version 1.2. * FPR12: This format is used for FatturaPA version 1.2 in cases where the invoice is destined for the Public Administration. @@ -70,7 +70,7 @@ class FatturaPA extends AbstractService * "D" (Differita): VAT is due at a later date, typically when payment for the goods or services is received. * "S" (Soggetta): VAT is due under the reverse charge mechanism, where the recipient of the goods or services is responsible for accounting for the VAT. */ - + /** * MP01 contanti //cash * MP02 assegno //check @@ -97,11 +97,11 @@ class FatturaPA extends AbstractService * MP23 PagoPA //PagoPA */ - /** - * TP01 pagamento a rate //payment in installments - * TP02 pagamento completo //full payment - * TP03 anticipo //advance - */ + /** + * TP01 pagamento a rate //payment in installments + * TP02 pagamento completo //full payment + * TP03 anticipo //advance + */ /** * @param Invoice $invoice @@ -113,181 +113,184 @@ class FatturaPA extends AbstractService public function run() { - $fatturaHeader = new FatturaElettronicaHeader(); + $fatturaHeader = new FatturaElettronicaHeader(); - $datiTrasmissione = new DatiTrasmissione(); - $datiTrasmissione->setFormatoTrasmissione("FPR12"); - $datiTrasmissione->setCodiceDestinatario($this->invoice->client->routing_id); - $datiTrasmissione->setProgressivoInvio($this->invoice->number); + $datiTrasmissione = new DatiTrasmissione(); + $datiTrasmissione->setFormatoTrasmissione("FPR12"); + $datiTrasmissione->setCodiceDestinatario($this->invoice->client->routing_id); + $datiTrasmissione->setProgressivoInvio($this->invoice->number); - $idPaese = new IdTrasmittente(); - $idPaese->setIdPaese($this->invoice->company->country()->iso_3166_2); - $idPaese->setIdCodice($this->invoice->company->settings->vat_number); + $idPaese = new IdTrasmittente(); + $idPaese->setIdPaese($this->invoice->company->country()->iso_3166_2); + $idPaese->setIdCodice($this->invoice->company->settings->vat_number); - $datiTrasmissione->setIdTrasmittente($idPaese); - $fatturaHeader->setDatiTrasmissione($datiTrasmissione); + $datiTrasmissione->setIdTrasmittente($idPaese); + $fatturaHeader->setDatiTrasmissione($datiTrasmissione); - $cedentePrestatore = new CedentePrestatore(); - $datiAnagrafici = new DatiAnagrafici(); - $idFiscaleIVA = new IdFiscaleIVA(IdPaese: $this->invoice->company->country()->iso_3166_2, IdCodice: $this->invoice->company->settings->vat_number); - $datiAnagrafici->setIdFiscaleIVA($idFiscaleIVA); + $cedentePrestatore = new CedentePrestatore(); + $datiAnagrafici = new DatiAnagrafici(); + $idFiscaleIVA = new IdFiscaleIVA(IdPaese: $this->invoice->company->country()->iso_3166_2, IdCodice: $this->invoice->company->settings->vat_number); + $datiAnagrafici->setIdFiscaleIVA($idFiscaleIVA); - $anagrafica = new Anagrafica(Denominazione: $this->invoice->company->present()->name()); - $datiAnagrafici->setAnagrafica($anagrafica); - $datiAnagrafici->setRegimeFiscale("RF01"); //swap this out with the custom settings. - $cedentePrestatore->setDatiAnagrafici($datiAnagrafici); + $anagrafica = new Anagrafica(Denominazione: $this->invoice->company->present()->name()); + $datiAnagrafici->setAnagrafica($anagrafica); + $datiAnagrafici->setRegimeFiscale("RF01"); //swap this out with the custom settings. + $cedentePrestatore->setDatiAnagrafici($datiAnagrafici); - $sede = new Sede(Indirizzo: $this->invoice->company->settings->address1, - CAP: (int)$this->invoice->company->settings->postal_code, - Comune: $this->invoice->company->settings->city, - Provincia: $this->invoice->company->settings->state); + $sede = new Sede( + Indirizzo: $this->invoice->company->settings->address1, + CAP: (int)$this->invoice->company->settings->postal_code, + Comune: $this->invoice->company->settings->city, + Provincia: $this->invoice->company->settings->state + ); - $cedentePrestatore->setSede($sede); - $fatturaHeader->setCedentePrestatore($cedentePrestatore); + $cedentePrestatore->setSede($sede); + $fatturaHeader->setCedentePrestatore($cedentePrestatore); - //client details - $datiAnagrafici = new DatiAnagrafici(); + //client details + $datiAnagrafici = new DatiAnagrafici(); -//for some reason the validation does not like codice fiscale for the client? -//perhaps it may need IdFiscaleIVA? -// $datiAnagrafici->setCodiceFiscale("09876543210"); + //for some reason the validation does not like codice fiscale for the client? + //perhaps it may need IdFiscaleIVA? + // $datiAnagrafici->setCodiceFiscale("09876543210"); - $anagrafica = new Anagrafica(Denominazione: $this->invoice->client->present()->name()); - $datiAnagrafici->setAnagrafica($anagrafica); + $anagrafica = new Anagrafica(Denominazione: $this->invoice->client->present()->name()); + $datiAnagrafici->setAnagrafica($anagrafica); - $sede = new Sede(Indirizzo: $this->invoice->client->address1, - CAP: (int)$this->invoice->client->postal_code, - Comune: $this->invoice->client->city, - Provincia: $this->invoice->client->state); + $sede = new Sede( + Indirizzo: $this->invoice->client->address1, + CAP: (int)$this->invoice->client->postal_code, + Comune: $this->invoice->client->city, + Provincia: $this->invoice->client->state + ); - $cessionarioCommittente = new CessionarioCommittente($datiAnagrafici, $sede); + $cessionarioCommittente = new CessionarioCommittente($datiAnagrafici, $sede); - $fatturaHeader->setCessionarioCommittente($cessionarioCommittente); + $fatturaHeader->setCessionarioCommittente($cessionarioCommittente); -////////////////// Fattura Body ////////////////// -$fatturaBody = new FatturaElettronicaBody(); + ////////////////// Fattura Body ////////////////// + $fatturaBody = new FatturaElettronicaBody(); -$datiGeneraliDocument = new DatiGeneraliDocumento(); -$datiGeneraliDocument->setTipoDocumento("TD01") - ->setDivisa($this->invoice->client->currency()->code) - ->setData($this->invoice->date) - ->setNumero($this->invoice->number) - ->setCausale($this->invoice->public_notes ?? ''); //unsure... + $datiGeneraliDocument = new DatiGeneraliDocumento(); + $datiGeneraliDocument->setTipoDocumento("TD01") + ->setDivisa($this->invoice->client->currency()->code) + ->setData($this->invoice->date) + ->setNumero($this->invoice->number) + ->setCausale($this->invoice->public_notes ?? ''); //unsure... -/**PO information -$datiOrdineAcquisto = new DatiOrdineAcquisto(); -$datiOrdineAcquisto->setRiferimentoNumeroLinea(1) - ->setIdDocumento($this->invoice->po_number) - ->setNumItem(1) - ->setCodiceCIG("123abc") // special invoice props - ->setCodiceCUP("456def"); // special invoice props -*/ + /**PO information + $datiOrdineAcquisto = new DatiOrdineAcquisto(); + $datiOrdineAcquisto->setRiferimentoNumeroLinea(1) + ->setIdDocumento($this->invoice->po_number) + ->setNumItem(1) + ->setCodiceCIG("123abc") // special invoice props + ->setCodiceCUP("456def"); // special invoice props + */ -/**Contract data -$datiContratto = new DatiContratto( - RiferimentoNumeroLinea: 1, - IdDocumento: 6685, - Data: "2024-01-01", - NumItem: 5, - CodiceCUP: "123abc", - CodiceCIG: "456def", -); -*/ + /**Contract data + $datiContratto = new DatiContratto( + RiferimentoNumeroLinea: 1, + IdDocumento: 6685, + Data: "2024-01-01", + NumItem: 5, + CodiceCUP: "123abc", + CodiceCIG: "456def", + ); + */ -/**Shipping/Delivery Data -$datiRicezione = new DatiRicezione( - RiferimentoNumeroLinea: 1, - IdDocumento: 6685, - Data: "2024-01-01", - NumItem: 5, - CodiceCUP: "123abc", - CodiceCIG: "456def", -); - */ + /**Shipping/Delivery Data + $datiRicezione = new DatiRicezione( + RiferimentoNumeroLinea: 1, + IdDocumento: 6685, + Data: "2024-01-01", + NumItem: 5, + CodiceCUP: "123abc", + CodiceCIG: "456def", + ); + */ - /**Shippers details + /**Shippers details $datiAnagraficiVettore = new DatiAnagraficiVettore(); $idFiscaleIVA = new IdFiscaleIVA("IT", "24681012141"); $anagrafica = new Anagrafica("Trasport SPA"); $datiAnagraficiVettore->setIdFiscaleIVA($idFiscaleIVA) - ->setAnagrafica($anagrafica); + ->setAnagrafica($anagrafica); $datiTrasporto = new DatiTrasporto(); $datiTrasporto->setDatiAnagraficiVettore($datiAnagraficiVettore) - ->setDataOraConsegna("2017-01-10T16:46:12.000+02:00"); + ->setDataOraConsegna("2017-01-10T16:46:12.000+02:00"); */ -$datiGenerali = new DatiGenerali(); -$datiGenerali->setDatiGeneraliDocumento($datiGeneraliDocument); - // ->setDatiOrdineAcquisto($datiOrdineAcquisto) - // ->setDatiContratto($datiContratto) - // ->setDatiRicezione($datiRicezione); + $datiGenerali = new DatiGenerali(); + $datiGenerali->setDatiGeneraliDocumento($datiGeneraliDocument); + // ->setDatiOrdineAcquisto($datiOrdineAcquisto) + // ->setDatiContratto($datiContratto) + // ->setDatiRicezione($datiRicezione); - $datiBeniServizi = new DatiBeniServizi(); - $tax_rate_level = 0; - //line items - foreach ($this->invoice->line_items as $key => $item) - { + $datiBeniServizi = new DatiBeniServizi(); + $tax_rate_level = 0; + //line items + foreach ($this->invoice->line_items as $key => $item) { - $numero = $key+1; - $dettaglioLinee = new DettaglioLinee( - NumeroLinea: "{$numero}", - Descrizione: $item->notes ?? 'Descrizione', - Quantita: sprintf('%0.2f', $item->quantity), - PrezzoUnitario: sprintf('%0.2f', $item->cost), - PrezzoTotale: sprintf('%0.2f', $item->line_total), - AliquotaIVA: sprintf('%0.2f', $item->tax_rate1), - ); + $numero = $key + 1; + $dettaglioLinee = new DettaglioLinee( + NumeroLinea: "{$numero}", + Descrizione: $item->notes ?? 'Descrizione', + Quantita: sprintf('%0.2f', $item->quantity), + PrezzoUnitario: sprintf('%0.2f', $item->cost), + PrezzoTotale: sprintf('%0.2f', $item->line_total), + AliquotaIVA: sprintf('%0.2f', $item->tax_rate1), + ); - $datiBeniServizi->setDettaglioLinee($dettaglioLinee); + $datiBeniServizi->setDettaglioLinee($dettaglioLinee); + + if ($item->tax_rate1 > $tax_rate_level) { + $tax_rate_level = sprintf('%0.2f', $item->tax_rate1); + } - if ($item->tax_rate1 > $tax_rate_level) { - $tax_rate_level = sprintf('%0.2f', $item->tax_rate1); } - } - - //totals - if($this->invoice->tax_rate1 > $tax_rate_level) { - $tax_rate_level = sprintf('%0.2f', $this->invoice->tax_rate1); - } + //totals + if($this->invoice->tax_rate1 > $tax_rate_level) { + $tax_rate_level = sprintf('%0.2f', $this->invoice->tax_rate1); + } - $calc = $this->invoice->calc(); - $subtotal = sprintf('%0.2f', $calc->getSubTotal()); - $taxes = sprintf('%0.2f', $calc->getTotalTaxes()); + $calc = $this->invoice->calc(); + $subtotal = sprintf('%0.2f', $calc->getSubTotal()); + $taxes = sprintf('%0.2f', $calc->getTotalTaxes()); - $datiRiepilogo = new DatiRiepilogo( - AliquotaIVA: "{$tax_rate_level}", - ImponibileImporto: "{$subtotal}", - Imposta: "{$taxes}", - EsigibilitaIVA: "I", - ); + $datiRiepilogo = new DatiRiepilogo( + AliquotaIVA: "{$tax_rate_level}", + ImponibileImporto: "{$subtotal}", + Imposta: "{$taxes}", + EsigibilitaIVA: "I", + ); - $datiBeniServizi->setDatiRiepilogo($datiRiepilogo); + $datiBeniServizi->setDatiRiepilogo($datiRiepilogo); - $dettalioPagament = new DettaglioPagamento( - ModalitaPagamento: "MP01", //String - DataScadenzaPagamento: (string) $this->invoice->due_date ?? $this->invoice->date, - ImportoPagamento: (string) sprintf('%0.2f', $this->invoice->balance), - ); + $dettalioPagament = new DettaglioPagamento( + ModalitaPagamento: "MP01", //String + DataScadenzaPagamento: (string) $this->invoice->due_date ?? $this->invoice->date, + ImportoPagamento: (string) sprintf('%0.2f', $this->invoice->balance), + ); - $datiPagamento = new DatiPagamento(); - $datiPagamento->setCondizioniPagamento("TP02") - ->setDettaglioPagamento($dettalioPagament); + $datiPagamento = new DatiPagamento(); + $datiPagamento->setCondizioniPagamento("TP02") + ->setDettaglioPagamento($dettalioPagament); - $fatturaBody->setDatiGenerali($datiGenerali) - ->setDatiBeniServizi($datiBeniServizi) - ->setDatiPagamento($datiPagamento); + $fatturaBody->setDatiGenerali($datiGenerali) + ->setDatiBeniServizi($datiBeniServizi) + ->setDatiPagamento($datiPagamento); - //////////////////////////////////// - $xmlService = new Service(); + //////////////////////////////////// + $xmlService = new Service(); - $xml = $xmlService->write('p:FatturaElettronica', new FatturaElettronica($fatturaHeader, $fatturaBody)); + $xml = $xmlService->write('p:FatturaElettronica', new FatturaElettronica($fatturaHeader, $fatturaBody)); - return $xml; + return $xml; } -} \ No newline at end of file +} diff --git a/app/Services/EDocument/Standards/FatturaPANew.php b/app/Services/EDocument/Standards/FatturaPANew.php index 6cdb87549b52..5988e27b9d59 100644 --- a/app/Services/EDocument/Standards/FatturaPANew.php +++ b/app/Services/EDocument/Standards/FatturaPANew.php @@ -90,7 +90,7 @@ class FatturaPANew extends AbstractService } - private function setIdTrasmittente():self + private function setIdTrasmittente(): self { $this->IdTrasmittente->IdPaese = $this->invoice->company->country()->iso_3166_2; $this->IdTrasmittente->IdCodice = $this->invoice->company->settings->vat_number; @@ -98,11 +98,11 @@ class FatturaPANew extends AbstractService return $this; } - private function setCedentePrestatore():self + private function setCedentePrestatore(): self { $this->CedentePrestatore->DatiAnagrafici = $this->DatiAnagrafici; - $sede = new Sede; + $sede = new Sede(); $sede->Indirizzo = $this->invoice->company->settings->address1; $sede->CAP = (int)$this->invoice->company->settings->postal_code; $sede->Comune = $this->invoice->company->settings->city; @@ -115,7 +115,7 @@ class FatturaPANew extends AbstractService return $this; } - private function setDatiAnagrafici():self + private function setDatiAnagrafici(): self { $this->DatiAnagrafici->RegimeFiscale = "RF01"; $this->DatiAnagrafici->Anagrafica = $this->Anagrafica; @@ -124,7 +124,7 @@ class FatturaPANew extends AbstractService return $this; } - private function setClientDetails():self + private function setClientDetails(): self { $datiAnagrafici = new DatiAnagrafici(); @@ -132,20 +132,20 @@ class FatturaPANew extends AbstractService $anagrafica->Denominazione = $this->invoice->client->present()->name(); $datiAnagrafici->Anagrafica = $anagrafica; - $idFiscale = new IdFiscaleIVA; - $idFiscale->IdCodice= $this->invoice->client->vat_number; + $idFiscale = new IdFiscaleIVA(); + $idFiscale->IdCodice = $this->invoice->client->vat_number; $idFiscale->IdPaese = $this->invoice->client->country->iso_3166_2; $datiAnagrafici->IdFiscaleIVA = $idFiscale; - - $sede = new Sede; + + $sede = new Sede(); $sede->Indirizzo = $this->invoice->client->address1; $sede->CAP = (int)$this->invoice->client->postal_code; $sede->Comune = $this->invoice->client->city; $sede->Provincia = $this->invoice->client->state; $sede->Nazione = $this->invoice->client->country->iso_3166_2; - $cessionarioCommittente = new CessionarioCommittente; + $cessionarioCommittente = new CessionarioCommittente(); $cessionarioCommittente->DatiAnagrafici = $datiAnagrafici; $cessionarioCommittente->Sede = $sede; @@ -154,7 +154,7 @@ class FatturaPANew extends AbstractService return $this; } - private function setIdFiscaleIVA():self + private function setIdFiscaleIVA(): self { $this->IdFiscaleIVA->IdPaese = $this->invoice->company->country()->iso_3166_2; @@ -164,14 +164,14 @@ class FatturaPANew extends AbstractService } //this is a choice, need to switch based on values here. - private function setAnagrafica():self + private function setAnagrafica(): self { $this->Anagrafica->Denominazione = $this->invoice->company->present()->name(); return $this; } - private function setDatiGeneraliDocumento():self + private function setDatiGeneraliDocumento(): self { $this->DatiGeneraliDocumento->TipoDocumento = "TD01"; @@ -183,23 +183,23 @@ class FatturaPANew extends AbstractService return $this; } - private function setDatiGenerali():self + private function setDatiGenerali(): self { $this->DatiGenerali->DatiGeneraliDocumento = $this->DatiGeneraliDocumento; $this->FatturaElettronicaBody->DatiGenerali = $this->DatiGenerali; - + return $this; } - private function setDettaglioPagamento():self + private function setDettaglioPagamento(): self { $this->DettaglioPagamento->ModalitaPagamento = "MP01"; //String $this->DettaglioPagamento->DataScadenzaPagamento = new \DateTime($this->invoice->due_date ?? $this->invoice->date); $this->DettaglioPagamento->ImportoPagamento = (string) sprintf('%0.2f', $this->invoice->balance); - $DatiPagamento = new DatiPagamento; + $DatiPagamento = new DatiPagamento(); $DatiPagamento->CondizioniPagamento = "TP02"; $DatiPagamento->DettaglioPagamento[] = $this->DettaglioPagamento; @@ -219,14 +219,14 @@ class FatturaPANew extends AbstractService foreach ($this->invoice->line_items as $key => $item) { $numero = $key + 1; - $dettaglioLinee = new DettaglioLinee; + $dettaglioLinee = new DettaglioLinee(); $dettaglioLinee->NumeroLinea = "{$numero}"; $dettaglioLinee->Descrizione = $item->notes ?? 'Descrizione'; $dettaglioLinee->Quantita = sprintf('%0.2f', $item->quantity); $dettaglioLinee->PrezzoUnitario = sprintf('%0.2f', $item->cost); $dettaglioLinee->PrezzoTotale = sprintf('%0.2f', $item->line_total); $dettaglioLinee->AliquotaIVA = sprintf('%0.2f', $item->tax_rate1); - + $datiBeniServizi->DettaglioLinee[] = $dettaglioLinee; @@ -244,7 +244,7 @@ class FatturaPANew extends AbstractService $subtotal = sprintf('%0.2f', $calc->getSubTotal()); $taxes = sprintf('%0.2f', $calc->getTotalTaxes()); - $datiRiepilogo = new DatiRiepilogo; + $datiRiepilogo = new DatiRiepilogo(); $datiRiepilogo->AliquotaIVA = "{$tax_rate_level}"; $datiRiepilogo->ImponibileImporto = "{$subtotal}"; $datiRiepilogo->Imposta = "{$taxes}"; @@ -269,20 +269,20 @@ class FatturaPANew extends AbstractService private function init(): self { - $this->FatturaElettronica = new FatturaElettronica; - $this->FatturaElettronicaBody = new FatturaElettronicaBody; - $this->FatturaElettronicaHeader = new FatturaElettronicaHeader; - $this->DatiTrasmissione = new DatiTrasmissione; - $this->IdTrasmittente = new IdTrasmittente; - $this->CedentePrestatore = new CedentePrestatore; - $this->DatiAnagrafici = new DatiAnagrafici; - $this->IdFiscaleIVA = new IdFiscaleIVA; - $this->Anagrafica = new Anagrafica; - $this->DatiGeneraliDocumento = new DatiGeneraliDocumento; - $this->DatiGenerali = new DatiGenerali; - $this->DettaglioPagamento = new DettaglioPagamento; - + $this->FatturaElettronica = new FatturaElettronica(); + $this->FatturaElettronicaBody = new FatturaElettronicaBody(); + $this->FatturaElettronicaHeader = new FatturaElettronicaHeader(); + $this->DatiTrasmissione = new DatiTrasmissione(); + $this->IdTrasmittente = new IdTrasmittente(); + $this->CedentePrestatore = new CedentePrestatore(); + $this->DatiAnagrafici = new DatiAnagrafici(); + $this->IdFiscaleIVA = new IdFiscaleIVA(); + $this->Anagrafica = new Anagrafica(); + $this->DatiGeneraliDocumento = new DatiGeneraliDocumento(); + $this->DatiGenerali = new DatiGenerali(); + $this->DettaglioPagamento = new DettaglioPagamento(); + return $this; } -} \ No newline at end of file +} diff --git a/app/Services/EDocument/Standards/OrderXDocument.php b/app/Services/EDocument/Standards/OrderXDocument.php index f6dbaf3e3dd7..de3af56868d5 100644 --- a/app/Services/EDocument/Standards/OrderXDocument.php +++ b/app/Services/EDocument/Standards/OrderXDocument.php @@ -25,7 +25,7 @@ use horstoeko\orderx\OrderProfiles; class OrderXDocument extends AbstractService { public OrderDocumentBuilder $orderxdocument; - + /** * __construct * @@ -40,7 +40,7 @@ class OrderXDocument extends AbstractService public function run(): self { - + $company = $this->document->company; $settings_entity = ($this->document instanceof PurchaseOrder) ? $this->document->vendor : $this->document->client; $profile = $settings_entity->getSetting('e_quote_type') ? $settings_entity->getSetting('e_quote_type') : "OrderX_Extended"; @@ -68,7 +68,7 @@ class OrderXDocument extends AbstractService } // Document type $document_class = get_class($this->document); - switch ($document_class){ + switch ($document_class) { case Quote::class: // Probably wrong file code https://github.com/horstoeko/zugferd/blob/master/src/codelists/ZugferdInvoiceType.php if (empty($this->document->number)) { @@ -129,12 +129,12 @@ class OrderXDocument extends AbstractService $this->orderxdocument->setDocumentPositionProductDetails("no product name defined"); } } -// TODO: add item classification (kg, m^3, ...) -// if (isset($item->task_id)) { -// $this->orderxdocument->setDocumentPositionQuantity($item->quantity, "HUR"); -// } else { -// $this->orderxdocument->setDocumentPositionQuantity($item->quantity, "H87"); -// } + // TODO: add item classification (kg, m^3, ...) + // if (isset($item->task_id)) { + // $this->orderxdocument->setDocumentPositionQuantity($item->quantity, "HUR"); + // } else { + // $this->orderxdocument->setDocumentPositionQuantity($item->quantity, "H87"); + // } $linenetamount = $item->line_total; if ($item->discount > 0) { if ($this->document->is_amount_discount) { @@ -182,15 +182,15 @@ class OrderXDocument extends AbstractService } $this->orderxdocument->setDocumentSummation( - $this->document->amount, - $this->document->balance, - $invoicing_data->getSubTotal(), - $invoicing_data->getTotalSurcharges(), - // $invoicing_data->getTotalDiscount(), - $invoicing_data->getSubTotal(), - $invoicing_data->getItemTotalTaxes(), - // 0.0, - // ($this->document->amount - $this->document->balance) + $this->document->amount, + $this->document->balance, + $invoicing_data->getSubTotal(), + $invoicing_data->getTotalSurcharges(), + // $invoicing_data->getTotalDiscount(), + $invoicing_data->getSubTotal(), + $invoicing_data->getItemTotalTaxes(), + // 0.0, + // ($this->document->amount - $this->document->balance) ); foreach ($this->tax_map as $item) { diff --git a/app/Services/EDocument/Standards/Peppol.php b/app/Services/EDocument/Standards/Peppol.php index 7d2065df1e05..fca7ac0ecedb 100644 --- a/app/Services/EDocument/Standards/Peppol.php +++ b/app/Services/EDocument/Standards/Peppol.php @@ -43,7 +43,6 @@ use InvoiceNinja\EInvoice\Models\Peppol\TaxTotal as PeppolTaxTotal; class Peppol extends AbstractService { - private array $InvoiceTypeCodes = [ "380" => "Commercial invoice", "381" => "Credit note", @@ -68,7 +67,7 @@ class Peppol extends AbstractService */ 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(); } @@ -90,45 +89,45 @@ class Peppol extends AbstractService $this->p_invoice->TaxTotal = $this->getTotalTaxes(); $this->p_invoice->LegalMonetaryTotal = $this->getLegalMonetaryTotal(); -// $payeeFinancialAccount = (new PayeeFinancialAccount()) -// ->setBankId($company->settings->custom_value1) -// ->setBankName($company->settings->custom_value2); + // $payeeFinancialAccount = (new PayeeFinancialAccount()) + // ->setBankId($company->settings->custom_value1) + // ->setBankName($company->settings->custom_value2); -// $paymentMeans = (new PaymentMeans()) -// ->setPaymentMeansCode($invoice->custom_value1) -// ->setPayeeFinancialAccount($payeeFinancialAccount); -// $ubl_invoice->setPaymentMeans($paymentMeans); + // $paymentMeans = (new PaymentMeans()) + // ->setPaymentMeansCode($invoice->custom_value1) + // ->setPayeeFinancialAccount($payeeFinancialAccount); + // $ubl_invoice->setPaymentMeans($paymentMeans); } private function getLegalMonetaryTotal(): LegalMonetaryTotal - { + { $taxable = $this->getTaxable(); - $lmt = new LegalMonetaryTotal; - - $lea = new LineExtensionAmount; + $lmt = new LegalMonetaryTotal(); + + $lea = new LineExtensionAmount(); $lea->currencyID = $this->invoice->client->currency()->code; $lea->amount = $taxable; $lmt->LineExtensionAmount = $lea; - $tea = new TaxExclusiveAmount; + $tea = new TaxExclusiveAmount(); $tea->currencyID = $this->invoice->client->currency()->code; $tea->amount = $taxable; $lmt->TaxExclusiveAmount = $tea; - $tia = new TaxInclusiveAmount; + $tia = new TaxInclusiveAmount(); $tia->currencyID = $this->invoice->client->currency()->code; $tia->amount = $this->invoice->amount; $lmt->TaxInclusiveAmount = $tia; - $pa = new PayableAmount; + $pa = new PayableAmount(); $pa->currencyID = $this->invoice->client->currency()->code; $pa->amount = $this->invoice->amount; $lmt->PayableAmount = $pa; return $lmt; - } + } private function getTotalTaxes(): array { @@ -136,24 +135,23 @@ class Peppol extends AbstractService $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->currencyID = $this->invoice->client->currency()->code; - $tax_amount->amount = round($this->invoice->amount * (1 / $this->invoice->tax_rate1),2); + $tax_amount->amount = round($this->invoice->amount * (1 / $this->invoice->tax_rate1), 2); -$tax_subtotal = new TaxSubtotal(); -$tax_subtotal->TaxAmount = $tax_amount; + $tax_subtotal = new TaxSubtotal(); + $tax_subtotal->TaxAmount = $tax_amount; -$taxable_amount = new TaxableAmount(); -$taxable_amount->currencyID = $this->invoice->client->currency()->code; -$taxable_amount->amount = $this->invoice->amount; -$tax_subtotal->TaxableAmount = $taxable_amount; + $taxable_amount = new TaxableAmount(); + $taxable_amount->currencyID = $this->invoice->client->currency()->code; + $taxable_amount->amount = $this->invoice->amount; + $tax_subtotal->TaxableAmount = $taxable_amount; + - $tc = new TaxCategory(); $tc->ID = $type_id == '2' ? 'HUR' : 'C62'; $tc->Percent = $this->invoice->tax_rate1; @@ -162,13 +160,13 @@ $tax_subtotal->TaxableAmount = $taxable_amount; $tc->TaxScheme = $ts; $tax_subtotal->TaxCategory = $tc; - $tax_total = new TaxTotal; + $tax_total = new TaxTotal(); $tax_total->TaxAmount = $tax_amount; $tax_total->TaxSubtotal = $tax_subtotal; $taxes[] = $tax_total; } - + if(strlen($this->invoice->tax_name2 ?? '') > 1) { @@ -176,17 +174,17 @@ $tax_subtotal->TaxableAmount = $taxable_amount; $tax_amount->currencyID = $this->invoice->client->currency()->code; $tax_amount->amount = round($this->invoice->amount * (1 / $this->invoice->tax_rate2), 2); -$tax_subtotal = new TaxSubtotal(); -$tax_subtotal->TaxAmount = $tax_amount; + $tax_subtotal = new TaxSubtotal(); + $tax_subtotal->TaxAmount = $tax_amount; -$taxable_amount = new TaxableAmount(); -$taxable_amount->currencyID = $this->invoice->client->currency()->code; -$taxable_amount->amount = $this->invoice->amount; -$tax_subtotal->TaxableAmount = $taxable_amount; + $taxable_amount = new TaxableAmount(); + $taxable_amount->currencyID = $this->invoice->client->currency()->code; + $taxable_amount->amount = $this->invoice->amount; + $tax_subtotal->TaxableAmount = $taxable_amount; $tc = new TaxCategory(); - $tc->ID = $type_id == '2' ? 'HUR' : 'C62'; + $tc->ID = $type_id == '2' ? 'HUR' : 'C62'; $tc->Percent = $this->invoice->tax_rate2; $ts = new PeppolTaxScheme(); $ts->ID = $this->invoice->tax_name2; @@ -208,13 +206,13 @@ $tax_subtotal->TaxableAmount = $taxable_amount; $tax_amount->currencyID = $this->invoice->client->currency()->code; $tax_amount->amount = round($this->invoice->amount * (1 / $this->invoice->tax_rate1), 2); -$tax_subtotal = new TaxSubtotal(); -$tax_subtotal->TaxAmount = $tax_amount; + $tax_subtotal = new TaxSubtotal(); + $tax_subtotal->TaxAmount = $tax_amount; -$taxable_amount = new TaxableAmount(); -$taxable_amount->currencyID = $this->invoice->client->currency()->code; -$taxable_amount->amount = $this->invoice->amount; -$tax_subtotal->TaxableAmount = $taxable_amount; + $taxable_amount = new TaxableAmount(); + $taxable_amount->currencyID = $this->invoice->client->currency()->code; + $taxable_amount->amount = $this->invoice->amount; + $tax_subtotal->TaxableAmount = $taxable_amount; $tc = new TaxCategory(); @@ -242,18 +240,17 @@ $tax_subtotal->TaxableAmount = $taxable_amount; { $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->Description = $item->notes; - $line = new InvoiceLine; - $line->ID = $key+1; + $line = new InvoiceLine(); + $line->ID = $key + 1; $line->InvoicedQuantity = $item->quantity; - $lea = new LineExtensionAmount; + $lea = new LineExtensionAmount(); $lea->currencyID = $this->invoice->client->currency()->code; $lea->amount = $item->line_total; $line->LineExtensionAmount = $lea; @@ -265,16 +262,17 @@ $tax_subtotal->TaxableAmount = $taxable_amount; // $tt->TaxAmount = $ta; $item_taxes = $this->getItemTaxes($item); - if(count($item_taxes) > 0) + if(count($item_taxes) > 0) { $line->TaxTotal = $item_taxes; + } - $price = new Price; - $pa = new PriceAmount; + $price = new Price(); + $pa = new PriceAmount(); $pa->currencyID = $this->invoice->client->currency()->code; $pa->amount = $this->costWithDiscount($item); $price->PriceAmount = $pa; - - $line->Price = $price; + + $line->Price = $price; $lines[] = $line; } @@ -301,32 +299,31 @@ $tax_subtotal->TaxableAmount = $taxable_amount; { $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->amount = round(($item->line_total * (1/$item->tax_rate1)),2); - $tax_subtotal = new TaxSubtotal; + $tax_amount->amount = round(($item->line_total * (1 / $item->tax_rate1)), 2); + $tax_subtotal = new TaxSubtotal(); $tax_subtotal->TaxAmount = $tax_amount; - $taxable_amount = new TaxableAmount; + $taxable_amount = new TaxableAmount(); $taxable_amount->currencyID = $this->invoice->client->currency()->code; $taxable_amount->amount = $item->line_total; $tax_subtotal->TaxableAmount = $taxable_amount; - $tc = new TaxCategory; + $tc = new TaxCategory(); $tc->ID = $item->type_id == '2' ? 'HUR' : 'C62'; $tc->Percent = $item->tax_rate1; - $ts = new PeppolTaxScheme; - $ts->ID = $item->tax_name1; + $ts = new PeppolTaxScheme(); + $ts->ID = $item->tax_name1; $tc->TaxScheme = $ts; $tax_subtotal->TaxCategory = $tc; - -$tax_total = new TaxTotal(); -$tax_total->TaxAmount = $tax_amount; -$tax_total->TaxSubtotal[] = $tax_subtotal; -$item_taxes[] = $tax_total; + + $tax_total = new TaxTotal(); + $tax_total->TaxAmount = $tax_amount; + $tax_total->TaxSubtotal[] = $tax_subtotal; + $item_taxes[] = $tax_total; } @@ -335,15 +332,15 @@ $item_taxes[] = $tax_total; $tax_amount = new TaxAmount(); $tax_amount->currencyID = $this->invoice->client->currency()->code; - $tax_amount->amount = round(($item->line_total * (1 / $item->tax_rate2)),2); + $tax_amount->amount = round(($item->line_total * (1 / $item->tax_rate2)), 2); -$tax_subtotal = new TaxSubtotal(); -$tax_subtotal->TaxAmount = $tax_amount; + $tax_subtotal = new TaxSubtotal(); + $tax_subtotal->TaxAmount = $tax_amount; -$taxable_amount = new TaxableAmount(); -$taxable_amount->currencyID = $this->invoice->client->currency()->code; -$taxable_amount->amount = $item->line_total; -$tax_subtotal->TaxableAmount = $taxable_amount; + $taxable_amount = new TaxableAmount(); + $taxable_amount->currencyID = $this->invoice->client->currency()->code; + $taxable_amount->amount = $item->line_total; + $tax_subtotal->TaxableAmount = $taxable_amount; $tc = new TaxCategory(); @@ -355,10 +352,10 @@ $tax_subtotal->TaxableAmount = $taxable_amount; $tax_subtotal->TaxCategory = $tc; -$tax_total = new TaxTotal(); -$tax_total->TaxAmount = $tax_amount; -$tax_total->TaxSubtotal[] = $tax_subtotal; -$item_taxes[] = $tax_total; + $tax_total = new TaxTotal(); + $tax_total->TaxAmount = $tax_amount; + $tax_total->TaxSubtotal[] = $tax_subtotal; + $item_taxes[] = $tax_total; } @@ -368,15 +365,15 @@ $item_taxes[] = $tax_total; $tax_amount = new TaxAmount(); $tax_amount->currencyID = $this->invoice->client->currency()->code; - $tax_amount->amount = round(($item->line_total * (1 / $item->tax_rate3)),2); + $tax_amount->amount = round(($item->line_total * (1 / $item->tax_rate3)), 2); -$tax_subtotal = new TaxSubtotal(); -$tax_subtotal->TaxAmount = $tax_amount; + $tax_subtotal = new TaxSubtotal(); + $tax_subtotal->TaxAmount = $tax_amount; -$taxable_amount = new TaxableAmount(); -$taxable_amount->currencyID = $this->invoice->client->currency()->code; -$taxable_amount->amount = $item->line_total; -$tax_subtotal->TaxableAmount = $taxable_amount; + $taxable_amount = new TaxableAmount(); + $taxable_amount->currencyID = $this->invoice->client->currency()->code; + $taxable_amount->amount = $item->line_total; + $tax_subtotal->TaxableAmount = $taxable_amount; $tc = new TaxCategory(); @@ -387,10 +384,10 @@ $tax_subtotal->TaxableAmount = $taxable_amount; $tc->TaxScheme = $ts; $tax_subtotal->TaxCategory = $tc; -$tax_total = new TaxTotal(); -$tax_total->TaxAmount = $tax_amount; -$tax_total->TaxSubtotal[] = $tax_subtotal; -$item_taxes[] = $tax_total; + $tax_total = new TaxTotal(); + $tax_total->TaxAmount = $tax_amount; + $tax_total->TaxSubtotal[] = $tax_subtotal; + $item_taxes[] = $tax_total; } @@ -404,7 +401,7 @@ $item_taxes[] = $tax_total; $asp = new AccountingSupplierParty(); $party = new Party(); - $party_name = new PartyName; + $party_name = new PartyName(); $party_name->Name = $this->invoice->company->present()->name(); $party->PartyName[] = $party_name; @@ -417,7 +414,7 @@ $item_taxes[] = $tax_total; // $address->CountrySubentityCode = $this->invoice->company->settings->state; $country = new Country(); - $country->IdentificationCode = $this->invoice->company->country()->iso_3166_2; + $country->IdentificationCode = $this->invoice->company->country()->iso_3166_2; $address->Country = $country; $party->PostalAddress = $address; @@ -439,7 +436,7 @@ $item_taxes[] = $tax_total; $acp = new AccountingCustomerParty(); $party = new Party(); - + $party_name = new PartyName(); $party_name->Name = $this->invoice->client->present()->name(); $party->PartyName[] = $party_name; @@ -459,7 +456,7 @@ $item_taxes[] = $tax_total; $party->PostalAddress = $address; $party->PhysicalLocation = $address; - + $contact = new Contact(); $contact->ElectronicMail = $this->invoice->client->present()->email(); @@ -516,4 +513,4 @@ $item_taxes[] = $tax_total; return $total; } -} \ No newline at end of file +} diff --git a/app/Services/EDocument/Standards/RoEInvoice.php b/app/Services/EDocument/Standards/RoEInvoice.php index 608173c55282..ebee4d1fcd38 100644 --- a/app/Services/EDocument/Standards/RoEInvoice.php +++ b/app/Services/EDocument/Standards/RoEInvoice.php @@ -35,7 +35,7 @@ use App\Models\Product; /** * Requirements: - * FACT1: + * FACT1: * Bank ID => company->settings->custom_value1 * Bank Name => company->settings->custom_value2 * Sector Code => company->settings->state @@ -44,7 +44,6 @@ use App\Models\Product; */ class RoEInvoice extends AbstractService { - private array $countrySubEntity = [ 'RO-AB' => 'Alba', 'RO-AG' => 'ArgeČ™', @@ -149,14 +148,14 @@ class RoEInvoice extends AbstractService { } - private function resolveSubEntityCode(string $city) + private function resolveSubEntityCode(string $city) { $city_references = &$this->countrySubEntity[$city]; return $city_references ?? 'RO-B'; } - private function resolveSectorCode(string $state) + private function resolveSectorCode(string $state) { return in_array($state, $this->sectorList) ? $state : 'SECTOR1'; } @@ -198,7 +197,7 @@ class RoEInvoice extends AbstractService $taxName = ''; - foreach ($invoice->line_items as $index => $item) { + foreach ($invoice->line_items as $index => $item) { if (!empty($item->tax_name1)) { $taxName = $item->tax_name1; @@ -219,11 +218,11 @@ class RoEInvoice extends AbstractService $payeeFinancialAccount = (new PayeeFinancialAccount()) ->setBankId($company->settings->custom_value1) ->setBankName($company->settings->custom_value2); - - $paymentMeans = (new PaymentMeans()) - ->setPaymentMeansCode($invoice->custom_value1) - ->setPayeeFinancialAccount($payeeFinancialAccount); - $ubl_invoice->setPaymentMeans($paymentMeans); + + $paymentMeans = (new PaymentMeans()) + ->setPaymentMeansCode($invoice->custom_value1) + ->setPayeeFinancialAccount($payeeFinancialAccount); + $ubl_invoice->setPaymentMeans($paymentMeans); // line items $invoice_lines = []; @@ -241,7 +240,7 @@ class RoEInvoice extends AbstractService $taxRatePercent = $item->tax_rate2; } elseif (!empty($item->tax_rate3)) { $taxRatePercent = $item->tax_rate3; - }else { + } else { $taxRatePercent = 0; } @@ -336,7 +335,7 @@ class RoEInvoice extends AbstractService ->setName($fullName) ->setElectronicMail($eMail) ->setTelephone($phone); - + $party->setContact($contact); return $party; @@ -359,13 +358,13 @@ class RoEInvoice extends AbstractService ->setId($this->resolveTaxCode($item->tax_id ?? 1)) ->setPercent($item->tax_rate3) ->setTaxScheme(((new TaxScheme())->setId(($item->tax_name3 === 'TVA') ? 'VAT' : $item->tax_name3))); - }else { - + } else { + $classifiedTaxCategory = (new ClassifiedTaxCategory()) ->setId($this->resolveTaxCode($item->tax_id ?? 8)) ->setPercent(0) ->setTaxScheme(((new TaxScheme())->setId(($item->tax_name3 === 'TVA') ? 'VAT' : $item->tax_name3))); - + } $invoiceLine = (new InvoiceLine()) @@ -511,7 +510,7 @@ class RoEInvoice extends AbstractService { $code = $tax_id; - match($tax_id){ + match($tax_id) { Product::PRODUCT_TYPE_REVERSE_TAX => $code = 'AE', // VAT_REVERSE_CHARGE = Product::PRODUCT_TYPE_EXEMPT => $code = 'E', // EXEMPT_FROM_TAX = Product::PRODUCT_TYPE_PHYSICAL => $code = 'S', // STANDARD_RATE = @@ -523,7 +522,7 @@ class RoEInvoice extends AbstractService Product::PRODUCT_TYPE_OVERRIDE_TAX => $code = 'S', // STANDARD_RATE = default => $code = 'S', }; - + return $code; } diff --git a/app/Services/EDocument/Standards/ZugferdEDokument.php b/app/Services/EDocument/Standards/ZugferdEDokument.php index f54d971ed1b3..e650372b98ba 100644 --- a/app/Services/EDocument/Standards/ZugferdEDokument.php +++ b/app/Services/EDocument/Standards/ZugferdEDokument.php @@ -25,7 +25,7 @@ class ZugferdEDokument extends AbstractService { public ZugferdDocumentBuilder $xdocument; - + /** * __construct * @@ -43,11 +43,11 @@ class ZugferdEDokument extends AbstractService /** @var \App\Models\Company $company */ $company = $this->document->company; - - + + /** @var \App\Models\Client $client */ $client = $this->document->client; - + $profile = $client->getSetting('e_invoice_type'); $profile = match ($profile) { @@ -81,7 +81,7 @@ class ZugferdEDokument extends AbstractService } // Document type $document_class = get_class($this->document); - switch ($document_class){ + switch ($document_class) { case Quote::class: // Probably wrong file code https://github.com/horstoeko/zugferd/blob/master/src/codelists/ZugferdInvoiceType.php if (empty($this->document->number)) { @@ -123,11 +123,11 @@ class ZugferdEDokument extends AbstractService } //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); - } - else + } else { $this->xdocument->addDocumentPaymentMean(68, ctrans("texts.xinvoice_online_payment")); + } if (str_contains($company->getSetting('vat_number'), "/")) { $this->xdocument->addDocumentSellerTaxRegistration("FC", $company->getSetting('vat_number')); @@ -135,7 +135,7 @@ class ZugferdEDokument extends AbstractService $this->xdocument->addDocumentSellerTaxRegistration("VA", $company->getSetting('vat_number')); } - if (!empty($client->vat_number)){ + if (!empty($client->vat_number)) { $this->xdocument->addDocumentBuyerTaxRegistration("VA", $client->vat_number); } @@ -144,7 +144,7 @@ class ZugferdEDokument extends AbstractService foreach ($this->document->line_items as $index => $item) { /** @var InvoiceItem $item **/ $this->xdocument->addNewPosition($index) - ->setDocumentPositionGrossPrice($item->gross_line_total+$item->discount) + ->setDocumentPositionGrossPrice($item->gross_line_total + $item->discount) ->setDocumentPositionNetPrice($item->line_total); if (!empty($item->product_key)) { if (!empty($item->notes)) { @@ -171,7 +171,7 @@ class ZugferdEDokument extends AbstractService } else { $line_discount -= $item->line_total * ($item->discount / 100); } - $this->xdocument->addDocumentPositionGrossPriceAllowanceCharge( abs($line_discount), false); + $this->xdocument->addDocumentPositionGrossPriceAllowanceCharge(abs($line_discount), false); } $this->xdocument->setDocumentPositionLineSummation($item->line_total); @@ -179,21 +179,21 @@ class ZugferdEDokument extends AbstractService if (!(empty($item->tax_name1) && empty($item->tax_name2) && empty($item->tax_name3))) { $taxtype = $this->getTaxType($item->tax_id); if (!empty($item->tax_name1)) { - if ($taxtype == ZugferdDutyTaxFeeCategories::VAT_EXEMPT_FOR_EEA_INTRACOMMUNITY_SUPPLY_OF_GOODS_AND_SERVICES){ + if ($taxtype == ZugferdDutyTaxFeeCategories::VAT_EXEMPT_FOR_EEA_INTRACOMMUNITY_SUPPLY_OF_GOODS_AND_SERVICES) { $this->xdocument->addDocumentPositionTax($taxtype, 'VAT', $item->tax_rate1, exemptionReason: ctrans('texts.intracommunity_tax_info')); } else { $this->xdocument->addDocumentPositionTax($taxtype, 'VAT', $item->tax_rate1); } $this->addtoTaxMap($taxtype, $item->line_total, $item->tax_rate1); } elseif (!empty($item->tax_name2)) { - if ($taxtype == ZugferdDutyTaxFeeCategories::VAT_EXEMPT_FOR_EEA_INTRACOMMUNITY_SUPPLY_OF_GOODS_AND_SERVICES){ + if ($taxtype == ZugferdDutyTaxFeeCategories::VAT_EXEMPT_FOR_EEA_INTRACOMMUNITY_SUPPLY_OF_GOODS_AND_SERVICES) { $this->xdocument->addDocumentPositionTax($taxtype, 'VAT', $item->tax_rate2, exemptionReason: ctrans('texts.intracommunity_tax_info')); } else { $this->xdocument->addDocumentPositionTax($taxtype, 'VAT', $item->tax_rate2); } $this->addtoTaxMap($taxtype, $item->line_total, $item->tax_rate2); } elseif (!empty($item->tax_name3)) { - if ($taxtype == ZugferdDutyTaxFeeCategories::VAT_EXEMPT_FOR_EEA_INTRACOMMUNITY_SUPPLY_OF_GOODS_AND_SERVICES){ + if ($taxtype == ZugferdDutyTaxFeeCategories::VAT_EXEMPT_FOR_EEA_INTRACOMMUNITY_SUPPLY_OF_GOODS_AND_SERVICES) { $this->xdocument->addDocumentPositionTax($taxtype, 'VAT', $item->tax_rate3, exemptionReason: ctrans('texts.intracommunity_tax_info')); } else { $this->xdocument->addDocumentPositionTax($taxtype, 'VAT', $item->tax_rate3); @@ -227,11 +227,11 @@ class ZugferdEDokument extends AbstractService $document_discount = abs($this->document->discount); } else { $document_discount = $this->document->amount * $this->document->discount / 100; - } + } - $this->xdocument->setDocumentSummation($this->document->amount, $this->document->balance, $invoicing_data->getSubTotal(), $invoicing_data->getTotalSurcharges(), $document_discount, $invoicing_data->getSubTotal()-$document_discount, $invoicing_data->getItemTotalTaxes(), 0.0, $this->document->amount - $this->document->balance); + $this->xdocument->setDocumentSummation($this->document->amount, $this->document->balance, $invoicing_data->getSubTotal(), $invoicing_data->getTotalSurcharges(), $document_discount, $invoicing_data->getSubTotal() - $document_discount, $invoicing_data->getItemTotalTaxes(), 0.0, $this->document->amount - $this->document->balance); foreach ($this->tax_map as $item) { - if ($document_discount > 0){ + if ($document_discount > 0) { if ($item["net_amount"] >= $document_discount) { $item["net_amount"] -= $document_discount; $this->xdocument->addDocumentAllowanceCharge($document_discount, false, $item["tax_type"], "VAT", $item["tax_rate"] * 100); @@ -242,10 +242,10 @@ class ZugferdEDokument extends AbstractService } } - if ($item["tax_type"] == ZugferdDutyTaxFeeCategories::VAT_EXEMPT_FOR_EEA_INTRACOMMUNITY_SUPPLY_OF_GOODS_AND_SERVICES){ + if ($item["tax_type"] == ZugferdDutyTaxFeeCategories::VAT_EXEMPT_FOR_EEA_INTRACOMMUNITY_SUPPLY_OF_GOODS_AND_SERVICES) { $this->xdocument->addDocumentTax($item["tax_type"], "VAT", $item["net_amount"], $item["tax_rate"] * $item["net_amount"], $item["tax_rate"] * 100, ctrans('texts.intracommunity_tax_info')); } else { - $this->xdocument->addDocumentTax($item["tax_type"], "VAT", $item["net_amount"], $item["tax_rate"] * $item["net_amount"], $item["tax_rate"] * 100); + $this->xdocument->addDocumentTax($item["tax_type"], "VAT", $item["net_amount"], $item["tax_rate"] * $item["net_amount"], $item["tax_rate"] * 100); } } diff --git a/app/Services/Email/Email.php b/app/Services/Email/Email.php index 447f65129aaa..04492da8fa77 100644 --- a/app/Services/Email/Email.php +++ b/app/Services/Email/Email.php @@ -250,8 +250,9 @@ class Email implements ShouldQueue 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); + } } /** @@ -302,21 +303,18 @@ class Email implements ShouldQueue $this->cleanUpMailers(); $this->logMailError($e->getMessage(), $this->company->clients()->first()); return; - } - catch(\Google\Service\Exception $e){ + } catch(\Google\Service\Exception $e) { if ($e->getCode() == '429') { - + $message = "Google rate limiting triggered, we are queueing based on Gmail requirements."; $this->logMailError($message, $this->company->clients()->first()); sleep(rand(1, 2)); $this->release(900); $message = null; } - - } - - catch (\Exception | \RuntimeException $e) { + + } catch (\Exception | \RuntimeException $e) { nlog("Mailer failed with {$e->getMessage()}"); $message = $e->getMessage(); @@ -332,7 +330,7 @@ class Email implements ShouldQueue return; } - + if(stripos($e->getMessage(), 'Dsn') !== false) { nlog("Incorrectly configured mail server - setting to default mail driver."); @@ -374,7 +372,7 @@ class Email implements ShouldQueue $this->fail(); $this->entityEmailFailed($message); $this->cleanUpMailers(); - + return; } @@ -648,8 +646,8 @@ class Email implements ShouldQueue $user = $this->resolveSendingUser(); - $sending_email = (isset ($this->email_object->settings->custom_sending_email) && stripos($this->email_object->settings->custom_sending_email, "@")) ? $this->email_object->settings->custom_sending_email : $user->email; - $sending_user = (isset ($this->email_object->settings->email_from_name) && strlen($this->email_object->settings->email_from_name) > 2) ? $this->email_object->settings->email_from_name : $user->name(); + $sending_email = (isset($this->email_object->settings->custom_sending_email) && stripos($this->email_object->settings->custom_sending_email, "@")) ? $this->email_object->settings->custom_sending_email : $user->email; + $sending_user = (isset($this->email_object->settings->email_from_name) && strlen($this->email_object->settings->email_from_name) > 2) ? $this->email_object->settings->email_from_name : $user->name(); $this->mailable ->from($sending_email, $sending_user); @@ -756,8 +754,8 @@ class Email implements ShouldQueue $user = $this->resolveSendingUser(); - $sending_email = (isset ($this->email_object->settings->custom_sending_email) && stripos($this->email_object->settings->custom_sending_email, "@")) ? $this->email_object->settings->custom_sending_email : $user->email; - $sending_user = (isset ($this->email_object->settings->email_from_name) && strlen($this->email_object->settings->email_from_name) > 2) ? $this->email_object->settings->email_from_name : $user->name(); + $sending_email = (isset($this->email_object->settings->custom_sending_email) && stripos($this->email_object->settings->custom_sending_email, "@")) ? $this->email_object->settings->custom_sending_email : $user->email; + $sending_user = (isset($this->email_object->settings->email_from_name) && strlen($this->email_object->settings->email_from_name) > 2) ? $this->email_object->settings->email_from_name : $user->name(); $this->mailable ->from($sending_email, $sending_user); @@ -778,8 +776,8 @@ class Email implements ShouldQueue $user = $this->resolveSendingUser(); - $sending_email = (isset ($this->email_object->settings->custom_sending_email) && stripos($this->email_object->settings->custom_sending_email, "@")) ? $this->email_object->settings->custom_sending_email : $user->email; - $sending_user = (isset ($this->email_object->settings->email_from_name) && strlen($this->email_object->settings->email_from_name) > 2) ? $this->email_object->settings->email_from_name : $user->name(); + $sending_email = (isset($this->email_object->settings->custom_sending_email) && stripos($this->email_object->settings->custom_sending_email, "@")) ? $this->email_object->settings->custom_sending_email : $user->email; + $sending_user = (isset($this->email_object->settings->email_from_name) && strlen($this->email_object->settings->email_from_name) > 2) ? $this->email_object->settings->email_from_name : $user->name(); $this->mailable ->from($sending_email, $sending_user); @@ -800,8 +798,8 @@ class Email implements ShouldQueue $user = $this->resolveSendingUser(); - $sending_email = (isset ($this->email_object->settings->custom_sending_email) && stripos($this->email_object->settings->custom_sending_email, "@")) ? $this->email_object->settings->custom_sending_email : $user->email; - $sending_user = (isset ($this->email_object->settings->email_from_name) && strlen($this->email_object->settings->email_from_name) > 2) ? $this->email_object->settings->email_from_name : $user->name(); + $sending_email = (isset($this->email_object->settings->custom_sending_email) && stripos($this->email_object->settings->custom_sending_email, "@")) ? $this->email_object->settings->custom_sending_email : $user->email; + $sending_user = (isset($this->email_object->settings->email_from_name) && strlen($this->email_object->settings->email_from_name) > 2) ? $this->email_object->settings->email_from_name : $user->name(); $this->mailable ->from($sending_email, $sending_user); @@ -934,7 +932,7 @@ class Email implements ShouldQueue { $expiry = $user->oauth_user_token_expiry ?: now()->subDay(); $token = false; - + if ($expiry->lt(now())) { $guzzle = new \GuzzleHttp\Client(); $url = 'https://login.microsoftonline.com/common/oauth2/v2.0/token'; @@ -949,8 +947,7 @@ class Email implements ShouldQueue 'refresh_token' => $user->oauth_user_refresh_token ], ])->getBody()->getContents()); - } - catch(\Exception $e){ + } catch(\Exception $e) { nlog("Problem getting new Microsoft token for User: {$user->email}"); } diff --git a/app/Services/Email/EmailDefaults.php b/app/Services/Email/EmailDefaults.php index 877ce2b605bd..068ad85c77ad 100644 --- a/app/Services/Email/EmailDefaults.php +++ b/app/Services/Email/EmailDefaults.php @@ -126,7 +126,7 @@ class EmailDefaults */ private function setFrom(): self { - if (Ninja::isHosted() && in_array($this->email->email_object->settings->email_sending_method,['default', 'mailgun'])) { + if (Ninja::isHosted() && in_array($this->email->email_object->settings->email_sending_method, ['default', 'mailgun'])) { if ($this->email->company->account->isPaid() && property_exists($this->email->email_object->settings, 'email_from_name') && strlen($this->email->email_object->settings->email_from_name) > 1) { $email_from_name = $this->email->email_object->settings->email_from_name; } else { diff --git a/app/Services/Invoice/AutoBillInvoice.php b/app/Services/Invoice/AutoBillInvoice.php index d6ecd64117b0..782b0fac9a76 100644 --- a/app/Services/Invoice/AutoBillInvoice.php +++ b/app/Services/Invoice/AutoBillInvoice.php @@ -36,7 +36,7 @@ class AutoBillInvoice extends AbstractService private Client $client; private array $used_credit = []; - + /*Specific variable for partial payments */ private bool $is_partial_amount = false; @@ -262,10 +262,10 @@ class AutoBillInvoice extends AbstractService ->workFlow() //07-06-2024 - run the workflow if paid! ->save(); } - + /** * If the client has unapplied payments on file - * we will use these prior to charging a + * we will use these prior to charging a * payment method on file. * * This needs to be wrapped in a transaction. @@ -282,11 +282,11 @@ class AutoBillInvoice extends AbstractService ->where('amount', '>', 0) ->orderBy('created_at') ->get(); - + $available_unapplied_balance = $unapplied_payments->sum('amount') - $unapplied_payments->sum('applied'); - + nlog("available unapplied balance = {$available_unapplied_balance}"); - + if ((int) $available_unapplied_balance == 0) { return $this; } @@ -296,7 +296,7 @@ class AutoBillInvoice extends AbstractService } $payment_repo = new PaymentRepository(new CreditRepository()); - + foreach ($unapplied_payments as $key => $payment) { $payment_balance = $payment->amount - $payment->applied; @@ -305,7 +305,7 @@ class AutoBillInvoice extends AbstractService if ($payment_balance > $this->invoice->partial) { $payload = ['client_id' => $this->invoice->client_id, 'invoices' => [['invoice_id' => $this->invoice->id,'amount' => $this->invoice->partial]]]; $payment_repo->save($payload, $payment); - + $this->invoice = $this->invoice->fresh(); return $this; @@ -316,16 +316,16 @@ class AutoBillInvoice extends AbstractService } else { //more than needed if ($payment_balance > $this->invoice->balance) { - + $payload = ['client_id' => $this->invoice->client_id, 'invoices' => [['invoice_id' => $this->invoice->id,'amount' => $this->invoice->balance]]]; $payment_repo->save($payload, $payment); $this->invoice = $this->invoice->fresh(); return $this; - + } else { - + $payload = ['client_id' => $this->invoice->client_id, 'invoices' => [['invoice_id' => $this->invoice->id,'amount' => $payment_balance]]]; $payment_repo->save($payload, $payment); diff --git a/app/Services/Invoice/GenerateDeliveryNote.php b/app/Services/Invoice/GenerateDeliveryNote.php index 8bce3df7610a..80a5fd236799 100644 --- a/app/Services/Invoice/GenerateDeliveryNote.php +++ b/app/Services/Invoice/GenerateDeliveryNote.php @@ -49,7 +49,7 @@ class GenerateDeliveryNote if($design && $design->is_template) { $ts = new TemplateService($design); - + $pdf = $ts->setCompany($this->invoice->company) ->build([ 'invoices' => collect([$this->invoice]), @@ -82,8 +82,8 @@ class GenerateDeliveryNote } $variables = $html->generateLabelsAndValues(); - $variables['labels']['$entity_label']= ctrans('texts.delivery_note'); - + $variables['labels']['$entity_label'] = ctrans('texts.delivery_note'); + $state = [ 'template' => $template->elements([ 'client' => $this->invoice->client, diff --git a/app/Services/Invoice/InvoiceService.php b/app/Services/Invoice/InvoiceService.php index 88666d79cfac..4389c8b32533 100644 --- a/app/Services/Invoice/InvoiceService.php +++ b/app/Services/Invoice/InvoiceService.php @@ -90,7 +90,7 @@ class InvoiceService if ($company_currency != $client_currency) { $exchange_rate = new CurrencyApi(); - $this->invoice->exchange_rate = 1/$exchange_rate->exchangeRate($client_currency, $company_currency, now()); + $this->invoice->exchange_rate = 1 / $exchange_rate->exchangeRate($client_currency, $company_currency, now()); } return $this; @@ -208,7 +208,7 @@ class InvoiceService { return $this->getEInvoice($contact); } - + public function sendEmail($contact = null) { $send_email = new SendEmail($this->invoice, null, $contact); @@ -488,7 +488,8 @@ class InvoiceService /*When a reminder is sent we want to touch the dates they were sent*/ 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) { case 'reminder1': $this->invoice->reminder1_sent = now(); diff --git a/app/Services/PdfMaker/PdfMaker.php b/app/Services/PdfMaker/PdfMaker.php index d0990d349706..876500e13309 100644 --- a/app/Services/PdfMaker/PdfMaker.php +++ b/app/Services/PdfMaker/PdfMaker.php @@ -80,7 +80,7 @@ class PdfMaker $replacements = []; $contents = $this->document->getElementsByTagName('ninja'); - $ts = new TemplateService(); + $ts = new TemplateService(); if(isset($this->options['client'])) { $client = $this->options['client']; @@ -88,10 +88,10 @@ class PdfMaker $ts->setCompany($client->company); $ts->addGlobal(['currency_code' => $client->company->currency()->code]); } catch(\Exception $e) { - nlog($e->getMessage()); + nlog($e->getMessage()); } } - + if(isset($this->options['vendor'])) { $vendor = $this->options['vendor']; try { diff --git a/app/Services/PurchaseOrder/PurchaseOrderExpense.php b/app/Services/PurchaseOrder/PurchaseOrderExpense.php index 9abb4b6b4869..80a43bc07f7f 100644 --- a/app/Services/PurchaseOrder/PurchaseOrderExpense.php +++ b/app/Services/PurchaseOrder/PurchaseOrderExpense.php @@ -57,12 +57,12 @@ class PurchaseOrderExpense $expense->number = empty($expense->number) ? $this->getNextExpenseNumber($expense) : $expense->number; - if($this->purchase_order->project_id){ + if($this->purchase_order->project_id) { $expense->project_id = $this->purchase_order->project_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->saveQuietly(); event('eloquent.created: App\Models\Expense', $expense); diff --git a/app/Services/PurchaseOrder/PurchaseOrderService.php b/app/Services/PurchaseOrder/PurchaseOrderService.php index ad9c4b02858d..005f99509f82 100644 --- a/app/Services/PurchaseOrder/PurchaseOrderService.php +++ b/app/Services/PurchaseOrder/PurchaseOrderService.php @@ -86,7 +86,7 @@ class PurchaseOrderService { return $this->getEPurchaseOrder($contact); } - + public function deleteEPurchaseOrder() { $this->purchase_order->load('invitations'); diff --git a/app/Services/Quote/ConvertQuote.php b/app/Services/Quote/ConvertQuote.php index 97c1e18e8641..ec822245d8f9 100644 --- a/app/Services/Quote/ConvertQuote.php +++ b/app/Services/Quote/ConvertQuote.php @@ -75,8 +75,9 @@ class ConvertQuote $quote->status_id = Quote::STATUS_CONVERTED; $quote->save(); - if($quote->documents()->count() > 0) + if($quote->documents()->count() > 0) { CopyDocs::dispatch($quote->documents()->pluck('id'), $invoice, $invoice->company->db); + } return $invoice; } diff --git a/app/Services/Report/ARDetailReport.php b/app/Services/Report/ARDetailReport.php index 8b937b495de2..588c48249cbc 100644 --- a/app/Services/Report/ARDetailReport.php +++ b/app/Services/Report/ARDetailReport.php @@ -91,7 +91,7 @@ class ARDetailReport extends BaseExport $query = Invoice::query() ->withTrashed() - ->whereHas('client', function ($query){ + ->whereHas('client', function ($query) { $query->where('is_deleted', 0); }) ->where('company_id', $this->company->id) diff --git a/app/Services/Report/ProfitLoss.php b/app/Services/Report/ProfitLoss.php index 812978d665eb..e3b9fc4e1db6 100644 --- a/app/Services/Report/ProfitLoss.php +++ b/app/Services/Report/ProfitLoss.php @@ -288,8 +288,9 @@ class ProfitLoss if ($pivot->paymentable_type == 'invoices') { $invoice = Invoice::query()->withTrashed()->find($pivot->paymentable_id); - if(!$invoice) + if(!$invoice) { continue; + } $pivot_diff = $pivot->amount - $pivot->refunded; $amount_payment_paid += $pivot_diff; @@ -301,10 +302,10 @@ class ProfitLoss } } - - if(!$invoice) { - continue; - } + + if(!$invoice) { + continue; + } if ($pivot->paymentable_type == 'credits') { $amount_credit_paid += $pivot->amount - $pivot->refunded; @@ -399,7 +400,7 @@ class ProfitLoss $csv->insertOne(['']); $csv->insertOne(['']); - + $csv->insertOne(['--------------------']); $csv->insertOne([ctrans('texts.revenue')]); $csv->insertOne(['--------------------']); @@ -414,7 +415,7 @@ class ProfitLoss $csv->insertOne(['--------------------']); $csv->insertOne([ctrans('texts.expenses')]); $csv->insertOne(['--------------------']); - foreach($this->expenses as $expense){ + foreach($this->expenses as $expense) { $csv->insertOne([$expense->currency, ($expense->total - $expense->foreign_tax_amount), $expense->foreign_tax_amount]); } @@ -450,10 +451,10 @@ class ProfitLoss private function expenseData() { $expenses = Expense::query()->where('company_id', $this->company->id) - ->where(function ($query){ - $query->whereNull('client_id')->orWhereHas('client', function ($q){ - $q->where('is_deleted', 0); - }); + ->where(function ($query) { + $query->whereNull('client_id')->orWhereHas('client', function ($q) { + $q->where('is_deleted', 0); + }); }) ->where('is_deleted', 0) ->withTrashed() diff --git a/app/Services/Subscription/StepService.php b/app/Services/Subscription/StepService.php index 84ed67ecf965..99baebca06a2 100644 --- a/app/Services/Subscription/StepService.php +++ b/app/Services/Subscription/StepService.php @@ -18,9 +18,9 @@ class StepService { public static function mapToClassNames(string $steps): array { - $classes = collect(Purchase::$dependencies)->mapWithKeys(fn($dependency, $class) => [$dependency['id'] => $class])->toArray(); + $classes = collect(Purchase::$dependencies)->mapWithKeys(fn ($dependency, $class) => [$dependency['id'] => $class])->toArray(); - return array_map(fn($step) => $classes[$step], explode(',', $steps)); + return array_map(fn ($step) => $classes[$step], explode(',', $steps)); } public static function check(array $steps): array @@ -35,7 +35,7 @@ class StepService if (!empty($dependent) && !array_intersect($dependent, $steps)) { $errors[] = ctrans('texts.step_dependency_fail', [ 'step' => ctrans('texts.' . self::mapClassNameToString($step)), - 'dependencies' => implode(', ', array_map(fn($dependency) => ctrans('texts.' . self::mapClassNameToString($dependency)), $dependent)), + 'dependencies' => implode(', ', array_map(fn ($dependency) => ctrans('texts.' . self::mapClassNameToString($dependency)), $dependent)), ]); } @@ -43,7 +43,7 @@ class StepService if (in_array($dependency, $steps) && $step_order[$dependency] > $step_order[$step]) { $errors[] = ctrans('texts.step_dependency_order_fail', [ 'step' => ctrans('texts.' . self::mapClassNameToString($step)), - 'dependency' => implode(', ', array_map(fn($dependency) => ctrans('texts.' . self::mapClassNameToString($dependency)), $dependent)), + 'dependency' => implode(', ', array_map(fn ($dependency) => ctrans('texts.' . self::mapClassNameToString($dependency)), $dependent)), ]); } } @@ -63,8 +63,8 @@ class StepService public static function mapClassNameToString(string $class): string { - $classes = collect(Purchase::$dependencies)->mapWithKeys(fn($dependency, $class) => [$class => $dependency['id']])->toArray(); + $classes = collect(Purchase::$dependencies)->mapWithKeys(fn ($dependency, $class) => [$class => $dependency['id']])->toArray(); return $classes[$class]; } -} \ No newline at end of file +} diff --git a/app/Services/Subscription/SubscriptionCalculator.php b/app/Services/Subscription/SubscriptionCalculator.php index c91747f981dc..0179f35b6147 100644 --- a/app/Services/Subscription/SubscriptionCalculator.php +++ b/app/Services/Subscription/SubscriptionCalculator.php @@ -27,8 +27,10 @@ class SubscriptionCalculator { use MakesHash; - public function __construct(public Subscription $subscription){} - + public function __construct(public Subscription $subscription) + { + } + /** * BuildPurchaseInvoice * @@ -55,12 +57,12 @@ class SubscriptionCalculator return $invoice_repo->save([], $invoice); } - + /** * Build Line Items - * + * * @param array $context - * + * * @return array */ private function buildItems(array $context): array @@ -74,9 +76,10 @@ class SubscriptionCalculator $items = []; foreach($recurring as $item) { - - if($item['quantity'] < 1) + + if($item['quantity'] < 1) { continue; + } $line_item = new InvoiceItem(); $line_item->product_key = $item['product']['product_key']; @@ -191,7 +194,9 @@ class SubscriptionCalculator return $this->subscription->price; } - public function executeUpgradePlan() {} + public function executeUpgradePlan() + { + } private function getRefundInvoice(Invoice $invoice) { diff --git a/app/Services/Template/TemplateAction.php b/app/Services/Template/TemplateAction.php index 9e4d775d87e2..170b0cef7701 100644 --- a/app/Services/Template/TemplateAction.php +++ b/app/Services/Template/TemplateAction.php @@ -114,43 +114,44 @@ class TemplateAction implements ShouldQueue /** Lets be clever and sniff out Statements */ if($first_entity instanceof Client && stripos(json_encode($template->design), '##statement##') !== false) { - - $options = [ - 'show_payments_table' => true, - 'show_aging_table' => true, - 'status' => 'all', - 'show_credits_table' => false, - 'template' => $this->template, - ]; - $pdfs = []; + $options = [ + 'show_payments_table' => true, + 'show_aging_table' => true, + 'status' => 'all', + 'show_credits_table' => false, + 'template' => $this->template, + ]; - foreach($result as $client) { - $pdfs[] = $client->service()->statement($options); - } + $pdfs = []; - if(count($pdfs) == 1) { - $pdf = $pdfs[0]; - } else { - $pdf = (new PdfMerge($pdfs))->run(); - } - - if($this->send_email) { - $this->sendEmail($pdf, $template); - } else { - $filename = "templates/{$this->hash}.pdf"; - Storage::disk(config('filesystems.default'))->put($filename, $pdf); - return $pdf; - } + foreach($result as $client) { + $pdfs[] = $client->service()->statement($options); + } + + if(count($pdfs) == 1) { + $pdf = $pdfs[0]; + } else { + $pdf = (new PdfMerge($pdfs))->run(); + } + + if($this->send_email) { + $this->sendEmail($pdf, $template); + } else { + $filename = "templates/{$this->hash}.pdf"; + Storage::disk(config('filesystems.default'))->put($filename, $pdf); + return $pdf; + } } - if($first_entity instanceof Client) + if($first_entity instanceof Client) { $currency_code = $first_entity->currency()->code; - elseif($first_entity->client) + } elseif($first_entity->client) { $currency_code = $first_entity->client->currency()->code; - else + } else { $currency_code = $this->company->currency()->code; + } if($result->count() <= 1) { $data[$key] = collect($result); diff --git a/app/Services/Template/TemplateService.php b/app/Services/Template/TemplateService.php index 7819b0bdd8f9..14babd5de3aa 100644 --- a/app/Services/Template/TemplateService.php +++ b/app/Services/Template/TemplateService.php @@ -94,7 +94,7 @@ class TemplateService $this->twig = new \Twig\Environment($loader, [ 'debug' => true, ]); - + $string_extension = new \Twig\Extension\StringLoaderExtension(); $this->twig->addExtension($string_extension); $this->twig->addExtension(new IntlExtension()); @@ -170,7 +170,7 @@ class TemplateService public function setGlobals(): self { - + foreach($this->global_vars as $key => $value) { $this->twig->addGlobal($key, $value); } @@ -251,7 +251,7 @@ class TemplateService */ public function getPdf(): string { - + if (config('ninja.invoiceninja_hosted_pdf_generation') || config('ninja.pdf_generator') == 'hosted_ninja') { $pdf = (new NinjaPdf())->build($this->compiled_html); } else { @@ -564,7 +564,7 @@ class TemplateService 'credit_balance' => $invoice->client->credit_balance, 'vat_number' => $invoice->client->vat_number ?? '', 'currency' => $invoice->client->currency()->code ?? 'USD', - 'locale' => substr($invoice->client->locale(),0,2), + 'locale' => substr($invoice->client->locale(), 0, 2), ], 'payments' => $payments, 'total_tax_map' => $invoice->calc()->getTotalTaxMap(), @@ -721,9 +721,10 @@ class TemplateService private function getPaymentRefundActivity(Payment $payment): array { - if(!is_array($payment->refund_meta)) + if(!is_array($payment->refund_meta)) { return []; - + } + return collect($payment->refund_meta) ->map(function ($refund) use ($payment) { diff --git a/app/Transformers/ProjectTransformer.php b/app/Transformers/ProjectTransformer.php index e03318b9a2a6..3d8ddcc6402c 100644 --- a/app/Transformers/ProjectTransformer.php +++ b/app/Transformers/ProjectTransformer.php @@ -47,9 +47,10 @@ class ProjectTransformer extends EntityTransformer { $transformer = new DocumentTransformer($this->serializer); - if($project->documents) + if($project->documents) { return $this->includeCollection($project->documents, $transformer, Document::class); - + } + return null; } @@ -83,14 +84,14 @@ class ProjectTransformer extends EntityTransformer public function includeExpenses(Project $project): \League\Fractal\Resource\Collection { $transformer = new ExpenseTransformer($this->serializer); - + return $this->includeCollection($project->expenses, $transformer, Expense::class); } public function includeQuotes(Project $project): \League\Fractal\Resource\Collection { $transformer = new QuoteTransformer($this->serializer); - + return $this->includeCollection($project->quotes, $transformer, Quote::class); } diff --git a/app/Transformers/TaskTransformer.php b/app/Transformers/TaskTransformer.php index 826f89ef1386..668cc4f7f3aa 100644 --- a/app/Transformers/TaskTransformer.php +++ b/app/Transformers/TaskTransformer.php @@ -111,8 +111,9 @@ class TaskTransformer extends EntityTransformer { $transformer = new ProjectTransformer($this->serializer); - if ($task->project) + if ($task->project) { return $this->includeItem($task->project, $transformer, Project::class); + } return null; } diff --git a/app/Transformers/UserTransformer.php b/app/Transformers/UserTransformer.php index 8f82a952ce89..3f4ec9801ac8 100644 --- a/app/Transformers/UserTransformer.php +++ b/app/Transformers/UserTransformer.php @@ -109,10 +109,11 @@ class UserTransformer extends EntityTransformer $transformer = new CompanyUserTransformer($this->serializer); - $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 $this->includeItem($cu, $transformer, CompanyUser::class); } diff --git a/app/Utils/HtmlEngine.php b/app/Utils/HtmlEngine.php index 94625a6af972..d63abf547a1c 100644 --- a/app/Utils/HtmlEngine.php +++ b/app/Utils/HtmlEngine.php @@ -397,7 +397,7 @@ class HtmlEngine $data['$balance'] = ['value' => Number::formatMoney($this->getBalance(), $this->client) ?: ' ', 'label' => ctrans('texts.balance')]; $data['$credit.balance'] = ['value' => Number::formatMoney($this->entity_calc->getBalance(), $this->client) ?: ' ', 'label' => ctrans('texts.credit_balance')]; $data['$client.credit_balance'] = &$data['$credit.balance']; - + $data['$invoice.balance'] = &$data['$balance']; $data['$taxes'] = ['value' => Number::formatMoney($this->entity_calc->getItemTotalTaxes(), $this->client) ?: ' ', 'label' => ctrans('texts.taxes')]; $data['$invoice.taxes'] = &$data['$taxes']; @@ -561,17 +561,18 @@ 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' => '']; - if(Ninja::isHosted()) + if(Ninja::isHosted()) { $logo = $this->company->present()->logo($this->settings); - else + } else { $logo = $this->company->present()->logo_base64($this->settings); + } $logo_url = $this->company->present()->logo($this->settings); $data['$company.logo'] = ['value' => $logo ?: ' ', 'label' => ctrans('texts.logo')]; $data['$company_logo'] = &$data['$company.logo']; - + $data['$company.logo_url'] = ['value' => $logo_url ?: ' ', 'label' => ctrans('texts.logo')]; $data['$company1'] = ['value' => $this->helpers->formatCustomFieldValue($this->company->custom_fields, 'company1', $this->settings->custom_value1, $this->client) ?: ' ', 'label' => $this->helpers->makeCustomField($this->company->custom_fields, 'company1')]; @@ -767,33 +768,35 @@ class HtmlEngine 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 collect($payment->refund_meta) ->map(function ($refund) use ($payment) { - $date = \Carbon\Carbon::parse($refund['date'] ?? $payment->date)->addSeconds($payment->client->timezone_offset()); - $date = $this->translateDate($date, $payment->client->date_format(), $payment->client->locale()); - $entity = ctrans('texts.invoice'); + $date = \Carbon\Carbon::parse($refund['date'] ?? $payment->date)->addSeconds($payment->client->timezone_offset()); + $date = $this->translateDate($date, $payment->client->date_format(), $payment->client->locale()); + $entity = ctrans('texts.invoice'); - $map = []; + $map = []; - foreach($refund['invoices'] as $refunded_invoice) { - $invoice = \App\Models\Invoice::withTrashed()->find($refunded_invoice['invoice_id']); - $amount = Number::formatMoney($refunded_invoice['amount'], $payment->client); - $notes = ctrans('texts.status_partially_refunded_amount', ['amount' => $amount]); + foreach($refund['invoices'] as $refunded_invoice) { + $invoice = \App\Models\Invoice::withTrashed()->find($refunded_invoice['invoice_id']); + $amount = Number::formatMoney($refunded_invoice['amount'], $payment->client); + $notes = ctrans('texts.status_partially_refunded_amount', ['amount' => $amount]); - array_push($map, "{$date} {$entity} #{$invoice->number} {$notes}\n"); + array_push($map, "{$date} {$entity} #{$invoice->number} {$notes}\n"); - } + } - return $map; + return $map; - })->flatten()->implode("\n"); + })->flatten()->implode("\n"); } /** diff --git a/app/Utils/Number.php b/app/Utils/Number.php index 9501df90f81f..2a8b592a6a99 100644 --- a/app/Utils/Number.php +++ b/app/Utils/Number.php @@ -89,8 +89,9 @@ class Number public static function parseFloat($value) { - if(!$value) + if(!$value) { return 0; + } //remove everything except for numbers, decimals, commas and hyphens $value = preg_replace('/[^0-9.,-]+/', '', $value); @@ -98,16 +99,17 @@ class Number $decimal = 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; + } - if(!$decimal && substr($value, -3, 1) != ","){ + if(!$decimal && substr($value, -3, 1) != ",") { $value = $value.".00"; } - + $decimal = strpos($value, '.'); - if($decimal < $comma){ //decimal before a comma = euro + if($decimal < $comma) { //decimal before a comma = euro $value = str_replace(['.',','], ['','.'], $value); return (float) $value; } @@ -119,7 +121,7 @@ class Number } - + /** * Formats a given value based on the clients currency * BACK to a float. @@ -130,13 +132,15 @@ class Number public static function parseFloatXX($value) { - if(!$value) + if(!$value) { return 0; + } $multiplier = false; - if(substr($value, 0,1) == '-') + if(substr($value, 0, 1) == '-') { $multiplier = -1; + } $s = str_replace(',', '.', $value); @@ -148,13 +152,14 @@ class Number $s = str_replace('.', '', substr($s, 0, -3)).substr($s, -3); - if($multiplier) - $s = floatval($s)*-1; + if($multiplier) { + $s = floatval($s) * -1; + } return (float) $s; } - + //next iteration of float parsing public static function parseFloat2($value) { @@ -198,8 +203,8 @@ class Number return (float)$value; } - - + + public static function parseStringFloat($value) { $value = preg_replace('/[^0-9-.]+/', '', $value); diff --git a/app/Utils/Statics.php b/app/Utils/Statics.php index ee36bbd80b2b..e4b2201db658 100644 --- a/app/Utils/Statics.php +++ b/app/Utils/Statics.php @@ -130,7 +130,7 @@ class Statics $data['bulk_updates'] = [ 'client' => \App\Models\Client::$bulk_update_columns, ]; - + return $data; } } diff --git a/app/Utils/Traits/CleanLineItems.php b/app/Utils/Traits/CleanLineItems.php index 59688878b5c4..9cd45a73f576 100644 --- a/app/Utils/Traits/CleanLineItems.php +++ b/app/Utils/Traits/CleanLineItems.php @@ -80,9 +80,9 @@ trait CleanLineItems if(isset($item['product_key'])) { $item['product_key'] = str_replace([" ['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, ['message' => 'Success', 'status_code' => 200]); diff --git a/app/Utils/TruthSource.php b/app/Utils/TruthSource.php index 11fa4c84a9b7..e5aa81108223 100644 --- a/app/Utils/TruthSource.php +++ b/app/Utils/TruthSource.php @@ -62,7 +62,7 @@ class TruthSource { return $this->premium_hosted; } - + public function getCompany() { return $this->company;