diff --git a/.php_cs b/.php_cs
deleted file mode 100644
index 33c6ee25511b..000000000000
--- a/.php_cs
+++ /dev/null
@@ -1,19 +0,0 @@
-notPath('vendor')
- ->notPath('bootstrap')
- ->notPath('storage')
- ->notPath('node_modules')
- ->in(__DIR__)
- ->name('*.php')
- ->notName('*.blade.php');
-
-return PhpCsFixer\Config::create()
- ->setRules([
- '@PSR2' => true,
- 'array_syntax' => ['syntax' => 'short'],
- 'ordered_imports' => ['sortAlgorithm' => 'alpha'],
- 'no_unused_imports' => true,
- ])
- ->setFinder($finder);
\ No newline at end of file
diff --git a/app/Console/Commands/BackupUpdate.php b/app/Console/Commands/BackupUpdate.php
index c96330cd6dcb..720418c930d6 100644
--- a/app/Console/Commands/BackupUpdate.php
+++ b/app/Console/Commands/BackupUpdate.php
@@ -14,11 +14,9 @@ namespace App\Console\Commands;
use App\Libraries\MultiDB;
use App\Models\Backup;
use App\Models\Company;
-use App\Models\Design;
use App\Models\Document;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;
-use stdClass;
class BackupUpdate extends Command
{
@@ -60,7 +58,6 @@ class BackupUpdate extends Command
if (! config('ninja.db.multi_db_enabled')) {
$this->handleOnDb();
} else {
-
//multiDB environment, need to
foreach (MultiDB::$dbs as $db) {
MultiDB::setDB($db);
@@ -78,50 +75,43 @@ class BackupUpdate extends Command
//logos
Company::cursor()
- ->each(function ($company){
+ ->each(function ($company) {
+ $company_logo = $company->present()->logo();
- $company_logo = $company->present()->logo();
+ if ($company_logo == 'https://invoicing.co/images/new_logo.png') {
+ return;
+ }
- if($company_logo == 'https://invoicing.co/images/new_logo.png')
- return;
+ $logo = @file_get_contents($company_logo);
- $logo = @file_get_contents($company_logo);
-
- if($logo){
-
- $path = str_replace("https://objects.invoicing.co/", "", $company->present()->logo());
- $path = str_replace("https://v5-at-backup.us-southeast-1.linodeobjects.com/", "", $path);
-
- Storage::disk($this->option('disk'))->put($path, $logo);
- }
+ if ($logo) {
+ $path = str_replace("https://objects.invoicing.co/", "", $company->present()->logo());
+ $path = str_replace("https://v5-at-backup.us-southeast-1.linodeobjects.com/", "", $path);
+ Storage::disk($this->option('disk'))->put($path, $logo);
+ }
});
//documents
Document::cursor()
- ->each(function ($document){
-
+ ->each(function ($document) {
$doc_bin = $document->getFile();
- if($doc_bin)
+ if ($doc_bin) {
Storage::disk($this->option('disk'))->put($document->url, $doc_bin);
-
+ }
});
- //backups
+ //backups
Backup::cursor()
- ->each(function ($backup){
+ ->each(function ($backup) {
+ $backup_bin = Storage::disk('s3')->get($backup->filename);
- $backup_bin = Storage::disk('s3')->get($backup->filename);
-
- if($backup_bin)
+ if ($backup_bin) {
Storage::disk($this->option('disk'))->put($backup->filename, $backup_bin);
-
+ }
});
-
-
-
}
}
diff --git a/app/Console/Commands/CheckData.php b/app/Console/Commands/CheckData.php
index 1c47c4b6d920..01a5e9e06e7e 100644
--- a/app/Console/Commands/CheckData.php
+++ b/app/Console/Commands/CheckData.php
@@ -28,9 +28,7 @@ use App\Models\CreditInvitation;
use App\Models\Invoice;
use App\Models\InvoiceInvitation;
use App\Models\Payment;
-use App\Models\Paymentable;
use App\Models\PurchaseOrder;
-use App\Models\PurchaseOrderInvitation;
use App\Models\Quote;
use App\Models\QuoteInvitation;
use App\Models\RecurringInvoiceInvitation;
@@ -102,7 +100,7 @@ class CheckData extends Command
public function handle()
{
- $time_start = microtime(true);
+ $time_start = microtime(true);
$database_connection = $this->option('database') ? $this->option('database') : 'Connected to Default DB';
$fix_status = $this->option('fix') ? "Fixing Issues" : "Just checking issues ";
@@ -113,8 +111,8 @@ class CheckData extends Command
config(['database.default' => $database]);
}
- $this->checkInvoiceBalances();
- $this->checkClientBalanceEdgeCases();
+ $this->checkInvoiceBalances();
+ $this->checkClientBalanceEdgeCases();
$this->checkPaidToDatesNew();
$this->checkContacts();
$this->checkVendorContacts();
@@ -128,7 +126,7 @@ class CheckData extends Command
$this->checkCompanyTokens();
$this->checkUserState();
- if(Ninja::isHosted()){
+ if (Ninja::isHosted()) {
$this->checkAccountStatuses();
$this->checkNinjaPortalUrls();
}
@@ -162,44 +160,35 @@ class CheckData extends Command
private function checkCompanyTokens()
{
-
- CompanyUser::doesnthave('token')->cursor()->each(function ($cu){
-
- if($cu->user){
+ CompanyUser::doesnthave('token')->cursor()->each(function ($cu) {
+ if ($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();
- }
- else {
+ } else {
$this->logMessage("Dangling User ID # {$cu->id}");
}
-
});
-
}
private function checkOauthSanity()
{
- User::where('oauth_provider_id', '1')->cursor()->each(function ($user){
-
+ User::where('oauth_provider_id', '1')->cursor()->each(function ($user) {
$this->logMessage("Invalid provider ID for user id# {$user->id}");
-
});
}
private function checkDuplicateRecurringInvoices()
{
-
- if(Ninja::isHosted())
- {
+ if (Ninja::isHosted()) {
$c = Client::on('db-ninja-01')->where('company_id', config('ninja.ninja_default_company_id'))
->with('recurring_invoices')
->cursor()
- ->each(function ($client){
- if($client->recurring_invoices()->where('is_deleted', 0)->where('deleted_at', null)->count() > 1)
- $this->logMessage("Duplicate Recurring Invoice => {$client->custom_value1}");
+ ->each(function ($client) {
+ if ($client->recurring_invoices()->where('is_deleted', 0)->where('deleted_at', null)->count() > 1) {
+ $this->logMessage("Duplicate Recurring Invoice => {$client->custom_value1}");
+ }
});
}
-
}
@@ -302,7 +291,6 @@ class CheckData extends Command
$new_contact->save();
}
}
-
}
private function checkVendorContacts()
@@ -350,7 +338,6 @@ class CheckData extends Command
}
if ($this->option('fix') == 'true') {
-
$vendors = Vendor::withTrashed()->doesntHave('contacts')->get();
foreach ($vendors as $vendor) {
@@ -363,7 +350,6 @@ class CheckData extends Command
$new_contact->save();
}
}
-
}
@@ -418,27 +404,22 @@ class CheckData extends Command
User::withTrashed()
->where('deleted_at', '0000-00-00 00:00:00.000000')
->cursor()
- ->each(function ($user){
+ ->each(function ($user) {
$user->restore();
});
}
private function checkEntityInvitations()
{
-
- RecurringInvoiceInvitation::where('deleted_at',"0000-00-00 00:00:00.000000")->withTrashed()->update(['deleted_at' => null]);
- InvoiceInvitation::where('deleted_at',"0000-00-00 00:00:00.000000")->withTrashed()->update(['deleted_at' => null]);
- QuoteInvitation::where('deleted_at',"0000-00-00 00:00:00.000000")->withTrashed()->update(['deleted_at' => null]);
- CreditInvitation::where('deleted_at',"0000-00-00 00:00:00.000000")->withTrashed()->update(['deleted_at' => null]);
+ RecurringInvoiceInvitation::where('deleted_at', "0000-00-00 00:00:00.000000")->withTrashed()->update(['deleted_at' => null]);
+ InvoiceInvitation::where('deleted_at', "0000-00-00 00:00:00.000000")->withTrashed()->update(['deleted_at' => null]);
+ QuoteInvitation::where('deleted_at', "0000-00-00 00:00:00.000000")->withTrashed()->update(['deleted_at' => null]);
+ CreditInvitation::where('deleted_at', "0000-00-00 00:00:00.000000")->withTrashed()->update(['deleted_at' => null]);
- collect([Invoice::class, Quote::class, Credit::class, PurchaseOrder::class])->each(function ($entity){
-
- if($entity::doesntHave('invitations')->count() > 0)
- {
-
+ collect([Invoice::class, Quote::class, Credit::class, PurchaseOrder::class])->each(function ($entity) {
+ if ($entity::doesntHave('invitations')->count() > 0) {
$entity::doesntHave('invitations')->cursor()->each(function ($entity) {
-
$client_vendor_key = 'client_id';
$contact_id = 'client_contact_id';
$contact_class = ClientContact::class;
@@ -446,55 +427,47 @@ class CheckData extends Command
$entity_key = \Illuminate\Support\Str::of(class_basename($entity))->snake()->append('_id')->value;
$entity_obj = get_class($entity).'Invitation';
- if($entity instanceof PurchaseOrder){
+ if ($entity instanceof PurchaseOrder) {
$client_vendor_key = 'vendor_id';
$contact_id = 'vendor_contact_id';
$contact_class = VendorContact::class;
}
- $invitation = false;
+ $invitation = false;
- //check contact exists!
- if($contact_class::where('company_id', $entity->company_id)->where($client_vendor_key,$entity->{$client_vendor_key})->exists())
- {
+ //check contact exists!
+ if ($contact_class::where('company_id', $entity->company_id)->where($client_vendor_key, $entity->{$client_vendor_key})->exists()) {
+ $contact = $contact_class::where('company_id', $entity->company_id)->where($client_vendor_key, $entity->{$client_vendor_key})->first();
- $contact = $contact_class::where('company_id', $entity->company_id)->where($client_vendor_key,$entity->{$client_vendor_key})->first();
-
- //double check if an archived invite exists
- if($contact && $entity_obj::withTrashed()->where($entity_key, $entity->id)->where($contact_id, $contact->id)->count() != 0) {
- $i = $entity_obj::withTrashed()->where($entity_key, $entity->id)->where($contact_id, $contact->id)->first();
- $i->restore();
- $this->logMessage("Found a valid contact and invitation restoring for {$entity_key} - {$entity->id}");
- }
- else {
- $invitation = new $entity_obj();
- $invitation->company_id = $entity->company_id;
- $invitation->user_id = $entity->user_id;
- $invitation->{$entity_key} = $entity->id;
- $invitation->{$contact_id} = $contact->id;
- $invitation->key = Str::random(config('ninja.key_length'));
- $this->logMessage("Add invitation for {$entity_key} - {$entity->id}");
- }
+ //double check if an archived invite exists
+ if ($contact && $entity_obj::withTrashed()->where($entity_key, $entity->id)->where($contact_id, $contact->id)->count() != 0) {
+ $i = $entity_obj::withTrashed()->where($entity_key, $entity->id)->where($contact_id, $contact->id)->first();
+ $i->restore();
+ $this->logMessage("Found a valid contact and invitation restoring for {$entity_key} - {$entity->id}");
+ } else {
+ $invitation = new $entity_obj();
+ $invitation->company_id = $entity->company_id;
+ $invitation->user_id = $entity->user_id;
+ $invitation->{$entity_key} = $entity->id;
+ $invitation->{$contact_id} = $contact->id;
+ $invitation->key = Str::random(config('ninja.key_length'));
+ $this->logMessage("Add invitation for {$entity_key} - {$entity->id}");
}
- else
- $this->logMessage("No contact present, so cannot add invitation for {$entity_key} - {$entity->id}");
-
- try{
-
- if($invitation)
- $invitation->save();
+ } else {
+ $this->logMessage("No contact present, so cannot add invitation for {$entity_key} - {$entity->id}");
}
- catch(\Exception $e){
+
+ try {
+ if ($invitation) {
+ $invitation->save();
+ }
+ } catch(\Exception $e) {
$this->logMessage($e->getMessage());
$invitation = null;
}
-
});
-
}
-
});
-
}
private function fixInvitations($entities, $entity)
@@ -503,8 +476,7 @@ class CheckData extends Command
$entity_obj = 'App\Models\\'.ucfirst(Str::camel($entity)).'Invitation';
- foreach($entities as $entity)
- {
+ foreach ($entities as $entity) {
$invitation = new $entity_obj();
$invitation->company_id = $entity->company_id;
$invitation->user_id = $entity->user_id;
@@ -512,20 +484,17 @@ class CheckData extends Command
$invitation->client_contact_id = ClientContact::whereClientId($entity->client_id)->first()->id;
$invitation->key = Str::random(config('ninja.key_length'));
- try{
+ try {
$invitation->save();
- }
- catch(\Exception $e){
+ } catch(\Exception $e) {
$invitation = null;
}
-
}
-
}
private function clientPaidToDateQuery()
{
- $results = \DB::select( \DB::raw("
+ $results = \DB::select(\DB::raw("
SELECT
clients.id as client_id,
clients.paid_to_date as client_paid_to_date,
@@ -540,14 +509,14 @@ class CheckData extends Command
GROUP BY clients.id
HAVING payments_applied != client_paid_to_date
ORDER BY clients.id;
- ") );
+ "));
return $results;
}
private function clientCreditPaymentables($client)
{
- $results = \DB::select( \DB::raw("
+ $results = \DB::select(\DB::raw("
SELECT
SUM(paymentables.amount - paymentables.refunded) as credit_payment
FROM payments
@@ -559,7 +528,7 @@ class CheckData extends Command
AND paymentables.amount > 0
AND payments.is_deleted = 0
AND payments.client_id = ?;
- "), [App\Models\Credit::class, $client->id] );
+ "), [App\Models\Credit::class, $client->id]);
return $results;
}
@@ -570,8 +539,7 @@ class CheckData extends Command
$this->wrong_paid_to_dates = 0;
- foreach($clients_to_check as $_client)
- {
+ foreach ($clients_to_check as $_client) {
$client = Client::withTrashed()->find($_client->client_id);
$credits_from_reversal = Credit::withTrashed()->where('client_id', $client->id)->where('is_deleted', 0)->whereNotNull('invoice_id')->sum('amount');
@@ -580,26 +548,22 @@ class CheckData extends Command
$total_paid_to_date = $_client->payments_applied + $credits_used_for_payments[0]->credit_payment - $credits_from_reversal;
- if(round($total_paid_to_date,2) != round($_client->client_paid_to_date,2)){
-
+ if (round($total_paid_to_date, 2) != round($_client->client_paid_to_date, 2)) {
$this->wrong_paid_to_dates++;
$this->logMessage($client->present()->name().' id = # '.$client->id." - Client Paid To Date = {$client->paid_to_date} != Invoice Payments = {$total_paid_to_date} - {$_client->payments_applied} + {$credits_used_for_payments[0]->credit_payment}");
$this->isValid = false;
- if($this->option('paid_to_date')){
+ if ($this->option('paid_to_date')) {
$this->logMessage("# {$client->id} " . $client->present()->name().' - '.$client->number." Fixing {$client->paid_to_date} to {$total_paid_to_date}");
$client->paid_to_date = $total_paid_to_date;
$client->save();
}
-
}
-
}
$this->logMessage("{$this->wrong_paid_to_dates} clients with incorrect paid to dates");
-
}
private function checkPaidToDates()
@@ -608,12 +572,12 @@ class CheckData extends Command
$credit_total_applied = 0;
$clients = DB::table('clients')
- ->leftJoin('payments', function($join) {
+ ->leftJoin('payments', function ($join) {
$join->on('payments.client_id', '=', 'clients.id')
->where('payments.is_deleted', 0)
- ->whereIn('payments.status_id', [Payment::STATUS_COMPLETED, Payment:: STATUS_PENDING, Payment::STATUS_PARTIALLY_REFUNDED, Payment::STATUS_REFUNDED]);
+ ->whereIn('payments.status_id', [Payment::STATUS_COMPLETED, Payment::STATUS_PENDING, Payment::STATUS_PARTIALLY_REFUNDED, Payment::STATUS_REFUNDED]);
})
- ->where('clients.is_deleted',0)
+ ->where('clients.is_deleted', 0)
->where('clients.updated_at', '>', now()->subDays(2))
->groupBy('clients.id')
->havingRaw('clients.paid_to_date != sum(coalesce(payments.amount - payments.refunded, 0))')
@@ -621,32 +585,28 @@ class CheckData extends Command
/* Due to accounting differences we need to perform a second loop here to ensure there actually is an issue */
$clients->each(function ($client_record) use ($credit_total_applied) {
-
$client = Client::withTrashed()->find($client_record->id);
$total_invoice_payments = 0;
foreach ($client->invoices()->where('is_deleted', false)->where('status_id', '>', 1)->get() as $invoice) {
-
$total_invoice_payments += $invoice->payments()
- ->where('is_deleted', false)->whereIn('status_id', [Payment::STATUS_COMPLETED, Payment:: STATUS_PENDING, Payment::STATUS_PARTIALLY_REFUNDED, Payment::STATUS_REFUNDED])
+ ->where('is_deleted', false)->whereIn('status_id', [Payment::STATUS_COMPLETED, Payment::STATUS_PENDING, Payment::STATUS_PARTIALLY_REFUNDED, Payment::STATUS_REFUNDED])
->selectRaw('sum(paymentables.amount - paymentables.refunded) as p')
->pluck('p')
->first();
-
}
//commented IN 27/06/2021 - sums ALL client payments AND the unapplied amounts to match the client paid to date
$p = Payment::where('client_id', $client->id)
->where('is_deleted', 0)
- ->whereIn('status_id', [Payment::STATUS_COMPLETED, Payment:: STATUS_PENDING, Payment::STATUS_PARTIALLY_REFUNDED, Payment::STATUS_REFUNDED])
+ ->whereIn('status_id', [Payment::STATUS_COMPLETED, Payment::STATUS_PENDING, Payment::STATUS_PARTIALLY_REFUNDED, Payment::STATUS_REFUNDED])
->sum(DB::Raw('amount - applied'));
$total_invoice_payments += $p;
// 10/02/21
foreach ($client->payments as $payment) {
-
$credit_total_applied += $payment->paymentables()
->where('paymentable_type', App\Models\Credit::class)
->selectRaw('sum(paymentables.amount - paymentables.refunded) as p')
@@ -656,7 +616,7 @@ class CheckData extends Command
if ($credit_total_applied < 0) {
$total_invoice_payments += $credit_total_applied;
- }
+ }
if (round($total_invoice_payments, 2) != round($client->paid_to_date, 2)) {
$this->wrong_paid_to_dates++;
@@ -665,7 +625,7 @@ class CheckData extends Command
$this->isValid = false;
- if($this->option('paid_to_date')){
+ if ($this->option('paid_to_date')) {
$this->logMessage("# {$client->id} " . $client->present()->name().' - '.$client->number." Fixing {$client->paid_to_date} to {$total_invoice_payments}");
$client->paid_to_date = $total_invoice_payments;
$client->save();
@@ -681,11 +641,9 @@ class CheckData extends Command
$this->wrong_balances = 0;
Client::cursor()->where('is_deleted', 0)->where('clients.updated_at', '>', now()->subDays(2))->each(function ($client) {
-
$client->invoices->where('is_deleted', false)->whereIn('status_id', '!=', Invoice::STATUS_DRAFT)->each(function ($invoice) use ($client) {
-
$total_paid = $invoice->payments()
- ->where('is_deleted', false)->whereIn('status_id', [Payment::STATUS_COMPLETED, Payment:: STATUS_PENDING, Payment::STATUS_PARTIALLY_REFUNDED, Payment::STATUS_REFUNDED])
+ ->where('is_deleted', false)->whereIn('status_id', [Payment::STATUS_COMPLETED, Payment::STATUS_PENDING, Payment::STATUS_PARTIALLY_REFUNDED, Payment::STATUS_REFUNDED])
->selectRaw('sum(paymentables.amount - paymentables.refunded) as p')
->pluck('p')
->first();
@@ -702,7 +660,6 @@ class CheckData extends Command
$this->isValid = false;
}
});
-
});
$this->logMessage("{$this->wrong_balances} clients with incorrect invoice balances");
@@ -710,7 +667,7 @@ class CheckData extends Command
private function clientBalanceQuery()
{
- $results = \DB::select( \DB::raw("
+ $results = \DB::select(\DB::raw("
SELECT
SUM(invoices.balance) as invoice_balance,
clients.id as client_id,
@@ -724,7 +681,7 @@ class CheckData extends Command
GROUP BY clients.id
HAVING invoice_balance != clients.balance
ORDER BY clients.id;
- ") );
+ "));
return $results;
}
@@ -736,8 +693,7 @@ class CheckData extends Command
$clients = $this->clientBalanceQuery();
- foreach($clients as $client)
- {
+ foreach ($clients as $client) {
$client = (array)$client;
if ((string) $client['invoice_balance'] != (string) $client['client_balance']) {
@@ -747,18 +703,14 @@ class CheckData extends Command
$this->logMessage($client_object->present()->name().' - '.$client_object->id." - calculated client balances do not match Invoice Balances = ". $client['invoice_balance'] ." - Client Balance = ".rtrim($client['client_balance'], '0'));
- if($this->option('client_balance')){
-
+ if ($this->option('client_balance')) {
$this->logMessage("# {$client_object->id} " . $client_object->present()->name().' - '.$client_object->number." Fixing {$client_object->balance} to " . $client['invoice_balance']);
$client_object->balance = $client['invoice_balance'];
$client_object->save();
-
}
- $this->isValid = false;
-
+ $this->isValid = false;
}
-
}
$this->logMessage("{$this->wrong_paid_to_dates} clients with incorrect client balances");
@@ -767,58 +719,46 @@ class CheckData extends Command
private function checkClientBalanceEdgeCases()
{
Client::query()
- ->where('is_deleted',false)
+ ->where('is_deleted', false)
->where('balance', '!=', 0)
->cursor()
- ->each(function ($client){
+ ->each(function ($client) {
+ $count = Invoice::withTrashed()
+ ->where('client_id', $client->id)
+ ->where('is_deleted', false)
+ ->whereIn('status_id', [2,3])
+ ->count();
- $count = Invoice::withTrashed()
- ->where('client_id', $client->id)
- ->where('is_deleted',false)
- ->whereIn('status_id', [2,3])
- ->count();
+ if ($count == 0) {
+ //factor in over payments to the client balance
+ $over_payment = Payment::where('client_id', $client->id)
+ ->where('is_deleted', 0)
+ ->whereIn('status_id', [1,4])
+ ->selectRaw('sum(amount - applied) as p')
+ ->pluck('p')
+ ->first();
- if($count == 0){
-
- //factor in over payments to the client balance
- $over_payment = Payment::where('client_id', $client->id)
- ->where('is_deleted', 0)
- ->whereIn('status_id', [1,4])
- ->selectRaw('sum(amount - applied) as p')
- ->pluck('p')
- ->first();
+ $over_payment = $over_payment*-1;
- $over_payment = $over_payment*-1;
-
- if(floatval($over_payment) == floatval($client->balance)){
-
- }
- else {
-
- $this->logMessage("# {$client->id} # {$client->name} {$client->balance} is invalid should be {$over_payment}");
-
- }
+ if (floatval($over_payment) == floatval($client->balance)) {
+ } else {
+ $this->logMessage("# {$client->id} # {$client->name} {$client->balance} is invalid should be {$over_payment}");
+ }
- if($this->option('client_balance') && (floatval($over_payment) != floatval($client->balance) )){
-
- $this->logMessage("# {$client->id} " . $client->present()->name().' - '.$client->number." Fixing {$client->balance} to 0");
-
- $client->balance = $over_payment;
- $client->save();
-
- }
-
-
- }
+ if ($this->option('client_balance') && (floatval($over_payment) != floatval($client->balance))) {
+ $this->logMessage("# {$client->id} " . $client->present()->name().' - '.$client->number." Fixing {$client->balance} to 0");
+ $client->balance = $over_payment;
+ $client->save();
+ }
+ }
});
-
}
private function invoiceBalanceQuery()
{
- $results = \DB::select( \DB::raw("
+ $results = \DB::select(\DB::raw("
SELECT
clients.id,
clients.balance,
@@ -832,7 +772,7 @@ class CheckData extends Command
GROUP BY clients.id
HAVING(invoices_balance != clients.balance)
ORDER BY clients.id;
- ") );
+ "));
return $results;
}
@@ -844,8 +784,7 @@ class CheckData extends Command
$_clients = $this->invoiceBalanceQuery();
- foreach($_clients as $_client)
- {
+ foreach ($_clients as $_client) {
$client = Client::withTrashed()->find($_client->id);
$invoice_balance = $client->invoices()->where('is_deleted', false)->whereIn('status_id', [2,3])->sum('balance');
@@ -860,27 +799,22 @@ class CheckData extends Command
$this->isValid = false;
- if($this->option('client_balance')){
-
+ if ($this->option('client_balance')) {
$this->logMessage("# {$client->id} " . $client->present()->name().' - '.$client->number." Fixing {$client->balance} to {$invoice_balance}");
$client->balance = $invoice_balance;
$client->save();
-
}
- if($ledger && (number_format($invoice_balance, 4) != number_format($ledger->balance, 4)))
- {
+ if ($ledger && (number_format($invoice_balance, 4) != number_format($ledger->balance, 4))) {
$ledger->adjustment = $invoice_balance;
$ledger->balance = $invoice_balance;
$ledger->notes = 'Ledger Adjustment';
$ledger->save();
}
-
}
}
$this->logMessage("{$this->wrong_balances} clients with incorrect balances");
-
}
private function checkLedgerBalances()
@@ -899,8 +833,7 @@ class CheckData extends Command
$this->isValid = false;
- if($this->option('ledger_balance')){
-
+ if ($this->option('ledger_balance')) {
$this->logMessage("# {$client->id} " . $client->present()->name().' - '.$client->number." Fixing {$client->balance} to {$invoice_balance}");
$client->balance = $invoice_balance;
$client->save();
@@ -910,7 +843,6 @@ class CheckData extends Command
$ledger->notes = 'Ledger Adjustment';
$ledger->save();
}
-
}
}
@@ -1002,31 +934,27 @@ class CheckData extends Command
public function checkAccountStatuses()
{
- Account::where('plan_expires', '<=', now()->subDays(2))->cursor()->each(function ($account){
-
+ Account::where('plan_expires', '<=', now()->subDays(2))->cursor()->each(function ($account) {
$client = Client::on('db-ninja-01')->where('company_id', config('ninja.ninja_default_company_id'))->where('custom_value2', $account->key)->first();
- if($client){
+ if ($client) {
$payment = Payment::on('db-ninja-01')
->where('company_id', config('ninja.ninja_default_company_id'))
->where('client_id', $client->id)
->where('date', '>=', now()->subDays(2))
->exists();
- if($payment)
+ if ($payment) {
$this->logMessage("I found a payment for {$account->key}");
-
+ }
}
-
});
}
public function checkClientSettings()
{
-
if ($this->option('fix') == 'true') {
-
// Client::query()->whereNull('settings->currency_id')->cursor()->each(function ($client){
// if(is_array($client->settings) && count($client->settings) == 0)
@@ -1047,36 +975,25 @@ class CheckData extends Command
// });
- Client::query()->whereNull('country_id')->cursor()->each(function ($client){
-
+ Client::query()->whereNull('country_id')->cursor()->each(function ($client) {
$client->country_id = $client->company->settings->country_id;
$client->save();
$this->logMessage("Fixing country for # {$client->id}");
-
});
-
}
-
}
public function checkVendorSettings()
{
-
- if ($this->option('fix') == 'true')
- {
-
- Vendor::query()->whereNull('currency_id')->orWhere('currency_id', '')->cursor()->each(function ($vendor){
-
+ if ($this->option('fix') == 'true') {
+ Vendor::query()->whereNull('currency_id')->orWhere('currency_id', '')->cursor()->each(function ($vendor) {
$vendor->currency_id = $vendor->company->settings->currency_id;
$vendor->save();
$this->logMessage("Fixing vendor currency for # {$vendor->id}");
-
});
-
}
-
}
@@ -1085,14 +1002,12 @@ class CheckData extends Command
{
$this->wrong_paid_status = 0;
- foreach(Invoice::with(['payments'])->where('is_deleted',0)->where('balance', '>', 0)->whereHas('payments')->where('status_id', 4)->cursor() as $invoice)
- {
+ foreach (Invoice::with(['payments'])->where('is_deleted', 0)->where('balance', '>', 0)->whereHas('payments')->where('status_id', 4)->cursor() as $invoice) {
$this->wrong_paid_status++;
$this->logMessage("# {$invoice->id} " . ' - '.$invoice->number." - Marked as paid, but balance = {$invoice->balance}");
- if($this->option('balance_status')){
-
+ if ($this->option('balance_status')) {
$val = $invoice->balance;
$invoice->balance = 0;
@@ -1101,8 +1016,7 @@ class CheckData extends Command
$p = $invoice->payments->first();
- if($p && (int)$p->amount == 0)
- {
+ if ($p && (int)$p->amount == 0) {
$p->amount = $val;
$p->applied = $val;
$p->save();
@@ -1114,62 +1028,48 @@ class CheckData extends Command
$this->logMessage("Fixing {$invoice->id} settings payment to {$val}");
-
}
-
}
$this->logMessage($this->wrong_paid_status." wrong invoices with bad balance state");
-
}
public function checkNinjaPortalUrls()
{
-
- $wrong_count = CompanyUser::where('is_owner',1)->where('ninja_portal_url', '')->count();
+ $wrong_count = CompanyUser::where('is_owner', 1)->where('ninja_portal_url', '')->count();
$this->logMessage("Missing ninja portal Urls = {$wrong_count}");
- if(!$this->option('portal_url'))
+ if (!$this->option('portal_url')) {
return;
+ }
- CompanyUser::where('is_owner',1)->where('ninja_portal_url', '')->cursor()->each(function ($cu){
+ CompanyUser::where('is_owner', 1)->where('ninja_portal_url', '')->cursor()->each(function ($cu) {
+ $cc = ClientContact::on('db-ninja-01')->where('company_id', config('ninja.ninja_default_company_id'))->where('email', $cu->user->email)->first();
- $cc = ClientContact::on('db-ninja-01')->where('company_id', config('ninja.ninja_default_company_id'))->where('email', $cu->user->email)->first();
-
- if($cc){
+ if ($cc) {
$ninja_portal_url = "https://invoiceninja.invoicing.co/client/ninja/{$cc->contact_key}/{$cu->account->key}";
$cu->ninja_portal_url = $ninja_portal_url;
$cu->save();
$this->logMessage("Fixing - {$ninja_portal_url}");
- }
- else{
-
+ } else {
$c = Client::on('db-ninja-01')->where("company_id", config('ninja.ninja_default_company_id'))->where('custom_value2', $cu->account->key)->first();
- if($c)
- {
-
- $cc = $c->contacts()->first();
+ if ($c) {
+ $cc = $c->contacts()->first();
- if($cc)
- {
+ if ($cc) {
$ninja_portal_url = "https://invoiceninja.invoicing.co/client/ninja/{$cc->contact_key}/{$cu->account->key}";
$cu->ninja_portal_url = $ninja_portal_url;
$cu->save();
$this->logMessage("Fixing - {$ninja_portal_url}");
-
- }
-
}
-
+ }
}
-
});
-
}
-}
\ No newline at end of file
+}
diff --git a/app/Console/Commands/CheckDb.php b/app/Console/Commands/CheckDb.php
index c8e09736aac0..f143b0c5a834 100644
--- a/app/Console/Commands/CheckDb.php
+++ b/app/Console/Commands/CheckDb.php
@@ -11,8 +11,6 @@
namespace App\Console\Commands;
-use App;
-use App\Factory\ClientContactFactory;
use App\Models\Account;
use App\Models\Activity;
use App\Models\Backup;
@@ -24,7 +22,6 @@ use App\Models\CompanyGateway;
use App\Models\CompanyLedger;
use App\Models\CompanyToken;
use App\Models\CompanyUser;
-use App\Models\Contact;
use App\Models\Credit;
use App\Models\CreditInvitation;
use App\Models\Design;
@@ -53,13 +50,7 @@ use App\Models\User;
use App\Models\Vendor;
use App\Models\VendorContact;
use App\Models\Webhook;
-use App\Utils\Ninja;
-use DB;
-use Exception;
use Illuminate\Console\Command;
-use Illuminate\Support\Str;
-use Mail;
-use Symfony\Component\Console\Input\InputOption;
/**
* Class CheckDb.
diff --git a/app/Console/Commands/CreateAccount.php b/app/Console/Commands/CreateAccount.php
index 5748d32da6d3..e4e5b31e3dca 100644
--- a/app/Console/Commands/CreateAccount.php
+++ b/app/Console/Commands/CreateAccount.php
@@ -13,40 +13,19 @@ namespace App\Console\Commands;
use App\DataMapper\ClientRegistrationFields;
use App\DataMapper\CompanySettings;
-use App\DataMapper\FeesAndLimits;
-use App\Events\Invoice\InvoiceWasCreated;
-use App\Factory\InvoiceFactory;
-use App\Factory\InvoiceItemFactory;
-use App\Helpers\Invoice\InvoiceSum;
use App\Jobs\Company\CreateCompanyPaymentTerms;
use App\Jobs\Company\CreateCompanyTaskStatuses;
use App\Jobs\Util\VersionCheck;
use App\Models\Account;
-use App\Models\Client;
-use App\Models\ClientContact;
use App\Models\Company;
-use App\Models\CompanyGateway;
use App\Models\CompanyToken;
-use App\Models\Country;
-use App\Models\Credit;
-use App\Models\Expense;
-use App\Models\Product;
-use App\Models\Project;
-use App\Models\Quote;
-use App\Models\Task;
use App\Models\User;
-use App\Models\Vendor;
-use App\Models\VendorContact;
use App\Repositories\InvoiceRepository;
-use App\Utils\Ninja;
use App\Utils\Traits\GeneratesCounter;
use App\Utils\Traits\MakesHash;
-use Carbon\Carbon;
-use Faker\Factory;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Hash;
-use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
class CreateAccount extends Command
@@ -140,7 +119,6 @@ class CreateAccount extends Command
(new VersionCheck())->handle();
$this->warmCache();
-
}
private function warmCache()
@@ -162,7 +140,6 @@ class CreateAccount extends Command
if ($tableData->count()) {
Cache::forever($name, $tableData);
}
-
}
}
}
diff --git a/app/Console/Commands/CreateSingleAccount.php b/app/Console/Commands/CreateSingleAccount.php
index d1a77dadbcdd..402769667cb3 100644
--- a/app/Console/Commands/CreateSingleAccount.php
+++ b/app/Console/Commands/CreateSingleAccount.php
@@ -50,13 +50,11 @@ use App\Utils\Ninja;
use App\Utils\Traits\GeneratesCounter;
use App\Utils\Traits\MakesHash;
use Carbon\Carbon;
-use Database\Factories\BankTransactionRuleFactory;
use Faker\Factory;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Schema;
-use Illuminate\Support\Str;
use stdClass;
class CreateSingleAccount extends Command
@@ -80,9 +78,9 @@ class CreateSingleAccount extends Command
*/
public function handle()
{
-
- if (Ninja::isHosted() || config('ninja.is_docker') || !$this->confirm('Are you sure you want to inject dummy data?'))
+ if (Ninja::isHosted() || config('ninja.is_docker') || !$this->confirm('Are you sure you want to inject dummy data?')) {
return;
+ }
$this->invoice_repo = new InvoiceRepository();
@@ -103,8 +101,7 @@ class CreateSingleAccount extends Command
{
$this->info('Creating Small Account and Company');
- if($user = User::where('email','small@example.com')->first())
- {
+ if ($user = User::where('email', 'small@example.com')->first()) {
$user->account->delete();
}
@@ -201,7 +198,7 @@ class CreateSingleAccount extends Command
$btr = BankTransactionRule::factory()->create([
'user_id' => $user->id,
'company_id' => $company->id,
- 'applies_to' => (bool)rand(0,1) ? 'CREDIT' : 'DEBIT',
+ 'applies_to' => (bool)rand(0, 1) ? 'CREDIT' : 'DEBIT',
]);
$client = Client::factory()->create([
@@ -359,7 +356,6 @@ class CreateSingleAccount extends Command
private function createClient($company, $user)
{
-
// dispatch(function () use ($company, $user) {
// });
@@ -630,30 +626,29 @@ class CreateSingleAccount extends Command
$cached_tables = config('ninja.cached_tables');
foreach ($cached_tables as $name => $class) {
- // check that the table exists in case the migration is pending
- if (! Schema::hasTable((new $class())->getTable())) {
- continue;
- }
- if ($name == 'payment_terms') {
- $orderBy = 'num_days';
- } elseif ($name == 'fonts') {
- $orderBy = 'sort_order';
- } elseif (in_array($name, ['currencies', 'industries', 'languages', 'countries', 'banks'])) {
- $orderBy = 'name';
- } else {
- $orderBy = 'id';
- }
- $tableData = $class::orderBy($orderBy)->get();
- if ($tableData->count()) {
- Cache::forever($name, $tableData);
- }
+ // check that the table exists in case the migration is pending
+ if (! Schema::hasTable((new $class())->getTable())) {
+ continue;
+ }
+ if ($name == 'payment_terms') {
+ $orderBy = 'num_days';
+ } elseif ($name == 'fonts') {
+ $orderBy = 'sort_order';
+ } elseif (in_array($name, ['currencies', 'industries', 'languages', 'countries', 'banks'])) {
+ $orderBy = 'name';
+ } else {
+ $orderBy = 'id';
+ }
+ $tableData = $class::orderBy($orderBy)->get();
+ if ($tableData->count()) {
+ Cache::forever($name, $tableData);
+ }
}
}
private function createGateways($company, $user)
{
if (config('ninja.testvars.stripe') && ($this->gateway == 'all' || $this->gateway == 'stripe')) {
-
$cg = new CompanyGateway;
$cg->company_id = $company->id;
$cg->user_id = $user->id;
@@ -672,8 +667,6 @@ class CreateSingleAccount extends Command
$cg->fees_and_limits = $fees_and_limits;
$cg->save();
-
-
}
if (config('ninja.testvars.paypal') && ($this->gateway == 'all' || $this->gateway == 'paypal')) {
diff --git a/app/Console/Commands/CreateTestData.php b/app/Console/Commands/CreateTestData.php
index e7b5d44d7998..cd94c3ab70c2 100644
--- a/app/Console/Commands/CreateTestData.php
+++ b/app/Console/Commands/CreateTestData.php
@@ -380,7 +380,6 @@ class CreateTestData extends Command
private function createClient($company, $user)
{
-
// dispatch(function () use ($company, $user) {
// });
diff --git a/app/Console/Commands/DemoMode.php b/app/Console/Commands/DemoMode.php
index 3acbdd942d83..8cde523d3eed 100644
--- a/app/Console/Commands/DemoMode.php
+++ b/app/Console/Commands/DemoMode.php
@@ -257,7 +257,6 @@ class DemoMode extends Command
private function createClient($company, $user, $assigned_user_id = null)
{
-
// dispatch(function () use ($company, $user) {
// });
diff --git a/app/Console/Commands/DesignUpdate.php b/app/Console/Commands/DesignUpdate.php
index e069afa93799..c924ea268dfc 100644
--- a/app/Console/Commands/DesignUpdate.php
+++ b/app/Console/Commands/DesignUpdate.php
@@ -56,7 +56,6 @@ class DesignUpdate extends Command
if (! config('ninja.db.multi_db_enabled')) {
$this->handleOnDb();
} else {
-
//multiDB environment, need to
foreach (MultiDB::$dbs as $db) {
MultiDB::setDB($db);
diff --git a/app/Console/Commands/HostedMigrations.php b/app/Console/Commands/HostedMigrations.php
index 77ca261b2d37..d2a3b4bcc1b8 100644
--- a/app/Console/Commands/HostedMigrations.php
+++ b/app/Console/Commands/HostedMigrations.php
@@ -11,27 +11,19 @@
namespace App\Console\Commands;
-use App\DataMapper\CompanySettings;
use App\Exceptions\MigrationValidatorFailed;
use App\Exceptions\NonExistingMigrationFile;
use App\Exceptions\ProcessingMigrationArchiveFailed;
use App\Exceptions\ResourceDependencyMissing;
use App\Exceptions\ResourceNotAvailableForMigration;
use App\Jobs\Util\Import;
-use App\Jobs\Util\StartMigration;
use App\Libraries\MultiDB;
use App\Mail\MigrationFailed;
-use App\Models\Account;
-use App\Models\Company;
-use App\Models\CompanyToken;
use App\Models\User;
use App\Utils\Traits\AppSetup;
use App\Utils\Traits\MakesHash;
use DirectoryIterator;
-use Faker\Factory;
-use Faker\Generator;
use Illuminate\Console\Command;
-use Illuminate\Support\Str;
use ZipArchive;
class HostedMigrations extends Command
diff --git a/app/Console/Commands/HostedUsers.php b/app/Console/Commands/HostedUsers.php
index 92df70a91830..133198b3e4cd 100644
--- a/app/Console/Commands/HostedUsers.php
+++ b/app/Console/Commands/HostedUsers.php
@@ -11,9 +11,7 @@
namespace App\Console\Commands;
-use App\Models\ClientContact;
use App\Models\Company;
-use App\Models\User;
use App\Utils\Ninja;
use Illuminate\Console\Command;
diff --git a/app/Console/Commands/MobileLocalization.php b/app/Console/Commands/MobileLocalization.php
index bcc3fc6df7bb..482cf9042ade 100644
--- a/app/Console/Commands/MobileLocalization.php
+++ b/app/Console/Commands/MobileLocalization.php
@@ -11,8 +11,6 @@
namespace App\Console\Commands;
-use App\Models\Company;
-use App\Models\User;
use App\Utils\CurlUtils;
use Illuminate\Console\Command;
diff --git a/app/Console/Commands/OpenApiYaml.php b/app/Console/Commands/OpenApiYaml.php
index 9c43a7408a9e..06ea62e50eaf 100644
--- a/app/Console/Commands/OpenApiYaml.php
+++ b/app/Console/Commands/OpenApiYaml.php
@@ -63,9 +63,7 @@ class OpenApiYaml extends Command
$this->info($directory);
foreach ($directory as $file) {
-
- $this->info($file);
-
+ $this->info($file);
}
Storage::disk('base')->delete('/openapi/api-docs.yaml');
@@ -76,14 +74,9 @@ class OpenApiYaml extends Command
$directory = new DirectoryIterator($path . '/paths/');
foreach ($directory as $file) {
-
- if ($file->isFile() && ! $file->isDot())
- {
-
+ if ($file->isFile() && ! $file->isDot()) {
Storage::disk('base')->append('/openapi/api-docs.yaml', file_get_contents("{$path}/paths/{$file->getFilename()}"));
-
}
-
}
@@ -96,20 +89,12 @@ class OpenApiYaml extends Command
$directory = new DirectoryIterator($path . '/components/schemas/');
foreach ($directory as $file) {
-
- if ($file->isFile() && ! $file->isDot())
- {
-
+ if ($file->isFile() && ! $file->isDot()) {
Storage::disk('base')->append('/openapi/api-docs.yaml', file_get_contents("{$path}/components/schemas/{$file->getFilename()}"));
-
}
-
}
// Storage::disk('base')->append('/openapi/api-docs.yaml', file_get_contents($path.'/components/schemas/account.yaml'));
Storage::disk('base')->append('/openapi/api-docs.yaml', file_get_contents($path.'/misc/misc.yaml'));
-
-
}
-
}
diff --git a/app/Console/Commands/PostUpdate.php b/app/Console/Commands/PostUpdate.php
index 8b71ba90d81d..9f6365404efa 100644
--- a/app/Console/Commands/PostUpdate.php
+++ b/app/Console/Commands/PostUpdate.php
@@ -12,7 +12,6 @@
namespace App\Console\Commands;
use App\Jobs\Util\VersionCheck;
-use App\Utils\Ninja;
use App\Utils\Traits\AppSetup;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;
diff --git a/app/Console/Commands/ReactBuilder.php b/app/Console/Commands/ReactBuilder.php
index c155bc2a43b0..7e75e59887b7 100644
--- a/app/Console/Commands/ReactBuilder.php
+++ b/app/Console/Commands/ReactBuilder.php
@@ -11,12 +11,7 @@
namespace App\Console\Commands;
-use App\Libraries\MultiDB;
-use App\Models\Backup;
-use App\Models\Design;
use Illuminate\Console\Command;
-use Illuminate\Support\Facades\Storage;
-use stdClass;
class ReactBuilder extends Command
{
diff --git a/app/Console/Commands/SendRemindersCron.php b/app/Console/Commands/SendRemindersCron.php
index 5f190351b9af..7319ec30f727 100644
--- a/app/Console/Commands/SendRemindersCron.php
+++ b/app/Console/Commands/SendRemindersCron.php
@@ -14,7 +14,6 @@ namespace App\Console\Commands;
use App\DataMapper\InvoiceItem;
use App\Events\Invoice\InvoiceWasEmailed;
use App\Jobs\Entity\EmailEntity;
-use App\Jobs\Ninja\SendReminders;
use App\Jobs\Util\WebhookHandler;
use App\Libraries\MultiDB;
use App\Models\Invoice;
@@ -97,7 +96,6 @@ class SendRemindersCron extends Command
$invoice->save();
}
});
-
}
private function calcLateFee($invoice, $template) :Invoice
diff --git a/app/Console/Commands/SendTestEmails.php b/app/Console/Commands/SendTestEmails.php
index 1b2a0920307d..0b0aef8bdfcb 100644
--- a/app/Console/Commands/SendTestEmails.php
+++ b/app/Console/Commands/SendTestEmails.php
@@ -13,22 +13,14 @@ namespace App\Console\Commands;
use App\DataMapper\CompanySettings;
use App\DataMapper\DefaultSettings;
-use App\Factory\ClientFactory;
-use App\Factory\InvoiceFactory;
-use App\Factory\InvoiceInvitationFactory;
-use App\Jobs\Invoice\CreateEntityPdf;
use App\Jobs\Mail\NinjaMailerJob;
use App\Jobs\Mail\NinjaMailerObject;
use App\Mail\Migration\MaxCompanies;
-use App\Mail\TemplateEmail;
use App\Models\Account;
-use App\Models\Client;
-use App\Models\ClientContact;
use App\Models\Company;
use App\Models\User;
use Faker\Factory;
use Illuminate\Console\Command;
-use Illuminate\Support\Facades\Mail;
class SendTestEmails extends Command
{
diff --git a/app/Console/Commands/TranslationsExport.php b/app/Console/Commands/TranslationsExport.php
index a88375cb405a..98a34e59bfac 100644
--- a/app/Console/Commands/TranslationsExport.php
+++ b/app/Console/Commands/TranslationsExport.php
@@ -11,14 +11,10 @@
namespace App\Console\Commands;
-use App\Libraries\MultiDB;
-use App\Models\Backup;
-use App\Models\Design;
use Illuminate\Console\Command;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Lang;
use Illuminate\Support\Facades\Storage;
-use stdClass;
class TranslationsExport extends Command
{
@@ -98,42 +94,35 @@ class TranslationsExport extends Command
{
$type =$this->option('type') ?? 'export';
- if($type == 'import')
+ if ($type == 'import') {
$this->import();
+ }
- if($type == 'export')
+ if ($type == 'export') {
$this->export();
-
+ }
}
private function import()
{
//loop and
- foreach($this->langs as $lang)
- {
-
+ foreach ($this->langs as $lang) {
$import_file = "textsphp_{$lang}.php";
$dir = $this->option('path') ?? storage_path('lang_import/');
$path = $dir.$import_file;
- if(file_exists($path)){
+ if (file_exists($path)) {
$this->logMessage($path);
$trans = file_get_contents($path);
file_put_contents(lang_path("/{$lang}/texts.php"), $trans);
-
- }
- else{
-
+ } else {
$this->logMessage("Could not open file");
$this->logMessage($path);
-
}
-
}
-
}
@@ -147,7 +136,7 @@ class TranslationsExport extends Command
$translations = Lang::getLoader()->load($lang, 'texts');
Storage::disk('local')->put("lang/{$lang}/{$lang}.json", json_encode(Arr::dot($translations), JSON_UNESCAPED_UNICODE));
- }
+ }
}
private function logMessage($str)
@@ -156,5 +145,4 @@ class TranslationsExport extends Command
$this->info($str);
$this->log .= $str."\n";
}
-
}
diff --git a/app/Console/Commands/TypeCheck.php b/app/Console/Commands/TypeCheck.php
index 387191db9054..d26785b0ad4b 100644
--- a/app/Console/Commands/TypeCheck.php
+++ b/app/Console/Commands/TypeCheck.php
@@ -11,17 +11,11 @@
namespace App\Console\Commands;
-use App\Http\ValidationRules\ValidClientGroupSettingsRule;
use App\Libraries\MultiDB;
-use App\Models\Backup;
use App\Models\Client;
use App\Models\Company;
-use App\Models\Design;
use App\Utils\Traits\ClientGroupSettingsSaver;
use Illuminate\Console\Command;
-use Illuminate\Support\Facades\Storage;
-use Illuminate\Support\Facades\Validator;
-use stdClass;
class TypeCheck extends Command
{
diff --git a/app/Console/Kernel.php b/app/Console/Kernel.php
index 056e3312a5de..4ba49439c45d 100644
--- a/app/Console/Kernel.php
+++ b/app/Console/Kernel.php
@@ -15,14 +15,13 @@ use App\Jobs\Cron\AutoBillCron;
use App\Jobs\Cron\RecurringExpensesCron;
use App\Jobs\Cron\RecurringInvoicesCron;
use App\Jobs\Cron\SubscriptionCron;
-use App\Jobs\Ledger\LedgerBalanceUpdate;
+use App\Jobs\Invoice\InvoiceCheckLateWebhook;
use App\Jobs\Ninja\AdjustEmailQuota;
use App\Jobs\Ninja\BankTransactionSync;
use App\Jobs\Ninja\CompanySizeCheck;
use App\Jobs\Ninja\QueueSize;
use App\Jobs\Ninja\SystemMaintenance;
use App\Jobs\Ninja\TaskScheduler;
-use App\Jobs\Invoice\InvoiceCheckLateWebhook;
use App\Jobs\Quote\QuoteCheckExpired;
use App\Jobs\Subscription\CleanStaleInvoiceOrder;
use App\Jobs\Util\DiskCleanup;
@@ -96,16 +95,13 @@ class Kernel extends ConsoleKernel
if (Ninja::isSelfHost()) {
-
$schedule->call(function () {
Account::whereNotNull('id')->update(['is_scheduler_running' => true]);
})->everyFiveMinutes();
-
}
/* Run hosted specific jobs */
if (Ninja::isHosted()) {
-
$schedule->job(new AdjustEmailQuota)->dailyAt('23:30')->withoutOverlapping();
/* Pulls in bank transactions from third party services */
@@ -119,15 +115,12 @@ class Kernel extends ConsoleKernel
$schedule->command('ninja:check-data --database=db-ninja-02')->dailyAt('02:20')->withoutOverlapping()->name('check-data-db-2-job')->onOneServer();
$schedule->command('ninja:s3-cleanup')->dailyAt('23:15')->withoutOverlapping()->name('s3-cleanup-job')->onOneServer();
-
}
if (config('queue.default') == 'database' && Ninja::isSelfHost() && config('ninja.internal_queue_enabled') && ! config('ninja.is_docker')) {
-
$schedule->command('queue:work database --stop-when-empty --memory=256')->everyMinute()->withoutOverlapping();
$schedule->command('queue:restart')->everyFiveMinutes()->withoutOverlapping();
-
}
}
diff --git a/app/DataMapper/BaseSettings.php b/app/DataMapper/BaseSettings.php
index 1b0269e86489..489e77db1078 100644
--- a/app/DataMapper/BaseSettings.php
+++ b/app/DataMapper/BaseSettings.php
@@ -57,5 +57,4 @@ class BaseSettings
return $value;
}
}
-
}
diff --git a/app/DataMapper/CompanySettings.php b/app/DataMapper/CompanySettings.php
index 20e479ebebc2..fc3630d6646a 100644
--- a/app/DataMapper/CompanySettings.php
+++ b/app/DataMapper/CompanySettings.php
@@ -762,7 +762,6 @@ class CompanySettings extends BaseSettings
*/
public static function defaults(): stdClass
{
-
$data = (object) get_class_vars(self::class);
unset($data->casts);
diff --git a/app/DataMapper/EmailTemplateDefaults.php b/app/DataMapper/EmailTemplateDefaults.php
index 0f2d856aa0c5..c0c1c1d43ce8 100644
--- a/app/DataMapper/EmailTemplateDefaults.php
+++ b/app/DataMapper/EmailTemplateDefaults.php
@@ -20,7 +20,6 @@ class EmailTemplateDefaults
App::setLocale($locale);
switch ($template) {
-
/* Template */
case 'email_template_invoice':
@@ -65,7 +64,7 @@ class EmailTemplateDefaults
return self::emailPurchaseOrderTemplate();
break;
- /* Subject */
+ /* Subject */
case 'email_subject_purchase_order':
return self::emailPurchaseOrderSubject();
case 'email_subject_invoice':
@@ -240,7 +239,6 @@ class EmailTemplateDefaults
public static function emailStatementTemplate()
{
-
$statement_message = '
$client
'.self::transformText('client_statement_body').'
';
return $statement_message;
diff --git a/app/DataMapper/Schedule/ClientStatement.php b/app/DataMapper/Schedule/ClientStatement.php
index 1e9720593ead..a51cc15154fd 100644
--- a/app/DataMapper/Schedule/ClientStatement.php
+++ b/app/DataMapper/Schedule/ClientStatement.php
@@ -11,15 +11,11 @@
namespace App\DataMapper\Schedule;
-use App\Models\Client;
-use stdClass;
-
class ClientStatement
{
-
/**
* Defines the template name
- *
+ *
* @var string
*/
public string $template = 'client_statement';
@@ -28,7 +24,7 @@ class ClientStatement
* An array of clients hashed_ids
*
* Leave blank if this action should apply to all clients
- *
+ *
* @var array
*/
public array $clients = [];
@@ -46,7 +42,7 @@ class ClientStatement
/**
* The date range the statement should include
- *
+ *
* @var string
*/
public string $date_range = 'this_month';
@@ -54,7 +50,7 @@ class ClientStatement
/**
* If a custom range is select for the date range then
* the start_date should be supplied in Y-m-d format
- *
+ *
* @var string
*/
public string $start_date = '';
@@ -62,7 +58,7 @@ class ClientStatement
/**
* If a custom range is select for the date range then
* the end_date should be supplied in Y-m-d format
- *
+ *
* @var string
*/
public string $end_date = '';
@@ -87,10 +83,8 @@ class ClientStatement
* String const which defines whether
* the invoices to be shown are either
* paid or unpaid
- *
+ *
* @var string
*/
public string $status = 'paid'; // paid | unpaid
-
-
-}
\ No newline at end of file
+}
diff --git a/app/DataMapper/Transactions/ClientStatusTransaction.php b/app/DataMapper/Transactions/ClientStatusTransaction.php
index 5c3810ef3e1b..5fd661f0462e 100644
--- a/app/DataMapper/Transactions/ClientStatusTransaction.php
+++ b/app/DataMapper/Transactions/ClientStatusTransaction.php
@@ -11,10 +11,6 @@
namespace App\DataMapper\Transactions;
-use App\Models\Client;
-use App\Models\Credit;
-use App\Models\Invoice;
-use App\Models\Payment;
use App\Models\TransactionEvent;
/**
diff --git a/app/DataMapper/Transactions/GatewayPaymentMadeTransaction.php b/app/DataMapper/Transactions/GatewayPaymentMadeTransaction.php
index cda3680e1e4d..7a69030dce1b 100644
--- a/app/DataMapper/Transactions/GatewayPaymentMadeTransaction.php
+++ b/app/DataMapper/Transactions/GatewayPaymentMadeTransaction.php
@@ -11,10 +11,6 @@
namespace App\DataMapper\Transactions;
-use App\Models\Client;
-use App\Models\Credit;
-use App\Models\Invoice;
-use App\Models\Payment;
use App\Models\TransactionEvent;
/**
diff --git a/app/DataMapper/Transactions/InvoiceCancelledTransaction.php b/app/DataMapper/Transactions/InvoiceCancelledTransaction.php
index 63952a11383b..d6f5b50de096 100644
--- a/app/DataMapper/Transactions/InvoiceCancelledTransaction.php
+++ b/app/DataMapper/Transactions/InvoiceCancelledTransaction.php
@@ -11,10 +11,6 @@
namespace App\DataMapper\Transactions;
-use App\Models\Client;
-use App\Models\Credit;
-use App\Models\Invoice;
-use App\Models\Payment;
use App\Models\TransactionEvent;
/**
diff --git a/app/DataMapper/Transactions/InvoiceDeletedTransaction.php b/app/DataMapper/Transactions/InvoiceDeletedTransaction.php
index be9dfc2a69df..503883bebab8 100644
--- a/app/DataMapper/Transactions/InvoiceDeletedTransaction.php
+++ b/app/DataMapper/Transactions/InvoiceDeletedTransaction.php
@@ -11,10 +11,6 @@
namespace App\DataMapper\Transactions;
-use App\Models\Client;
-use App\Models\Credit;
-use App\Models\Invoice;
-use App\Models\Payment;
use App\Models\TransactionEvent;
/**
diff --git a/app/DataMapper/Transactions/InvoiceFeeAppliedTransaction.php b/app/DataMapper/Transactions/InvoiceFeeAppliedTransaction.php
index 24621e21b7e3..2a02beed93b5 100644
--- a/app/DataMapper/Transactions/InvoiceFeeAppliedTransaction.php
+++ b/app/DataMapper/Transactions/InvoiceFeeAppliedTransaction.php
@@ -11,10 +11,6 @@
namespace App\DataMapper\Transactions;
-use App\Models\Client;
-use App\Models\Credit;
-use App\Models\Invoice;
-use App\Models\Payment;
use App\Models\TransactionEvent;
/**
diff --git a/app/DataMapper/Transactions/InvoicePaymentTransaction.php b/app/DataMapper/Transactions/InvoicePaymentTransaction.php
index 46f89c1ad5d8..10c22d1630f5 100644
--- a/app/DataMapper/Transactions/InvoicePaymentTransaction.php
+++ b/app/DataMapper/Transactions/InvoicePaymentTransaction.php
@@ -11,10 +11,6 @@
namespace App\DataMapper\Transactions;
-use App\Models\Client;
-use App\Models\Credit;
-use App\Models\Invoice;
-use App\Models\Payment;
use App\Models\TransactionEvent;
/**
diff --git a/app/DataMapper/Transactions/InvoiceReversalTransaction.php b/app/DataMapper/Transactions/InvoiceReversalTransaction.php
index fb32c72f3e53..9e514a3717fb 100644
--- a/app/DataMapper/Transactions/InvoiceReversalTransaction.php
+++ b/app/DataMapper/Transactions/InvoiceReversalTransaction.php
@@ -11,10 +11,6 @@
namespace App\DataMapper\Transactions;
-use App\Models\Client;
-use App\Models\Credit;
-use App\Models\Invoice;
-use App\Models\Payment;
use App\Models\TransactionEvent;
/**
diff --git a/app/DataMapper/Transactions/InvoiceUpdatedTransaction.php b/app/DataMapper/Transactions/InvoiceUpdatedTransaction.php
index efbb0798c762..48a27f5ba6de 100644
--- a/app/DataMapper/Transactions/InvoiceUpdatedTransaction.php
+++ b/app/DataMapper/Transactions/InvoiceUpdatedTransaction.php
@@ -11,10 +11,6 @@
namespace App\DataMapper\Transactions;
-use App\Models\Client;
-use App\Models\Credit;
-use App\Models\Invoice;
-use App\Models\Payment;
use App\Models\TransactionEvent;
/**
diff --git a/app/DataMapper/Transactions/MarkPaidTransaction.php b/app/DataMapper/Transactions/MarkPaidTransaction.php
index eca93175d54f..d099c0b05f1d 100644
--- a/app/DataMapper/Transactions/MarkPaidTransaction.php
+++ b/app/DataMapper/Transactions/MarkPaidTransaction.php
@@ -11,10 +11,6 @@
namespace App\DataMapper\Transactions;
-use App\Models\Client;
-use App\Models\Credit;
-use App\Models\Invoice;
-use App\Models\Payment;
use App\Models\TransactionEvent;
/**
diff --git a/app/DataMapper/Transactions/PaymentAppliedTransaction.php b/app/DataMapper/Transactions/PaymentAppliedTransaction.php
index 1291d97f8ce7..41f114f0b7c0 100644
--- a/app/DataMapper/Transactions/PaymentAppliedTransaction.php
+++ b/app/DataMapper/Transactions/PaymentAppliedTransaction.php
@@ -11,10 +11,6 @@
namespace App\DataMapper\Transactions;
-use App\Models\Client;
-use App\Models\Credit;
-use App\Models\Invoice;
-use App\Models\Payment;
use App\Models\TransactionEvent;
/**
diff --git a/app/DataMapper/Transactions/PaymentDeletedTransaction.php b/app/DataMapper/Transactions/PaymentDeletedTransaction.php
index c0f1b6964653..575bcbc0a66f 100644
--- a/app/DataMapper/Transactions/PaymentDeletedTransaction.php
+++ b/app/DataMapper/Transactions/PaymentDeletedTransaction.php
@@ -11,10 +11,6 @@
namespace App\DataMapper\Transactions;
-use App\Models\Client;
-use App\Models\Credit;
-use App\Models\Invoice;
-use App\Models\Payment;
use App\Models\TransactionEvent;
/**
diff --git a/app/DataMapper/Transactions/PaymentFailedTransaction.php b/app/DataMapper/Transactions/PaymentFailedTransaction.php
index 5152ad703187..f7ee79e5e695 100644
--- a/app/DataMapper/Transactions/PaymentFailedTransaction.php
+++ b/app/DataMapper/Transactions/PaymentFailedTransaction.php
@@ -11,10 +11,6 @@
namespace App\DataMapper\Transactions;
-use App\Models\Client;
-use App\Models\Credit;
-use App\Models\Invoice;
-use App\Models\Payment;
use App\Models\TransactionEvent;
/**
diff --git a/app/DataMapper/Transactions/PaymentMadeTransaction.php b/app/DataMapper/Transactions/PaymentMadeTransaction.php
index 3b7adf51d301..1c9688e3304d 100644
--- a/app/DataMapper/Transactions/PaymentMadeTransaction.php
+++ b/app/DataMapper/Transactions/PaymentMadeTransaction.php
@@ -11,10 +11,6 @@
namespace App\DataMapper\Transactions;
-use App\Models\Client;
-use App\Models\Credit;
-use App\Models\Invoice;
-use App\Models\Payment;
use App\Models\TransactionEvent;
/**
diff --git a/app/DataMapper/Transactions/PaymentRefundedTransaction.php b/app/DataMapper/Transactions/PaymentRefundedTransaction.php
index 2b31a45f9300..83788d6f3fc8 100644
--- a/app/DataMapper/Transactions/PaymentRefundedTransaction.php
+++ b/app/DataMapper/Transactions/PaymentRefundedTransaction.php
@@ -11,10 +11,6 @@
namespace App\DataMapper\Transactions;
-use App\Models\Client;
-use App\Models\Credit;
-use App\Models\Invoice;
-use App\Models\Payment;
use App\Models\TransactionEvent;
/**
diff --git a/app/Events/PurchaseOrder/PurchaseOrderWasAccepted.php b/app/Events/PurchaseOrder/PurchaseOrderWasAccepted.php
index 77f71e960426..004ca3830aa1 100644
--- a/app/Events/PurchaseOrder/PurchaseOrderWasAccepted.php
+++ b/app/Events/PurchaseOrder/PurchaseOrderWasAccepted.php
@@ -13,7 +13,6 @@ namespace App\Events\PurchaseOrder;
use App\Models\Company;
use App\Models\PurchaseOrder;
-use App\Models\PurchaseOrderInvitation;
use App\Models\VendorContact;
use Illuminate\Queue\SerializesModels;
diff --git a/app/Events/Subscription/SubscriptionWasCreated.php b/app/Events/Subscription/SubscriptionWasCreated.php
index 1da537bbbf1f..1aef2036b4ed 100644
--- a/app/Events/Subscription/SubscriptionWasCreated.php
+++ b/app/Events/Subscription/SubscriptionWasCreated.php
@@ -4,11 +4,8 @@ namespace App\Events\Subscription;
use App\Models\Company;
use App\Models\Subscription;
-use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
-use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
-use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
diff --git a/app/Exceptions/Handler.php b/app/Exceptions/Handler.php
index a7d534780cec..9e258dbb19f2 100644
--- a/app/Exceptions/Handler.php
+++ b/app/Exceptions/Handler.php
@@ -11,10 +11,6 @@
namespace App\Exceptions;
-use App\Exceptions\FilePermissionsFailure;
-use App\Exceptions\InternalPDFFailure;
-use App\Exceptions\PhantomPDFFailure;
-use App\Exceptions\StripeConnectFailure;
use App\Utils\Ninja;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Auth\AuthenticationException;
@@ -29,13 +25,13 @@ use Illuminate\Session\TokenMismatchException;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Schema;
use Illuminate\Validation\ValidationException;
+use League\Flysystem\UnableToCreateDirectory;
use PDOException;
use Sentry\Laravel\Integration;
use Sentry\State\Scope;
use Symfony\Component\Console\Exception\CommandNotFoundException;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
-use League\Flysystem\UnableToCreateDirectory;
use Throwable;
class Handler extends ExceptionHandler
@@ -127,7 +123,6 @@ class Handler extends ExceptionHandler
if ($this->validException($exception) && $this->sentryShouldReport($exception)) {
Integration::captureUnhandledException($exception);
}
-
} elseif (app()->bound('sentry')) {
Integration::configureScope(function (Scope $scope): void {
if (auth()->guard('contact') && auth()->guard('contact')->user() && auth()->guard('contact')->user()->company->account->report_errors) {
@@ -191,10 +186,11 @@ class Handler extends ExceptionHandler
*/
protected function sentryShouldReport(Throwable $e)
{
- if(Ninja::isHosted())
+ if (Ninja::isHosted()) {
$dontReport = array_merge($this->hostedDontReport, $this->internalDontReport);
- else
+ } else {
$dontReport = array_merge($this->selfHostDontReport, $this->internalDontReport);
+ }
return is_null(Arr::first($dontReport, fn ($type) => $e instanceof $type));
}
@@ -244,7 +240,7 @@ class Handler extends ExceptionHandler
return response()->json(['message' => $exception->getMessage()], 400);
} elseif ($exception instanceof StripeConnectFailure) {
return response()->json(['message' => $exception->getMessage()], 400);
- }
+ }
return parent::render($request, $exception);
}
@@ -258,7 +254,7 @@ class Handler extends ExceptionHandler
$guard = Arr::get($exception->guards(), 0);
switch ($guard) {
- case 'contact':
+ case 'contact':
$login = 'client.login';
break;
case 'user':
diff --git a/app/Exceptions/PaymentFailed.php b/app/Exceptions/PaymentFailed.php
index 9b2735edd08a..713dd54af13f 100644
--- a/app/Exceptions/PaymentFailed.php
+++ b/app/Exceptions/PaymentFailed.php
@@ -23,8 +23,7 @@ class PaymentFailed extends Exception
public function render($request)
{
- if (auth()->guard('contact')->user() || ($request->has('cko-session-id') && $request->query('cko-session-id') )) {
-
+ if (auth()->guard('contact')->user() || ($request->has('cko-session-id') && $request->query('cko-session-id'))) {
return render('gateways.unsuccessful', [
'message' => $this->getMessage(),
'code' => $this->getCode(),
diff --git a/app/Exceptions/PaymentRefundFailed.php b/app/Exceptions/PaymentRefundFailed.php
index bb273ba25973..4aa2c4487c66 100644
--- a/app/Exceptions/PaymentRefundFailed.php
+++ b/app/Exceptions/PaymentRefundFailed.php
@@ -36,7 +36,6 @@ class PaymentRefundFailed extends Exception
*/
public function render($request)
{
-
// $msg = 'Unable to refund the transaction';
$msg = ctrans('texts.warning_local_refund');
diff --git a/app/Exceptions/YodleeApiException.php b/app/Exceptions/YodleeApiException.php
index c8a2e224f135..177be9ae1834 100644
--- a/app/Exceptions/YodleeApiException.php
+++ b/app/Exceptions/YodleeApiException.php
@@ -36,7 +36,6 @@ class YodleeApiException extends Exception
*/
public function render($request)
{
-
// $msg = 'Unable to refund the transaction';
$msg = ctrans('texts.error');
diff --git a/app/Export/CSV/BaseExport.php b/app/Export/CSV/BaseExport.php
index ea562d76c47a..96990889b935 100644
--- a/app/Export/CSV/BaseExport.php
+++ b/app/Export/CSV/BaseExport.php
@@ -32,7 +32,6 @@ class BaseExport
}
switch ($date_range) {
-
case 'all':
return $query;
case 'last7':
@@ -53,7 +52,6 @@ class BaseExport
return $query->whereBetween($this->date_key, [$custom_start_date, $custom_end_date])->orderBy($this->date_key, 'ASC');
default:
return $query->whereBetween($this->date_key, [now()->startOfYear(), now()])->orderBy($this->date_key, 'ASC');
-
}
}
diff --git a/app/Export/CSV/ClientExport.php b/app/Export/CSV/ClientExport.php
index e0504a6c340b..772c0152e7e5 100644
--- a/app/Export/CSV/ClientExport.php
+++ b/app/Export/CSV/ClientExport.php
@@ -17,7 +17,6 @@ use App\Models\Company;
use App\Transformers\ClientContactTransformer;
use App\Transformers\ClientTransformer;
use App\Utils\Ninja;
-use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\App;
use League\Csv\Writer;
@@ -181,11 +180,13 @@ class ClientExport extends BaseExport
private function calculateStatus($client)
{
- if($client->is_deleted)
+ if ($client->is_deleted) {
return ctrans('texts.deleted');
+ }
- if($client->deleted_at)
+ if ($client->deleted_at) {
return ctrans('texts.arcvived');
+ }
return ctrans('texts.active');
}
diff --git a/app/Export/CSV/CreditExport.php b/app/Export/CSV/CreditExport.php
index 82dff6795a19..a612810863d3 100644
--- a/app/Export/CSV/CreditExport.php
+++ b/app/Export/CSV/CreditExport.php
@@ -12,7 +12,6 @@
namespace App\Export\CSV;
use App\Libraries\MultiDB;
-use App\Models\Client;
use App\Models\Company;
use App\Models\Credit;
use App\Transformers\CreditTransformer;
diff --git a/app/Export/CSV/DocumentExport.php b/app/Export/CSV/DocumentExport.php
index c9167ef1561f..891a4499b227 100644
--- a/app/Export/CSV/DocumentExport.php
+++ b/app/Export/CSV/DocumentExport.php
@@ -12,9 +12,7 @@
namespace App\Export\CSV;
use App\Libraries\MultiDB;
-use App\Models\Client;
use App\Models\Company;
-use App\Models\Credit;
use App\Models\Document;
use App\Transformers\DocumentTransformer;
use App\Utils\Ninja;
diff --git a/app/Export/CSV/ExpenseExport.php b/app/Export/CSV/ExpenseExport.php
index dced738d742c..de7e2dc19652 100644
--- a/app/Export/CSV/ExpenseExport.php
+++ b/app/Export/CSV/ExpenseExport.php
@@ -12,7 +12,6 @@
namespace App\Export\CSV;
use App\Libraries\MultiDB;
-use App\Models\Client;
use App\Models\Company;
use App\Models\Expense;
use App\Transformers\ExpenseTransformer;
diff --git a/app/Export/CSV/InvoiceExport.php b/app/Export/CSV/InvoiceExport.php
index 492cb6d998a4..464ede3f1f05 100644
--- a/app/Export/CSV/InvoiceExport.php
+++ b/app/Export/CSV/InvoiceExport.php
@@ -12,7 +12,6 @@
namespace App\Export\CSV;
use App\Libraries\MultiDB;
-use App\Models\Client;
use App\Models\Company;
use App\Models\Invoice;
use App\Transformers\InvoiceTransformer;
diff --git a/app/Export/CSV/InvoiceItemExport.php b/app/Export/CSV/InvoiceItemExport.php
index 7404a1714fb4..501b4e31a613 100644
--- a/app/Export/CSV/InvoiceItemExport.php
+++ b/app/Export/CSV/InvoiceItemExport.php
@@ -100,7 +100,6 @@ class InvoiceItemExport extends BaseExport
public function run()
{
-
MultiDB::setDb($this->company->db);
App::forgetInstance('translator');
App::setLocale($this->company->locale());
@@ -110,8 +109,9 @@ class InvoiceItemExport extends BaseExport
//load the CSV document from a string
$this->csv = Writer::createFromString();
- if(count($this->input['report_keys']) == 0)
+ if (count($this->input['report_keys']) == 0) {
$this->input['report_keys'] = array_values($this->entity_keys);
+ }
//insert the header
$this->csv->insertOne($this->buildHeader());
@@ -119,19 +119,16 @@ class InvoiceItemExport extends BaseExport
$query = Invoice::query()
->withTrashed()
->with('client')->where('company_id', $this->company->id)
- ->where('is_deleted',0);
+ ->where('is_deleted', 0);
$query = $this->addDateRange($query);
$query->cursor()
- ->each(function ($invoice){
-
+ ->each(function ($invoice) {
$this->iterateItems($invoice);
+ });
- });
-
- return $this->csv->toString();
-
+ return $this->csv->toString();
}
private function iterateItems(Invoice $invoice)
@@ -140,81 +137,71 @@ class InvoiceItemExport extends BaseExport
$transformed_items = [];
- foreach($invoice->line_items as $item)
- {
+ foreach ($invoice->line_items as $item) {
$item_array = [];
- foreach(array_values($this->input['report_keys']) as $key){
-
- if(str_contains($key, "item.")){
-
+ foreach (array_values($this->input['report_keys']) as $key) {
+ if (str_contains($key, "item.")) {
$key = str_replace("item.", "", $key);
- if(property_exists($item, $key))
+ if (property_exists($item, $key)) {
$item_array[$key] = $item->{$key};
- else
+ } else {
$item_array[$key] = '';
-
+ }
}
-
}
$entity = [];
- foreach(array_values($this->input['report_keys']) as $key)
- {
+ foreach (array_values($this->input['report_keys']) as $key) {
$keyval = array_search($key, $this->entity_keys);
- if(array_key_exists($key, $transformed_items))
+ if (array_key_exists($key, $transformed_items)) {
$entity[$keyval] = $transformed_items[$key];
- else
+ } else {
$entity[$keyval] = "";
-
+ }
}
$transformed_items = array_merge($transformed_invoice, $item_array);
$entity = $this->decorateAdvancedFields($invoice, $transformed_items);
- $this->csv->insertOne($entity);
-
+ $this->csv->insertOne($entity);
}
-
}
private function buildRow(Invoice $invoice) :array
{
-
$transformed_invoice = $this->invoice_transformer->transform($invoice);
$entity = [];
- foreach(array_values($this->input['report_keys']) as $key){
-
+ foreach (array_values($this->input['report_keys']) as $key) {
$keyval = array_search($key, $this->entity_keys);
- if(array_key_exists($key, $transformed_invoice))
+ if (array_key_exists($key, $transformed_invoice)) {
$entity[$keyval] = $transformed_invoice[$key];
- else
+ } else {
$entity[$keyval] = "";
-
+ }
}
return $this->decorateAdvancedFields($invoice, $entity);
-
}
private function decorateAdvancedFields(Invoice $invoice, array $entity) :array
{
- if(in_array('currency_id', $this->input['report_keys']))
+ if (in_array('currency_id', $this->input['report_keys'])) {
$entity['currency'] = $invoice->client->currency() ? $invoice->client->currency()->code : $invoice->company->currency()->code;
+ }
// if(in_array('client_id', $this->input['report_keys']))
- $entity['client'] = $invoice->client->present()->name();
+ $entity['client'] = $invoice->client->present()->name();
// if(in_array('status_id', $this->input['report_keys']))
- $entity['status'] = $invoice->stringStatus($invoice->status_id);
+ $entity['status'] = $invoice->stringStatus($invoice->status_id);
return $entity;
}
-
}
diff --git a/app/Export/CSV/PaymentExport.php b/app/Export/CSV/PaymentExport.php
index 878db42df229..22e838e4164d 100644
--- a/app/Export/CSV/PaymentExport.php
+++ b/app/Export/CSV/PaymentExport.php
@@ -12,9 +12,7 @@
namespace App\Export\CSV;
use App\Libraries\MultiDB;
-use App\Models\Client;
use App\Models\Company;
-use App\Models\Credit;
use App\Models\Document;
use App\Models\Payment;
use App\Transformers\PaymentTransformer;
diff --git a/app/Export/CSV/ProductExport.php b/app/Export/CSV/ProductExport.php
index ba3afc73dcce..a210df2260a3 100644
--- a/app/Export/CSV/ProductExport.php
+++ b/app/Export/CSV/ProductExport.php
@@ -12,9 +12,7 @@
namespace App\Export\CSV;
use App\Libraries\MultiDB;
-use App\Models\Client;
use App\Models\Company;
-use App\Models\Credit;
use App\Models\Document;
use App\Models\Product;
use App\Transformers\ProductTransformer;
diff --git a/app/Export/CSV/ProductSalesExport.php b/app/Export/CSV/ProductSalesExport.php
index 1fdfb7362872..505d0b72ba61 100644
--- a/app/Export/CSV/ProductSalesExport.php
+++ b/app/Export/CSV/ProductSalesExport.php
@@ -12,17 +12,13 @@
namespace App\Export\CSV;
use App\Libraries\MultiDB;
-use App\Models\Client;
use App\Models\Company;
-use App\Models\Credit;
use App\Models\Document;
use App\Models\Invoice;
-use App\Models\Product;
-use App\Transformers\ProductTransformer;
use App\Utils\Ninja;
+use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\App;
use League\Csv\Writer;
-use Illuminate\Support\Carbon;
class ProductSalesExport extends BaseExport
{
@@ -98,10 +94,9 @@ class ProductSalesExport extends BaseExport
$query->cursor()
->each(function ($invoice) {
-
- foreach($invoice->line_items as $item)
- $this->csv->insertOne($this->buildRow($invoice, $item));
-
+ foreach ($invoice->line_items as $item) {
+ $this->csv->insertOne($this->buildRow($invoice, $item));
+ }
});
return $this->csv->toString();
diff --git a/app/Export/CSV/QuoteExport.php b/app/Export/CSV/QuoteExport.php
index 482b9d685d17..72bee3d23515 100644
--- a/app/Export/CSV/QuoteExport.php
+++ b/app/Export/CSV/QuoteExport.php
@@ -12,7 +12,6 @@
namespace App\Export\CSV;
use App\Libraries\MultiDB;
-use App\Models\Client;
use App\Models\Company;
use App\Models\Quote;
use App\Transformers\QuoteTransformer;
diff --git a/app/Export/CSV/QuoteItemExport.php b/app/Export/CSV/QuoteItemExport.php
index 6e4ea48bcdf3..e8baeecedcd0 100644
--- a/app/Export/CSV/QuoteItemExport.php
+++ b/app/Export/CSV/QuoteItemExport.php
@@ -12,7 +12,6 @@
namespace App\Export\CSV;
use App\Libraries\MultiDB;
-use App\Models\Client;
use App\Models\Company;
use App\Models\Quote;
use App\Transformers\QuoteTransformer;
diff --git a/app/Export/CSV/RecurringInvoiceExport.php b/app/Export/CSV/RecurringInvoiceExport.php
index 7fe5664c34d1..aaf4565caceb 100644
--- a/app/Export/CSV/RecurringInvoiceExport.php
+++ b/app/Export/CSV/RecurringInvoiceExport.php
@@ -12,7 +12,6 @@
namespace App\Export\CSV;
use App\Libraries\MultiDB;
-use App\Models\Client;
use App\Models\Company;
use App\Models\RecurringInvoice;
use App\Transformers\RecurringInvoiceTransformer;
diff --git a/app/Export/CSV/TaskExport.php b/app/Export/CSV/TaskExport.php
index b91445687ea8..095fcd498537 100644
--- a/app/Export/CSV/TaskExport.php
+++ b/app/Export/CSV/TaskExport.php
@@ -12,7 +12,6 @@
namespace App\Export\CSV;
use App\Libraries\MultiDB;
-use App\Models\Client;
use App\Models\Company;
use App\Models\DateFormat;
use App\Models\Task;
diff --git a/app/Factory/BankIntegrationFactory.php b/app/Factory/BankIntegrationFactory.php
index a4918feccd5e..e49934c5a6dd 100644
--- a/app/Factory/BankIntegrationFactory.php
+++ b/app/Factory/BankIntegrationFactory.php
@@ -12,7 +12,6 @@
namespace App\Factory;
use App\Models\BankIntegration;
-use Illuminate\Support\Str;
class BankIntegrationFactory
{
diff --git a/app/Factory/BankTransactionFactory.php b/app/Factory/BankTransactionFactory.php
index 8355a83a24cd..3760d1bc40f7 100644
--- a/app/Factory/BankTransactionFactory.php
+++ b/app/Factory/BankTransactionFactory.php
@@ -12,7 +12,6 @@
namespace App\Factory;
use App\Models\BankTransaction;
-use Illuminate\Support\Str;
class BankTransactionFactory
{
diff --git a/app/Factory/BankTransactionRuleFactory.php b/app/Factory/BankTransactionRuleFactory.php
index 360ee32e1ab3..7bb2199b4d97 100644
--- a/app/Factory/BankTransactionRuleFactory.php
+++ b/app/Factory/BankTransactionRuleFactory.php
@@ -12,7 +12,6 @@
namespace App\Factory;
use App\Models\BankTransactionRule;
-use Illuminate\Support\Str;
class BankTransactionRuleFactory
{
diff --git a/app/Factory/ClientGatewayTokenFactory.php b/app/Factory/ClientGatewayTokenFactory.php
index 2fdd96ca5d60..be343a280737 100644
--- a/app/Factory/ClientGatewayTokenFactory.php
+++ b/app/Factory/ClientGatewayTokenFactory.php
@@ -12,7 +12,6 @@
namespace App\Factory;
use App\Models\ClientGatewayToken;
-use Illuminate\Support\Str;
class ClientGatewayTokenFactory
{
diff --git a/app/Factory/CompanyGatewayFactory.php b/app/Factory/CompanyGatewayFactory.php
index 8046399aff67..952054ed4383 100644
--- a/app/Factory/CompanyGatewayFactory.php
+++ b/app/Factory/CompanyGatewayFactory.php
@@ -11,7 +11,6 @@
namespace App\Factory;
-use App\DataMapper\FeesAndLimits;
use App\Models\CompanyGateway;
class CompanyGatewayFactory
diff --git a/app/Factory/PurchaseOrderFactory.php b/app/Factory/PurchaseOrderFactory.php
index df5908486215..31a082ac83b7 100644
--- a/app/Factory/PurchaseOrderFactory.php
+++ b/app/Factory/PurchaseOrderFactory.php
@@ -13,7 +13,6 @@ namespace App\Factory;
use App\Models\Client;
use App\Models\PurchaseOrder;
-use Illuminate\Database\Eloquent\Model;
class PurchaseOrderFactory
{
diff --git a/app/Factory/PurchaseOrderInvitationFactory.php b/app/Factory/PurchaseOrderInvitationFactory.php
index 8d354d244c8e..59371726cc53 100644
--- a/app/Factory/PurchaseOrderInvitationFactory.php
+++ b/app/Factory/PurchaseOrderInvitationFactory.php
@@ -3,7 +3,6 @@
namespace App\Factory;
use App\Models\PurchaseOrderInvitation;
-use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
class PurchaseOrderInvitationFactory
diff --git a/app/Factory/RecurringExpenseToExpenseFactory.php b/app/Factory/RecurringExpenseToExpenseFactory.php
index eb527dfc5795..1fc9626aa72e 100644
--- a/app/Factory/RecurringExpenseToExpenseFactory.php
+++ b/app/Factory/RecurringExpenseToExpenseFactory.php
@@ -13,7 +13,6 @@ namespace App\Factory;
use App\Models\Expense;
use App\Models\RecurringExpense;
-use App\Utils\Helpers;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;
@@ -175,7 +174,10 @@ class RecurringExpenseToExpenseFactory
$replacement = sprintf('%s to %s', $_left, $_right);
$value = preg_replace(
- sprintf('/%s/', preg_quote($match)), $replacement, $value, 1
+ sprintf('/%s/', preg_quote($match)),
+ $replacement,
+ $value,
+ 1
);
}
}
@@ -196,7 +198,10 @@ class RecurringExpenseToExpenseFactory
if (! Str::contains($match, ['-', '+', '/', '*'])) {
$value = preg_replace(
- sprintf('/%s/', $matches->keys()->first()), $replacements['literal'][$matches->keys()->first()], $value, 1
+ sprintf('/%s/', $matches->keys()->first()),
+ $replacements['literal'][$matches->keys()->first()],
+ $value,
+ 1
);
}
@@ -236,7 +241,10 @@ class RecurringExpenseToExpenseFactory
}
$value = preg_replace(
- $target, $output, $value, 1
+ $target,
+ $output,
+ $value,
+ 1
);
}
}
diff --git a/app/Factory/UserFactory.php b/app/Factory/UserFactory.php
index 593cc98b2af0..d31a0019b2c9 100644
--- a/app/Factory/UserFactory.php
+++ b/app/Factory/UserFactory.php
@@ -11,7 +11,6 @@
namespace App\Factory;
-use App\Models\CompanyUser;
use App\Models\User;
class UserFactory
diff --git a/app/Filters/BankIntegrationFilters.php b/app/Filters/BankIntegrationFilters.php
index 1932b0995dba..c1340b6f2651 100644
--- a/app/Filters/BankIntegrationFilters.php
+++ b/app/Filters/BankIntegrationFilters.php
@@ -49,7 +49,6 @@ class BankIntegrationFilters extends QueryFilters
return $this->builder->where(function ($query) use ($filter) {
$query->where('bank_account_name', 'like', '%'.$filter.'%');
});
-
}
/**
@@ -68,7 +67,6 @@ class BankIntegrationFilters extends QueryFilters
$filters = explode(',', $filter);
return $this->builder->where(function ($query) use ($filters) {
-
if (in_array(parent::STATUS_ACTIVE, $filters)) {
$query->orWhereNull('deleted_at');
}
diff --git a/app/Filters/BankTransactionFilters.php b/app/Filters/BankTransactionFilters.php
index 4830277be8aa..a1aab569020c 100644
--- a/app/Filters/BankTransactionFilters.php
+++ b/app/Filters/BankTransactionFilters.php
@@ -50,7 +50,6 @@ class BankTransactionFilters extends QueryFilters
return $this->builder->where(function ($query) use ($filter) {
$query->where('bank_transactions.description', 'like', '%'.$filter.'%');
});
-
}
@@ -79,8 +78,7 @@ class BankTransactionFilters extends QueryFilters
return $this->builder;
}
- $this->builder->where(function ($query) use ($status_parameters){
-
+ $this->builder->where(function ($query) use ($status_parameters) {
$status_array = [];
$debit_or_withdrawal_array = [];
@@ -105,14 +103,13 @@ class BankTransactionFilters extends QueryFilters
$debit_or_withdrawal_array[] = 'DEBIT';
}
- if(count($status_array) >=1) {
+ if (count($status_array) >=1) {
$query->whereIn('status_id', $status_array);
}
- if(count($debit_or_withdrawal_array) >=1) {
+ if (count($debit_or_withdrawal_array) >=1) {
$query->orWhereIn('base_type', $debit_or_withdrawal_array);
}
-
});
return $this->builder;
@@ -132,17 +129,21 @@ class BankTransactionFilters extends QueryFilters
return $this->builder;
}
- if($sort_col[0] == 'deposit')
+ if ($sort_col[0] == 'deposit') {
return $this->builder->where('base_type', 'CREDIT')->orderBy('amount', $sort_col[1]);
+ }
- if($sort_col[0] == 'withdrawal')
+ if ($sort_col[0] == 'withdrawal') {
return $this->builder->where('base_type', 'DEBIT')->orderBy('amount', $sort_col[1]);
+ }
- if($sort_col[0] == 'status')
+ if ($sort_col[0] == 'status') {
$sort_col[0] = 'status_id';
+ }
- if(in_array($sort_col[0],['invoices','expense']))
+ if (in_array($sort_col[0], ['invoices','expense'])) {
return $this->builder;
+ }
return $this->builder->orderBy($sort_col[0], $sort_col[1]);
}
diff --git a/app/Filters/BankTransactionRuleFilters.php b/app/Filters/BankTransactionRuleFilters.php
index be79cb58fe4a..ee8496f579b5 100644
--- a/app/Filters/BankTransactionRuleFilters.php
+++ b/app/Filters/BankTransactionRuleFilters.php
@@ -49,7 +49,6 @@ class BankTransactionRuleFilters extends QueryFilters
return $this->builder->where(function ($query) use ($filter) {
$query->where('bank_transaction_rules.name', 'like', '%'.$filter.'%');
});
-
}
/**
diff --git a/app/Filters/ClientFilters.php b/app/Filters/ClientFilters.php
index 0c3b86bec946..c2b23f0ad28f 100644
--- a/app/Filters/ClientFilters.php
+++ b/app/Filters/ClientFilters.php
@@ -147,8 +147,9 @@ class ClientFilters extends QueryFilters
return $this->builder;
}
- if($sort_col[0] == 'display_name')
+ if ($sort_col[0] == 'display_name') {
$sort_col[0] = 'name';
+ }
return $this->builder->orderBy($sort_col[0], $sort_col[1]);
}
@@ -165,11 +166,10 @@ class ClientFilters extends QueryFilters
public function filter_details(string $filter = '')
{
-
- if($filter == 'true')
+ if ($filter == 'true') {
return $this->builder->select('id', 'name', 'number', 'id_number');
+ }
return $this->builder;
-
}
}
diff --git a/app/Filters/CreditFilters.php b/app/Filters/CreditFilters.php
index b95e18b1433f..7fa39b281c21 100644
--- a/app/Filters/CreditFilters.php
+++ b/app/Filters/CreditFilters.php
@@ -44,17 +44,21 @@ class CreditFilters extends QueryFilters
$credit_filters = [];
- if (in_array('draft', $status_parameters))
+ if (in_array('draft', $status_parameters)) {
$credit_filters[] = Credit::STATUS_DRAFT;
+ }
- if (in_array('partial', $status_parameters))
+ if (in_array('partial', $status_parameters)) {
$credit_filters[] = Credit::STATUS_PARTIAL;
+ }
- if (in_array('applied', $status_parameters))
+ if (in_array('applied', $status_parameters)) {
$credit_filters[] = Credit::STATUS_APPLIED;
+ }
- if(count($credit_filters) >=1)
+ if (count($credit_filters) >=1) {
$this->builder->whereIn('status_id', $credit_filters);
+ }
return $this->builder;
}
diff --git a/app/Filters/DesignFilters.php b/app/Filters/DesignFilters.php
index e19707ff062d..d44cc2995147 100644
--- a/app/Filters/DesignFilters.php
+++ b/app/Filters/DesignFilters.php
@@ -23,7 +23,7 @@ class DesignFilters extends QueryFilters
*
* @param string query filter
* @return Builder
- *
+ *
* @deprecated
*/
public function filter(string $filter = ''): Builder
@@ -41,7 +41,7 @@ class DesignFilters extends QueryFilters
* Sorts the list based on $sort.
*
* @param string sort formatted as column|asc
- *
+ *
* @return Builder
*/
public function sort(string $sort = ''): Builder
@@ -62,6 +62,6 @@ class DesignFilters extends QueryFilters
*/
public function entityFilter(): Builder
{
- return $this->builder->where('company_id', auth()->user()->company()->id)->orWhere('company_id', null)->orderBy('id','asc');
+ return $this->builder->where('company_id', auth()->user()->company()->id)->orWhere('company_id', null)->orderBy('id', 'asc');
}
}
diff --git a/app/Filters/DocumentFilters.php b/app/Filters/DocumentFilters.php
index 0391c10aff0f..1b312161ab84 100644
--- a/app/Filters/DocumentFilters.php
+++ b/app/Filters/DocumentFilters.php
@@ -39,10 +39,10 @@ class DocumentFilters extends QueryFilters
* Overriding method as client_id does
* not exist on this model, just pass
* back the builder
- *
+ *
* @param string $client_id The client hashed id.
- *
- * @return Builder
+ *
+ * @return Builder
*/
public function client_id(string $client_id = ''): Builder
{
@@ -69,8 +69,9 @@ class DocumentFilters extends QueryFilters
public function company_documents($value = 'false')
{
- if($value == 'true')
+ if ($value == 'true') {
return $this->builder->where('documentable_type', Company::class);
+ }
return $this->builder;
}
diff --git a/app/Filters/ExpenseCategoryFilters.php b/app/Filters/ExpenseCategoryFilters.php
index 3ed24beac66a..b25ad4d282e9 100644
--- a/app/Filters/ExpenseCategoryFilters.php
+++ b/app/Filters/ExpenseCategoryFilters.php
@@ -32,7 +32,6 @@ class ExpenseCategoryFilters extends QueryFilters
}
return $this->builder->where('name', 'like', '%'.$filter.'%');
-
}
/**
@@ -49,8 +48,9 @@ class ExpenseCategoryFilters extends QueryFilters
return $this->builder;
}
- if (is_array($sort_col) && in_array($sort_col[1], ['asc', 'desc']) && in_array($sort_col[0], ['name']))
+ if (is_array($sort_col) && in_array($sort_col[1], ['asc', 'desc']) && in_array($sort_col[0], ['name'])) {
return $this->builder->orderBy($sort_col[0], $sort_col[1]);
+ }
return $this->builder;
diff --git a/app/Filters/ExpenseFilters.php b/app/Filters/ExpenseFilters.php
index e04cc216e93d..0ff6e69035a8 100644
--- a/app/Filters/ExpenseFilters.php
+++ b/app/Filters/ExpenseFilters.php
@@ -65,52 +65,40 @@ class ExpenseFilters extends QueryFilters
return $this->builder;
}
- $this->builder->where(function ($query) use($status_parameters){
-
+ $this->builder->where(function ($query) use ($status_parameters) {
if (in_array('logged', $status_parameters)) {
-
- $query->orWhere(function ($query){
+ $query->orWhere(function ($query) {
$query->where('amount', '>', 0)
->whereNull('invoice_id')
->whereNull('payment_date')
- ->where('should_be_invoiced',false);
+ ->where('should_be_invoiced', false);
});
-
}
if (in_array('pending', $status_parameters)) {
-
- $query->orWhere(function ($query){
- $query->where('should_be_invoiced',true)
+ $query->orWhere(function ($query) {
+ $query->where('should_be_invoiced', true)
->whereNull('invoice_id');
});
-
}
if (in_array('invoiced', $status_parameters)) {
-
- $query->orWhere(function ($query){
+ $query->orWhere(function ($query) {
$query->whereNotNull('invoice_id');
});
-
}
if (in_array('paid', $status_parameters)) {
-
- $query->orWhere(function ($query){
+ $query->orWhere(function ($query) {
$query->whereNotNull('payment_date');
});
-
}
if (in_array('unpaid', $status_parameters)) {
-
- $query->orWhere(function ($query){
+ $query->orWhere(function ($query) {
$query->whereNull('payment_date');
});
-
}
-
});
// nlog($this->builder->toSql());
@@ -123,10 +111,8 @@ class ExpenseFilters extends QueryFilters
*/
public function match_transactions($value = '')
{
-
- if($value == 'true')
- {
- return $this->builder->where('is_deleted',0)->whereNull('transaction_id');
+ if ($value == 'true') {
+ return $this->builder->where('is_deleted', 0)->whereNull('transaction_id');
}
return $this->builder;
diff --git a/app/Filters/InvoiceFilters.php b/app/Filters/InvoiceFilters.php
index 55d2d2097fcb..6ae3da8e6f66 100644
--- a/app/Filters/InvoiceFilters.php
+++ b/app/Filters/InvoiceFilters.php
@@ -50,8 +50,7 @@ class InvoiceFilters extends QueryFilters
return $this->builder;
}
- $this->builder->where(function ($query) use($status_parameters){
-
+ $this->builder->where(function ($query) use ($status_parameters) {
$invoice_filters = [];
if (in_array('paid', $status_parameters)) {
@@ -63,7 +62,7 @@ class InvoiceFilters extends QueryFilters
$invoice_filters[] = Invoice::STATUS_PARTIAL;
}
- if(count($invoice_filters) >0){
+ if (count($invoice_filters) >0) {
$query->whereIn('status_id', $invoice_filters);
}
@@ -79,8 +78,9 @@ class InvoiceFilters extends QueryFilters
public function number(string $number = ''): Builder
{
- if(strlen($number) == 0)
+ if (strlen($number) == 0) {
return $this->builder;
+ }
return $this->builder->where('number', $number);
}
@@ -112,20 +112,19 @@ class InvoiceFilters extends QueryFilters
}
/**
- * @return Builder
- * @throws RuntimeException
+ * @return Builder
+ * @throws RuntimeException
*/
public function without_deleted_clients(): Builder
{
-
return $this->builder->whereHas('client', function ($query) {
- $query->where('is_deleted',0);
- });
+ $query->where('is_deleted', 0);
+ });
}
/**
- * @return Builder
- * @throws InvalidArgumentException
+ * @return Builder
+ * @throws InvalidArgumentException
*/
public function upcoming(): Builder
{
@@ -138,8 +137,8 @@ class InvoiceFilters extends QueryFilters
}
/**
- * @return void
- * @throws InvalidArgumentException
+ * @return void
+ * @throws InvalidArgumentException
*/
public function overdue(): Builder
{
@@ -153,9 +152,9 @@ class InvoiceFilters extends QueryFilters
}
/**
- * @param string $client_id
- * @return Builder
- * @throws InvalidArgumentException
+ * @param string $client_id
+ * @return Builder
+ * @throws InvalidArgumentException
*/
public function payable(string $client_id = ''): Builder
{
@@ -198,15 +197,15 @@ class InvoiceFilters extends QueryFilters
{
if (auth()->guard('contact')->user()) {
return $this->contactViewFilter();
- } else {
+ } else {
return $this->builder->company()->with(['invitations.company'], ['documents.company']);
}
}
/**
- * @param string $filter
- * @return Builder
- * @throws InvalidArgumentException
+ * @param string $filter
+ * @return Builder
+ * @throws InvalidArgumentException
*/
public function private_notes($filter = '') :Builder
{
diff --git a/app/Filters/PaymentFilters.php b/app/Filters/PaymentFilters.php
index f3c21072d1ef..c4ef5d9370a1 100644
--- a/app/Filters/PaymentFilters.php
+++ b/app/Filters/PaymentFilters.php
@@ -46,17 +46,14 @@ class PaymentFilters extends QueryFilters
*/
public function match_transactions($value = 'true'): Builder
{
-
- if($value == 'true'){
-
+ if ($value == 'true') {
return $this->builder
- ->where('is_deleted',0)
- ->where(function ($query){
+ ->where('is_deleted', 0)
+ ->where(function ($query) {
$query->whereNull('transaction_id')
- ->orWhere("transaction_id","")
+ ->orWhere("transaction_id", "")
->company();
});
-
}
return $this->builder;
diff --git a/app/Filters/ProjectFilters.php b/app/Filters/ProjectFilters.php
index c1545464480d..bcb6d1f0a260 100644
--- a/app/Filters/ProjectFilters.php
+++ b/app/Filters/ProjectFilters.php
@@ -61,8 +61,9 @@ class ProjectFilters extends QueryFilters
return $this->builder;
}
- if(is_array($sort_col))
+ if (is_array($sort_col)) {
return $this->builder->orderBy($sort_col[0], $sort_col[1]);
+ }
}
/**
diff --git a/app/Filters/PurchaseOrderFilters.php b/app/Filters/PurchaseOrderFilters.php
index 7fb0c759490c..a3ef1709c6f4 100644
--- a/app/Filters/PurchaseOrderFilters.php
+++ b/app/Filters/PurchaseOrderFilters.php
@@ -16,7 +16,6 @@ use Illuminate\Database\Eloquent\Builder;
class PurchaseOrderFilters extends QueryFilters
{
-
/**
* Filter based on client status.
*
@@ -41,8 +40,7 @@ class PurchaseOrderFilters extends QueryFilters
return $this->builder;
}
- $this->builder->where(function ($query) use ($status_parameters){
-
+ $this->builder->where(function ($query) use ($status_parameters) {
$po_status = [];
if (in_array('draft', $status_parameters)) {
@@ -50,12 +48,11 @@ class PurchaseOrderFilters extends QueryFilters
}
if (in_array('sent', $status_parameters)) {
- $query->orWhere(function ($q){
- $q->where('status_id', PurchaseOrder::STATUS_SENT)
- ->whereNull('due_date')
- ->orWhere('due_date', '>=', now()->toDateString());
- });
-
+ $query->orWhere(function ($q) {
+ $q->where('status_id', PurchaseOrder::STATUS_SENT)
+ ->whereNull('due_date')
+ ->orWhere('due_date', '>=', now()->toDateString());
+ });
}
if (in_array('accepted', $status_parameters)) {
@@ -66,7 +63,7 @@ class PurchaseOrderFilters extends QueryFilters
$po_status[] = PurchaseOrder::STATUS_CANCELLED;
}
- if(count($status_parameters) >=1) {
+ if (count($status_parameters) >=1) {
$query->whereIn('status_id', $status_parameters);
}
});
diff --git a/app/Filters/QueryFilters.php b/app/Filters/QueryFilters.php
index db25717050b0..a9924bca1225 100644
--- a/app/Filters/QueryFilters.php
+++ b/app/Filters/QueryFilters.php
@@ -55,7 +55,7 @@ abstract class QueryFilters
/**
* The "with" filter property column.
- *
+ *
* var string
*/
protected $with_property = 'id';
@@ -151,7 +151,7 @@ abstract class QueryFilters
if (in_array(self::STATUS_ARCHIVED, $filters)) {
$query->orWhere(function ($query) {
- $query->whereNotNull('deleted_at')->where('is_deleted',0);
+ $query->whereNotNull('deleted_at')->where('is_deleted', 0);
});
}
@@ -188,7 +188,6 @@ abstract class QueryFilters
default:
return '=';
break;
-
}
}
@@ -208,38 +207,30 @@ abstract class QueryFilters
public function created_at($value = '')
{
-
- if($value == '')
+ if ($value == '') {
return $this->builder;
+ }
- try{
-
- if(is_numeric($value)){
+ try {
+ if (is_numeric($value)) {
$created_at = Carbon::createFromTimestamp((int)$value);
- }
- else{
+ } else {
$created_at = Carbon::parse($value);
}
return $this->builder->where('created_at', '>=', $created_at);
-
- }
- catch(\Exception $e) {
-
+ } catch(\Exception $e) {
return $this->builder;
-
}
-
}
public function updated_at($value = '')
{
-
- if ($value == '')
+ if ($value == '') {
return $this->builder;
+ }
try {
-
if (is_numeric($value)) {
$created_at = Carbon::createFromTimestamp((int)$value);
} else {
@@ -248,7 +239,6 @@ abstract class QueryFilters
return $this->builder->where('updated_at', '>=', $created_at);
} catch (\Exception $e) {
-
return $this->builder;
}
}
diff --git a/app/Filters/QuoteFilters.php b/app/Filters/QuoteFilters.php
index 23bb09ba8cb7..ca011386d944 100644
--- a/app/Filters/QuoteFilters.php
+++ b/app/Filters/QuoteFilters.php
@@ -65,14 +65,13 @@ class QuoteFilters extends QueryFilters
return $this->builder;
}
- $this->builder->where(function ($query) use ($status_parameters){
-
+ $this->builder->where(function ($query) use ($status_parameters) {
if (in_array('sent', $status_parameters)) {
- $query->orWhere(function ($q){
- $q->where('status_id', Quote::STATUS_SENT)
- ->whereNull('due_date')
- ->orWhere('due_date', '>=', now()->toDateString());
- });
+ $query->orWhere(function ($q) {
+ $q->where('status_id', Quote::STATUS_SENT)
+ ->whereNull('due_date')
+ ->orWhere('due_date', '>=', now()->toDateString());
+ });
}
$quote_filters = [];
@@ -86,26 +85,25 @@ class QuoteFilters extends QueryFilters
$quote_filters[] = Quote::STATUS_APPROVED;
}
- if(count($quote_filters) >0){
+ if (count($quote_filters) >0) {
$query->orWhereIn('status_id', $quote_filters);
}
if (in_array('expired', $status_parameters)) {
- $query->orWhere(function ($q){
- $q->where('status_id', Quote::STATUS_SENT)
- ->whereNotNull('due_date')
- ->where('due_date', '<=', now()->toDateString());
- });
+ $query->orWhere(function ($q) {
+ $q->where('status_id', Quote::STATUS_SENT)
+ ->whereNotNull('due_date')
+ ->where('due_date', '<=', now()->toDateString());
+ });
}
if (in_array('upcoming', $status_parameters)) {
- $query->orWhere(function ($q){
- $q->where('status_id', Quote::STATUS_SENT)
- ->where('due_date', '>=', now()->toDateString())
- ->orderBy('due_date', 'DESC');
- });
+ $query->orWhere(function ($q) {
+ $q->where('status_id', Quote::STATUS_SENT)
+ ->where('due_date', '>=', now()->toDateString())
+ ->orderBy('due_date', 'DESC');
+ });
}
-
});
return $this->builder;
@@ -134,8 +132,9 @@ class QuoteFilters extends QueryFilters
return $this->builder;
}
- if($sort_col[0] == 'valid_until')
+ if ($sort_col[0] == 'valid_until') {
$sort_col[0] = 'due_date';
+ }
return $this->builder->orderBy($sort_col[0], $sort_col[1]);
}
diff --git a/app/Filters/RecurringInvoiceFilters.php b/app/Filters/RecurringInvoiceFilters.php
index 07884685e7fc..d9655b975b63 100644
--- a/app/Filters/RecurringInvoiceFilters.php
+++ b/app/Filters/RecurringInvoiceFilters.php
@@ -66,21 +66,24 @@ class RecurringInvoiceFilters extends QueryFilters
$recurring_filters = [];
- if (in_array('active', $status_parameters))
+ if (in_array('active', $status_parameters)) {
$recurring_filters[] = RecurringInvoice::STATUS_ACTIVE;
+ }
- if (in_array('paused', $status_parameters))
+ if (in_array('paused', $status_parameters)) {
$recurring_filters[] = RecurringInvoice::STATUS_PAUSED;
+ }
- if (in_array('completed', $status_parameters))
+ if (in_array('completed', $status_parameters)) {
$recurring_filters[] = RecurringInvoice::STATUS_COMPLETED;
+ }
- if(count($recurring_filters) >= 1)
+ if (count($recurring_filters) >= 1) {
return $this->builder->whereIn('status_id', $recurring_filters);
+ }
return $this->builder;
-
}
public function number(string $number = ''): Builder
diff --git a/app/Filters/TaskFilters.php b/app/Filters/TaskFilters.php
index 9e732fcf978d..7a2495f1d434 100644
--- a/app/Filters/TaskFilters.php
+++ b/app/Filters/TaskFilters.php
@@ -74,7 +74,6 @@ class TaskFilters extends QueryFilters
public function project_tasks($project): Builder
{
-
if (strlen($project) == 0) {
return $this->builder;
}
diff --git a/app/Filters/UserFilters.php b/app/Filters/UserFilters.php
index a53b2eded078..ec3c0a08fd9a 100644
--- a/app/Filters/UserFilters.php
+++ b/app/Filters/UserFilters.php
@@ -70,17 +70,16 @@ class UserFilters extends QueryFilters
}
/**
- * Overrides the base with() function as no company ID
+ * Overrides the base with() function as no company ID
* exists on the user table
- *
+ *
* @param string $value Hashed ID of the user to return back in the dataset
- *
+ *
* @return Builder
*/
public function with(string $value = ''): Builder
{
-
- if(strlen($value) == 0) {
+ if (strlen($value) == 0) {
return $this->builder;
}
@@ -89,5 +88,4 @@ class UserFilters extends QueryFilters
->orderByRaw("{$this->with_property} = ? DESC", [$value])
->where('account_id', auth()->user()->account_id);
}
-
}
diff --git a/app/Helpers/Bank/AccountTransformerInterface.php b/app/Helpers/Bank/AccountTransformerInterface.php
index 6155a3976deb..94c7bb816d0b 100644
--- a/app/Helpers/Bank/AccountTransformerInterface.php
+++ b/app/Helpers/Bank/AccountTransformerInterface.php
@@ -13,5 +13,5 @@ namespace App\Helpers\Bank;
interface AccountTransformerInterface
{
- public function transform($accounts);
+ public function transform($accounts);
}
diff --git a/app/Helpers/Bank/BankExpenseInterface.php b/app/Helpers/Bank/BankExpenseInterface.php
index ca441bcb04fc..5b23a9321f68 100644
--- a/app/Helpers/Bank/BankExpenseInterface.php
+++ b/app/Helpers/Bank/BankExpenseInterface.php
@@ -13,5 +13,4 @@ namespace App\Helpers\Bank;
interface BankExpenseInterface
{
-
}
diff --git a/app/Helpers/Bank/Yodlee/Transformer/AccountTransformer.php b/app/Helpers/Bank/Yodlee/Transformer/AccountTransformer.php
index e2b90656fb6f..84b50df7fabf 100644
--- a/app/Helpers/Bank/Yodlee/Transformer/AccountTransformer.php
+++ b/app/Helpers/Bank/Yodlee/Transformer/AccountTransformer.php
@@ -12,7 +12,7 @@
namespace App\Helpers\Bank\Yodlee\Transformer;
use App\Helpers\Bank\AccountTransformerInterface;
-
+
/**
[0] => stdClass Object
(
@@ -33,7 +33,7 @@ use App\Helpers\Bank\AccountTransformerInterface;
[includeInNetWorth] => 1
[providerId] => 18769
[providerName] => Dag Site Captcha
- [isManual] =>
+ [isManual] =>
[currentBalance] => stdClass Object
(
[currency] => USD
@@ -64,17 +64,15 @@ use App\Helpers\Bank\AccountTransformerInterface;
class AccountTransformer implements AccountTransformerInterface
{
-
public function transform($yodlee_account)
{
-
$data = [];
- if(!property_exists($yodlee_account, 'account'))
+ if (!property_exists($yodlee_account, 'account')) {
return $data;
+ }
- foreach($yodlee_account->account as $account)
- {
+ foreach ($yodlee_account->account as $account) {
$data[] = $this->transformAccount($account);
}
@@ -83,7 +81,6 @@ class AccountTransformer implements AccountTransformerInterface
public function transformAccount($account)
{
-
return [
'id' => $account->id,
'account_type' => $account->CONTAINER,
@@ -100,5 +97,3 @@ class AccountTransformer implements AccountTransformerInterface
];
}
}
-
-
diff --git a/app/Helpers/Bank/Yodlee/Transformer/ExpenseTransformer.php b/app/Helpers/Bank/Yodlee/Transformer/ExpenseTransformer.php
index 6274bb2ed911..ced5d0a48f14 100644
--- a/app/Helpers/Bank/Yodlee/Transformer/ExpenseTransformer.php
+++ b/app/Helpers/Bank/Yodlee/Transformer/ExpenseTransformer.php
@@ -10,7 +10,7 @@
*/
namespace App\Helpers\Bank\Yodlee\Transformer;
-
+
/**
"date": "string",
"sourceId": "string",
@@ -74,7 +74,4 @@ namespace App\Helpers\Bank\Yodlee\Transformer;
class ExpenseTransformer
{
-
}
-
-
diff --git a/app/Helpers/Bank/Yodlee/Transformer/IncomeTransformer.php b/app/Helpers/Bank/Yodlee/Transformer/IncomeTransformer.php
index 3ae26cbf7c9e..42c0e9bf5895 100644
--- a/app/Helpers/Bank/Yodlee/Transformer/IncomeTransformer.php
+++ b/app/Helpers/Bank/Yodlee/Transformer/IncomeTransformer.php
@@ -74,7 +74,7 @@ use Illuminate\Support\Facades\Cache;
"holdingDescription": "string",
"isin": "string",
"status": "POSTED"
-
+
(
[CONTAINER] => bank
[id] => 103953585
@@ -96,7 +96,7 @@ use Illuminate\Support\Facades\Cache;
[original] => CHEROKEE NATION TAX TA TAHLEQUAH OK
)
-[isManual] =>
+[isManual] =>
[sourceType] => AGGREGATED
[date] => 2022-08-03
[transactionDate] => 2022-08-03
@@ -119,17 +119,17 @@ class IncomeTransformer implements BankRevenueInterface
public function transform($transaction)
{
-
$data = [];
- if(!property_exists($transaction, 'transaction'))
+ if (!property_exists($transaction, 'transaction')) {
return $data;
+ }
- foreach($transaction->transaction as $transaction)
- {
+ foreach ($transaction->transaction as $transaction) {
//do not store duplicate / pending transactions
- if(property_exists($transaction,'status') && $transaction->status == 'PENDING')
+ if (property_exists($transaction, 'status') && $transaction->status == 'PENDING') {
continue;
+ }
$data[] = $this->transformTransaction($transaction);
}
@@ -139,7 +139,6 @@ class IncomeTransformer implements BankRevenueInterface
public function transformTransaction($transaction)
{
-
return [
'transaction_id' => $transaction->id,
'amount' => $transaction->amount->amount,
@@ -158,34 +157,29 @@ class IncomeTransformer implements BankRevenueInterface
{
//CREDIT / DEBIT
- if(property_exists($transaction, 'highLevelCategoryId') && $transaction->highLevelCategoryId == 10000012)
+ if (property_exists($transaction, 'highLevelCategoryId') && $transaction->highLevelCategoryId == 10000012) {
return 'CREDIT';
+ }
return 'DEBIT';
-
}
private function convertCurrency(string $code)
{
-
$currencies = Cache::get('currencies');
if (! $currencies) {
$this->buildCache(true);
}
- $currency = $currencies->filter(function ($item) use($code){
+ $currency = $currencies->filter(function ($item) use ($code) {
return $item->code == $code;
})->first();
- if($currency)
+ if ($currency) {
return $currency->id;
+ }
return 1;
-
}
-
-
}
-
-
diff --git a/app/Helpers/Bank/Yodlee/Yodlee.php b/app/Helpers/Bank/Yodlee/Yodlee.php
index 325f168ca504..709acd306c46 100644
--- a/app/Helpers/Bank/Yodlee/Yodlee.php
+++ b/app/Helpers/Bank/Yodlee/Yodlee.php
@@ -16,10 +16,9 @@ use App\Helpers\Bank\Yodlee\Transformer\AccountTransformer;
use App\Helpers\Bank\Yodlee\Transformer\IncomeTransformer;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;
-
+
class Yodlee
{
-
public bool $test_mode = false;
private string $api_endpoint = 'https://production.api.yodlee.com/ysl';
@@ -44,7 +43,6 @@ class Yodlee
public function __construct(?string $bank_account_id = null)
{
-
$this->bank_account_id = $bank_account_id;
$this->client_id = config('ninja.yodlee.client_id');
@@ -56,13 +54,13 @@ class Yodlee
$this->test_mode = config('ninja.yodlee.test_mode');
config('ninja.yodlee.dev_mode') ? $this->setDevUrl() : null;
-
}
public function getFastTrackUrl()
{
- if(config('ninja.yodlee.dev_mode'))
+ if (config('ninja.yodlee.dev_mode')) {
return $this->dev_fast_track_url;
+ }
return $this->test_mode ? $this->test_fast_track_url : $this->production_track_url;
}
@@ -94,12 +92,13 @@ class Yodlee
*/
public function getAccessToken($is_admin = false)
{
- if($is_admin)
+ if ($is_admin) {
$user = $this->admin_name;
- else
+ } else {
$user = $this->bank_account_id ?: $this->admin_name;
+ }
- $response = $this->bankFormRequest('/auth/token', 'post', [], ['loginName' => $user]);
+ $response = $this->bankFormRequest('/auth/token', 'post', [], ['loginName' => $user]);
return $response->token->accessToken;
}
@@ -107,103 +106,98 @@ class Yodlee
public function createUser($company)
{
-
$token = $this->getAccessToken(true);
$user['user'] = [
'loginName' => Str::uuid(),
];
-/*
-{
- "user": {
- "preferences": {
- "dateFormat": "string",
- "timeZone": "string",
- "currency": "USD",
- "locale": "en_US"
- },
- "address": {
- "zip": "string",
- "country": "string",
- "address3": "string",
- "address2": "string",
- "city": "string",
- "address1": "string",
- "state": "string"
- },
- "loginName": "string",
- "name": {
- "middle": "string",
- "last": "string",
- "fullName": "string",
- "first": "string"
- },
- "email": "string",
- "segmentName": "string"
- }
-}
-*/
+ /*
+ {
+ "user": {
+ "preferences": {
+ "dateFormat": "string",
+ "timeZone": "string",
+ "currency": "USD",
+ "locale": "en_US"
+ },
+ "address": {
+ "zip": "string",
+ "country": "string",
+ "address3": "string",
+ "address2": "string",
+ "city": "string",
+ "address1": "string",
+ "state": "string"
+ },
+ "loginName": "string",
+ "name": {
+ "middle": "string",
+ "last": "string",
+ "fullName": "string",
+ "first": "string"
+ },
+ "email": "string",
+ "segmentName": "string"
+ }
+ }
+ */
$response = Http::withHeaders($this->getHeaders(["Authorization" => "Bearer {$token}"]))->post($this->getEndpoint(). "/user/register", $user);
- if($response->successful())
+ if ($response->successful()) {
return $response->object();
+ }
- if($response->failed())
+ if ($response->failed()) {
throw new YodleeApiException($response->body());
-
+ }
}
public function getAccounts($params = [])
{
-
$token = $this->getAccessToken();
$response = Http::withHeaders($this->getHeaders(["Authorization" => "Bearer {$token}"]))->get($this->getEndpoint(). "/accounts", $params);
- if($response->successful()){
-
+ if ($response->successful()) {
$at = new AccountTransformer();
return $at->transform($response->object());
-
}
- if($response->failed())
+ if ($response->failed()) {
throw new YodleeApiException($response->body());
-
+ }
}
public function getAccount($account_id)
{
-
$token = $this->getAccessToken();
$response = Http::withHeaders($this->getHeaders(["Authorization" => "Bearer {$token}"]))->get($this->getEndpoint(). "/accounts/{$account_id}", []);
- if($response->successful())
+ if ($response->successful()) {
return true;
+ }
- if($response->failed())
+ if ($response->failed()) {
return false;
+ }
}
public function deleteAccount($account_id)
{
-
$token = $this->getAccessToken();
$response = Http::withHeaders($this->getHeaders(["Authorization" => "Bearer {$token}"]))->delete($this->getEndpoint(). "/accounts/{$account_id}", []);
- if($response->successful()){
-
+ if ($response->successful()) {
return true;
-
}
- if($response->failed())
+ if ($response->failed()) {
throw new YodleeApiException($response->body());
-
+ }
}
@@ -213,16 +207,15 @@ class Yodlee
$response = Http::withHeaders($this->getHeaders(["Authorization" => "Bearer {$token}"]))->get($this->getEndpoint(). "/transactions", $params);
- if($response->successful()){
+ if ($response->successful()) {
// return $response->object();
$it = new IncomeTransformer();
return $it->transform($response->object());
-
}
- if($response->failed())
+ if ($response->failed()) {
throw new YodleeApiException($response->body());
-
+ }
}
public function getTransactionCount($params = [])
@@ -231,16 +224,14 @@ class Yodlee
$response = Http::withHeaders($this->getHeaders(["Authorization" => "Bearer {$token}"]))->get($this->getEndpoint(). "/transactions/count", $params);
- if($response->successful()){
-
+ if ($response->successful()) {
return $response->object();
-
}
- if($response->failed())
+ if ($response->failed()) {
throw new YodleeApiException($response->body());
-
- }
+ }
+ }
public function getTransactionCategories($params = [])
{
@@ -248,25 +239,26 @@ class Yodlee
$response = Http::withHeaders($this->getHeaders(["Authorization" => "Bearer {$token}"]))->get($this->getEndpoint(). "/transactions/categories", $params);
- if($response->successful())
+ if ($response->successful()) {
return $response->object();
+ }
- if($response->failed())
+ if ($response->failed()) {
throw new YodleeApiException($response->body());
-
+ }
}
private function bankFormRequest(string $uri, string $verb, array $data, array $headers)
{
-
$response = Http::withHeaders($this->getFormHeaders($headers))->asForm()->{$verb}($this->getEndpoint() . $uri, $this->buildBody());
- if($response->successful())
+ if ($response->successful()) {
return $response->object();
+ }
- if($response->failed())
+ if ($response->failed()) {
throw new YodleeApiException($response->body());
-
+ }
}
private function getHeaders($data = [])
@@ -287,12 +279,9 @@ class Yodlee
private function buildBody()
{
-
return [
'clientId' => $this->client_id,
'secret' => $this->client_secret,
];
-
}
-
}
diff --git a/app/Helpers/ClientPortal.php b/app/Helpers/ClientPortal.php
index 0e5a2276ef40..25f7706344f0 100644
--- a/app/Helpers/ClientPortal.php
+++ b/app/Helpers/ClientPortal.php
@@ -26,7 +26,7 @@ function isActive($page, bool $boolean = false)
$current_page = Route::currentRouteName();
$action = Route::currentRouteAction(); // string
- $show = str_replace(['.show','payment_methodss','documentss','subscriptionss','paymentss'],['s.index','payment_methods','documents','subscriptions','payments'], $current_page);
+ $show = str_replace(['.show','payment_methodss','documentss','subscriptionss','paymentss'], ['s.index','payment_methods','documents','subscriptions','payments'], $current_page);
if ($page == $current_page && $boolean) {
return true;
@@ -36,7 +36,7 @@ function isActive($page, bool $boolean = false)
return 'bg-gray-200';
}
- if(($page == $show) && $boolean){
+ if (($page == $show) && $boolean) {
return true;
}
diff --git a/app/Helpers/Epc/EpcQrGenerator.php b/app/Helpers/Epc/EpcQrGenerator.php
index 1778f336d349..2da19d1da679 100644
--- a/app/Helpers/Epc/EpcQrGenerator.php
+++ b/app/Helpers/Epc/EpcQrGenerator.php
@@ -15,17 +15,16 @@ use App\Models\Company;
use App\Models\Invoice;
use App\Models\RecurringInvoice;
use App\Utils\Ninja;
-use BaconQrCode\Renderer\ImageRenderer;
use BaconQrCode\Renderer\Image\SvgImageBackEnd;
+use BaconQrCode\Renderer\ImageRenderer;
use BaconQrCode\Renderer\RendererStyle\RendererStyle;
use BaconQrCode\Writer;
/**
* EpcQrGenerator.
*/
-class EpcQrGenerator
+class EpcQrGenerator
{
-
private array $sepa = [
'serviceTag' => 'BCD',
'version' => 2,
@@ -36,11 +35,12 @@ class EpcQrGenerator
];
- public function __construct(protected Company $company, protected Invoice|RecurringInvoice $invoice, protected float $amount){}
+ public function __construct(protected Company $company, protected Invoice|RecurringInvoice $invoice, protected float $amount)
+ {
+ }
public function getQrCode()
{
-
$renderer = new ImageRenderer(
new RendererStyle(200),
new SvgImageBackEnd()
@@ -51,22 +51,18 @@ class EpcQrGenerator
try {
$qr = $writer->writeString($this->encodeMessage(), 'utf-8');
- }
- catch(\Throwable $e){
+ } catch(\Throwable $e) {
return '';
- }
- catch(\Exception $e){
+ } catch(\Exception $e) {
return '';
}
return "";
-
}
public function encodeMessage()
{
-
- return rtrim(implode("\n", array(
+ return rtrim(implode("\n", [
$this->sepa['serviceTag'],
sprintf('%03d', $this->sepa['version']),
$this->sepa['characterSet'],
@@ -76,25 +72,25 @@ class EpcQrGenerator
isset($this->company?->custom_fields?->company1) ? $this->company->settings->custom_value1 : '',
$this->formatMoney($this->amount),
$this->sepa['purpose'],
- substr($this->invoice->number,0,34),
+ substr($this->invoice->number, 0, 34),
'',
''
- )), "\n");
-
+ ]), "\n");
}
private function validateFields()
{
-
- if(Ninja::isSelfHost() && isset($this->company?->custom_fields?->company2))
+ if (Ninja::isSelfHost() && isset($this->company?->custom_fields?->company2)) {
nlog('The BIC field is not present and _may_ be a required fields for EPC QR codes');
+ }
- if(Ninja::isSelfHost() && isset($this->company?->custom_fields?->company1))
+ if (Ninja::isSelfHost() && isset($this->company?->custom_fields?->company1)) {
nlog('The IBAN field is required');
-
+ }
}
- private function formatMoney($value) {
+ private function formatMoney($value)
+ {
return sprintf('EUR%s', number_format($value, 2, '.', ''));
}
-}
\ No newline at end of file
+}
diff --git a/app/Helpers/Generic.php b/app/Helpers/Generic.php
index cccd27e0c06c..a0b3247aab47 100644
--- a/app/Helpers/Generic.php
+++ b/app/Helpers/Generic.php
@@ -43,4 +43,4 @@ function nlog($output, $context = []): void
$output = null;
$context = null;
-}
\ No newline at end of file
+}
diff --git a/app/Helpers/Invoice/InvoiceItemSum.php b/app/Helpers/Invoice/InvoiceItemSum.php
index 7201a03325d1..464679e2f5e2 100644
--- a/app/Helpers/Invoice/InvoiceItemSum.php
+++ b/app/Helpers/Invoice/InvoiceItemSum.php
@@ -112,11 +112,9 @@ class InvoiceItemSum
if ($this->invoice->is_amount_discount) {
$this->setLineTotal($this->getLineTotal() - $this->formatValue($this->item->discount, $this->currency->precision));
} else {
-
$discount = ($this->item->line_total * ($this->item->discount / 100));
$this->setLineTotal($this->formatValue(($this->getLineTotal() - $discount), $this->currency->precision));
-
}
$this->item->is_amount_discount = $this->invoice->is_amount_discount;
diff --git a/app/Helpers/Invoice/InvoiceSum.php b/app/Helpers/Invoice/InvoiceSum.php
index ffdfdf11232f..3510804b5917 100644
--- a/app/Helpers/Invoice/InvoiceSum.php
+++ b/app/Helpers/Invoice/InvoiceSum.php
@@ -12,7 +12,6 @@
namespace App\Helpers\Invoice;
use App\Models\Invoice;
-use App\Models\TaxRate;
use App\Utils\Traits\NumberFormatter;
use Illuminate\Support\Collection;
@@ -101,7 +100,6 @@ class InvoiceSum
private function calculateCustomValues()
{
-
$this->total_custom_values += $this->valuer($this->invoice->custom_surcharge1);
$this->total_custom_values += $this->valuer($this->invoice->custom_surcharge2);
@@ -151,7 +149,6 @@ class InvoiceSum
*/
private function calculateBalance()
{
-
$this->setCalculatedAttributes();
return $this;
diff --git a/app/Helpers/Invoice/ProRata.php b/app/Helpers/Invoice/ProRata.php
index 97facf247b73..7c2027f6b8ac 100644
--- a/app/Helpers/Invoice/ProRata.php
+++ b/app/Helpers/Invoice/ProRata.php
@@ -13,9 +13,7 @@ namespace App\Helpers\Invoice;
use App\Models\Invoice;
use App\Models\RecurringInvoice;
-use Carbon\Exceptions\InvalidFormatException;
use Exception;
-use Illuminate\Contracts\Container\BindingResolutionException;
use Illuminate\Support\Carbon;
class ProRata
diff --git a/app/Helpers/Mail/GmailTransport.php b/app/Helpers/Mail/GmailTransport.php
index 4ea61fa3d2bc..4c74e0961d1e 100644
--- a/app/Helpers/Mail/GmailTransport.php
+++ b/app/Helpers/Mail/GmailTransport.php
@@ -11,9 +11,9 @@
namespace App\Helpers\Mail;
+use Google\Client;
use Google\Service\Gmail;
use Google\Service\Gmail\Message;
-use Google\Client;
use Symfony\Component\Mailer\SentMessage;
use Symfony\Component\Mailer\Transport\AbstractTransport;
use Symfony\Component\Mime\MessageConverter;
@@ -23,7 +23,6 @@ use Symfony\Component\Mime\MessageConverter;
*/
class GmailTransport extends AbstractTransport
{
-
public function __construct()
{
parent::__construct();
@@ -50,34 +49,26 @@ class GmailTransport extends AbstractTransport
$bcc_list = '';
- if($bccs)
- {
+ if ($bccs) {
$bcc_list = 'Bcc: ';
- foreach($bccs->getAddresses() as $address){
-
+ foreach ($bccs->getAddresses() as $address) {
$bcc_list .= $address->getAddress() .',';
-
}
$bcc_list = rtrim($bcc_list, ",") . "\r\n";
- }
+ }
$body->setRaw($this->base64_encode($bcc_list.$message->toString()));
- try{
+ try {
$service->users_messages->send('me', $body, []);
- }
- catch(\Google\Service\Exception $e) {
-
+ } catch(\Google\Service\Exception $e) {
/* Need to slow down */
- if($e->getCode() == '429') {
-
+ if ($e->getCode() == '429') {
nlog("429 google - retrying ");
$service->users_messages->send('me', $body, []);
-
}
-
}
}
@@ -90,5 +81,4 @@ class GmailTransport extends AbstractTransport
{
return 'gmail';
}
-
}
diff --git a/app/Helpers/Mail/Office365MailTransport.php b/app/Helpers/Mail/Office365MailTransport.php
index e396e8f42531..246ebb025069 100644
--- a/app/Helpers/Mail/Office365MailTransport.php
+++ b/app/Helpers/Mail/Office365MailTransport.php
@@ -11,16 +11,13 @@
namespace App\Helpers\Mail;
-use Illuminate\Support\Str;
use Microsoft\Graph\Graph;
-use Microsoft\Graph\Model\UploadSession;
use Symfony\Component\Mailer\SentMessage;
use Symfony\Component\Mailer\Transport\AbstractTransport;
use Symfony\Component\Mime\MessageConverter;
class Office365MailTransport extends AbstractTransport
{
-
public function __construct()
{
parent::__construct();
@@ -28,7 +25,6 @@ class Office365MailTransport extends AbstractTransport
protected function doSend(SentMessage $message): void
{
-
$symfony_message = MessageConverter::toEmail($message->getOriginalMessage());
$graph = new Graph();
@@ -41,16 +37,11 @@ class Office365MailTransport extends AbstractTransport
$bcc_list = '';
- if($bccs)
- {
-
- foreach($bccs->getAddresses() as $address){
-
+ if ($bccs) {
+ foreach ($bccs->getAddresses() as $address) {
$bcc_list .= 'Bcc: "'.$address->getAddress().'" <'.$address->getAddress().'>\r\n';
-
}
-
- }
+ }
try {
$graphMessage = $graph->createRequest('POST', '/users/'.$symfony_message->getFrom()[0]->getAddress().'/sendmail')
@@ -66,12 +57,10 @@ class Office365MailTransport extends AbstractTransport
->setReturnType(\Microsoft\Graph\Model\Message::class)
->execute();
}
-
}
public function __toString(): string
{
return 'office365';
}
-
}
diff --git a/app/Helpers/Subscription/SubscriptionCalculator.php b/app/Helpers/Subscription/SubscriptionCalculator.php
index ef0fa8465f64..dd9675bef4ad 100644
--- a/app/Helpers/Subscription/SubscriptionCalculator.php
+++ b/app/Helpers/Subscription/SubscriptionCalculator.php
@@ -13,7 +13,6 @@ namespace App\Helpers\Subscription;
use App\Helpers\Invoice\ProRata;
use App\Models\Invoice;
-use App\Models\RecurringInvoice;
use App\Models\Subscription;
use Illuminate\Support\Carbon;
diff --git a/app/Helpers/SwissQr/SwissQrGenerator.php b/app/Helpers/SwissQr/SwissQrGenerator.php
index d6b47a99c315..abacbb57c056 100644
--- a/app/Helpers/SwissQr/SwissQrGenerator.php
+++ b/app/Helpers/SwissQr/SwissQrGenerator.php
@@ -21,7 +21,6 @@ use Sprain\SwissQrBill as QrBill;
*/
class SwissQrGenerator
{
-
protected Company $company;
protected $invoice;
@@ -39,155 +38,143 @@ class SwissQrGenerator
private function calcDueAmount()
{
- if($this->invoice->partial > 0)
+ if ($this->invoice->partial > 0) {
return $this->invoice->partial;
+ }
- if($this->invoice->status_id == Invoice::STATUS_DRAFT)
+ if ($this->invoice->status_id == Invoice::STATUS_DRAFT) {
return $this->invoice->amount;
+ }
return $this->invoice->balance;
}
public function run()
{
-
- // This is an example how to create a typical qr bill:
- // - with reference number
- // - with known debtor
- // - with specified amount
- // - with human-readable additional information
- // - using your QR-IBAN
+ // This is an example how to create a typical qr bill:
+ // - with reference number
+ // - with known debtor
+ // - with specified amount
+ // - with human-readable additional information
+ // - using your QR-IBAN
//
- // Likely the most common use-case in the business world.
+ // Likely the most common use-case in the business world.
- // Create a new instance of QrBill, containing default headers with fixed values
- $qrBill = QrBill\QrBill::create();
+ // Create a new instance of QrBill, containing default headers with fixed values
+ $qrBill = QrBill\QrBill::create();
- // Add creditor information
- // Who will receive the payment and to which bank account?
- $qrBill->setCreditor(
- QrBill\DataGroup\Element\CombinedAddress::create(
- $this->company->present()->name(),
- $this->company->present()->address1(),
- $this->company->present()->getCompanyCityState(),
- 'CH'
- ));
-
- $qrBill->setCreditorInformation(
- QrBill\DataGroup\Element\CreditorInformation::create(
- $this->company->present()->qr_iban() ?: '' // This is a special QR-IBAN. Classic IBANs will not be valid here.
- ));
-
- // Add debtor information
- // Who has to pay the invoice? This part is optional.
- //
- // Notice how you can use two different styles of addresses: CombinedAddress or StructuredAddress
- // They are interchangeable for creditor as well as debtor.
- $qrBill->setUltimateDebtor(
- QrBill\DataGroup\Element\StructuredAddress::createWithStreet(
- substr($this->client->present()->name(), 0 , 70),
- $this->client->address1 ? substr($this->client->address1, 0 , 70) : ' ',
- $this->client->address2 ? substr($this->client->address2, 0 , 16) : ' ',
- $this->client->postal_code ? substr($this->client->postal_code, 0, 16) : ' ',
- $this->client->city ? substr($this->client->city, 0, 35) : ' ',
- 'CH'
- ));
-
- // Add payment amount information
- // What amount is to be paid?
- $qrBill->setPaymentAmountInformation(
- QrBill\DataGroup\Element\PaymentAmountInformation::create(
- 'CHF',
- $this->calcDueAmount()
- ));
-
- // Add payment reference
- // This is what you will need to identify incoming payments.
-
- if(stripos($this->invoice->number, "Live") === 0)
- {
- // we're currently in preview status. Let's give a dummy reference for now
- $invoice_number = "123456789";
- }
- else
- {
- $tempInvoiceNumber = $this->invoice->number;
- $tempInvoiceNumber = preg_replace('/[^A-Za-z0-9]/', '', $tempInvoiceNumber);
- $tempInvoiceNumber = substr($tempInvoiceNumber, 1);
-
- $calcInvoiceNumber = "";
- $array = str_split($tempInvoiceNumber);
- foreach($array as $char)
- {
- if (is_numeric($char))
- {
- //
- }
- else
- {
- if ($char)
- {
- $char = strtolower($char);
- $char = ord($char) - 96;
- }
- else
- {
- return 0;
- }
- }
- $calcInvoiceNumber .= $char;
- }
-
- $invoice_number = $calcInvoiceNumber;
-
- }
-
- if(strlen($this->company->present()->besr_id()) > 1)
- {
- $referenceNumber = QrBill\Reference\QrPaymentReferenceGenerator::generate(
- $this->company->present()->besr_id() ?: '', // You receive this number from your bank (BESR-ID). Unless your bank is PostFinance, in that case use NULL.
- $invoice_number// A number to match the payment with your internal data, e.g. an invoice number
+ // Add creditor information
+ // Who will receive the payment and to which bank account?
+ $qrBill->setCreditor(
+ QrBill\DataGroup\Element\CombinedAddress::create(
+ $this->company->present()->name(),
+ $this->company->present()->address1(),
+ $this->company->present()->getCompanyCityState(),
+ 'CH'
+ )
);
- $qrBill->setPaymentReference(
- QrBill\DataGroup\Element\PaymentReference::create(
- QrBill\DataGroup\Element\PaymentReference::TYPE_QR,
- $referenceNumber
- ));
+ $qrBill->setCreditorInformation(
+ QrBill\DataGroup\Element\CreditorInformation::create(
+ $this->company->present()->qr_iban() ?: '' // This is a special QR-IBAN. Classic IBANs will not be valid here.
+ )
+ );
- }
- else{
+ // Add debtor information
+ // Who has to pay the invoice? This part is optional.
+ //
+ // Notice how you can use two different styles of addresses: CombinedAddress or StructuredAddress
+ // They are interchangeable for creditor as well as debtor.
+ $qrBill->setUltimateDebtor(
+ QrBill\DataGroup\Element\StructuredAddress::createWithStreet(
+ substr($this->client->present()->name(), 0, 70),
+ $this->client->address1 ? substr($this->client->address1, 0, 70) : ' ',
+ $this->client->address2 ? substr($this->client->address2, 0, 16) : ' ',
+ $this->client->postal_code ? substr($this->client->postal_code, 0, 16) : ' ',
+ $this->client->city ? substr($this->client->city, 0, 35) : ' ',
+ 'CH'
+ )
+ );
- $qrBill->setPaymentReference(
- QrBill\DataGroup\Element\PaymentReference::create(
- QrBill\DataGroup\Element\PaymentReference::TYPE_NON
- ));
+ // Add payment amount information
+ // What amount is to be paid?
+ $qrBill->setPaymentAmountInformation(
+ QrBill\DataGroup\Element\PaymentAmountInformation::create(
+ 'CHF',
+ $this->calcDueAmount()
+ )
+ );
- }
+ // Add payment reference
+ // This is what you will need to identify incoming payments.
+
+ if (stripos($this->invoice->number, "Live") === 0) {
+ // we're currently in preview status. Let's give a dummy reference for now
+ $invoice_number = "123456789";
+ } else {
+ $tempInvoiceNumber = $this->invoice->number;
+ $tempInvoiceNumber = preg_replace('/[^A-Za-z0-9]/', '', $tempInvoiceNumber);
+ $tempInvoiceNumber = substr($tempInvoiceNumber, 1);
+
+ $calcInvoiceNumber = "";
+ $array = str_split($tempInvoiceNumber);
+ foreach ($array as $char) {
+ if (is_numeric($char)) {
+ //
+ } else {
+ if ($char) {
+ $char = strtolower($char);
+ $char = ord($char) - 96;
+ } else {
+ return 0;
+ }
+ }
+ $calcInvoiceNumber .= $char;
+ }
+
+ $invoice_number = $calcInvoiceNumber;
+ }
- // Optionally, add some human-readable information about what the bill is for.
- $qrBill->setAdditionalInformation(
- QrBill\DataGroup\Element\AdditionalInformation::create(
- $this->invoice->public_notes ? substr($this->invoice->public_notes, 0, 139) : ctrans('texts.invoice_number_placeholder', ['invoice' => $this->invoice->number])
- )
- );
+ if (strlen($this->company->present()->besr_id()) > 1) {
+ $referenceNumber = QrBill\Reference\QrPaymentReferenceGenerator::generate(
+ $this->company->present()->besr_id() ?: '', // You receive this number from your bank (BESR-ID). Unless your bank is PostFinance, in that case use NULL.
+ $invoice_number// A number to match the payment with your internal data, e.g. an invoice number
+ );
+
+ $qrBill->setPaymentReference(
+ QrBill\DataGroup\Element\PaymentReference::create(
+ QrBill\DataGroup\Element\PaymentReference::TYPE_QR,
+ $referenceNumber
+ )
+ );
+ } else {
+ $qrBill->setPaymentReference(
+ QrBill\DataGroup\Element\PaymentReference::create(
+ QrBill\DataGroup\Element\PaymentReference::TYPE_NON
+ )
+ );
+ }
+
+ // Optionally, add some human-readable information about what the bill is for.
+ $qrBill->setAdditionalInformation(
+ QrBill\DataGroup\Element\AdditionalInformation::create(
+ $this->invoice->public_notes ? substr($this->invoice->public_notes, 0, 139) : ctrans('texts.invoice_number_placeholder', ['invoice' => $this->invoice->number])
+ )
+ );
- // Now get the QR code image and save it as a file.
+ // Now get the QR code image and save it as a file.
try {
-
$output = new QrBill\PaymentPart\Output\HtmlOutput\HtmlOutput($qrBill, $this->client->locale() ?: 'en');
$html = $output
->setPrintable(false)
->getPaymentPart();
- return $html;
-
+ return $html;
} catch (\Exception $e) {
-
- foreach($qrBill->getViolations() as $key => $violation) {
+ foreach ($qrBill->getViolations() as $key => $violation) {
nlog("qr");
nlog($violation);
}
@@ -197,8 +184,5 @@ class SwissQrGenerator
return '';
// return $e->getMessage();
}
-
-
}
-
}
diff --git a/app/Http/Controllers/ActivityController.php b/app/Http/Controllers/ActivityController.php
index 9e3916d32612..71de89040149 100644
--- a/app/Http/Controllers/ActivityController.php
+++ b/app/Http/Controllers/ActivityController.php
@@ -92,10 +92,10 @@ class ActivityController extends BaseController
->take($default_activities);
if ($request->has('react')) {
-
- if(!auth()->user()->isAdmin())
+ if (!auth()->user()->isAdmin()) {
$activities->where('user_id', auth()->user()->id);
- // return response()->json(['data' => []], 200);
+ }
+ // return response()->json(['data' => []], 200);
$system = ctrans('texts.system');
@@ -183,7 +183,6 @@ class ActivityController extends BaseController
*/
if ($backup && $backup->filename && Storage::disk(config('filesystems.default'))->exists($backup->filename)) { //disk
-
if (Ninja::isHosted()) {
$html_backup = file_get_contents(Storage::disk(config('filesystems.default'))->url($backup->filename));
} else {
diff --git a/app/Http/Controllers/Auth/ContactForgotPasswordController.php b/app/Http/Controllers/Auth/ContactForgotPasswordController.php
index f106936236bf..cda235731295 100644
--- a/app/Http/Controllers/Auth/ContactForgotPasswordController.php
+++ b/app/Http/Controllers/Auth/ContactForgotPasswordController.php
@@ -112,7 +112,6 @@ class ContactForgotPasswordController extends Controller
$response = false;
if ($contact) {
-
/* Update all instances of the client */
$token = Str::random(60);
ClientContact::where('email', $contact->email)->update(['token' => $token]);
diff --git a/app/Http/Controllers/Auth/ContactLoginController.php b/app/Http/Controllers/Auth/ContactLoginController.php
index edc60dc3c512..0872b085069d 100644
--- a/app/Http/Controllers/Auth/ContactLoginController.php
+++ b/app/Http/Controllers/Auth/ContactLoginController.php
@@ -24,7 +24,6 @@ use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
-use Route;
class ContactLoginController extends Controller
{
@@ -45,12 +44,11 @@ class ContactLoginController extends Controller
if ($request->session()->has('company_key')) {
MultiDB::findAndSetDbByCompanyKey($request->session()->get('company_key'));
$company = Company::where('company_key', $request->input('company_key'))->first();
- }
- elseif($request->has('company_key')){
- MultiDB::findAndSetDbByCompanyKey($request->input('company_key'));
+ } elseif ($request->has('company_key')) {
+ MultiDB::findAndSetDbByCompanyKey($request->input('company_key'));
$company = Company::where('company_key', $request->input('company_key'))->first();
- }elseif($company_key){
- MultiDB::findAndSetDbByCompanyKey($company_key);
+ } elseif ($company_key) {
+ MultiDB::findAndSetDbByCompanyKey($company_key);
$company = Company::where('company_key', $company_key)->first();
}
diff --git a/app/Http/Controllers/Auth/ContactRegisterController.php b/app/Http/Controllers/Auth/ContactRegisterController.php
index 827f6147caac..15acb8c7d765 100644
--- a/app/Http/Controllers/Auth/ContactRegisterController.php
+++ b/app/Http/Controllers/Auth/ContactRegisterController.php
@@ -51,7 +51,6 @@ class ContactRegisterController extends Controller
public function register(RegisterRequest $request)
{
-
$request->merge(['company' => $request->company()]);
$client = $this->getClient($request->all());
@@ -70,7 +69,7 @@ class ContactRegisterController extends Controller
$client->save();
- if(isset($data['currency_id'])) {
+ if (isset($data['currency_id'])) {
$settings = $client->settings;
$settings->currency_id = isset($data['currency_id']) ? $data['currency_id'] : $data['company']->settings->currency_id;
$client->settings = $settings;
diff --git a/app/Http/Controllers/Auth/LoginController.php b/app/Http/Controllers/Auth/LoginController.php
index 4ac3e5ce2f39..5d4f4b347947 100644
--- a/app/Http/Controllers/Auth/LoginController.php
+++ b/app/Http/Controllers/Auth/LoginController.php
@@ -19,7 +19,6 @@ use App\Http\Controllers\Controller;
use App\Http\Requests\Login\LoginRequest;
use App\Jobs\Account\CreateAccount;
use App\Jobs\Company\CreateCompanyToken;
-use App\Jobs\Util\SystemLogger;
use App\Libraries\MultiDB;
use App\Libraries\OAuth\OAuth;
use App\Libraries\OAuth\Providers\Google;
@@ -28,7 +27,6 @@ use App\Models\Client;
use App\Models\Company;
use App\Models\CompanyToken;
use App\Models\CompanyUser;
-use App\Models\SystemLog;
use App\Models\User;
use App\Transformers\CompanyUserTransformer;
use App\Utils\Ninja;
@@ -41,12 +39,10 @@ use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
-use Illuminate\Support\Str;
use Laravel\Socialite\Facades\Socialite;
use Microsoft\Graph\Model;
use PragmaRX\Google2FA\Google2FA;
use Turbo124\Beacon\Facades\LightLogs;
-use Illuminate\Support\Facades\Http;
class LoginController extends BaseController
{
@@ -418,7 +414,7 @@ class LoginController extends BaseController
$name = OAuth::splitName($user->name);
- if($provider == 'apple') {
+ if ($provider == 'apple') {
$name[0] = request()->has('first_name') ? request()->input('first_name') : $name[0];
$name[1] = request()->has('last_name') ? request()->input('last_name') : $name[1];
}
@@ -495,12 +491,13 @@ class LoginController extends BaseController
private function handleMicrosoftOauth()
{
- if (request()->has('accessToken'))
+ if (request()->has('accessToken')) {
$accessToken = request()->input('accessToken');
- elseif(request()->has('access_token'))
+ } elseif (request()->has('access_token')) {
$accessToken = request()->input('access_token');
- else
+ } else {
return response()->json(['message' => 'Invalid response from oauth server, no access token in response.'], 400);
+ }
$graph = new \Microsoft\Graph\Graph();
@@ -554,7 +551,6 @@ class LoginController extends BaseController
return response()->json(['message' => 'Unable to authenticate this user'], 400);
-
}
private function existingOauthUser($existing_user)
@@ -600,10 +596,11 @@ class LoginController extends BaseController
$google = new Google();
- if(request()->has('id_token'))
+ if (request()->has('id_token')) {
$user = $google->getTokenResponse(request()->input('id_token'));
- else
+ } else {
return response()->json(['message' => 'Illegal request'], 403);
+ }
if (is_array($user)) {
$query = [
@@ -632,7 +629,6 @@ class LoginController extends BaseController
}
if ($user) {
-
//check the user doesn't already exist in some form
if ($existing_login_user = MultiDB::hasUser(['email' => $google->harvestEmail($user)])) {
if (!$existing_login_user->account) {
@@ -702,7 +698,7 @@ class LoginController extends BaseController
$parameters = ['access_type' => 'offline', 'prompt' => 'consent select_account', 'redirect_uri' => config('ninja.app_url') . '/auth/google'];
}
- if($provider == 'microsoft'){
+ if ($provider == 'microsoft') {
$scopes = ['email', 'Mail.Send', 'offline_access', 'profile', 'User.Read openid'];
$parameters = ['response_type' => 'code', 'redirect_uri' => config('ninja.app_url')."/auth/microsoft"];
}
@@ -766,8 +762,7 @@ class LoginController extends BaseController
$oauth_expiry = now()->addSeconds($socialite_user->accessTokenResponseBody['expires_in']) ?: now()->addSeconds(300);
- if($user = OAuth::handleAuth($socialite_user, $provider))
- {
+ if ($user = OAuth::handleAuth($socialite_user, $provider)) {
nlog('found user and updating their user record');
$name = OAuth::splitName($socialite_user->getName());
diff --git a/app/Http/Controllers/Auth/VendorContactLoginController.php b/app/Http/Controllers/Auth/VendorContactLoginController.php
index 242fd81ba839..91708e065faf 100644
--- a/app/Http/Controllers/Auth/VendorContactLoginController.php
+++ b/app/Http/Controllers/Auth/VendorContactLoginController.php
@@ -11,20 +11,9 @@
namespace App\Http\Controllers\Auth;
-use App\Events\Contact\ContactLoggedIn;
use App\Http\Controllers\Controller;
-use App\Http\ViewComposers\PortalComposer;
-use App\Libraries\MultiDB;
-use App\Models\Account;
-use App\Models\ClientContact;
-use App\Models\Company;
-use App\Utils\Ninja;
use Auth;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
-use Illuminate\Http\JsonResponse;
-use Illuminate\Http\Request;
-use Illuminate\Support\Facades\Hash;
-use Route;
class VendorContactLoginController extends Controller
{
diff --git a/app/Http/Controllers/Bank/YodleeController.php b/app/Http/Controllers/Bank/YodleeController.php
index 7f107c1e8431..1783d097c904 100644
--- a/app/Http/Controllers/Bank/YodleeController.php
+++ b/app/Http/Controllers/Bank/YodleeController.php
@@ -20,11 +20,9 @@ use Illuminate\Http\Request;
class YodleeController extends BaseController
{
-
public function auth(YodleeAuthRequest $request)
{
-
- // create a user at this point
+ // create a user at this point
// use the one time token here to pull in the actual user
// store the user_account_id on the accounts table
@@ -35,15 +33,11 @@ class YodleeController extends BaseController
//ensure user is enterprise!!
- if($company->account->bank_integration_account_id){
-
+ if ($company->account->bank_integration_account_id) {
$flow = 'edit';
$token = $company->account->bank_integration_account_id;
-
- }
- else{
-
+ } else {
$flow = 'add';
$response = $yodlee->createUser($company);
@@ -53,13 +47,13 @@ class YodleeController extends BaseController
$company->account->bank_integration_account_id = $token;
$company->push();
-
}
$yodlee = new Yodlee($token);
- if($request->has('window_closed') && $request->input("window_closed") == "true")
+ if ($request->has('window_closed') && $request->input("window_closed") == "true") {
$this->getAccounts($company, $token);
+ }
$data = [
'access_token' => $yodlee->getAccessToken(),
@@ -72,20 +66,16 @@ class YodleeController extends BaseController
];
return view('bank.yodlee.auth', $data);
-
}
private function getAccounts($company, $token)
{
$yodlee = new Yodlee($token);
- $accounts = $yodlee->getAccounts();
+ $accounts = $yodlee->getAccounts();
- foreach($accounts as $account)
- {
-
- if(!BankIntegration::where('bank_account_id', $account['id'])->where('company_id', $company->id)->exists())
- {
+ foreach ($accounts as $account) {
+ if (!BankIntegration::where('bank_account_id', $account['id'])->where('company_id', $company->id)->exists()) {
$bank_integration = new BankIntegration();
$bank_integration->company_id = $company->id;
$bank_integration->account_id = $company->account_id;
@@ -104,16 +94,12 @@ class YodleeController extends BaseController
$bank_integration->save();
}
-
}
- $company->account->bank_integrations->each(function ($bank_integration) use ($company){
-
+ $company->account->bank_integrations->each(function ($bank_integration) use ($company) {
ProcessBankTransactions::dispatch($company->account->bank_integration_account_id, $bank_integration);
-
});
-
}
@@ -183,7 +169,7 @@ class YodleeController extends BaseController
}*/
public function refreshWebhook(Request $request)
{
-//we should ignore this one
+ //we should ignore this one
nlog("yodlee refresh");
nlog($request->all());
@@ -218,7 +204,6 @@ class YodleeController extends BaseController
*/
public function balanceWebhook(Request $request)
{
-
nlog("yodlee refresh");
nlog($request->all());
@@ -230,15 +215,15 @@ class YodleeController extends BaseController
}
/*
-{
- "event":{
- "data":[
- {
- "autoRefresh":{
+{
+ "event":{
+ "data":[
+ {
+ "autoRefresh":{
"additionalStatus":"SCHEDULED",
"status":"ENABLED"
},
- "accountIds":[
+ "accountIds":[
1112645899,
1112645898
],
@@ -254,7 +239,7 @@ class YodleeController extends BaseController
*/
public function refreshUpdatesWebhook(Request $request)
{
-//notifies a user if there are problems with yodlee accessing the data
+ //notifies a user if there are problems with yodlee accessing the data
nlog("update refresh");
nlog($request->all());
@@ -289,7 +274,7 @@ class YodleeController extends BaseController
*/
public function dataUpdatesWebhook(Request $request)
{
-//this is the main hook we use for notifications
+ //this is the main hook we use for notifications
nlog("data refresh");
nlog($request->all());
@@ -300,5 +285,4 @@ class YodleeController extends BaseController
// return response()->json(['message' => 'Unauthorized'], 403);
}
-
}
diff --git a/app/Http/Controllers/BankIntegrationController.php b/app/Http/Controllers/BankIntegrationController.php
index 1c47c4fa4c96..02dabc66d189 100644
--- a/app/Http/Controllers/BankIntegrationController.php
+++ b/app/Http/Controllers/BankIntegrationController.php
@@ -25,7 +25,6 @@ use App\Http\Requests\BankIntegration\UpdateBankIntegrationRequest;
use App\Jobs\Bank\ProcessBankTransactions;
use App\Models\BankIntegration;
use App\Repositories\BankIntegrationRepository;
-use App\Services\Bank\BankMatchingService;
use App\Transformers\BankIntegrationTransformer;
use App\Utils\Traits\MakesHash;
use Illuminate\Http\Request;
@@ -94,11 +93,9 @@ class BankIntegrationController extends BaseController
*/
public function index(BankIntegrationFilters $filters)
{
-
$bank_integrations = BankIntegration::filter($filters);
return $this->listResponse($bank_integrations);
-
}
/**
@@ -262,7 +259,6 @@ class BankIntegrationController extends BaseController
*/
public function update(UpdateBankIntegrationRequest $request, BankIntegration $bank_integration)
{
-
//stubs for updating the model
$bank_integration = $this->bank_integration_repo->save($request->all(), $bank_integration);
@@ -476,9 +472,8 @@ class BankIntegrationController extends BaseController
->company()
->cursor()
->each(function ($bank_integration, $key) use ($action) {
-
- $this->bank_integration_repo->{$action}($bank_integration);
- });
+ $this->bank_integration_repo->{$action}($bank_integration);
+ });
/* Need to understand which permission are required for the given bulk action ie. view / edit */
@@ -528,18 +523,16 @@ class BankIntegrationController extends BaseController
$bank_account_id = auth()->user()->account->bank_integration_account_id;
- if(!$bank_account_id)
+ if (!$bank_account_id) {
return response()->json(['message' => 'Not yet authenticated with Bank Integration service'], 400);
+ }
$yodlee = new Yodlee($bank_account_id);
- $accounts = $yodlee->getAccounts();
+ $accounts = $yodlee->getAccounts();
- foreach($accounts as $account)
- {
-
- if(!BankIntegration::where('bank_account_id', $account['id'])->where('company_id', auth()->user()->company()->id)->exists())
- {
+ foreach ($accounts as $account) {
+ if (!BankIntegration::where('bank_account_id', $account['id'])->where('company_id', auth()->user()->company()->id)->exists()) {
$bank_integration = new BankIntegration();
$bank_integration->company_id = auth()->user()->company()->id;
$bank_integration->account_id = auth()->user()->account_id;
@@ -556,19 +549,17 @@ class BankIntegrationController extends BaseController
$bank_integration->currency = $account['account_currency'];
$bank_integration->save();
-
}
}
$account = auth()->user()->account;
- if(Cache::get("throttle_polling:{$account->key}"))
+ if (Cache::get("throttle_polling:{$account->key}")) {
return response()->json(BankIntegration::query()->company(), 200);
+ }
- $account->bank_integrations->each(function ($bank_integration) use ($account){
-
+ $account->bank_integrations->each(function ($bank_integration) use ($account) {
ProcessBankTransactions::dispatch($account->bank_integration_account_id, $bank_integration);
-
});
Cache::put("throttle_polling:{$account->key}", true, 300);
@@ -615,11 +606,11 @@ class BankIntegrationController extends BaseController
public function removeAccount(AdminBankIntegrationRequest $request, $acc_id)
{
-
$bank_account_id = auth()->user()->account->bank_integration_account_id;
- if(!$bank_account_id)
+ if (!$bank_account_id) {
return response()->json(['message' => 'Not yet authenticated with Bank Integration service'], 400);
+ }
$bi = BankIntegration::withTrashed()->where('bank_account_id', $acc_id)->company()->firstOrFail();
@@ -629,7 +620,6 @@ class BankIntegrationController extends BaseController
$this->bank_integration_repo->delete($bi);
return $this->itemResponse($bi->fresh());
-
}
@@ -671,14 +661,10 @@ class BankIntegrationController extends BaseController
*/
public function getTransactions(AdminBankIntegrationRequest $request)
{
-
auth()->user()->account->bank_integrations->each(function ($bank_integration) {
-
(new ProcessBankTransactions(auth()->user()->account->bank_integration_account_id, $bank_integration))->handle();
-
});
return response()->json(['message' => 'Fetching transactions....'], 200);
-
}
-}
\ No newline at end of file
+}
diff --git a/app/Http/Controllers/BankTransactionController.php b/app/Http/Controllers/BankTransactionController.php
index a1596e0f9afa..3967a969750e 100644
--- a/app/Http/Controllers/BankTransactionController.php
+++ b/app/Http/Controllers/BankTransactionController.php
@@ -13,27 +13,19 @@ namespace App\Http\Controllers;
use App\Factory\BankTransactionFactory;
use App\Filters\BankTransactionFilters;
-use App\Helpers\Bank\Yodlee\Yodlee;
-use App\Http\Requests\BankTransaction\AdminBankTransactionRequest;
use App\Http\Requests\BankTransaction\BulkBankTransactionRequest;
use App\Http\Requests\BankTransaction\CreateBankTransactionRequest;
use App\Http\Requests\BankTransaction\DestroyBankTransactionRequest;
use App\Http\Requests\BankTransaction\EditBankTransactionRequest;
-use App\Http\Requests\BankTransaction\ImportBankTransactionsRequest;
use App\Http\Requests\BankTransaction\MatchBankTransactionRequest;
use App\Http\Requests\BankTransaction\ShowBankTransactionRequest;
use App\Http\Requests\BankTransaction\StoreBankTransactionRequest;
use App\Http\Requests\BankTransaction\UpdateBankTransactionRequest;
-use App\Http\Requests\Import\PreImportRequest;
use App\Jobs\Bank\MatchBankTransactions;
use App\Models\BankTransaction;
use App\Repositories\BankTransactionRepository;
-use App\Services\Bank\BankMatchingService;
use App\Transformers\BankTransactionTransformer;
use App\Utils\Traits\MakesHash;
-use Illuminate\Http\Request;
-use Illuminate\Support\Facades\Cache;
-use Illuminate\Support\Str;
class BankTransactionController extends BaseController
{
@@ -98,11 +90,9 @@ class BankTransactionController extends BaseController
*/
public function index(BankTransactionFilters $filters)
{
-
$bank_transactions = BankTransaction::filter($filters);
return $this->listResponse($bank_transactions);
-
}
/**
@@ -266,7 +256,6 @@ class BankTransactionController extends BaseController
*/
public function update(UpdateBankTransactionRequest $request, BankTransaction $bank_transaction)
{
-
//stubs for updating the model
$bank_transaction = $this->bank_transaction_repo->save($request->all(), $bank_transaction);
@@ -478,18 +467,13 @@ class BankTransactionController extends BaseController
$bank_transactions = BankTransaction::withTrashed()->whereIn('id', $this->transformKeys($ids))->company()->get();
- if($action == 'convert_matched') //catch this action
- {
-
+ if ($action == 'convert_matched') { //catch this action
+
$this->bank_transaction_repo->convert_matched($bank_transactions);
-
- }
- else {
-
+ } else {
$bank_transactions->each(function ($bank_transaction, $key) use ($action) {
- $this->bank_transaction_repo->{$action}($bank_transaction);
+ $this->bank_transaction_repo->{$action}($bank_transaction);
});
-
}
/* Need to understand which permission are required for the given bulk action ie. view / edit */
@@ -548,14 +532,10 @@ class BankTransactionController extends BaseController
*/
public function match(MatchBankTransactionRequest $request)
{
-
// MatchBankTransactions::dispatch(auth()->user()->company()->id, auth()->user()->company()->db, $request->all());
$bts = (new MatchBankTransactions(auth()->user()->company()->id, auth()->user()->company()->db, $request->all()))->handle();
return $this->listResponse($bts);
-
}
-
-
-}
\ No newline at end of file
+}
diff --git a/app/Http/Controllers/BankTransactionRuleController.php b/app/Http/Controllers/BankTransactionRuleController.php
index 143ae68a70cc..822a3cdc5165 100644
--- a/app/Http/Controllers/BankTransactionRuleController.php
+++ b/app/Http/Controllers/BankTransactionRuleController.php
@@ -11,11 +11,9 @@
namespace App\Http\Controllers;
-use App\Factory\BankTransactionFactory;
use App\Factory\BankTransactionRuleFactory;
use App\Filters\BankTransactionFilters;
use App\Filters\BankTransactionRuleFilters;
-use App\Helpers\Bank\Yodlee\Yodlee;
use App\Http\Requests\BankTransactionRule\BulkBankTransactionRuleRequest;
use App\Http\Requests\BankTransactionRule\CreateBankTransactionRuleRequest;
use App\Http\Requests\BankTransactionRule\DestroyBankTransactionRuleRequest;
@@ -23,20 +21,10 @@ use App\Http\Requests\BankTransactionRule\EditBankTransactionRuleRequest;
use App\Http\Requests\BankTransactionRule\ShowBankTransactionRuleRequest;
use App\Http\Requests\BankTransactionRule\StoreBankTransactionRuleRequest;
use App\Http\Requests\BankTransactionRule\UpdateBankTransactionRuleRequest;
-use App\Http\Requests\BankTransaction\AdminBankTransactionRuleRequest;
-use App\Http\Requests\Import\PreImportRequest;
-use App\Jobs\Bank\MatchBankTransactionRules;
-use App\Models\BankTransaction;
use App\Models\BankTransactionRule;
-use App\Repositories\BankTransactionRepository;
use App\Repositories\BankTransactionRuleRepository;
-use App\Services\Bank\BankMatchingService;
use App\Transformers\BankTransactionRuleTransformer;
-use App\Transformers\BankTransactionTransformer;
use App\Utils\Traits\MakesHash;
-use Illuminate\Http\Request;
-use Illuminate\Support\Facades\Cache;
-use Illuminate\Support\Str;
class BankTransactionRuleController extends BaseController
{
@@ -101,11 +89,9 @@ class BankTransactionRuleController extends BaseController
*/
public function index(BankTransactionRuleFilters $filters)
{
-
$bank_transaction_rules = BankTransactionRule::filter($filters);
return $this->listResponse($bank_transaction_rules);
-
}
/**
@@ -269,7 +255,6 @@ class BankTransactionRuleController extends BaseController
*/
public function update(UpdateBankTransactionRuleRequest $request, BankTransactionRule $bank_transaction_rule)
{
-
//stubs for updating the model
$bank_transaction = $this->bank_transaction_repo->save($request->all(), $bank_transaction_rule);
@@ -484,11 +469,10 @@ class BankTransactionRuleController extends BaseController
->company()
->cursor()
->each(function ($bank_transaction_rule, $key) use ($action) {
- $this->bank_transaction_repo->{$action}($bank_transaction_rule);
- });
+ $this->bank_transaction_repo->{$action}($bank_transaction_rule);
+ });
/* Need to understand which permission are required for the given bulk action ie. view / edit */
return $this->listResponse(BankTransactionRule::withTrashed()->whereIn('id', $this->transformKeys($ids))->company());
}
-
-}
\ No newline at end of file
+}
diff --git a/app/Http/Controllers/BaseController.php b/app/Http/Controllers/BaseController.php
index f319791092be..8871455980a6 100644
--- a/app/Http/Controllers/BaseController.php
+++ b/app/Http/Controllers/BaseController.php
@@ -11,33 +11,33 @@
namespace App\Http\Controllers;
-use App\Models\User;
-use App\Utils\Ninja;
-use App\Models\Design;
-use App\Utils\Statics;
use App\Models\Account;
-use App\Models\TaxRate;
-use App\Models\Webhook;
-use App\Models\Scheduler;
-use App\Models\TaskStatus;
-use App\Models\PaymentTerm;
-use Illuminate\Support\Str;
-use League\Fractal\Manager;
-use App\Models\GroupSetting;
-use App\Models\CompanyGateway;
-use App\Utils\Traits\AppSetup;
use App\Models\BankIntegration;
use App\Models\BankTransaction;
-use App\Models\ExpenseCategory;
-use League\Fractal\Resource\Item;
use App\Models\BankTransactionRule;
+use App\Models\CompanyGateway;
+use App\Models\Design;
+use App\Models\ExpenseCategory;
+use App\Models\GroupSetting;
+use App\Models\PaymentTerm;
+use App\Models\Scheduler;
+use App\Models\TaskStatus;
+use App\Models\TaxRate;
+use App\Models\User;
+use App\Models\Webhook;
use App\Transformers\ArraySerializer;
use App\Transformers\EntityTransformer;
-use League\Fractal\Resource\Collection;
-use Illuminate\Database\Eloquent\Builder;
-use League\Fractal\Serializer\JsonApiSerializer;
-use League\Fractal\Pagination\IlluminatePaginatorAdapter;
+use App\Utils\Ninja;
+use App\Utils\Statics;
+use App\Utils\Traits\AppSetup;
use Illuminate\Contracts\Container\BindingResolutionException;
+use Illuminate\Database\Eloquent\Builder;
+use Illuminate\Support\Str;
+use League\Fractal\Manager;
+use League\Fractal\Pagination\IlluminatePaginatorAdapter;
+use League\Fractal\Resource\Collection;
+use League\Fractal\Resource\Item;
+use League\Fractal\Serializer\JsonApiSerializer;
/**
* Class BaseController.
@@ -184,9 +184,9 @@ class BaseController extends Controller
/**
* Filters the includes to ensure the
- * end user has the correct permissions to
+ * end user has the correct permissions to
* view the includes
- *
+ *
* @param array $includes The includes for the object
* @return string The filtered array of includes
*/
@@ -204,12 +204,11 @@ class BaseController extends Controller
$collection = collect(explode(",", $includes));
- $filtered_includes = $collection->filter(function ($include) use ($permissions_array){
+ $filtered_includes = $collection->filter(function ($include) use ($permissions_array) {
return auth()->user()->hasPermission($permissions_array[$include]);
});
return $filtered_includes->implode(",");
-
}
/**
@@ -247,7 +246,7 @@ class BaseController extends Controller
/**
* Refresh API response with latest cahnges
* @param Builer $query
- * @property App\Models\User auth()->user()
+ * @property App\Models\User auth()->user()
* @return Builer
*/
protected function refreshResponse($query)
@@ -283,11 +282,9 @@ class BaseController extends Controller
$query->where('clients.updated_at', '>=', $updated_at)->with('contacts.company', 'gateway_tokens', 'documents');
if (! $user->hasPermission('view_client')) {
-
- $query->whereNested(function($query) use ($user) {
+ $query->whereNested(function ($query) use ($user) {
$query->where('clients.user_id', $user->id)->orWhere('clients.assigned_user_id', $user->id);
- });
-
+ });
}
},
'company.company_gateways' => function ($query) use ($user) {
@@ -301,10 +298,9 @@ class BaseController extends Controller
$query->where('updated_at', '>=', $updated_at)->with('invitations', 'documents');
if (! $user->hasPermission('view_credit')) {
-
- $query->whereNested(function($query) use ($user) {
+ $query->whereNested(function ($query) use ($user) {
$query->where('credits.user_id', $user->id)->orWhere('credits.assigned_user_id', $user->id);
- });
+ });
}
},
'company.designs'=> function ($query) use ($updated_at, $user) {
@@ -321,37 +317,30 @@ class BaseController extends Controller
$query->where('updated_at', '>=', $updated_at)->with('documents');
if (! $user->hasPermission('view_expense')) {
-
- $query->whereNested(function($query) use ($user) {
+ $query->whereNested(function ($query) use ($user) {
$query->where('expenses.user_id', $user->id)->orWhere('expenses.assigned_user_id', $user->id);
- });
+ });
}
},
'company.groups' => function ($query) {
$query->whereNotNull('updated_at')->with('documents');
-
},
'company.invoices'=> function ($query) use ($updated_at, $user) {
$query->where('updated_at', '>=', $updated_at)->with('invitations', 'documents');
if (! $user->hasPermission('view_invoice')) {
-
-
- $query->whereNested(function($query) use ($user) {
+ $query->whereNested(function ($query) use ($user) {
$query->where('invoices.user_id', $user->id)->orWhere('invoices.assigned_user_id', $user->id);
- });
-
+ });
}
},
'company.payments'=> function ($query) use ($updated_at, $user) {
$query->where('updated_at', '>=', $updated_at)->with('paymentables', 'documents');
if (! $user->hasPermission('view_payment')) {
-
- $query->whereNested(function($query) use ($user) {
+ $query->whereNested(function ($query) use ($user) {
$query->where('payments.user_id', $user->id)->orWhere('payments.assigned_user_id', $user->id);
- });
-
+ });
}
},
'company.payment_terms'=> function ($query) use ($user) {
@@ -365,78 +354,63 @@ class BaseController extends Controller
$query->where('updated_at', '>=', $updated_at)->with('documents');
if (! $user->hasPermission('view_product')) {
-
- $query->whereNested(function($query) use ($user) {
+ $query->whereNested(function ($query) use ($user) {
$query->where('products.user_id', $user->id)->orWhere('products.assigned_user_id', $user->id);
-
});
}
-
},
'company.projects'=> function ($query) use ($updated_at, $user) {
$query->where('updated_at', '>=', $updated_at)->with('documents');
if (! $user->hasPermission('view_project')) {
-
- $query->whereNested(function($query) use ($user) {
+ $query->whereNested(function ($query) use ($user) {
$query->where('projects.user_id', $user->id)->orWhere('projects.assigned_user_id', $user->id);
- });
-
+ });
}
},
'company.purchase_orders'=> function ($query) use ($updated_at, $user) {
$query->where('updated_at', '>=', $updated_at)->with('documents');
if (! $user->hasPermission('view_purchase_order')) {
-
- $query->whereNested(function($query) use ($user) {
+ $query->whereNested(function ($query) use ($user) {
$query->where('purchase_orders.user_id', $user->id)->orWhere('purchase_orders.assigned_user_id', $user->id);
- });
-
+ });
}
},
'company.quotes'=> function ($query) use ($updated_at, $user) {
$query->where('updated_at', '>=', $updated_at)->with('invitations', 'documents');
if (! $user->hasPermission('view_quote')) {
-
- $query->whereNested(function($query) use ($user) {
+ $query->whereNested(function ($query) use ($user) {
$query->where('quotes.user_id', $user->id)->orWhere('quotes.assigned_user_id', $user->id);
- });
-
+ });
}
},
'company.recurring_invoices'=> function ($query) use ($updated_at, $user) {
$query->where('updated_at', '>=', $updated_at)->with('invitations', 'documents', 'client.gateway_tokens', 'client.group_settings', 'client.company');
if (! $user->hasPermission('view_recurring_invoice')) {
-
- $query->whereNested(function($query) use ($user) {
+ $query->whereNested(function ($query) use ($user) {
$query->where('recurring_invoices.user_id', $user->id)->orWhere('recurring_invoices.assigned_user_id', $user->id);
- });
-
+ });
}
},
'company.recurring_expenses'=> function ($query) use ($updated_at, $user) {
$query->where('updated_at', '>=', $updated_at)->with('documents');
if (! $user->hasPermission('view_recurring_expense')) {
-
- $query->whereNested(function($query) use ($user) {
+ $query->whereNested(function ($query) use ($user) {
$query->where('recurring_expenses.user_id', $user->id)->orWhere('recurring_expenses.assigned_user_id', $user->id);
- });
-
+ });
}
},
'company.tasks'=> function ($query) use ($updated_at, $user) {
$query->where('updated_at', '>=', $updated_at)->with('documents');
if (! $user->hasPermission('view_task')) {
-
- $query->whereNested(function($query) use ($user) {
+ $query->whereNested(function ($query) use ($user) {
$query->where('tasks.user_id', $user->id)->orWhere('tasks.assigned_user_id', $user->id);
- });
-
+ });
}
},
'company.tax_rates'=> function ($query) {
@@ -446,11 +420,9 @@ class BaseController extends Controller
$query->where('updated_at', '>=', $updated_at)->with('contacts', 'documents');
if (! $user->hasPermission('view_vendor')) {
-
- $query->whereNested(function($query) use ($user) {
+ $query->whereNested(function ($query) use ($user) {
$query->where('vendors.user_id', $user->id)->orWhere('vendors.assigned_user_id', $user->id);
- });
-
+ });
}
},
'company.expense_categories'=> function ($query) {
@@ -480,10 +452,9 @@ class BaseController extends Controller
}
//allows us to return integrations for users who can create bank transactions
- if(!$user->isSuperUser() && $user->hasIntersectPermissions(['create_bank_transaction','edit_bank_transaction','view_bank_transaction'])) {
+ if (!$user->isSuperUser() && $user->hasIntersectPermissions(['create_bank_transaction','edit_bank_transaction','view_bank_transaction'])) {
$query->exclude(["balance"]);
}
-
},
'company.bank_transactions'=> function ($query) use ($updated_at, $user) {
$query->where('updated_at', '>=', $updated_at);
@@ -526,8 +497,9 @@ class BaseController extends Controller
private function resolveQueryLimit()
{
- if(request()->has('per_page'))
+ if (request()->has('per_page')) {
return abs((int)request()->input('per_page', 20));
+ }
return 20;
}
@@ -575,24 +547,20 @@ class BaseController extends Controller
}
},
'company.bank_integrations'=> function ($query) use ($user) {
-
if (! $user->hasPermission('view_bank_transaction')) {
$query->where('bank_integrations.user_id', $user->id);
}
- if(!$user->isSuperUser() && $user->hasIntersectPermissions(['create_bank_transaction','edit_bank_transaction','view_bank_transaction'])) {
+ if (!$user->isSuperUser() && $user->hasIntersectPermissions(['create_bank_transaction','edit_bank_transaction','view_bank_transaction'])) {
$query->exclude(["balance"]);
}
-
},
'company.bank_transaction_rules'=> function ($query) use ($user) {
-
if (! $user->isAdmin()) {
$query->where('bank_transaction_rules.user_id', $user->id);
}
},
'company.task_schedulers'=> function ($query) use ($user) {
-
if (! $user->isAdmin()) {
$query->where('schedulers.user_id', $user->id);
}
@@ -615,17 +583,18 @@ class BaseController extends Controller
}
/**
- * In case a user is not an admin and is
- * able to access multiple companies, then we
+ * In case a user is not an admin and is
+ * able to access multiple companies, then we
* need to pass back the mini load only
- *
+ *
* @return bool
*/
private function complexPermissionsUser(): bool
{
//if the user is attached to more than one company AND they are not an admin across all companies
- if(auth()->user()->company_users()->count() > 1 && (auth()->user()->company_users()->where('is_admin',1)->count() != auth()->user()->company_users()->count()))
+ if (auth()->user()->company_users()->count() > 1 && (auth()->user()->company_users()->where('is_admin', 1)->count() != auth()->user()->company_users()->count())) {
return true;
+ }
return false;
}
@@ -664,11 +633,9 @@ class BaseController extends Controller
$query->where('clients.created_at', '>=', $created_at)->with('contacts.company', 'gateway_tokens', 'documents');
if (! $user->hasPermission('view_client')) {
-
- $query->whereNested(function($query) use ($user) {
+ $query->whereNested(function ($query) use ($user) {
$query->where('clients.user_id', $user->id)->orWhere('clients.assigned_user_id', $user->id);
});
-
}
},
'company.company_gateways' => function ($query) use ($user) {
@@ -682,8 +649,7 @@ class BaseController extends Controller
$query->where('created_at', '>=', $created_at)->with('invitations', 'documents');
if (! $user->hasPermission('view_credit')) {
-
- $query->whereNested(function($query) use ($user) {
+ $query->whereNested(function ($query) use ($user) {
$query->where('credits.user_id', $user->id)->orWhere('credits.assigned_user_id', $user->id);
});
}
@@ -695,8 +661,7 @@ class BaseController extends Controller
$query->where('created_at', '>=', $created_at)->with('documents');
if (! $user->hasPermission('view_expense')) {
-
- $query->whereNested(function($query) use ($user) {
+ $query->whereNested(function ($query) use ($user) {
$query->where('expenses.user_id', $user->id)->orWhere('expenses.assigned_user_id', $user->id);
});
}
@@ -708,22 +673,18 @@ class BaseController extends Controller
$query->where('created_at', '>=', $created_at)->with('invitations', 'documents');
if (! $user->hasPermission('view_invoice')) {
-
- $query->whereNested(function($query) use ($user) {
+ $query->whereNested(function ($query) use ($user) {
$query->where('invoices.user_id', $user->id)->orWhere('invoices.assigned_user_id', $user->id);
});
-
}
},
'company.payments'=> function ($query) use ($created_at, $user) {
$query->where('created_at', '>=', $created_at)->with('paymentables', 'documents');
if (! $user->hasPermission('view_payment')) {
-
- $query->whereNested(function($query) use ($user) {
+ $query->whereNested(function ($query) use ($user) {
$query->where('payments.user_id', $user->id)->orWhere('payments.assigned_user_id', $user->id);
});
-
}
},
'company.payment_terms'=> function ($query) use ($created_at) {
@@ -733,8 +694,7 @@ class BaseController extends Controller
$query->where('created_at', '>=', $created_at)->with('documents');
if (! $user->hasPermission('view_product')) {
-
- $query->whereNested(function($query) use ($user) {
+ $query->whereNested(function ($query) use ($user) {
$query->where('products.user_id', $user->id)->orWhere('products.assigned_user_id', $user->id);
});
}
@@ -743,8 +703,7 @@ class BaseController extends Controller
$query->where('created_at', '>=', $created_at)->with('documents');
if (! $user->hasPermission('view_project')) {
-
- $query->whereNested(function($query) use ($user) {
+ $query->whereNested(function ($query) use ($user) {
$query->where('projects.user_id', $user->id)->orWhere('projects.assigned_user_id', $user->id);
});
}
@@ -753,44 +712,36 @@ class BaseController extends Controller
$query->where('created_at', '>=', $created_at)->with('documents');
if (! $user->hasPermission('view_purchase_order')) {
-
- $query->whereNested(function($query) use ($user) {
+ $query->whereNested(function ($query) use ($user) {
$query->where('purchase_orders.user_id', $user->id)->orWhere('purchase_orders.assigned_user_id', $user->id);
});
-
}
},
'company.quotes'=> function ($query) use ($created_at, $user) {
$query->where('created_at', '>=', $created_at)->with('invitations', 'documents');
if (! $user->hasPermission('view_quote')) {
-
- $query->whereNested(function($query) use ($user) {
+ $query->whereNested(function ($query) use ($user) {
$query->where('quotes.user_id', $user->id)->orWhere('quotes.assigned_user_id', $user->id);
});
-
}
},
'company.recurring_invoices'=> function ($query) use ($created_at, $user) {
$query->where('created_at', '>=', $created_at)->with('invitations', 'documents', 'client.gateway_tokens', 'client.group_settings', 'client.company');
if (! $user->hasPermission('view_recurring_invoice')) {
-
- $query->whereNested(function($query) use ($user) {
+ $query->whereNested(function ($query) use ($user) {
$query->where('recurring_invoices.user_id', $user->id)->orWhere('recurring_invoices.assigned_user_id', $user->id);
});
-
}
},
'company.tasks'=> function ($query) use ($created_at, $user) {
$query->where('created_at', '>=', $created_at)->with('documents');
if (! $user->hasPermission('view_task')) {
-
- $query->whereNested(function($query) use ($user) {
+ $query->whereNested(function ($query) use ($user) {
$query->where('tasks.user_id', $user->id)->orWhere('tasks.assigned_user_id', $user->id);
});
-
}
},
'company.tax_rates' => function ($query) use ($created_at) {
@@ -800,11 +751,9 @@ class BaseController extends Controller
$query->where('created_at', '>=', $created_at)->with('contacts', 'documents');
if (! $user->hasPermission('view_vendor')) {
-
- $query->whereNested(function($query) use ($user) {
+ $query->whereNested(function ($query) use ($user) {
$query->where('vendors.user_id', $user->id)->orWhere('vendors.assigned_user_id', $user->id);
});
-
}
},
'company.expense_categories'=> function ($query) {
@@ -838,11 +787,9 @@ class BaseController extends Controller
$query->where('created_at', '>=', $created_at)->with('documents');
if (! $user->hasPermission('view_recurring_expense')) {
-
- $query->whereNested(function($query) use ($user) {
+ $query->whereNested(function ($query) use ($user) {
$query->where('recurring_expenses.user_id', $user->id)->orWhere('recurring_expenses.assigned_user_id', $user->id);
});
-
}
},
'company.bank_integrations'=> function ($query) use ($created_at, $user) {
@@ -852,10 +799,9 @@ class BaseController extends Controller
$query->where('bank_integrations.user_id', $user->id);
}
- if(!$user->isSuperUser() && $user->hasIntersectPermissions(['create_bank_transaction','edit_bank_transaction','view_bank_transaction'])) {
+ if (!$user->isSuperUser() && $user->hasIntersectPermissions(['create_bank_transaction','edit_bank_transaction','view_bank_transaction'])) {
$query->exclude(["balance"]);
}
-
},
'company.bank_transactions'=> function ($query) use ($created_at, $user) {
$query->where('created_at', '>=', $created_at);
@@ -902,22 +848,20 @@ class BaseController extends Controller
if (auth()->user() && ! auth()->user()->hasPermission('view_'.Str::snake(class_basename($this->entity_type)))) {
//06-10-2022 - some entities do not have assigned_user_id - this becomes an issue when we have a large company and low permission users
- if(in_array($this->entity_type, [User::class])){
+ if (in_array($this->entity_type, [User::class])) {
$query->where('id', auth()->user()->id);
- }
- elseif(in_array($this->entity_type, [BankTransactionRule::class,CompanyGateway::class, TaxRate::class, BankIntegration::class, Scheduler::class, BankTransaction::class, Webhook::class, ExpenseCategory::class])){ //table without assigned_user_id
-
- if($this->entity_type == BankIntegration::class && !auth()->user()->isSuperUser() && auth()->user()->hasIntersectPermissions(['create_bank_transaction','edit_bank_transaction','view_bank_transaction']))
- $query->exclude(["balance"]); //allows us to selective display bank integrations back to the user if they can view / create bank transactions but without the bank balance being present in the response
- else
+ } elseif (in_array($this->entity_type, [BankTransactionRule::class,CompanyGateway::class, TaxRate::class, BankIntegration::class, Scheduler::class, BankTransaction::class, Webhook::class, ExpenseCategory::class])) { //table without assigned_user_id
+ if ($this->entity_type == BankIntegration::class && !auth()->user()->isSuperUser() && auth()->user()->hasIntersectPermissions(['create_bank_transaction','edit_bank_transaction','view_bank_transaction'])) {
+ $query->exclude(["balance"]);
+ } //allows us to selective display bank integrations back to the user if they can view / create bank transactions but without the bank balance being present in the response
+ else {
$query->where('user_id', '=', auth()->user()->id);
- }
- elseif(in_array($this->entity_type, [Design::class, GroupSetting::class, PaymentTerm::class, TaskStatus::class])){
+ }
+ } elseif (in_array($this->entity_type, [Design::class, GroupSetting::class, PaymentTerm::class, TaskStatus::class])) {
// nlog($this->entity_type);
- }
- else
+ } else {
$query->where('user_id', '=', auth()->user()->id)->orWhere('assigned_user_id', auth()->user()->id);
-
+ }
}
// $query->exclude(['balance','credit_balance','paid_to_date']);
@@ -1003,7 +947,6 @@ class BaseController extends Controller
protected function getRequestIncludes($data)
{
-
/*
* Thresholds for displaying large account on first load
*/
@@ -1032,10 +975,10 @@ class BaseController extends Controller
public function flutterRoute()
{
if ((bool) $this->checkAppSetup() !== false && $account = Account::first()) {
-
//always redirect invoicing.co to invoicing.co
- if(Ninja::isHosted() && !in_array(request()->getSchemeAndHttpHost(), ['https://staging.invoicing.co', 'https://invoicing.co', 'https://demo.invoicing.co']))
+ if (Ninja::isHosted() && !in_array(request()->getSchemeAndHttpHost(), ['https://staging.invoicing.co', 'https://invoicing.co', 'https://demo.invoicing.co'])) {
return redirect()->secure('https://invoicing.co');
+ }
if (config('ninja.require_https') && ! request()->isSecure()) {
return redirect()->secure(request()->getRequestUri());
@@ -1053,7 +996,7 @@ class BaseController extends Controller
// 06-09-2022 - parse the path if loaded in a subdirectory for canvaskit resolution
$canvas_path_array = parse_url(config('ninja.app_url'));
$canvas_path = (array_key_exists('path', $canvas_path_array)) ? $canvas_path_array['path'] : '';
- $canvas_path = rtrim(str_replace("index.php", "", $canvas_path),'/');
+ $canvas_path = rtrim(str_replace("index.php", "", $canvas_path), '/');
$data = [];
@@ -1074,7 +1017,7 @@ class BaseController extends Controller
$data['login'] = 'true';
}
- if(request()->session()->has('signup')){
+ if (request()->session()->has('signup')) {
$data['signup'] = 'true';
}
@@ -1119,7 +1062,6 @@ class BaseController extends Controller
return 'main.html.dart.js';
default:
return 'main.foss.dart.js';
-
}
}
diff --git a/app/Http/Controllers/ClientController.php b/app/Http/Controllers/ClientController.php
index f71d62495e01..bf4b43b76f07 100644
--- a/app/Http/Controllers/ClientController.php
+++ b/app/Http/Controllers/ClientController.php
@@ -493,7 +493,6 @@ class ClientController extends BaseController
*/
public function bulk(BulkClientRequest $request)
{
-
$action = $request->action;
$clients = Client::withTrashed()
@@ -501,10 +500,10 @@ class ClientController extends BaseController
->whereIn('id', $request->ids)
->cursor()
->each(function ($client) use ($action) {
- if (auth()->user()->can('edit', $client)) {
- $this->client_repo->{$action}($client);
- }
- });
+ if (auth()->user()->can('edit', $client)) {
+ $this->client_repo->{$action}($client);
+ }
+ });
return $this->listResponse(Client::withTrashed()->company()->whereIn('id', $request->ids));
}
@@ -625,14 +624,11 @@ class ClientController extends BaseController
{
//delete all documents
$client->documents->each(function ($document) {
-
- try{
+ try {
Storage::disk(config('filesystems.default'))->delete($document->url);
- }
- catch(\Exception $e){
+ } catch(\Exception $e) {
nlog($e->getMessage());
}
-
});
//force delete the client
@@ -707,19 +703,17 @@ class ClientController extends BaseController
public function merge(PurgeClientRequest $request, Client $client, string $mergeable_client)
{
-
$m_client = Client::withTrashed()
->where('id', $this->decodePrimaryKey($mergeable_client))
->where('company_id', auth()->user()->company()->id)
->first();
- if(!$m_client)
+ if (!$m_client) {
return response()->json(['message' => "Client not found"]);
+ }
$merged_client = $client->service()->merge($m_client)->save();
return $this->itemResponse($merged_client);
-
}
-
}
diff --git a/app/Http/Controllers/ClientGatewayTokenController.php b/app/Http/Controllers/ClientGatewayTokenController.php
index 53263bfffa5e..75ea17883dea 100644
--- a/app/Http/Controllers/ClientGatewayTokenController.php
+++ b/app/Http/Controllers/ClientGatewayTokenController.php
@@ -11,8 +11,6 @@
namespace App\Http\Controllers;
-use App\Events\ClientGatewayToken\ClientGatewayTokenWasCreated;
-use App\Events\ClientGatewayToken\ClientGatewayTokenWasUpdated;
use App\Factory\ClientGatewayTokenFactory;
use App\Filters\ClientGatewayTokenFilters;
use App\Http\Requests\ClientGatewayToken\CreateClientGatewayTokenRequest;
@@ -22,19 +20,15 @@ use App\Http\Requests\ClientGatewayToken\ListClientGatewayTokenRequest;
use App\Http\Requests\ClientGatewayToken\ShowClientGatewayTokenRequest;
use App\Http\Requests\ClientGatewayToken\StoreClientGatewayTokenRequest;
use App\Http\Requests\ClientGatewayToken\UpdateClientGatewayTokenRequest;
-use App\Http\Requests\ClientGatewayToken\UploadClientGatewayTokenRequest;
use App\Jobs\ClientGatewayToken\StoreClientGatewayToken;
use App\Jobs\ClientGatewayToken\UpdateClientGatewayToken;
-use App\Models\Account;
use App\Models\ClientGatewayToken;
use App\Repositories\ClientGatewayTokenRepository;
use App\Transformers\ClientGatewayTokenTransformer;
-use App\Utils\Ninja;
use App\Utils\Traits\BulkOptions;
use App\Utils\Traits\MakesHash;
use App\Utils\Traits\SavesDocuments;
use App\Utils\Traits\Uploadable;
-use Illuminate\Http\Request;
use Illuminate\Http\Response;
/**
diff --git a/app/Http/Controllers/ClientPortal/ApplePayDomainController.php b/app/Http/Controllers/ClientPortal/ApplePayDomainController.php
index 8bb88d30e953..c4b016c647e5 100644
--- a/app/Http/Controllers/ClientPortal/ApplePayDomainController.php
+++ b/app/Http/Controllers/ClientPortal/ApplePayDomainController.php
@@ -13,11 +13,9 @@ namespace App\Http\Controllers\ClientPortal;
use App\Http\Controllers\Controller;
use App\Libraries\MultiDB;
-use App\Models\Company;
use App\Models\CompanyGateway;
use App\Utils\Ninja;
use Illuminate\Http\Request;
-use Illuminate\Support\Facades\Storage;
class ApplePayDomainController extends Controller
{
@@ -25,7 +23,6 @@ class ApplePayDomainController extends Controller
public function showAppleMerchantId(Request $request)
{
-
/* Self Host */
if (Ninja::isSelfHost()) {
diff --git a/app/Http/Controllers/ClientPortal/DocumentController.php b/app/Http/Controllers/ClientPortal/DocumentController.php
index 3c50a64419af..b1a816d4bf77 100644
--- a/app/Http/Controllers/ClientPortal/DocumentController.php
+++ b/app/Http/Controllers/ClientPortal/DocumentController.php
@@ -86,7 +86,7 @@ class DocumentController extends Controller
$zipFile->saveAsFile($filepath) // save the archive to a file
->close(); // close archive
- return response()->download($filepath, $filename)->deleteFileAfterSend(true);
+ return response()->download($filepath, $filename)->deleteFileAfterSend(true);
} catch (\PhpZip\Exception\ZipException $e) {
// handle exception
} finally {
diff --git a/app/Http/Controllers/ClientPortal/InvitationController.php b/app/Http/Controllers/ClientPortal/InvitationController.php
index 51fd56224e86..52ca200c8ceb 100644
--- a/app/Http/Controllers/ClientPortal/InvitationController.php
+++ b/app/Http/Controllers/ClientPortal/InvitationController.php
@@ -25,7 +25,6 @@ use App\Models\Payment;
use App\Models\PurchaseOrderInvitation;
use App\Models\QuoteInvitation;
use App\Services\ClientPortal\InstantPayment;
-use App\Utils\CurlUtils;
use App\Utils\Ninja;
use App\Utils\Traits\MakesDates;
use App\Utils\Traits\MakesHash;
@@ -70,9 +69,9 @@ class InvitationController extends Controller
private function genericRouter(string $entity, string $invitation_key)
{
-
- if(!in_array($entity, ['invoice', 'credit', 'quote', 'recurring_invoice']))
+ if (!in_array($entity, ['invoice', 'credit', 'quote', 'recurring_invoice'])) {
return response()->json(['message' => 'Invalid resource request']);
+ }
$is_silent = 'false';
@@ -86,38 +85,37 @@ class InvitationController extends Controller
->with('contact.client')
->firstOrFail();
- if($invitation->{$entity}->is_deleted)
+ if ($invitation->{$entity}->is_deleted) {
return $this->render('generic.not_available', ['account' => $invitation->company->account, 'company' => $invitation->company]);
+ }
/* 12/01/2022 Clean up an edge case where if the contact is trashed, restore if a invitation comes back. */
- if($invitation->contact->trashed())
+ if ($invitation->contact->trashed()) {
$invitation->contact->restore();
+ }
/* Return early if we have the correct client_hash embedded */
$client_contact = $invitation->contact;
- if(empty($client_contact->email))
- $client_contact->email = Str::random(15) . "@example.com"; $client_contact->save();
+ if (empty($client_contact->email)) {
+ $client_contact->email = Str::random(15) . "@example.com";
+ } $client_contact->save();
if (request()->has('client_hash') && request()->input('client_hash') == $invitation->contact->client->client_hash) {
request()->session()->invalidate();
auth()->guard('contact')->loginUsingId($client_contact->id, true);
-
} elseif ((bool) $invitation->contact->client->getSetting('enable_client_portal_password') !== false) {
-
//if no contact password has been set - allow user to set password - then continue to view entity
- if(empty($invitation->contact->password)){
-
- return $this->render('view_entity.set_password', [
- 'root' => 'themes',
- 'entity_type' => $entity,
- 'invitation_key' => $invitation_key
- ]);
+ if (empty($invitation->contact->password)) {
+ return $this->render('view_entity.set_password', [
+ 'root' => 'themes',
+ 'entity_type' => $entity,
+ 'invitation_key' => $invitation_key
+ ]);
}
$this->middleware('auth:contact');
return redirect()->route('client.login');
-
} else {
request()->session()->invalidate();
auth()->guard('contact')->loginUsingId($client_contact->id, true);
@@ -127,22 +125,20 @@ class InvitationController extends Controller
if (auth()->guard('contact')->user() && ! request()->has('silent') && ! $invitation->viewed_date) {
$invitation->markViewed();
- if(!session()->get('is_silent'))
+ if (!session()->get('is_silent')) {
event(new InvitationWasViewed($invitation->{$entity}, $invitation, $invitation->{$entity}->company, Ninja::eventVars()));
+ }
- if(!session()->get('is_silent'))
+ if (!session()->get('is_silent')) {
$this->fireEntityViewedEvent($invitation, $entity);
- }
- else{
+ }
+ } else {
$is_silent = 'true';
return redirect()->route('client.'.$entity.'.show', [$entity => $this->encodePrimaryKey($invitation->{$key}), 'silent' => $is_silent]);
-
}
return redirect()->route('client.'.$entity.'.show', [$entity => $this->encodePrimaryKey($invitation->{$key})]);
-
-
}
private function fireEntityViewedEvent($invitation, $entity_string)
@@ -165,20 +161,20 @@ class InvitationController extends Controller
public function routerForDownload(string $entity, string $invitation_key)
{
-
set_time_limit(45);
- if(Ninja::isHosted())
+ if (Ninja::isHosted()) {
return $this->returnRawPdf($entity, $invitation_key);
+ }
return redirect('client/'.$entity.'/'.$invitation_key.'/download_pdf');
}
private function returnRawPdf(string $entity, string $invitation_key)
{
-
- if(!in_array($entity, ['invoice', 'credit', 'quote', 'recurring_invoice']))
+ if (!in_array($entity, ['invoice', 'credit', 'quote', 'recurring_invoice'])) {
return response()->json(['message' => 'Invalid resource request']);
+ }
$key = $entity.'_id';
@@ -189,8 +185,9 @@ class InvitationController extends Controller
->with('contact.client')
->firstOrFail();
- if(!$invitation)
+ if (!$invitation) {
return response()->json(["message" => "no record found"], 400);
+ }
$file_name = $invitation->{$entity}->numberFormatter().'.pdf';
@@ -198,13 +195,13 @@ class InvitationController extends Controller
$headers = ['Content-Type' => 'application/pdf'];
- if(request()->input('inline') == 'true')
+ if (request()->input('inline') == 'true') {
$headers = array_merge($headers, ['Content-Disposition' => 'inline']);
+ }
- return response()->streamDownload(function () use($file) {
- echo $file;
- }, $file_name, $headers);
-
+ return response()->streamDownload(function () use ($file) {
+ echo $file;
+ }, $file_name, $headers);
}
public function routerForIframe(string $entity, string $client_hash, string $invitation_key)
@@ -216,13 +213,13 @@ class InvitationController extends Controller
$contact = ClientContact::withTrashed()->where('contact_key', $contact_key)->firstOrFail();
$payment = Payment::find($this->decodePrimaryKey($payment_id));
- if($payment->client_id != $contact->client_id)
+ if ($payment->client_id != $contact->client_id) {
abort(403, 'You are not authorized to view this resource');
+ }
auth()->guard('contact')->loginUsingId($contact->id, true);
return redirect()->route('client.payments.show', $payment->hashed_id);
-
}
public function payInvoice(Request $request, string $invitation_key)
@@ -232,23 +229,23 @@ class InvitationController extends Controller
->with('contact.client')
->firstOrFail();
- if($invitation->contact->trashed())
+ if ($invitation->contact->trashed()) {
$invitation->contact->restore();
+ }
auth()->guard('contact')->loginUsingId($invitation->contact->id, true);
$invoice = $invitation->invoice;
- if($invoice->partial > 0)
+ if ($invoice->partial > 0) {
$amount = round($invoice->partial, (int)$invoice->client->currency()->precision);
- else
+ } else {
$amount = round($invoice->balance, (int)$invoice->client->currency()->precision);
+ }
$gateways = $invitation->contact->client->service()->getPaymentMethods($amount);
- if(is_array($gateways) && count($gateways) >=1)
- {
-
+ if (is_array($gateways) && count($gateways) >=1) {
$data = [
'company_gateway_id' => $gateways[0]['company_gateway_id'],
'payment_method_id' => $gateways[0]['gateway_type_id'],
@@ -265,38 +262,37 @@ class InvitationController extends Controller
$entity = 'invoice';
- if($invoice && is_array($gateways) && count($gateways) == 0)
+ if ($invoice && is_array($gateways) && count($gateways) == 0) {
return redirect()->route('client.invoice.show', ['invoice' => $this->encodePrimaryKey($invitation->invoice_id)]);
+ }
abort(404, "Invoice not found");
}
public function unsubscribe(Request $request, string $entity, string $invitation_key)
{
- if($entity == 'invoice'){
+ if ($entity == 'invoice') {
$invite = InvoiceInvitation::withTrashed()->where('key', $invitation_key)->first();
$invite->contact->send_email = false;
$invite->contact->save();
- }elseif($entity == 'quote'){
+ } elseif ($entity == 'quote') {
$invite = QuoteInvitation::withTrashed()->where('key', $invitation_key)->first();
$invite->contact->send_email = false;
$invite->contact->save();
- }elseif($entity == 'credit'){
+ } elseif ($entity == 'credit') {
$invite = CreditInvitation::withTrashed()->where('key', $invitation_key)->first();
$invite->contact->send_email = false;
$invite->contact->save();
- }elseif($entity == 'purchase_order'){
+ } elseif ($entity == 'purchase_order') {
$invite = PurchaseOrderInvitation::withTrashed()->where('key', $invitation_key)->first();
$invite->contact->send_email = false;
$invite->contact->save();
- }
- else
+ } else {
return abort(404);
+ }
$data['logo'] = $invite->company->present()->logo();
return $this->render('generic.unsubscribe', $data);
-
}
-
}
diff --git a/app/Http/Controllers/ClientPortal/InvoiceController.php b/app/Http/Controllers/ClientPortal/InvoiceController.php
index d87f56e06d2c..3bfa90b48ac5 100644
--- a/app/Http/Controllers/ClientPortal/InvoiceController.php
+++ b/app/Http/Controllers/ClientPortal/InvoiceController.php
@@ -20,10 +20,8 @@ use App\Http\Requests\ClientPortal\Invoices\ShowInvoicesRequest;
use App\Models\Invoice;
use App\Utils\Ninja;
use App\Utils\Number;
-use App\Utils\TempFile;
use App\Utils\Traits\MakesDates;
use App\Utils\Traits\MakesHash;
-use Illuminate\Contracts\Container\BindingResolutionException;
use Illuminate\Contracts\View\Factory;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
@@ -227,7 +225,6 @@ class InvoiceController extends Controller
$zipFile = new \PhpZip\ZipFile();
try {
foreach ($invoices as $invoice) {
-
//add it to the zip
$zipFile->addFromString(basename($invoice->pdf_file_path()), file_get_contents($invoice->pdf_file_path(null, 'url', true)));
}
@@ -238,7 +235,7 @@ class InvoiceController extends Controller
$zipFile->saveAsFile($filepath) // save the archive to a file
->close(); // close archive
- return response()->download($filepath, $filename)->deleteFileAfterSend(true);
+ return response()->download($filepath, $filename)->deleteFileAfterSend(true);
} catch (\PhpZip\Exception\ZipException $e) {
// handle exception
} finally {
diff --git a/app/Http/Controllers/ClientPortal/NinjaPlanController.php b/app/Http/Controllers/ClientPortal/NinjaPlanController.php
index 9e040640dfa5..d3d275b92a9f 100644
--- a/app/Http/Controllers/ClientPortal/NinjaPlanController.php
+++ b/app/Http/Controllers/ClientPortal/NinjaPlanController.php
@@ -15,7 +15,6 @@ namespace App\Http\Controllers\ClientPortal;
use App\DataMapper\Analytics\TrialStarted;
use App\Factory\RecurringInvoiceFactory;
use App\Http\Controllers\Controller;
-use App\Http\Requests\ClientPortal\Uploads\StoreUploadRequest;
use App\Libraries\MultiDB;
use App\Models\Account;
use App\Models\ClientContact;
@@ -28,11 +27,8 @@ use App\Models\Subscription;
use App\Notifications\Ninja\NewAccountNotification;
use App\Repositories\RecurringInvoiceRepository;
use App\Repositories\SubscriptionRepository;
-use App\Utils\Ninja;
use App\Utils\Traits\MakesHash;
-use Illuminate\Contracts\Routing\ResponseFactory;
use Illuminate\Http\Request;
-use Illuminate\Http\Response;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Auth;
use Turbo124\Beacon\Facades\LightLogs;
@@ -184,7 +180,7 @@ class NinjaPlanController extends Controller
$old_recurring = RecurringInvoice::where('company_id', config('ninja.ninja_default_company_id'))->where('client_id', $client->id)->first();
- if($old_recurring) {
+ if ($old_recurring) {
$old_recurring->service()->stop()->save();
$old_recurring_repo = new RecurringInvoiceRepository();
$old_recurring_repo->archive($old_recurring);
@@ -207,7 +203,6 @@ class NinjaPlanController extends Controller
public function plan()
{
-
// return $this->trial();
//harvest the current plan
$data = [];
diff --git a/app/Http/Controllers/ClientPortal/PaymentController.php b/app/Http/Controllers/ClientPortal/PaymentController.php
index dd7405278f17..3307eb7d2eb7 100644
--- a/app/Http/Controllers/ClientPortal/PaymentController.php
+++ b/app/Http/Controllers/ClientPortal/PaymentController.php
@@ -12,27 +12,20 @@
namespace App\Http\Controllers\ClientPortal;
-use App\Exceptions\PaymentFailed;
use App\Factory\PaymentFactory;
use App\Http\Controllers\Controller;
use App\Http\Requests\ClientPortal\Payments\PaymentResponseRequest;
-use App\Jobs\Invoice\InjectSignature;
-use App\Jobs\Util\SystemLogger;
use App\Models\CompanyGateway;
use App\Models\Invoice;
use App\Models\Payment;
use App\Models\PaymentHash;
-use App\Models\SystemLog;
use App\Services\ClientPortal\InstantPayment;
use App\Services\Subscription\SubscriptionService;
-use App\Utils\Number;
use App\Utils\Traits\MakesDates;
use App\Utils\Traits\MakesHash;
use Illuminate\Contracts\View\Factory;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
-use Illuminate\Support\Facades\Cache;
-use Illuminate\Support\Str;
use Illuminate\View\View;
/**
@@ -90,15 +83,13 @@ class PaymentController extends Controller
public function response(PaymentResponseRequest $request)
{
-
$gateway = CompanyGateway::findOrFail($request->input('company_gateway_id'));
$payment_hash = PaymentHash::where('hash', $request->payment_hash)->firstOrFail();
$invoice = Invoice::with('client')->find($payment_hash->fee_invoice_id);
$client = $invoice ? $invoice->client : auth()->guard('contact')->user()->client;
// 09-07-2022 catch duplicate responses for invoices that already paid here.
- if($invoice && $invoice->status_id == Invoice::STATUS_PAID){
-
+ if ($invoice && $invoice->status_id == Invoice::STATUS_PAID) {
$data = [
'invoice' => $invoice,
'key' => false,
@@ -110,15 +101,14 @@ class PaymentController extends Controller
}
return $this->render('invoices.show', $data);
-
}
- return $gateway
- ->driver($client)
- ->setPaymentMethod($request->input('payment_method_id'))
- ->setPaymentHash($payment_hash)
- ->checkRequirements()
- ->processPaymentResponse($request);
+ return $gateway
+ ->driver($client)
+ ->setPaymentMethod($request->input('payment_method_id'))
+ ->setPaymentHash($payment_hash)
+ ->checkRequirements()
+ ->processPaymentResponse($request);
}
/**
@@ -150,15 +140,14 @@ class PaymentController extends Controller
$invoices = Invoice::whereIn('id', $this->transformKeys(array_column($payment_hash->invoices(), 'invoice_id')));
- $invoices->each(function ($i){
+ $invoices->each(function ($i) {
$i->is_proforma = false;
$i->saveQuietly();
});
event('eloquent.created: App\Models\Payment', $payment);
- if($invoices->sum('balance') > 0){
-
+ if ($invoices->sum('balance') > 0) {
$invoice = $invoices->first();
$invoice->service()->touchPdf(true);
diff --git a/app/Http/Controllers/ClientPortal/PaymentMethodController.php b/app/Http/Controllers/ClientPortal/PaymentMethodController.php
index de3c718928a9..f281816b65e2 100644
--- a/app/Http/Controllers/ClientPortal/PaymentMethodController.php
+++ b/app/Http/Controllers/ClientPortal/PaymentMethodController.php
@@ -23,7 +23,6 @@ use App\Utils\Traits\MakesDates;
use Exception;
use Illuminate\Contracts\View\Factory;
use Illuminate\Http\RedirectResponse;
-use Illuminate\Support\Facades\Log;
use Illuminate\View\View;
class PaymentMethodController extends Controller
diff --git a/app/Http/Controllers/ClientPortal/QuoteController.php b/app/Http/Controllers/ClientPortal/QuoteController.php
index 2bde3a57816c..ca99bdfe64d0 100644
--- a/app/Http/Controllers/ClientPortal/QuoteController.php
+++ b/app/Http/Controllers/ClientPortal/QuoteController.php
@@ -13,7 +13,6 @@
namespace App\Http\Controllers\ClientPortal;
use App\Events\Misc\InvitationWasViewed;
-use App\Events\Quote\QuoteWasApproved;
use App\Events\Quote\QuoteWasViewed;
use App\Http\Controllers\Controller;
use App\Http\Requests\ClientPortal\Quotes\ProcessQuotesInBulkRequest;
@@ -22,11 +21,9 @@ use App\Http\Requests\ClientPortal\Quotes\ShowQuotesRequest;
use App\Jobs\Invoice\InjectSignature;
use App\Models\Quote;
use App\Utils\Ninja;
-use App\Utils\TempFile;
use App\Utils\Traits\MakesHash;
use Illuminate\Contracts\View\Factory;
use Illuminate\Http\Request;
-use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Storage;
use Illuminate\View\View;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
@@ -81,7 +78,7 @@ class QuoteController extends Controller
public function bulk(ProcessQuotesInBulkRequest $request)
{
$transformed_ids = $this->transformKeys($request->quotes);
-nlog(request()->all());
+ nlog(request()->all());
if ($request->action == 'download') {
return $this->downloadQuotes((array) $transformed_ids);
@@ -145,7 +142,6 @@ nlog(request()->all());
$zipFile = new \PhpZip\ZipFile();
try {
foreach ($quotes as $quote) {
-
//add it to the zip
$zipFile->addFromString(basename($quote->pdf_file_path()), file_get_contents($quote->pdf_file_path(null, 'url', true)));
}
@@ -156,7 +152,7 @@ nlog(request()->all());
$zipFile->saveAsFile($filepath) // save the archive to a file
->close(); // close archive
- return response()->download($filepath, $filename)->deleteFileAfterSend(true);
+ return response()->download($filepath, $filename)->deleteFileAfterSend(true);
} catch (\PhpZip\Exception\ZipException $e) {
// handle exception
} finally {
@@ -181,12 +177,9 @@ nlog(request()->all());
if ($process) {
foreach ($quotes as $quote) {
-
-
- if(request()->has('user_input') && strlen(request()->input('user_input')) > 2) {
-
+ if (request()->has('user_input') && strlen(request()->input('user_input')) > 2) {
$quote->public_notes .= $quote->public_notes . "\n" . request()->input('user_input');
- $quote->saveQuietly();
+ $quote->saveQuietly();
}
$quote->service()->approve(auth()->user())->save();
@@ -197,8 +190,7 @@ nlog(request()->all());
}
if (count($ids) == 1) {
-
- //forward client to the invoice if it exists
+ //forward client to the invoice if it exists
if ($quote->invoice()->exists()) {
return redirect()->route('client.invoice.show', $quote->invoice->hashed_id);
}
diff --git a/app/Http/Controllers/ClientPortal/RecurringInvoiceController.php b/app/Http/Controllers/ClientPortal/RecurringInvoiceController.php
index 7a26b9850698..fdf5e92cb78f 100644
--- a/app/Http/Controllers/ClientPortal/RecurringInvoiceController.php
+++ b/app/Http/Controllers/ClientPortal/RecurringInvoiceController.php
@@ -20,7 +20,6 @@ use App\Jobs\Mail\NinjaMailerJob;
use App\Jobs\Mail\NinjaMailerObject;
use App\Mail\RecurringInvoice\ClientContactRequestCancellationObject;
use App\Models\RecurringInvoice;
-use App\Notifications\ClientContactRequestCancellation;
use App\Utils\Traits\MakesDates;
use App\Utils\Traits\MakesHash;
use App\Utils\Traits\Notifications\UserNotifies;
@@ -51,7 +50,7 @@ class RecurringInvoiceController extends Controller
*
* @param ShowRecurringInvoiceRequest $request
* @param RecurringInvoice $recurring_invoice
- *
+ *
* @return Factory|View
*/
public function show(ShowRecurringInvoiceRequest $request, RecurringInvoice $recurring_invoice)
@@ -63,17 +62,15 @@ class RecurringInvoiceController extends Controller
/**
* Handle the request cancellation notification
- *
+ *
* @param RequestCancellationRequest $request [description]
* @param RecurringInvoice $recurring_invoice [description]
- *
+ *
* @return \Illuminate\Routing\Redirector|\Illuminate\Http\RedirectResponse
*/
public function requestCancellation(RequestCancellationRequest $request, RecurringInvoice $recurring_invoice)
{
-
if ($recurring_invoice->subscription?->allow_cancellation) {
-
$nmo = new NinjaMailerObject;
$nmo->mailable = (new NinjaMailer((new ClientContactRequestCancellationObject($recurring_invoice, auth()->user(), false))->build()));
$nmo->company = $recurring_invoice->company;
diff --git a/app/Http/Controllers/ClientPortal/SubscriptionController.php b/app/Http/Controllers/ClientPortal/SubscriptionController.php
index 393a7ed63e91..73a32f6b47de 100644
--- a/app/Http/Controllers/ClientPortal/SubscriptionController.php
+++ b/app/Http/Controllers/ClientPortal/SubscriptionController.php
@@ -16,7 +16,6 @@ use App\Http\Controllers\Controller;
use App\Http\Requests\ClientPortal\RecurringInvoices\ShowRecurringInvoiceRequest;
use App\Models\RecurringInvoice;
use App\Utils\Ninja;
-use Illuminate\Http\Request;
class SubscriptionController extends Controller
{
@@ -50,9 +49,8 @@ class SubscriptionController extends Controller
public function show(ShowRecurringInvoiceRequest $request, RecurringInvoice $recurring_invoice)
{
return $this->render('subscriptions.show', [
- 'invoice' => $recurring_invoice->load('invoices','subscription'),
+ 'invoice' => $recurring_invoice->load('invoices', 'subscription'),
'subscription' => $recurring_invoice->subscription
]);
}
-
}
diff --git a/app/Http/Controllers/ClientPortal/SubscriptionPlanSwitchController.php b/app/Http/Controllers/ClientPortal/SubscriptionPlanSwitchController.php
index 6fd26bbba7ac..f06258104ea4 100644
--- a/app/Http/Controllers/ClientPortal/SubscriptionPlanSwitchController.php
+++ b/app/Http/Controllers/ClientPortal/SubscriptionPlanSwitchController.php
@@ -16,8 +16,6 @@ use App\Http\Controllers\Controller;
use App\Http\Requests\ClientPortal\Subscriptions\ShowPlanSwitchRequest;
use App\Models\RecurringInvoice;
use App\Models\Subscription;
-use Illuminate\Http\Request;
-use Illuminate\Support\Str;
class SubscriptionPlanSwitchController extends Controller
{
@@ -31,7 +29,6 @@ class SubscriptionPlanSwitchController extends Controller
*/
public function index(ShowPlanSwitchRequest $request, RecurringInvoice $recurring_invoice, Subscription $target)
{
-
$amount = $recurring_invoice->subscription
->service()
->calculateUpgradePriceV2($recurring_invoice, $target);
@@ -45,7 +42,7 @@ class SubscriptionPlanSwitchController extends Controller
render('subscriptions.denied');
}
- $amount = max(0,$amount);
+ $amount = max(0, $amount);
return render('subscriptions.switch', [
'subscription' => $recurring_invoice->subscription,
@@ -53,7 +50,6 @@ class SubscriptionPlanSwitchController extends Controller
'target' => $target,
'amount' => $amount,
]);
-
}
public function not_availabe()
diff --git a/app/Http/Controllers/ClientPortal/SubscriptionPurchaseController.php b/app/Http/Controllers/ClientPortal/SubscriptionPurchaseController.php
index c13a1782ae60..b8d8f1fe395c 100644
--- a/app/Http/Controllers/ClientPortal/SubscriptionPurchaseController.php
+++ b/app/Http/Controllers/ClientPortal/SubscriptionPurchaseController.php
@@ -17,7 +17,6 @@ use App\Models\Subscription;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Cache;
-use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
class SubscriptionPurchaseController extends Controller
@@ -53,13 +52,11 @@ class SubscriptionPurchaseController extends Controller
$this->setLocale($request->query('locale'));
}
- if(!auth()->guard('contact')->check() && $subscription->registration_required && $subscription->company->client_can_register) {
-
- session()->put('url.intended', route('client.subscription.upgrade',['subscription' => $subscription->hashed_id]));
+ if (!auth()->guard('contact')->check() && $subscription->registration_required && $subscription->company->client_can_register) {
+ session()->put('url.intended', route('client.subscription.upgrade', ['subscription' => $subscription->hashed_id]));
return redirect()->route('client.register', ['company_key' => $subscription->company->company_key]);
- }
- elseif(!auth()->guard('contact')->check() && $subscription->registration_required && ! $subscription->company->client_can_register) {
+ } elseif (!auth()->guard('contact')->check() && $subscription->registration_required && ! $subscription->company->client_can_register) {
return render('generic.subscription_blocked', ['account' => $subscription->company->account, 'company' => $subscription->company]);
}
@@ -85,7 +82,4 @@ class SubscriptionPurchaseController extends Controller
App::setLocale($record->locale);
}
}
-
-
-
}
diff --git a/app/Http/Controllers/ClientPortal/SwitchCompanyController.php b/app/Http/Controllers/ClientPortal/SwitchCompanyController.php
index cd1cddc2b9e1..8f6dc09366dd 100644
--- a/app/Http/Controllers/ClientPortal/SwitchCompanyController.php
+++ b/app/Http/Controllers/ClientPortal/SwitchCompanyController.php
@@ -15,7 +15,6 @@ namespace App\Http\Controllers\ClientPortal;
use App\Http\Controllers\Controller;
use App\Models\ClientContact;
use App\Utils\Traits\MakesHash;
-use Illuminate\Support\Facades\Auth;
class SwitchCompanyController extends Controller
{
diff --git a/app/Http/Controllers/ClientStatementController.php b/app/Http/Controllers/ClientStatementController.php
index 846fbe5dea41..4b41d43ba361 100644
--- a/app/Http/Controllers/ClientStatementController.php
+++ b/app/Http/Controllers/ClientStatementController.php
@@ -12,14 +12,6 @@
namespace App\Http\Controllers;
use App\Http\Requests\Statements\CreateStatementRequest;
-use App\Models\Design;
-use App\Models\InvoiceInvitation;
-use App\Services\PdfMaker\Design as PdfDesignModel;
-use App\Services\PdfMaker\Design as PdfMakerDesign;
-use App\Services\PdfMaker\PdfMaker as PdfMakerService;
-use App\Utils\HostedPDF\NinjaPdf;
-use App\Utils\HtmlEngine;
-use App\Utils\PhantomJS\Phantom;
use App\Utils\Traits\MakesHash;
use App\Utils\Traits\Pdf\PdfMaker;
@@ -110,15 +102,18 @@ class ClientStatementController extends BaseController
{
$send_email = false;
- if($request->has('send_email') && $request->send_email == 'true')
+ if ($request->has('send_email') && $request->send_email == 'true') {
$send_email = true;
+ }
$pdf = $request->client()->service()->statement(
- $request->only(['start_date', 'end_date', 'show_payments_table', 'show_aging_table', 'status']), $send_email
+ $request->only(['start_date', 'end_date', 'show_payments_table', 'show_aging_table', 'status']),
+ $send_email
);
- if($send_email)
+ if ($send_email) {
return response()->json(['message' => ctrans('texts.email_queued')], 200);
+ }
if ($pdf) {
return response()->streamDownload(function () use ($pdf) {
diff --git a/app/Http/Controllers/CompanyController.php b/app/Http/Controllers/CompanyController.php
index 8253f977e058..d5575e4e9753 100644
--- a/app/Http/Controllers/CompanyController.php
+++ b/app/Http/Controllers/CompanyController.php
@@ -13,8 +13,6 @@ namespace App\Http\Controllers;
use App\DataMapper\Analytics\AccountDeleted;
use App\DataMapper\CompanySettings;
-use App\DataMapper\DefaultSettings;
-use App\Factory\CompanyFactory;
use App\Http\Requests\Company\CreateCompanyRequest;
use App\Http\Requests\Company\DefaultCompanyRequest;
use App\Http\Requests\Company\DestroyCompanyRequest;
@@ -29,7 +27,6 @@ use App\Jobs\Company\CreateCompanyTaskStatuses;
use App\Jobs\Company\CreateCompanyToken;
use App\Jobs\Mail\NinjaMailerJob;
use App\Jobs\Mail\NinjaMailerObject;
-use App\Jobs\Ninja\RefundCancelledAccount;
use App\Mail\Company\CompanyDeleted;
use App\Models\Account;
use App\Models\Company;
@@ -42,9 +39,7 @@ use App\Utils\Traits\MakesHash;
use App\Utils\Traits\SavesDocuments;
use App\Utils\Traits\Uploadable;
use Illuminate\Foundation\Bus\DispatchesJobs;
-use Illuminate\Http\Request;
use Illuminate\Http\Response;
-use Illuminate\Support\Facades\Auth;
use Turbo124\Beacon\Facades\LightLogs;
/**
diff --git a/app/Http/Controllers/CompanyGatewayController.php b/app/Http/Controllers/CompanyGatewayController.php
index 72ab74d2de06..b641344be700 100644
--- a/app/Http/Controllers/CompanyGatewayController.php
+++ b/app/Http/Controllers/CompanyGatewayController.php
@@ -29,7 +29,6 @@ use App\Repositories\CompanyRepository;
use App\Transformers\CompanyGatewayTransformer;
use App\Utils\Traits\MakesHash;
use Illuminate\Foundation\Bus\DispatchesJobs;
-use Illuminate\Http\Request;
use Illuminate\Http\Response;
/**
@@ -506,8 +505,8 @@ class CompanyGatewayController extends BaseController
->company()
->cursor()
->each(function ($company_gateway, $key) use ($action) {
- $this->company_repo->{$action}($company_gateway);
- });
+ $this->company_repo->{$action}($company_gateway);
+ });
return $this->listResponse(CompanyGateway::withTrashed()->company()->whereIn('id', $request->ids));
}
diff --git a/app/Http/Controllers/ConnectedAccountController.php b/app/Http/Controllers/ConnectedAccountController.php
index 99a7d14b8bc0..94a75fccf9ec 100644
--- a/app/Http/Controllers/ConnectedAccountController.php
+++ b/app/Http/Controllers/ConnectedAccountController.php
@@ -13,15 +13,12 @@ namespace App\Http\Controllers;
use App\Libraries\MultiDB;
use App\Libraries\OAuth\Providers\Google;
-use App\Models\CompanyUser;
use App\Models\User;
-use App\Transformers\CompanyUserTransformer;
use App\Transformers\UserTransformer;
use App\Utils\Traits\User\LoginCache;
use Google_Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
-use Illuminate\Support\Str;
use Microsoft\Graph\Model;
class ConnectedAccountController extends BaseController
@@ -95,8 +92,9 @@ class ConnectedAccountController extends BaseController
{
nlog($request->all());
- if(!$request->has('access_token'))
+ if (!$request->has('access_token')) {
return response()->json(['message' => 'No access_token parameter found!'], 400);
+ }
$graph = new \Microsoft\Graph\Graph();
$graph->setAccessToken($request->input('access_token'));
@@ -105,15 +103,15 @@ class ConnectedAccountController extends BaseController
->setReturnType(Model\User::class)
->execute();
- if($user){
-
+ if ($user) {
$email = $user->getMail() ?: $user->getUserPrincipalName();
nlog("microsoft");
nlog($email);
- if(auth()->user()->email != $email && MultiDB::checkUserEmailExists($email))
+ if (auth()->user()->email != $email && MultiDB::checkUserEmailExists($email)) {
return response()->json(['message' => ctrans('texts.email_already_register')], 400);
+ }
$connected_account = [
'email' => $email,
@@ -129,14 +127,12 @@ class ConnectedAccountController extends BaseController
$this->setLoginCache(auth()->user());
return $this->itemResponse(auth()->user());
-
}
return response()
->json(['message' => ctrans('texts.invalid_credentials')], 401)
->header('X-App-Version', config('ninja.app_version'))
->header('X-Api-Version', config('ninja.minimum_client_version'));
-
}
private function handleGoogleOauth()
diff --git a/app/Http/Controllers/Contact/LoginController.php b/app/Http/Controllers/Contact/LoginController.php
index efb9a6dce954..3ecc364402ba 100644
--- a/app/Http/Controllers/Contact/LoginController.php
+++ b/app/Http/Controllers/Contact/LoginController.php
@@ -13,8 +13,6 @@ namespace App\Http\Controllers\Contact;
use App\Http\Controllers\BaseController;
use App\Http\Controllers\Controller;
-use App\Jobs\Account\CreateAccount;
-use App\Libraries\MultiDB;
use App\Libraries\OAuth\OAuth;
use App\Models\ClientContact;
use App\Models\User;
diff --git a/app/Http/Controllers/CreditController.php b/app/Http/Controllers/CreditController.php
index 1964deb2b583..7efebce877b2 100644
--- a/app/Http/Controllers/CreditController.php
+++ b/app/Http/Controllers/CreditController.php
@@ -27,8 +27,6 @@ use App\Http\Requests\Credit\UpdateCreditRequest;
use App\Http\Requests\Credit\UploadCreditRequest;
use App\Jobs\Credit\ZipCredits;
use App\Jobs\Entity\EmailEntity;
-use App\Jobs\Invoice\EmailCredit;
-use App\Jobs\Invoice\ZipInvoices;
use App\Models\Account;
use App\Models\Client;
use App\Models\Credit;
@@ -37,7 +35,6 @@ use App\Repositories\CreditRepository;
use App\Services\PdfMaker\PdfMerge;
use App\Transformers\CreditTransformer;
use App\Utils\Ninja;
-use App\Utils\TempFile;
use App\Utils\Traits\MakesHash;
use App\Utils\Traits\SavesDocuments;
use Illuminate\Http\Response;
@@ -499,8 +496,9 @@ class CreditController extends BaseController
{
$action = $request->input('action');
- if(Ninja::isHosted() && (stripos($action, 'email') !== false) && !auth()->user()->company()->account->account_sms_verified)
+ if (Ninja::isHosted() && (stripos($action, 'email') !== false) && !auth()->user()->company()->account->account_sms_verified) {
return response(['message' => 'Please verify your account to send emails.'], 400);
+ }
$credits = Credit::withTrashed()
->whereIn('id', $request->ids)
@@ -529,18 +527,16 @@ class CreditController extends BaseController
return response()->json(['message' => ctrans('texts.sent_message')], 200);
}
- if($action == 'bulk_print' && auth()->user()->can('view', $credits->first())){
-
- $paths = $credits->map(function ($credit){
+ if ($action == 'bulk_print' && auth()->user()->can('view', $credits->first())) {
+ $paths = $credits->map(function ($credit) {
return $credit->service()->getCreditPdf($credit->invitations->first());
});
$merge = (new PdfMerge($paths->toArray()))->run();
- return response()->streamDownload(function () use ($merge) {
- echo ($merge);
- }, 'print.pdf', ['Content-Type' => 'application/pdf']);
-
+ return response()->streamDownload(function () use ($merge) {
+ echo($merge);
+ }, 'print.pdf', ['Content-Type' => 'application/pdf']);
}
$credits->each(function ($credit, $key) use ($action) {
@@ -565,7 +561,7 @@ class CreditController extends BaseController
$credit->service()->markPaid()->save();
return $this->itemResponse($credit);
- break;
+ break;
case 'clone_to_credit':
$credit = CloneCreditFactory::create($credit, auth()->user()->id);
@@ -591,7 +587,7 @@ class CreditController extends BaseController
return response()->streamDownload(function () use ($file) {
echo Storage::get($file);
}, basename($file), ['Content-Type' => 'application/pdf']);
- break;
+ break;
case 'archive':
$this->credit_repository->archive($credit);
diff --git a/app/Http/Controllers/DesignController.php b/app/Http/Controllers/DesignController.php
index 7a068f687120..677516725b4c 100644
--- a/app/Http/Controllers/DesignController.php
+++ b/app/Http/Controllers/DesignController.php
@@ -24,7 +24,6 @@ use App\Models\Design;
use App\Repositories\DesignRepository;
use App\Transformers\DesignTransformer;
use App\Utils\Traits\MakesHash;
-use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Str;
diff --git a/app/Http/Controllers/DocumentController.php b/app/Http/Controllers/DocumentController.php
index 8efa4966f124..20263da9d34b 100644
--- a/app/Http/Controllers/DocumentController.php
+++ b/app/Http/Controllers/DocumentController.php
@@ -13,7 +13,6 @@ use App\Models\Document;
use App\Repositories\DocumentRepository;
use App\Transformers\DocumentTransformer;
use App\Utils\Traits\MakesHash;
-use Illuminate\Http\Request;
use Illuminate\Http\Response;
class DocumentController extends BaseController
diff --git a/app/Http/Controllers/EmailController.php b/app/Http/Controllers/EmailController.php
index d618d8cf0dd9..69be30768391 100644
--- a/app/Http/Controllers/EmailController.php
+++ b/app/Http/Controllers/EmailController.php
@@ -13,10 +13,8 @@ namespace App\Http\Controllers;
use App\Events\Credit\CreditWasEmailed;
use App\Events\Quote\QuoteWasEmailed;
-use App\Http\Middleware\UserVerified;
use App\Http\Requests\Email\SendEmailRequest;
use App\Jobs\Entity\EmailEntity;
-use App\Jobs\Mail\EntitySentMailer;
use App\Jobs\PurchaseOrder\PurchaseOrderEmail;
use App\Models\Credit;
use App\Models\Invoice;
@@ -135,15 +133,15 @@ class EmailController extends BaseController
$mo->entity_string = $entity;
$mo->email_template = $template;
- if(Ninja::isHosted() && !$entity_obj->company->account->account_sms_verified)
- return response(['message' => 'Please verify your account to send emails.'], 400);
+ if (Ninja::isHosted() && !$entity_obj->company->account->account_sms_verified) {
+ return response(['message' => 'Please verify your account to send emails.'], 400);
+ }
- if($entity == 'purchaseOrder' || $entity == 'purchase_order' || $template == 'purchase_order' || $entity == 'App\Models\PurchaseOrder'){
+ if ($entity == 'purchaseOrder' || $entity == 'purchase_order' || $template == 'purchase_order' || $entity == 'App\Models\PurchaseOrder') {
return $this->sendPurchaseOrder($entity_obj, $data, $template);
}
$entity_obj->invitations->each(function ($invitation) use ($data, $entity_string, $entity_obj, $template, $mo) {
-
if (! $invitation->contact->trashed() && $invitation->contact->email) {
$entity_obj->service()->markSent()->save();
@@ -151,7 +149,6 @@ class EmailController extends BaseController
// MailEntity::dispatch($invitation, $invitation->company->db, $mo);
}
-
});
$entity_obj = $entity_obj->fresh();
@@ -196,7 +193,6 @@ class EmailController extends BaseController
private function sendPurchaseOrder($entity_obj, $data, $template)
{
-
$this->entity_type = PurchaseOrder::class;
$this->entity_transformer = PurchaseOrderTransformer::class;
@@ -206,6 +202,5 @@ class EmailController extends BaseController
PurchaseOrderEmail::dispatch($entity_obj, $entity_obj->company, $data);
return $this->itemResponse($entity_obj);
-
}
}
diff --git a/app/Http/Controllers/ExpenseController.php b/app/Http/Controllers/ExpenseController.php
index 5e17dbdd6220..5b88ab9ea3ff 100644
--- a/app/Http/Controllers/ExpenseController.php
+++ b/app/Http/Controllers/ExpenseController.php
@@ -31,7 +31,6 @@ use App\Utils\Traits\BulkOptions;
use App\Utils\Traits\MakesHash;
use App\Utils\Traits\SavesDocuments;
use App\Utils\Traits\Uploadable;
-use Illuminate\Http\Request;
use Illuminate\Http\Response;
/**
diff --git a/app/Http/Controllers/FilterController.php b/app/Http/Controllers/FilterController.php
index e957298d8642..270a2c4e1d81 100644
--- a/app/Http/Controllers/FilterController.php
+++ b/app/Http/Controllers/FilterController.php
@@ -11,9 +11,7 @@
namespace App\Http\Controllers;
-use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Http\Request;
-use Illuminate\Http\Response;
class FilterController extends BaseController
{
@@ -33,7 +31,6 @@ class FilterController extends BaseController
$entity_filters = [];
switch ($entity) {
-
case 'invoice':
$entity_filters = ['bulk_download', 'mark_paid', 'mark_sent', 'download', 'cancel', 'email'];
break;
@@ -53,7 +50,6 @@ class FilterController extends BaseController
case 'recurring_invoice':
$entity_filters = ['bulk_download', 'start', 'stop', 'email'];
break;
-
}
return response()->json(array_merge($this->base_filters, $entity_filters), 200);
diff --git a/app/Http/Controllers/Gateways/Mollie3dsController.php b/app/Http/Controllers/Gateways/Mollie3dsController.php
index 15bdc60261ac..3eab60b6a537 100644
--- a/app/Http/Controllers/Gateways/Mollie3dsController.php
+++ b/app/Http/Controllers/Gateways/Mollie3dsController.php
@@ -14,7 +14,6 @@ namespace App\Http\Controllers\Gateways;
use App\Http\Controllers\Controller;
use App\Http\Requests\Gateways\Mollie\Mollie3dsRequest;
-use App\Models\PaymentHash;
class Mollie3dsController extends Controller
{
diff --git a/app/Http/Controllers/GroupSettingController.php b/app/Http/Controllers/GroupSettingController.php
index 4c9ee3cbd351..bafcdd17c728 100644
--- a/app/Http/Controllers/GroupSettingController.php
+++ b/app/Http/Controllers/GroupSettingController.php
@@ -27,7 +27,6 @@ use App\Utils\Traits\MakesHash;
use App\Utils\Traits\SavesDocuments;
use App\Utils\Traits\Uploadable;
use Illuminate\Foundation\Bus\DispatchesJobs;
-use Illuminate\Http\Request;
use Illuminate\Http\Response;
class GroupSettingController extends BaseController
diff --git a/app/Http/Controllers/HostedMigrationController.php b/app/Http/Controllers/HostedMigrationController.php
index 5ef26c869f67..479b8d0d137a 100644
--- a/app/Http/Controllers/HostedMigrationController.php
+++ b/app/Http/Controllers/HostedMigrationController.php
@@ -13,12 +13,9 @@ namespace App\Http\Controllers;
use App\Jobs\Account\CreateAccount;
use App\Libraries\MultiDB;
-use App\Models\Client;
-use App\Models\ClientContact;
use App\Models\Company;
use App\Models\CompanyToken;
use Illuminate\Http\Request;
-use Illuminate\Support\Facades\Artisan;
class HostedMigrationController extends Controller
{
diff --git a/app/Http/Controllers/ImportController.php b/app/Http/Controllers/ImportController.php
index 3f19741c1407..4d0634265176 100644
--- a/app/Http/Controllers/ImportController.php
+++ b/app/Http/Controllers/ImportController.php
@@ -159,14 +159,15 @@ class ImportController extends Controller
public function detectDelimiter($csvfile)
{
- $delimiters = array(',', '.', ';');
+ $delimiters = [',', '.', ';'];
$bestDelimiter = ' ';
$count = 0;
- foreach ($delimiters as $delimiter)
+ foreach ($delimiters as $delimiter) {
if (substr_count($csvfile, $delimiter) > $count) {
$count = substr_count($csvfile, $delimiter);
$bestDelimiter = $delimiter;
}
+ }
return $bestDelimiter;
}
}
diff --git a/app/Http/Controllers/ImportJsonController.php b/app/Http/Controllers/ImportJsonController.php
index 62ac13e7db24..309e70066bfe 100644
--- a/app/Http/Controllers/ImportJsonController.php
+++ b/app/Http/Controllers/ImportJsonController.php
@@ -11,17 +11,11 @@
namespace App\Http\Controllers;
-use App\Exceptions\NonExistingMigrationFile;
use App\Http\Requests\Import\ImportJsonRequest;
-use App\Jobs\Company\CompanyExport;
use App\Jobs\Company\CompanyImport;
use App\Utils\Ninja;
use App\Utils\Traits\MakesHash;
use Illuminate\Http\Response;
-use Illuminate\Support\Facades\Cache;
-use Illuminate\Support\Facades\Storage;
-use Illuminate\Support\Str;
-use ZipArchive;
class ImportJsonController extends BaseController
{
diff --git a/app/Http/Controllers/InAppPurchase/AppleController.php b/app/Http/Controllers/InAppPurchase/AppleController.php
index f4e0bfd39190..8f3f385c7545 100644
--- a/app/Http/Controllers/InAppPurchase/AppleController.php
+++ b/app/Http/Controllers/InAppPurchase/AppleController.php
@@ -58,7 +58,6 @@ class AppleController extends BaseController
*/
public function confirm_purchase(Request $request)
{
-
//store transaction_id in accounts table for future reference.
}
diff --git a/app/Http/Controllers/InvoiceController.php b/app/Http/Controllers/InvoiceController.php
index f8214c1a134d..fb7cde006ec1 100644
--- a/app/Http/Controllers/InvoiceController.php
+++ b/app/Http/Controllers/InvoiceController.php
@@ -29,13 +29,11 @@ use App\Http\Requests\Invoice\UpdateInvoiceRequest;
use App\Http\Requests\Invoice\UpdateReminderRequest;
use App\Http\Requests\Invoice\UploadInvoiceRequest;
use App\Jobs\Cron\AutoBill;
-use App\Jobs\Entity\EmailEntity;
use App\Jobs\Invoice\BulkInvoiceJob;
use App\Jobs\Invoice\StoreInvoice;
use App\Jobs\Invoice\UpdateReminders;
use App\Jobs\Invoice\ZipInvoices;
use App\Jobs\Ninja\TransactionLog;
-use App\Jobs\Util\UnlinkFile;
use App\Models\Account;
use App\Models\Client;
use App\Models\Invoice;
@@ -46,12 +44,10 @@ use App\Services\PdfMaker\PdfMerge;
use App\Transformers\InvoiceTransformer;
use App\Transformers\QuoteTransformer;
use App\Utils\Ninja;
-use App\Utils\TempFile;
use App\Utils\Traits\MakesHash;
use App\Utils\Traits\SavesDocuments;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
-use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
/**
@@ -536,8 +532,9 @@ class InvoiceController extends BaseController
$ids = $request->input('ids');
- if(Ninja::isHosted() && (stripos($action, 'email') !== false) && !auth()->user()->company()->account->account_sms_verified)
+ if (Ninja::isHosted() && (stripos($action, 'email') !== false) && !auth()->user()->company()->account->account_sms_verified) {
return response(['message' => 'Please verify your account to send emails.'], 400);
+ }
$invoices = Invoice::withTrashed()->whereIn('id', $this->transformKeys($ids))->company()->get();
@@ -563,28 +560,24 @@ class InvoiceController extends BaseController
return response()->json(['message' => ctrans('texts.sent_message')], 200);
}
- if($action == 'download' && $invoices->count() >=1 && auth()->user()->can('view', $invoices->first())) {
-
- $file = $invoices->first()->service()->getInvoicePdf();
-
- return response()->streamDownload(function () use ($file) {
- echo Storage::get($file);
- }, basename($file), ['Content-Type' => 'application/pdf']);
+ if ($action == 'download' && $invoices->count() >=1 && auth()->user()->can('view', $invoices->first())) {
+ $file = $invoices->first()->service()->getInvoicePdf();
+ return response()->streamDownload(function () use ($file) {
+ echo Storage::get($file);
+ }, basename($file), ['Content-Type' => 'application/pdf']);
}
- if($action == 'bulk_print' && auth()->user()->can('view', $invoices->first())){
-
- $paths = $invoices->map(function ($invoice){
+ if ($action == 'bulk_print' && auth()->user()->can('view', $invoices->first())) {
+ $paths = $invoices->map(function ($invoice) {
return $invoice->service()->getInvoicePdf();
});
$merge = (new PdfMerge($paths->toArray()))->run();
- return response()->streamDownload(function () use ($merge) {
- echo ($merge);
- }, 'print.pdf', ['Content-Type' => 'application/pdf']);
-
+ return response()->streamDownload(function () use ($merge) {
+ echo($merge);
+ }, 'print.pdf', ['Content-Type' => 'application/pdf']);
}
/*
diff --git a/app/Http/Controllers/LicenseController.php b/app/Http/Controllers/LicenseController.php
index 0e6916679211..88e04574d928 100644
--- a/app/Http/Controllers/LicenseController.php
+++ b/app/Http/Controllers/LicenseController.php
@@ -14,7 +14,6 @@ namespace App\Http\Controllers;
use App\Models\Account;
use App\Utils\CurlUtils;
use Carbon\Carbon;
-use Illuminate\Http\Request;
use Illuminate\Http\Response;
use stdClass;
diff --git a/app/Http/Controllers/LogoutController.php b/app/Http/Controllers/LogoutController.php
index 9007888b70a4..2889b777d0dd 100644
--- a/app/Http/Controllers/LogoutController.php
+++ b/app/Http/Controllers/LogoutController.php
@@ -14,8 +14,6 @@ namespace App\Http\Controllers;
use App\Models\CompanyToken;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
-use stdClass;
-use Symfony\Component\HttpFoundation\StreamedResponse;
class LogoutController extends BaseController
{
diff --git a/app/Http/Controllers/OneTimeTokenController.php b/app/Http/Controllers/OneTimeTokenController.php
index 6362287e1444..a271fc7b0b3e 100644
--- a/app/Http/Controllers/OneTimeTokenController.php
+++ b/app/Http/Controllers/OneTimeTokenController.php
@@ -14,7 +14,6 @@ namespace App\Http\Controllers;
use App\Http\Requests\OneTimeToken\OneTimeRouterRequest;
use App\Http\Requests\OneTimeToken\OneTimeTokenRequest;
use App\Models\Company;
-use App\Models\CompanyUser;
use App\Models\User;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
diff --git a/app/Http/Controllers/OpenAPI/BankTransactionRule.php b/app/Http/Controllers/OpenAPI/BankTransactionRule.php
index 522b1764b265..fa62eb3a39ea 100644
--- a/app/Http/Controllers/OpenAPI/BankTransactionRule.php
+++ b/app/Http/Controllers/OpenAPI/BankTransactionRule.php
@@ -22,4 +22,4 @@
* @OA\Property(property="vendor_id", type="string", example="AS3df3A", description="The vendor hashed id"),
* @OA\Property(property="category_id", type="string", example="AS3df3A", description="The category hashed id"),
* )
- */
\ No newline at end of file
+ */
diff --git a/app/Http/Controllers/PaymentController.php b/app/Http/Controllers/PaymentController.php
index 5db41cfb45b1..e6bc57408d6d 100644
--- a/app/Http/Controllers/PaymentController.php
+++ b/app/Http/Controllers/PaymentController.php
@@ -584,7 +584,7 @@ class PaymentController extends BaseController
{
switch ($action) {
case 'restore':
- $this->payment_repo->restore($payment);
+ $this->payment_repo->restore($payment);
if (! $bulk) {
return $this->itemResponse($payment);
@@ -592,7 +592,7 @@ class PaymentController extends BaseController
break;
case 'archive':
- $this->payment_repo->archive($payment);
+ $this->payment_repo->archive($payment);
if (! $bulk) {
return $this->itemResponse($payment);
@@ -600,7 +600,7 @@ class PaymentController extends BaseController
// code...
break;
case 'delete':
- $this->payment_repo->delete($payment);
+ $this->payment_repo->delete($payment);
if (! $bulk) {
return $this->itemResponse($payment);
diff --git a/app/Http/Controllers/PaymentNotificationWebhookController.php b/app/Http/Controllers/PaymentNotificationWebhookController.php
index 0a4f1f7e59db..5e9510caa184 100644
--- a/app/Http/Controllers/PaymentNotificationWebhookController.php
+++ b/app/Http/Controllers/PaymentNotificationWebhookController.php
@@ -13,11 +13,9 @@
namespace App\Http\Controllers;
use App\Http\Requests\Payments\PaymentNotificationWebhookRequest;
-use App\Libraries\MultiDB;
use App\Models\Client;
use App\Models\CompanyGateway;
use App\Utils\Traits\MakesHash;
-use Auth;
class PaymentNotificationWebhookController extends Controller
{
diff --git a/app/Http/Controllers/PaymentWebhookController.php b/app/Http/Controllers/PaymentWebhookController.php
index 5c394b44cdf3..4704dc14f5c4 100644
--- a/app/Http/Controllers/PaymentWebhookController.php
+++ b/app/Http/Controllers/PaymentWebhookController.php
@@ -19,8 +19,9 @@ class PaymentWebhookController extends Controller
public function __invoke(PaymentWebhookRequest $request)
{
//return early if we cannot resolve the company gateway
- if(!$request->getCompanyGateway())
+ if (!$request->getCompanyGateway()) {
return response()->json([], 200);
+ }
return $request
->getCompanyGateway()
diff --git a/app/Http/Controllers/PostMarkController.php b/app/Http/Controllers/PostMarkController.php
index 4acfb7b8d497..5639d3ccd308 100644
--- a/app/Http/Controllers/PostMarkController.php
+++ b/app/Http/Controllers/PostMarkController.php
@@ -11,20 +11,8 @@
namespace App\Http\Controllers;
-use App\DataMapper\Analytics\Mail\EmailBounce;
-use App\DataMapper\Analytics\Mail\EmailSpam;
use App\Jobs\PostMark\ProcessPostmarkWebhook;
-use App\Jobs\Util\SystemLogger;
-use App\Libraries\MultiDB;
-use App\Models\CreditInvitation;
-use App\Models\InvoiceInvitation;
-use App\Models\QuoteInvitation;
-use App\Models\RecurringInvoiceInvitation;
-use App\Models\SystemLog;
-use App\Notifications\Ninja\EmailBounceNotification;
-use App\Notifications\Ninja\EmailSpamNotification;
use Illuminate\Http\Request;
-use Turbo124\Beacon\Facades\LightLogs;
/**
* Class PostMarkController.
diff --git a/app/Http/Controllers/PreviewController.php b/app/Http/Controllers/PreviewController.php
index 216f8c0e5704..e69a12e22f3c 100644
--- a/app/Http/Controllers/PreviewController.php
+++ b/app/Http/Controllers/PreviewController.php
@@ -32,9 +32,9 @@ use App\Repositories\CreditRepository;
use App\Repositories\InvoiceRepository;
use App\Repositories\QuoteRepository;
use App\Repositories\RecurringInvoiceRepository;
+use App\Services\PdfMaker\Design;
use App\Services\PdfMaker\Design as PdfDesignModel;
use App\Services\PdfMaker\Design as PdfMakerDesign;
-use App\Services\PdfMaker\Design;
use App\Services\PdfMaker\PdfMaker;
use App\Utils\HostedPDF\NinjaPdf;
use App\Utils\HtmlEngine;
@@ -177,8 +177,9 @@ class PreviewController extends BaseController
public function design(DesignPreviewRequest $request)
{
- if(Ninja::isHosted() && $request->getHost() != 'preview.invoicing.co')
+ if (Ninja::isHosted() && $request->getHost() != 'preview.invoicing.co') {
return response()->json(['message' => 'This server cannot handle this request.'], 400);
+ }
$company = auth()->user()->company();
@@ -214,34 +215,34 @@ class PreviewController extends BaseController
->first();
}
- if($request->has('client_id')) {
+ if ($request->has('client_id')) {
$client = Client::withTrashed()->find($this->decodePrimaryKey($request->client_id));
- if($request->settings_type == 'client'){
- $client->settings = $request->settings;
- $client->save();
- }
-
+ if ($request->settings_type == 'client') {
+ $client->settings = $request->settings;
+ $client->save();
+ }
}
- if($request->has('group_id')) {
+ if ($request->has('group_id')) {
$group = GroupSetting::withTrashed()->find($this->decodePrimaryKey($request->group_id));
- if($request->settings_type == 'group'){
- $group->settings = $request->settings;
- $group->save();
- }
-
+ if ($request->settings_type == 'group') {
+ $group->settings = $request->settings;
+ $group->save();
+ }
}
- if($request->settings_type == 'company'){
+ if ($request->settings_type == 'company') {
$company->settings = $request->settings;
$company->save();
}
- if($request->has('footer') && !$request->filled('footer') && $request->input('entity') == 'recurring_invoice')
+ if ($request->has('footer') && !$request->filled('footer') && $request->input('entity') == 'recurring_invoice') {
$request->merge(['footer' => $company->settings->invoice_footer]);
+ }
- if($request->has('terms') && !$request->filled('terms') && $request->input('entity') == 'recurring_invoice')
+ if ($request->has('terms') && !$request->filled('terms') && $request->input('entity') == 'recurring_invoice') {
$request->merge(['terms' => $company->settings->invoice_terms]);
+ }
$entity_obj = $repo->save($request->all(), $entity_obj);
@@ -302,9 +303,7 @@ class PreviewController extends BaseController
nlog($maker->getCompiledHTML());
return $maker->getCompiledHTML();
}
-
- }
- catch(\Exception $e){
+ } catch(\Exception $e) {
nlog($e->getMessage());
DB::connection(config('database.default'))->rollBack();
@@ -316,36 +315,34 @@ class PreviewController extends BaseController
return (new Phantom)->convertHtmlToPdf($maker->getCompiledHTML(true));
}
- if(config('ninja.invoiceninja_hosted_pdf_generation') || config('ninja.pdf_generator') == 'hosted_ninja'){
+ if (config('ninja.invoiceninja_hosted_pdf_generation') || config('ninja.pdf_generator') == 'hosted_ninja') {
$pdf = (new NinjaPdf())->build($maker->getCompiledHTML(true));
$numbered_pdf = $this->pageNumbering($pdf, auth()->user()->company());
- $numbered_pdf = $this->pageNumbering($pdf, auth()->user()->company());
+ $numbered_pdf = $this->pageNumbering($pdf, auth()->user()->company());
- if ($numbered_pdf) {
- $pdf = $numbered_pdf;
+ if ($numbered_pdf) {
+ $pdf = $numbered_pdf;
+ }
+
+ return $pdf;
}
- return $pdf;
- }
-
$file_path = (new PreviewPdf($maker->getCompiledHTML(true), $company))->handle();
$response = Response::make($file_path, 200);
$response->header('Content-Type', 'application/pdf');
return $response;
-
-
-
}
public function live(PreviewInvoiceRequest $request)
{
- if(Ninja::isHosted() && $request->getHost() != 'preview.invoicing.co')
+ if (Ninja::isHosted() && $request->getHost() != 'preview.invoicing.co') {
return response()->json(['message' => 'This server cannot handle this request.'], 400);
+ }
$company = auth()->user()->company();
@@ -381,11 +378,13 @@ class PreviewController extends BaseController
->first();
}
- if($request->has('footer') && !$request->filled('footer') && $request->input('entity') == 'recurring_invoice')
+ if ($request->has('footer') && !$request->filled('footer') && $request->input('entity') == 'recurring_invoice') {
$request->merge(['footer' => $company->settings->invoice_footer]);
+ }
- if($request->has('terms') && !$request->filled('terms') && $request->input('entity') == 'recurring_invoice')
+ if ($request->has('terms') && !$request->filled('terms') && $request->input('entity') == 'recurring_invoice') {
$request->merge(['terms' => $company->settings->invoice_terms]);
+ }
$entity_obj = $repo->save($request->all(), $entity_obj);
@@ -445,9 +444,7 @@ class PreviewController extends BaseController
if (request()->query('html') == 'true') {
return $maker->getCompiledHTML();
}
-
- }
- catch(\Exception $e){
+ } catch(\Exception $e) {
nlog($e->getMessage());
DB::connection(config('database.default'))->rollBack();
@@ -459,21 +456,21 @@ class PreviewController extends BaseController
return (new Phantom)->convertHtmlToPdf($maker->getCompiledHTML(true));
}
- if(config('ninja.invoiceninja_hosted_pdf_generation') || config('ninja.pdf_generator') == 'hosted_ninja'){
+ if (config('ninja.invoiceninja_hosted_pdf_generation') || config('ninja.pdf_generator') == 'hosted_ninja') {
$pdf = (new NinjaPdf())->build($maker->getCompiledHTML(true));
$numbered_pdf = $this->pageNumbering($pdf, auth()->user()->company());
- $numbered_pdf = $this->pageNumbering($pdf, auth()->user()->company());
+ $numbered_pdf = $this->pageNumbering($pdf, auth()->user()->company());
- if ($numbered_pdf) {
- $pdf = $numbered_pdf;
+ if ($numbered_pdf) {
+ $pdf = $numbered_pdf;
+ }
+
+ return $pdf;
}
- return $pdf;
- }
-
$file_path = (new PreviewPdf($maker->getCompiledHTML(true), $company))->handle();
if (Ninja::isHosted()) {
diff --git a/app/Http/Controllers/PreviewPurchaseOrderController.php b/app/Http/Controllers/PreviewPurchaseOrderController.php
index e22d6feabb18..284286733fc0 100644
--- a/app/Http/Controllers/PreviewPurchaseOrderController.php
+++ b/app/Http/Controllers/PreviewPurchaseOrderController.php
@@ -12,38 +12,21 @@
namespace App\Http\Controllers;
use App\DataMapper\Analytics\LivePreview;
-use App\Factory\CreditFactory;
-use App\Factory\InvoiceFactory;
use App\Factory\PurchaseOrderFactory;
-use App\Factory\QuoteFactory;
-use App\Factory\RecurringInvoiceFactory;
-use App\Http\Requests\Invoice\StoreInvoiceRequest;
-use App\Http\Requests\Preview\PreviewInvoiceRequest;
use App\Http\Requests\Preview\PreviewPurchaseOrderRequest;
use App\Jobs\Util\PreviewPdf;
use App\Libraries\MultiDB;
use App\Models\Client;
-use App\Models\ClientContact;
-use App\Models\Credit;
-use App\Models\Invoice;
-use App\Models\InvoiceInvitation;
use App\Models\PurchaseOrder;
use App\Models\PurchaseOrderInvitation;
-use App\Models\Quote;
-use App\Models\RecurringInvoice;
use App\Models\Vendor;
use App\Models\VendorContact;
-use App\Repositories\CreditRepository;
-use App\Repositories\InvoiceRepository;
use App\Repositories\PurchaseOrderRepository;
-use App\Repositories\QuoteRepository;
-use App\Repositories\RecurringInvoiceRepository;
+use App\Services\PdfMaker\Design;
use App\Services\PdfMaker\Design as PdfDesignModel;
use App\Services\PdfMaker\Design as PdfMakerDesign;
-use App\Services\PdfMaker\Design;
use App\Services\PdfMaker\PdfMaker;
use App\Utils\HostedPDF\NinjaPdf;
-use App\Utils\HtmlEngine;
use App\Utils\Ninja;
use App\Utils\PhantomJS\Phantom;
use App\Utils\Traits\MakesHash;
@@ -52,7 +35,6 @@ use App\Utils\Traits\Pdf\PageNumbering;
use App\Utils\VendorHtmlEngine;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\DB;
-use Illuminate\Support\Facades\Lang;
use Illuminate\Support\Facades\Response;
use Turbo124\Beacon\Facades\LightLogs;
@@ -107,7 +89,6 @@ class PreviewPurchaseOrderController extends BaseController
! empty(request()->input('entity')) &&
! empty(request()->input('entity_id')) &&
request()->has('body')) {
-
$design_object = json_decode(json_encode(request()->input('design')));
if (! is_object($design_object)) {
@@ -159,16 +140,16 @@ class PreviewPurchaseOrderController extends BaseController
return (new Phantom)->convertHtmlToPdf($maker->getCompiledHTML(true));
}
- if(config('ninja.invoiceninja_hosted_pdf_generation') || config('ninja.pdf_generator') == 'hosted_ninja'){
+ if (config('ninja.invoiceninja_hosted_pdf_generation') || config('ninja.pdf_generator') == 'hosted_ninja') {
$pdf = (new NinjaPdf())->build($maker->getCompiledHTML(true));
$numbered_pdf = $this->pageNumbering($pdf, auth()->user()->company());
- if($numbered_pdf)
+ if ($numbered_pdf) {
$pdf = $numbered_pdf;
+ }
return $pdf;
-
}
//else
@@ -191,24 +172,22 @@ class PreviewPurchaseOrderController extends BaseController
$class = PurchaseOrder::class;
try {
-
DB::connection(config('database.default'))->beginTransaction();
- if($request->has('entity_id')){
-
+ if ($request->has('entity_id')) {
$entity_obj = $class::on(config('database.default'))
->with('vendor.company')
->where('id', $this->decodePrimaryKey($request->input('entity_id')))
->where('company_id', $company->id)
->withTrashed()
->first();
-
}
$entity_obj = $repo->save($request->all(), $entity_obj);
- if(!$request->has('entity_id'))
+ if (!$request->has('entity_id')) {
$entity_obj->service()->fillDefaults()->save();
+ }
App::forgetInstance('translator');
$t = app('translator');
@@ -220,8 +199,9 @@ class PreviewPurchaseOrderController extends BaseController
$design = \App\Models\Design::find($entity_obj->design_id);
/* Catch all in case migration doesn't pass back a valid design */
- if(!$design)
+ if (!$design) {
$design = \App\Models\Design::find(2);
+ }
if ($design->is_custom) {
$options = [
@@ -258,11 +238,7 @@ class PreviewPurchaseOrderController extends BaseController
if (request()->query('html') == 'true') {
return $maker->getCompiledHTML();
}
-
-
- }
- catch(\Exception $e){
-
+ } catch(\Exception $e) {
DB::connection(config('database.default'))->rollBack();
return;
}
@@ -273,13 +249,14 @@ class PreviewPurchaseOrderController extends BaseController
return (new Phantom)->convertHtmlToPdf($maker->getCompiledHTML(true));
}
- if(config('ninja.invoiceninja_hosted_pdf_generation') || config('ninja.pdf_generator') == 'hosted_ninja'){
+ if (config('ninja.invoiceninja_hosted_pdf_generation') || config('ninja.pdf_generator') == 'hosted_ninja') {
$pdf = (new NinjaPdf())->build($maker->getCompiledHTML(true));
$numbered_pdf = $this->pageNumbering($pdf, auth()->user()->company());
- if($numbered_pdf)
+ if ($numbered_pdf) {
$pdf = $numbered_pdf;
+ }
return $pdf;
}
@@ -287,19 +264,17 @@ class PreviewPurchaseOrderController extends BaseController
$file_path = (new PreviewPdf($maker->getCompiledHTML(true), $company))->handle();
- if(Ninja::isHosted())
- {
- LightLogs::create(new LivePreview())
- ->increment()
- ->batch();
- }
+ if (Ninja::isHosted()) {
+ LightLogs::create(new LivePreview())
+ ->increment()
+ ->batch();
+ }
$response = Response::make($file_path, 200);
$response->header('Content-Type', 'application/pdf');
return $response;
-
}
private function blankEntity()
@@ -311,8 +286,9 @@ class PreviewPurchaseOrderController extends BaseController
$invitation = PurchaseOrderInvitation::where('company_id', auth()->user()->company()->id)->orderBy('id', 'desc')->first();
/* If we don't have a valid invitation in the system - create a mock using transactions */
- if(!$invitation)
+ if (!$invitation) {
return $this->mockEntity();
+ }
$design_object = json_decode(json_encode(request()->input('design')));
@@ -351,15 +327,16 @@ class PreviewPurchaseOrderController extends BaseController
return (new Phantom)->convertHtmlToPdf($maker->getCompiledHTML(true));
}
- if(config('ninja.invoiceninja_hosted_pdf_generation') || config('ninja.pdf_generator') == 'hosted_ninja'){
+ if (config('ninja.invoiceninja_hosted_pdf_generation') || config('ninja.pdf_generator') == 'hosted_ninja') {
$pdf = (new NinjaPdf())->build($maker->getCompiledHTML(true));
$numbered_pdf = $this->pageNumbering($pdf, auth()->user()->company());
- if($numbered_pdf)
- $pdf = $numbered_pdf;
+ if ($numbered_pdf) {
+ $pdf = $numbered_pdf;
+ }
- return $pdf;
+ return $pdf;
}
$file_path = (new PreviewPdf($maker->getCompiledHTML(true), auth()->user()->company()))->handle();
@@ -368,12 +345,10 @@ class PreviewPurchaseOrderController extends BaseController
$response->header('Content-Type', 'application/pdf');
return $response;
-
}
private function mockEntity()
{
-
DB::connection(auth()->user()->company()->db)->beginTransaction();
$vendor = Vendor::factory()->create([
@@ -448,15 +423,16 @@ class PreviewPurchaseOrderController extends BaseController
return (new Phantom)->convertHtmlToPdf($maker->getCompiledHTML(true));
}
- if(config('ninja.invoiceninja_hosted_pdf_generation') || config('ninja.pdf_generator') == 'hosted_ninja'){
+ if (config('ninja.invoiceninja_hosted_pdf_generation') || config('ninja.pdf_generator') == 'hosted_ninja') {
$pdf = (new NinjaPdf())->build($maker->getCompiledHTML(true));
$numbered_pdf = $this->pageNumbering($pdf, auth()->user()->company());
- if($numbered_pdf)
- $pdf = $numbered_pdf;
+ if ($numbered_pdf) {
+ $pdf = $numbered_pdf;
+ }
- return $pdf;
+ return $pdf;
}
$file_path = (new PreviewPdf($maker->getCompiledHTML(true), auth()->user()->company()))->handle();
diff --git a/app/Http/Controllers/ProductController.php b/app/Http/Controllers/ProductController.php
index e865b811d582..010d656c951f 100644
--- a/app/Http/Controllers/ProductController.php
+++ b/app/Http/Controllers/ProductController.php
@@ -26,7 +26,6 @@ use App\Repositories\ProductRepository;
use App\Transformers\ProductTransformer;
use App\Utils\Traits\MakesHash;
use App\Utils\Traits\SavesDocuments;
-use Illuminate\Http\Request;
use Illuminate\Http\Response;
class ProductController extends BaseController
diff --git a/app/Http/Controllers/ProjectController.php b/app/Http/Controllers/ProjectController.php
index fb2a5ef316e9..fc921b191242 100644
--- a/app/Http/Controllers/ProjectController.php
+++ b/app/Http/Controllers/ProjectController.php
@@ -27,7 +27,6 @@ use App\Transformers\ProjectTransformer;
use App\Utils\Traits\GeneratesCounter;
use App\Utils\Traits\MakesHash;
use App\Utils\Traits\SavesDocuments;
-use Illuminate\Http\Request;
use Illuminate\Http\Response;
/**
diff --git a/app/Http/Controllers/PurchaseOrderController.php b/app/Http/Controllers/PurchaseOrderController.php
index c77c95a27083..51ae86e9e3ed 100644
--- a/app/Http/Controllers/PurchaseOrderController.php
+++ b/app/Http/Controllers/PurchaseOrderController.php
@@ -11,7 +11,6 @@
namespace App\Http\Controllers;
-
use App\Events\PurchaseOrder\PurchaseOrderWasCreated;
use App\Events\PurchaseOrder\PurchaseOrderWasUpdated;
use App\Factory\PurchaseOrderFactory;
@@ -25,16 +24,13 @@ use App\Http\Requests\PurchaseOrder\ShowPurchaseOrderRequest;
use App\Http\Requests\PurchaseOrder\StorePurchaseOrderRequest;
use App\Http\Requests\PurchaseOrder\UpdatePurchaseOrderRequest;
use App\Http\Requests\PurchaseOrder\UploadPurchaseOrderRequest;
-use App\Jobs\Invoice\ZipInvoices;
use App\Jobs\PurchaseOrder\PurchaseOrderEmail;
use App\Jobs\PurchaseOrder\ZipPurchaseOrders;
use App\Models\Account;
use App\Models\Client;
-use App\Models\Expense;
use App\Models\PurchaseOrder;
use App\Repositories\PurchaseOrderRepository;
use App\Services\PdfMaker\PdfMerge;
-use App\Transformers\ExpenseTransformer;
use App\Transformers\PurchaseOrderTransformer;
use App\Utils\Ninja;
use App\Utils\Traits\MakesHash;
@@ -186,7 +182,6 @@ class PurchaseOrderController extends BaseController
*/
public function store(StorePurchaseOrderRequest $request)
{
-
$purchase_order = $this->purchase_order_repository->save($request->all(), PurchaseOrderFactory::create(auth()->user()->company()->id, auth()->user()->id));
$purchase_order = $purchase_order->service()
@@ -478,13 +473,13 @@ class PurchaseOrderController extends BaseController
*/
public function bulk(BulkPurchaseOrderRequest $request)
{
-
$action = $request->input('action');
$ids = $request->input('ids');
- if(Ninja::isHosted() && (stripos($action, 'email') !== false) && !auth()->user()->company()->account->account_sms_verified)
+ if (Ninja::isHosted() && (stripos($action, 'email') !== false) && !auth()->user()->company()->account->account_sms_verified) {
return response(['message' => 'Please verify your account to send emails.'], 400);
+ }
$purchase_orders = PurchaseOrder::withTrashed()->whereIn('id', $this->transformKeys($ids))->company()->get();
@@ -507,18 +502,16 @@ class PurchaseOrderController extends BaseController
return response()->json(['message' => ctrans('texts.sent_message')], 200);
}
- if($action == 'bulk_print' && auth()->user()->can('view', $purchase_orders->first())){
-
- $paths = $purchase_orders->map(function ($purchase_order){
+ if ($action == 'bulk_print' && auth()->user()->can('view', $purchase_orders->first())) {
+ $paths = $purchase_orders->map(function ($purchase_order) {
return $purchase_order->service()->getPurchaseOrderPdf();
});
$merge = (new PdfMerge($paths->toArray()))->run();
- return response()->streamDownload(function () use ($merge) {
- echo ($merge);
- }, 'print.pdf', ['Content-Type' => 'application/pdf']);
-
+ return response()->streamDownload(function () use ($merge) {
+ echo($merge);
+ }, 'print.pdf', ['Content-Type' => 'application/pdf']);
}
/*
@@ -605,7 +598,7 @@ class PurchaseOrderController extends BaseController
}
private function performAction(PurchaseOrder $purchase_order, $action, $bulk = false)
- {
+ {
/*If we are using bulk actions, we don't want to return anything */
switch ($action) {
case 'mark_sent':
@@ -619,9 +612,9 @@ class PurchaseOrderController extends BaseController
$file = $purchase_order->service()->getPurchaseOrderPdf();
- return response()->streamDownload(function () use($file) {
- echo Storage::get($file);
- }, basename($file), ['Content-Type' => 'application/pdf']);
+ return response()->streamDownload(function () use ($file) {
+ echo Storage::get($file);
+ }, basename($file), ['Content-Type' => 'application/pdf']);
break;
case 'restore':
@@ -673,8 +666,9 @@ class PurchaseOrderController extends BaseController
case 'expense':
- if($purchase_order->expense()->exists())
+ if ($purchase_order->expense()->exists()) {
return response()->json(['message' => ctrans('texts.purchase_order_already_expensed')], 400);
+ }
$expense = $purchase_order->service()->expense();
@@ -682,8 +676,7 @@ class PurchaseOrderController extends BaseController
case 'cancel':
- if($purchase_order->status_id <= PurchaseOrder::STATUS_SENT)
- {
+ if ($purchase_order->status_id <= PurchaseOrder::STATUS_SENT) {
$purchase_order->status_id = PurchaseOrder::STATUS_CANCELLED;
$purchase_order->save();
}
@@ -751,16 +744,16 @@ class PurchaseOrderController extends BaseController
*/
public function upload(UploadPurchaseOrderRequest $request, PurchaseOrder $purchase_order)
{
-
- if(!$this->checkFeature(Account::FEATURE_DOCUMENTS))
+ if (!$this->checkFeature(Account::FEATURE_DOCUMENTS)) {
return $this->featureFailure();
+ }
- if ($request->has('documents'))
+ if ($request->has('documents')) {
$this->saveDocuments($request->file('documents'), $purchase_order);
+ }
return $this->itemResponse($purchase_order->fresh());
-
- }
+ }
/**
@@ -828,8 +821,4 @@ class PurchaseOrderController extends BaseController
echo Storage::get($file);
}, basename($file), $headers);
}
-
-
-
-
}
diff --git a/app/Http/Controllers/QuoteController.php b/app/Http/Controllers/QuoteController.php
index a75dd9ec3104..ca27b5840054 100644
--- a/app/Http/Controllers/QuoteController.php
+++ b/app/Http/Controllers/QuoteController.php
@@ -27,20 +27,16 @@ use App\Http\Requests\Quote\ShowQuoteRequest;
use App\Http\Requests\Quote\StoreQuoteRequest;
use App\Http\Requests\Quote\UpdateQuoteRequest;
use App\Http\Requests\Quote\UploadQuoteRequest;
-use App\Jobs\Invoice\ZipInvoices;
use App\Jobs\Quote\ZipQuotes;
use App\Models\Account;
use App\Models\Client;
use App\Models\Invoice;
-use App\Models\Project;
use App\Models\Quote;
use App\Repositories\QuoteRepository;
use App\Services\PdfMaker\PdfMerge;
use App\Transformers\InvoiceTransformer;
-use App\Transformers\ProjectTransformer;
use App\Transformers\QuoteTransformer;
use App\Utils\Ninja;
-use App\Utils\TempFile;
use App\Utils\Traits\GeneratesCounter;
use App\Utils\Traits\MakesHash;
use App\Utils\Traits\SavesDocuments;
@@ -516,8 +512,9 @@ class QuoteController extends BaseController
$ids = request()->input('ids');
- if(Ninja::isHosted() && (stripos($action, 'email') !== false) && !auth()->user()->company()->account->account_sms_verified)
+ if (Ninja::isHosted() && (stripos($action, 'email') !== false) && !auth()->user()->company()->account->account_sms_verified) {
return response(['message' => 'Please verify your account to send emails.'], 400);
+ }
$quotes = Quote::withTrashed()->whereIn('id', $this->transformKeys($ids))->company()->get();
@@ -554,32 +551,26 @@ class QuoteController extends BaseController
return $this->listResponse(Quote::withTrashed()->whereIn('id', $this->transformKeys($ids))->company());
}
- if($action == 'bulk_print' && auth()->user()->can('view', $quotes->first())){
-
- $paths = $quotes->map(function ($quote){
+ if ($action == 'bulk_print' && auth()->user()->can('view', $quotes->first())) {
+ $paths = $quotes->map(function ($quote) {
return $quote->service()->getQuotePdf();
});
$merge = (new PdfMerge($paths->toArray()))->run();
- return response()->streamDownload(function () use ($merge) {
- echo ($merge);
- }, 'print.pdf', ['Content-Type' => 'application/pdf']);
-
+ return response()->streamDownload(function () use ($merge) {
+ echo($merge);
+ }, 'print.pdf', ['Content-Type' => 'application/pdf']);
}
- if($action == 'convert_to_project')
- {
-
+ if ($action == 'convert_to_project') {
$quotes->each(function ($quote, $key) use ($action) {
- if (auth()->user()->can('edit', $quote))
- {
+ if (auth()->user()->can('edit', $quote)) {
$project = CloneQuoteToProjectFactory::create($quote, auth()->user()->id);
if (empty($project->number)) {
$project->number = $this->getNextProjectNumber($project);
-
}
$project->save();
$quote->project_id = $project->id;
@@ -693,7 +684,7 @@ class QuoteController extends BaseController
return $this->itemResponse($quote->service()->convertToInvoice());
- break;
+ break;
case 'clone_to_invoice':
diff --git a/app/Http/Controllers/RecurringExpenseController.php b/app/Http/Controllers/RecurringExpenseController.php
index b601a12c6a35..2edb1be1e82e 100644
--- a/app/Http/Controllers/RecurringExpenseController.php
+++ b/app/Http/Controllers/RecurringExpenseController.php
@@ -31,7 +31,6 @@ use App\Utils\Traits\BulkOptions;
use App\Utils\Traits\MakesHash;
use App\Utils\Traits\SavesDocuments;
use App\Utils\Traits\Uploadable;
-use Illuminate\Http\Request;
use Illuminate\Http\Response;
/**
diff --git a/app/Http/Controllers/RecurringInvoiceController.php b/app/Http/Controllers/RecurringInvoiceController.php
index 756e26f67da7..d19830888da4 100644
--- a/app/Http/Controllers/RecurringInvoiceController.php
+++ b/app/Http/Controllers/RecurringInvoiceController.php
@@ -30,7 +30,6 @@ use App\Transformers\RecurringInvoiceTransformer;
use App\Utils\Ninja;
use App\Utils\Traits\MakesHash;
use App\Utils\Traits\SavesDocuments;
-use Carbon\Carbon;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Storage;
diff --git a/app/Http/Controllers/Reports/ProductSalesReportController.php b/app/Http/Controllers/Reports/ProductSalesReportController.php
index 6eb518451ef0..f27de4b19343 100644
--- a/app/Http/Controllers/Reports/ProductSalesReportController.php
+++ b/app/Http/Controllers/Reports/ProductSalesReportController.php
@@ -11,10 +11,8 @@
namespace App\Http\Controllers\Reports;
-use App\Export\CSV\ProductExport;
use App\Export\CSV\ProductSalesExport;
use App\Http\Controllers\BaseController;
-use App\Http\Requests\Report\GenericReportRequest;
use App\Http\Requests\Report\ProductSalesReportRequest;
use App\Jobs\Report\SendToAdmin;
use App\Models\Client;
diff --git a/app/Http/Controllers/Reports/ProfitAndLossController.php b/app/Http/Controllers/Reports/ProfitAndLossController.php
index 1d7c8833ccf1..3d1f0751066d 100644
--- a/app/Http/Controllers/Reports/ProfitAndLossController.php
+++ b/app/Http/Controllers/Reports/ProfitAndLossController.php
@@ -11,7 +11,6 @@
namespace App\Http\Controllers\Reports;
-use App\Export\CSV\PaymentExport;
use App\Http\Controllers\BaseController;
use App\Http\Requests\Report\ProfitLossRequest;
use App\Jobs\Report\SendToAdmin;
diff --git a/app/Http/Controllers/SetupController.php b/app/Http/Controllers/SetupController.php
index 7d024d894cd8..ff0faf16cbc4 100644
--- a/app/Http/Controllers/SetupController.php
+++ b/app/Http/Controllers/SetupController.php
@@ -20,7 +20,6 @@ use App\Jobs\Util\SchedulerCheck;
use App\Jobs\Util\VersionCheck;
use App\Models\Account;
use App\Utils\CurlUtils;
-use App\Utils\HostedPDF\NinjaPdf;
use App\Utils\Ninja;
use App\Utils\SystemHealth;
use App\Utils\Traits\AppSetup;
@@ -31,9 +30,7 @@ use Illuminate\Contracts\Routing\ResponseFactory;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Artisan;
-use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
-use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Storage;
@@ -212,7 +209,6 @@ class SetupController extends Controller
public function checkPdf(Request $request)
{
try {
-
// if (config('ninja.pdf_generator') == 'phantom') {
// return $this->testPhantom();
// }
diff --git a/app/Http/Controllers/StaticController.php b/app/Http/Controllers/StaticController.php
index 2b9c2ae3fb26..bd9fddf84e31 100644
--- a/app/Http/Controllers/StaticController.php
+++ b/app/Http/Controllers/StaticController.php
@@ -11,13 +11,7 @@
namespace App\Http\Controllers;
-use App\Http\Requests\Account\CreateAccountRequest;
-use App\Jobs\Account\CreateAccount;
-use App\Models\Account;
-use App\Models\CompanyUser;
-use App\Transformers\CompanyUserTransformer;
use App\Utils\Statics;
-use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Http\Response;
class StaticController extends BaseController
diff --git a/app/Http/Controllers/StripeConnectController.php b/app/Http/Controllers/StripeConnectController.php
index 73a12b03ebfd..9408f987b0b9 100644
--- a/app/Http/Controllers/StripeConnectController.php
+++ b/app/Http/Controllers/StripeConnectController.php
@@ -12,7 +12,6 @@
namespace App\Http\Controllers;
use App\DataMapper\FeesAndLimits;
-use App\Exceptions\SystemError;
use App\Factory\CompanyGatewayFactory;
use App\Http\Requests\StripeConnect\InitializeStripeConnectRequest;
use App\Libraries\MultiDB;
@@ -20,10 +19,7 @@ use App\Models\Client;
use App\Models\Company;
use App\Models\CompanyGateway;
use App\Models\GatewayType;
-use App\PaymentDrivers\Stripe\Connect\Account;
use App\PaymentDrivers\Stripe\Jobs\StripeWebhook;
-use Exception;
-use Illuminate\Http\Request;
use Stripe\Exception\ApiErrorException;
class StripeConnectController extends BaseController
@@ -70,7 +66,7 @@ class StripeConnectController extends BaseController
{
\Stripe\Stripe::setApiKey(config('ninja.ninja_stripe_key'));
- if($request->has('error') && $request->error == 'access_denied'){
+ if ($request->has('error') && $request->error == 'access_denied') {
return view('auth.connect.access_denied');
}
@@ -80,9 +76,7 @@ class StripeConnectController extends BaseController
'code' => $request->input('code'),
]);
} catch (\Exception $e) {
-
return view('auth.connect.access_denied');
-
}
MultiDB::findAndSetDbByCompanyKey($request->getTokenContent()['company_key']);
diff --git a/app/Http/Controllers/StripeController.php b/app/Http/Controllers/StripeController.php
index 8980d74181b8..a50402a6c1e1 100644
--- a/app/Http/Controllers/StripeController.php
+++ b/app/Http/Controllers/StripeController.php
@@ -38,7 +38,6 @@ class StripeController extends BaseController
public function import()
{
-
// return response()->json(['message' => 'Processing'], 200);
if (auth()->user()->isAdmin()) {
diff --git a/app/Http/Controllers/TaskController.php b/app/Http/Controllers/TaskController.php
index e157fdf8e735..2617ebf1f270 100644
--- a/app/Http/Controllers/TaskController.php
+++ b/app/Http/Controllers/TaskController.php
@@ -33,7 +33,6 @@ use App\Utils\Traits\BulkOptions;
use App\Utils\Traits\MakesHash;
use App\Utils\Traits\SavesDocuments;
use App\Utils\Traits\Uploadable;
-use Illuminate\Http\Request;
use Illuminate\Http\Response;
/**
diff --git a/app/Http/Controllers/TaskSchedulerController.php b/app/Http/Controllers/TaskSchedulerController.php
index dc3d297cf0fc..6de1bd1581d9 100644
--- a/app/Http/Controllers/TaskSchedulerController.php
+++ b/app/Http/Controllers/TaskSchedulerController.php
@@ -12,19 +12,15 @@
namespace App\Http\Controllers;
use App\Factory\SchedulerFactory;
+use App\Http\Requests\Task\DestroySchedulerRequest;
use App\Http\Requests\TaskScheduler\CreateSchedulerRequest;
use App\Http\Requests\TaskScheduler\ShowSchedulerRequest;
use App\Http\Requests\TaskScheduler\StoreSchedulerRequest;
use App\Http\Requests\TaskScheduler\UpdateSchedulerRequest;
-use App\Http\Requests\Task\DestroySchedulerRequest;
-use App\Jobs\Ninja\TaskScheduler;
-use App\Jobs\Report\ProfitAndLoss;
use App\Models\Scheduler;
use App\Repositories\SchedulerRepository;
use App\Transformers\SchedulerTransformer;
use App\Utils\Traits\MakesHash;
-use Carbon\Carbon;
-use Illuminate\Database\Eloquent\Model;
use Symfony\Component\HttpFoundation\Request;
class TaskSchedulerController extends BaseController
@@ -336,8 +332,9 @@ class TaskSchedulerController extends BaseController
{
$action = request()->input('action');
- if(!in_array($action, ['archive', 'restore', 'delete']))
+ if (!in_array($action, ['archive', 'restore', 'delete'])) {
return response()->json(['message' => 'Bulk action does not exist'], 400);
+ }
$ids = request()->input('ids');
@@ -351,5 +348,4 @@ class TaskSchedulerController extends BaseController
return $this->listResponse(Scheduler::withTrashed()->whereIn('id', $this->transformKeys($ids)));
}
-
}
diff --git a/app/Http/Controllers/TaskStatusController.php b/app/Http/Controllers/TaskStatusController.php
index 3ed5ae224db9..188312faa512 100644
--- a/app/Http/Controllers/TaskStatusController.php
+++ b/app/Http/Controllers/TaskStatusController.php
@@ -461,10 +461,8 @@ class TaskStatusController extends BaseController
->whereIn('id', $this->transformKeys($ids))
->cursor()
->each(function ($task_status, $key) use ($action) {
-
- $this->task_status_repo->{$action}($task_status);
-
- });
+ $this->task_status_repo->{$action}($task_status);
+ });
return $this->listResponse(TaskStatus::withTrashed()->whereIn('id', $this->transformKeys($ids)));
}
diff --git a/app/Http/Controllers/TaxRateController.php b/app/Http/Controllers/TaxRateController.php
index 29f7e2a310ba..fb60fbc40bb9 100644
--- a/app/Http/Controllers/TaxRateController.php
+++ b/app/Http/Controllers/TaxRateController.php
@@ -23,7 +23,6 @@ use App\Models\TaxRate;
use App\Repositories\BaseRepository;
use App\Transformers\TaxRateTransformer;
use App\Utils\Traits\MakesHash;
-use Illuminate\Http\Request;
use Illuminate\Http\Response;
/**
diff --git a/app/Http/Controllers/TemplateController.php b/app/Http/Controllers/TemplateController.php
index b7faf147f3a3..f105c868b027 100644
--- a/app/Http/Controllers/TemplateController.php
+++ b/app/Http/Controllers/TemplateController.php
@@ -11,14 +11,11 @@
namespace App\Http\Controllers;
-use App\Utils\Ninja;
use App\Utils\TemplateEngine;
use App\Utils\Traits\MakesHash;
use App\Utils\Traits\MakesInvoiceHtml;
use App\Utils\Traits\MakesTemplateData;
use Illuminate\Http\Response;
-use Illuminate\Support\Facades\App;
-use Illuminate\Support\Facades\Lang;
class TemplateController extends BaseController
{
diff --git a/app/Http/Controllers/TokenController.php b/app/Http/Controllers/TokenController.php
index bf35e279480e..6cf4413bf57b 100644
--- a/app/Http/Controllers/TokenController.php
+++ b/app/Http/Controllers/TokenController.php
@@ -25,7 +25,6 @@ use App\Transformers\CompanyTokenHashedTransformer;
use App\Transformers\CompanyTokenTransformer;
use App\Utils\Traits\ChecksEntityStatus;
use App\Utils\Traits\MakesHash;
-use Illuminate\Http\Request;
use Illuminate\Http\Response;
/**
diff --git a/app/Http/Controllers/TwilioController.php b/app/Http/Controllers/TwilioController.php
index a58cbb015c60..465e1b989830 100644
--- a/app/Http/Controllers/TwilioController.php
+++ b/app/Http/Controllers/TwilioController.php
@@ -17,13 +17,10 @@ use App\Http\Requests\Twilio\Generate2faRequest;
use App\Http\Requests\Twilio\GenerateSmsRequest;
use App\Libraries\MultiDB;
use App\Models\User;
-use Illuminate\Foundation\Bus\DispatchesJobs;
-use Illuminate\Http\Response;
use Twilio\Rest\Client;
class TwilioController extends BaseController
{
-
public function __construct()
{
parent::__construct();
@@ -38,8 +35,9 @@ class TwilioController extends BaseController
{
$account = auth()->user()->company()->account;
- if(MultiDB::hasPhoneNumber($request->phone))
+ if (MultiDB::hasPhoneNumber($request->phone)) {
return response()->json(['message' => 'This phone number has already been verified with another account'], 400);
+ }
$sid = config('ninja.twilio_account_sid');
$token = config('ninja.twilio_auth_token');
@@ -53,11 +51,8 @@ class TwilioController extends BaseController
->services(config('ninja.twilio_verify_sid'))
->verifications
->create($request->phone, "sms");
- }
- catch(\Exception $e) {
-
+ } catch(\Exception $e) {
return response()->json(['message' => 'Invalid phone number please use + country code + number ie. +15552343334'], 400);
-
}
$account->account_sms_verification_code = $verification->sid;
@@ -74,7 +69,6 @@ class TwilioController extends BaseController
*/
public function confirm(ConfirmSmsRequest $request)
{
-
$account = auth()->user()->company()->account;
$sid = config('ninja.twilio_account_sid');
@@ -92,8 +86,7 @@ class TwilioController extends BaseController
]);
- if($verification_check->status == 'approved'){
-
+ if ($verification_check->status == 'approved') {
$account->account_sms_verified = true;
$account->save();
@@ -108,15 +101,15 @@ class TwilioController extends BaseController
return response()->json(['message' => 'SMS not verified'], 400);
-
}
public function generate2faResetCode(Generate2faRequest $request)
{
$user = User::where('email', $request->email)->first();
- if(!$user)
+ if (!$user) {
return response()->json(['message' => 'Unable to retrieve user.'], 400);
+ }
$sid = config('ninja.twilio_account_sid');
$token = config('ninja.twilio_auth_token');
@@ -129,11 +122,8 @@ class TwilioController extends BaseController
->services(config('ninja.twilio_verify_sid'))
->verifications
->create($user->phone, "sms");
- }
- catch(\Exception $e) {
-
+ } catch(\Exception $e) {
return response()->json(['message' => 'Invalid phone number on file, we are unable to reset. Please contact support.'], 400);
-
}
$user->sms_verification_code = $verification->sid;
@@ -146,8 +136,9 @@ class TwilioController extends BaseController
{
$user = User::where('email', $request->email)->first();
- if(!$user)
+ if (!$user) {
return response()->json(['message' => 'Unable to retrieve user.'], 400);
+ }
$sid = config('ninja.twilio_account_sid');
$token = config('ninja.twilio_auth_token');
@@ -163,9 +154,8 @@ class TwilioController extends BaseController
"code" => $request->code
]);
- if($verification_check->status == 'approved'){
-
- if($request->query('validate_only') == 'true'){
+ if ($verification_check->status == 'approved') {
+ if ($request->query('validate_only') == 'true') {
$user->verified_phone_number = true;
$user->save();
return response()->json(['message' => 'SMS verified'], 200);
@@ -179,12 +169,10 @@ class TwilioController extends BaseController
}
return response()->json(['message' => 'SMS not verified.'], 400);
-
- }
+ }
public function validatePhoneNumber()
{
-
$sid = config('ninja.twilio_account_sid');
$token = config('ninja.twilio_auth_token');
@@ -194,7 +182,5 @@ class TwilioController extends BaseController
->fetch(["countryCode" => "AU"]);
print($phone_number);
-
}
-
}
diff --git a/app/Http/Controllers/TwoFactorController.php b/app/Http/Controllers/TwoFactorController.php
index e05adb3060a1..bc3b1ba77411 100644
--- a/app/Http/Controllers/TwoFactorController.php
+++ b/app/Http/Controllers/TwoFactorController.php
@@ -14,7 +14,6 @@ namespace App\Http\Controllers;
use App\Http\Requests\TwoFactor\EnableTwoFactorRequest;
use App\Models\User;
use App\Transformers\UserTransformer;
-use Crypt;
use PragmaRX\Google2FA\Google2FA;
class TwoFactorController extends BaseController
diff --git a/app/Http/Controllers/UserController.php b/app/Http/Controllers/UserController.php
index 99d4505945fc..8cccb0a93fc6 100644
--- a/app/Http/Controllers/UserController.php
+++ b/app/Http/Controllers/UserController.php
@@ -11,14 +11,12 @@
namespace App\Http\Controllers;
-use App\DataMapper\CompanySettings;
use App\Events\User\UserWasCreated;
use App\Events\User\UserWasDeleted;
use App\Events\User\UserWasUpdated;
use App\Factory\UserFactory;
use App\Filters\UserFilters;
use App\Http\Controllers\Traits\VerifiesUserEmail;
-use App\Http\Requests\User\AttachCompanyUserRequest;
use App\Http\Requests\User\BulkUserRequest;
use App\Http\Requests\User\CreateUserRequest;
use App\Http\Requests\User\DestroyUserRequest;
@@ -29,18 +27,13 @@ use App\Http\Requests\User\ShowUserRequest;
use App\Http\Requests\User\StoreUserRequest;
use App\Http\Requests\User\UpdateUserRequest;
use App\Jobs\Company\CreateCompanyToken;
-use App\Jobs\Mail\NinjaMailer;
-use App\Jobs\Mail\NinjaMailerJob;
-use App\Jobs\Mail\NinjaMailerObject;
use App\Jobs\User\UserEmailChanged;
-use App\Mail\Admin\VerifyUserObject;
use App\Models\CompanyUser;
use App\Models\User;
use App\Repositories\UserRepository;
use App\Transformers\UserTransformer;
use App\Utils\Ninja;
use App\Utils\Traits\MakesHash;
-use Illuminate\Http\Request;
use Illuminate\Http\Response;
/**
@@ -64,11 +57,9 @@ class UserController extends BaseController
*/
public function __construct(UserRepository $user_repo)
{
-
parent::__construct();
$this->user_repo = $user_repo;
-
}
/**
@@ -461,8 +452,9 @@ class UserController extends BaseController
*/
public function destroy(DestroyUserRequest $request, User $user)
{
- if($user->isOwner())
- return response()->json(['message', 'Cannot detach owner.'],400);
+ if ($user->isOwner()) {
+ return response()->json(['message', 'Cannot detach owner.'], 400);
+ }
/* If the user passes the company user we archive the company user */
$user = $this->user_repo->delete($request->all(), $user);
@@ -600,7 +592,6 @@ class UserController extends BaseController
*/
public function detach(DetachCompanyUserRequest $request, User $user)
{
-
if ($request->entityIsDeleted($user)) {
return $request->disallowUpdate();
}
@@ -610,8 +601,9 @@ class UserController extends BaseController
->withTrashed()
->first();
- if($company_user->is_owner)
+ if ($company_user->is_owner) {
return response()->json(['message', 'Cannot detach owner.'], 401);
+ }
$token = $company_user->token->where('company_id', $company_user->company_id)->where('user_id', $company_user->user_id)->first();
@@ -674,11 +666,9 @@ class UserController extends BaseController
*/
public function invite(ReconfirmUserRequest $request, User $user)
{
-
$user->service()->invite($user->company());
return response()->json(['message' => ctrans('texts.confirmation_resent')], 200);
-
}
@@ -730,10 +720,8 @@ class UserController extends BaseController
*/
public function reconfirm(ReconfirmUserRequest $request, User $user)
{
-
$user->service()->invite($user->company());
return response()->json(['message' => ctrans('texts.confirmation_resent')], 200);
-
}
}
diff --git a/app/Http/Controllers/VendorController.php b/app/Http/Controllers/VendorController.php
index 07e932b181a9..4ac01af36de1 100644
--- a/app/Http/Controllers/VendorController.php
+++ b/app/Http/Controllers/VendorController.php
@@ -31,7 +31,6 @@ use App\Utils\Traits\BulkOptions;
use App\Utils\Traits\MakesHash;
use App\Utils\Traits\SavesDocuments;
use App\Utils\Traits\Uploadable;
-use Illuminate\Http\Request;
use Illuminate\Http\Response;
/**
diff --git a/app/Http/Controllers/VendorPortal/DocumentController.php b/app/Http/Controllers/VendorPortal/DocumentController.php
index 71b35af63747..c12820953b25 100644
--- a/app/Http/Controllers/VendorPortal/DocumentController.php
+++ b/app/Http/Controllers/VendorPortal/DocumentController.php
@@ -13,8 +13,8 @@
namespace App\Http\Controllers\VendorPortal;
use App\Http\Controllers\Controller;
-use App\Http\Requests\VendorPortal\Documents\ShowDocumentRequest;
use App\Http\Requests\Document\DownloadMultipleDocumentsRequest;
+use App\Http\Requests\VendorPortal\Documents\ShowDocumentRequest;
use App\Libraries\MultiDB;
use App\Models\Document;
use App\Utils\TempFile;
@@ -111,7 +111,7 @@ class DocumentController extends Controller
$zipFile->saveAsFile($filepath) // save the archive to a file
->close(); // close archive
- return response()->download($filepath, $filename)->deleteFileAfterSend(true);
+ return response()->download($filepath, $filename)->deleteFileAfterSend(true);
} catch (\PhpZip\Exception\ZipException $e) {
// handle exception
} finally {
diff --git a/app/Http/Controllers/VendorPortal/InvitationController.php b/app/Http/Controllers/VendorPortal/InvitationController.php
index b2a7fe7f5f19..80bc02e5d5df 100644
--- a/app/Http/Controllers/VendorPortal/InvitationController.php
+++ b/app/Http/Controllers/VendorPortal/InvitationController.php
@@ -11,28 +11,14 @@
namespace App\Http\Controllers\VendorPortal;
-use App\Events\Credit\CreditWasViewed;
-use App\Events\Invoice\InvoiceWasViewed;
use App\Events\Misc\InvitationWasViewed;
use App\Events\PurchaseOrder\PurchaseOrderWasViewed;
-use App\Events\Quote\QuoteWasViewed;
use App\Http\Controllers\Controller;
-use App\Jobs\Entity\CreateRawPdf;
use App\Jobs\Vendor\CreatePurchaseOrderPdf;
-use App\Models\Client;
-use App\Models\ClientContact;
-use App\Models\CreditInvitation;
-use App\Models\InvoiceInvitation;
-use App\Models\Payment;
-use App\Models\PurchaseOrder;
use App\Models\PurchaseOrderInvitation;
-use App\Models\QuoteInvitation;
-use App\Services\ClientPortal\InstantPayment;
-use App\Utils\CurlUtils;
use App\Utils\Ninja;
use App\Utils\Traits\MakesDates;
use App\Utils\Traits\MakesHash;
-use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
@@ -46,33 +32,34 @@ class InvitationController extends Controller
public function purchaseOrder(string $invitation_key)
{
-
Auth::logout();
$invitation = PurchaseOrderInvitation::withTrashed()
->where('key', $invitation_key)
->whereHas('purchase_order', function ($query) {
- $query->where('is_deleted',0);
+ $query->where('is_deleted', 0);
})
->with('contact.vendor')
->first();
- if(!$invitation)
- return abort(404,'The resource is no longer available.');
+ if (!$invitation) {
+ return abort(404, 'The resource is no longer available.');
+ }
- if($invitation->contact->trashed())
+ if ($invitation->contact->trashed()) {
$invitation->contact->restore();
+ }
$vendor_contact = $invitation->contact;
$entity = 'purchase_order';
- if(empty($vendor_contact->email))
- $vendor_contact->email = Str::random(15) . "@example.com"; $vendor_contact->save();
+ if (empty($vendor_contact->email)) {
+ $vendor_contact->email = Str::random(15) . "@example.com";
+ } $vendor_contact->save();
if (request()->has('vendor_hash') && request()->input('vendor_hash') == $invitation->contact->vendor->vendor_hash) {
request()->session()->invalidate();
auth()->guard('vendor')->loginUsingId($vendor_contact->id, true);
-
} else {
request()->session()->invalidate();
auth()->guard('vendor')->loginUsingId($vendor_contact->id, true);
@@ -81,21 +68,14 @@ class InvitationController extends Controller
session()->put('is_silent', request()->has('silent'));
if (auth()->guard('vendor')->user() && ! session()->get('is_silent') && ! $invitation->viewed_date) {
-
$invitation->markViewed();
event(new InvitationWasViewed($invitation->purchase_order, $invitation, $invitation->company, Ninja::eventVars()));
event(new PurchaseOrderWasViewed($invitation, $invitation->company, Ninja::eventVars()));
-
- }
- else{
-
+ } else {
return redirect()->route('vendor.'.$entity.'.show', [$entity => $this->encodePrimaryKey($invitation->purchase_order_id), 'silent' => session()->get('is_silent')]);
-
}
return redirect()->route('vendor.'.$entity.'.show', [$entity => $this->encodePrimaryKey($invitation->purchase_order_id)]);
-
-
}
public function download(string $invitation_key)
@@ -105,8 +85,9 @@ class InvitationController extends Controller
->with('contact.vendor')
->firstOrFail();
- if(!$invitation)
+ if (!$invitation) {
return response()->json(["message" => "no record found"], 400);
+ }
$file_name = $invitation->purchase_order->numberFormatter().'.pdf';
@@ -114,15 +95,12 @@ class InvitationController extends Controller
$headers = ['Content-Type' => 'application/pdf'];
- if(request()->input('inline') == 'true')
+ if (request()->input('inline') == 'true') {
$headers = array_merge($headers, ['Content-Disposition' => 'inline']);
+ }
- return response()->streamDownload(function () use($file) {
- echo $file;
- }, $file_name, $headers);
+ return response()->streamDownload(function () use ($file) {
+ echo $file;
+ }, $file_name, $headers);
}
-
-
-
-
}
diff --git a/app/Http/Controllers/VendorPortal/PurchaseOrderController.php b/app/Http/Controllers/VendorPortal/PurchaseOrderController.php
index 6d1eee326790..1a9d309558d1 100644
--- a/app/Http/Controllers/VendorPortal/PurchaseOrderController.php
+++ b/app/Http/Controllers/VendorPortal/PurchaseOrderController.php
@@ -24,7 +24,6 @@ use App\Utils\Ninja;
use App\Utils\Traits\MakesDates;
use App\Utils\Traits\MakesHash;
use Illuminate\Contracts\View\Factory;
-use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\View\View;
@@ -203,7 +202,6 @@ class PurchaseOrderController extends Controller
$zipFile = new \PhpZip\ZipFile();
try {
foreach ($purchase_orders as $purchase_order) {
-
//add it to the zip
$zipFile->addFromString(basename($purchase_order->pdf_file_path()), file_get_contents($purchase_order->pdf_file_path(null, 'url', true)));
}
@@ -214,7 +212,7 @@ class PurchaseOrderController extends Controller
$zipFile->saveAsFile($filepath) // save the archive to a file
->close(); // close archive
- return response()->download($filepath, $filename)->deleteFileAfterSend(true);
+ return response()->download($filepath, $filename)->deleteFileAfterSend(true);
} catch (\PhpZip\Exception\ZipException $e) {
// handle exception
} finally {
diff --git a/app/Http/Controllers/VendorPortal/UploadController.php b/app/Http/Controllers/VendorPortal/UploadController.php
index ac7cc1f8e6c0..c9c6da65815b 100644
--- a/app/Http/Controllers/VendorPortal/UploadController.php
+++ b/app/Http/Controllers/VendorPortal/UploadController.php
@@ -33,7 +33,6 @@ class UploadController extends Controller
*/
public function upload(StoreUploadRequest $request, PurchaseOrder $purchase_order)
{
-
$this->saveDocuments($request->getFile(), $purchase_order, true);
return response([], 200);
diff --git a/app/Http/Controllers/VendorPortal/VendorContactController.php b/app/Http/Controllers/VendorPortal/VendorContactController.php
index 224eb2dacf7e..ea26616691a0 100644
--- a/app/Http/Controllers/VendorPortal/VendorContactController.php
+++ b/app/Http/Controllers/VendorPortal/VendorContactController.php
@@ -15,7 +15,6 @@ use App\Http\Controllers\Controller;
use App\Models\VendorContact;
use App\Utils\Traits\MakesHash;
use App\Utils\TranslationHelper;
-use Illuminate\Http\Request;
class VendorContactController extends Controller
{
diff --git a/app/Http/Controllers/VendorPortal/VendorContactHashLoginController.php b/app/Http/Controllers/VendorPortal/VendorContactHashLoginController.php
index 1636f43cbae6..96190431d68c 100644
--- a/app/Http/Controllers/VendorPortal/VendorContactHashLoginController.php
+++ b/app/Http/Controllers/VendorPortal/VendorContactHashLoginController.php
@@ -12,8 +12,6 @@
namespace App\Http\Controllers\VendorPortal;
use App\Http\Controllers\Controller;
-use App\Http\ViewComposers\PortalComposer;
-use App\Models\RecurringInvoice;
use Auth;
class VendorContactHashLoginController extends Controller
@@ -37,6 +35,4 @@ class VendorContactHashLoginController extends Controller
{
return render('generic.error', ['title' => session()->get('title'), 'notification' => session()->get('notification')]);
}
-
-
}
diff --git a/app/Http/Controllers/WePayController.php b/app/Http/Controllers/WePayController.php
index d8351f78a4ba..a37a5e56a95b 100644
--- a/app/Http/Controllers/WePayController.php
+++ b/app/Http/Controllers/WePayController.php
@@ -17,7 +17,6 @@ use App\Models\CompanyGateway;
use App\Models\User;
use App\PaymentDrivers\WePayPaymentDriver;
use App\Utils\Traits\MakesHash;
-use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
class WePayController extends BaseController
diff --git a/app/Http/Controllers/WebhookController.php b/app/Http/Controllers/WebhookController.php
index 5c6b9d5ffbef..f77fef636efb 100644
--- a/app/Http/Controllers/WebhookController.php
+++ b/app/Http/Controllers/WebhookController.php
@@ -24,7 +24,6 @@ use App\Models\Webhook;
use App\Repositories\BaseRepository;
use App\Transformers\WebhookTransformer;
use App\Utils\Traits\MakesHash;
-use Illuminate\Http\Request;
use Illuminate\Http\Response;
class WebhookController extends BaseController
diff --git a/app/Http/Livewire/BillingPortalPurchase.php b/app/Http/Livewire/BillingPortalPurchase.php
index 567ddabf56ae..8b7f79a5628f 100644
--- a/app/Http/Livewire/BillingPortalPurchase.php
+++ b/app/Http/Livewire/BillingPortalPurchase.php
@@ -11,6 +11,7 @@
namespace App\Http\Livewire;
+use App\DataMapper\ClientSettings;
use App\Factory\ClientFactory;
use App\Jobs\Mail\NinjaMailerJob;
use App\Jobs\Mail\NinjaMailerObject;
@@ -22,12 +23,9 @@ use App\Models\Invoice;
use App\Models\Subscription;
use App\Repositories\ClientContactRepository;
use App\Repositories\ClientRepository;
-use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
-use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
-use App\DataMapper\ClientSettings;
use Livewire\Component;
class BillingPortalPurchase extends Component
@@ -198,16 +196,14 @@ class BillingPortalPurchase extends Component
if (request()->query('coupon')) {
$this->coupon = request()->query('coupon');
$this->handleCoupon();
- }
- elseif(strlen($this->subscription->promo_code) == 0 && $this->subscription->promo_discount > 0){
+ } elseif (strlen($this->subscription->promo_code) == 0 && $this->subscription->promo_discount > 0) {
$this->price = $this->subscription->promo_price;
}
/* Leave this here, otherwise a logged in user will need to reauth... painfully */
- if(Auth::guard('contact')->check()){
+ if (Auth::guard('contact')->check()) {
return $this->getPaymentMethods(auth()->guard('contact')->user());
}
-
}
/**
@@ -277,25 +273,22 @@ class BillingPortalPurchase extends Component
}
}
- if(array_key_exists('currency_id', $this->request_data)) {
-
- $currency = Cache::get('currencies')->filter(function ($item){
+ if (array_key_exists('currency_id', $this->request_data)) {
+ $currency = Cache::get('currencies')->filter(function ($item) {
return $item->id == $this->request_data['currency_id'];
})->first();
- if($currency)
+ if ($currency) {
$data['settings']->currency_id = $currency->id;
-
- }
- elseif($this->subscription->group_settings && property_exists($this->subscription->group_settings->settings, 'currency_id')) {
-
- $currency = Cache::get('currencies')->filter(function ($item){
+ }
+ } elseif ($this->subscription->group_settings && property_exists($this->subscription->group_settings->settings, 'currency_id')) {
+ $currency = Cache::get('currencies')->filter(function ($item) {
return $item->id == $this->subscription->group_settings->settings->currency_id;
})->first();
- if($currency)
+ if ($currency) {
$data['settings']->currency_id = $currency->id;
-
+ }
}
if (array_key_exists('locale', $this->request_data)) {
@@ -334,10 +327,11 @@ class BillingPortalPurchase extends Component
return $this;
}
- if ((int)$this->price == 0)
+ if ((int)$this->price == 0) {
$this->steps['payment_required'] = false;
- else
+ } else {
$this->steps['fetched_payment_methods'] = true;
+ }
$this->methods = $contact->client->service()->getPaymentMethods($this->price);
@@ -431,7 +425,6 @@ class BillingPortalPurchase extends Component
public function handlePaymentNotRequired()
{
-
$is_eligible = $this->subscription->service()->isEligible($this->contact);
if ($is_eligible['status_code'] != 200) {
@@ -478,16 +471,15 @@ class BillingPortalPurchase extends Component
return $this->quantity;
}
- $this->quantity--;
- $this->price = $this->price * $this->quantity;
+ $this->quantity--;
+ $this->price = $this->price * $this->quantity;
- return $this->quantity;
+ return $this->quantity;
}
public function handleCoupon()
{
-
- if($this->steps['discount_applied']){
+ if ($this->steps['discount_applied']) {
$this->price = $this->subscription->promo_price;
return;
}
@@ -496,9 +488,9 @@ class BillingPortalPurchase extends Component
$this->price = $this->subscription->promo_price;
$this->quantity = 1;
$this->steps['discount_applied'] = true;
- }
- else
+ } else {
$this->price = $this->subscription->price;
+ }
}
public function passwordlessLogin()
diff --git a/app/Http/Livewire/BillingPortalPurchasev2.php b/app/Http/Livewire/BillingPortalPurchasev2.php
index f7f4d1ba79dc..ae9c980d082c 100644
--- a/app/Http/Livewire/BillingPortalPurchasev2.php
+++ b/app/Http/Livewire/BillingPortalPurchasev2.php
@@ -15,9 +15,7 @@ use App\DataMapper\ClientSettings;
use App\Factory\ClientFactory;
use App\Jobs\Mail\NinjaMailerJob;
use App\Jobs\Mail\NinjaMailerObject;
-use App\Jobs\Subscription\CleanStaleInvoiceOrder;
use App\Libraries\MultiDB;
-use App\Mail\ContactPasswordlessLogin;
use App\Mail\Subscription\OtpCode;
use App\Models\Client;
use App\Models\ClientContact;
@@ -27,15 +25,11 @@ use App\Models\Subscription;
use App\Repositories\ClientContactRepository;
use App\Repositories\ClientRepository;
use App\Utils\Number;
-use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
-use Illuminate\Support\Facades\DB;
-use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
-use Illuminate\Validation\Rule;
-use Laracasts\Presenter\Exceptions\PresenterException;
use InvalidArgumentException;
+use Laracasts\Presenter\Exceptions\PresenterException;
use Livewire\Component;
class BillingPortalPurchasev2 extends Component
@@ -171,7 +165,7 @@ class BillingPortalPurchasev2 extends Component
$this->company = $this->subscription->company;
- if(auth()->guard('contact')->check()){
+ if (auth()->guard('contact')->check()) {
$this->email = auth()->guard('contact')->user()->email;
$this->contact = auth()->guard('contact')->user();
$this->authenticated = true;
@@ -195,31 +189,28 @@ class BillingPortalPurchasev2 extends Component
//every thing below is redundant
- if (request()->query('coupon')) {
+ if (request()->query('coupon')) {
$this->coupon = request()->query('coupon');
$this->handleCoupon();
+ } elseif (isset($this->subscription->promo_code) && strlen($this->subscription->promo_code) == 0 && $this->subscription->promo_discount > 0) {
+ $this->price = $this->subscription->promo_price;
}
- elseif(isset($this->subscription->promo_code) && strlen($this->subscription->promo_code) == 0 && $this->subscription->promo_discount > 0){
- $this->price = $this->subscription->promo_price;
- }
-
}
public function loginValidation()
{
$this->resetErrorBag('login');
- $this->resetValidation('login');
+ $this->resetValidation('login');
}
public function handleLogin($user_code)
{
-
$this->resetErrorBag('login');
$this->resetValidation('login');
$code = Cache::get("subscriptions:otp:{$this->email}");
- if($user_code != $code){
+ if ($user_code != $code) {
$errors = $this->getErrorBag();
$errors->add('login', ctrans('texts.invalid_code'));
return $this;
@@ -229,11 +220,10 @@ class BillingPortalPurchasev2 extends Component
->where('company_id', $this->subscription->company_id)
->first();
- if($contact){
+ if ($contact) {
Auth::guard('contact')->loginUsingId($contact->id, true);
$this->contact = $contact;
- }
- else {
+ } else {
$this->createClientContact();
}
@@ -241,32 +231,30 @@ class BillingPortalPurchasev2 extends Component
$this->authenticated = true;
$this->payment_started = true;
-
}
public function resetEmail()
{
$this->resetErrorBag('login');
- $this->resetValidation('login');
+ $this->resetValidation('login');
$this->email = null;
}
public function handleEmail()
{
- $this->validateOnly('email', ['email' => 'required|bail|email:rfc']);
+ $this->validateOnly('email', ['email' => 'required|bail|email:rfc']);
- $rand = rand(100000,999999);
+ $rand = rand(100000, 999999);
- $email_hash = "subscriptions:otp:{$this->email}";
+ $email_hash = "subscriptions:otp:{$this->email}";
- Cache::put($email_hash, $rand, 120);
+ Cache::put($email_hash, $rand, 120);
- $this->emailOtpCode($rand);
+ $this->emailOtpCode($rand);
}
private function emailOtpCode($code)
{
-
$cc = new ClientContact();
$cc->email = $this->email;
@@ -276,7 +264,6 @@ class BillingPortalPurchasev2 extends Component
$nmo->settings = $this->subscription->company->settings;
$nmo->to_user = $cc;
NinjaMailerJob::dispatch($nmo);
-
}
/**
@@ -284,17 +271,14 @@ class BillingPortalPurchasev2 extends Component
*/
public function handleCoupon()
{
-
- if($this->coupon == $this->subscription->promo_code) {
+ if ($this->coupon == $this->subscription->promo_code) {
$this->valid_coupon = true;
$this->buildBundle();
- }
- else{
+ } else {
$this->discount = 0;
$this->valid_coupon = false;
$this->buildBundle();
}
-
}
/**
@@ -302,142 +286,123 @@ class BillingPortalPurchasev2 extends Component
*/
public function buildBundle()
{
- $this->bundle = collect();
+ $this->bundle = collect();
- $data = $this->data;
+ $data = $this->data;
- /* Recurring products can have a variable quantity */
- foreach($this->recurring_products as $key => $p)
- {
+ /* Recurring products can have a variable quantity */
+ foreach ($this->recurring_products as $key => $p) {
+ $qty = isset($data[$key]['recurring_qty']) ? $data[$key]['recurring_qty'] : 1;
+ $total = $p->price * $qty;
- $qty = isset($data[$key]['recurring_qty']) ? $data[$key]['recurring_qty'] : 1;
+ $this->bundle->push([
+ 'description' => $p->notes,
+ 'product_key' => $p->product_key,
+ 'unit_cost' => $p->price,
+ 'product' => nl2br(substr($p->notes, 0, 50)),
+ 'price' => Number::formatMoney($total, $this->subscription->company).' / '. RecurringInvoice::frequencyForKey($this->subscription->frequency_id),
+ 'total' => $total,
+ 'qty' => $qty,
+ 'is_recurring' => true,
+ 'product_image' => $p->product_image,
+ ]);
+ }
+
+ /* One time products can only have a single quantity */
+ foreach ($this->products as $key => $p) {
+ $qty = 1;
+ $total = $p->price * $qty;
+
+ $this->bundle->push([
+ 'description' => $p->notes,
+ 'product_key' => $p->product_key,
+ 'unit_cost' => $p->price,
+ 'product' => nl2br(substr($p->notes, 0, 50)),
+ 'price' => Number::formatMoney($total, $this->subscription->company),
+ 'total' => $total,
+ 'qty' => $qty,
+ 'is_recurring' => false
+ ]);
+ }
+
+ foreach ($this->data as $key => $value) {
+ /* Optional recurring products can have a variable quantity */
+ if (isset($this->data[$key]['optional_recurring_qty'])) {
+ $p = $this->optional_recurring_products->first(function ($v, $k) use ($key) {
+ return $k == $key;
+ });
+
+ $qty = isset($this->data[$key]['optional_recurring_qty']) ? $this->data[$key]['optional_recurring_qty'] : false;
$total = $p->price * $qty;
- $this->bundle->push([
- 'description' => $p->notes,
- 'product_key' => $p->product_key,
- 'unit_cost' => $p->price,
- 'product' => nl2br(substr($p->notes, 0, 50)),
- 'price' => Number::formatMoney($total, $this->subscription->company).' / '. RecurringInvoice::frequencyForKey($this->subscription->frequency_id),
- 'total' => $total,
- 'qty' => $qty,
- 'is_recurring' => true,
- 'product_image' => $p->product_image,
- ]);
+ if ($qty) {
+ $this->bundle->push([
+ 'description' => $p->notes,
+ 'product_key' => $p->product_key,
+ 'unit_cost' => $p->price,
+ 'product' => nl2br(substr($p->notes, 0, 50)),
+ 'price' => Number::formatMoney($total, $this->subscription->company).' / '. RecurringInvoice::frequencyForKey($this->subscription->frequency_id),
+ 'total' => $total,
+ 'qty' => $qty,
+ 'is_recurring' => true
+ ]);
+ }
}
- /* One time products can only have a single quantity */
- foreach($this->products as $key => $p)
- {
+ /* Optional products can have a variable quantity */
+ if (isset($this->data[$key]['optional_qty'])) {
+ $p = $this->optional_products->first(function ($v, $k) use ($key) {
+ return $k == $key;
+ });
- $qty = 1;
+ $qty = isset($this->data[$key]['optional_qty']) ? $this->data[$key]['optional_qty'] : false;
$total = $p->price * $qty;
- $this->bundle->push([
- 'description' => $p->notes,
- 'product_key' => $p->product_key,
- 'unit_cost' => $p->price,
- 'product' => nl2br(substr($p->notes, 0, 50)),
- 'price' => Number::formatMoney($total, $this->subscription->company),
- 'total' => $total,
- 'qty' => $qty,
- 'is_recurring' => false
- ]);
-
- }
-
- foreach($this->data as $key => $value)
- {
-
- /* Optional recurring products can have a variable quantity */
- if(isset($this->data[$key]['optional_recurring_qty']))
- {
- $p = $this->optional_recurring_products->first(function ($v,$k) use($key){
- return $k == $key;
- });
-
- $qty = isset($this->data[$key]['optional_recurring_qty']) ? $this->data[$key]['optional_recurring_qty'] : false;
- $total = $p->price * $qty;
-
- if($qty)
- {
-
- $this->bundle->push([
- 'description' => $p->notes,
- 'product_key' => $p->product_key,
- 'unit_cost' => $p->price,
- 'product' => nl2br(substr($p->notes, 0, 50)),
- 'price' => Number::formatMoney($total, $this->subscription->company).' / '. RecurringInvoice::frequencyForKey($this->subscription->frequency_id),
- 'total' => $total,
- 'qty' => $qty,
- 'is_recurring' => true
- ]);
-
- }
+ if ($qty) {
+ $this->bundle->push([
+ 'description' => $p->notes,
+ 'product_key' => $p->product_key,
+ 'unit_cost' => $p->price,
+ 'product' => nl2br(substr($p->notes, 0, 50)),
+ 'price' => Number::formatMoney($total, $this->subscription->company),
+ 'total' => $total,
+ 'qty' => $qty,
+ 'is_recurring' => false
+ ]);
}
-
- /* Optional products can have a variable quantity */
- if(isset($this->data[$key]['optional_qty']))
- {
- $p = $this->optional_products->first(function ($v,$k) use($key){
- return $k == $key;
- });
-
- $qty = isset($this->data[$key]['optional_qty']) ? $this->data[$key]['optional_qty'] : false;
- $total = $p->price * $qty;
-
- if($qty)
- {
- $this->bundle->push([
- 'description' => $p->notes,
- 'product_key' => $p->product_key,
- 'unit_cost' => $p->price,
- 'product' => nl2br(substr($p->notes, 0, 50)),
- 'price' => Number::formatMoney($total, $this->subscription->company),
- 'total' => $total,
- 'qty' => $qty,
- 'is_recurring' => false
- ]);
- }
-
- }
-
}
+ }
$this->sub_total = Number::formatMoney($this->bundle->sum('total'), $this->subscription->company);
$this->total = $this->sub_total;
- if($this->valid_coupon)
- {
-
- if($this->subscription->is_amount_discount)
+ if ($this->valid_coupon) {
+ if ($this->subscription->is_amount_discount) {
$discount = $this->subscription->promo_discount;
- else
+ } else {
$discount = round($this->bundle->sum('total') * ($this->subscription->promo_discount / 100), 2);
+ }
$this->discount = Number::formatMoney($discount, $this->subscription->company);
$this->total = Number::formatMoney(($this->bundle->sum('total') - $discount), $this->subscription->company);
$this->float_amount_total = ($this->bundle->sum('total') - $discount);
- }
- else {
+ } else {
$this->float_amount_total = $this->bundle->sum('total');
$this->total = Number::formatMoney($this->float_amount_total, $this->subscription->company);
-
}
return $this;
}
/**
- * @return $this
- * @throws PresenterException
- * @throws InvalidArgumentException
+ * @return $this
+ * @throws PresenterException
+ * @throws InvalidArgumentException
*/
private function createClientContact()
{
-
$company = $this->subscription->company;
$user = $this->subscription->user;
$user->setCompany($company);
@@ -459,18 +424,19 @@ class BillingPortalPurchasev2 extends Component
Auth::guard('contact')->loginUsingId($this->contact->id, true);
return $this;
- }
+ }
/**
- * @param mixed $propertyName
- *
- * @return BillingPortalPurchasev2
+ * @param mixed $propertyName
+ *
+ * @return BillingPortalPurchasev2
*/
public function updated($propertyName) :self
{
- if(in_array($propertyName, ['login','email']))
+ if (in_array($propertyName, ['login','email'])) {
return $this;
+ }
$this->buildBundle();
@@ -486,11 +452,13 @@ class BillingPortalPurchasev2 extends Component
{
nlog("total amount = {$this->float_amount_total}");
- if($this->float_amount_total == 0)
+ if ($this->float_amount_total == 0) {
$this->methods = [];
+ }
- if($this->contact && $this->float_amount_total >= 1)
+ if ($this->contact && $this->float_amount_total >= 1) {
$this->methods = $this->contact->client->service()->getPaymentMethods($this->float_amount_total);
+ }
return $this;
}
@@ -519,16 +487,13 @@ class BillingPortalPurchasev2 extends Component
*/
public function handleBeforePaymentEvents() :self
{
-
$eligibility_check = $this->subscription->service()->isEligible($this->contact);
- if(is_array($eligibility_check) && $eligibility_check['message'] != 'Success'){
-
+ if (is_array($eligibility_check) && $eligibility_check['message'] != 'Success') {
$this->is_eligible = false;
$this->not_eligible_message = $eligibility_check['message'];
return $this;
-
}
$data = [
@@ -565,13 +530,12 @@ class BillingPortalPurchasev2 extends Component
$this->emit('beforePaymentEventsCompleted');
return $this;
-
}
/**
* Starts the trial
- *
+ *
* @return \Illuminate\Routing\Redirector|\Illuminate\Http\RedirectResponse
*/
public function handleTrial()
@@ -586,22 +550,19 @@ class BillingPortalPurchasev2 extends Component
}
/**
- * When the subscription total comes to $0 we
+ * When the subscription total comes to $0 we
* pass back a $0 Invoice.
*
* @return \Illuminate\Routing\Redirector|\Illuminate\Http\RedirectResponse
*/
public function handlePaymentNotRequired()
{
-
$eligibility_check = $this->subscription->service()->isEligible($this->contact);
- if(is_array($eligibility_check) && $eligibility_check['message'] != 'Success'){
-
+ if (is_array($eligibility_check) && $eligibility_check['message'] != 'Success') {
$this->is_eligible = false;
$this->not_eligible_message = $eligibility_check['message'];
return $this;
-
}
$invoice = $this->subscription
@@ -612,16 +573,15 @@ class BillingPortalPurchasev2 extends Component
->adjustInventory()
->save();
- $invoice->number = null;
+ $invoice->number = null;
- $invoice->service()
- ->markPaid()
- ->save();
-
- return $this->subscription
- ->service()
- ->handleNoPaymentFlow($invoice, $this->bundle, $this->contact);
+ $invoice->service()
+ ->markPaid()
+ ->save();
+ return $this->subscription
+ ->service()
+ ->handleNoPaymentFlow($invoice, $this->bundle, $this->contact);
}
@@ -655,7 +615,6 @@ class BillingPortalPurchasev2 extends Component
public function store()
{
-
}
/**
@@ -691,25 +650,22 @@ class BillingPortalPurchasev2 extends Component
}
}
- if(array_key_exists('currency_id', $this->request_data)) {
-
- $currency = Cache::get('currencies')->filter(function ($item){
+ if (array_key_exists('currency_id', $this->request_data)) {
+ $currency = Cache::get('currencies')->filter(function ($item) {
return $item->id == $this->request_data['currency_id'];
})->first();
- if($currency)
+ if ($currency) {
$data['settings']->currency_id = $currency->id;
-
- }
- elseif($this->subscription->group_settings && property_exists($this->subscription->group_settings->settings, 'currency_id')) {
-
- $currency = Cache::get('currencies')->filter(function ($item){
+ }
+ } elseif ($this->subscription->group_settings && property_exists($this->subscription->group_settings->settings, 'currency_id')) {
+ $currency = Cache::get('currencies')->filter(function ($item) {
return $item->id == $this->subscription->group_settings->settings->currency_id;
})->first();
- if($currency)
+ if ($currency) {
$data['settings']->currency_id = $currency->id;
-
+ }
}
if (array_key_exists('locale', $this->request_data)) {
@@ -749,5 +705,4 @@ class BillingPortalPurchasev2 extends Component
return render('components.livewire.billing-portal-purchasev2');
}
-
}
diff --git a/app/Http/Livewire/DocumentsTable.php b/app/Http/Livewire/DocumentsTable.php
index f808004d2e5b..277886344ce6 100644
--- a/app/Http/Livewire/DocumentsTable.php
+++ b/app/Http/Livewire/DocumentsTable.php
@@ -83,7 +83,7 @@ class DocumentsTable extends Component
break;
case 'expenses':
- // $this->query = $this->expenses();
+ // $this->query = $this->expenses();
break;
case 'invoices':
diff --git a/app/Http/Livewire/PurchaseOrdersTable.php b/app/Http/Livewire/PurchaseOrdersTable.php
index cb5f1120dc12..438f368e7745 100644
--- a/app/Http/Livewire/PurchaseOrdersTable.php
+++ b/app/Http/Livewire/PurchaseOrdersTable.php
@@ -16,7 +16,6 @@ use App\Libraries\MultiDB;
use App\Models\Invoice;
use App\Models\PurchaseOrder;
use App\Utils\Traits\WithSorting;
-use Carbon\Carbon;
use Livewire\Component;
use Livewire\WithPagination;
diff --git a/app/Http/Livewire/QuotesTable.php b/app/Http/Livewire/QuotesTable.php
index 8ed587326661..69d9677c83c9 100644
--- a/app/Http/Livewire/QuotesTable.php
+++ b/app/Http/Livewire/QuotesTable.php
@@ -15,7 +15,6 @@ namespace App\Http\Livewire;
use App\Libraries\MultiDB;
use App\Models\Company;
use App\Models\Quote;
-use App\Utils\Traits\WithSorting;
use Livewire\Component;
use Livewire\WithPagination;
@@ -29,7 +28,7 @@ class QuotesTable extends Component
public Company $company;
- public string $sort = 'status_id';
+ public string $sort = 'status_id';
public bool $sort_asc = true;
@@ -56,16 +55,13 @@ class QuotesTable extends Component
public function render()
{
-
$query = Quote::query()
->with('client.contacts', 'company')
->orderBy($this->sort, $this->sort_asc ? 'asc' : 'desc');
if (count($this->status) > 0) {
-
/* Special filter for expired*/
if (in_array('-1', $this->status)) {
-
$query->where(function ($query) {
$query->whereDate('due_date', '<=', now()->startOfDay())
->whereNotNull('due_date')
diff --git a/app/Http/Livewire/RecurringInvoices/UpdateAutoBilling.php b/app/Http/Livewire/RecurringInvoices/UpdateAutoBilling.php
index f7183ec3b52a..da7831e4065d 100644
--- a/app/Http/Livewire/RecurringInvoices/UpdateAutoBilling.php
+++ b/app/Http/Livewire/RecurringInvoices/UpdateAutoBilling.php
@@ -28,7 +28,7 @@ class UpdateAutoBilling extends Component
Invoice::where('recurring_id', $this->invoice->id)
->whereIn('status_id', [2,3])
- ->where('is_deleted',0)
+ ->where('is_deleted', 0)
->where('balance', '>', 0)
->update(['auto_bill_enabled' => $this->invoice->auto_bill_enabled]);
}
diff --git a/app/Http/Livewire/RequiredClientInfo.php b/app/Http/Livewire/RequiredClientInfo.php
index a2286249e584..f4d0c1a13f79 100644
--- a/app/Http/Livewire/RequiredClientInfo.php
+++ b/app/Http/Livewire/RequiredClientInfo.php
@@ -149,8 +149,7 @@ class RequiredClientInfo extends Component
$this->client = $this->contact->client;
- if($this->company->settings->show_accept_invoice_terms && request()->query('hash'))
- {
+ if ($this->company->settings->show_accept_invoice_terms && request()->query('hash')) {
$this->show_terms = true;
$this->terms_accepted = false;
$this->show_form = true;
@@ -158,19 +157,16 @@ class RequiredClientInfo extends Component
$hash = Cache::get(request()->input('hash'));
$this->invoice = Invoice::find($this->decodePrimaryKey($hash['invoice_id']));
-
}
count($this->fields) > 0 || $this->show_terms
? $this->checkFields()
: $this->show_form = false;
-
}
public function toggleTermsAccepted()
{
$this->terms_accepted = !$this->terms_accepted;
-
}
public function handleSubmit(array $data): bool
@@ -209,7 +205,6 @@ class RequiredClientInfo extends Component
private function updateClientDetails(array $data): bool
{
-
$client = [];
$contact = [];
@@ -232,13 +227,12 @@ class RequiredClientInfo extends Component
->push();
if ($contact_update && $client_update) {
-
$cg = CompanyGateway::find($this->company_gateway_id);
- if($cg && $cg->update_details){
+ if ($cg && $cg->update_details) {
$payment_gateway = $cg->driver($this->client)->init();
- // if(method_exists($payment_gateway, "updateCustomer"))
+ // if(method_exists($payment_gateway, "updateCustomer"))
// $payment_gateway->updateCustomer();
}
@@ -269,7 +263,6 @@ class RequiredClientInfo extends Component
}
}
}
-
}
public function showCopyBillingCheckbox(): bool
diff --git a/app/Http/Livewire/SubscriptionPlanSwitch.php b/app/Http/Livewire/SubscriptionPlanSwitch.php
index 8a1f92128dc1..484493179b42 100644
--- a/app/Http/Livewire/SubscriptionPlanSwitch.php
+++ b/app/Http/Livewire/SubscriptionPlanSwitch.php
@@ -105,7 +105,9 @@ class SubscriptionPlanSwitch extends Component
'hash' => $this->hash,
]);
- Cache::put($this->hash, [
+ Cache::put(
+ $this->hash,
+ [
'subscription_id' => $this->target->hashed_id,
'target_id' => $this->target->hashed_id,
'recurring_invoice' => $this->recurring_invoice->hashed_id,
@@ -113,7 +115,7 @@ class SubscriptionPlanSwitch extends Component
'invoice_id' => $this->state['invoice']->hashed_id,
'context' => 'change_plan',
now()->addMinutes(60), ]
- );
+ );
$this->state['payment_initialised'] = true;
} else {
diff --git a/app/Http/Livewire/WepaySignup.php b/app/Http/Livewire/WepaySignup.php
index d4c747d83e65..7ef0b68ea0bd 100644
--- a/app/Http/Livewire/WepaySignup.php
+++ b/app/Http/Livewire/WepaySignup.php
@@ -20,7 +20,6 @@ use App\Models\CompanyGateway;
use App\Models\GatewayType;
use App\Models\User;
use App\PaymentDrivers\WePayPaymentDriver;
-use Illuminate\Support\Facades\Hash;
use Livewire\Component;
use WePay;
diff --git a/app/Http/Middleware/ContactAccount.php b/app/Http/Middleware/ContactAccount.php
index ce932f397c7d..1cecef46a1cd 100644
--- a/app/Http/Middleware/ContactAccount.php
+++ b/app/Http/Middleware/ContactAccount.php
@@ -11,7 +11,6 @@
namespace App\Http\Middleware;
-use App\Libraries\MultiDB;
use App\Models\Account;
use App\Utils\Ninja;
use Closure;
diff --git a/app/Http/Middleware/ContactKeyLogin.php b/app/Http/Middleware/ContactKeyLogin.php
index a8bb99e170e8..b45f1c465ca6 100644
--- a/app/Http/Middleware/ContactKeyLogin.php
+++ b/app/Http/Middleware/ContactKeyLogin.php
@@ -68,9 +68,9 @@ class ContactKeyLogin
} elseif ($request->segment(3) && config('ninja.db.multi_db_enabled')) {
if (MultiDB::findAndSetDbByContactKey($request->segment(3))) {
if ($client_contact = ClientContact::with('company')->where('contact_key', $request->segment(3))->first()) {
-
- if($client_contact->company->settings->enable_client_portal_password)
+ if ($client_contact->company->settings->enable_client_portal_password) {
return redirect()->route('client.login', ['company_key' => $client_contact->company->company_key]);
+ }
if (empty($client_contact->email)) {
$client_contact->email = Str::random(6).'@example.com';
@@ -88,9 +88,9 @@ class ContactKeyLogin
}
} elseif ($request->segment(2) && $request->segment(2) == 'key_login' && $request->segment(3)) {
if ($client_contact = ClientContact::with('company')->where('contact_key', $request->segment(3))->first()) {
-
- if($client_contact->company->settings->enable_client_portal_password)
+ if ($client_contact->company->settings->enable_client_portal_password) {
return redirect()->route('client.login', ['company_key' => $client_contact->company->company_key]);
+ }
if (empty($client_contact->email)) {
$client_contact->email = Str::random(6).'@example.com';
@@ -135,9 +135,9 @@ class ContactKeyLogin
}
} elseif ($request->segment(3)) {
if ($client_contact = ClientContact::with('company')->where('contact_key', $request->segment(3))->first()) {
-
- if($client_contact->company->settings->enable_client_portal_password)
+ if ($client_contact->company->settings->enable_client_portal_password) {
return redirect()->route('client.login', ['company_key' => $client_contact->company->company_key]);
+ }
if (empty($client_contact->email)) {
$client_contact->email = Str::random(6).'@example.com';
diff --git a/app/Http/Middleware/Cors.php b/app/Http/Middleware/Cors.php
index f5cb51145651..869157ea686e 100644
--- a/app/Http/Middleware/Cors.php
+++ b/app/Http/Middleware/Cors.php
@@ -4,7 +4,6 @@ namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Response;
-use Symfony\Component\HttpFoundation\BinaryFileResponse;
class Cors
{
diff --git a/app/Http/Middleware/Locale.php b/app/Http/Middleware/Locale.php
index e203a4d03233..cea5b9b8f7b6 100644
--- a/app/Http/Middleware/Locale.php
+++ b/app/Http/Middleware/Locale.php
@@ -14,7 +14,6 @@ namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
-use Illuminate\Support\Facades\Auth;
class Locale
{
@@ -27,7 +26,6 @@ class Locale
*/
public function handle($request, Closure $next)
{
-
/*LOCALE SET */
if ($request->has('lang')) {
$locale = $request->input('lang');
diff --git a/app/Http/Middleware/PasswordProtection.php b/app/Http/Middleware/PasswordProtection.php
index ddd0c51aa8ff..2c3aa7773b72 100644
--- a/app/Http/Middleware/PasswordProtection.php
+++ b/app/Http/Middleware/PasswordProtection.php
@@ -32,7 +32,6 @@ class PasswordProtection
*/
public function handle($request, Closure $next)
{
-
$error = [
'message' => 'Invalid Password',
'errors' => new stdClass,
@@ -40,38 +39,33 @@ class PasswordProtection
$timeout = auth()->user()->company()->default_password_timeout;
- if($timeout == 0)
+ if ($timeout == 0) {
$timeout = 30*60*1000*1000;
- else
+ } else {
$timeout = $timeout/1000;
+ }
//test if password if base64 encoded
$x_api_password = $request->header('X-API-PASSWORD');
- if($request->header('X-API-PASSWORD-BASE64'))
- {
+ if ($request->header('X-API-PASSWORD-BASE64')) {
$x_api_password = base64_decode($request->header('X-API-PASSWORD-BASE64'));
}
// If no password supplied - then we just check if their authentication is in cache //
if (Cache::get(auth()->user()->hashed_id.'_'.auth()->user()->account_id.'_logged_in') && !$x_api_password) {
-
Cache::put(auth()->user()->hashed_id.'_'.auth()->user()->account_id.'_logged_in', Str::random(64), $timeout);
return $next($request);
-
- }elseif( $request->header('X-API-OAUTH-PASSWORD') && strlen($request->header('X-API-OAUTH-PASSWORD')) >=1){
-
+ } elseif ($request->header('X-API-OAUTH-PASSWORD') && strlen($request->header('X-API-OAUTH-PASSWORD')) >=1) {
//user is attempting to reauth with OAuth - check the token value
//todo expand this to include all OAuth providers
- if(auth()->user()->oauth_provider_id == 'google')
- {
+ if (auth()->user()->oauth_provider_id == 'google') {
$user = false;
$google = new Google();
$user = $google->getTokenResponse(request()->header('X-API-OAUTH-PASSWORD'));
if (is_array($user)) {
-
$query = [
'oauth_user_id' => $google->harvestSubField($user),
'oauth_provider_id'=> 'google'
@@ -79,67 +73,47 @@ class PasswordProtection
//If OAuth and user also has a password set - check both
if ($existing_user = MultiDB::hasUser($query) && auth()->user()->company()->oauth_password_required && auth()->user()->has_password && Hash::check(auth()->user()->password, $x_api_password)) {
-
nlog("existing user with password");
Cache::put(auth()->user()->hashed_id.'_'.auth()->user()->account_id.'_logged_in', Str::random(64), $timeout);
return $next($request);
- }
- elseif($existing_user = MultiDB::hasUser($query) && !auth()->user()->company()->oauth_password_required){
-
+ } elseif ($existing_user = MultiDB::hasUser($query) && !auth()->user()->company()->oauth_password_required) {
nlog("existing user without password");
Cache::put(auth()->user()->hashed_id.'_'.auth()->user()->account_id.'_logged_in', Str::random(64), $timeout);
- return $next($request);
+ return $next($request);
}
}
-
- }
- elseif(auth()->user()->oauth_provider_id == 'microsoft')
- {
- try{
- $payload = json_decode(base64_decode(str_replace('_', '/', str_replace('-','+',explode('.', request()->header('X-API-OAUTH-PASSWORD'))[1]))));
- }
- catch(\Exception $e){
+ } elseif (auth()->user()->oauth_provider_id == 'microsoft') {
+ try {
+ $payload = json_decode(base64_decode(str_replace('_', '/', str_replace('-', '+', explode('.', request()->header('X-API-OAUTH-PASSWORD'))[1]))));
+ } catch(\Exception $e) {
nlog("could not decode microsoft response");
return response()->json(['message' => 'Could not decode the response from Microsoft'], 412);
}
- if($payload->preferred_username == auth()->user()->email){
-
+ if ($payload->preferred_username == auth()->user()->email) {
Cache::put(auth()->user()->hashed_id.'_'.auth()->user()->account_id.'_logged_in', Str::random(64), $timeout);
return $next($request);
}
- }
- elseif(auth()->user()->oauth_provider_id == 'apple')
- {
-
+ } elseif (auth()->user()->oauth_provider_id == 'apple') {
$user = Socialite::driver('apple')->userFromToken($request->header('X-API-OAUTH-PASSWORD'));
- if($user && ($user->email == auth()->user()->email)){
-
+ if ($user && ($user->email == auth()->user()->email)) {
Cache::put(auth()->user()->hashed_id.'_'.auth()->user()->account_id.'_logged_in', Str::random(64), $timeout);
return $next($request);
}
-
}
return response()->json($error, 412);
-
-
- }elseif ($x_api_password && Hash::check($x_api_password, auth()->user()->password)) {
-
+ } elseif ($x_api_password && Hash::check($x_api_password, auth()->user()->password)) {
Cache::put(auth()->user()->hashed_id.'_'.auth()->user()->account_id.'_logged_in', Str::random(64), $timeout);
return $next($request);
-
} else {
-
return response()->json($error, 412);
}
-
-
}
-}
\ No newline at end of file
+}
diff --git a/app/Http/Middleware/QueryLogging.php b/app/Http/Middleware/QueryLogging.php
index 2e8a6d052ab9..a41de37b2cb2 100644
--- a/app/Http/Middleware/QueryLogging.php
+++ b/app/Http/Middleware/QueryLogging.php
@@ -33,7 +33,6 @@ class QueryLogging
*/
public function handle(Request $request, Closure $next)
{
-
// Enable query logging for development
if (! Ninja::isHosted() || ! config('beacon.enabled')) {
return $next($request);
@@ -69,7 +68,7 @@ class QueryLogging
$ip = request()->ip();
}
- LightLogs::create(new DbQuery($request->method(), substr(urldecode($request->url()),0,180), $count, $time, $ip))
+ LightLogs::create(new DbQuery($request->method(), substr(urldecode($request->url()), 0, 180), $count, $time, $ip))
->batch();
}
diff --git a/app/Http/Middleware/RedirectIfAuthenticated.php b/app/Http/Middleware/RedirectIfAuthenticated.php
index b73804aec818..96640d0780c1 100644
--- a/app/Http/Middleware/RedirectIfAuthenticated.php
+++ b/app/Http/Middleware/RedirectIfAuthenticated.php
@@ -42,7 +42,7 @@ class RedirectIfAuthenticated
case 'vendor':
if (Auth::guard($guard)->check()) {
//TODO create routes for vendor
- // return redirect()->route('vendor.dashboard');
+ // return redirect()->route('vendor.dashboard');
}
break;
default:
diff --git a/app/Http/Middleware/SessionDomains.php b/app/Http/Middleware/SessionDomains.php
index 4e7b7ddfd22a..261f84217c01 100644
--- a/app/Http/Middleware/SessionDomains.php
+++ b/app/Http/Middleware/SessionDomains.php
@@ -14,7 +14,6 @@ namespace App\Http\Middleware;
use App\Utils\Ninja;
use Closure;
use Illuminate\Http\Request;
-use Illuminate\Support\Facades\Cookie;
class SessionDomains
{
diff --git a/app/Http/Middleware/SetInviteDb.php b/app/Http/Middleware/SetInviteDb.php
index a6df51daa7ca..07dc7b4419d1 100644
--- a/app/Http/Middleware/SetInviteDb.php
+++ b/app/Http/Middleware/SetInviteDb.php
@@ -53,7 +53,6 @@ class SetInviteDb
/* Try and determine the DB from the invitation key STRING*/
if (config('ninja.db.multi_db_enabled')) {
-
// nlog("/ Try and determine the DB from the invitation key /");
$hashids = new Hashids(config('ninja.hash_salt'), 10);
diff --git a/app/Http/Middleware/StartupCheck.php b/app/Http/Middleware/StartupCheck.php
index d4b3686ab91f..31d091e8a4ee 100644
--- a/app/Http/Middleware/StartupCheck.php
+++ b/app/Http/Middleware/StartupCheck.php
@@ -39,7 +39,6 @@ class StartupCheck
foreach ($cached_tables as $name => $class) {
if ($request->has('clear_cache') || ! Cache::has($name)) {
-
// check that the table exists in case the migration is pending
if (! Schema::hasTable((new $class())->getTable())) {
continue;
diff --git a/app/Http/Middleware/TokenAuth.php b/app/Http/Middleware/TokenAuth.php
index abd52376f098..00858a707b0a 100644
--- a/app/Http/Middleware/TokenAuth.php
+++ b/app/Http/Middleware/TokenAuth.php
@@ -11,7 +11,6 @@
namespace App\Http\Middleware;
-use App\Events\User\UserLoggedIn;
use App\Models\CompanyToken;
use App\Models\User;
use App\Utils\Ninja;
@@ -70,7 +69,7 @@ class TokenAuth
/*
| This method binds the db to the jobs created using this
- | session
+ | session
*/
app('queue')->createPayloadUsing(function () use ($company_token) {
return ['db' => $company_token->company->db];
diff --git a/app/Http/Middleware/UserVerified.php b/app/Http/Middleware/UserVerified.php
index f92209cab001..c951c13f3a6f 100644
--- a/app/Http/Middleware/UserVerified.php
+++ b/app/Http/Middleware/UserVerified.php
@@ -11,11 +11,9 @@
namespace App\Http\Middleware;
-use App\Libraries\MultiDB;
use App\Models\User;
use App\Utils\Ninja;
use Closure;
-use Hashids\Hashids;
use Illuminate\Http\Request;
/**
diff --git a/app/Http/Middleware/VendorContactKeyLogin.php b/app/Http/Middleware/VendorContactKeyLogin.php
index c599ba7aac45..ae7e93ca1169 100644
--- a/app/Http/Middleware/VendorContactKeyLogin.php
+++ b/app/Http/Middleware/VendorContactKeyLogin.php
@@ -11,7 +11,6 @@
namespace App\Http\Middleware;
-use App\Http\ViewComposers\PortalComposer;
use App\Libraries\MultiDB;
use App\Models\Vendor;
use App\Models\VendorContact;
@@ -148,8 +147,6 @@ class VendorContactKeyLogin
private function setRedirectPath()
{
-
return 'vendor/purchase_orders';
-
}
}
diff --git a/app/Http/Middleware/VendorLocale.php b/app/Http/Middleware/VendorLocale.php
index 580449a6a4a4..a64fc1ec41f5 100644
--- a/app/Http/Middleware/VendorLocale.php
+++ b/app/Http/Middleware/VendorLocale.php
@@ -14,7 +14,6 @@ namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
-use Illuminate\Support\Facades\Auth;
class VendorLocale
{
diff --git a/app/Http/Middleware/VerifyHash.php b/app/Http/Middleware/VerifyHash.php
index f572221bac1f..f06e5bca4ccc 100644
--- a/app/Http/Middleware/VerifyHash.php
+++ b/app/Http/Middleware/VerifyHash.php
@@ -2,10 +2,7 @@
namespace App\Http\Middleware;
-use App\Models\Account;
-use App\Models\Company;
use App\Models\PaymentHash;
-use App\Utils\Ninja;
use Closure;
use Illuminate\Http\Request;
@@ -20,16 +17,14 @@ class VerifyHash
*/
public function handle($request, Closure $next)
{
-
- if($request->has('payment_hash')){
-
+ if ($request->has('payment_hash')) {
$ph = PaymentHash::with('fee_invoice')->where('hash', $request->payment_hash)->first();
- if($ph)
+ if ($ph) {
auth()->guard('contact')->loginUsingId($ph->fee_invoice->invitations->first()->contact->id, true);
+ }
return $next($request);
-
}
abort(404, 'Unable to verify payment hash');
diff --git a/app/Http/Requests/Account/UpdateAccountRequest.php b/app/Http/Requests/Account/UpdateAccountRequest.php
index c0373220c1e6..a55c1d7708c6 100644
--- a/app/Http/Requests/Account/UpdateAccountRequest.php
+++ b/app/Http/Requests/Account/UpdateAccountRequest.php
@@ -12,10 +12,6 @@
namespace App\Http\Requests\Account;
use App\Http\Requests\Request;
-use App\Http\ValidationRules\Account\BlackListRule;
-use App\Http\ValidationRules\Account\EmailBlackListRule;
-use App\Http\ValidationRules\NewUniqueUserRule;
-use App\Utils\Ninja;
class UpdateAccountRequest extends Request
{
diff --git a/app/Http/Requests/BankIntegration/AdminBankIntegrationRequest.php b/app/Http/Requests/BankIntegration/AdminBankIntegrationRequest.php
index 7f9b8d3bed65..ffe01a3f2cf6 100644
--- a/app/Http/Requests/BankIntegration/AdminBankIntegrationRequest.php
+++ b/app/Http/Requests/BankIntegration/AdminBankIntegrationRequest.php
@@ -12,7 +12,6 @@
namespace App\Http\Requests\BankIntegration;
use App\Http\Requests\Request;
-use App\Models\BankIntegration;
class AdminBankIntegrationRequest extends Request
{
diff --git a/app/Http/Requests/BankIntegration/BulkBankIntegrationRequest.php b/app/Http/Requests/BankIntegration/BulkBankIntegrationRequest.php
index 6c424ed829c6..965b245608f0 100644
--- a/app/Http/Requests/BankIntegration/BulkBankIntegrationRequest.php
+++ b/app/Http/Requests/BankIntegration/BulkBankIntegrationRequest.php
@@ -27,11 +27,9 @@ class BulkBankIntegrationRequest extends Request
public function rules()
{
-
return [
'ids' => 'required|bail|array',
'action' => 'in:archive,restore,delete'
];
-
}
}
diff --git a/app/Http/Requests/BankIntegration/StoreBankIntegrationRequest.php b/app/Http/Requests/BankIntegration/StoreBankIntegrationRequest.php
index 8e19c44aa7ac..753bf6fdc66b 100644
--- a/app/Http/Requests/BankIntegration/StoreBankIntegrationRequest.php
+++ b/app/Http/Requests/BankIntegration/StoreBankIntegrationRequest.php
@@ -31,7 +31,6 @@ class StoreBankIntegrationRequest extends Request
public function rules()
{
-
$rules = [
'bank_account_name' => 'required|min:3',
'auto_sync' => 'sometimes|bool'
@@ -44,8 +43,9 @@ class StoreBankIntegrationRequest extends Request
{
$input = $this->all();
- if((!array_key_exists('provider_name', $input) || strlen($input['provider_name']) == 0) && array_key_exists('bank_account_name', $input))
+ if ((!array_key_exists('provider_name', $input) || strlen($input['provider_name']) == 0) && array_key_exists('bank_account_name', $input)) {
$input['provider_name'] = $input['bank_account_name'];
+ }
$this->replace($input);
}
@@ -54,5 +54,4 @@ class StoreBankIntegrationRequest extends Request
{
return [];
}
-
}
diff --git a/app/Http/Requests/BankIntegration/UpdateBankIntegrationRequest.php b/app/Http/Requests/BankIntegration/UpdateBankIntegrationRequest.php
index 15e73ef2c74a..15b600ac8117 100644
--- a/app/Http/Requests/BankIntegration/UpdateBankIntegrationRequest.php
+++ b/app/Http/Requests/BankIntegration/UpdateBankIntegrationRequest.php
@@ -49,5 +49,4 @@ class UpdateBankIntegrationRequest extends Request
$this->replace($input);
}
-
}
diff --git a/app/Http/Requests/BankTransaction/AdminBankTransactionRequest.php b/app/Http/Requests/BankTransaction/AdminBankTransactionRequest.php
index 5254b79d91b7..bc784e850bbe 100644
--- a/app/Http/Requests/BankTransaction/AdminBankTransactionRequest.php
+++ b/app/Http/Requests/BankTransaction/AdminBankTransactionRequest.php
@@ -12,7 +12,6 @@
namespace App\Http\Requests\BankTransaction;
use App\Http\Requests\Request;
-use App\Models\BankTransaction;
class AdminBankTransactionRequest extends Request
{
diff --git a/app/Http/Requests/BankTransaction/BulkBankTransactionRequest.php b/app/Http/Requests/BankTransaction/BulkBankTransactionRequest.php
index 4b55fa697624..a95fb7fd23a3 100644
--- a/app/Http/Requests/BankTransaction/BulkBankTransactionRequest.php
+++ b/app/Http/Requests/BankTransaction/BulkBankTransactionRequest.php
@@ -27,11 +27,9 @@ class BulkBankTransactionRequest extends Request
public function rules()
{
-
return [
'ids' => 'required|bail|array',
'action' => 'in:archive,restore,delete,convert_matched'
];
-
}
}
diff --git a/app/Http/Requests/BankTransaction/ImportBankTransactionsRequest.php b/app/Http/Requests/BankTransaction/ImportBankTransactionsRequest.php
index c07d6953f047..4eb0f3da1ffc 100644
--- a/app/Http/Requests/BankTransaction/ImportBankTransactionsRequest.php
+++ b/app/Http/Requests/BankTransaction/ImportBankTransactionsRequest.php
@@ -12,7 +12,6 @@
namespace App\Http\Requests\BankTransaction;
use App\Http\Requests\Request;
-use App\Models\BankTransaction;
class ImportBankTransactionsRequest extends Request
{
@@ -28,7 +27,6 @@ class ImportBankTransactionsRequest extends Request
public function rules()
{
-
$rules = [
'transactions' => 'bail|array',
'transactions.*.id' => 'bail|required',
@@ -39,29 +37,28 @@ class ImportBankTransactionsRequest extends Request
$rules['transactions.*.vendor_id'] = 'bail|sometimes|exists:vendors,id,company_id,'.auth()->user()->company()->id.',is_deleted,0';
return $rules;
-
}
public function prepareForValidation()
{
$inputs = $this->all();
- foreach($inputs['transactions'] as $key => $input)
- {
-
- if(array_key_exists('id', $inputs['transactions'][$key]))
+ foreach ($inputs['transactions'] as $key => $input) {
+ if (array_key_exists('id', $inputs['transactions'][$key])) {
$inputs['transactions'][$key]['id'] = $this->decodePrimaryKey($input['id']);
+ }
- if(array_key_exists('ninja_category_id', $inputs['transactions'][$key]) && strlen($inputs['transactions'][$key]['ninja_category_id']) >= 1)
+ if (array_key_exists('ninja_category_id', $inputs['transactions'][$key]) && strlen($inputs['transactions'][$key]['ninja_category_id']) >= 1) {
$inputs['transactions'][$key]['ninja_category_id'] = $this->decodePrimaryKey($inputs['transactions'][$key]['ninja_category_id']);
+ }
- if(array_key_exists('vendor_id', $inputs['transactions'][$key]) && strlen($inputs['transactions'][$key]['vendor_id']) >= 1)
+ if (array_key_exists('vendor_id', $inputs['transactions'][$key]) && strlen($inputs['transactions'][$key]['vendor_id']) >= 1) {
$inputs['transactions'][$key]['vendor_id'] = $this->decodePrimaryKey($inputs['transactions'][$key]['vendor_id']);
+ }
// $input = $this->decodePrimaryKeys($input);
}
$this->replace($inputs);
-
}
}
diff --git a/app/Http/Requests/BankTransaction/MatchBankTransactionRequest.php b/app/Http/Requests/BankTransaction/MatchBankTransactionRequest.php
index 2ec471cfea86..12946ad42d9d 100644
--- a/app/Http/Requests/BankTransaction/MatchBankTransactionRequest.php
+++ b/app/Http/Requests/BankTransaction/MatchBankTransactionRequest.php
@@ -12,7 +12,6 @@
namespace App\Http\Requests\BankTransaction;
use App\Http\Requests\Request;
-use App\Models\BankTransaction;
use App\Models\Expense;
use App\Models\Payment;
@@ -30,7 +29,6 @@ class MatchBankTransactionRequest extends Request
public function rules()
{
-
$rules = [
'transactions' => 'bail|array',
'transactions.*.invoice_ids' => 'nullable|string|sometimes',
@@ -43,49 +41,46 @@ class MatchBankTransactionRequest extends Request
$rules['transactions.*.expense_id'] = 'bail|sometimes|nullable|exists:expenses,id,company_id,'.auth()->user()->company()->id.',is_deleted,0';
return $rules;
-
}
public function prepareForValidation()
{
$inputs = $this->all();
- foreach($inputs['transactions'] as $key => $input)
- {
-
- if(array_key_exists('id', $inputs['transactions'][$key]))
+ foreach ($inputs['transactions'] as $key => $input) {
+ if (array_key_exists('id', $inputs['transactions'][$key])) {
$inputs['transactions'][$key]['id'] = $this->decodePrimaryKey($input['id']);
+ }
- if(array_key_exists('ninja_category_id', $inputs['transactions'][$key]) && strlen($inputs['transactions'][$key]['ninja_category_id']) >= 1)
+ if (array_key_exists('ninja_category_id', $inputs['transactions'][$key]) && strlen($inputs['transactions'][$key]['ninja_category_id']) >= 1) {
$inputs['transactions'][$key]['ninja_category_id'] = $this->decodePrimaryKey($inputs['transactions'][$key]['ninja_category_id']);
+ }
- if(array_key_exists('vendor_id', $inputs['transactions'][$key]) && strlen($inputs['transactions'][$key]['vendor_id']) >= 1)
+ if (array_key_exists('vendor_id', $inputs['transactions'][$key]) && strlen($inputs['transactions'][$key]['vendor_id']) >= 1) {
$inputs['transactions'][$key]['vendor_id'] = $this->decodePrimaryKey($inputs['transactions'][$key]['vendor_id']);
+ }
- if(array_key_exists('payment_id', $inputs['transactions'][$key]) && strlen($inputs['transactions'][$key]['payment_id']) >= 1){
+ if (array_key_exists('payment_id', $inputs['transactions'][$key]) && strlen($inputs['transactions'][$key]['payment_id']) >= 1) {
$inputs['transactions'][$key]['payment_id'] = $this->decodePrimaryKey($inputs['transactions'][$key]['payment_id']);
$p = Payment::withTrashed()->where('company_id', auth()->user()->company()->id)->where('id', $inputs['transactions'][$key]['payment_id'])->first();
/*Ensure we don't relink an existing payment*/
- if(!$p || is_numeric($p->transaction_id)){
+ if (!$p || is_numeric($p->transaction_id)) {
unset($inputs['transactions'][$key]);
}
-
}
- if(array_key_exists('expense_id', $inputs['transactions'][$key]) && strlen($inputs['transactions'][$key]['expense_id']) >= 1){
+ if (array_key_exists('expense_id', $inputs['transactions'][$key]) && strlen($inputs['transactions'][$key]['expense_id']) >= 1) {
$inputs['transactions'][$key]['expense_id'] = $this->decodePrimaryKey($inputs['transactions'][$key]['expense_id']);
$e = Expense::withTrashed()->where('company_id', auth()->user()->company()->id)->where('id', $inputs['transactions'][$key]['expense_id'])->first();
/*Ensure we don't relink an existing expense*/
- if(!$e || is_numeric($e->transaction_id))
+ if (!$e || is_numeric($e->transaction_id)) {
unset($inputs['transactions'][$key]['expense_id']);
-
+ }
}
-
}
$this->replace($inputs);
-
}
}
diff --git a/app/Http/Requests/BankTransaction/StoreBankTransactionRequest.php b/app/Http/Requests/BankTransaction/StoreBankTransactionRequest.php
index 2c6523a6dbfe..266aa4eb0328 100644
--- a/app/Http/Requests/BankTransaction/StoreBankTransactionRequest.php
+++ b/app/Http/Requests/BankTransaction/StoreBankTransactionRequest.php
@@ -31,7 +31,6 @@ class StoreBankTransactionRequest extends Request
public function rules()
{
-
$rules = [];
$rules['bank_integration_id'] = 'bail|required|exists:bank_integrations,id,company_id,'.auth()->user()->company()->id.',is_deleted,0';
@@ -43,13 +42,12 @@ class StoreBankTransactionRequest extends Request
{
$input = $this->all();
- if(array_key_exists('bank_integration_id', $input) && $input['bank_integration_id'] == "")
- unset($input['bank_integration_id']);
- elseif(array_key_exists('bank_integration_id', $input) && strlen($input['bank_integration_id']) > 1 && !is_numeric($input['bank_integration_id']))
- $input['bank_integration_id'] = $this->decodePrimaryKey($input['bank_integration_id']);
+ if (array_key_exists('bank_integration_id', $input) && $input['bank_integration_id'] == "") {
+ unset($input['bank_integration_id']);
+ } elseif (array_key_exists('bank_integration_id', $input) && strlen($input['bank_integration_id']) > 1 && !is_numeric($input['bank_integration_id'])) {
+ $input['bank_integration_id'] = $this->decodePrimaryKey($input['bank_integration_id']);
+ }
$this->replace($input);
}
-
-
}
diff --git a/app/Http/Requests/BankTransaction/UpdateBankTransactionRequest.php b/app/Http/Requests/BankTransaction/UpdateBankTransactionRequest.php
index e4da4dfc5fad..c774e8a1dd75 100644
--- a/app/Http/Requests/BankTransaction/UpdateBankTransactionRequest.php
+++ b/app/Http/Requests/BankTransaction/UpdateBankTransactionRequest.php
@@ -36,14 +36,17 @@ class UpdateBankTransactionRequest extends Request
'amount' => 'numeric|required',
];
- if (isset($this->currency_id))
+ if (isset($this->currency_id)) {
$rules['currency_id'] = 'sometimes|exists:currencies,id';
+ }
- if(isset($this->vendor_id))
+ if (isset($this->vendor_id)) {
$rules['vendor_id'] = 'bail|required|exists:vendors,id,company_id,'.auth()->user()->company()->id.',is_deleted,0';
+ }
- if(isset($this->expense_id))
+ if (isset($this->expense_id)) {
$rules['expense_id'] = 'bail|required|exists:expenses,id,company_id,'.auth()->user()->company()->id.',is_deleted,0';
+ }
$rules['bank_integration_id'] = 'bail|required|exists:bank_integrations,id,company_id,'.auth()->user()->company()->id.',is_deleted,0';
@@ -56,24 +59,28 @@ class UpdateBankTransactionRequest extends Request
$input = $this->all();
- if(array_key_exists('baseType', $input) && strlen($input['baseType']) > 1)
- $input['base_type'] = $input['baseType']; //== 'deposit' ? 'CREDIT' : 'DEBIT';
+ if (array_key_exists('baseType', $input) && strlen($input['baseType']) > 1) {
+ $input['base_type'] = $input['baseType'];
+ } //== 'deposit' ? 'CREDIT' : 'DEBIT';
- if(array_key_exists('vendor_id', $input) && strlen($input['vendor_id']) > 1)
- $input['vendor_id'] = $this->decodePrimaryKey($input['vendor_id']);
+ if (array_key_exists('vendor_id', $input) && strlen($input['vendor_id']) > 1) {
+ $input['vendor_id'] = $this->decodePrimaryKey($input['vendor_id']);
+ }
- if(array_key_exists('expense_id', $input) && strlen($input['expense_id']) > 1)
- $input['expense_id'] = $this->decodePrimaryKey($input['expense_id']);
+ if (array_key_exists('expense_id', $input) && strlen($input['expense_id']) > 1) {
+ $input['expense_id'] = $this->decodePrimaryKey($input['expense_id']);
+ }
- if(array_key_exists('ninja_category_id', $input) && strlen($input['ninja_category_id']) > 1)
- $input['ninja_category_id'] = $this->decodePrimaryKey($input['ninja_category_id']);
+ if (array_key_exists('ninja_category_id', $input) && strlen($input['ninja_category_id']) > 1) {
+ $input['ninja_category_id'] = $this->decodePrimaryKey($input['ninja_category_id']);
+ }
- if(array_key_exists('bank_integration_id', $input) && $input['bank_integration_id'] == "")
- unset($input['bank_integration_id']);
- elseif(array_key_exists('bank_integration_id', $input) && strlen($input['bank_integration_id']) > 1)
- $input['bank_integration_id'] = $this->decodePrimaryKey($input['bank_integration_id']);
+ if (array_key_exists('bank_integration_id', $input) && $input['bank_integration_id'] == "") {
+ unset($input['bank_integration_id']);
+ } elseif (array_key_exists('bank_integration_id', $input) && strlen($input['bank_integration_id']) > 1) {
+ $input['bank_integration_id'] = $this->decodePrimaryKey($input['bank_integration_id']);
+ }
$this->replace($input);
}
-
}
diff --git a/app/Http/Requests/BankTransactionRule/BulkBankTransactionRuleRequest.php b/app/Http/Requests/BankTransactionRule/BulkBankTransactionRuleRequest.php
index 6e6509ee7615..1d5ae4b5b6f4 100644
--- a/app/Http/Requests/BankTransactionRule/BulkBankTransactionRuleRequest.php
+++ b/app/Http/Requests/BankTransactionRule/BulkBankTransactionRuleRequest.php
@@ -27,11 +27,9 @@ class BulkBankTransactionRuleRequest extends Request
public function rules()
{
-
return [
'ids' => 'required|bail|array',
'action' => 'in:archive,restore,delete'
];
-
}
}
diff --git a/app/Http/Requests/BankTransactionRule/StoreBankTransactionRuleRequest.php b/app/Http/Requests/BankTransactionRule/StoreBankTransactionRuleRequest.php
index 1a3341edfe4b..f0d9997252b7 100644
--- a/app/Http/Requests/BankTransactionRule/StoreBankTransactionRuleRequest.php
+++ b/app/Http/Requests/BankTransactionRule/StoreBankTransactionRuleRequest.php
@@ -11,10 +11,10 @@
namespace App\Http\Requests\BankTransactionRule;
-use App\Models\Account;
use App\Http\Requests\Request;
-use App\Utils\Traits\MakesHash;
+use App\Models\Account;
use App\Models\BankTransactionRule;
+use App\Utils\Traits\MakesHash;
class StoreBankTransactionRuleRequest extends Request
{
@@ -27,7 +27,8 @@ class StoreBankTransactionRuleRequest extends Request
*/
public function authorize() : bool
{
- return auth()->user()->can('create', BankTransactionRule::class) && auth()->user()->account->hasFeature(Account::FEATURE_API);;
+ return auth()->user()->can('create', BankTransactionRule::class) && auth()->user()->account->hasFeature(Account::FEATURE_API);
+ ;
}
public function rules()
@@ -44,14 +45,17 @@ class StoreBankTransactionRuleRequest extends Request
'applies_to' => 'bail|sometimes|string',
];
- if(isset($this->category_id))
+ if (isset($this->category_id)) {
$rules['category_id'] = 'bail|sometimes|exists:expense_categories,id,company_id,'.auth()->user()->company()->id.',is_deleted,0';
+ }
- if(isset($this->vendor_id))
+ if (isset($this->vendor_id)) {
$rules['vendor_id'] = 'bail|sometimes|exists:vendors,id,company_id,'.auth()->user()->company()->id.',is_deleted,0';
+ }
- if(isset($this->client_id))
+ if (isset($this->client_id)) {
$rules['client_id'] = 'bail|sometimes|exists:clients,id,company_id,'.auth()->user()->company()->id.',is_deleted,0';
+ }
return $rules;
@@ -65,7 +69,4 @@ class StoreBankTransactionRuleRequest extends Request
$this->replace($input);
}
-
-
-
}
diff --git a/app/Http/Requests/BankTransactionRule/UpdateBankTransactionRuleRequest.php b/app/Http/Requests/BankTransactionRule/UpdateBankTransactionRuleRequest.php
index c3d358479c3f..0ab11577fdae 100644
--- a/app/Http/Requests/BankTransactionRule/UpdateBankTransactionRuleRequest.php
+++ b/app/Http/Requests/BankTransactionRule/UpdateBankTransactionRuleRequest.php
@@ -42,14 +42,17 @@ class UpdateBankTransactionRuleRequest extends Request
'applies_to' => 'bail|sometimes|string',
];
- if(isset($this->category_id))
+ if (isset($this->category_id)) {
$rules['category_id'] = 'bail|sometimes|exists:expense_categories,id,company_id,'.auth()->user()->company()->id.',is_deleted,0';
+ }
- if(isset($this->vendor_id))
+ if (isset($this->vendor_id)) {
$rules['vendor_id'] = 'bail|sometimes|exists:vendors,id,company_id,'.auth()->user()->company()->id.',is_deleted,0';
+ }
- if(isset($this->client_id))
+ if (isset($this->client_id)) {
$rules['client_id'] = 'bail|sometimes|exists:clients,id,company_id,'.auth()->user()->company()->id.',is_deleted,0';
+ }
return $rules;
@@ -63,5 +66,4 @@ class UpdateBankTransactionRuleRequest extends Request
$this->replace($input);
}
-
}
diff --git a/app/Http/Requests/Chart/ShowChartRequest.php b/app/Http/Requests/Chart/ShowChartRequest.php
index ce7f09113c4c..83754f2a86e0 100644
--- a/app/Http/Requests/Chart/ShowChartRequest.php
+++ b/app/Http/Requests/Chart/ShowChartRequest.php
@@ -12,7 +12,6 @@
namespace App\Http\Requests\Chart;
use App\Http\Requests\Request;
-use App\Models\Activity;
class ShowChartRequest extends Request
{
diff --git a/app/Http/Requests/Client/AdjustClientLedgerRequest.php b/app/Http/Requests/Client/AdjustClientLedgerRequest.php
index bea9d767e6cc..5ef789ff3143 100644
--- a/app/Http/Requests/Client/AdjustClientLedgerRequest.php
+++ b/app/Http/Requests/Client/AdjustClientLedgerRequest.php
@@ -13,7 +13,6 @@ namespace App\Http\Requests\Client;
use App\Http\Requests\Request;
use App\Utils\Traits\MakesHash;
-use Illuminate\Validation\Rule;
class AdjustClientLedgerRequest extends Request
{
diff --git a/app/Http/Requests/Client/BulkClientRequest.php b/app/Http/Requests/Client/BulkClientRequest.php
index d02b8b932a77..b77c09a5277d 100644
--- a/app/Http/Requests/Client/BulkClientRequest.php
+++ b/app/Http/Requests/Client/BulkClientRequest.php
@@ -12,7 +12,6 @@
namespace App\Http\Requests\Client;
use App\Http\Requests\Request;
-use App\Models\Client;
use App\Utils\Traits\MakesHash;
use Illuminate\Validation\Rule;
@@ -32,20 +31,19 @@ class BulkClientRequest extends Request
public function rules()
{
-
return [
- 'ids' => ['required','bail','array',Rule::exists('clients','id')->where('company_id', auth()->user()->company()->id)],
+ 'ids' => ['required','bail','array',Rule::exists('clients', 'id')->where('company_id', auth()->user()->company()->id)],
'action' => 'in:archive,restore,delete'
];
-
}
public function prepareForValidation()
{
$input = $this->all();
- if(isset($input['ids']))
+ if (isset($input['ids'])) {
$input['ids'] = $this->transformKeys($input['ids']);
+ }
$this->replace($input);
}
diff --git a/app/Http/Requests/Client/StoreClientRequest.php b/app/Http/Requests/Client/StoreClientRequest.php
index 2fcd04abdb04..91c03091659f 100644
--- a/app/Http/Requests/Client/StoreClientRequest.php
+++ b/app/Http/Requests/Client/StoreClientRequest.php
@@ -97,24 +97,25 @@ class StoreClientRequest extends Request
$settings = (array)ClientSettings::defaults();
/* Stub settings if they don't exist */
- if(!array_key_exists('settings', $input))
+ if (!array_key_exists('settings', $input)) {
$input['settings'] = [];
- elseif(is_object($input['settings']))
+ } elseif (is_object($input['settings'])) {
$input['settings'] = (array)$input['settings'];
+ }
/* Merge default into base settings */
$input['settings'] = array_merge($input['settings'], $settings);
/* Type and property enforcement */
- foreach ($input['settings'] as $key => $value)
- {
+ foreach ($input['settings'] as $key => $value) {
if ($key == 'default_task_rate') {
$value = floatval($value);
$input['settings'][$key] = $value;
}
- if($key == 'translations')
+ if ($key == 'translations') {
unset($input['settings']['translations']);
+ }
}
/* Convert hashed IDs to IDs*/
@@ -129,7 +130,6 @@ class StoreClientRequest extends Request
} else {
$input['settings']['currency_id'] = (string) auth()->user()->company()->settings->currency_id;
}
-
} elseif (! array_key_exists('currency_id', $input['settings'])) {
$input['settings']['currency_id'] = (string) auth()->user()->company()->settings->currency_id;
}
@@ -141,8 +141,9 @@ class StoreClientRequest extends Request
if (isset($input['language_code'])) {
$input['settings']['language_id'] = $this->getLanguageId($input['language_code']);
- if(strlen($input['settings']['language_id']) == 0)
+ if (strlen($input['settings']['language_id']) == 0) {
unset($input['settings']['language_id']);
+ }
}
if (isset($input['country_code'])) {
diff --git a/app/Http/Requests/ClientGatewayToken/CreateClientGatewayTokenRequest.php b/app/Http/Requests/ClientGatewayToken/CreateClientGatewayTokenRequest.php
index 37d3c8fb906e..39eab01b6c21 100644
--- a/app/Http/Requests/ClientGatewayToken/CreateClientGatewayTokenRequest.php
+++ b/app/Http/Requests/ClientGatewayToken/CreateClientGatewayTokenRequest.php
@@ -12,7 +12,6 @@
namespace App\Http\Requests\ClientGatewayToken;
use App\Http\Requests\Request;
-use App\Models\ClientGatewayToken;
class CreateClientGatewayTokenRequest extends Request
{
diff --git a/app/Http/Requests/ClientGatewayToken/ListClientGatewayTokenRequest.php b/app/Http/Requests/ClientGatewayToken/ListClientGatewayTokenRequest.php
index d9664b4a79a3..affe6cc570f9 100644
--- a/app/Http/Requests/ClientGatewayToken/ListClientGatewayTokenRequest.php
+++ b/app/Http/Requests/ClientGatewayToken/ListClientGatewayTokenRequest.php
@@ -12,7 +12,6 @@
namespace App\Http\Requests\ClientGatewayToken;
use App\Http\Requests\Request;
-use App\Models\ClientGatewayToken;
class ListClientGatewayTokenRequest extends Request
{
diff --git a/app/Http/Requests/ClientGatewayToken/StoreClientGatewayTokenRequest.php b/app/Http/Requests/ClientGatewayToken/StoreClientGatewayTokenRequest.php
index 77cf214b1eeb..ff022150af9d 100644
--- a/app/Http/Requests/ClientGatewayToken/StoreClientGatewayTokenRequest.php
+++ b/app/Http/Requests/ClientGatewayToken/StoreClientGatewayTokenRequest.php
@@ -11,15 +11,9 @@
namespace App\Http\Requests\ClientGatewayToken;
-use App\DataMapper\ClientSettings;
use App\Http\Requests\Request;
-use App\Http\ValidationRules\Ninja\CanStoreClientsRule;
-use App\Http\ValidationRules\ValidClientGroupSettingsRule;
use App\Models\Client;
-use App\Models\GroupSetting;
use App\Utils\Traits\MakesHash;
-use Illuminate\Support\Facades\Cache;
-use Illuminate\Validation\Rule;
class StoreClientGatewayTokenRequest extends Request
{
diff --git a/app/Http/Requests/ClientGatewayToken/UpdateClientGatewayTokenRequest.php b/app/Http/Requests/ClientGatewayToken/UpdateClientGatewayTokenRequest.php
index 89a9ae7eb09d..2499aa2c12f6 100644
--- a/app/Http/Requests/ClientGatewayToken/UpdateClientGatewayTokenRequest.php
+++ b/app/Http/Requests/ClientGatewayToken/UpdateClientGatewayTokenRequest.php
@@ -11,12 +11,8 @@
namespace App\Http\Requests\ClientGatewayToken;
-use App\DataMapper\CompanySettings;
use App\Http\Requests\Request;
-use App\Http\ValidationRules\ValidClientGroupSettingsRule;
-use App\Utils\Traits\ChecksEntityStatus;
use App\Utils\Traits\MakesHash;
-use Illuminate\Validation\Rule;
class UpdateClientGatewayTokenRequest extends Request
{
diff --git a/app/Http/Requests/ClientPortal/RegisterRequest.php b/app/Http/Requests/ClientPortal/RegisterRequest.php
index 437ff679673d..52a37b985ac7 100644
--- a/app/Http/Requests/ClientPortal/RegisterRequest.php
+++ b/app/Http/Requests/ClientPortal/RegisterRequest.php
@@ -64,7 +64,6 @@ class RegisterRequest extends FormRequest
public function company()
{
-
//this should be all we need, the rest SHOULD be redundant because of our Middleware
if ($this->key) {
return Company::where('company_key', $this->key)->first();
diff --git a/app/Http/Requests/ClientPortal/Subscriptions/ShowPlanSwitchRequest.php b/app/Http/Requests/ClientPortal/Subscriptions/ShowPlanSwitchRequest.php
index 1a906018d87d..6aa86843f739 100644
--- a/app/Http/Requests/ClientPortal/Subscriptions/ShowPlanSwitchRequest.php
+++ b/app/Http/Requests/ClientPortal/Subscriptions/ShowPlanSwitchRequest.php
@@ -16,7 +16,6 @@ use Illuminate\Foundation\Http\FormRequest;
class ShowPlanSwitchRequest extends FormRequest
{
-
/**
* Determine if the user is authorized to make this request.
*
@@ -41,8 +40,6 @@ class ShowPlanSwitchRequest extends FormRequest
protected function failedAuthorization()
{
-
throw new ClientPortalAuthorizationException('Unable to change plans due to a restriction on this product.', 400);
-
}
}
diff --git a/app/Http/Requests/Company/StoreCompanyRequest.php b/app/Http/Requests/Company/StoreCompanyRequest.php
index ae3ccf0194c1..b9219f000dd2 100644
--- a/app/Http/Requests/Company/StoreCompanyRequest.php
+++ b/app/Http/Requests/Company/StoreCompanyRequest.php
@@ -11,7 +11,6 @@
namespace App\Http\Requests\Company;
-use App\DataMapper\CompanySettings;
use App\Http\Requests\Request;
use App\Http\ValidationRules\Company\ValidCompanyQuantity;
use App\Http\ValidationRules\Company\ValidSubdomain;
@@ -61,8 +60,9 @@ class StoreCompanyRequest extends Request
{
$input = $this->all();
- if(!isset($input['name']))
+ if (!isset($input['name'])) {
$input['name'] = 'Untitled Company';
+ }
if (array_key_exists('google_analytics_url', $input)) {
$input['google_analytics_key'] = $input['google_analytics_url'];
diff --git a/app/Http/Requests/Company/UpdateCompanyRequest.php b/app/Http/Requests/Company/UpdateCompanyRequest.php
index f27ec426a83f..c2228b1c5052 100644
--- a/app/Http/Requests/Company/UpdateCompanyRequest.php
+++ b/app/Http/Requests/Company/UpdateCompanyRequest.php
@@ -71,7 +71,6 @@ class UpdateCompanyRequest extends Request
public function prepareForValidation()
{
-
$input = $this->all();
if (array_key_exists('portal_domain', $input) && strlen($input['portal_domain']) > 1) {
@@ -100,16 +99,15 @@ class UpdateCompanyRequest extends Request
{
$account = $this->company->account;
- if(Ninja::isHosted())
- {
- foreach($this->protected_input as $protected_var)
- {
+ if (Ninja::isHosted()) {
+ foreach ($this->protected_input as $protected_var) {
$settings[$protected_var] = str_replace("script", "", $settings[$protected_var]);
}
}
- if(isset($settings['email_style_custom']))
+ if (isset($settings['email_style_custom'])) {
$settings['email_style_custom'] = str_replace(['{{','}}'], ['',''], $settings['email_style_custom']);
+ }
if (! $account->isFreeHostedClient()) {
return $settings;
@@ -128,8 +126,7 @@ class UpdateCompanyRequest extends Request
private function addScheme($url, $scheme = 'https://')
{
- if(Ninja::isHosted())
- {
+ if (Ninja::isHosted()) {
$url = str_replace('http://', '', $url);
$url = parse_url($url, PHP_URL_SCHEME) === null ? $scheme.$url : $url;
}
diff --git a/app/Http/Requests/CompanyGateway/BulkCompanyGatewayRequest.php b/app/Http/Requests/CompanyGateway/BulkCompanyGatewayRequest.php
index 9a1ec51e5788..444bf89291fe 100644
--- a/app/Http/Requests/CompanyGateway/BulkCompanyGatewayRequest.php
+++ b/app/Http/Requests/CompanyGateway/BulkCompanyGatewayRequest.php
@@ -31,24 +31,20 @@ class BulkCompanyGatewayRequest extends Request
public function rules()
{
-
return [
- 'ids' => ['required','bail','array',Rule::exists('company_gateways','id')->where('company_id', auth()->user()->company()->id)],
+ 'ids' => ['required','bail','array',Rule::exists('company_gateways', 'id')->where('company_id', auth()->user()->company()->id)],
'action' => 'required|bail|in:archive,restore,delete'
];
-
}
public function prepareForValidation()
{
$input = $this->all();
- if(isset($input['ids']))
+ if (isset($input['ids'])) {
$input['ids'] = $this->transformKeys($input['ids']);
+ }
$this->replace($input);
}
-
-
-
}
diff --git a/app/Http/Requests/CompanyGateway/StoreCompanyGatewayRequest.php b/app/Http/Requests/CompanyGateway/StoreCompanyGatewayRequest.php
index 04f31d08ca5c..5f148f504354 100644
--- a/app/Http/Requests/CompanyGateway/StoreCompanyGatewayRequest.php
+++ b/app/Http/Requests/CompanyGateway/StoreCompanyGatewayRequest.php
@@ -34,7 +34,7 @@ class StoreCompanyGatewayRequest extends Request
public function rules()
{
$rules = [
- 'gateway_key' => ['bail', 'required','alpha_num',Rule::exists('gateways','key')],
+ 'gateway_key' => ['bail', 'required','alpha_num',Rule::exists('gateways', 'key')],
'fees_and_limits' => new ValidCompanyGatewayFeesAndLimitsRule(),
];
@@ -68,5 +68,4 @@ class StoreCompanyGatewayRequest extends Request
$this->replace($input);
}
-
}
diff --git a/app/Http/Requests/Credit/BulkCreditRequest.php b/app/Http/Requests/Credit/BulkCreditRequest.php
index 0a04dee09273..fd04b4216320 100644
--- a/app/Http/Requests/Credit/BulkCreditRequest.php
+++ b/app/Http/Requests/Credit/BulkCreditRequest.php
@@ -36,7 +36,7 @@ class BulkCreditRequest extends FormRequest
public function rules()
{
return [
- 'ids' => ['required','bail','array',Rule::exists('credits','id')->where('company_id', auth()->user()->company()->id)],
+ 'ids' => ['required','bail','array',Rule::exists('credits', 'id')->where('company_id', auth()->user()->company()->id)],
'action' => 'required|bail|in:archive,restore,delete,email,bulk_download,bulk_print,mark_paid,clone_to_credit,history,mark_sent,download,send_email'
];
}
@@ -45,10 +45,10 @@ class BulkCreditRequest extends FormRequest
{
$input = $this->all();
- if(isset($input['ids']))
+ if (isset($input['ids'])) {
$input['ids'] = $this->transformKeys($input['ids']);
+ }
$this->replace($input);
}
-
}
diff --git a/app/Http/Requests/Design/StoreDesignRequest.php b/app/Http/Requests/Design/StoreDesignRequest.php
index 73e494e09844..15e9cabd8bf9 100644
--- a/app/Http/Requests/Design/StoreDesignRequest.php
+++ b/app/Http/Requests/Design/StoreDesignRequest.php
@@ -11,8 +11,8 @@
namespace App\Http\Requests\Design;
-use App\Models\Account;
use App\Http\Requests\Request;
+use App\Models\Account;
class StoreDesignRequest extends Request
{
@@ -23,7 +23,8 @@ class StoreDesignRequest extends Request
*/
public function authorize() : bool
{
- return auth()->user()->isAdmin() && auth()->user()->account->hasFeature(Account::FEATURE_API);;
+ return auth()->user()->isAdmin() && auth()->user()->account->hasFeature(Account::FEATURE_API);
+ ;
}
public function rules()
diff --git a/app/Http/Requests/Email/SendEmailRequest.php b/app/Http/Requests/Email/SendEmailRequest.php
index 19ca5499f45a..bc5ec63d6ef0 100644
--- a/app/Http/Requests/Email/SendEmailRequest.php
+++ b/app/Http/Requests/Email/SendEmailRequest.php
@@ -57,11 +57,13 @@ class SendEmailRequest extends Request
unset($input['template']);
}
- if(array_key_exists('entity_id', $input))
+ if (array_key_exists('entity_id', $input)) {
$input['entity_id'] = $this->decodePrimaryKey($input['entity_id']);
+ }
- if(array_key_exists('entity', $input))
+ if (array_key_exists('entity', $input)) {
$input['entity'] = "App\Models\\".ucfirst(Str::camel($input['entity']));
+ }
$this->replace($input);
}
diff --git a/app/Http/Requests/Expense/StoreExpenseRequest.php b/app/Http/Requests/Expense/StoreExpenseRequest.php
index b0956a85a3cc..ea8c71e0ac05 100644
--- a/app/Http/Requests/Expense/StoreExpenseRequest.php
+++ b/app/Http/Requests/Expense/StoreExpenseRequest.php
@@ -12,10 +12,8 @@
namespace App\Http\Requests\Expense;
use App\Http\Requests\Request;
-use App\Http\ValidationRules\Expense\UniqueExpenseNumberRule;
use App\Models\Expense;
use App\Models\Project;
-use App\Models\PurchaseOrder;
use App\Utils\Traits\MakesHash;
use Illuminate\Validation\Rule;
@@ -68,14 +66,11 @@ class StoreExpenseRequest extends Request
if (array_key_exists('project_id', $input) && isset($input['project_id'])) {
$project = Project::withTrashed()->where('id', $input['project_id'])->company()->first();
- if($project){
+ if ($project) {
$input['client_id'] = $project->client_id;
- }
- else
- {
+ } else {
unset($input['project_id']);
}
-
}
diff --git a/app/Http/Requests/Expense/UpdateExpenseRequest.php b/app/Http/Requests/Expense/UpdateExpenseRequest.php
index e3ac76c89558..a8b0ee968250 100644
--- a/app/Http/Requests/Expense/UpdateExpenseRequest.php
+++ b/app/Http/Requests/Expense/UpdateExpenseRequest.php
@@ -68,14 +68,11 @@ class UpdateExpenseRequest extends Request
if (array_key_exists('project_id', $input) && isset($input['project_id'])) {
$project = Project::withTrashed()->where('id', $input['project_id'])->company()->first();
- if($project){
+ if ($project) {
$input['client_id'] = $project->client_id;
- }
- else
- {
+ } else {
unset($input['project_id']);
}
-
}
$this->replace($input);
diff --git a/app/Http/Requests/Gateways/Mollie/Mollie3dsRequest.php b/app/Http/Requests/Gateways/Mollie/Mollie3dsRequest.php
index 880312fc29d1..d3f4f5d7b7a6 100644
--- a/app/Http/Requests/Gateways/Mollie/Mollie3dsRequest.php
+++ b/app/Http/Requests/Gateways/Mollie/Mollie3dsRequest.php
@@ -13,7 +13,6 @@
namespace App\Http\Requests\Gateways\Mollie;
use App\Models\Client;
-use App\Models\ClientGatewayToken;
use App\Models\Company;
use App\Models\CompanyGateway;
use App\Models\PaymentHash;
diff --git a/app/Http/Requests/GroupSetting/StoreGroupSettingRequest.php b/app/Http/Requests/GroupSetting/StoreGroupSettingRequest.php
index 7e15f9a66a2e..ec629276068a 100644
--- a/app/Http/Requests/GroupSetting/StoreGroupSettingRequest.php
+++ b/app/Http/Requests/GroupSetting/StoreGroupSettingRequest.php
@@ -11,11 +11,11 @@
namespace App\Http\Requests\GroupSetting;
+use App\DataMapper\ClientSettings;
+use App\Http\Requests\Request;
+use App\Http\ValidationRules\ValidClientGroupSettingsRule;
use App\Models\Account;
use App\Models\GroupSetting;
-use App\Http\Requests\Request;
-use App\DataMapper\ClientSettings;
-use App\Http\ValidationRules\ValidClientGroupSettingsRule;
class StoreGroupSettingRequest extends Request
{
diff --git a/app/Http/Requests/Invoice/ActionInvoiceRequest.php b/app/Http/Requests/Invoice/ActionInvoiceRequest.php
index fc3bc1abbefb..30e078336b8b 100644
--- a/app/Http/Requests/Invoice/ActionInvoiceRequest.php
+++ b/app/Http/Requests/Invoice/ActionInvoiceRequest.php
@@ -12,7 +12,6 @@
namespace App\Http\Requests\Invoice;
use App\Http\Requests\Request;
-use App\Models\Invoice;
use App\Utils\Traits\Invoice\ActionsInvoice;
use App\Utils\Traits\MakesHash;
@@ -70,4 +69,4 @@ class ActionInvoiceRequest extends Request
'action' => $this->error_msg,
];
}
-}
\ No newline at end of file
+}
diff --git a/app/Http/Requests/Invoice/BulkInvoiceRequest.php b/app/Http/Requests/Invoice/BulkInvoiceRequest.php
index 7235d305f1e6..dbccd463803e 100644
--- a/app/Http/Requests/Invoice/BulkInvoiceRequest.php
+++ b/app/Http/Requests/Invoice/BulkInvoiceRequest.php
@@ -15,7 +15,6 @@ use App\Http\Requests\Request;
class BulkInvoiceRequest extends Request
{
-
public function authorize() : bool
{
return true;
@@ -28,5 +27,4 @@ class BulkInvoiceRequest extends Request
'ids' => 'required'
];
}
-
}
diff --git a/app/Http/Requests/Invoice/UpdateInvoiceRequest.php b/app/Http/Requests/Invoice/UpdateInvoiceRequest.php
index 0197f15869c0..0fbcf8cb3402 100644
--- a/app/Http/Requests/Invoice/UpdateInvoiceRequest.php
+++ b/app/Http/Requests/Invoice/UpdateInvoiceRequest.php
@@ -12,10 +12,8 @@
namespace App\Http\Requests\Invoice;
use App\Http\Requests\Request;
-use App\Http\ValidationRules\Invoice\InvoiceBalanceSanity;
use App\Http\ValidationRules\Invoice\LockedInvoiceRule;
use App\Http\ValidationRules\Project\ValidProjectForClient;
-use App\Models\Invoice;
use App\Utils\Traits\ChecksEntityStatus;
use App\Utils\Traits\CleanLineItems;
use App\Utils\Traits\MakesHash;
diff --git a/app/Http/Requests/Login/LoginRequest.php b/app/Http/Requests/Login/LoginRequest.php
index 63372bb94df8..7d0ab21d8cb0 100644
--- a/app/Http/Requests/Login/LoginRequest.php
+++ b/app/Http/Requests/Login/LoginRequest.php
@@ -46,5 +46,4 @@ class LoginRequest extends Request
'password' => 'required|max:1000',
];
}
-
}
diff --git a/app/Http/Requests/Payment/StorePaymentRequest.php b/app/Http/Requests/Payment/StorePaymentRequest.php
index 9614199f76b7..908c3fd65ad1 100644
--- a/app/Http/Requests/Payment/StorePaymentRequest.php
+++ b/app/Http/Requests/Payment/StorePaymentRequest.php
@@ -43,7 +43,7 @@ class StorePaymentRequest extends Request
$invoices_total = 0;
$credits_total = 0;
- if (isset($input['client_id']) && is_string($input['client_id']) ) {
+ if (isset($input['client_id']) && is_string($input['client_id'])) {
$input['client_id'] = $this->decodePrimaryKey($input['client_id']);
}
@@ -53,9 +53,9 @@ class StorePaymentRequest extends Request
if (isset($input['invoices']) && is_array($input['invoices']) !== false) {
foreach ($input['invoices'] as $key => $value) {
-
- if(is_string($value['invoice_id']))
+ if (is_string($value['invoice_id'])) {
$input['invoices'][$key]['invoice_id'] = $this->decodePrimaryKey($value['invoice_id']);
+ }
if (array_key_exists('amount', $value)) {
$invoices_total += $value['amount'];
diff --git a/app/Http/Requests/Payments/PaymentNotificationWebhookRequest.php b/app/Http/Requests/Payments/PaymentNotificationWebhookRequest.php
index 4b4bd406fe5a..f2e9a66fccca 100644
--- a/app/Http/Requests/Payments/PaymentNotificationWebhookRequest.php
+++ b/app/Http/Requests/Payments/PaymentNotificationWebhookRequest.php
@@ -14,11 +14,6 @@ namespace App\Http\Requests\Payments;
use App\Http\Requests\Request;
use App\Libraries\MultiDB;
-use App\Models\Client;
-use App\Models\Company;
-use App\Models\CompanyGateway;
-use App\Models\Payment;
-use App\Models\PaymentHash;
use App\Utils\Traits\MakesHash;
class PaymentNotificationWebhookRequest extends Request
diff --git a/app/Http/Requests/Payments/PaymentWebhookRequest.php b/app/Http/Requests/Payments/PaymentWebhookRequest.php
index 0d338af471d4..f2e00d40dec3 100644
--- a/app/Http/Requests/Payments/PaymentWebhookRequest.php
+++ b/app/Http/Requests/Payments/PaymentWebhookRequest.php
@@ -14,7 +14,6 @@ namespace App\Http\Requests\Payments;
use App\Http\Requests\Request;
use App\Libraries\MultiDB;
-use App\Models\Client;
use App\Models\Company;
use App\Models\CompanyGateway;
use App\Models\Payment;
@@ -48,7 +47,6 @@ class PaymentWebhookRequest extends Request
MultiDB::findAndSetDbByCompanyKey($this->company_key);
return CompanyGateway::withTrashed()->find($this->decodePrimaryKey($this->company_gateway_id));
-
}
/**
diff --git a/app/Http/Requests/Preview/DesignPreviewRequest.php b/app/Http/Requests/Preview/DesignPreviewRequest.php
index 46c3d0c01154..3d9a6cb973df 100644
--- a/app/Http/Requests/Preview/DesignPreviewRequest.php
+++ b/app/Http/Requests/Preview/DesignPreviewRequest.php
@@ -12,7 +12,6 @@
namespace App\Http\Requests\Preview;
use App\Http\Requests\Request;
-use App\Http\ValidationRules\Project\ValidProjectForClient;
use App\Models\Credit;
use App\Models\Invoice;
use App\Models\PurchaseOrder;
@@ -20,7 +19,6 @@ use App\Models\Quote;
use App\Models\RecurringInvoice;
use App\Utils\Traits\CleanLineItems;
use App\Utils\Traits\MakesHash;
-use Illuminate\Validation\Rule;
class DesignPreviewRequest extends Request
{
@@ -34,10 +32,10 @@ class DesignPreviewRequest extends Request
*/
public function authorize() : bool
{
- return auth()->user()->can('create', Invoice::class) ||
- auth()->user()->can('create', Quote::class) ||
- auth()->user()->can('create', RecurringInvoice::class) ||
- auth()->user()->can('create', Credit::class) ||
+ return auth()->user()->can('create', Invoice::class) ||
+ auth()->user()->can('create', Quote::class) ||
+ auth()->user()->can('create', RecurringInvoice::class) ||
+ auth()->user()->can('create', Credit::class) ||
auth()->user()->can('create', PurchaseOrder::class);
}
diff --git a/app/Http/Requests/Preview/PreviewInvoiceRequest.php b/app/Http/Requests/Preview/PreviewInvoiceRequest.php
index 59453725be65..75375c620934 100644
--- a/app/Http/Requests/Preview/PreviewInvoiceRequest.php
+++ b/app/Http/Requests/Preview/PreviewInvoiceRequest.php
@@ -12,14 +12,12 @@
namespace App\Http\Requests\Preview;
use App\Http\Requests\Request;
-use App\Http\ValidationRules\Project\ValidProjectForClient;
use App\Models\Credit;
use App\Models\Invoice;
use App\Models\Quote;
use App\Models\RecurringInvoice;
use App\Utils\Traits\CleanLineItems;
use App\Utils\Traits\MakesHash;
-use Illuminate\Validation\Rule;
class PreviewInvoiceRequest extends Request
{
diff --git a/app/Http/Requests/Preview/PreviewPurchaseOrderRequest.php b/app/Http/Requests/Preview/PreviewPurchaseOrderRequest.php
index 6d72da9a3c88..eae0e42b36b0 100644
--- a/app/Http/Requests/Preview/PreviewPurchaseOrderRequest.php
+++ b/app/Http/Requests/Preview/PreviewPurchaseOrderRequest.php
@@ -12,15 +12,9 @@
namespace App\Http\Requests\Preview;
use App\Http\Requests\Request;
-use App\Http\ValidationRules\Project\ValidProjectForClient;
-use App\Models\Credit;
-use App\Models\Invoice;
use App\Models\PurchaseOrder;
-use App\Models\Quote;
-use App\Models\RecurringInvoice;
use App\Utils\Traits\CleanLineItems;
use App\Utils\Traits\MakesHash;
-use Illuminate\Validation\Rule;
class PreviewPurchaseOrderRequest extends Request
{
@@ -55,7 +49,7 @@ class PreviewPurchaseOrderRequest extends Request
$input['line_items'] = isset($input['line_items']) ? $this->cleanItems($input['line_items']) : [];
$input['amount'] = 0;
$input['balance'] = 0;
- $input['number'] = ctrans('texts.live_preview') . " #". rand(0,1000);
+ $input['number'] = ctrans('texts.live_preview') . " #". rand(0, 1000);
$this->replace($input);
}
diff --git a/app/Http/Requests/PurchaseOrder/BulkPurchaseOrderRequest.php b/app/Http/Requests/PurchaseOrder/BulkPurchaseOrderRequest.php
index 0790444a1a49..28a581ffd3d8 100644
--- a/app/Http/Requests/PurchaseOrder/BulkPurchaseOrderRequest.php
+++ b/app/Http/Requests/PurchaseOrder/BulkPurchaseOrderRequest.php
@@ -15,7 +15,6 @@ use App\Http\Requests\Request;
class BulkPurchaseOrderRequest extends Request
{
-
/**
* Determine if the user is authorized to make this request.
*
@@ -34,5 +33,4 @@ class BulkPurchaseOrderRequest extends Request
'action' => 'in:archive,restore,delete,email,bulk_download,bulk_print,mark_sent,download,send_email,add_to_inventory,expense,cancel'
];
}
-
}
diff --git a/app/Http/Requests/PurchaseOrder/StorePurchaseOrderRequest.php b/app/Http/Requests/PurchaseOrder/StorePurchaseOrderRequest.php
index 3fa224149fa1..21c82dda16c0 100644
--- a/app/Http/Requests/PurchaseOrder/StorePurchaseOrderRequest.php
+++ b/app/Http/Requests/PurchaseOrder/StorePurchaseOrderRequest.php
@@ -11,7 +11,6 @@
namespace App\Http\Requests\PurchaseOrder;
-
use App\Http\Requests\Request;
use App\Models\PurchaseOrder;
use App\Utils\Traits\CleanLineItems;
@@ -57,13 +56,13 @@ class StorePurchaseOrderRequest extends Request
$input = $this->decodePrimaryKeys($input);
- if (isset($input['line_items']) && is_array($input['line_items']))
+ if (isset($input['line_items']) && is_array($input['line_items'])) {
$input['line_items'] = isset($input['line_items']) ? $this->cleanItems($input['line_items']) : [];
+ }
$input['amount'] = 0;
$input['balance'] = 0;
$this->replace($input);
}
-
}
diff --git a/app/Http/Requests/PurchaseOrder/UploadPurchaseOrderRequest.php b/app/Http/Requests/PurchaseOrder/UploadPurchaseOrderRequest.php
index e0a40251b7c2..a534153f3076 100644
--- a/app/Http/Requests/PurchaseOrder/UploadPurchaseOrderRequest.php
+++ b/app/Http/Requests/PurchaseOrder/UploadPurchaseOrderRequest.php
@@ -27,13 +27,12 @@ class UploadPurchaseOrderRequest extends Request
public function rules()
{
+ $rules = [];
- $rules = [];
-
- if($this->input('documents'))
+ if ($this->input('documents')) {
$rules['documents'] = 'file|mimes:csv,png,ai,jpeg,tiff,pdf,gif,psd,txt,doc,xls,ppt,xlsx,docx,pptx|max:2000000';
+ }
- return $rules;
-
+ return $rules;
}
}
diff --git a/app/Http/Requests/RecurringExpense/StoreRecurringExpenseRequest.php b/app/Http/Requests/RecurringExpense/StoreRecurringExpenseRequest.php
index 2fc1f44d07d2..978989b3730f 100644
--- a/app/Http/Requests/RecurringExpense/StoreRecurringExpenseRequest.php
+++ b/app/Http/Requests/RecurringExpense/StoreRecurringExpenseRequest.php
@@ -12,7 +12,6 @@
namespace App\Http\Requests\RecurringExpense;
use App\Http\Requests\Request;
-use App\Http\ValidationRules\RecurringExpense\UniqueRecurringExpenseNumberRule;
use App\Models\RecurringExpense;
use App\Utils\Traits\MakesHash;
use Illuminate\Validation\Rule;
diff --git a/app/Http/Requests/RecurringInvoice/StoreRecurringInvoiceRequest.php b/app/Http/Requests/RecurringInvoice/StoreRecurringInvoiceRequest.php
index cee0ccd888ab..6b92361e9566 100644
--- a/app/Http/Requests/RecurringInvoice/StoreRecurringInvoiceRequest.php
+++ b/app/Http/Requests/RecurringInvoice/StoreRecurringInvoiceRequest.php
@@ -18,7 +18,6 @@ use App\Models\Client;
use App\Models\RecurringInvoice;
use App\Utils\Traits\CleanLineItems;
use App\Utils\Traits\MakesHash;
-use Illuminate\Http\UploadedFile;
class StoreRecurringInvoiceRequest extends Request
{
@@ -74,7 +73,7 @@ class StoreRecurringInvoiceRequest extends Request
{
$input = $this->all();
- if (array_key_exists('due_date_days', $input) && is_null($input['due_date_days'])){
+ if (array_key_exists('due_date_days', $input) && is_null($input['due_date_days'])) {
$input['due_date_days'] = 'terms';
}
diff --git a/app/Http/Requests/RecurringInvoice/UpdateRecurringInvoiceRequest.php b/app/Http/Requests/RecurringInvoice/UpdateRecurringInvoiceRequest.php
index 8b2343180a73..bbaeed17f9f6 100644
--- a/app/Http/Requests/RecurringInvoice/UpdateRecurringInvoiceRequest.php
+++ b/app/Http/Requests/RecurringInvoice/UpdateRecurringInvoiceRequest.php
@@ -16,7 +16,6 @@ use App\Http\ValidationRules\Project\ValidProjectForClient;
use App\Utils\Traits\ChecksEntityStatus;
use App\Utils\Traits\CleanLineItems;
use App\Utils\Traits\MakesHash;
-use Illuminate\Http\UploadedFile;
use Illuminate\Validation\Rule;
class UpdateRecurringInvoiceRequest extends Request
@@ -68,7 +67,7 @@ class UpdateRecurringInvoiceRequest extends Request
{
$input = $this->all();
- if (array_key_exists('due_date_days', $input) && is_null($input['due_date_days'])){
+ if (array_key_exists('due_date_days', $input) && is_null($input['due_date_days'])) {
$input['due_date_days'] = 'terms';
}
diff --git a/app/Http/Requests/RecurringQuote/StoreRecurringQuoteRequest.php b/app/Http/Requests/RecurringQuote/StoreRecurringQuoteRequest.php
index 5e783683861f..588ccaa80e9a 100644
--- a/app/Http/Requests/RecurringQuote/StoreRecurringQuoteRequest.php
+++ b/app/Http/Requests/RecurringQuote/StoreRecurringQuoteRequest.php
@@ -17,7 +17,6 @@ use App\Models\Client;
use App\Models\RecurringQuote;
use App\Utils\Traits\CleanLineItems;
use App\Utils\Traits\MakesHash;
-use Illuminate\Http\UploadedFile;
class StoreRecurringQuoteRequest extends Request
{
diff --git a/app/Http/Requests/RecurringQuote/UpdateRecurringQuoteRequest.php b/app/Http/Requests/RecurringQuote/UpdateRecurringQuoteRequest.php
index b63a2e215aa5..9c58ad24a20e 100644
--- a/app/Http/Requests/RecurringQuote/UpdateRecurringQuoteRequest.php
+++ b/app/Http/Requests/RecurringQuote/UpdateRecurringQuoteRequest.php
@@ -15,7 +15,6 @@ use App\Http\Requests\Request;
use App\Utils\Traits\ChecksEntityStatus;
use App\Utils\Traits\CleanLineItems;
use App\Utils\Traits\MakesHash;
-use Illuminate\Http\UploadedFile;
use Illuminate\Validation\Rule;
class UpdateRecurringQuoteRequest extends Request
diff --git a/app/Http/Requests/Report/GenericReportRequest.php b/app/Http/Requests/Report/GenericReportRequest.php
index c17326cfe537..0789ec649476 100644
--- a/app/Http/Requests/Report/GenericReportRequest.php
+++ b/app/Http/Requests/Report/GenericReportRequest.php
@@ -12,7 +12,6 @@
namespace App\Http\Requests\Report;
use App\Http\Requests\Request;
-use Illuminate\Validation\Rule;
class GenericReportRequest extends Request
{
@@ -28,7 +27,6 @@ class GenericReportRequest extends Request
public function rules()
{
-
return [
'date_range' => 'bail|required|string',
'end_date' => 'bail|required_if:date_range,custom|nullable|date',
@@ -58,7 +56,7 @@ class GenericReportRequest extends Request
$input['start_date'] = null;
$input['end_date'] = null;
}
-nlog($input);
+ nlog($input);
$this->replace($input);
}
diff --git a/app/Http/Requests/Report/ProductSalesReportRequest.php b/app/Http/Requests/Report/ProductSalesReportRequest.php
index c0399b8335f5..87b0f5ddf22e 100644
--- a/app/Http/Requests/Report/ProductSalesReportRequest.php
+++ b/app/Http/Requests/Report/ProductSalesReportRequest.php
@@ -13,7 +13,6 @@ namespace App\Http\Requests\Report;
use App\Http\Requests\Request;
use App\Utils\Traits\MakesHash;
-use Illuminate\Validation\Rule;
class ProductSalesReportRequest extends Request
{
@@ -31,7 +30,6 @@ class ProductSalesReportRequest extends Request
public function rules()
{
-
return [
'date_range' => 'bail|required|string',
'end_date' => 'bail|required_if:date_range,custom|nullable|date',
@@ -63,8 +61,9 @@ class ProductSalesReportRequest extends Request
$input['end_date'] = null;
}
- if(array_key_exists('client_id', $input) && strlen($input['client_id']) >=1)
+ if (array_key_exists('client_id', $input) && strlen($input['client_id']) >=1) {
$input['client_id'] = $this->decodePrimaryKey($input['client_id']);
+ }
$this->replace($input);
}
diff --git a/app/Http/Requests/Request.php b/app/Http/Requests/Request.php
index a26ed66e8536..7a8c300ecb2b 100644
--- a/app/Http/Requests/Request.php
+++ b/app/Http/Requests/Request.php
@@ -11,7 +11,6 @@
namespace App\Http\Requests;
-use App\Http\Requests\RuntimeFormRequest;
use App\Http\ValidationRules\User\RelatedUserRule;
use App\Utils\Traits\MakesHash;
use Illuminate\Foundation\Http\FormRequest;
@@ -154,7 +153,6 @@ class Request extends FormRequest
if (array_key_exists('vendor_contact_id', $input['invitations'][$key]) && is_string($input['invitations'][$key]['vendor_contact_id'])) {
$input['invitations'][$key]['vendor_contact_id'] = $this->decodePrimaryKey($input['invitations'][$key]['vendor_contact_id']);
}
-
}
}
@@ -198,8 +196,9 @@ class Request extends FormRequest
public function checkTimeLog(array $log): bool
{
- if(count($log) == 0)
+ if (count($log) == 0) {
return true;
+ }
/*Get first value of all arrays*/
$result = array_column($log, 0);
@@ -210,41 +209,44 @@ class Request extends FormRequest
$new_array = [];
/*Rebuild the array in order*/
- foreach($result as $key => $value)
+ foreach ($result as $key => $value) {
$new_array[] = $log[$key];
+ }
/*Iterate through the array and perform checks*/
- foreach($new_array as $key => $array)
- {
+ foreach ($new_array as $key => $array) {
/*Flag which helps us know if there is a NEXT timelog*/
$next = false;
/* If there are more than 1 time log in the array, ensure the last timestamp is not zero*/
- if(count($new_array) >1 && $array[1] == 0)
+ if (count($new_array) >1 && $array[1] == 0) {
return false;
+ }
- /* Check if the start time is greater than the end time */
- /* Ignore the last value for now, we'll do a separate check for this */
- if($array[0] > $array[1] && $array[1] != 0)
+ /* Check if the start time is greater than the end time */
+ /* Ignore the last value for now, we'll do a separate check for this */
+ if ($array[0] > $array[1] && $array[1] != 0) {
return false;
+ }
/* Find the next time log value - if it exists */
- if(array_key_exists($key+1, $new_array))
+ if (array_key_exists($key+1, $new_array)) {
$next = $new_array[$key+1];
+ }
/* check the next time log and ensure the start time is GREATER than the end time of the previous record */
- if($next && $next[0] < $array[1])
+ if ($next && $next[0] < $array[1]) {
return false;
+ }
/* Get the last row of the timelog*/
$last_row = end($new_array);
/*If the last value is NOT zero, ensure start time is not GREATER than the endtime */
- if($last_row[1] != 0 && $last_row[0] > $last_row[1])
+ if ($last_row[1] != 0 && $last_row[0] > $last_row[1]) {
return false;
+ }
return true;
}
-
}
-
}
diff --git a/app/Http/Requests/StripeConnect/InitializeStripeConnectRequest.php b/app/Http/Requests/StripeConnect/InitializeStripeConnectRequest.php
index 43770e0cdf4b..80791b424812 100644
--- a/app/Http/Requests/StripeConnect/InitializeStripeConnectRequest.php
+++ b/app/Http/Requests/StripeConnect/InitializeStripeConnectRequest.php
@@ -12,7 +12,6 @@
namespace App\Http\Requests\StripeConnect;
-use App\Models\ClientContact;
use App\Models\Company;
use App\Models\User;
use Illuminate\Foundation\Http\FormRequest;
diff --git a/app/Http/Requests/Subscription/DestroySubscriptionRequest.php b/app/Http/Requests/Subscription/DestroySubscriptionRequest.php
index a12ccf6740ce..20015d6260ed 100644
--- a/app/Http/Requests/Subscription/DestroySubscriptionRequest.php
+++ b/app/Http/Requests/Subscription/DestroySubscriptionRequest.php
@@ -12,7 +12,6 @@
namespace App\Http\Requests\Subscription;
use App\Http\Requests\Request;
-use Illuminate\Foundation\Http\FormRequest;
class DestroySubscriptionRequest extends Request
{
diff --git a/app/Http/Requests/Subscription/EditSubscriptionRequest.php b/app/Http/Requests/Subscription/EditSubscriptionRequest.php
index b219d4eca76d..3b5c0e67e097 100644
--- a/app/Http/Requests/Subscription/EditSubscriptionRequest.php
+++ b/app/Http/Requests/Subscription/EditSubscriptionRequest.php
@@ -12,7 +12,6 @@
namespace App\Http\Requests\Subscription;
use App\Http\Requests\Request;
-use Illuminate\Foundation\Http\FormRequest;
class EditSubscriptionRequest extends Request
{
diff --git a/app/Http/Requests/Subscription/ShowSubscriptionRequest.php b/app/Http/Requests/Subscription/ShowSubscriptionRequest.php
index c8896e7e1673..50a2b7318055 100644
--- a/app/Http/Requests/Subscription/ShowSubscriptionRequest.php
+++ b/app/Http/Requests/Subscription/ShowSubscriptionRequest.php
@@ -12,7 +12,6 @@
namespace App\Http\Requests\Subscription;
use App\Http\Requests\Request;
-use Illuminate\Foundation\Http\FormRequest;
class ShowSubscriptionRequest extends Request
{
diff --git a/app/Http/Requests/Subscription/StoreSubscriptionRequest.php b/app/Http/Requests/Subscription/StoreSubscriptionRequest.php
index aa781f351da1..2a358ac37a94 100644
--- a/app/Http/Requests/Subscription/StoreSubscriptionRequest.php
+++ b/app/Http/Requests/Subscription/StoreSubscriptionRequest.php
@@ -11,9 +11,9 @@
namespace App\Http\Requests\Subscription;
+use App\Http\Requests\Request;
use App\Models\Account;
use App\Models\Subscription;
-use App\Http\Requests\Request;
use Illuminate\Validation\Rule;
class StoreSubscriptionRequest extends Request
@@ -37,8 +37,8 @@ class StoreSubscriptionRequest extends Request
{
$rules = [
'name' => ['required', Rule::unique('subscriptions')->where('company_id', auth()->user()->company()->id)],
- 'group_id' => ['bail','sometimes', 'nullable', Rule::exists('group_settings','id')->where('company_id', auth()->user()->company()->id)],
- 'assigned_user_id' => ['bail','sometimes', 'nullable', Rule::exists('users','id')->where('account_id', auth()->user()->account_id)],
+ 'group_id' => ['bail','sometimes', 'nullable', Rule::exists('group_settings', 'id')->where('company_id', auth()->user()->company()->id)],
+ 'assigned_user_id' => ['bail','sometimes', 'nullable', Rule::exists('users', 'id')->where('account_id', auth()->user()->account_id)],
'product_ids' => 'bail|sometimes|nullable|string',
'recurring_product_ids' => 'bail|sometimes|nullable|string',
'is_recurring' => 'bail|sometimes|bool',
diff --git a/app/Http/Requests/Subscription/UpdateSubscriptionRequest.php b/app/Http/Requests/Subscription/UpdateSubscriptionRequest.php
index 9b6493c15a7c..811d38000c67 100644
--- a/app/Http/Requests/Subscription/UpdateSubscriptionRequest.php
+++ b/app/Http/Requests/Subscription/UpdateSubscriptionRequest.php
@@ -38,8 +38,8 @@ class UpdateSubscriptionRequest extends Request
{
$rules = [
'name' => ['bail','sometimes', Rule::unique('subscriptions')->where('company_id', auth()->user()->company()->id)->ignore($this->subscription->id)],
- 'group_id' => ['bail','sometimes', 'nullable', Rule::exists('group_settings','id')->where('company_id', auth()->user()->company()->id)],
- 'assigned_user_id' => ['bail','sometimes', 'nullable', Rule::exists('users','id')->where('account_id', auth()->user()->account_id)],
+ 'group_id' => ['bail','sometimes', 'nullable', Rule::exists('group_settings', 'id')->where('company_id', auth()->user()->company()->id)],
+ 'assigned_user_id' => ['bail','sometimes', 'nullable', Rule::exists('users', 'id')->where('account_id', auth()->user()->account_id)],
'product_ids' => 'bail|sometimes|nullable|string',
'recurring_product_ids' => 'bail|sometimes|nullable|string',
'is_recurring' => 'bail|sometimes|bool',
diff --git a/app/Http/Requests/Task/SortTaskRequest.php b/app/Http/Requests/Task/SortTaskRequest.php
index 1edfea8c45d5..20ae64370cd4 100644
--- a/app/Http/Requests/Task/SortTaskRequest.php
+++ b/app/Http/Requests/Task/SortTaskRequest.php
@@ -23,7 +23,6 @@ class SortTaskRequest extends Request
public function authorize() : bool
{
return true;
-
}
public function rules()
diff --git a/app/Http/Requests/Task/StoreTaskRequest.php b/app/Http/Requests/Task/StoreTaskRequest.php
index 0d0247902050..b5d160316e08 100644
--- a/app/Http/Requests/Task/StoreTaskRequest.php
+++ b/app/Http/Requests/Task/StoreTaskRequest.php
@@ -39,23 +39,24 @@ class StoreTaskRequest extends Request
$rules['number'] = Rule::unique('tasks')->where('company_id', auth()->user()->company()->id);
}
- if(isset($this->client_id))
+ if (isset($this->client_id)) {
$rules['client_id'] = 'bail|required|exists:clients,id,company_id,'.auth()->user()->company()->id.',is_deleted,0';
+ }
- if(isset($this->project_id))
+ if (isset($this->project_id)) {
$rules['project_id'] = 'bail|required|exists:projects,id,company_id,'.auth()->user()->company()->id.',is_deleted,0';
+ }
$rules['timelog'] = ['bail','array',function ($attribute, $values, $fail) {
-
- foreach($values as $k)
- {
- if(!is_int($k[0]) || !is_int($k[1]))
- $fail('The '.$attribute.' - '.print_r($k,1).' is invalid. Unix timestamps only.');
+ foreach ($values as $k) {
+ if (!is_int($k[0]) || !is_int($k[1])) {
+ $fail('The '.$attribute.' - '.print_r($k, 1).' is invalid. Unix timestamps only.');
+ }
}
- if(!$this->checkTimeLog($values))
+ if (!$this->checkTimeLog($values)) {
$fail('Please correct overlapping values');
-
+ }
}];
@@ -74,15 +75,12 @@ class StoreTaskRequest extends Request
/* Ensure the project is related */
if (array_key_exists('project_id', $input) && isset($input['project_id'])) {
$project = Project::withTrashed()->where('id', $input['project_id'])->company()->first();
-;
- if($project){
+ ;
+ if ($project) {
$input['client_id'] = $project->client_id;
- }
- else
- {
+ } else {
unset($input['project_id']);
}
-
}
$this->replace($input);
diff --git a/app/Http/Requests/Task/UpdateTaskRequest.php b/app/Http/Requests/Task/UpdateTaskRequest.php
index 2046a5e8f868..8917e44643d4 100644
--- a/app/Http/Requests/Task/UpdateTaskRequest.php
+++ b/app/Http/Requests/Task/UpdateTaskRequest.php
@@ -29,10 +29,12 @@ class UpdateTaskRequest extends Request
* @return bool
*/
public function authorize() : bool
- {nlog("oioi");
+ {
+ nlog("oioi");
//prevent locked tasks from updating
- if($this->task->invoice_id && $this->task->company->invoice_task_lock)
+ if ($this->task->invoice_id && $this->task->company->invoice_task_lock) {
return false;
+ }
return auth()->user()->can('edit', $this->task);
}
@@ -45,23 +47,24 @@ class UpdateTaskRequest extends Request
$rules['number'] = Rule::unique('tasks')->where('company_id', auth()->user()->company()->id)->ignore($this->task->id);
}
- if(isset($this->client_id))
+ if (isset($this->client_id)) {
$rules['client_id'] = 'bail|required|exists:clients,id,company_id,'.auth()->user()->company()->id.',is_deleted,0';
+ }
- if(isset($this->project_id))
+ if (isset($this->project_id)) {
$rules['project_id'] = 'bail|required|exists:projects,id,company_id,'.auth()->user()->company()->id.',is_deleted,0';
+ }
$rules['timelog'] = ['bail','array',function ($attribute, $values, $fail) {
-
- foreach($values as $k)
- {
- if(!is_int($k[0]) || !is_int($k[1]))
- $fail('The '.$attribute.' - '.print_r($k,1).' is invalid. Unix timestamps only.');
+ foreach ($values as $k) {
+ if (!is_int($k[0]) || !is_int($k[1])) {
+ $fail('The '.$attribute.' - '.print_r($k, 1).' is invalid. Unix timestamps only.');
+ }
}
- if(!$this->checkTimeLog($values))
+ if (!$this->checkTimeLog($values)) {
$fail('Please correct overlapping values');
-
+ }
}];
return $this->globalRules($rules);
@@ -79,14 +82,11 @@ class UpdateTaskRequest extends Request
if (array_key_exists('project_id', $input) && isset($input['project_id'])) {
$project = Project::withTrashed()->where('id', $input['project_id'])->company()->first();
- if($project){
+ if ($project) {
$input['client_id'] = $project->client_id;
- }
- else
- {
+ } else {
unset($input['project_id']);
}
-
}
if (array_key_exists('color', $input) && is_null($input['color'])) {
@@ -101,5 +101,4 @@ class UpdateTaskRequest extends Request
{
throw new AuthorizationException(ctrans('texts.task_update_authorization_error'));
}
-
}
diff --git a/app/Http/Requests/TaskScheduler/CreateSchedulerRequest.php b/app/Http/Requests/TaskScheduler/CreateSchedulerRequest.php
index 8b4a343d8ea8..2d84a13f9164 100644
--- a/app/Http/Requests/TaskScheduler/CreateSchedulerRequest.php
+++ b/app/Http/Requests/TaskScheduler/CreateSchedulerRequest.php
@@ -24,5 +24,4 @@ class CreateSchedulerRequest extends Request
{
return auth()->user()->isAdmin();
}
-
}
diff --git a/app/Http/Requests/TaskScheduler/StoreSchedulerRequest.php b/app/Http/Requests/TaskScheduler/StoreSchedulerRequest.php
index 656e5f5fe3e6..9061d57912d6 100644
--- a/app/Http/Requests/TaskScheduler/StoreSchedulerRequest.php
+++ b/app/Http/Requests/TaskScheduler/StoreSchedulerRequest.php
@@ -13,7 +13,6 @@ namespace App\Http\Requests\TaskScheduler;
use App\Http\Requests\Request;
use App\Http\ValidationRules\Scheduler\ValidClientIds;
-use App\Models\Client;
use App\Utils\Traits\MakesHash;
use Illuminate\Validation\Rule;
@@ -32,7 +31,6 @@ class StoreSchedulerRequest extends Request
public function rules()
{
-
$rules = [
'name' => ['bail', 'required', Rule::unique('schedulers')->where('company_id', auth()->user()->company()->id)],
'is_paused' => 'bail|sometimes|boolean',
@@ -45,19 +43,16 @@ class StoreSchedulerRequest extends Request
];
return $rules;
-
}
public function prepareForValidation()
{
-
$input = $this->all();
- if (array_key_exists('next_run', $input) && is_string($input['next_run']))
+ if (array_key_exists('next_run', $input) && is_string($input['next_run'])) {
$this->merge(['next_run_client' => $input['next_run']]);
+ }
return $input;
}
-
-
}
diff --git a/app/Http/Requests/TaskScheduler/UpdateSchedulerRequest.php b/app/Http/Requests/TaskScheduler/UpdateSchedulerRequest.php
index bc1d02b0553a..02a5e69b5351 100644
--- a/app/Http/Requests/TaskScheduler/UpdateSchedulerRequest.php
+++ b/app/Http/Requests/TaskScheduler/UpdateSchedulerRequest.php
@@ -27,7 +27,6 @@ class UpdateSchedulerRequest extends Request
public function rules(): array
{
-
$rules = [
'name' => ['bail', 'sometimes', Rule::unique('schedulers')->where('company_id', auth()->user()->company()->id)->ignore($this->task_scheduler->id)],
'is_paused' => 'bail|sometimes|boolean',
@@ -39,19 +38,16 @@ class UpdateSchedulerRequest extends Request
];
return $rules;
-
}
public function prepareForValidation()
{
-
$input = $this->all();
- if (array_key_exists('next_run', $input) && is_string($input['next_run']))
+ if (array_key_exists('next_run', $input) && is_string($input['next_run'])) {
$this->merge(['next_run_client' => $input['next_run']]);
+ }
return $input;
-
}
-
}
diff --git a/app/Http/Requests/TaskStatus/ActionTaskStatusRequest.php b/app/Http/Requests/TaskStatus/ActionTaskStatusRequest.php
index 3df02d2dde86..1091c06e22af 100644
--- a/app/Http/Requests/TaskStatus/ActionTaskStatusRequest.php
+++ b/app/Http/Requests/TaskStatus/ActionTaskStatusRequest.php
@@ -27,11 +27,9 @@ class ActionTaskStatusRequest extends Request
public function rules()
{
-
return [
'ids' => 'required|bail|array',
'action' => 'in:archive,restore,delete'
];
-
}
}
diff --git a/app/Http/Requests/Token/UpdateTokenRequest.php b/app/Http/Requests/Token/UpdateTokenRequest.php
index 20f572e28bf7..584dce16b22f 100644
--- a/app/Http/Requests/Token/UpdateTokenRequest.php
+++ b/app/Http/Requests/Token/UpdateTokenRequest.php
@@ -34,5 +34,4 @@ class UpdateTokenRequest extends Request
'name' => 'required',
];
}
-
}
diff --git a/app/Http/Requests/Twilio/Confirm2faRequest.php b/app/Http/Requests/Twilio/Confirm2faRequest.php
index b6da44d00171..d686e6345463 100644
--- a/app/Http/Requests/Twilio/Confirm2faRequest.php
+++ b/app/Http/Requests/Twilio/Confirm2faRequest.php
@@ -14,10 +14,8 @@ namespace App\Http\Requests\Twilio;
use App\Http\Requests\Request;
use App\Libraries\MultiDB;
-
class Confirm2faRequest extends Request
{
-
/**
* Determine if the user is authorized to make this request.
*
@@ -30,7 +28,6 @@ class Confirm2faRequest extends Request
public function rules()
{
-
return [
'code' => 'required',
'email' => 'required|exists:users,email',
@@ -41,10 +38,10 @@ class Confirm2faRequest extends Request
{
$input = $this->all();
- if(array_key_exists('email', $input))
+ if (array_key_exists('email', $input)) {
MultiDB::userFindAndSetDb($input['email']);
+ }
$this->replace($input);
}
-
}
diff --git a/app/Http/Requests/Twilio/ConfirmSmsRequest.php b/app/Http/Requests/Twilio/ConfirmSmsRequest.php
index 1ed81d622739..8ef72e05c655 100644
--- a/app/Http/Requests/Twilio/ConfirmSmsRequest.php
+++ b/app/Http/Requests/Twilio/ConfirmSmsRequest.php
@@ -13,10 +13,8 @@ namespace App\Http\Requests\Twilio;
use App\Http\Requests\Request;
-
class ConfirmSmsRequest extends Request
{
-
/**
* Determine if the user is authorized to make this request.
*
@@ -29,10 +27,8 @@ class ConfirmSmsRequest extends Request
public function rules()
{
-
return [
'code' => 'required',
];
}
-
}
diff --git a/app/Http/Requests/Twilio/Generate2faRequest.php b/app/Http/Requests/Twilio/Generate2faRequest.php
index f4cbaa196a4a..d34190faaabc 100644
--- a/app/Http/Requests/Twilio/Generate2faRequest.php
+++ b/app/Http/Requests/Twilio/Generate2faRequest.php
@@ -14,10 +14,8 @@ namespace App\Http\Requests\Twilio;
use App\Http\Requests\Request;
use App\Libraries\MultiDB;
-
class Generate2faRequest extends Request
{
-
/**
* Determine if the user is authorized to make this request.
*
@@ -31,21 +29,19 @@ class Generate2faRequest extends Request
public function rules()
{
-
return [
'email' => 'required|exists:users,email',
];
-
}
public function prepareForValidation()
{
$input = $this->all();
- if(array_key_exists('email', $input))
+ if (array_key_exists('email', $input)) {
MultiDB::userFindAndSetDb($input['email']);
+ }
$this->replace($input);
}
-
}
diff --git a/app/Http/Requests/Twilio/GenerateSmsRequest.php b/app/Http/Requests/Twilio/GenerateSmsRequest.php
index deeef41cafaa..c503cc12b5bb 100644
--- a/app/Http/Requests/Twilio/GenerateSmsRequest.php
+++ b/app/Http/Requests/Twilio/GenerateSmsRequest.php
@@ -13,10 +13,8 @@ namespace App\Http\Requests\Twilio;
use App\Http\Requests\Request;
-
class GenerateSmsRequest extends Request
{
-
/**
* Determine if the user is authorized to make this request.
*
@@ -30,10 +28,8 @@ class GenerateSmsRequest extends Request
public function rules()
{
-
return [
'phone' => 'required|regex:^\+[1-9]\d{1,14}$^',
];
-
}
}
diff --git a/app/Http/Requests/TwoFactor/EnableTwoFactorRequest.php b/app/Http/Requests/TwoFactor/EnableTwoFactorRequest.php
index bddd6f23dd94..9c6293c8bd20 100644
--- a/app/Http/Requests/TwoFactor/EnableTwoFactorRequest.php
+++ b/app/Http/Requests/TwoFactor/EnableTwoFactorRequest.php
@@ -12,7 +12,6 @@
namespace App\Http\Requests\TwoFactor;
use App\Http\Requests\Request;
-use Illuminate\Validation\Rule;
class EnableTwoFactorRequest extends Request
{
@@ -23,7 +22,8 @@ class EnableTwoFactorRequest extends Request
*/
public function authorize() : bool
{
- return true;;
+ return true;
+ ;
}
public function rules()
@@ -36,6 +36,5 @@ class EnableTwoFactorRequest extends Request
public function prepareForValidation()
{
-
}
}
diff --git a/app/Http/Requests/User/BulkUserRequest.php b/app/Http/Requests/User/BulkUserRequest.php
index 109e86c5f758..1ae2ee8dca63 100644
--- a/app/Http/Requests/User/BulkUserRequest.php
+++ b/app/Http/Requests/User/BulkUserRequest.php
@@ -13,7 +13,6 @@ namespace App\Http\Requests\User;
use App\Http\Requests\Request;
use App\Http\ValidationRules\Ninja\CanRestoreUserRule;
-use App\Http\ValidationRules\UniqueUserRule;
use App\Utils\Ninja;
class BulkUserRequest extends Request
diff --git a/app/Http/Requests/User/StoreUserRequest.php b/app/Http/Requests/User/StoreUserRequest.php
index 4b6ed76574f8..179b6238809a 100644
--- a/app/Http/Requests/User/StoreUserRequest.php
+++ b/app/Http/Requests/User/StoreUserRequest.php
@@ -11,7 +11,6 @@
namespace App\Http\Requests\User;
-use App\DataMapper\DefaultSettings;
use App\Factory\UserFactory;
use App\Http\Requests\Request;
use App\Http\ValidationRules\Ninja\CanAddUserRule;
@@ -21,7 +20,6 @@ use App\Http\ValidationRules\ValidUserForCompany;
use App\Libraries\MultiDB;
use App\Models\User;
use App\Utils\Ninja;
-use Illuminate\Validation\Rule;
class StoreUserRequest extends Request
{
@@ -51,9 +49,9 @@ class StoreUserRequest extends Request
if (Ninja::isHosted()) {
$rules['id'] = new CanAddUserRule();
- if($this->phone && isset($this->phone))
+ if ($this->phone && isset($this->phone)) {
$rules['phone'] = ['bail', 'string', 'sometimes', new HasValidPhoneNumber()];
-
+ }
}
return $rules;
diff --git a/app/Http/Requests/User/UpdateUserRequest.php b/app/Http/Requests/User/UpdateUserRequest.php
index 69dd646752d5..2bbc24e21e85 100644
--- a/app/Http/Requests/User/UpdateUserRequest.php
+++ b/app/Http/Requests/User/UpdateUserRequest.php
@@ -18,7 +18,6 @@ use App\Utils\Ninja;
class UpdateUserRequest extends Request
{
-
private bool $phone_has_changed = false;
/**
@@ -43,8 +42,9 @@ class UpdateUserRequest extends Request
$rules['email'] = ['email', 'sometimes', new UniqueUserRule($this->user, $input['email'])];
}
- if(Ninja::isHosted() && $this->phone_has_changed && $this->phone && isset($this->phone))
+ if (Ninja::isHosted() && $this->phone_has_changed && $this->phone && isset($this->phone)) {
$rules['phone'] = ['sometimes', 'bail', 'string', new HasValidPhoneNumber()];
+ }
return $rules;
}
@@ -65,14 +65,14 @@ class UpdateUserRequest extends Request
$input['last_name'] = strip_tags($input['last_name']);
}
- if(array_key_exists('phone', $input) && isset($input['phone']) && strlen($input['phone']) > 1 && ($this->user->phone != $input['phone'])){
+ if (array_key_exists('phone', $input) && isset($input['phone']) && strlen($input['phone']) > 1 && ($this->user->phone != $input['phone'])) {
$this->phone_has_changed = true;
}
- if(array_key_exists('oauth_provider_id', $input) && $input['oauth_provider_id'] == '')
+ if (array_key_exists('oauth_provider_id', $input) && $input['oauth_provider_id'] == '') {
$input['oauth_user_id'] = '';
+ }
$this->replace($input);
}
-
}
diff --git a/app/Http/Requests/Vendor/StoreVendorRequest.php b/app/Http/Requests/Vendor/StoreVendorRequest.php
index a35baa725b2d..dc67adcbffa4 100644
--- a/app/Http/Requests/Vendor/StoreVendorRequest.php
+++ b/app/Http/Requests/Vendor/StoreVendorRequest.php
@@ -12,7 +12,6 @@
namespace App\Http\Requests\Vendor;
use App\Http\Requests\Request;
-use App\Http\ValidationRules\ValidVendorGroupSettingsRule;
use App\Models\Vendor;
use App\Utils\Traits\MakesHash;
use Illuminate\Validation\Rule;
@@ -42,8 +41,9 @@ class StoreVendorRequest extends Request
$rules['contacts.*.email'] = 'bail|nullable|distinct|sometimes|email';
- if (isset($this->number))
+ if (isset($this->number)) {
$rules['number'] = Rule::unique('vendors')->where('company_id', $user->company()->id);
+ }
$rules['currency_id'] = 'bail|required|exists:currencies,id';
@@ -58,7 +58,7 @@ class StoreVendorRequest extends Request
$input = $this->all();
- if(!array_key_exists('currency_id', $input) || empty($input['currency_id'])){
+ if (!array_key_exists('currency_id', $input) || empty($input['currency_id'])) {
$input['currency_id'] = $user->company()->settings->currency_id;
}
diff --git a/app/Http/Requests/Vendor/UpdateVendorRequest.php b/app/Http/Requests/Vendor/UpdateVendorRequest.php
index a02e72a3b443..8beda8c22eef 100644
--- a/app/Http/Requests/Vendor/UpdateVendorRequest.php
+++ b/app/Http/Requests/Vendor/UpdateVendorRequest.php
@@ -64,8 +64,9 @@ class UpdateVendorRequest extends Request
$input['assigned_user_id'] = $this->decodePrimaryKey($input['assigned_user_id']);
}
- if(array_key_exists('country_id', $input) && is_null($input['country_id']))
+ if (array_key_exists('country_id', $input) && is_null($input['country_id'])) {
unset($input['country_id']);
+ }
$input = $this->decodePrimaryKeys($input);
diff --git a/app/Http/Requests/Webhook/StoreWebhookRequest.php b/app/Http/Requests/Webhook/StoreWebhookRequest.php
index 7fd5d372c24a..b6f0ed24bf1b 100644
--- a/app/Http/Requests/Webhook/StoreWebhookRequest.php
+++ b/app/Http/Requests/Webhook/StoreWebhookRequest.php
@@ -11,8 +11,8 @@
namespace App\Http\Requests\Webhook;
-use App\Models\Account;
use App\Http\Requests\Request;
+use App\Models\Account;
class StoreWebhookRequest extends Request
{
@@ -40,10 +40,11 @@ class StoreWebhookRequest extends Request
{
$input = $this->all();
- if(!isset($input['rest_method']))
+ if (!isset($input['rest_method'])) {
$input['rest_method'] = 'post';
- // if(isset($input['headers']) && count($input['headers']) == 0)
- // $input['headers'] = null;
+ }
+ // if(isset($input['headers']) && count($input['headers']) == 0)
+ // $input['headers'] = null;
$this->replace($input);
}
diff --git a/app/Http/Requests/Webhook/UpdateWebhookRequest.php b/app/Http/Requests/Webhook/UpdateWebhookRequest.php
index 21b46163a16b..d8fd2ed783cd 100644
--- a/app/Http/Requests/Webhook/UpdateWebhookRequest.php
+++ b/app/Http/Requests/Webhook/UpdateWebhookRequest.php
@@ -44,10 +44,11 @@ class UpdateWebhookRequest extends Request
{
$input = $this->all();
- if(!isset($input['rest_method']))
+ if (!isset($input['rest_method'])) {
$input['rest_method'] = 'post';
+ }
- // if(isset($input['headers']) && count($input['headers']) == 0)
+ // if(isset($input['headers']) && count($input['headers']) == 0)
// $input['headers'] = null;
$this->replace($input);
diff --git a/app/Http/Requests/Yodlee/YodleeAdminRequest.php b/app/Http/Requests/Yodlee/YodleeAdminRequest.php
index b161e14d8539..0ef06a68aa88 100644
--- a/app/Http/Requests/Yodlee/YodleeAdminRequest.php
+++ b/app/Http/Requests/Yodlee/YodleeAdminRequest.php
@@ -15,7 +15,6 @@ use App\Http\Requests\Request;
class YodleeAdminRequest extends Request
{
-
/**
* Determine if the user is authorized to make this request.
*
@@ -35,5 +34,4 @@ class YodleeAdminRequest extends Request
{
return [];
}
-
-}
\ No newline at end of file
+}
diff --git a/app/Http/Requests/Yodlee/YodleeAuthRequest.php b/app/Http/Requests/Yodlee/YodleeAuthRequest.php
index 37709a095ec6..ff267c5f98f5 100644
--- a/app/Http/Requests/Yodlee/YodleeAuthRequest.php
+++ b/app/Http/Requests/Yodlee/YodleeAuthRequest.php
@@ -19,7 +19,6 @@ use Illuminate\Support\Facades\Cache;
class YodleeAuthRequest extends Request
{
-
/**
* Determine if the user is authorized to make this request.
*
@@ -56,15 +55,12 @@ class YodleeAuthRequest extends Request
MultiDB::findAndSetDbByCompanyKey($this->getTokenContent()['company_key']);
return User::findOrFail($this->getTokenContent()['user_id']);
-
}
public function getCompany()
{
-
MultiDB::findAndSetDbByCompanyKey($this->getTokenContent()['company_key']);
return Company::where('company_key', $this->getTokenContent()['company_key'])->firstOrFail();
-
}
-}
\ No newline at end of file
+}
diff --git a/app/Http/ValidationRules/Account/BlackListRule.php b/app/Http/ValidationRules/Account/BlackListRule.php
index 90cb41ac2a76..c79d1270afef 100644
--- a/app/Http/ValidationRules/Account/BlackListRule.php
+++ b/app/Http/ValidationRules/Account/BlackListRule.php
@@ -11,7 +11,6 @@
namespace App\Http\ValidationRules\Account;
-use App\Libraries\MultiDB;
use Illuminate\Contracts\Validation\Rule;
/**
diff --git a/app/Http/ValidationRules/Account/EmailBlackListRule.php b/app/Http/ValidationRules/Account/EmailBlackListRule.php
index 23448f89fe39..43e3451d1b6c 100644
--- a/app/Http/ValidationRules/Account/EmailBlackListRule.php
+++ b/app/Http/ValidationRules/Account/EmailBlackListRule.php
@@ -11,7 +11,6 @@
namespace App\Http\ValidationRules\Account;
-use App\Libraries\MultiDB;
use Illuminate\Contracts\Validation\Rule;
/**
diff --git a/app/Http/ValidationRules/Company/ValidCompanyQuantity.php b/app/Http/ValidationRules/Company/ValidCompanyQuantity.php
index c8e257add07c..aae4328f4e8d 100644
--- a/app/Http/ValidationRules/Company/ValidCompanyQuantity.php
+++ b/app/Http/ValidationRules/Company/ValidCompanyQuantity.php
@@ -26,7 +26,6 @@ class ValidCompanyQuantity implements Rule
*/
public function passes($attribute, $value)
{
-
if (Ninja::isSelfHost()) {
return auth()->user()->company()->account->companies->count() < 10;
}
diff --git a/app/Http/ValidationRules/Credit/ValidCreditsRules.php b/app/Http/ValidationRules/Credit/ValidCreditsRules.php
index 8a2c9b2c7f20..7b6fc32aed88 100644
--- a/app/Http/ValidationRules/Credit/ValidCreditsRules.php
+++ b/app/Http/ValidationRules/Credit/ValidCreditsRules.php
@@ -53,8 +53,7 @@ class ValidCreditsRules implements Rule
$total_credit_amount = array_sum(array_column($this->input['credits'], 'amount'));
- if($total_credit_amount <= 0){
-
+ if ($total_credit_amount <= 0) {
$this->error_msg = "Total of credits must be more than zero.";
return false;
diff --git a/app/Http/ValidationRules/Ninja/CanAddUserRule.php b/app/Http/ValidationRules/Ninja/CanAddUserRule.php
index adccb9c1de08..6e19dbd09b14 100644
--- a/app/Http/ValidationRules/Ninja/CanAddUserRule.php
+++ b/app/Http/ValidationRules/Ninja/CanAddUserRule.php
@@ -31,7 +31,6 @@ class CanAddUserRule implements Rule
*/
public function passes($attribute, $value)
{
-
/* If the user is active then we can add them to the company */
if (User::where('email', request()->input('email'))->where('account_id', auth()->user()->account_id)->where('is_deleted', 0)->exists()) {
return true;
diff --git a/app/Http/ValidationRules/Ninja/CanRestoreUserRule.php b/app/Http/ValidationRules/Ninja/CanRestoreUserRule.php
index c3c1d2525b61..a73e4ce555e1 100644
--- a/app/Http/ValidationRules/Ninja/CanRestoreUserRule.php
+++ b/app/Http/ValidationRules/Ninja/CanRestoreUserRule.php
@@ -12,7 +12,6 @@
namespace App\Http\ValidationRules\Ninja;
use App\Models\CompanyUser;
-use App\Models\User;
use Illuminate\Contracts\Validation\Rule;
/**
diff --git a/app/Http/ValidationRules/Scheduler/ValidClientIds.php b/app/Http/ValidationRules/Scheduler/ValidClientIds.php
index 8326db809e25..64086bc5e906 100644
--- a/app/Http/ValidationRules/Scheduler/ValidClientIds.php
+++ b/app/Http/ValidationRules/Scheduler/ValidClientIds.php
@@ -28,9 +28,7 @@ class ValidClientIds implements Rule
*/
public function passes($attribute, $value)
{
-
return Client::where('company_id', auth()->user()->company()->id)->whereIn('id', $this->transformKeys($value))->count() == count($value);
-
}
/**
diff --git a/app/Http/ValidationRules/User/HasValidPhoneNumber.php b/app/Http/ValidationRules/User/HasValidPhoneNumber.php
index 997e26e5510b..72c6b79d0f45 100644
--- a/app/Http/ValidationRules/User/HasValidPhoneNumber.php
+++ b/app/Http/ValidationRules/User/HasValidPhoneNumber.php
@@ -11,8 +11,6 @@
namespace App\Http\ValidationRules\User;
-use App\Models\CompanyUser;
-use App\Models\User;
use Illuminate\Contracts\Validation\Rule;
/**
@@ -26,8 +24,8 @@ class HasValidPhoneNumber implements Rule
{
}
- public function message()
- {
+ public function message()
+ {
return [
'phone' => ctrans('texts.phone_validation_error'),
];
@@ -40,44 +38,41 @@ class HasValidPhoneNumber implements Rule
*/
public function passes($attribute, $value)
{
+ $sid = config('ninja.twilio_account_sid');
+ $token = config('ninja.twilio_auth_token');
- $sid = config('ninja.twilio_account_sid');
- $token = config('ninja.twilio_auth_token');
+ if (!$sid) {
+ return true;
+ }
- if(!$sid)
- return true;
-
- if(is_null($value))
+ if (is_null($value)) {
return false;
+ }
- $twilio = new \Twilio\Rest\Client($sid, $token);
+ $twilio = new \Twilio\Rest\Client($sid, $token);
- $country = auth()->user()->account?->companies()?->first()?->country();
+ $country = auth()->user()->account?->companies()?->first()?->country();
- if(!$country || strlen(auth()->user()->phone) < 2)
- return true;
+ if (!$country || strlen(auth()->user()->phone) < 2) {
+ return true;
+ }
- $countryCode = $country->iso_3166_2;
+ $countryCode = $country->iso_3166_2;
- try{
-
- $phone_number = $twilio->lookups->v1->phoneNumbers($value)
- ->fetch(["countryCode" => $countryCode]);
+ try {
+ $phone_number = $twilio->lookups->v1->phoneNumbers($value)
+ ->fetch(["countryCode" => $countryCode]);
$user = auth()->user();
request()->merge(['validated_phone' => $phone_number->phoneNumber ]);
- $user->verified_phone_number = false;
+ $user->verified_phone_number = false;
$user->save();
return true;
-
- }
- catch(\Exception $e) {
- return false;
- }
-
+ } catch(\Exception $e) {
+ return false;
+ }
}
-
}
diff --git a/app/Http/ValidationRules/ValidAmount.php b/app/Http/ValidationRules/ValidAmount.php
index 6f296e4f205a..4438b935ad9b 100644
--- a/app/Http/ValidationRules/ValidAmount.php
+++ b/app/Http/ValidationRules/ValidAmount.php
@@ -11,7 +11,6 @@
namespace App\Http\ValidationRules;
-use App\Libraries\MultiDB;
use Illuminate\Contracts\Validation\Rule;
/**
diff --git a/app/Http/ValidationRules/ValidRefundableInvoices.php b/app/Http/ValidationRules/ValidRefundableInvoices.php
index f430ebad5806..d14b37844689 100644
--- a/app/Http/ValidationRules/ValidRefundableInvoices.php
+++ b/app/Http/ValidationRules/ValidRefundableInvoices.php
@@ -71,7 +71,6 @@ class ValidRefundableInvoices implements Rule
foreach ($this->input['invoices'] as $val) {
if ($val['invoice_id'] == $invoice->id) {
-
//$pivot_record = $invoice->payments->where('id', $invoice->id)->first();
$pivot_record = $payment->paymentables->where('paymentable_id', $invoice->id)->first();
diff --git a/app/Http/ViewComposers/PortalComposer.php b/app/Http/ViewComposers/PortalComposer.php
index 6203df8e9a66..10261419bffd 100644
--- a/app/Http/ViewComposers/PortalComposer.php
+++ b/app/Http/ViewComposers/PortalComposer.php
@@ -14,7 +14,6 @@ namespace App\Http\ViewComposers;
use App\Utils\Ninja;
use App\Utils\TranslationHelper;
use Illuminate\Support\Facades\App;
-use Illuminate\Support\Facades\Lang;
use Illuminate\View\View;
/**
diff --git a/app/Import/Definitions/BankTransactionMap.php b/app/Import/Definitions/BankTransactionMap.php
index 138f8d5d0ad0..b6482926ee8c 100644
--- a/app/Import/Definitions/BankTransactionMap.php
+++ b/app/Import/Definitions/BankTransactionMap.php
@@ -44,4 +44,4 @@ class BankTransactionMap
9 => 'texts.type',
];
}
-}
\ No newline at end of file
+}
diff --git a/app/Import/Providers/BaseImport.php b/app/Import/Providers/BaseImport.php
index 938115dfe010..1d1954dfa0c5 100644
--- a/app/Import/Providers/BaseImport.php
+++ b/app/Import/Providers/BaseImport.php
@@ -15,7 +15,6 @@ use App\Factory\ClientFactory;
use App\Factory\InvoiceFactory;
use App\Factory\PaymentFactory;
use App\Factory\QuoteFactory;
-use App\Http\Requests\Invoice\StoreInvoiceRequest;
use App\Http\Requests\Quote\StoreQuoteRequest;
use App\Import\ImportException;
use App\Jobs\Mail\NinjaMailerJob;
@@ -31,12 +30,9 @@ use App\Repositories\PaymentRepository;
use App\Repositories\QuoteRepository;
use App\Utils\Traits\CleanLineItems;
use Illuminate\Support\Facades\Cache;
-use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
-use Illuminate\Support\Str;
use League\Csv\Reader;
use League\Csv\Statement;
-use Symfony\Component\HttpFoundation\ParameterBag;
class BaseImport
{
@@ -152,7 +148,7 @@ class BaseImport
private function runValidation($data)
- {
+ {
$_syn_request_class = new $this->request_name;
$_syn_request_class->setContainer(app());
$_syn_request_class->initialize($data);
@@ -163,7 +159,6 @@ class BaseImport
$_syn_request_class->setValidator($validator);
return $validator;
-
}
public function ingest($data, $entity_type)
@@ -173,8 +168,7 @@ class BaseImport
$is_free_hosted_client = $this->company->account->isFreeHostedClient();
$hosted_client_count = $this->company->account->hosted_client_count;
- if($this->factory_name == 'App\Factory\ClientFactory' && $is_free_hosted_client && (count($data) > $hosted_client_count))
- {
+ if ($this->factory_name == 'App\Factory\ClientFactory' && $is_free_hosted_client && (count($data) > $hosted_client_count)) {
$this->error_array[$entity_type][] = [
$entity_type => 'client',
'error' => 'Error, you are attempting to import more clients than your plan allows',
@@ -184,12 +178,12 @@ class BaseImport
}
foreach ($data as $key => $record) {
-
try {
$entity = $this->transformer->transform($record);
- if(!$entity)
+ if (!$entity) {
continue;
+ }
$validator = $this->runValidation($entity);
@@ -226,9 +220,8 @@ class BaseImport
'error' => $message,
];
- nlog("Ingest {$ex->getMessage()}");
- nlog($record);
-
+ nlog("Ingest {$ex->getMessage()}");
+ nlog($record);
}
}
@@ -415,7 +408,6 @@ class BaseImport
}
return $count;
-
}
private function actionInvoiceStatus(
@@ -568,11 +560,9 @@ class BaseImport
'error' => $message,
];
}
-
}
return $count;
-
}
protected function getUserIDForRecord($record)
diff --git a/app/Import/Providers/Csv.php b/app/Import/Providers/Csv.php
index 7ecb4417dadb..895b874634d2 100644
--- a/app/Import/Providers/Csv.php
+++ b/app/Import/Providers/Csv.php
@@ -27,9 +27,7 @@ use App\Http\Requests\Payment\StorePaymentRequest;
use App\Http\Requests\Product\StoreProductRequest;
use App\Http\Requests\Quote\StoreQuoteRequest;
use App\Http\Requests\Vendor\StoreVendorRequest;
-use App\Import\ImportException;
-use App\Import\Providers\BaseImport;
-use App\Import\Providers\ImportInterface;
+use App\Import\Transformer\Bank\BankTransformer;
use App\Import\Transformer\Csv\ClientTransformer;
use App\Import\Transformer\Csv\ExpenseTransformer;
use App\Import\Transformer\Csv\InvoiceTransformer;
@@ -37,7 +35,6 @@ use App\Import\Transformer\Csv\PaymentTransformer;
use App\Import\Transformer\Csv\ProductTransformer;
use App\Import\Transformer\Csv\QuoteTransformer;
use App\Import\Transformer\Csv\VendorTransformer;
-use App\Import\Transformer\Bank\BankTransformer;
use App\Repositories\BankTransactionRepository;
use App\Repositories\ClientRepository;
use App\Repositories\ExpenseRepository;
@@ -48,8 +45,6 @@ use App\Repositories\QuoteRepository;
use App\Repositories\VendorRepository;
use App\Services\Bank\BankMatchingService;
use App\Utils\Traits\MakesHash;
-use Illuminate\Support\Facades\Validator;
-use Symfony\Component\HttpFoundation\ParameterBag;
class Csv extends BaseImport implements ImportInterface
{
@@ -81,16 +76,12 @@ class Csv extends BaseImport implements ImportInterface
$data = $this->getCsvData($entity_type);
- if (is_array($data))
- {
-
+ if (is_array($data)) {
$data = $this->preTransformCsv($data, $entity_type);
- foreach($data as $key => $value)
- {
+ foreach ($data as $key => $value) {
$data[$key]['transaction.bank_integration_id'] = $this->decodePrimaryKey($this->request['bank_integration_id']);
}
-
}
if (empty($data)) {
@@ -111,7 +102,6 @@ class Csv extends BaseImport implements ImportInterface
nlog("bank matching co id = {$this->company->id}");
(new BankMatchingService($this->company->id, $this->company->db))->handle();
-
}
public function client()
diff --git a/app/Import/Providers/Freshbooks.php b/app/Import/Providers/Freshbooks.php
index e3d02b621652..d6df4a9b2b07 100644
--- a/app/Import/Providers/Freshbooks.php
+++ b/app/Import/Providers/Freshbooks.php
@@ -73,7 +73,6 @@ class Freshbooks extends BaseImport
public function invoice()
{
-
//make sure we update and create products with wave
$initial_update_products_value = $this->company->update_products;
$this->company->update_products = true;
diff --git a/app/Import/Providers/Invoice2Go.php b/app/Import/Providers/Invoice2Go.php
index 0d56666f5139..48a656a7cbcc 100644
--- a/app/Import/Providers/Invoice2Go.php
+++ b/app/Import/Providers/Invoice2Go.php
@@ -11,12 +11,9 @@
namespace App\Import\Providers;
-use App\Factory\ClientFactory;
use App\Factory\InvoiceFactory;
-use App\Http\Requests\Client\StoreClientRequest;
use App\Http\Requests\Invoice\StoreInvoiceRequest;
use App\Import\Transformer\Invoice2Go\InvoiceTransformer;
-use App\Repositories\ClientRepository;
use App\Repositories\InvoiceRepository;
class Invoice2Go extends BaseImport
@@ -45,7 +42,6 @@ class Invoice2Go extends BaseImport
public function invoice()
{
-
//make sure we update and create products with wave
$initial_update_products_value = $this->company->update_products;
$this->company->update_products = true;
diff --git a/app/Import/Providers/Invoicely.php b/app/Import/Providers/Invoicely.php
index bec43bb35623..b92ea01732be 100644
--- a/app/Import/Providers/Invoicely.php
+++ b/app/Import/Providers/Invoicely.php
@@ -72,7 +72,6 @@ class Invoicely extends BaseImport
public function invoice()
{
-
//make sure we update and create products with wave
$initial_update_products_value = $this->company->update_products;
$this->company->update_products = true;
diff --git a/app/Import/Providers/Wave.php b/app/Import/Providers/Wave.php
index 1794304d1131..9543c704a2e9 100644
--- a/app/Import/Providers/Wave.php
+++ b/app/Import/Providers/Wave.php
@@ -85,13 +85,11 @@ class Wave extends BaseImport implements ImportInterface
public function product()
{
-
//done automatically inside the invoice() method as we need to harvest the products from the line items
}
public function invoice()
{
-
//make sure we update and create products with wave
$initial_update_products_value = $this->company->update_products;
$this->company->update_products = true;
@@ -170,7 +168,7 @@ class Wave extends BaseImport implements ImportInterface
$data = $this->getCsvData($entity_type);
- if(!$data){
+ if (!$data) {
$this->entity_count['expense'] = 0;
return;
}
@@ -279,6 +277,5 @@ class Wave extends BaseImport implements ImportInterface
}
return $count;
-
}
}
diff --git a/app/Import/Providers/Zoho.php b/app/Import/Providers/Zoho.php
index 9c245471a789..38a2e829b959 100644
--- a/app/Import/Providers/Zoho.php
+++ b/app/Import/Providers/Zoho.php
@@ -74,7 +74,6 @@ class Zoho extends BaseImport
public function invoice()
{
-
//make sure we update and create products with wave
$initial_update_products_value = $this->company->update_products;
$this->company->update_products = true;
diff --git a/app/Import/Transformer/Bank/BankTransformer.php b/app/Import/Transformer/Bank/BankTransformer.php
index 648967063dd4..bff66a30e895 100644
--- a/app/Import/Transformer/Bank/BankTransformer.php
+++ b/app/Import/Transformer/Bank/BankTransformer.php
@@ -11,10 +11,7 @@
namespace App\Import\Transformer\Bank;
-use App\Import\ImportException;
use App\Import\Transformer\BaseTransformer;
-use App\Models\BankTransaction;
-use App\Utils\Number;
/**
* Class BankTransformer.
@@ -28,11 +25,11 @@ class BankTransformer extends BaseTransformer
*/
public function transform($transaction)
{
- $now = now();
+ $now = now();
- $transformed = [
+ $transformed = [
'bank_integration_id' => $transaction['transaction.bank_integration_id'],
- 'transaction_id' => $this->getNumber($transaction,'transaction.transaction_id'),
+ 'transaction_id' => $this->getNumber($transaction, 'transaction.transaction_id'),
'amount' => abs($this->getFloat($transaction, 'transaction.amount')),
'currency_id' => $this->getCurrencyByCode($transaction, 'transaction.currency'),
'account_type' => strlen($this->getString($transaction, 'transaction.account_type')) > 1 ? $this->getString($transaction, 'transaction.account_type') : 'bank',
@@ -55,27 +52,30 @@ class BankTransformer extends BaseTransformer
private function calculateType($transaction)
{
+ if (array_key_exists('transaction.base_type', $transaction) && (($transaction['transaction.base_type'] == 'CREDIT') || strtolower($transaction['transaction.base_type']) == 'deposit')) {
+ return 'CREDIT';
+ }
- if(array_key_exists('transaction.base_type', $transaction) && (($transaction['transaction.base_type'] == 'CREDIT') || strtolower($transaction['transaction.base_type']) == 'deposit'))
- return 'CREDIT';
+ if (array_key_exists('transaction.base_type', $transaction) && (($transaction['transaction.base_type'] == 'DEBIT') || strtolower($transaction['transaction.base_type']) == 'withdrawal')) {
+ return 'DEBIT';
+ }
- if(array_key_exists('transaction.base_type', $transaction) && (($transaction['transaction.base_type'] == 'DEBIT') || strtolower($transaction['transaction.base_type']) == 'withdrawal'))
- return 'DEBIT';
+ if (array_key_exists('transaction.category_id', $transaction)) {
+ return 'DEBIT';
+ }
- if(array_key_exists('transaction.category_id', $transaction))
- return 'DEBIT';
+ if (array_key_exists('transaction.category_type', $transaction) && $transaction['transaction.category_type'] == 'Income') {
+ return 'CREDIT';
+ }
- if(array_key_exists('transaction.category_type', $transaction) && $transaction['transaction.category_type'] == 'Income')
- return 'CREDIT';
+ if (array_key_exists('transaction.category_type', $transaction)) {
+ return 'DEBIT';
+ }
- if(array_key_exists('transaction.category_type', $transaction))
- return 'DEBIT';
-
- if(array_key_exists('transaction.amount', $transaction) && is_numeric($transaction['transaction.amount']) && $transaction['transaction.amount'] > 0)
- return 'CREDIT';
-
- return 'DEBIT';
+ if (array_key_exists('transaction.amount', $transaction) && is_numeric($transaction['transaction.amount']) && $transaction['transaction.amount'] > 0) {
+ return 'CREDIT';
+ }
+ return 'DEBIT';
}
-
-}
\ No newline at end of file
+}
diff --git a/app/Import/Transformer/BaseTransformer.php b/app/Import/Transformer/BaseTransformer.php
index 437486b72dcf..989f821145ec 100644
--- a/app/Import/Transformer/BaseTransformer.php
+++ b/app/Import/Transformer/BaseTransformer.php
@@ -14,21 +14,19 @@ namespace App\Import\Transformer;
use App\Factory\ExpenseCategoryFactory;
use App\Factory\ProjectFactory;
use App\Factory\VendorFactory;
+use App\Models\Client;
use App\Models\ClientContact;
use App\Models\Country;
-use App\Models\ExpenseCategory;
-use App\Models\PaymentType;
-use App\Models\User;
use App\Models\Expense;
-use App\Models\Project;
+use App\Models\ExpenseCategory;
use App\Models\Invoice;
-use App\Models\Quote;
-use App\Models\Client;
-use App\Models\TaxRate;
+use App\Models\PaymentType;
use App\Models\Product;
+use App\Models\Project;
+use App\Models\Quote;
+use App\Models\TaxRate;
use App\Models\Vendor;
use App\Utils\Number;
-use Exception;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
@@ -46,26 +44,19 @@ class BaseTransformer
public function parseDate($date)
{
-
- try{
-
+ try {
$parsed_date = Carbon::parse($date);
return $parsed_date->format('Y-m-d');
-
- }
- catch(\Exception $e){
-
+ } catch(\Exception $e) {
$parsed_date = date('Y-m-d', strtotime($date));
- if($parsed_date == '1970-01-01')
+ if ($parsed_date == '1970-01-01') {
return now()->format('Y-m-d');
+ }
return $parsed_date;
-
}
-
-
}
public function getInvoiceTypeId($data, $field)
@@ -107,7 +98,6 @@ class BaseTransformer
public function getClient($client_name, $client_email)
{
-
if (! empty($client_name)) {
$client_id_search = Client::where('company_id', $this->company->id)
->where('is_deleted', false)
diff --git a/app/Import/Transformer/Csv/ExpenseTransformer.php b/app/Import/Transformer/Csv/ExpenseTransformer.php
index 5bca96630429..2aee2e7dda45 100644
--- a/app/Import/Transformer/Csv/ExpenseTransformer.php
+++ b/app/Import/Transformer/Csv/ExpenseTransformer.php
@@ -42,7 +42,7 @@ class ExpenseTransformer extends BaseTransformer
'client_id' => isset($data['expense.client'])
? $this->getClientId($data['expense.client'])
: null,
- 'date' => strlen($this->getString($data, 'expense.date') > 1) ? date('Y-m-d', strtotime(str_replace("/","-",$data['expense.date']))) : now()->format('Y-m-d'),
+ 'date' => strlen($this->getString($data, 'expense.date') > 1) ? date('Y-m-d', strtotime(str_replace("/", "-", $data['expense.date']))) : now()->format('Y-m-d'),
'public_notes' => $this->getString($data, 'expense.public_notes'),
'private_notes' => $this->getString($data, 'expense.private_notes'),
'category_id' => isset($data['expense.category'])
@@ -55,7 +55,7 @@ class ExpenseTransformer extends BaseTransformer
? $this->getPaymentTypeId($data['expense.payment_type'])
: null,
'payment_date' => isset($data['expense.payment_date'])
- ? date('Y-m-d', strtotime(str_replace("/","-",$data['expense.payment_date'])))
+ ? date('Y-m-d', strtotime(str_replace("/", "-", $data['expense.payment_date'])))
: null,
'custom_value1' => $this->getString($data, 'expense.custom_value1'),
'custom_value2' => $this->getString($data, 'expense.custom_value2'),
diff --git a/app/Import/Transformer/Csv/InvoiceTransformer.php b/app/Import/Transformer/Csv/InvoiceTransformer.php
index 07da5f3b4879..76447deb7f71 100644
--- a/app/Import/Transformer/Csv/InvoiceTransformer.php
+++ b/app/Import/Transformer/Csv/InvoiceTransformer.php
@@ -13,7 +13,6 @@ namespace App\Import\Transformer\Csv;
use App\Import\ImportException;
use App\Import\Transformer\BaseTransformer;
-use App\Import\Transformer\Csv\ClientTransformer;
use App\Models\Invoice;
/**
@@ -222,7 +221,7 @@ class InvoiceTransformer extends BaseTransformer
$record,
'item.custom_value4'
),
- 'type_id' => $this->getInvoiceTypeId( $record, 'item.type_id' ),
+ 'type_id' => $this->getInvoiceTypeId($record, 'item.type_id'),
];
}
diff --git a/app/Import/Transformer/Csv/QuoteTransformer.php b/app/Import/Transformer/Csv/QuoteTransformer.php
index 8c1add9da979..dab125073a1f 100644
--- a/app/Import/Transformer/Csv/QuoteTransformer.php
+++ b/app/Import/Transformer/Csv/QuoteTransformer.php
@@ -13,7 +13,6 @@ namespace App\Import\Transformer\Csv;
use App\Import\ImportException;
use App\Import\Transformer\BaseTransformer;
-use App\Import\Transformer\Csv\ClientTransformer;
use App\Models\Quote;
/**
@@ -57,10 +56,10 @@ class QuoteTransformer extends BaseTransformer
'discount' => $this->getFloat($quote_data, 'quote.discount'),
'po_number' => $this->getString($quote_data, 'quote.po_number'),
'date' => isset($quote_data['quote.date'])
- ? date('Y-m-d', strtotime(str_replace("/","-",$quote_data['quote.date'])))
+ ? date('Y-m-d', strtotime(str_replace("/", "-", $quote_data['quote.date'])))
: now()->format('Y-m-d'),
'due_date' => isset($quote_data['quote.due_date'])
- ? date('Y-m-d', strtotime(str_replace("/","-",$quote_data['quote.due_date'])))
+ ? date('Y-m-d', strtotime(str_replace("/", "-", $quote_data['quote.due_date'])))
: null,
'terms' => $this->getString($quote_data, 'quote.terms'),
'public_notes' => $this->getString(
diff --git a/app/Import/Transformer/Freshbooks/InvoiceTransformer.php b/app/Import/Transformer/Freshbooks/InvoiceTransformer.php
index 316779875761..e072206e9c2f 100644
--- a/app/Import/Transformer/Freshbooks/InvoiceTransformer.php
+++ b/app/Import/Transformer/Freshbooks/InvoiceTransformer.php
@@ -14,7 +14,6 @@ namespace App\Import\Transformer\Freshbooks;
use App\Import\ImportException;
use App\Import\Transformer\BaseTransformer;
use App\Models\Invoice;
-use App\Utils\Number;
/**
* Class InvoiceTransformer.
@@ -82,8 +81,9 @@ class InvoiceTransformer extends BaseTransformer
//Line Subtotal
public function calcTaxRate($record, $field)
{
- if(isset($record['Line Subtotal']) && $record['Line Subtotal'] > 0)
+ if (isset($record['Line Subtotal']) && $record['Line Subtotal'] > 0) {
return ($record[$field] / $record['Line Subtotal']) * 100;
+ }
$tax_amount1 = isset($record['Tax 1 Amount']) ? $record['Tax 1 Amount'] : 0;
@@ -93,11 +93,11 @@ class InvoiceTransformer extends BaseTransformer
$subtotal = $line_total - $tax_amount2 - $tax_amount1;
- if($subtotal > 0)
+ if ($subtotal > 0) {
return $record[$field] / $subtotal * 100;
+ }
return 0;
-
}
/** @return float */
diff --git a/app/Import/Transformer/Invoice2Go/InvoiceTransformer.php b/app/Import/Transformer/Invoice2Go/InvoiceTransformer.php
index f5b18674cd95..b7b35926a44e 100644
--- a/app/Import/Transformer/Invoice2Go/InvoiceTransformer.php
+++ b/app/Import/Transformer/Invoice2Go/InvoiceTransformer.php
@@ -28,7 +28,6 @@ class InvoiceTransformer extends BaseTransformer
*/
public function transform($invoice_data)
{
-
if (!isset($invoice_data['DocumentNumber'])) {
throw new ImportException('DocumentNumber key not found in this import file.');
}
diff --git a/app/Import/Transformer/Wave/ExpenseTransformer.php b/app/Import/Transformer/Wave/ExpenseTransformer.php
index db7a3e2671fc..497d214bc6d6 100644
--- a/app/Import/Transformer/Wave/ExpenseTransformer.php
+++ b/app/Import/Transformer/Wave/ExpenseTransformer.php
@@ -11,7 +11,6 @@
namespace App\Import\Transformer\Wave;
-use App\Import\ImportException;
use App\Import\Transformer\BaseTransformer;
/**
diff --git a/app/Import/Transformer/Zoho/InvoiceTransformer.php b/app/Import/Transformer/Zoho/InvoiceTransformer.php
index 90f7f28c7bd5..56f26bd3c75a 100644
--- a/app/Import/Transformer/Zoho/InvoiceTransformer.php
+++ b/app/Import/Transformer/Zoho/InvoiceTransformer.php
@@ -58,7 +58,6 @@ class InvoiceTransformer extends BaseTransformer
$line_items = [];
foreach ($line_items_data as $record) {
-
$item_notes_key = array_key_exists('Item Description', $record) ? 'Item Description' : 'Item Desc';
$line_items[] = [
diff --git a/app/Jobs/Account/CreateAccount.php b/app/Jobs/Account/CreateAccount.php
index c416b1eb798e..756c744e3765 100644
--- a/app/Jobs/Account/CreateAccount.php
+++ b/app/Jobs/Account/CreateAccount.php
@@ -18,25 +18,16 @@ use App\Jobs\Company\CreateCompany;
use App\Jobs\Company\CreateCompanyPaymentTerms;
use App\Jobs\Company\CreateCompanyTaskStatuses;
use App\Jobs\Company\CreateCompanyToken;
-use App\Jobs\Mail\NinjaMailer;
use App\Jobs\Mail\NinjaMailerJob;
use App\Jobs\Mail\NinjaMailerObject;
use App\Jobs\User\CreateUser;
use App\Jobs\Util\VersionCheck;
-use App\Mail\Admin\AccountCreatedObject;
-use App\Mail\Admin\VerifyUserObject;
use App\Models\Account;
-use App\Models\Timezone;
-use App\Notifications\Ninja\NewAccountCreated;
use App\Utils\Ninja;
use App\Utils\Traits\User\LoginCache;
use Illuminate\Foundation\Bus\Dispatchable;
-use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
-use Illuminate\Support\Facades\Auth;
-use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;
-use Symfony\Component\HttpFoundation\Response;
use Turbo124\Beacon\Facades\LightLogs;
class CreateAccount
@@ -86,7 +77,7 @@ class CreateAccount
$sp794f3f->hosted_company_count = config('ninja.quotas.free.max_companies');
$sp794f3f->account_sms_verified = true;
- if(in_array($this->getDomain($this->request['email']), ['givmail.com','yopmail.com','gmail.com', 'hotmail.com', 'outlook.com', 'yahoo.com', 'aol.com', 'mail.ru','brand-app.biz','proton.me','ema-sofia.eu'])){
+ if (in_array($this->getDomain($this->request['email']), ['givmail.com','yopmail.com','gmail.com', 'hotmail.com', 'outlook.com', 'yahoo.com', 'aol.com', 'mail.ru','brand-app.biz','proton.me','ema-sofia.eu'])) {
$sp794f3f->account_sms_verified = false;
}
@@ -96,7 +87,7 @@ class CreateAccount
$sp794f3f->save();
- $sp035a66 = (new CreateCompany($this->request,$sp794f3f))->handle();
+ $sp035a66 = (new CreateCompany($this->request, $sp794f3f))->handle();
$sp035a66->load('account');
$sp794f3f->default_company_id = $sp035a66->id;
$sp794f3f->save();
@@ -164,7 +155,7 @@ class CreateAccount
private function getDomain($email)
{
- if( filter_var( $email, FILTER_VALIDATE_EMAIL ) ) {
+ if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
// split on @ and return last value of array (the domain)
$domain = explode('@', $email);
@@ -175,5 +166,4 @@ class CreateAccount
return 'gmail.com';
}
-
}
diff --git a/app/Jobs/Bank/MatchBankTransactions.php b/app/Jobs/Bank/MatchBankTransactions.php
index 708206c15a3f..42a03df4925c 100644
--- a/app/Jobs/Bank/MatchBankTransactions.php
+++ b/app/Jobs/Bank/MatchBankTransactions.php
@@ -19,15 +19,12 @@ use App\Factory\PaymentFactory;
use App\Helpers\Bank\Yodlee\Yodlee;
use App\Libraries\Currency\Conversion\CurrencyApi;
use App\Libraries\MultiDB;
-use App\Models\BankIntegration;
use App\Models\BankTransaction;
use App\Models\Company;
-use App\Models\Currency;
use App\Models\Expense;
use App\Models\ExpenseCategory;
use App\Models\Invoice;
use App\Models\Payment;
-use App\Services\Bank\BankMatchingService;
use App\Utils\Ninja;
use App\Utils\Traits\GeneratesCounter;
use App\Utils\Traits\MakesHash;
@@ -71,13 +68,11 @@ class MatchBankTransactions implements ShouldQueue
*/
public function __construct(int $company_id, string $db, array $input)
{
-
$this->company_id = $company_id;
$this->db = $db;
$this->input = $input['transactions'];
$this->categories = collect();
$this->bts = collect();
-
}
/**
@@ -88,43 +83,41 @@ class MatchBankTransactions implements ShouldQueue
*/
public function handle()
{
-
MultiDB::setDb($this->db);
$this->company = Company::find($this->company_id);
- if($this->company->account->bank_integration_account_id)
+ if ($this->company->account->bank_integration_account_id) {
$yodlee = new Yodlee($this->company->account->bank_integration_account_id);
- else
+ } else {
$yodlee = false;
+ }
$bank_categories = Cache::get('bank_categories');
- if(!$bank_categories && $yodlee){
+ if (!$bank_categories && $yodlee) {
$_categories = $yodlee->getTransactionCategories();
$this->categories = collect($_categories->transactionCategory);
Cache::forever('bank_categories', $this->categories);
- }
- else {
+ } else {
$this->categories = collect($bank_categories);
}
- foreach($this->input as $input)
- {
+ foreach ($this->input as $input) {
nlog($input);
- if(array_key_exists('invoice_ids', $input) && strlen($input['invoice_ids']) >= 1)
+ if (array_key_exists('invoice_ids', $input) && strlen($input['invoice_ids']) >= 1) {
$this->matchInvoicePayment($input);
- elseif(array_key_exists('payment_id', $input) && strlen($input['payment_id']) >= 1)
+ } elseif (array_key_exists('payment_id', $input) && strlen($input['payment_id']) >= 1) {
$this->linkPayment($input);
- elseif(array_key_exists('expense_id', $input) && strlen($input['expense_id']) >= 1)
+ } elseif (array_key_exists('expense_id', $input) && strlen($input['expense_id']) >= 1) {
$this->linkExpense($input);
- elseif((array_key_exists('vendor_id', $input) && strlen($input['vendor_id']) >= 1) || (array_key_exists('ninja_category_id', $input) && strlen($input['ninja_category_id']) >= 1))
+ } elseif ((array_key_exists('vendor_id', $input) && strlen($input['vendor_id']) >= 1) || (array_key_exists('ninja_category_id', $input) && strlen($input['ninja_category_id']) >= 1)) {
$this->matchExpense($input);
+ }
}
return BankTransaction::whereIn('id', $this->bts);
-
}
private function getInvoices(string $invoice_hashed_ids)
@@ -133,15 +126,12 @@ class MatchBankTransactions implements ShouldQueue
$invoices = explode(",", $invoice_hashed_ids);
- if(count($invoices) >= 1)
- {
-
- foreach($invoices as $invoice){
-
- if(is_string($invoice) && strlen($invoice) > 1)
+ if (count($invoices) >= 1) {
+ foreach ($invoices as $invoice) {
+ if (is_string($invoice) && strlen($invoice) > 1) {
$collection->push($this->decodePrimaryKey($invoice));
+ }
}
-
}
return $collection;
@@ -149,32 +139,28 @@ class MatchBankTransactions implements ShouldQueue
private function checkPayable($invoices) :bool
{
-
- foreach($invoices as $invoice){
-
+ foreach ($invoices as $invoice) {
$invoice->service()->markSent();
- if(!$invoice->isPayable())
+ if (!$invoice->isPayable()) {
return false;
-
+ }
}
return true;
-
}
private function linkExpense($input)
{
-
$this->bt = BankTransaction::find($input['id']);
- if(!$this->bt || $this->bt->status_id == BankTransaction::STATUS_CONVERTED)
+ if (!$this->bt || $this->bt->status_id == BankTransaction::STATUS_CONVERTED) {
return $this;
+ }
$expense = Expense::withTrashed()->find($input['expense_id']);
- if($expense && !$expense->transaction_id) {
-
+ if ($expense && !$expense->transaction_id) {
$expense->transaction_id = $this->bt->id;
$expense->save();
@@ -185,25 +171,22 @@ class MatchBankTransactions implements ShouldQueue
$this->bt->save();
$this->bts->push($this->bt->id);
-
}
return $this;
-
}
private function linkPayment($input)
{
-
$this->bt = BankTransaction::find($input['id']);
- if(!$this->bt || $this->bt->status_id == BankTransaction::STATUS_CONVERTED)
+ if (!$this->bt || $this->bt->status_id == BankTransaction::STATUS_CONVERTED) {
return $this;
+ }
$payment = Payment::withTrashed()->find($input['payment_id']);
- if($payment && !$payment->transaction_id) {
-
+ if ($payment && !$payment->transaction_id) {
$payment->transaction_id = $this->bt->id;
$payment->save();
@@ -219,34 +202,34 @@ class MatchBankTransactions implements ShouldQueue
}
private function matchInvoicePayment($input) :self
- {
+ {
$this->bt = BankTransaction::find($input['id']);
- if(!$this->bt || $this->bt->status_id == BankTransaction::STATUS_CONVERTED)
- return $this;
+ if (!$this->bt || $this->bt->status_id == BankTransaction::STATUS_CONVERTED) {
+ return $this;
+ }
$_invoices = Invoice::withTrashed()->find($this->getInvoices($input['invoice_ids']));
$amount = $this->bt->amount;
- if($_invoices && $this->checkPayable($_invoices)){
-
+ if ($_invoices && $this->checkPayable($_invoices)) {
$this->createPayment($_invoices, $amount);
$this->bts->push($this->bt->id);
-
}
return $this;
}
private function matchExpense($input) :self
- {
+ {
//if there is a category id, pull it from Yodlee and insert - or just reuse!!
$this->bt = BankTransaction::find($input['id']);
- if(!$this->bt || $this->bt->status_id == BankTransaction::STATUS_CONVERTED)
- return $this;
+ if (!$this->bt || $this->bt->status_id == BankTransaction::STATUS_CONVERTED) {
+ return $this;
+ }
$expense = ExpenseFactory::create($this->bt->company_id, $this->bt->user_id);
$expense->category_id = $this->resolveCategory($input);
@@ -258,8 +241,9 @@ class MatchBankTransactions implements ShouldQueue
$expense->transaction_reference = $this->bt->description;
$expense->transaction_id = $this->bt->id;
- if(array_key_exists('vendor_id', $input))
+ if (array_key_exists('vendor_id', $input)) {
$expense->vendor_id = $input['vendor_id'];
+ }
$expense->invoice_documents = $this->company->invoice_expense_documents;
$expense->should_be_invoiced = $this->company->mark_expenses_invoiceable;
@@ -267,8 +251,9 @@ class MatchBankTransactions implements ShouldQueue
$this->bt->expense_id = $expense->id;
- if(array_key_exists('vendor_id', $input))
+ if (array_key_exists('vendor_id', $input)) {
$this->bt->vendor_id = $input['vendor_id'];
+ }
$this->bt->status_id = BankTransaction::STATUS_CONVERTED;
$this->bt->save();
@@ -282,47 +267,39 @@ class MatchBankTransactions implements ShouldQueue
{
$this->available_balance = $amount;
- \DB::connection(config('database.default'))->transaction(function () use($invoices) {
-
- $invoices->each(function ($invoice) use ($invoices){
-
+ \DB::connection(config('database.default'))->transaction(function () use ($invoices) {
+ $invoices->each(function ($invoice) use ($invoices) {
$this->invoice = Invoice::withTrashed()->where('id', $invoice->id)->lockForUpdate()->first();
- $_amount = false;
+ $_amount = false;
- if(floatval($this->invoice->balance) < floatval($this->available_balance) && $this->available_balance > 0)
- {
- $_amount = $this->invoice->balance;
- $this->applied_amount += $this->invoice->balance;
- $this->available_balance = $this->available_balance - $this->invoice->balance;
- }
- elseif(floatval($this->invoice->balance) >= floatval($this->available_balance) && $this->available_balance > 0)
- {
- $_amount = $this->available_balance;
- $this->applied_amount += $this->available_balance;
- $this->available_balance = 0;
- }
+ if (floatval($this->invoice->balance) < floatval($this->available_balance) && $this->available_balance > 0) {
+ $_amount = $this->invoice->balance;
+ $this->applied_amount += $this->invoice->balance;
+ $this->available_balance = $this->available_balance - $this->invoice->balance;
+ } elseif (floatval($this->invoice->balance) >= floatval($this->available_balance) && $this->available_balance > 0) {
+ $_amount = $this->available_balance;
+ $this->applied_amount += $this->available_balance;
+ $this->available_balance = 0;
+ }
- if($_amount)
- {
-
- $this->attachable_invoices[] = ['id' => $this->invoice->id, 'amount' => $_amount];
-
- $this->invoice
- ->service()
- ->setExchangeRate()
- ->updateBalance($_amount * -1)
- ->updatePaidToDate($_amount)
- ->setCalculatedStatus()
- ->save();
- }
-
- });
+ if ($_amount) {
+ $this->attachable_invoices[] = ['id' => $this->invoice->id, 'amount' => $_amount];
+ $this->invoice
+ ->service()
+ ->setExchangeRate()
+ ->updateBalance($_amount * -1)
+ ->updatePaidToDate($_amount)
+ ->setCalculatedStatus()
+ ->save();
+ }
+ });
}, 2);
- if(!$this->invoice)
+ if (!$this->invoice) {
return;
+ }
/* Create Payment */
$payment = PaymentFactory::create($this->invoice->company_id, $this->invoice->user_id);
@@ -345,19 +322,17 @@ class MatchBankTransactions implements ShouldQueue
$payment->service()->applyNumber()->save();
- if($payment->client->getSetting('send_email_on_mark_paid'))
+ if ($payment->client->getSetting('send_email_on_mark_paid')) {
$payment->service()->sendEmail();
+ }
$this->setExchangeRate($payment);
/* Create a payment relationship to the invoice entity */
- foreach($this->attachable_invoices as $attachable_invoice)
- {
-
+ foreach ($this->attachable_invoices as $attachable_invoice) {
$payment->invoices()->attach($attachable_invoice['id'], [
'amount' => $attachable_invoice['amount'],
]);
-
}
event('eloquent.created: App\Models\Payment', $payment);
@@ -396,7 +371,7 @@ class MatchBankTransactions implements ShouldQueue
private function resolveCategory($input) :?int
{
- if(array_key_exists('ninja_category_id', $input) && (int)$input['ninja_category_id'] > 1){
+ if (array_key_exists('ninja_category_id', $input) && (int)$input['ninja_category_id'] > 1) {
$this->bt->ninja_category_id = $input['ninja_category_id'];
$this->bt->save();
@@ -407,11 +382,11 @@ class MatchBankTransactions implements ShouldQueue
$ec = ExpenseCategory::where('company_id', $this->bt->company_id)->where('bank_category_id', $this->bt->category_id)->first();
- if($ec)
+ if ($ec) {
return $ec->id;
+ }
- if($category)
- {
+ if ($category) {
$ec = ExpenseCategoryFactory::create($this->bt->company_id, $this->bt->user_id);
$ec->bank_category_id = $this->bt->category_id;
$ec->name = $category->highLevelCategoryName;
@@ -447,9 +422,4 @@ class MatchBankTransactions implements ShouldQueue
{
return [new WithoutOverlapping($this->company_id)];
}
-
-
-
-
-
-}
\ No newline at end of file
+}
diff --git a/app/Jobs/Bank/ProcessBankTransactions.php b/app/Jobs/Bank/ProcessBankTransactions.php
index 74d996f0fd14..bb49547f4b3c 100644
--- a/app/Jobs/Bank/ProcessBankTransactions.php
+++ b/app/Jobs/Bank/ProcessBankTransactions.php
@@ -22,7 +22,6 @@ use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
-use Illuminate\Support\Carbon;
class ProcessBankTransactions implements ShouldQueue
{
@@ -49,7 +48,6 @@ class ProcessBankTransactions implements ShouldQueue
$this->bank_integration = $bank_integration;
$this->from_date = $bank_integration->from_date;
$this->company = $this->bank_integration->company;
-
}
/**
@@ -60,41 +58,33 @@ class ProcessBankTransactions implements ShouldQueue
*/
public function handle()
{
-
set_time_limit(0);
//Loop through everything until we are up to date
$this->from_date = $this->from_date ?: '2021-01-01';
- do{
-
+ do {
try {
$this->processTransactions();
- }
- catch(\Exception $e) {
+ } catch(\Exception $e) {
nlog("{$this->bank_integration_account_id} - exited abnormally => ". $e->getMessage());
return;
}
-
- }
- while($this->stop_loop);
+ } while ($this->stop_loop);
BankMatchingService::dispatch($this->company->id, $this->company->db);
-
}
private function processTransactions()
{
-
$yodlee = new Yodlee($this->bank_integration_account_id);
- if(!$yodlee->getAccount($this->bank_integration->bank_account_id))
- {
- $this->bank_integration->disabled_upstream = true;
- $this->bank_integration->save();
- $this->stop_loop = false;
- return;
+ if (!$yodlee->getAccount($this->bank_integration->bank_account_id)) {
+ $this->bank_integration->disabled_upstream = true;
+ $this->bank_integration->save();
+ $this->stop_loop = false;
+ return;
}
$data = [
@@ -111,11 +101,10 @@ class ProcessBankTransactions implements ShouldQueue
$count = $transaction_count->transaction->TOTAL->count;
//get transactions array
- $transactions = $yodlee->getTransactions($data);
+ $transactions = $yodlee->getTransactions($data);
//if no transactions, update the from_date and move on
- if(count($transactions) == 0){
-
+ if (count($transactions) == 0) {
$this->bank_integration->from_date = now()->subDays(2);
$this->bank_integration->disabled_upstream = false;
$this->bank_integration->save();
@@ -135,15 +124,14 @@ class ProcessBankTransactions implements ShouldQueue
$now = now();
- foreach($transactions as $transaction)
- {
-
- if(BankTransaction::where('transaction_id', $transaction['transaction_id'])->where('company_id', $this->company->id)->withTrashed()->exists())
+ foreach ($transactions as $transaction) {
+ if (BankTransaction::where('transaction_id', $transaction['transaction_id'])->where('company_id', $this->company->id)->withTrashed()->exists()) {
continue;
+ }
//this should be much faster to insert than using ::create()
$bt = \DB::table('bank_transactions')->insert(
- array_merge($transaction,[
+ array_merge($transaction, [
'company_id' => $this->company->id,
'user_id' => $user_id,
'bank_integration_id' => $this->bank_integration->id,
@@ -151,19 +139,15 @@ class ProcessBankTransactions implements ShouldQueue
'updated_at' => $now,
])
);
-
}
$this->skip = $this->skip + 500;
- if($count < 500){
+ if ($count < 500) {
$this->stop_loop = false;
$this->bank_integration->from_date = now()->subDays(2);
$this->bank_integration->save();
-
}
-
}
-
-}
\ No newline at end of file
+}
diff --git a/app/Jobs/Company/CompanyExport.php b/app/Jobs/Company/CompanyExport.php
index 871b396b4b16..574a6b3257de 100644
--- a/app/Jobs/Company/CompanyExport.php
+++ b/app/Jobs/Company/CompanyExport.php
@@ -13,16 +13,13 @@ namespace App\Jobs\Company;
use App\Jobs\Mail\NinjaMailerJob;
use App\Jobs\Mail\NinjaMailerObject;
-use App\Jobs\Util\UnlinkFile;
use App\Libraries\MultiDB;
use App\Mail\DownloadBackup;
-use App\Mail\DownloadInvoices;
use App\Models\Company;
use App\Models\CreditInvitation;
use App\Models\InvoiceInvitation;
use App\Models\PurchaseOrderInvitation;
use App\Models\QuoteInvitation;
-use App\Models\RecurringInvoice;
use App\Models\RecurringInvoiceInvitation;
use App\Models\User;
use App\Models\VendorContact;
@@ -36,8 +33,6 @@ use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Storage;
-use function Amp\call;
-
class CompanyExport implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels, MakesHash;
@@ -71,7 +66,6 @@ class CompanyExport implements ShouldQueue
*/
public function handle()
{
-
MultiDB::setDb($this->company->db);
$this->company = Company::where('company_key', $this->company->company_key)->first();
@@ -81,8 +75,7 @@ class CompanyExport implements ShouldQueue
$this->export_data['app_version'] = config('ninja.app_version');
$this->export_data['storage_url'] = Storage::url('');
- $this->export_data['activities'] = $this->company->all_activities->map(function ($activity){
-
+ $this->export_data['activities'] = $this->company->all_activities->map(function ($activity) {
$activity = $this->transformArrayOfKeys($activity, [
'user_id',
'company_id',
@@ -104,7 +97,6 @@ class CompanyExport implements ShouldQueue
]);
return $activity;
-
})->makeHidden(['id'])->all();
// $this->export_data['backups'] = $this->company->all_activities()->with('backup')->cursor()->map(function ($activity){
@@ -120,149 +112,120 @@ class CompanyExport implements ShouldQueue
// })->all();
- $this->export_data['users'] = $this->company->users()->withTrashed()->cursor()->map(function ($user){
-
+ $this->export_data['users'] = $this->company->users()->withTrashed()->cursor()->map(function ($user) {
$user->account_id = $this->encodePrimaryKey($user->account_id);
// $user->id = $this->encodePrimaryKey($user->id);
return $user->makeVisible(['id']);
-
})->all();
- $this->export_data['client_contacts'] = $this->company->client_contacts->map(function ($client_contact){
-
+ $this->export_data['client_contacts'] = $this->company->client_contacts->map(function ($client_contact) {
$client_contact = $this->transformArrayOfKeys($client_contact, ['company_id', 'user_id', 'client_id']);
- return $client_contact->makeVisible([
- 'password',
- 'remember_token',
- 'user_id',
- 'company_id',
- 'client_id',
- 'google_2fa_secret',
- 'id',
- 'oauth_provider_id',
- 'oauth_user_id',
- 'token',
- 'hashed_id',
- ]);
-
+ return $client_contact->makeVisible([
+ 'password',
+ 'remember_token',
+ 'user_id',
+ 'company_id',
+ 'client_id',
+ 'google_2fa_secret',
+ 'id',
+ 'oauth_provider_id',
+ 'oauth_user_id',
+ 'token',
+ 'hashed_id',
+ ]);
})->all();
- $this->export_data['client_gateway_tokens'] = $this->company->client_gateway_tokens->map(function ($client_gateway_token){
-
+ $this->export_data['client_gateway_tokens'] = $this->company->client_gateway_tokens->map(function ($client_gateway_token) {
$client_gateway_token = $this->transformArrayOfKeys($client_gateway_token, ['company_id', 'client_id', 'company_gateway_id']);
return $client_gateway_token->makeVisible(['id']);
-
})->all();
- $this->export_data['clients'] = $this->company->clients()->orderBy('number', 'DESC')->cursor()->map(function ($client){
-
+ $this->export_data['clients'] = $this->company->clients()->orderBy('number', 'DESC')->cursor()->map(function ($client) {
$client = $this->transformArrayOfKeys($client, ['company_id', 'user_id', 'assigned_user_id', 'group_settings_id']);
return $client->makeVisible(['id','private_notes','user_id','company_id','last_login','hashed_id']);
-
})->all();
$this->export_data['company'] = $this->company->toArray();
$this->export_data['company']['company_key'] = $this->createHash();
- $this->export_data['company_gateways'] = $this->company->company_gateways()->withTrashed()->cursor()->map(function ($company_gateway){
-
+ $this->export_data['company_gateways'] = $this->company->company_gateways()->withTrashed()->cursor()->map(function ($company_gateway) {
$company_gateway = $this->transformArrayOfKeys($company_gateway, ['company_id', 'user_id']);
$company_gateway->config = decrypt($company_gateway->config);
return $company_gateway->makeVisible(['id']);
-
})->all();
- $this->export_data['company_tokens'] = $this->company->tokens->map(function ($token){
-
+ $this->export_data['company_tokens'] = $this->company->tokens->map(function ($token) {
$token = $this->transformArrayOfKeys($token, ['company_id', 'account_id', 'user_id']);
return $token;
-
})->all();
- $this->export_data['company_ledger'] = $this->company->ledger->map(function ($ledger){
-
+ $this->export_data['company_ledger'] = $this->company->ledger->map(function ($ledger) {
$ledger = $this->transformArrayOfKeys($ledger, ['activity_id', 'client_id', 'company_id', 'account_id', 'user_id','company_ledgerable_id']);
return $ledger;
-
})->all();
- $this->export_data['company_users'] = $this->company->company_users()->without(['user','account'])->cursor()->map(function ($company_user){
-
+ $this->export_data['company_users'] = $this->company->company_users()->without(['user','account'])->cursor()->map(function ($company_user) {
$company_user = $this->transformArrayOfKeys($company_user, ['company_id', 'account_id', 'user_id']);
return $company_user;
-
})->all();
- $this->export_data['credits'] = $this->company->credits()->orderBy('number', 'DESC')->cursor()->map(function ($credit){
-
+ $this->export_data['credits'] = $this->company->credits()->orderBy('number', 'DESC')->cursor()->map(function ($credit) {
$credit = $this->transformBasicEntities($credit);
$credit = $this->transformArrayOfKeys($credit, ['recurring_id','client_id', 'vendor_id', 'project_id', 'design_id', 'subscription_id','invoice_id']);
return $credit->makeVisible(['id']);
-
})->all();
- $this->export_data['credit_invitations'] = CreditInvitation::where('company_id', $this->company->id)->withTrashed()->cursor()->map(function ($credit){
-
+ $this->export_data['credit_invitations'] = CreditInvitation::where('company_id', $this->company->id)->withTrashed()->cursor()->map(function ($credit) {
$credit = $this->transformArrayOfKeys($credit, ['company_id', 'user_id', 'client_contact_id', 'credit_id']);
return $credit->makeVisible(['id']);
-
})->all();
$this->export_data['designs'] = $this->company->user_designs->makeHidden(['id'])->all();
- $this->export_data['documents'] = $this->company->all_documents->map(function ($document){
-
+ $this->export_data['documents'] = $this->company->all_documents->map(function ($document) {
$document = $this->transformArrayOfKeys($document, ['user_id', 'assigned_user_id', 'company_id', 'project_id', 'vendor_id','documentable_id']);
$document->hashed_id = $this->encodePrimaryKey($document->id);
return $document->makeVisible(['id']);
-
})->all();
- $this->export_data['expense_categories'] = $this->company->expense_categories->map(function ($expense_category){
-
+ $this->export_data['expense_categories'] = $this->company->expense_categories->map(function ($expense_category) {
$expense_category = $this->transformArrayOfKeys($expense_category, ['user_id', 'company_id']);
return $expense_category->makeVisible(['id']);
-
})->all();
- $this->export_data['expenses'] = $this->company->expenses()->orderBy('number', 'DESC')->cursor()->map(function ($expense){
-
+ $this->export_data['expenses'] = $this->company->expenses()->orderBy('number', 'DESC')->cursor()->map(function ($expense) {
$expense = $this->transformBasicEntities($expense);
$expense = $this->transformArrayOfKeys($expense, ['vendor_id', 'invoice_id', 'client_id', 'category_id', 'recurring_expense_id','project_id']);
return $expense->makeVisible(['id']);
-
})->all();
- $this->export_data['group_settings'] = $this->company->group_settings->map(function ($gs){
-
+ $this->export_data['group_settings'] = $this->company->group_settings->map(function ($gs) {
$gs = $this->transformArrayOfKeys($gs, ['user_id', 'company_id']);
return $gs->makeVisible(['id']);
-
})->all();
- $this->export_data['invoices'] = $this->company->invoices()->orderBy('number', 'DESC')->cursor()->map(function ($invoice){
-
+ $this->export_data['invoices'] = $this->company->invoices()->orderBy('number', 'DESC')->cursor()->map(function ($invoice) {
$invoice = $this->transformBasicEntities($invoice);
$invoice = $this->transformArrayOfKeys($invoice, ['recurring_id','client_id', 'vendor_id', 'project_id', 'design_id', 'subscription_id','project_id']);
@@ -271,103 +234,81 @@ class CompanyExport implements ShouldQueue
'user_id',
'client_id',
'company_id',]);
-
})->all();
- $this->export_data['invoice_invitations'] = InvoiceInvitation::where('company_id', $this->company->id)->withTrashed()->cursor()->map(function ($invoice){
-
+ $this->export_data['invoice_invitations'] = InvoiceInvitation::where('company_id', $this->company->id)->withTrashed()->cursor()->map(function ($invoice) {
$invoice = $this->transformArrayOfKeys($invoice, ['company_id', 'user_id', 'client_contact_id', 'invoice_id']);
return $invoice->makeVisible(['id']);
-
})->all();
- $this->export_data['payment_terms'] = $this->company->user_payment_terms->map(function ($term){
-
+ $this->export_data['payment_terms'] = $this->company->user_payment_terms->map(function ($term) {
$term = $this->transformArrayOfKeys($term, ['user_id', 'company_id']);
return $term;
-
})->makeHidden(['id'])->all();
- $this->export_data['payments'] = $this->company->payments()->orderBy('number', 'DESC')->cursor()->map(function ($payment){
-
+ $this->export_data['payments'] = $this->company->payments()->orderBy('number', 'DESC')->cursor()->map(function ($payment) {
$payment = $this->transformBasicEntities($payment);
$payment = $this->transformArrayOfKeys($payment, ['client_id','project_id', 'vendor_id', 'client_contact_id', 'invitation_id', 'company_gateway_id', 'transaction_id']);
$payment->paymentables = $this->transformPaymentable($payment);
return $payment->makeVisible(['id']);
-
})->all();
- $this->export_data['products'] = $this->company->products->map(function ($product){
-
+ $this->export_data['products'] = $this->company->products->map(function ($product) {
$product = $this->transformBasicEntities($product);
$product = $this->transformArrayOfKeys($product, ['vendor_id','project_id']);
return $product->makeVisible(['id']);
-
})->all();
- $this->export_data['projects'] = $this->company->projects()->orderBy('number', 'DESC')->cursor()->map(function ($project){
-
+ $this->export_data['projects'] = $this->company->projects()->orderBy('number', 'DESC')->cursor()->map(function ($project) {
$project = $this->transformBasicEntities($project);
$project = $this->transformArrayOfKeys($project, ['client_id']);
return $project->makeVisible(['id']);
-
})->all();
- $this->export_data['quotes'] = $this->company->quotes()->orderBy('number', 'DESC')->cursor()->map(function ($quote){
-
+ $this->export_data['quotes'] = $this->company->quotes()->orderBy('number', 'DESC')->cursor()->map(function ($quote) {
$quote = $this->transformBasicEntities($quote);
$quote = $this->transformArrayOfKeys($quote, ['invoice_id','recurring_id','client_id', 'vendor_id', 'project_id', 'design_id', 'subscription_id']);
return $quote->makeVisible(['id']);
-
})->all();
- $this->export_data['quote_invitations'] = QuoteInvitation::where('company_id', $this->company->id)->withTrashed()->cursor()->map(function ($quote){
-
+ $this->export_data['quote_invitations'] = QuoteInvitation::where('company_id', $this->company->id)->withTrashed()->cursor()->map(function ($quote) {
$quote = $this->transformArrayOfKeys($quote, ['company_id', 'user_id', 'client_contact_id', 'quote_id']);
return $quote->makeVisible(['id']);
-
})->all();
- $this->export_data['recurring_expenses'] = $this->company->recurring_expenses()->orderBy('number', 'DESC')->cursor()->map(function ($expense){
-
+ $this->export_data['recurring_expenses'] = $this->company->recurring_expenses()->orderBy('number', 'DESC')->cursor()->map(function ($expense) {
$expense = $this->transformBasicEntities($expense);
$expense = $this->transformArrayOfKeys($expense, ['vendor_id', 'invoice_id', 'client_id', 'category_id', 'project_id']);
return $expense->makeVisible(['id']);
-
})->all();
- $this->export_data['recurring_invoices'] = $this->company->recurring_invoices()->orderBy('number', 'DESC')->cursor()->map(function ($ri){
-
+ $this->export_data['recurring_invoices'] = $this->company->recurring_invoices()->orderBy('number', 'DESC')->cursor()->map(function ($ri) {
$ri = $this->transformBasicEntities($ri);
$ri = $this->transformArrayOfKeys($ri, ['client_id', 'vendor_id', 'project_id', 'design_id', 'subscription_id']);
return $ri->makeVisible(['id']);
-
})->all();
- $this->export_data['recurring_invoice_invitations'] = RecurringInvoiceInvitation::where('company_id', $this->company->id)->withTrashed()->cursor()->map(function ($ri){
-
+ $this->export_data['recurring_invoice_invitations'] = RecurringInvoiceInvitation::where('company_id', $this->company->id)->withTrashed()->cursor()->map(function ($ri) {
$ri = $this->transformArrayOfKeys($ri, ['company_id', 'user_id', 'client_contact_id', 'recurring_invoice_id']);
return $ri;
-
})->all();
- $this->export_data['subscriptions'] = $this->company->subscriptions->map(function ($subscription){
-
+ $this->export_data['subscriptions'] = $this->company->subscriptions->map(function ($subscription) {
$subscription = $this->transformBasicEntities($subscription);
$subscription->group_id = $this->encodePrimaryKey($subscription->group_id);
@@ -378,74 +319,58 @@ class CompanyExport implements ShouldQueue
'product_ids',
'recurring_product_ids',
'group_id']);
-
})->all();
- $this->export_data['system_logs'] = $this->company->system_logs->map(function ($log){
-
+ $this->export_data['system_logs'] = $this->company->system_logs->map(function ($log) {
$log->client_id = $this->encodePrimaryKey($log->client_id);
$log->company_id = $this->encodePrimaryKey($log->company_id);
return $log;
-
})->makeHidden(['id'])->all();
- $this->export_data['tasks'] = $this->company->tasks()->orderBy('number', 'DESC')->cursor()->map(function ($task){
-
+ $this->export_data['tasks'] = $this->company->tasks()->orderBy('number', 'DESC')->cursor()->map(function ($task) {
$task = $this->transformBasicEntities($task);
$task = $this->transformArrayOfKeys($task, ['client_id', 'invoice_id', 'project_id', 'status_id']);
return $task->makeVisible(['id']);
-
})->all();
- $this->export_data['task_statuses'] = $this->company->task_statuses->map(function ($status){
-
+ $this->export_data['task_statuses'] = $this->company->task_statuses->map(function ($status) {
$status->id = $this->encodePrimaryKey($status->id);
$status->user_id = $this->encodePrimaryKey($status->user_id);
$status->company_id = $this->encodePrimaryKey($status->company_id);
return $status;
-
})->all();
- $this->export_data['tax_rates'] = $this->company->tax_rates->map(function ($rate){
-
+ $this->export_data['tax_rates'] = $this->company->tax_rates->map(function ($rate) {
$rate->company_id = $this->encodePrimaryKey($rate->company_id);
$rate->user_id = $this->encodePrimaryKey($rate->user_id);
return $rate;
-
})->makeHidden(['id'])->all();
- $this->export_data['vendors'] = $this->company->vendors()->orderBy('number', 'DESC')->cursor()->map(function ($vendor){
-
+ $this->export_data['vendors'] = $this->company->vendors()->orderBy('number', 'DESC')->cursor()->map(function ($vendor) {
return $this->transformBasicEntities($vendor)->makeVisible(['id']);
-
})->all();
- $this->export_data['vendor_contacts'] = VendorContact::where('company_id', $this->company->id)->withTrashed()->cursor()->map(function ($vendor){
-
+ $this->export_data['vendor_contacts'] = VendorContact::where('company_id', $this->company->id)->withTrashed()->cursor()->map(function ($vendor) {
$vendor = $this->transformBasicEntities($vendor);
$vendor = $this->transformArrayOfKeys($vendor, ['vendor_id']);
return $vendor->makeVisible(['id','user_id']);
-
})->all();
- $this->export_data['webhooks'] = $this->company->webhooks->map(function ($hook){
-
+ $this->export_data['webhooks'] = $this->company->webhooks->map(function ($hook) {
$hook->user_id = $this->encodePrimaryKey($hook->user_id);
$hook->company_id = $this->encodePrimaryKey($hook->company_id);
return $hook;
-
})->makeHidden(['id'])->all();
- $this->export_data['purchase_orders'] = $this->company->purchase_orders()->orderBy('number', 'DESC')->cursor()->map(function ($purchase_order){
-
+ $this->export_data['purchase_orders'] = $this->company->purchase_orders()->orderBy('number', 'DESC')->cursor()->map(function ($purchase_order) {
$purchase_order = $this->transformBasicEntities($purchase_order);
$purchase_order = $this->transformArrayOfKeys($purchase_order, ['expense_id','client_id', 'vendor_id', 'project_id', 'design_id', 'subscription_id','project_id']);
@@ -455,67 +380,53 @@ class CompanyExport implements ShouldQueue
'client_id',
'vendor_id',
'company_id',]);
-
})->all();
- $this->export_data['purchase_order_invitations'] = PurchaseOrderInvitation::where('company_id', $this->company->id)->withTrashed()->cursor()->map(function ($purchase_order){
-
+ $this->export_data['purchase_order_invitations'] = PurchaseOrderInvitation::where('company_id', $this->company->id)->withTrashed()->cursor()->map(function ($purchase_order) {
$purchase_order = $this->transformArrayOfKeys($purchase_order, ['company_id', 'user_id', 'vendor_contact_id', 'purchase_order_id']);
return $purchase_order->makeVisible(['id']);
-
})->all();
- $this->export_data['bank_integrations'] = $this->company->bank_integrations()->orderBy('id', 'ASC')->cursor()->map(function ($bank_integration){
-
+ $this->export_data['bank_integrations'] = $this->company->bank_integrations()->orderBy('id', 'ASC')->cursor()->map(function ($bank_integration) {
$bank_integration = $this->transformArrayOfKeys($bank_integration, ['account_id','company_id', 'user_id']);
return $bank_integration->makeVisible(['id','user_id','company_id','account_id']);
-
})->all();
- $this->export_data['bank_transactions'] = $this->company->bank_transactions()->orderBy('id', 'ASC')->cursor()->map(function ($bank_transaction){
-
+ $this->export_data['bank_transactions'] = $this->company->bank_transactions()->orderBy('id', 'ASC')->cursor()->map(function ($bank_transaction) {
$bank_transaction = $this->transformArrayOfKeys($bank_transaction, ['company_id', 'user_id','bank_integration_id','expense_id','category_id','ninja_category_id','vendor_id']);
return $bank_transaction->makeVisible(['id','user_id','company_id']);
-
})->all();
//write to tmp and email to owner();
- $this->zipAndSend();
+ $this->zipAndSend();
- return true;
+ return true;
}
private function transformBasicEntities($model)
{
-
return $this->transformArrayOfKeys($model, ['user_id', 'assigned_user_id', 'company_id']);
-
}
private function transformArrayOfKeys($model, $keys)
{
-
- foreach($keys as $key){
+ foreach ($keys as $key) {
$model->{$key} = $this->encodePrimaryKey($model->{$key});
}
return $model;
-
}
private function transformPaymentable($payment)
{
-
$new_arr = [];
- foreach($payment->paymentables as $paymentable)
- {
-
+ foreach ($payment->paymentables as $paymentable) {
$paymentable->payment_id = $this->encodePrimaryKey($paymentable->payment_id);
$paymentable->paymentable_id = $this->encodePrimaryKey($paymentable->paymentable_id);
@@ -523,13 +434,11 @@ class CompanyExport implements ShouldQueue
}
return $new_arr;
-
}
private function zipAndSend()
{
-
- $file_name = date('Y-m-d').'_'.str_replace([" ", "/"],["_",""], $this->company->present()->name() . '_' . $this->company->company_key .'.zip');
+ $file_name = date('Y-m-d').'_'.str_replace([" ", "/"], ["_",""], $this->company->present()->name() . '_' . $this->company->company_key .'.zip');
$path = 'backups';
@@ -537,22 +446,21 @@ class CompanyExport implements ShouldQueue
try {
mkdir(public_path('storage/backups/'));
- }
- catch(\Exception $e) {
+ } catch(\Exception $e) {
nlog("could not create directory");
}
$zip_path = public_path('storage/backups/'.$file_name);
$zip = new \ZipArchive();
- if ($zip->open($zip_path, \ZipArchive::CREATE)!==TRUE) {
+ if ($zip->open($zip_path, \ZipArchive::CREATE)!==true) {
nlog("cannot open {$zip_path}");
}
$zip->addFromString("backup.json", json_encode($this->export_data));
$zip->close();
- if(Ninja::isHosted()) {
+ if (Ninja::isHosted()) {
Storage::disk(config('filesystems.default'))->put('backups/'.$file_name, file_get_contents($zip_path));
}
@@ -562,7 +470,8 @@ class CompanyExport implements ShouldQueue
$t = app('translator');
$t->replace(Ninja::transformTranslations($this->company->settings));
- $company_reference = Company::find($this->company->id);;
+ $company_reference = Company::find($this->company->id);
+ ;
$nmo = new NinjaMailerObject;
$nmo->mailable = new DownloadBackup($storage_file_path, $company_reference);
@@ -572,10 +481,9 @@ class CompanyExport implements ShouldQueue
NinjaMailerJob::dispatch($nmo, true);
- if(Ninja::isHosted()){
+ if (Ninja::isHosted()) {
sleep(3);
unlink($zip_path);
}
}
-
}
diff --git a/app/Jobs/Company/CompanyImport.php b/app/Jobs/Company/CompanyImport.php
index 698399527c1f..3c5ca9d8707d 100644
--- a/app/Jobs/Company/CompanyImport.php
+++ b/app/Jobs/Company/CompanyImport.php
@@ -16,10 +16,7 @@ use App\Exceptions\NonExistingMigrationFile;
use App\Factory\ClientContactFactory;
use App\Jobs\Mail\NinjaMailerJob;
use App\Jobs\Mail\NinjaMailerObject;
-use App\Jobs\Util\UnlinkFile;
use App\Libraries\MultiDB;
-use App\Mail\DownloadBackup;
-use App\Mail\DownloadInvoices;
use App\Mail\Import\CompanyImportFailure;
use App\Mail\Import\ImportCompleted;
use App\Models\Activity;
@@ -43,8 +40,8 @@ use App\Models\GroupSetting;
use App\Models\Invoice;
use App\Models\InvoiceInvitation;
use App\Models\Payment;
-use App\Models\PaymentTerm;
use App\Models\Paymentable;
+use App\Models\PaymentTerm;
use App\Models\Product;
use App\Models\Project;
use App\Models\PurchaseOrder;
@@ -66,6 +63,7 @@ use App\Utils\Ninja;
use App\Utils\TempFile;
use App\Utils\Traits\GeneratesCounter;
use App\Utils\Traits\MakesHash;
+use function GuzzleHttp\json_encode;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
@@ -78,7 +76,6 @@ use Illuminate\Support\Str;
use JsonMachine\JsonDecoder\ExtJsonDecoder;
use JsonMachine\JsonMachine;
use ZipArchive;
-use function GuzzleHttp\json_encode;
class CompanyImport implements ShouldQueue
{
@@ -236,17 +233,18 @@ class CompanyImport implements ShouldQueue
$json = JsonMachine::fromFile($this->file_path, '/'.$key, new ExtJsonDecoder);
- if($force_array)
+ if ($force_array) {
return iterator_to_array($json);
+ }
return $json;
}
public function handle()
{
- MultiDB::setDb($this->company->db);
+ MultiDB::setDb($this->company->db);
- $this->company = Company::where('company_key', $this->company->company_key)->firstOrFail();
+ $this->company = Company::where('company_key', $this->company->company_key)->firstOrFail();
$this->account = $this->company->account;
$this->company_owner = $this->company->owner();
@@ -255,8 +253,9 @@ class CompanyImport implements ShouldQueue
// $this->backup_file = Cache::get($this->hash);
- if ( empty( $this->file_location ) )
+ if (empty($this->file_location)) {
throw new \Exception('No import data found, has the cache expired?');
+ }
// $this->backup_file = json_decode(file_get_contents($this->file_location));
$tmp_file = $this->unzipFile();
@@ -265,15 +264,12 @@ class CompanyImport implements ShouldQueue
$this->checkUserCount();
- if(array_key_exists('import_settings', $this->request_array) && $this->request_array['import_settings'] == 'true') {
-
+ if (array_key_exists('import_settings', $this->request_array) && $this->request_array['import_settings'] == 'true') {
$this->preFlightChecks()->importSettings();
}
- if(array_key_exists('import_data', $this->request_array) && $this->request_array['import_data'] == 'true') {
-
- try{
-
+ if (array_key_exists('import_data', $this->request_array) && $this->request_array['import_data'] == 'true') {
+ try {
$this->preFlightChecks()
->purgeCompanyData()
->importCompany()
@@ -292,18 +288,12 @@ class CompanyImport implements ShouldQueue
$nmo->settings = $_company->settings;
$nmo->to_user = $_company->owner();
NinjaMailerJob::dispatch($nmo);
-
- }
- catch(\Exception $e){
-
+ } catch(\Exception $e) {
info($e->getMessage());
-
- }
-
+ }
}
unlink($tmp_file);
-
}
//
@@ -315,23 +305,19 @@ class CompanyImport implements ShouldQueue
->clients()
->whereDoesntHave('contacts')
->cursor()
- ->each(function ($client){
-
- $new_contact = ClientContactFactory::create($client->company_id, $client->user_id);
- $new_contact->client_id = $client->id;
- $new_contact->contact_key = Str::random(40);
- $new_contact->is_primary = true;
- $new_contact->confirmed = true;
- $new_contact->email = ' ';
- $new_contact->save();
-
- });
-
+ ->each(function ($client) {
+ $new_contact = ClientContactFactory::create($client->company_id, $client->user_id);
+ $new_contact->client_id = $client->id;
+ $new_contact->contact_key = Str::random(40);
+ $new_contact->is_primary = true;
+ $new_contact->confirmed = true;
+ $new_contact->email = ' ';
+ $new_contact->save();
+ });
}
private function unzipFile()
{
-
$path = TempFile::filePath(Storage::disk(config('filesystems.default'))->get($this->file_location), basename($this->file_location));
$zip = new ZipArchive();
@@ -343,75 +329,68 @@ class CompanyImport implements ShouldQueue
$zip->close();
$file_location = "{$file_path}/backup.json";
- if (! file_exists($file_path))
+ if (! file_exists($file_path)) {
throw new NonExistingMigrationFile('Backup file does not exist, or is corrupted.');
+ }
return $file_location;
-
}
/**
- * On the hosted platform we cannot allow the
+ * On the hosted platform we cannot allow the
* import to start if there are users > plan number
* due to entity user_id dependencies
- *
+ *
* @return bool
*/
private function checkUserCount()
{
-
- if(Ninja::isSelfHost())
+ if (Ninja::isSelfHost()) {
$this->pre_flight_checks_pass = true;
+ }
// $backup_users = $this->backup_file->users;
$backup_users = $this->getObject('users', true);
$company_users = $this->company->users;
- nlog("Backup user count = ".count($backup_users));
+ nlog("Backup user count = ".count($backup_users));
- if(count($backup_users) > 1){
+ if (count($backup_users) > 1) {
+ }
+ nlog("backup users email = " . $backup_users[0]->email);
+
+ if (count($backup_users) == 1 && $this->company_owner->email != $backup_users[0]->email) {
+ }
+
+ $backup_users_emails = array_column($backup_users, 'email');
+
+ $company_users_emails = $company_users->pluck('email')->toArray();
+
+ $existing_user_count = count(array_intersect($backup_users_emails, $company_users_emails));
+
+ nlog("existing user count = {$existing_user_count}");
+
+ if ($existing_user_count > 1) {
+ if ($this->account->plan == 'pro') {
}
- nlog("backup users email = " . $backup_users[0]->email);
-
- if(count($backup_users) == 1 && $this->company_owner->email != $backup_users[0]->email) {
-
+ if ($this->account->plan == 'enterprise') {
}
+ }
- $backup_users_emails = array_column($backup_users, 'email');
+ if ($this->company->account->isFreeHostedClient() && (count($this->getObject('clients', true)) > config('ninja.quotas.free.clients'))) {
+ nlog("client quota busted");
- $company_users_emails = $company_users->pluck('email')->toArray();
+ $client_limit = config('ninja.quotas.free.clients');
+ $client_count = count($this->getObject('clients', true));
- $existing_user_count = count(array_intersect($backup_users_emails, $company_users_emails));
-
- nlog("existing user count = {$existing_user_count}");
-
- if($existing_user_count > 1){
-
- if($this->account->plan == 'pro'){
-
- }
-
- if($this->account->plan == 'enterprise'){
-
- }
- }
-
- if($this->company->account->isFreeHostedClient() && (count($this->getObject('clients', true)) > config('ninja.quotas.free.clients')) ){
+ $this->message = "You are attempting to import ({$client_count}) clients, your current plan allows a total of ({$client_limit})";
- nlog("client quota busted");
-
- $client_limit = config('ninja.quotas.free.clients');
- $client_count = count($this->getObject('clients', true));
-
- $this->message = "You are attempting to import ({$client_count}) clients, your current plan allows a total of ({$client_limit})";
-
- $this->pre_flight_checks_pass = false;
-
- }
+ $this->pre_flight_checks_pass = false;
+ }
return $this;
}
@@ -424,24 +403,21 @@ class CompanyImport implements ShouldQueue
private function preFlightChecks()
{
- //check the file version and perform any necessary adjustments to the file in order to proceed - needed when we change schema
+ //check the file version and perform any necessary adjustments to the file in order to proceed - needed when we change schema
$data = (object)$this->getObject('app_version', true);
- if($this->current_app_version != $data->app_version)
- {
+ if ($this->current_app_version != $data->app_version) {
//perform some magic here
}
- if($this->pre_flight_checks_pass === false)
- {
-
+ if ($this->pre_flight_checks_pass === false) {
$this->sendImportMail($this->message);
throw new \Exception($this->message);
}
- return $this;
+ return $this;
}
private function importSettings()
@@ -489,125 +465,123 @@ class CompanyImport implements ShouldQueue
private function importCompany()
{
//$tmp_company = $this->backup_file->company;
- $tmp_company = (object)$this->getObject("company",true);
+ $tmp_company = (object)$this->getObject("company", true);
$tmp_company->company_key = $this->createHash();
$tmp_company->db = config('database.default');
$tmp_company->account_id = $this->account->id;
- if(Ninja::isHosted())
+ if (Ninja::isHosted()) {
$tmp_company->subdomain = MultiDB::randomSubdomainGenerator();
- else
+ } else {
$tmp_company->subdomain = '';
+ }
- foreach($this->company_properties as $value){
-
- if(property_exists($tmp_company, $value))
- $this->company->{$value} = $tmp_company->{$value};
-
+ foreach ($this->company_properties as $value) {
+ if (property_exists($tmp_company, $value)) {
+ $this->company->{$value} = $tmp_company->{$value};
+ }
}
- if(Ninja::isHosted())
- {
+ if (Ninja::isHosted()) {
$this->company->portal_mode = 'subdomain';
- $this->company->portal_domain = '';
+ $this->company->portal_domain = '';
}
$this->company->save();
- return $this;
+ return $this;
}
private function importData()
{
-
- foreach($this->importables as $import){
-
+ foreach ($this->importables as $import) {
$method = "import_{$import}";
nlog($method);
$this->{$method}();
-
}
nlog("finished importing company data");
return $this;
-
}
private function import_bank_integrations()
{
- $this->genericImport(BankIntegration::class,
- ['assigned_user_id','account_id', 'company_id', 'id', 'hashed_id'],
+ $this->genericImport(
+ BankIntegration::class,
+ ['assigned_user_id','account_id', 'company_id', 'id', 'hashed_id'],
[
- ['users' => 'user_id'],
- ],
+ ['users' => 'user_id'],
+ ],
'bank_integrations',
- 'description');
+ 'description'
+ );
return $this;
}
private function import_bank_transactions()
{
- $this->genericImport(BankTransaction::class,
- ['assigned_user_id','company_id', 'id', 'hashed_id', 'user_id'],
+ $this->genericImport(
+ BankTransaction::class,
+ ['assigned_user_id','company_id', 'id', 'hashed_id', 'user_id'],
[
- ['users' => 'user_id'],
+ ['users' => 'user_id'],
['expenses' => 'expense_id'],
['vendors' => 'vendor_id'],
['expense_categories' => 'ninja_category_id'],
['expense_categories' => 'category_id'],
['bank_integrations' => 'bank_integration_id']
- ],
+ ],
'bank_transactions',
- null);
+ null
+ );
return $this;
}
private function import_recurring_expenses()
{
-//unset / transforms / object_property / match_key
- $this->genericImport(RecurringExpense::class,
- ['assigned_user_id', 'user_id', 'client_id', 'company_id', 'id', 'hashed_id', 'project_id', 'vendor_id','recurring_expense_id'],
+ //unset / transforms / object_property / match_key
+ $this->genericImport(
+ RecurringExpense::class,
+ ['assigned_user_id', 'user_id', 'client_id', 'company_id', 'id', 'hashed_id', 'project_id', 'vendor_id','recurring_expense_id'],
[
- ['users' => 'user_id'],
- ['users' => 'assigned_user_id'],
+ ['users' => 'user_id'],
+ ['users' => 'assigned_user_id'],
['clients' => 'client_id'],
['projects' => 'project_id'],
['vendors' => 'vendor_id'],
['invoices' => 'invoice_id'],
['expense_categories' => 'category_id'],
- ],
+ ],
'recurring_expenses',
- 'number');
+ 'number'
+ );
return $this;
}
private function import_payment_terms()
{
-
- $this->genericImport(PaymentTerm::class,
- ['user_id', 'assigned_user_id', 'company_id', 'id', 'hashed_id'],
- [['users' => 'user_id']],
+ $this->genericImport(
+ PaymentTerm::class,
+ ['user_id', 'assigned_user_id', 'company_id', 'id', 'hashed_id'],
+ [['users' => 'user_id']],
'payment_terms',
- 'num_days');
+ 'num_days'
+ );
return $this;
-
}
/* Cannot use generic as we are matching on two columns for existing data */
private function import_tax_rates()
{
-
// foreach($this->backup_file->tax_rates as $obj)
- foreach((object)$this->getObject("tax_rates") as $obj)
- {
-
+ foreach ((object)$this->getObject("tax_rates") as $obj) {
$user_id = $this->transformId('users', $obj->user_id);
$obj_array = (array)$obj;
@@ -618,14 +592,13 @@ class CompanyImport implements ShouldQueue
unset($obj_array['tax_rate_id']);
$new_obj = TaxRate::firstOrNew(
- ['name' => $obj->name, 'company_id' => $this->company->id, 'rate' => $obj->rate],
- $obj_array,
- );
+ ['name' => $obj->name, 'company_id' => $this->company->id, 'rate' => $obj->rate],
+ $obj_array,
+ );
$new_obj->company_id = $this->company->id;
$new_obj->user_id = $user_id;
$new_obj->save(['timestamps' => false]);
-
}
return $this;
@@ -633,396 +606,406 @@ class CompanyImport implements ShouldQueue
private function import_expense_categories()
{
-
- $this->genericImport(ExpenseCategory::class,
- ['user_id', 'company_id', 'id', 'hashed_id'],
- [['users' => 'user_id']],
+ $this->genericImport(
+ ExpenseCategory::class,
+ ['user_id', 'company_id', 'id', 'hashed_id'],
+ [['users' => 'user_id']],
'expense_categories',
- 'name');
+ 'name'
+ );
return $this;
-
}
private function import_task_statuses()
{
-
- $this->genericImport(TaskStatus::class,
- ['user_id', 'company_id', 'id', 'hashed_id'],
- [['users' => 'user_id']],
+ $this->genericImport(
+ TaskStatus::class,
+ ['user_id', 'company_id', 'id', 'hashed_id'],
+ [['users' => 'user_id']],
'task_statuses',
- 'name');
+ 'name'
+ );
return $this;
-
}
private function import_clients()
{
-
- $this->genericImport(Client::class,
- ['user_id', 'assigned_user_id', 'company_id', 'id', 'hashed_id', 'gateway_tokens', 'contacts', 'documents','country'],
- [['users' => 'user_id'], ['users' => 'assigned_user_id']],
+ $this->genericImport(
+ Client::class,
+ ['user_id', 'assigned_user_id', 'company_id', 'id', 'hashed_id', 'gateway_tokens', 'contacts', 'documents','country'],
+ [['users' => 'user_id'], ['users' => 'assigned_user_id']],
'clients',
- 'number');
+ 'number'
+ );
return $this;
-
}
private function import_client_contacts()
{
-
- $this->genericImport(ClientContact::class,
- ['user_id', 'company_id', 'id', 'hashed_id','company'],
- [['users' => 'user_id'], ['clients' => 'client_id']],
+ $this->genericImport(
+ ClientContact::class,
+ ['user_id', 'company_id', 'id', 'hashed_id','company'],
+ [['users' => 'user_id'], ['clients' => 'client_id']],
'client_contacts',
- 'email');
+ 'email'
+ );
return $this;
-
}
private function import_vendors()
{
-
- $this->genericImport(Vendor::class,
- ['user_id', 'assigned_user_id', 'company_id', 'id', 'hashed_id'],
- [['users' => 'user_id'], ['users' =>'assigned_user_id']],
+ $this->genericImport(
+ Vendor::class,
+ ['user_id', 'assigned_user_id', 'company_id', 'id', 'hashed_id'],
+ [['users' => 'user_id'], ['users' =>'assigned_user_id']],
'vendors',
- 'number');
+ 'number'
+ );
return $this;
}
private function import_vendor_contacts()
{
-
- $this->genericImport(VendorContact::class,
- ['user_id', 'company_id', 'id', 'hashed_id','company','assigned_user_id'],
- [['users' => 'user_id'], ['vendors' => 'vendor_id']],
+ $this->genericImport(
+ VendorContact::class,
+ ['user_id', 'company_id', 'id', 'hashed_id','company','assigned_user_id'],
+ [['users' => 'user_id'], ['vendors' => 'vendor_id']],
'vendor_contacts',
- 'email');
+ 'email'
+ );
return $this;
-
}
private function import_projects()
{
-
- $this->genericImport(Project::class,
- ['user_id', 'assigned_user_id', 'company_id', 'id', 'hashed_id','client_id'],
- [['users' => 'user_id'], ['users' =>'assigned_user_id'], ['clients' => 'client_id']],
+ $this->genericImport(
+ Project::class,
+ ['user_id', 'assigned_user_id', 'company_id', 'id', 'hashed_id','client_id'],
+ [['users' => 'user_id'], ['users' =>'assigned_user_id'], ['clients' => 'client_id']],
'projects',
- 'number');
+ 'number'
+ );
- return $this;
+ return $this;
}
private function import_products()
{
-
- $this->genericNewClassImport(Product::class,
+ $this->genericNewClassImport(
+ Product::class,
['user_id', 'company_id', 'hashed_id', 'id'],
[['users' => 'user_id'], ['users' =>'assigned_user_id'], ['vendors' => 'vendor_id'], ['projects' => 'project_id']],
- 'products'
+ 'products'
);
- return $this;
+ return $this;
}
private function import_company_gateways()
{
-
- $this->genericNewClassImport(CompanyGateway::class,
+ $this->genericNewClassImport(
+ CompanyGateway::class,
['user_id', 'company_id', 'hashed_id', 'id'],
[['users' => 'user_id']],
- 'company_gateways'
+ 'company_gateways'
);
- return $this;
+ return $this;
}
private function import_client_gateway_tokens()
{
+ $this->genericNewClassImport(
+ ClientGatewayToken::class,
+ ['company_id', 'id', 'hashed_id','client_id'],
+ [['clients' => 'client_id', 'company_gateways' => 'company_gateway_id']],
+ 'client_gateway_tokens'
+ );
- $this->genericNewClassImport(ClientGatewayToken::class,
- ['company_id', 'id', 'hashed_id','client_id'],
- [['clients' => 'client_id', 'company_gateways' => 'company_gateway_id']],
- 'client_gateway_tokens');
-
- return $this;
+ return $this;
}
private function import_group_settings()
{
-
- $this->genericImport(GroupSetting::class,
- ['user_id', 'company_id', 'id', 'hashed_id'],
- [['users' => 'user_id']],
+ $this->genericImport(
+ GroupSetting::class,
+ ['user_id', 'company_id', 'id', 'hashed_id'],
+ [['users' => 'user_id']],
'group_settings',
- 'name');
+ 'name'
+ );
- return $this;
+ return $this;
}
private function import_subscriptions()
{
-
- $this->genericImport(Subscription::class,
- ['user_id', 'assigned_user_id', 'company_id', 'id', 'hashed_id'],
- [['group_settings' => 'group_id'], ['users' => 'user_id'], ['users' => 'assigned_user_id']],
+ $this->genericImport(
+ Subscription::class,
+ ['user_id', 'assigned_user_id', 'company_id', 'id', 'hashed_id'],
+ [['group_settings' => 'group_id'], ['users' => 'user_id'], ['users' => 'assigned_user_id']],
'subscriptions',
- 'name');
+ 'name'
+ );
- return $this;
+ return $this;
}
private function import_recurring_invoices()
{
-
- $this->genericImport(RecurringInvoice::class,
- ['user_id', 'assigned_user_id', 'company_id', 'id', 'hashed_id', 'client_id','subscription_id','project_id','vendor_id','status'],
+ $this->genericImport(
+ RecurringInvoice::class,
+ ['user_id', 'assigned_user_id', 'company_id', 'id', 'hashed_id', 'client_id','subscription_id','project_id','vendor_id','status'],
[
- ['subscriptions' => 'subscription_id'],
- ['users' => 'user_id'],
+ ['subscriptions' => 'subscription_id'],
+ ['users' => 'user_id'],
['users' => 'assigned_user_id'],
['clients' => 'client_id'],
['projects' => 'project_id'],
['vendors' => 'vendor_id'],
['clients' => 'client_id'],
- ],
+ ],
'recurring_invoices',
- 'number');
+ 'number'
+ );
return $this;
-
}
private function import_recurring_invoice_invitations()
{
-
-
- $this->genericImport(RecurringInvoiceInvitation::class,
- ['user_id', 'client_contact_id', 'company_id', 'id', 'hashed_id', 'recurring_invoice_id'],
+ $this->genericImport(
+ RecurringInvoiceInvitation::class,
+ ['user_id', 'client_contact_id', 'company_id', 'id', 'hashed_id', 'recurring_invoice_id'],
[
- ['users' => 'user_id'],
+ ['users' => 'user_id'],
['recurring_invoices' => 'recurring_invoice_id'],
['client_contacts' => 'client_contact_id'],
- ],
+ ],
'recurring_invoice_invitations',
- 'key');
+ 'key'
+ );
return $this;
-
}
private function import_invoices()
{
-
- $this->genericImport(Invoice::class,
- ['user_id', 'client_id', 'company_id', 'id', 'hashed_id', 'recurring_id','status'],
+ $this->genericImport(
+ Invoice::class,
+ ['user_id', 'client_id', 'company_id', 'id', 'hashed_id', 'recurring_id','status'],
[
- ['users' => 'user_id'],
- ['users' => 'assigned_user_id'],
+ ['users' => 'user_id'],
+ ['users' => 'assigned_user_id'],
['recurring_invoices' => 'recurring_id'],
['clients' => 'client_id'],
['subscriptions' => 'subscription_id'],
['projects' => 'project_id'],
['vendors' => 'vendor_id'],
- ],
+ ],
'invoices',
- 'number');
+ 'number'
+ );
- return $this;
+ return $this;
}
private function import_invoice_invitations()
{
-
-
- $this->genericImport(InvoiceInvitation::class,
- ['user_id', 'client_contact_id', 'company_id', 'id', 'hashed_id', 'invoice_id'],
+ $this->genericImport(
+ InvoiceInvitation::class,
+ ['user_id', 'client_contact_id', 'company_id', 'id', 'hashed_id', 'invoice_id'],
[
- ['users' => 'user_id'],
+ ['users' => 'user_id'],
['invoices' => 'invoice_id'],
['client_contacts' => 'client_contact_id'],
- ],
+ ],
'invoice_invitations',
- 'key');
+ 'key'
+ );
- return $this;
+ return $this;
}
private function import_purchase_orders()
{
-
- $this->genericImport(PurchaseOrder::class,
- ['user_id', 'company_id', 'id', 'hashed_id', 'recurring_id','status', 'vendor_id', 'subscription_id','client_id'],
+ $this->genericImport(
+ PurchaseOrder::class,
+ ['user_id', 'company_id', 'id', 'hashed_id', 'recurring_id','status', 'vendor_id', 'subscription_id','client_id'],
[
- ['users' => 'user_id'],
- ['users' => 'assigned_user_id'],
+ ['users' => 'user_id'],
+ ['users' => 'assigned_user_id'],
['recurring_invoices' => 'recurring_id'],
['projects' => 'project_id'],
['vendors' => 'vendor_id'],
- ],
+ ],
'purchase_orders',
- 'number');
+ 'number'
+ );
- return $this;
+ return $this;
}
private function import_purchase_order_invitations()
{
-
-
- $this->genericImport(PurchaseOrderInvitation::class,
- ['user_id', 'vendor_contact_id', 'company_id', 'id', 'hashed_id', 'purchase_order_id'],
+ $this->genericImport(
+ PurchaseOrderInvitation::class,
+ ['user_id', 'vendor_contact_id', 'company_id', 'id', 'hashed_id', 'purchase_order_id'],
[
- ['users' => 'user_id'],
+ ['users' => 'user_id'],
['purchase_orders' => 'purchase_order_id'],
['vendor_contacts' => 'vendor_contact_id'],
- ],
+ ],
'purchase_order_invitations',
- 'key');
+ 'key'
+ );
- return $this;
+ return $this;
}
private function import_quotes()
{
-
- $this->genericImport(Quote::class,
- ['user_id', 'client_id', 'company_id', 'id', 'hashed_id', 'recurring_id','status'],
+ $this->genericImport(
+ Quote::class,
+ ['user_id', 'client_id', 'company_id', 'id', 'hashed_id', 'recurring_id','status'],
[
- ['users' => 'user_id'],
- ['users' => 'assigned_user_id'],
+ ['users' => 'user_id'],
+ ['users' => 'assigned_user_id'],
['recurring_invoices' => 'recurring_id'],
['clients' => 'client_id'],
['subscriptions' => 'subscription_id'],
['projects' => 'project_id'],
['vendors' => 'vendor_id'],
- ],
+ ],
'quotes',
- 'number');
+ 'number'
+ );
return $this;
-
}
private function import_quote_invitations()
{
-
- $this->genericImport(QuoteInvitation::class,
- ['user_id', 'client_contact_id', 'company_id', 'id', 'hashed_id', 'quote_id'],
+ $this->genericImport(
+ QuoteInvitation::class,
+ ['user_id', 'client_contact_id', 'company_id', 'id', 'hashed_id', 'quote_id'],
[
- ['users' => 'user_id'],
+ ['users' => 'user_id'],
['quotes' => 'quote_id'],
['client_contacts' => 'client_contact_id'],
- ],
+ ],
'quote_invitations',
- 'key');
+ 'key'
+ );
- return $this;
+ return $this;
}
private function import_credits()
{
-
-
- $this->genericImport(Credit::class,
- ['user_id', 'client_id', 'company_id', 'id', 'hashed_id', 'recurring_id','status'],
+ $this->genericImport(
+ Credit::class,
+ ['user_id', 'client_id', 'company_id', 'id', 'hashed_id', 'recurring_id','status'],
[
- ['users' => 'user_id'],
- ['users' => 'assigned_user_id'],
+ ['users' => 'user_id'],
+ ['users' => 'assigned_user_id'],
['recurring_invoices' => 'recurring_id'],
['clients' => 'client_id'],
['subscriptions' => 'subscription_id'],
['projects' => 'project_id'],
['vendors' => 'vendor_id'],
- ],
+ ],
'credits',
- 'number');
+ 'number'
+ );
- return $this;
+ return $this;
}
private function import_credit_invitations()
{
-
- $this->genericImport(CreditInvitation::class,
- ['user_id', 'client_contact_id', 'company_id', 'id', 'hashed_id', 'credit_id'],
+ $this->genericImport(
+ CreditInvitation::class,
+ ['user_id', 'client_contact_id', 'company_id', 'id', 'hashed_id', 'credit_id'],
[
- ['users' => 'user_id'],
+ ['users' => 'user_id'],
['credits' => 'credit_id'],
['client_contacts' => 'client_contact_id'],
- ],
+ ],
'credit_invitations',
- 'key');
+ 'key'
+ );
- return $this;
+ return $this;
}
private function import_expenses()
{
-
- $this->genericImport(Expense::class,
- ['assigned_user_id', 'user_id', 'client_id', 'company_id', 'id', 'hashed_id', 'project_id','vendor_id','recurring_expense_id'],
+ $this->genericImport(
+ Expense::class,
+ ['assigned_user_id', 'user_id', 'client_id', 'company_id', 'id', 'hashed_id', 'project_id','vendor_id','recurring_expense_id'],
[
- ['users' => 'user_id'],
- ['users' => 'assigned_user_id'],
+ ['users' => 'user_id'],
+ ['users' => 'assigned_user_id'],
['clients' => 'client_id'],
['projects' => 'project_id'],
['vendors' => 'vendor_id'],
['invoices' => 'invoice_id'],
// ['recurring_expenses' => 'recurring_expense_id'],
['expense_categories' => 'category_id'],
- ],
+ ],
'expenses',
- 'number');
+ 'number'
+ );
return $this;
-
}
private function import_tasks()
{
-
- $this->genericImport(Task::class,
- ['assigned_user_id', 'user_id', 'client_id', 'company_id', 'id', 'hashed_id', 'invoice_id','project_id'],
+ $this->genericImport(
+ Task::class,
+ ['assigned_user_id', 'user_id', 'client_id', 'company_id', 'id', 'hashed_id', 'invoice_id','project_id'],
[
- ['users' => 'user_id'],
- ['users' => 'assigned_user_id'],
+ ['users' => 'user_id'],
+ ['users' => 'assigned_user_id'],
['clients' => 'client_id'],
['projects' => 'project_id'],
['invoices' => 'invoice_id'],
- ],
+ ],
'tasks',
- 'number');
+ 'number'
+ );
- return $this;
+ return $this;
}
private function import_payments()
{
-
- $this->genericImport(Payment::class,
- ['assigned_user_id', 'user_id', 'client_id', 'company_id', 'id', 'hashed_id', 'client_contact_id','invitation_id','vendor_id','paymentables'],
+ $this->genericImport(
+ Payment::class,
+ ['assigned_user_id', 'user_id', 'client_id', 'company_id', 'id', 'hashed_id', 'client_contact_id','invitation_id','vendor_id','paymentables'],
[
- ['users' => 'user_id'],
- ['users' => 'assigned_user_id'],
+ ['users' => 'user_id'],
+ ['users' => 'assigned_user_id'],
['clients' => 'client_id'],
['client_contacts' => 'client_contact_id'],
['vendors' => 'vendor_id'],
['invoice_invitations' => 'invitation_id'],
['company_gateways' => 'company_gateway_id'],
['bank_transactions' => 'transaction_id'],
- ],
+ ],
'payments',
- 'number');
+ 'number'
+ );
$this->paymentablesImport();
@@ -1031,20 +1014,20 @@ class CompanyImport implements ShouldQueue
private function import_activities()
{
-
$activities = [];
- $this->genericNewClassImport(Activity::class,
+ $this->genericNewClassImport(
+ Activity::class,
[
'hashed_id',
'company_id',
'backup',
'invitation_id',
'payment_id',
- ],
+ ],
[
- ['users' => 'user_id'],
+ ['users' => 'user_id'],
['clients' => 'client_id'],
['client_contacts' => 'client_contact_id'],
['projects' => 'project_id'],
@@ -1059,68 +1042,68 @@ class CompanyImport implements ShouldQueue
['recurring_invoices' => 'recurring_invoice_id'],
// ['recurring_expenses' => 'recurring_expense_id'],
// ['invitations' => 'invitation_id'],
- ],
- 'activities');
+ ],
+ 'activities'
+ );
return $this;
-
}
private function import_backups()
{
-
- $this->genericImportWithoutCompany(Backup::class,
- ['hashed_id','id'],
+ $this->genericImportWithoutCompany(
+ Backup::class,
+ ['hashed_id','id'],
[
- ['activities' => 'activity_id'],
- ],
+ ['activities' => 'activity_id'],
+ ],
'backups',
- 'created_at');
+ 'created_at'
+ );
- return $this;
- }
+ return $this;
+ }
private function import_company_ledger()
{
-
- $this->genericImport(CompanyLedger::class,
- ['company_id', 'user_id', 'client_id', 'activity_id', 'id','account_id'],
+ $this->genericImport(
+ CompanyLedger::class,
+ ['company_id', 'user_id', 'client_id', 'activity_id', 'id','account_id'],
[
- ['users' => 'user_id'],
+ ['users' => 'user_id'],
['clients' => 'client_id'],
// ['activities' => 'activity_id'],
- ],
+ ],
'company_ledger',
- 'created_at');
+ 'created_at'
+ );
return $this;
-
}
private function import_designs()
{
-
- $this->genericImport(Design::class,
- ['company_id', 'user_id', 'hashed_id'],
+ $this->genericImport(
+ Design::class,
+ ['company_id', 'user_id', 'hashed_id'],
[
['users' => 'user_id'],
- ],
+ ],
'designs',
- 'name');
+ 'name'
+ );
return $this;
-
}
private function import_documents()
{
-
- foreach((object)$this->getObject("documents") as $document)
- {
+ foreach ((object)$this->getObject("documents") as $document) {
//todo enable this for v5.5.51
- if(!$this->transformDocumentId($document->documentable_id, $document->documentable_type))
+ if (!$this->transformDocumentId($document->documentable_id, $document->documentable_type)) {
continue;
+ }
$new_document = new Document();
$new_document->user_id = $this->transformId('users', $document->user_id);
@@ -1151,31 +1134,24 @@ class CompanyImport implements ShouldQueue
$storage_url = (object)$this->getObject('storage_url', true);
- if(!Storage::exists($new_document->url) && is_string($storage_url)){
-
+ if (!Storage::exists($new_document->url) && is_string($storage_url)) {
$url = $storage_url . $new_document->url;
$file = @file_get_contents($url);
- if($file)
- {
- try{
+ if ($file) {
+ try {
Storage::disk(config('filesystems.default'))->put($new_document->url, $file);
$new_document->disk = config('filesystems.default');
$new_document->save();
-
- }
- catch(\Exception $e)
- {
+ } catch(\Exception $e) {
nlog($e->getMessage());
nlog("I could not upload {$new_document->url}");
$new_document->forceDelete();
}
}
-
}
-
}
return $this;
@@ -1183,14 +1159,15 @@ class CompanyImport implements ShouldQueue
private function import_webhooks()
{
-
- $this->genericImport(Webhook::class,
- ['company_id', 'user_id'],
+ $this->genericImport(
+ Webhook::class,
+ ['company_id', 'user_id'],
[
['users' => 'user_id'],
- ],
+ ],
'webhooks',
- 'created_at');
+ 'created_at'
+ );
return $this;
}
@@ -1206,11 +1183,10 @@ class CompanyImport implements ShouldQueue
User::unguard();
//foreach ($this->backup_file->users as $user)
- foreach((object)$this->getObject("users") as $user)
- {
-
- if(User::withTrashed()->where('email', $user->email)->where('account_id', '!=', $this->account->id)->exists())
+ foreach ((object)$this->getObject("users") as $user) {
+ if (User::withTrashed()->where('email', $user->email)->where('account_id', '!=', $this->account->id)->exists()) {
throw new ImportCompanyFailed("{$user->email} is already in the system attached to a different account");
+ }
$user_array = (array)$user;
unset($user_array['laravel_through_key']);
@@ -1228,11 +1204,9 @@ class CompanyImport implements ShouldQueue
$new_user->save(['timestamps' => false]);
$this->ids['users']["{$user->hashed_id}"] = $new_user->id;
-
}
User::reguard();
-
}
private function import_company_users()
@@ -1240,8 +1214,7 @@ class CompanyImport implements ShouldQueue
CompanyUser::unguard();
// foreach($this->backup_file->company_users as $cu)
- foreach((object)$this->getObject("company_users") as $cu)
- {
+ foreach ((object)$this->getObject("company_users") as $cu) {
$user_id = $this->transformId('users', $cu->user_id);
$cu_array = (array)$cu;
@@ -1262,11 +1235,9 @@ class CompanyImport implements ShouldQueue
$new_cu->account_id = $this->account->id;
$new_cu->save(['timestamps' => false]);
-
}
CompanyUser::reguard();
-
}
private function transformDocumentId($id, $type)
@@ -1318,14 +1289,9 @@ class CompanyImport implements ShouldQueue
private function paymentablesImport()
{
-
// foreach($this->backup_file->payments as $payment)
- foreach((object)$this->getObject("payments") as $payment)
- {
-
- foreach($payment->paymentables as $paymentable_obj)
- {
-
+ foreach ((object)$this->getObject("payments") as $payment) {
+ foreach ($payment->paymentables as $paymentable_obj) {
$paymentable = new Paymentable();
$paymentable->payment_id = $this->transformId('payments', $paymentable_obj->payment_id);
$paymentable->paymentable_type = $paymentable_obj->paymentable_type;
@@ -1351,9 +1317,9 @@ class CompanyImport implements ShouldQueue
break;
case Credit::class:
return $this->transformId('credits', $id);
- break;
+ break;
case Payment::class:
- return $this->transformId('payments', $id);
+ return $this->transformId('payments', $id);
default:
# code...
break;
@@ -1363,66 +1329,57 @@ class CompanyImport implements ShouldQueue
private function genericNewClassImport($class, $unset, $transforms, $object_property)
{
-
$class::unguard();
- foreach((object)$this->getObject($object_property) as $obj)
- {
+ foreach ((object)$this->getObject($object_property) as $obj) {
/* Remove unwanted keys*/
$obj_array = (array)$obj;
- foreach($unset as $un){
+ foreach ($unset as $un) {
unset($obj_array[$un]);
}
- if($class instanceof CompanyGateway){
-
- if(Ninja::isHosted() && $obj_array['gateway_key'] == 'd14dd26a37cecc30fdd65700bfb55b23'){
+ if ($class instanceof CompanyGateway) {
+ if (Ninja::isHosted() && $obj_array['gateway_key'] == 'd14dd26a37cecc30fdd65700bfb55b23') {
$obj_array['gateway_key'] = 'd14dd26a47cecc30fdd65700bfb67b34';
}
- if(Ninja::isSelfHost() && $obj_array['gateway_key'] == 'd14dd26a47cecc30fdd65700bfb67b34'){
+ if (Ninja::isSelfHost() && $obj_array['gateway_key'] == 'd14dd26a47cecc30fdd65700bfb67b34') {
$obj_array['gateway_key'] = 'd14dd26a37cecc30fdd65700bfb55b23';
- }
-
+ }
}
- if(array_key_exists('deleted_at', $obj_array) && $obj_array['deleted_at'] > 1){
+ if (array_key_exists('deleted_at', $obj_array) && $obj_array['deleted_at'] > 1) {
$obj_array['deleted_at'] = now();
}
$activity_invitation_key = false;
- if($class == 'App\Models\Activity'){
-
- if(isset($obj->invitation_id)){
-
- if(isset($obj->invoice_id))
+ if ($class == 'App\Models\Activity') {
+ if (isset($obj->invitation_id)) {
+ if (isset($obj->invoice_id)) {
$activity_invitation_key = 'invoice_invitations';
- elseif(isset($obj->quote_id))
+ } elseif (isset($obj->quote_id)) {
$activity_invitation_key = 'quote_invitations';
- elseif(isset($obj->credit_id))
+ } elseif (isset($obj->credit_id)) {
$activity_invitation_key = 'credit_invitations';
-
+ }
}
$obj_array['account_id'] = $this->account->id;
-
}
/* Transform old keys to new keys */
- foreach($transforms as $transform)
- {
- foreach($transform as $key => $value)
- {
- if($class == 'App\Models\Activity' && $activity_invitation_key && $key == 'invitations'){
+ foreach ($transforms as $transform) {
+ foreach ($transform as $key => $value) {
+ if ($class == 'App\Models\Activity' && $activity_invitation_key && $key == 'invitations') {
$key = $activity_invitation_key;
}
$obj_array["{$value}"] = $this->transformId($key, $obj->{$value});
- }
+ }
}
- if($class == 'App\Models\CompanyGateway') {
+ if ($class == 'App\Models\CompanyGateway') {
$obj_array['config'] = encrypt($obj_array['config']);
}
@@ -1433,105 +1390,90 @@ class CompanyImport implements ShouldQueue
$new_obj->save(['timestamps' => false]);
$this->ids["{$object_property}"]["{$obj->hashed_id}"] = $new_obj->id;
-
}
$class::reguard();
-
-
}
private function genericImportWithoutCompany($class, $unset, $transforms, $object_property, $match_key)
{
-
$class::unguard();
//foreach($this->backup_file->{$object_property} as $obj)
- foreach((object)$this->getObject($object_property) as $obj)
- {
-
- if(is_null($obj))
+ foreach ((object)$this->getObject($object_property) as $obj) {
+ if (is_null($obj)) {
continue;
+ }
/* Remove unwanted keys*/
$obj_array = (array)$obj;
- foreach($unset as $un){
+ foreach ($unset as $un) {
unset($obj_array[$un]);
}
/* Transform old keys to new keys */
- foreach($transforms as $transform)
- {
- foreach($transform as $key => $value)
- {
+ foreach ($transforms as $transform) {
+ foreach ($transform as $key => $value) {
$obj_array["{$value}"] = $this->transformId($key, $obj->{$value});
- }
+ }
}
- if(array_key_exists('deleted_at', $obj_array) && $obj_array['deleted_at'] > 1){
+ if (array_key_exists('deleted_at', $obj_array) && $obj_array['deleted_at'] > 1) {
$obj_array['deleted_at'] = now();
}
/* New to convert product ids from old hashes to new hashes*/
- if($class == 'App\Models\Subscription'){
- $obj_array['product_ids'] = $this->recordProductIds($obj_array['product_ids']);
- $obj_array['recurring_product_ids'] = $this->recordProductIds($obj_array['recurring_product_ids']);
- $obj_array['webhook_configuration'] = json_encode($obj_array['webhook_configuration']);
+ if ($class == 'App\Models\Subscription') {
+ $obj_array['product_ids'] = $this->recordProductIds($obj_array['product_ids']);
+ $obj_array['recurring_product_ids'] = $this->recordProductIds($obj_array['recurring_product_ids']);
+ $obj_array['webhook_configuration'] = json_encode($obj_array['webhook_configuration']);
}
$new_obj = $class::firstOrNew(
- [$match_key => $obj->{$match_key}],
- $obj_array,
- );
+ [$match_key => $obj->{$match_key}],
+ $obj_array,
+ );
$new_obj->save(['timestamps' => false]);
- if($new_obj instanceof CompanyLedger){
-
- }
- else
+ if ($new_obj instanceof CompanyLedger) {
+ } else {
$this->ids["{$object_property}"]["{$obj->hashed_id}"] = $new_obj->id;
-
+ }
}
$class::reguard();
-
}
/* Ensure if no number is set, we don't overwrite a record with an existing number */
private function genericImport($class, $unset, $transforms, $object_property, $match_key)
{
-
$class::unguard();
$x = 0;
- foreach((object)$this->getObject($object_property) as $obj)
- {
-
+ foreach ((object)$this->getObject($object_property) as $obj) {
/* Remove unwanted keys*/
$obj_array = (array)$obj;
- foreach($unset as $un){
+ foreach ($unset as $un) {
unset($obj_array[$un]);
}
/* Transform old keys to new keys */
- foreach($transforms as $transform)
- {
- foreach($transform as $key => $value)
- {
+ foreach ($transforms as $transform) {
+ foreach ($transform as $key => $value) {
$obj_array["{$value}"] = $this->transformId($key, $obj->{$value});
- }
+ }
}
- if(array_key_exists('deleted_at', $obj_array) && $obj_array['deleted_at'] > 1){
+ if (array_key_exists('deleted_at', $obj_array) && $obj_array['deleted_at'] > 1) {
$obj_array['deleted_at'] = now();
}
/* New to convert product ids from old hashes to new hashes*/
- if($class == 'App\Models\Subscription'){
-
- if(array_key_exists('company', $obj_array))
+ if ($class == 'App\Models\Subscription') {
+ if (array_key_exists('company', $obj_array)) {
unset($obj_array['company']);
+ }
$obj_array['webhook_configuration'] = (array)$obj_array['webhook_configuration'];
$obj_array['recurring_product_ids'] = '';
@@ -1539,147 +1481,128 @@ class CompanyImport implements ShouldQueue
}
/* Expenses that don't have a number will not be inserted - so need to override here*/
- if($class == 'App\Models\Expense' && is_null($obj->{$match_key})){
+ if ($class == 'App\Models\Expense' && is_null($obj->{$match_key})) {
$new_obj = new Expense();
$new_obj->company_id = $this->company->id;
$new_obj->fill($obj_array);
$new_obj->save(['timestamps' => false]);
$new_obj->number = $this->getNextExpenseNumber($new_obj);
-
- }
- elseif($class == 'App\Models\Invoice' && is_null($obj->{$match_key})){
+ } elseif ($class == 'App\Models\Invoice' && is_null($obj->{$match_key})) {
$new_obj = new Invoice();
$new_obj->company_id = $this->company->id;
$new_obj->fill($obj_array);
$new_obj->save(['timestamps' => false]);
- $new_obj->number = $this->getNextInvoiceNumber($client = Client::withTrashed()->find($obj_array['client_id']),$new_obj);
- }
- elseif($class == 'App\Models\PurchaseOrder' && is_null($obj->{$match_key})){
+ $new_obj->number = $this->getNextInvoiceNumber($client = Client::withTrashed()->find($obj_array['client_id']), $new_obj);
+ } elseif ($class == 'App\Models\PurchaseOrder' && is_null($obj->{$match_key})) {
$new_obj = new PurchaseOrder();
$new_obj->company_id = $this->company->id;
$new_obj->fill($obj_array);
$new_obj->save(['timestamps' => false]);
$new_obj->number = $this->getNextPurchaseOrderNumber($new_obj);
- }
- elseif($class == 'App\Models\Payment' && is_null($obj->{$match_key})){
+ } elseif ($class == 'App\Models\Payment' && is_null($obj->{$match_key})) {
$new_obj = new Payment();
$new_obj->company_id = $this->company->id;
$new_obj->fill($obj_array);
$new_obj->save(['timestamps' => false]);
$new_obj->number = $this->getNextPaymentNumber($client = Client::withTrashed()->find($obj_array['client_id']), $new_obj);
- }
- elseif($class == 'App\Models\Quote' && is_null($obj->{$match_key})){
+ } elseif ($class == 'App\Models\Quote' && is_null($obj->{$match_key})) {
$new_obj = new Quote();
$new_obj->company_id = $this->company->id;
$new_obj->fill($obj_array);
$new_obj->save(['timestamps' => false]);
$new_obj->number = $this->getNextQuoteNumber($client = Client::withTrashed()->find($obj_array['client_id']), $new_obj);
- }
- elseif($class == 'App\Models\ClientContact'){
+ } elseif ($class == 'App\Models\ClientContact') {
$new_obj = new ClientContact();
$new_obj->company_id = $this->company->id;
$new_obj->fill($obj_array);
$new_obj->save(['timestamps' => false]);
- }
- elseif($class == 'App\Models\VendorContact'){
+ } elseif ($class == 'App\Models\VendorContact') {
$new_obj = new VendorContact();
$new_obj->company_id = $this->company->id;
$new_obj->fill($obj_array);
$new_obj->save(['timestamps' => false]);
- }
- elseif($class == 'App\Models\RecurringExpense' && is_null($obj->{$match_key})){
+ } elseif ($class == 'App\Models\RecurringExpense' && is_null($obj->{$match_key})) {
$new_obj = new RecurringExpense();
$new_obj->company_id = $this->company->id;
$new_obj->fill($obj_array);
$new_obj->save(['timestamps' => false]);
- $new_obj->number = $this->getNextRecurringExpenseNumber($new_obj);
- }
- elseif($class == 'App\Models\Project' && is_null($obj->{$match_key})){
+ $new_obj->number = $this->getNextRecurringExpenseNumber($new_obj);
+ } elseif ($class == 'App\Models\Project' && is_null($obj->{$match_key})) {
$new_obj = new Project();
$new_obj->company_id = $this->company->id;
$new_obj->fill($obj_array);
$new_obj->save(['timestamps' => false]);
- $new_obj->number = $this->getNextProjectNumber($new_obj);
- }
- elseif($class == 'App\Models\Task' && is_null($obj->{$match_key})){
+ $new_obj->number = $this->getNextProjectNumber($new_obj);
+ } elseif ($class == 'App\Models\Task' && is_null($obj->{$match_key})) {
$new_obj = new Task();
$new_obj->company_id = $this->company->id;
$new_obj->fill($obj_array);
$new_obj->save(['timestamps' => false]);
- $new_obj->number = $this->getNextTaskNumber($new_obj);
- }
- elseif($class == 'App\Models\Vendor' && is_null($obj->{$match_key})){
+ $new_obj->number = $this->getNextTaskNumber($new_obj);
+ } elseif ($class == 'App\Models\Vendor' && is_null($obj->{$match_key})) {
$new_obj = new Vendor();
$new_obj->company_id = $this->company->id;
$new_obj->fill($obj_array);
$new_obj->save(['timestamps' => false]);
- $new_obj->number = $this->getNextVendorNumber($new_obj);
- }
- elseif($class == 'App\Models\CompanyLedger'){
+ $new_obj->number = $this->getNextVendorNumber($new_obj);
+ } elseif ($class == 'App\Models\CompanyLedger') {
$new_obj = $class::firstOrNew(
- [$match_key => $obj->{$match_key}, 'company_id' => $this->company->id],
- $obj_array,
- );
- }
- elseif($class == 'App\Models\BankIntegration'){
+ [$match_key => $obj->{$match_key}, 'company_id' => $this->company->id],
+ $obj_array,
+ );
+ } elseif ($class == 'App\Models\BankIntegration') {
$new_obj = new BankIntegration();
$new_obj->company_id = $this->company->id;
$new_obj->account_id = $this->account->id;
$new_obj->fill($obj_array);
$new_obj->save(['timestamps' => false]);
- }
- elseif($class == 'App\Models\BankTransaction'){
-
+ } elseif ($class == 'App\Models\BankTransaction') {
$new_obj = new BankTransaction();
$new_obj->company_id = $this->company->id;
- $obj_array['invoice_ids'] = collect(explode(",",$obj_array['invoice_ids']))->map(function ($id) {
- return $this->transformId('invoices', $id);
- })->map(function ($encodeable){
+ $obj_array['invoice_ids'] = collect(explode(",", $obj_array['invoice_ids']))->map(function ($id) {
+ return $this->transformId('invoices', $id);
+ })->map(function ($encodeable) {
return $this->encodePrimaryKey($encodeable);
})->implode(",");
$new_obj->fill($obj_array);
$new_obj->save(['timestamps' => false]);
- }
- else{
+ } else {
$new_obj = $class::withTrashed()->firstOrNew(
- [$match_key => $obj->{$match_key}, 'company_id' => $this->company->id],
- $obj_array,
- );
- }
+ [$match_key => $obj->{$match_key}, 'company_id' => $this->company->id],
+ $obj_array,
+ );
+ }
$new_obj->save(['timestamps' => false]);
- if($new_obj instanceof CompanyLedger){
- }
- else
+ if ($new_obj instanceof CompanyLedger) {
+ } else {
$this->ids["{$object_property}"]["{$obj->hashed_id}"] = $new_obj->id;
-
+ }
}
$class::reguard();
-
}
private function recordProductIds($ids)
{
-
$id_array = explode(",", $ids);
$tmp_arr = [];
- foreach($id_array as $id) {
-
- if(!$id)
+ foreach ($id_array as $id) {
+ if (!$id) {
continue;
+ }
$id = $this->decodePrimaryKey($id);
nlog($id);
$tmp_arr[] = $this->encodePrimaryKey($this->transformId('products', $id));
- }
+ }
return implode(",", $tmp_arr);
}
@@ -1689,19 +1612,19 @@ class CompanyImport implements ShouldQueue
* In the case of users - we need to check if the system
* is attempting to migrate resources above their quota,
*
- * ie. > 50 clients or more than 1 user
+ * ie. > 50 clients or more than 1 user
*/
private function transformId(string $resource, ?string $old): ?int
{
- if(empty($old))
+ if (empty($old)) {
return null;
+ }
- if ($resource == 'users' && $this->force_user_coalesce){
+ if ($resource == 'users' && $this->force_user_coalesce) {
return $this->company_owner->id;
}
if (! array_key_exists($resource, $this->ids)) {
-
$this->sendImportMail("The Import failed due to missing data in the import file. Resource {$resource} not available.");
throw new \Exception("Resource {$resource} not available.");
@@ -1713,8 +1636,9 @@ class CompanyImport implements ShouldQueue
nlog("If we are missing a user - default to the company owner");
- if($resource == 'users')
+ if ($resource == 'users') {
return $this->company_owner->id;
+ }
$this->sendImportMail("The Import failed due to missing data in the import file. Resource {$resource} not available.");
@@ -1727,8 +1651,8 @@ class CompanyImport implements ShouldQueue
}
- private function sendImportMail($message){
-
+ private function sendImportMail($message)
+ {
App::forgetInstance('translator');
$t = app('translator');
$t->replace(Ninja::transformTranslations($this->company->settings));
@@ -1741,6 +1665,5 @@ class CompanyImport implements ShouldQueue
$nmo->settings = $this->company->settings;
$nmo->to_user = $this->company->owner();
NinjaMailerJob::dispatch($nmo);
-
}
-}
\ No newline at end of file
+}
diff --git a/app/Jobs/Company/CreateCompany.php b/app/Jobs/Company/CreateCompany.php
index 1d6a7cb1efba..78dcff40618b 100644
--- a/app/Jobs/Company/CreateCompany.php
+++ b/app/Jobs/Company/CreateCompany.php
@@ -18,7 +18,6 @@ use App\Models\Company;
use App\Utils\Ninja;
use App\Utils\Traits\MakesHash;
use Illuminate\Foundation\Bus\Dispatchable;
-use Illuminate\Http\Request;
class CreateCompany
{
diff --git a/app/Jobs/Credit/ApplyCreditPayment.php b/app/Jobs/Credit/ApplyCreditPayment.php
index 398e5a7eae8d..77e875ccf832 100644
--- a/app/Jobs/Credit/ApplyCreditPayment.php
+++ b/app/Jobs/Credit/ApplyCreditPayment.php
@@ -51,7 +51,6 @@ class ApplyCreditPayment implements ShouldQueue
*/
public function handle()
{
-
/* Update Pivot Record amount */
$this->payment->credits->each(function ($cred) {
if ($cred->id == $this->credit->id) {
@@ -66,7 +65,6 @@ class ApplyCreditPayment implements ShouldQueue
$credit_balance = $this->credit->balance;
if ($this->amount == $credit_balance) { //total credit applied.
-
$this->credit
->service()
->markSent()
@@ -75,7 +73,6 @@ class ApplyCreditPayment implements ShouldQueue
->updatePaidToDate($this->amount)
->save();
} elseif ($this->amount < $credit_balance) { //compare number appropriately
-
$this->credit
->service()
->markSent()
diff --git a/app/Jobs/Credit/ZipCredits.php b/app/Jobs/Credit/ZipCredits.php
index 1b56f7ff5a6e..b649d6f7ee85 100644
--- a/app/Jobs/Credit/ZipCredits.php
+++ b/app/Jobs/Credit/ZipCredits.php
@@ -19,15 +19,12 @@ use App\Libraries\MultiDB;
use App\Mail\DownloadCredits;
use App\Models\Company;
use App\Models\User;
-use App\Utils\TempFile;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
-use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Storage;
-use ZipArchive;
class ZipCredits implements ShouldQueue
{
diff --git a/app/Jobs/Cron/AutoBill.php b/app/Jobs/Cron/AutoBill.php
index 58d7435bd737..60f0c2572d76 100644
--- a/app/Jobs/Cron/AutoBill.php
+++ b/app/Jobs/Cron/AutoBill.php
@@ -13,9 +13,9 @@ namespace App\Jobs\Cron;
use App\Libraries\MultiDB;
use App\Models\Invoice;
-use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
+use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
diff --git a/app/Jobs/Cron/AutoBillCron.php b/app/Jobs/Cron/AutoBillCron.php
index 242bb0050278..8879c6930776 100644
--- a/app/Jobs/Cron/AutoBillCron.php
+++ b/app/Jobs/Cron/AutoBillCron.php
@@ -11,11 +11,8 @@
namespace App\Jobs\Cron;
-use App\Jobs\Cron\AutoBill;
-use App\Jobs\RecurringInvoice\SendRecurring;
use App\Libraries\MultiDB;
use App\Models\Invoice;
-use App\Models\RecurringInvoice;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Carbon;
@@ -63,14 +60,11 @@ class AutoBillCron
nlog($auto_bill_partial_invoices->count().' partial invoices to auto bill');
$auto_bill_partial_invoices->chunk(400, function ($invoices) {
-
- foreach($invoices as $invoice)
- {
+ foreach ($invoices as $invoice) {
AutoBill::dispatch($invoice->id, false);
}
sleep(2);
-
});
$auto_bill_invoices = Invoice::whereDate('due_date', '<=', now())
@@ -87,14 +81,11 @@ class AutoBillCron
nlog($auto_bill_invoices->count().' full invoices to auto bill');
$auto_bill_invoices->chunk(400, function ($invoices) {
-
- foreach($invoices as $invoice)
- {
+ foreach ($invoices as $invoice) {
AutoBill::dispatch($invoice->id, false);
}
sleep(2);
-
});
} else {
//multiDB environment, need to
@@ -114,10 +105,8 @@ class AutoBillCron
nlog($auto_bill_partial_invoices->count()." partial invoices to auto bill db = {$db}");
- $auto_bill_partial_invoices->chunk(400, function ($invoices) use($db){
-
- foreach($invoices as $invoice)
- {
+ $auto_bill_partial_invoices->chunk(400, function ($invoices) use ($db) {
+ foreach ($invoices as $invoice) {
AutoBill::dispatch($invoice->id, $db);
}
@@ -137,15 +126,12 @@ class AutoBillCron
nlog($auto_bill_invoices->count()." full invoices to auto bill db = {$db}");
- $auto_bill_invoices->chunk(400, function ($invoices) use($db){
-
- foreach($invoices as $invoice)
- {
+ $auto_bill_invoices->chunk(400, function ($invoices) use ($db) {
+ foreach ($invoices as $invoice) {
AutoBill::dispatch($invoice->id, $db);
}
sleep(2);
-
});
}
diff --git a/app/Jobs/Cron/CompanyRecurringCron.php b/app/Jobs/Cron/CompanyRecurringCron.php
index a50663daebb5..a46d84e5af44 100644
--- a/app/Jobs/Cron/CompanyRecurringCron.php
+++ b/app/Jobs/Cron/CompanyRecurringCron.php
@@ -11,12 +11,10 @@
namespace App\Jobs\Cron;
-use App\Jobs\RecurringInvoice\SendRecurring;
use App\Libraries\MultiDB;
use App\Models\Company;
use App\Models\RecurringInvoice;
use Illuminate\Foundation\Bus\Dispatchable;
-use Illuminate\Support\Carbon;
/*@not used*/
@@ -44,27 +42,24 @@ class CompanyRecurringCron
{
//multiDB environment, need to
foreach (MultiDB::$dbs as $db) {
-
MultiDB::setDB($db);
Company::where('is_disabled', 0)
- ->whereHas('recurring_invoices', function ($query){
- $query->where('next_send_date', '<=', now()->toDateTimeString())
- ->whereNotNull('next_send_date')
- ->whereNull('deleted_at')
- ->where('is_deleted', false)
- ->where('status_id', RecurringInvoice::STATUS_ACTIVE)
- ->where('remaining_cycles', '!=', '0')
- ->whereHas('client', function ($query) {
+ ->whereHas('recurring_invoices', function ($query) {
+ $query->where('next_send_date', '<=', now()->toDateTimeString())
+ ->whereNotNull('next_send_date')
+ ->whereNull('deleted_at')
+ ->where('is_deleted', false)
+ ->where('status_id', RecurringInvoice::STATUS_ACTIVE)
+ ->where('remaining_cycles', '!=', '0')
+ ->whereHas('client', function ($query) {
$query->where('is_deleted', 0)
->where('deleted_at', null);
- });
- })
- ->cursor()->each(function ($company){
-
- SendCompanyRecurring::dispatch($company->id, $company->db);
-
- });
+ });
+ })
+ ->cursor()->each(function ($company) {
+ SendCompanyRecurring::dispatch($company->id, $company->db);
+ });
}
}
}
diff --git a/app/Jobs/Cron/RecurringExpensesCron.php b/app/Jobs/Cron/RecurringExpensesCron.php
index c6733f64757d..773a97e26ebe 100644
--- a/app/Jobs/Cron/RecurringExpensesCron.php
+++ b/app/Jobs/Cron/RecurringExpensesCron.php
@@ -46,7 +46,6 @@ class RecurringExpensesCron
nlog('Sending recurring expenses '.Carbon::now()->format('Y-m-d h:i:s'));
if (! config('ninja.db.multi_db_enabled')) {
-
$recurring_expenses = RecurringExpense::where('next_send_date', '<=', now()->toDateTimeString())
->whereNotNull('next_send_date')
->whereNull('deleted_at')
@@ -67,34 +66,31 @@ class RecurringExpensesCron
$this->generateExpense($recurring_expense);
}
});
-
} else {
//multiDB environment, need to
foreach (MultiDB::$dbs as $db) {
MultiDB::setDB($db);
- $recurring_expenses = RecurringExpense::where('next_send_date', '<=', now()->toDateTimeString())
- ->whereNotNull('next_send_date')
- ->whereNull('deleted_at')
- ->where('status_id', RecurringInvoice::STATUS_ACTIVE)
- ->where('remaining_cycles', '!=', '0')
- ->whereHas('company', function ($query) {
- $query->where('is_disabled', 0);
- })
- ->with('company')
- ->cursor();
+ $recurring_expenses = RecurringExpense::where('next_send_date', '<=', now()->toDateTimeString())
+ ->whereNotNull('next_send_date')
+ ->whereNull('deleted_at')
+ ->where('status_id', RecurringInvoice::STATUS_ACTIVE)
+ ->where('remaining_cycles', '!=', '0')
+ ->whereHas('company', function ($query) {
+ $query->where('is_disabled', 0);
+ })
+ ->with('company')
+ ->cursor();
- nlog(now()->format('Y-m-d').' Generating Recurring Expenses. Count = '.$recurring_expenses->count());
-
- $recurring_expenses->each(function ($recurring_expense, $key) {
- nlog('Current date = '.now()->format('Y-m-d').' Recurring date = '.$recurring_expense->next_send_date);
-
- if (! $recurring_expense->company->is_disabled) {
- $this->generateExpense($recurring_expense);
- }
- });
+ nlog(now()->format('Y-m-d').' Generating Recurring Expenses. Count = '.$recurring_expenses->count());
+ $recurring_expenses->each(function ($recurring_expense, $key) {
+ nlog('Current date = '.now()->format('Y-m-d').' Recurring date = '.$recurring_expense->next_send_date);
+ if (! $recurring_expense->company->is_disabled) {
+ $this->generateExpense($recurring_expense);
+ }
+ });
}
}
}
diff --git a/app/Jobs/Cron/RecurringInvoicesCron.php b/app/Jobs/Cron/RecurringInvoicesCron.php
index 48dd442d402f..69bf17a41fb4 100644
--- a/app/Jobs/Cron/RecurringInvoicesCron.php
+++ b/app/Jobs/Cron/RecurringInvoicesCron.php
@@ -104,7 +104,6 @@ class RecurringInvoicesCron
nlog(now()->format('Y-m-d').' Sending Recurring Invoices. Count = '.$recurring_invoices->count());
$recurring_invoices->each(function ($recurring_invoice, $key) {
-
nlog("Trying to send {$recurring_invoice->number}");
if ($recurring_invoice->company->stop_on_unpaid_recurring) {
@@ -123,6 +122,5 @@ class RecurringInvoicesCron
}
nlog("Recurring invoice send duration " . $start . " - " . Carbon::now()->format('Y-m-d h:i:s'));
-
}
}
diff --git a/app/Jobs/Cron/SendCompanyRecurring.php b/app/Jobs/Cron/SendCompanyRecurring.php
index 14c9c063ddd1..6b1d31e7dae4 100644
--- a/app/Jobs/Cron/SendCompanyRecurring.php
+++ b/app/Jobs/Cron/SendCompanyRecurring.php
@@ -16,7 +16,6 @@ use App\Libraries\MultiDB;
use App\Models\Company;
use App\Models\RecurringInvoice;
use Illuminate\Foundation\Bus\Dispatchable;
-use Illuminate\Support\Carbon;
/*@not used*/
@@ -38,11 +37,9 @@ class SendCompanyRecurring
public function __construct($company_id, $db)
{
-
$this->company_id = $company_id;
$this->db = $db;
-
}
/**
@@ -52,40 +49,36 @@ class SendCompanyRecurring
*/
public function handle() : void
{
-
MultiDB::setDB($this->db);
$recurring_invoices = Company::where('id', $this->company_id)
->where('is_disabled', 0)
- ->whereHas('recurring_invoices', function ($query){
- $query->where('next_send_date', '<=', now()->toDateTimeString())
- ->whereNotNull('next_send_date')
- ->whereNull('deleted_at')
- ->where('is_deleted', false)
- ->where('status_id', RecurringInvoice::STATUS_ACTIVE)
- ->where('remaining_cycles', '!=', '0')
- ->whereHas('client', function ($query) {
- $query->where('is_deleted', 0)
- ->where('deleted_at', null);
- });
- })
- ->cursor()->each(function ($recurring_invoice){
+ ->whereHas('recurring_invoices', function ($query) {
+ $query->where('next_send_date', '<=', now()->toDateTimeString())
+ ->whereNotNull('next_send_date')
+ ->whereNull('deleted_at')
+ ->where('is_deleted', false)
+ ->where('status_id', RecurringInvoice::STATUS_ACTIVE)
+ ->where('remaining_cycles', '!=', '0')
+ ->whereHas('client', function ($query) {
+ $query->where('is_deleted', 0)
+ ->where('deleted_at', null);
+ });
+ })
+ ->cursor()->each(function ($recurring_invoice) {
+ nlog("Trying to send {$recurring_invoice->number}");
- nlog("Trying to send {$recurring_invoice->number}");
+ if ($recurring_invoice->company->stop_on_unpaid_recurring) {
+ if ($recurring_invoice->invoices()->whereIn('status_id', [2, 3])->where('is_deleted', 0)->where('balance', '>', 0)->exists()) {
+ return;
+ }
+ }
- if ($recurring_invoice->company->stop_on_unpaid_recurring) {
- if ($recurring_invoice->invoices()->whereIn('status_id', [2, 3])->where('is_deleted', 0)->where('balance', '>', 0)->exists()) {
- return;
- }
- }
-
- try {
- (new SendRecurring($recurring_invoice, $recurring_invoice->company->db))->handle();
- } catch (\Exception $e) {
- nlog("Unable to sending recurring invoice {$recurring_invoice->id} ".$e->getMessage());
- }
-
- });
-
+ try {
+ (new SendRecurring($recurring_invoice, $recurring_invoice->company->db))->handle();
+ } catch (\Exception $e) {
+ nlog("Unable to sending recurring invoice {$recurring_invoice->id} ".$e->getMessage());
+ }
+ });
}
}
diff --git a/app/Jobs/Cron/SubscriptionCron.php b/app/Jobs/Cron/SubscriptionCron.php
index 186a05722c99..8fc2412bf630 100644
--- a/app/Jobs/Cron/SubscriptionCron.php
+++ b/app/Jobs/Cron/SubscriptionCron.php
@@ -15,7 +15,6 @@ use App\Libraries\MultiDB;
use App\Models\Invoice;
use App\Utils\Traits\SubscriptionHooker;
use Illuminate\Foundation\Bus\Dispatchable;
-use Illuminate\Support\Carbon;
class SubscriptionCron
{
@@ -41,11 +40,10 @@ class SubscriptionCron
nlog('Subscription Cron');
if (! config('ninja.db.multi_db_enabled')) {
-
$invoices = Invoice::where('is_deleted', 0)
->whereIn('status_id', [Invoice::STATUS_SENT, Invoice::STATUS_PARTIAL])
->where('balance', '>', 0)
- ->where('is_proforma',0)
+ ->where('is_proforma', 0)
->whereDate('due_date', '<=', now()->addDay()->startOfDay())
->whereNull('deleted_at')
->whereNotNull('subscription_id')
@@ -65,8 +63,6 @@ class SubscriptionCron
//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?
});
-
-
} else {
//multiDB environment, need to
foreach (MultiDB::$dbs as $db) {
@@ -75,7 +71,7 @@ class SubscriptionCron
$invoices = Invoice::where('is_deleted', 0)
->whereIn('status_id', [Invoice::STATUS_SENT, Invoice::STATUS_PARTIAL])
->where('balance', '>', 0)
- ->where('is_proforma',0)
+ ->where('is_proforma', 0)
->whereDate('due_date', '<=', now()->addDay()->startOfDay())
->whereNull('deleted_at')
->whereNotNull('subscription_id')
@@ -95,10 +91,7 @@ class SubscriptionCron
//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/Document/ZipDocuments.php b/app/Jobs/Document/ZipDocuments.php
index 4ee54338890f..c713e778e599 100644
--- a/app/Jobs/Document/ZipDocuments.php
+++ b/app/Jobs/Document/ZipDocuments.php
@@ -11,18 +11,15 @@
namespace App\Jobs\Document;
-use App\Jobs\Entity\CreateEntityPdf;
use App\Jobs\Mail\NinjaMailerJob;
use App\Jobs\Mail\NinjaMailerObject;
use App\Jobs\Util\UnlinkFile;
use App\Libraries\MultiDB;
use App\Mail\DownloadDocuments;
-use App\Mail\DownloadInvoices;
use App\Models\Company;
use App\Models\Document;
use App\Models\User;
use App\Utils\Ninja;
-use App\Utils\TempFile;
use App\Utils\Traits\MakesDates;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
@@ -31,9 +28,7 @@ use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\App;
-use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Storage;
-use ZipArchive;
class ZipDocuments implements ShouldQueue
{
@@ -128,7 +123,7 @@ class ZipDocuments implements ShouldQueue
$entity = ctrans('texts.document');
- if(isset($document->documentable)){
+ if (isset($document->documentable)) {
$entity = $document->documentable->translate_entity();
}
diff --git a/app/Jobs/Entity/CreateEntityPdf.php b/app/Jobs/Entity/CreateEntityPdf.php
index 6c12b1c1ec8b..b59e3529fdb4 100644
--- a/app/Jobs/Entity/CreateEntityPdf.php
+++ b/app/Jobs/Entity/CreateEntityPdf.php
@@ -34,7 +34,6 @@ use App\Utils\Traits\MakesHash;
use App\Utils\Traits\MakesInvoiceHtml;
use App\Utils\Traits\NumberFormatter;
use App\Utils\Traits\Pdf\PageNumbering;
-use App\Utils\Traits\Pdf\PDF;
use App\Utils\Traits\Pdf\PdfMaker;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
@@ -42,9 +41,7 @@ use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\App;
-use Illuminate\Support\Facades\Lang;
use Illuminate\Support\Facades\Storage;
-use setasign\Fpdi\PdfParser\StreamReader;
class CreateEntityPdf implements ShouldQueue
{
diff --git a/app/Jobs/Entity/CreateRawPdf.php b/app/Jobs/Entity/CreateRawPdf.php
index 178ab18f97ad..ebd2704c894f 100644
--- a/app/Jobs/Entity/CreateRawPdf.php
+++ b/app/Jobs/Entity/CreateRawPdf.php
@@ -13,7 +13,6 @@ namespace App\Jobs\Entity;
use App\Exceptions\FilePermissionsFailure;
use App\Libraries\MultiDB;
-use App\Models\Account;
use App\Models\Credit;
use App\Models\CreditInvitation;
use App\Models\Design;
@@ -41,8 +40,6 @@ use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\App;
-use Illuminate\Support\Facades\Lang;
-use Illuminate\Support\Facades\Storage;
class CreateRawPdf implements ShouldQueue
{
@@ -90,7 +87,6 @@ class CreateRawPdf implements ShouldQueue
public function handle()
{
-
/* Forget the singleton*/
App::forgetInstance('translator');
diff --git a/app/Jobs/Entity/EmailEntity.php b/app/Jobs/Entity/EmailEntity.php
index dda2c0711fab..cdf5235dbd6f 100644
--- a/app/Jobs/Entity/EmailEntity.php
+++ b/app/Jobs/Entity/EmailEntity.php
@@ -83,7 +83,6 @@ class EmailEntity implements ShouldQueue
$this->html_engine = new HtmlEngine($invitation);
$this->template_data = $template_data;
-
}
/**
diff --git a/app/Jobs/Import/CSVIngest.php b/app/Jobs/Import/CSVIngest.php
index 879470d1bf75..cdeaab860c28 100644
--- a/app/Jobs/Import/CSVIngest.php
+++ b/app/Jobs/Import/CSVIngest.php
@@ -81,7 +81,6 @@ class CSVIngest implements ShouldQueue
$engine->finalizeImport();
$this->checkContacts();
-
}
private function checkContacts()
@@ -106,23 +105,17 @@ class CSVIngest implements ShouldQueue
$new_contact->save();
}
- Client::with('contacts')->where('company_id', $this->company->id)->cursor()->each(function ($client){
-
- $contact = $client->contacts()->first();
- $contact->is_primary = true;
- $contact->save();
-
+ Client::with('contacts')->where('company_id', $this->company->id)->cursor()->each(function ($client) {
+ $contact = $client->contacts()->first();
+ $contact->is_primary = true;
+ $contact->save();
});
- Vendor::with('contacts')->where('company_id', $this->company->id)->cursor()->each(function ($vendor){
-
- $contact = $vendor->contacts()->first();
- $contact->is_primary = true;
- $contact->save();
-
+ Vendor::with('contacts')->where('company_id', $this->company->id)->cursor()->each(function ($vendor) {
+ $contact = $vendor->contacts()->first();
+ $contact->is_primary = true;
+ $contact->save();
});
-
-
}
private function bootEngine()
diff --git a/app/Jobs/Inventory/AdjustProductInventory.php b/app/Jobs/Inventory/AdjustProductInventory.php
index 95ba7cc9150c..f4772ca9010f 100644
--- a/app/Jobs/Inventory/AdjustProductInventory.php
+++ b/app/Jobs/Inventory/AdjustProductInventory.php
@@ -20,7 +20,6 @@ use App\Models\Company;
use App\Models\Invoice;
use App\Models\Product;
use App\Utils\Traits\Notifications\UserNotifies;
-use App\Utils\Traits\NumberFormatter;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
@@ -64,11 +63,9 @@ class AdjustProductInventory implements ShouldQueue
public function handleDeletedInvoice()
{
+ MultiDB::setDb($this->company->db);
- MultiDB::setDb($this->company->db);
-
- foreach ($this->invoice->line_items as $item) {
-
+ foreach ($this->invoice->line_items as $item) {
$p = Product::where('product_key', $item->product_key)->where('company_id', $this->company->id)->first();
if (! $p) {
@@ -79,15 +76,13 @@ class AdjustProductInventory implements ShouldQueue
$p->saveQuietly();
}
-
}
public function handleRestoredInvoice()
{
+ MultiDB::setDb($this->company->db);
- MultiDB::setDb($this->company->db);
-
- foreach ($this->invoice->line_items as $item) {
+ foreach ($this->invoice->line_items as $item) {
$p = Product::where('product_key', $item->product_key)->where('company_id', $this->company->id)->first();
if (! $p) {
@@ -97,7 +92,6 @@ class AdjustProductInventory implements ShouldQueue
$p->in_stock_quantity -= $item->quantity;
$p->saveQuietly();
}
-
}
public function middleware()
@@ -148,17 +142,11 @@ class AdjustProductInventory implements ShouldQueue
$nmo->company = $this->company;
$nmo->settings = $this->company->settings;
- $this->company->company_users->each(function ($cu) use($product, $nmo){
-
- if($this->checkNotificationExists($cu, $product, ['inventory_all', 'inventory_user']))
- {
-
+ $this->company->company_users->each(function ($cu) use ($product, $nmo) {
+ if ($this->checkNotificationExists($cu, $product, ['inventory_all', 'inventory_user'])) {
$nmo->to_user = $cu->user;
NinjaMailerJob::dispatch($nmo);
-
}
-
});
-
}
}
diff --git a/app/Jobs/Invoice/BulkInvoiceJob.php b/app/Jobs/Invoice/BulkInvoiceJob.php
index 787663c63519..dfbdb18a7905 100644
--- a/app/Jobs/Invoice/BulkInvoiceJob.php
+++ b/app/Jobs/Invoice/BulkInvoiceJob.php
@@ -13,20 +13,6 @@ namespace App\Jobs\Invoice;
use App\Jobs\Entity\EmailEntity;
use App\Models\Invoice;
-use CleverIt\UBL\Invoice\Address;
-use CleverIt\UBL\Invoice\Contact;
-use CleverIt\UBL\Invoice\Country;
-use CleverIt\UBL\Invoice\Generator;
-use CleverIt\UBL\Invoice\Invoice as UBLInvoice;
-use CleverIt\UBL\Invoice\InvoiceLine;
-use CleverIt\UBL\Invoice\Item;
-use CleverIt\UBL\Invoice\LegalMonetaryTotal;
-use CleverIt\UBL\Invoice\Party;
-use CleverIt\UBL\Invoice\TaxCategory;
-use CleverIt\UBL\Invoice\TaxScheme;
-use CleverIt\UBL\Invoice\TaxSubTotal;
-use CleverIt\UBL\Invoice\TaxTotal;
-use Exception;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
diff --git a/app/Jobs/Invoice/CheckGatewayFee.php b/app/Jobs/Invoice/CheckGatewayFee.php
index 9fc58042e12a..e888f38489aa 100644
--- a/app/Jobs/Invoice/CheckGatewayFee.php
+++ b/app/Jobs/Invoice/CheckGatewayFee.php
@@ -29,7 +29,9 @@ class CheckGatewayFee implements ShouldQueue
* @param $invoice_id
* @param string $db
*/
- public function __construct(public int $invoice_id, public string $db){}
+ public function __construct(public int $invoice_id, public string $db)
+ {
+ }
/**
* Execute the job.
@@ -42,13 +44,12 @@ class CheckGatewayFee implements ShouldQueue
$i = Invoice::withTrashed()->find($this->invoice_id);
- if(!$i)
+ if (!$i) {
return;
-
- if($i->status_id == Invoice::STATUS_SENT)
- {
- $i->service()->removeUnpaidGatewayFees();
}
+ if ($i->status_id == Invoice::STATUS_SENT) {
+ $i->service()->removeUnpaidGatewayFees();
+ }
}
}
diff --git a/app/Jobs/Invoice/InvoiceCheckLateWebhook.php b/app/Jobs/Invoice/InvoiceCheckLateWebhook.php
index bb045cbd2544..0c99407d11b2 100644
--- a/app/Jobs/Invoice/InvoiceCheckLateWebhook.php
+++ b/app/Jobs/Invoice/InvoiceCheckLateWebhook.php
@@ -29,7 +29,9 @@ class InvoiceCheckLateWebhook implements ShouldQueue
/**
* Create a new job instance.
*/
- public function __construct() {}
+ public function __construct()
+ {
+ }
/**
* Execute the job.
@@ -40,8 +42,7 @@ class InvoiceCheckLateWebhook implements ShouldQueue
{
nlog("sending overdue webhooks for invoices");
- if (! config('ninja.db.multi_db_enabled')){
-
+ if (! config('ninja.db.multi_db_enabled')) {
$company_ids = Webhook::where('event_id', Webhook::EVENT_LATE_INVOICE)
->where('is_deleted', 0)
->pluck('company_id');
@@ -54,26 +55,19 @@ class InvoiceCheckLateWebhook implements ShouldQueue
->where('balance', '>', 0)
->whereIn('company_id', $company_ids)
->whereHas('client', function ($query) {
- $query->where('is_deleted', 0)
- ->where('deleted_at', null);
- })
- ->whereHas('company', function ($query){
+ $query->where('is_deleted', 0)
+ ->where('deleted_at', null);
+ })
+ ->whereHas('company', function ($query) {
$query->where('is_disabled', 0);
})
->whereBetween('due_date', [now()->subDay()->startOfDay(), now()->startOfDay()->subSecond()])
->cursor()
- ->each(function ($invoice){
-
- WebhookHandler::dispatch(Webhook::EVENT_LATE_INVOICE, $invoice, $invoice->company, 'client')->delay(now()->addSeconds(2));
-
+ ->each(function ($invoice) {
+ WebhookHandler::dispatch(Webhook::EVENT_LATE_INVOICE, $invoice, $invoice->company, 'client')->delay(now()->addSeconds(2));
});
-
- }
- else {
-
- foreach (MultiDB::$dbs as $db)
- {
-
+ } else {
+ foreach (MultiDB::$dbs as $db) {
MultiDB::setDB($db);
$company_ids = Webhook::where('event_id', Webhook::EVENT_LATE_INVOICE)
@@ -88,24 +82,18 @@ class InvoiceCheckLateWebhook implements ShouldQueue
->where('balance', '>', 0)
->whereIn('company_id', $company_ids)
->whereHas('client', function ($query) {
- $query->where('is_deleted', 0)
- ->where('deleted_at', null);
- })
- ->whereHas('company', function ($query){
+ $query->where('is_deleted', 0)
+ ->where('deleted_at', null);
+ })
+ ->whereHas('company', function ($query) {
$query->where('is_disabled', 0);
})
->whereBetween('due_date', [now()->subDay()->startOfDay(), now()->startOfDay()->subSecond()])
->cursor()
- ->each(function ($invoice){
-
- WebhookHandler::dispatch(Webhook::EVENT_LATE_INVOICE, $invoice, $invoice->company, 'client')->delay(now()->addSeconds(2));
-
+ ->each(function ($invoice) {
+ WebhookHandler::dispatch(Webhook::EVENT_LATE_INVOICE, $invoice, $invoice->company, 'client')->delay(now()->addSeconds(2));
});
-
-
}
}
-
}
-
}
diff --git a/app/Jobs/Invoice/ZipInvoices.php b/app/Jobs/Invoice/ZipInvoices.php
index 51d5989954f1..9a0d4752c3a8 100644
--- a/app/Jobs/Invoice/ZipInvoices.php
+++ b/app/Jobs/Invoice/ZipInvoices.php
@@ -19,15 +19,12 @@ use App\Libraries\MultiDB;
use App\Mail\DownloadInvoices;
use App\Models\Company;
use App\Models\User;
-use App\Utils\TempFile;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
-use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Storage;
-use ZipArchive;
class ZipInvoices implements ShouldQueue
{
diff --git a/app/Jobs/Ledger/ClientLedgerBalanceUpdate.php b/app/Jobs/Ledger/ClientLedgerBalanceUpdate.php
index b63fc65623db..731ec0872a77 100644
--- a/app/Jobs/Ledger/ClientLedgerBalanceUpdate.php
+++ b/app/Jobs/Ledger/ClientLedgerBalanceUpdate.php
@@ -52,11 +52,7 @@ class ClientLedgerBalanceUpdate implements ShouldQueue
MultiDB::setDb($this->company->db);
CompanyLedger::where('balance', 0)->where('client_id', $this->client->id)->orderBy('updated_at', 'ASC')->cursor()->each(function ($company_ledger) {
-
- if ($company_ledger->balance == 0)
- {
-
-
+ if ($company_ledger->balance == 0) {
$last_record = CompanyLedger::where('client_id', $company_ledger->client_id)
->where('company_id', $company_ledger->company_id)
->where('balance', '!=', 0)
@@ -69,13 +65,10 @@ class ClientLedgerBalanceUpdate implements ShouldQueue
->orderBy('id', 'DESC')
->first();
}
-
}
- $company_ledger->balance = $last_record->balance + $company_ledger->adjustment;
- $company_ledger->save();
-
+ $company_ledger->balance = $last_record->balance + $company_ledger->adjustment;
+ $company_ledger->save();
});
-
}
}
diff --git a/app/Jobs/Ledger/LedgerBalanceUpdate.php b/app/Jobs/Ledger/LedgerBalanceUpdate.php
index 5fc6ffabefdf..72a6a274ce7b 100644
--- a/app/Jobs/Ledger/LedgerBalanceUpdate.php
+++ b/app/Jobs/Ledger/LedgerBalanceUpdate.php
@@ -12,7 +12,6 @@
namespace App\Jobs\Ledger;
use App\Libraries\MultiDB;
-use App\Models\Company;
use App\Models\CompanyLedger;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
diff --git a/app/Jobs/Mail/NinjaMailerJob.php b/app/Jobs/Mail/NinjaMailerJob.php
index ecaf942e9e37..48844a200b28 100644
--- a/app/Jobs/Mail/NinjaMailerJob.php
+++ b/app/Jobs/Mail/NinjaMailerJob.php
@@ -15,7 +15,6 @@ use App\DataMapper\Analytics\EmailFailure;
use App\DataMapper\Analytics\EmailSuccess;
use App\Events\Invoice\InvoiceWasEmailedAndFailed;
use App\Events\Payment\PaymentWasEmailedAndFailed;
-use App\Jobs\Mail\NinjaMailerObject;
use App\Jobs\Util\SystemLogger;
use App\Libraries\Google\Google;
use App\Libraries\MultiDB;
@@ -34,9 +33,9 @@ use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\App;
+use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Mail;
use Turbo124\Beacon\Facades\LightLogs;
-use Illuminate\Support\Facades\Cache;
/*Multi Mailer implemented*/
@@ -66,11 +65,9 @@ class NinjaMailerJob implements ShouldQueue
public function __construct(NinjaMailerObject $nmo, bool $override = false)
{
-
$this->nmo = $nmo;
$this->override = $override;
-
}
public function backoff()
@@ -87,24 +84,23 @@ class NinjaMailerJob implements ShouldQueue
$this->company = Company::where('company_key', $this->nmo->company->company_key)->first();
/* If any pre conditions fail, we return early here */
- if(!$this->company || $this->preFlightChecksFail())
+ if (!$this->company || $this->preFlightChecksFail()) {
return;
+ }
/* Set the email driver */
$this->setMailDriver();
/* Run time we set Reply To Email*/
if (strlen($this->nmo->settings->reply_to_email) > 1) {
-
- if(property_exists($this->nmo->settings, 'reply_to_name'))
+ if (property_exists($this->nmo->settings, 'reply_to_name')) {
$reply_to_name = strlen($this->nmo->settings->reply_to_name) > 3 ? $this->nmo->settings->reply_to_name : $this->nmo->settings->reply_to_email;
- else
+ } else {
$reply_to_name = $this->nmo->settings->reply_to_email;
+ }
$this->nmo->mailable->replyTo($this->nmo->settings->reply_to_email, $reply_to_name);
-
- }
- else {
+ } else {
$this->nmo->mailable->replyTo($this->company->owner()->email, $this->company->owner()->present()->name());
}
@@ -112,15 +108,12 @@ class NinjaMailerJob implements ShouldQueue
$this->nmo->mailable->tag($this->company->company_key);
/* If we have an invitation present, we pass the invitation key into the email headers*/
- if($this->nmo->invitation)
- {
-
+ if ($this->nmo->invitation) {
$this->nmo
->mailable
->withSymfonyMessage(function ($message) {
- $message->getHeaders()->addTextHeader('x-invitation', $this->nmo->invitation->key);
+ $message->getHeaders()->addTextHeader('x-invitation', $this->nmo->invitation->key);
});
-
}
//send email
@@ -130,11 +123,11 @@ class NinjaMailerJob implements ShouldQueue
$mailer = Mail::mailer($this->mailer);
- if($this->client_postmark_secret){
+ if ($this->client_postmark_secret) {
$mailer->postmark_config($this->client_postmark_secret);
}
- if($this->client_mailgun_secret){
+ if ($this->client_mailgun_secret) {
$mailer->mailgun_config($this->client_mailgun_secret, $this->client_mailgun_domain);
}
@@ -150,24 +143,19 @@ class NinjaMailerJob implements ShouldQueue
$this->nmo = null;
$this->company = null;
-
- }
- 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){
- nlog("Mailer failed with a Logic Exception {$e->getMessage()}");
- $this->fail();
- $this->cleanUpMailers();
- $this->logMailError($e->getMessage(), $this->company->clients()->first());
- return;
- }
- catch (\Exception | \Google\Service\Exception $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) {
+ nlog("Mailer failed with a Logic Exception {$e->getMessage()}");
+ $this->fail();
+ $this->cleanUpMailers();
+ $this->logMailError($e->getMessage(), $this->company->clients()->first());
+ return;
+ } catch (\Exception | \Google\Service\Exception $e) {
nlog("Mailer failed with {$e->getMessage()}");
$message = $e->getMessage();
@@ -176,9 +164,7 @@ class NinjaMailerJob implements ShouldQueue
* this merges a text string with a json object
* need to harvest the ->Message property using the following
*/
- if(stripos($e->getMessage(), 'code 406') || stripos($e->getMessage(), 'code 300') || stripos($e->getMessage(), 'code 413'))
- {
-
+ if (stripos($e->getMessage(), 'code 406') || stripos($e->getMessage(), 'code 300') || stripos($e->getMessage(), 'code 413')) {
$message = "Either Attachment too large, or recipient has been suppressed.";
$this->fail();
@@ -186,36 +172,32 @@ class NinjaMailerJob implements ShouldQueue
$this->cleanUpMailers();
return;
-
}
//only report once, not on all tries
- if($this->attempts() == $this->tries)
- {
-
+ if ($this->attempts() == $this->tries) {
/* If the is an entity attached to the message send a failure mailer */
- if($this->nmo->entity)
+ if ($this->nmo->entity) {
$this->entityEmailFailed($message);
+ }
/* Don't send postmark failures to Sentry */
- if(Ninja::isHosted() && (!$e instanceof ClientException))
+ if (Ninja::isHosted() && (!$e instanceof ClientException)) {
app('sentry')->captureException($e);
-
+ }
}
/* Releasing immediately does not add in the backoff */
$this->release($this->backoff()[$this->attempts()-1]);
-
}
- /*Clean up mailers*/
+ /*Clean up mailers*/
$this->cleanUpMailers();
-
}
/**
* Entity notification when an email fails to send
- *
+ *
* @param string $message
* @return void
*/
@@ -235,9 +217,9 @@ class NinjaMailerJob implements ShouldQueue
break;
}
- if ($this->nmo->to_user instanceof ClientContact)
+ if ($this->nmo->to_user instanceof ClientContact) {
$this->logMailError($message, $this->nmo->to_user->client);
-
+ }
}
/**
@@ -275,9 +257,9 @@ class NinjaMailerJob implements ShouldQueue
break;
}
- if(Ninja::isSelfHost())
+ if (Ninja::isSelfHost()) {
$this->setSelfHostMultiMailer();
-
+ }
}
/**
@@ -286,10 +268,7 @@ class NinjaMailerJob implements ShouldQueue
*/
private function setSelfHostMultiMailer(): void
{
-
- if (env($this->company->id . '_MAIL_HOST'))
- {
-
+ if (env($this->company->id . '_MAIL_HOST')) {
config([
'mail.mailers.smtp' => [
'transport' => 'smtp',
@@ -300,20 +279,17 @@ class NinjaMailerJob implements ShouldQueue
],
]);
- if(env($this->company->id . '_MAIL_FROM_ADDRESS'))
- {
- $this->nmo
- ->mailable
- ->from(env($this->company->id . '_MAIL_FROM_ADDRESS', env('MAIL_FROM_ADDRESS')), env($this->company->id . '_MAIL_FROM_NAME', env('MAIL_FROM_NAME')));
- }
-
+ if (env($this->company->id . '_MAIL_FROM_ADDRESS')) {
+ $this->nmo
+ ->mailable
+ ->from(env($this->company->id . '_MAIL_FROM_ADDRESS', env('MAIL_FROM_ADDRESS')), env($this->company->id . '_MAIL_FROM_NAME', env('MAIL_FROM_NAME')));
+ }
}
-
}
/**
* Ensure we discard any data that is not required
- *
+ *
* @return void
*/
private function cleanUpMailers(): void
@@ -324,21 +300,20 @@ class NinjaMailerJob implements ShouldQueue
$this->client_mailgun_domain = false;
- //always dump the drivers to prevent reuse
+ //always dump the drivers to prevent reuse
app('mail.manager')->forgetMailers();
}
- /**
+ /**
* Check to ensure no cross account
* emails can be sent.
- *
+ *
* @param User $user
*/
private function checkValidSendingUser($user)
{
/* Always ensure the user is set on the correct account */
- if($user->account_id != $this->company->account_id){
-
+ if ($user->account_id != $this->company->account_id) {
$this->nmo->settings->email_sending_method = 'default';
return $this->setMailDriver();
}
@@ -348,17 +323,18 @@ class NinjaMailerJob implements ShouldQueue
* Resolves the sending user
* when configuring the Mailer
* on behalf of the client
- *
+ *
* @return User $user
*/
private function resolveSendingUser(): ?User
{
$sending_user = $this->nmo->settings->gmail_sending_user_id;
- if($sending_user == "0")
+ if ($sending_user == "0") {
$user = $this->company->owner();
- else
+ } else {
$user = User::find($this->decodePrimaryKey($sending_user));
+ }
return $user;
}
@@ -369,11 +345,10 @@ class NinjaMailerJob implements ShouldQueue
*/
private function setMailgunMailer()
{
- if(strlen($this->nmo->settings->mailgun_secret) > 2 && strlen($this->nmo->settings->mailgun_domain) > 2){
+ if (strlen($this->nmo->settings->mailgun_secret) > 2 && strlen($this->nmo->settings->mailgun_domain) > 2) {
$this->client_mailgun_secret = $this->nmo->settings->mailgun_secret;
$this->client_mailgun_domain = $this->nmo->settings->mailgun_domain;
- }
- else{
+ } else {
$this->nmo->settings->email_sending_method = 'default';
return $this->setMailDriver();
}
@@ -383,9 +358,9 @@ class NinjaMailerJob implements ShouldQueue
$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
- ->from($sending_email, $sending_user);
+ $this->nmo
+ ->mailable
+ ->from($sending_email, $sending_user);
}
/**
@@ -394,10 +369,9 @@ class NinjaMailerJob implements ShouldQueue
*/
private function setPostmarkMailer()
{
- if(strlen($this->nmo->settings->postmark_secret) > 2){
+ if (strlen($this->nmo->settings->postmark_secret) > 2) {
$this->client_postmark_secret = $this->nmo->settings->postmark_secret;
- }
- else{
+ } else {
$this->nmo->settings->email_sending_method = 'default';
return $this->setMailDriver();
}
@@ -407,9 +381,9 @@ class NinjaMailerJob implements ShouldQueue
$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
- ->from($sending_email, $sending_user);
+ $this->nmo
+ ->mailable
+ ->from($sending_email, $sending_user);
}
/**
@@ -426,26 +400,20 @@ class NinjaMailerJob implements ShouldQueue
$token = $this->refreshOfficeToken($user);
- if($token)
- {
+ if ($token) {
$user->oauth_user_token = $token;
$user->save();
-
- }
- else {
-
+ } else {
$this->nmo->settings->email_sending_method = 'default';
return $this->setMailDriver();
-
}
$this->nmo
->mailable
->from($user->email, $user->name())
- ->withSymfonyMessage(function ($message) use($token) {
- $message->getHeaders()->addTextHeader('gmailtoken', $token);
+ ->withSymfonyMessage(function ($message) use ($token) {
+ $message->getHeaders()->addTextHeader('gmailtoken', $token);
});
-
}
/**
@@ -454,7 +422,6 @@ class NinjaMailerJob implements ShouldQueue
*/
private function setGmailMailer()
{
-
$user = $this->resolveSendingUser();
$this->checkValidSendingUser($user);
@@ -463,17 +430,14 @@ class NinjaMailerJob implements ShouldQueue
$google = (new Google())->init();
- try{
-
+ try {
if ($google->getClient()->isAccessTokenExpired()) {
$google->refreshToken($user);
$user = $user->fresh();
}
$google->getClient()->setAccessToken(json_encode($user->oauth_user_token));
-
- }
- catch(\Exception $e) {
+ } catch(\Exception $e) {
$this->logMailError('Gmail Token Invalid', $this->company->clients()->first());
$this->nmo->settings->email_sending_method = 'default';
return $this->setMailDriver();
@@ -483,7 +447,7 @@ class NinjaMailerJob implements ShouldQueue
* If the user doesn't have a valid token, notify them
*/
- if(!$user->oauth_user_token) {
+ if (!$user->oauth_user_token) {
$this->company->account->gmailCredentialNotification();
$this->nmo->settings->email_sending_method = 'default';
return $this->setMailDriver();
@@ -497,7 +461,7 @@ class NinjaMailerJob implements ShouldQueue
$token = $user->oauth_user_token->access_token;
- if(!$token) {
+ if (!$token) {
$this->company->account->gmailCredentialNotification();
$this->nmo->settings->email_sending_method = 'default';
return $this->setMailDriver();
@@ -506,45 +470,47 @@ class NinjaMailerJob implements ShouldQueue
$this->nmo
->mailable
->from($user->email, $user->name())
- ->withSymfonyMessage(function ($message) use($token) {
- $message->getHeaders()->addTextHeader('gmailtoken', $token);
+ ->withSymfonyMessage(function ($message) use ($token) {
+ $message->getHeaders()->addTextHeader('gmailtoken', $token);
});
-
}
/**
- * On the hosted platform we scan all outbound email for
+ * On the hosted platform we scan all outbound email for
* spam. This sequence processes the filters we use on all
* emails.
- *
+ *
* @return bool
*/
private function preFlightChecksFail(): bool
{
-
/* If we are migrating data we don't want to fire any emails */
- if($this->company->is_disabled && !$this->override)
+ if ($this->company->is_disabled && !$this->override) {
return true;
+ }
/* To handle spam users we drop all emails from flagged accounts */
- if(Ninja::isHosted() && $this->company->account && $this->company->account->is_flagged)
+ if (Ninja::isHosted() && $this->company->account && $this->company->account->is_flagged) {
return true;
+ }
/* On the hosted platform we set default contacts a @example.com email address - we shouldn't send emails to these types of addresses */
- if(Ninja::isHosted() && $this->nmo->to_user && strpos($this->nmo->to_user->email, '@example.com') !== false)
+ if (Ninja::isHosted() && $this->nmo->to_user && strpos($this->nmo->to_user->email, '@example.com') !== false) {
return true;
+ }
/* GMail users are uncapped */
- if(Ninja::isHosted() && ($this->nmo->settings->email_sending_method == 'gmail' || $this->nmo->settings->email_sending_method == 'office365'))
+ if (Ninja::isHosted() && ($this->nmo->settings->email_sending_method == 'gmail' || $this->nmo->settings->email_sending_method == 'office365')) {
return false;
+ }
/* On the hosted platform, if the user is over the email quotas, we do not send the email. */
- if(Ninja::isHosted() && $this->company->account && $this->company->account->emailQuotaExceeded())
+ if (Ninja::isHosted() && $this->company->account && $this->company->account->emailQuotaExceeded()) {
return true;
+ }
/* If the account is verified, we allow emails to flow */
- if(Ninja::isHosted() && $this->company->account && $this->company->account->is_verified_account) {
-
+ if (Ninja::isHosted() && $this->company->account && $this->company->account->is_verified_account) {
//11-01-2022
/* Continue to analyse verified accounts in case they later start sending poor quality emails*/
@@ -555,35 +521,36 @@ class NinjaMailerJob implements ShouldQueue
}
/* Ensure the user has a valid email address */
- if(!str_contains($this->nmo->to_user->email, "@"))
+ if (!str_contains($this->nmo->to_user->email, "@")) {
return true;
+ }
/* On the hosted platform if the user has not verified their account we fail here - but still check what they are trying to send! */
- if(Ninja::isHosted() && $this->company->account && !$this->company->account->account_sms_verified){
-
- if(class_exists(\Modules\Admin\Jobs\Account\EmailQuality::class))
+ if (Ninja::isHosted() && $this->company->account && !$this->company->account->account_sms_verified) {
+ if (class_exists(\Modules\Admin\Jobs\Account\EmailQuality::class)) {
return (new \Modules\Admin\Jobs\Account\EmailQuality($this->nmo, $this->company))->run();
+ }
return true;
}
/* On the hosted platform we actively scan all outbound emails to ensure outbound email quality remains high */
- if(class_exists(\Modules\Admin\Jobs\Account\EmailQuality::class))
+ if (class_exists(\Modules\Admin\Jobs\Account\EmailQuality::class)) {
return (new \Modules\Admin\Jobs\Account\EmailQuality($this->nmo, $this->company))->run();
+ }
return false;
}
/**
* Logs any errors to the SystemLog
- *
+ *
* @param string $errors
* @param App\Models\User | App\Models\Client $recipient_object
* @return void
*/
private function logMailError($errors, $recipient_object) :void
{
-
(new SystemLogger(
$errors,
SystemLog::CATEGORY_MAIL,
@@ -601,12 +568,11 @@ class NinjaMailerJob implements ShouldQueue
->send();
$job_failure = null;
-
}
/**
* Attempts to refresh the Microsoft refreshToken
- *
+ *
* @param App\Models\User
* @return string | boool
*/
@@ -614,10 +580,9 @@ class NinjaMailerJob implements ShouldQueue
{
$expiry = $user->oauth_user_token_expiry ?: now()->subDay();
- if($expiry->lt(now()))
- {
- $guzzle = new \GuzzleHttp\Client();
- $url = 'https://login.microsoftonline.com/common/oauth2/v2.0/token';
+ if ($expiry->lt(now())) {
+ $guzzle = new \GuzzleHttp\Client();
+ $url = 'https://login.microsoftonline.com/common/oauth2/v2.0/token';
$token = json_decode($guzzle->post($url, [
'form_params' => [
@@ -629,8 +594,7 @@ class NinjaMailerJob implements ShouldQueue
],
])->getBody()->getContents());
- if($token){
-
+ if ($token) {
$user->oauth_user_refresh_token = property_exists($token, 'refresh_token') ? $token->refresh_token : $user->oauth_user_refresh_token;
$user->oauth_user_token = $token->access_token;
$user->oauth_user_token_expiry = now()->addSeconds($token->expires_in);
@@ -643,14 +607,10 @@ class NinjaMailerJob implements ShouldQueue
}
return $user->oauth_user_token;
-
}
public function failed($exception = null)
{
-
config(['queue.failed.driver' => null]);
-
}
-
-}
\ No newline at end of file
+}
diff --git a/app/Jobs/Mail/PaymentFailedMailer.php b/app/Jobs/Mail/PaymentFailedMailer.php
index d79f4bb64388..c5fa3c14dbcc 100644
--- a/app/Jobs/Mail/PaymentFailedMailer.php
+++ b/app/Jobs/Mail/PaymentFailedMailer.php
@@ -11,18 +11,13 @@
namespace App\Jobs\Mail;
-use App\Jobs\Mail\NinjaMailer;
-use App\Jobs\Mail\NinjaMailerJob;
-use App\Jobs\Mail\NinjaMailerObject;
use App\Libraries\MultiDB;
use App\Mail\Admin\ClientPaymentFailureObject;
-use App\Mail\Admin\EntityNotificationMailer;
use App\Mail\Admin\PaymentFailureObject;
use App\Models\Client;
use App\Models\Company;
use App\Models\Invoice;
use App\Models\PaymentHash;
-use App\Models\User;
use App\Utils\Traits\MakesHash;
use App\Utils\Traits\Notifications\UserNotifies;
use Illuminate\Bus\Queueable;
@@ -70,7 +65,7 @@ class PaymentFailedMailer implements ShouldQueue
*/
public function handle()
{
- if(!is_string($this->error)){
+ if (!is_string($this->error)) {
$this->error = "Payment failed, no reason given.";
}
diff --git a/app/Jobs/Mail/PaymentFailureMailer.php b/app/Jobs/Mail/PaymentFailureMailer.php
index 75c546609169..336c8009c101 100644
--- a/app/Jobs/Mail/PaymentFailureMailer.php
+++ b/app/Jobs/Mail/PaymentFailureMailer.php
@@ -11,11 +11,7 @@
namespace App\Jobs\Mail;
-use App\Jobs\Mail\NinjaMailer;
-use App\Jobs\Mail\NinjaMailerJob;
-use App\Jobs\Mail\NinjaMailerObject;
use App\Libraries\MultiDB;
-use App\Mail\Admin\EntityNotificationMailer;
use App\Mail\Admin\PaymentFailureObject;
use App\Models\User;
use App\Utils\Traits\Notifications\UserNotifies;
@@ -72,13 +68,11 @@ class PaymentFailureMailer implements ShouldQueue
*/
public function handle()
{
-
//Set DB
MultiDB::setDb($this->company->db);
//iterate through company_users
$this->company->company_users->each(function ($company_user) {
-
//determine if this user has the right permissions
$methods = $this->findCompanyUserNotificationType($company_user, ['payment_failure_all', 'payment_failure', 'payment_failure_user', 'all_notifications']);
diff --git a/app/Jobs/Ninja/AdjustEmailQuota.php b/app/Jobs/Ninja/AdjustEmailQuota.php
index 909ed72843f7..7e0a1cddab35 100644
--- a/app/Jobs/Ninja/AdjustEmailQuota.php
+++ b/app/Jobs/Ninja/AdjustEmailQuota.php
@@ -63,19 +63,16 @@ class AdjustEmailQuota implements ShouldQueue
$email_count = Cache::get($account->key);
- if($email_count > 0){
-
- try{
+ if ($email_count > 0) {
+ try {
LightLogs::create(new EmailCount($email_count, $account->key))->send();
- }
- catch(\Exception $e){
+ } catch(\Exception $e) {
nlog($e->getMessage());
}
}
Cache::forget($account->key);
Cache::forget("throttle_notified:{$account->key}");
-
});
}
}
diff --git a/app/Jobs/Ninja/BankTransactionSync.php b/app/Jobs/Ninja/BankTransactionSync.php
index 370fef9e7b86..ae7dc4d7b33a 100644
--- a/app/Jobs/Ninja/BankTransactionSync.php
+++ b/app/Jobs/Ninja/BankTransactionSync.php
@@ -20,7 +20,6 @@ use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
-use Illuminate\Support\Facades\Cache;
class BankTransactionSync implements ShouldQueue
{
@@ -44,31 +43,21 @@ class BankTransactionSync implements ShouldQueue
*/
public function handle()
{
-
//multiDB environment, need to
- foreach (MultiDB::$dbs as $db)
- {
+ foreach (MultiDB::$dbs as $db) {
MultiDB::setDB($db);
nlog("syncing transactions");
- $a = Account::with('bank_integrations')->whereNotNull('bank_integration_account_id')->cursor()->each(function ($account){
+ $a = Account::with('bank_integrations')->whereNotNull('bank_integration_account_id')->cursor()->each(function ($account) {
+ // $queue = Ninja::isHosted() ? 'bank' : 'default';
- // $queue = Ninja::isHosted() ? 'bank' : 'default';
-
- if($account->isPaid() && $account->plan == 'enterprise')
- {
-
- $account->bank_integrations()->where('auto_sync', true)->cursor()->each(function ($bank_integration) use ($account){
-
- (new ProcessBankTransactions($account->bank_integration_account_id, $bank_integration))->handle();
-
- });
-
- }
-
- });
+ if ($account->isPaid() && $account->plan == 'enterprise') {
+ $account->bank_integrations()->where('auto_sync', true)->cursor()->each(function ($bank_integration) use ($account) {
+ (new ProcessBankTransactions($account->bank_integration_account_id, $bank_integration))->handle();
+ });
+ }
+ });
}
}
-
}
diff --git a/app/Jobs/Ninja/CheckCompanyData.php b/app/Jobs/Ninja/CheckCompanyData.php
index 2478f611cb90..bd4d95504e96 100644
--- a/app/Jobs/Ninja/CheckCompanyData.php
+++ b/app/Jobs/Ninja/CheckCompanyData.php
@@ -25,7 +25,6 @@ use Illuminate\Queue\Middleware\RateLimited;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
-use Turbo124\Beacon\Jobs\Database\MySQL\DbStatus;
class CheckCompanyData implements ShouldQueue
{
@@ -124,8 +123,8 @@ class CheckCompanyData implements ShouldQueue
$this->company->clients->where('is_deleted', 0)->each(function ($client) use ($wrong_balances) {
$client->invoices->where('is_deleted', false)->whereIn('status_id', '!=', Invoice::STATUS_DRAFT)->each(function ($invoice) use ($wrong_balances, $client) {
- $total_amount = $invoice->payments->whereIn('status_id', [Payment::STATUS_COMPLETED, Payment:: STATUS_PENDING, Payment::STATUS_PARTIALLY_REFUNDED])->sum('pivot.amount');
- $total_refund = $invoice->payments->whereIn('status_id', [Payment::STATUS_COMPLETED, Payment:: STATUS_PENDING, Payment::STATUS_PARTIALLY_REFUNDED])->sum('pivot.refunded');
+ $total_amount = $invoice->payments->whereIn('status_id', [Payment::STATUS_COMPLETED, Payment::STATUS_PENDING, Payment::STATUS_PARTIALLY_REFUNDED])->sum('pivot.amount');
+ $total_refund = $invoice->payments->whereIn('status_id', [Payment::STATUS_COMPLETED, Payment::STATUS_PENDING, Payment::STATUS_PARTIALLY_REFUNDED])->sum('pivot.refunded');
$total_credit = $invoice->credits->sum('amount');
$total_paid = $total_amount - $total_refund;
@@ -153,8 +152,8 @@ class CheckCompanyData implements ShouldQueue
$total_invoice_payments = 0;
foreach ($client->invoices->where('is_deleted', false)->where('status_id', '>', 1) as $invoice) {
- $total_amount = $invoice->payments->where('is_deleted', false)->whereIn('status_id', [Payment::STATUS_COMPLETED, Payment:: STATUS_PENDING, Payment::STATUS_PARTIALLY_REFUNDED, Payment::STATUS_REFUNDED])->sum('pivot.amount');
- $total_refund = $invoice->payments->where('is_deleted', false)->whereIn('status_id', [Payment::STATUS_COMPLETED, Payment:: STATUS_PENDING, Payment::STATUS_PARTIALLY_REFUNDED, Payment::STATUS_REFUNDED])->sum('pivot.refunded');
+ $total_amount = $invoice->payments->where('is_deleted', false)->whereIn('status_id', [Payment::STATUS_COMPLETED, Payment::STATUS_PENDING, Payment::STATUS_PARTIALLY_REFUNDED, Payment::STATUS_REFUNDED])->sum('pivot.amount');
+ $total_refund = $invoice->payments->where('is_deleted', false)->whereIn('status_id', [Payment::STATUS_COMPLETED, Payment::STATUS_PENDING, Payment::STATUS_PARTIALLY_REFUNDED, Payment::STATUS_REFUNDED])->sum('pivot.refunded');
$total_invoice_payments += ($total_amount - $total_refund);
}
diff --git a/app/Jobs/Ninja/CompanySizeCheck.php b/app/Jobs/Ninja/CompanySizeCheck.php
index 89c07bdcdc11..2eeb238a2ea6 100644
--- a/app/Jobs/Ninja/CompanySizeCheck.php
+++ b/app/Jobs/Ninja/CompanySizeCheck.php
@@ -43,7 +43,6 @@ class CompanySizeCheck implements ShouldQueue
public function handle()
{
if (! config('ninja.db.multi_db_enabled')) {
-
Company::where('is_large', false)->withCount(['invoices', 'clients', 'products', 'quotes'])->cursor()->each(function ($company) {
if ($company->invoices_count > 500 || $company->products_count > 500 || $company->clients_count > 500) {
nlog("Marking company {$company->id} as large");
@@ -56,29 +55,21 @@ class CompanySizeCheck implements ShouldQueue
Client::where('updated_at', '>', now()->subDay())
->cursor()
- ->each(function ($client){
-
- $client->credit_balance = $client->service()->getCreditBalance();
- $client->save();
-
+ ->each(function ($client) {
+ $client->credit_balance = $client->service()->getCreditBalance();
+ $client->save();
});
/* Ensures lower permissioned users return the correct dataset and refresh responses */
- Account::whereHas('companies', function ($query){
- $query->where('is_large',0);
+ Account::whereHas('companies', function ($query) {
+ $query->where('is_large', 0);
+ })
+ ->whereHas('company_users', function ($query) {
+ $query->where('is_admin', 0);
})
- ->whereHas('company_users', function ($query){
-
- $query->where('is_admin', 0);
-
- })
- ->cursor()->each(function ($account){
-
- $account->companies()->update(['is_large' => true]);
-
+ ->cursor()->each(function ($account) {
+ $account->companies()->update(['is_large' => true]);
});
-
-
} else {
//multiDB environment, need to
foreach (MultiDB::$dbs as $db) {
@@ -98,31 +89,23 @@ class CompanySizeCheck implements ShouldQueue
Client::where('updated_at', '>', now()->subDay())
->cursor()
- ->each(function ($client){
-
- $client->credit_balance = $client->service()->getCreditBalance();
- $client->save();
-
+ ->each(function ($client) {
+ $client->credit_balance = $client->service()->getCreditBalance();
+ $client->save();
});
Account::where('plan', 'enterprise')
->whereDate('plan_expires', '>', now())
- ->whereHas('companies', function ($query){
- $query->where('is_large',0);
+ ->whereHas('companies', function ($query) {
+ $query->where('is_large', 0);
})
- ->whereHas('company_users', function ($query){
-
- $query->where('is_admin', 0);
-
- })
- ->cursor()->each(function ($account){
-
- $account->companies()->update(['is_large' => true]);
-
+ ->whereHas('company_users', function ($query) {
+ $query->where('is_admin', 0);
+ })
+ ->cursor()->each(function ($account) {
+ $account->companies()->update(['is_large' => true]);
});
-
}
}
}
-
}
diff --git a/app/Jobs/Ninja/QueueSize.php b/app/Jobs/Ninja/QueueSize.php
index c1282edb581a..96850337b988 100644
--- a/app/Jobs/Ninja/QueueSize.php
+++ b/app/Jobs/Ninja/QueueSize.php
@@ -19,7 +19,6 @@ use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Queue;
use Turbo124\Beacon\Facades\LightLogs;
-use Turbo124\Beacon\Jobs\Database\MySQL\DbStatus;
class QueueSize implements ShouldQueue
{
diff --git a/app/Jobs/Ninja/SendReminders.php b/app/Jobs/Ninja/SendReminders.php
index 7587ec6004f2..33a0cdc9f1b1 100644
--- a/app/Jobs/Ninja/SendReminders.php
+++ b/app/Jobs/Ninja/SendReminders.php
@@ -209,7 +209,6 @@ class SendReminders implements ShouldQueue
$invoice = $this->calcLateFee($invoice, $template);
$invoice->invitations->each(function ($invitation) use ($template, $invoice) {
-
//only send if enable_reminder setting is toggled to yes
if ($this->checkSendSetting($invoice, $template) && $invoice->company->account->hasFeature(Account::FEATURE_EMAIL_TEMPLATES_REMINDERS)) {
nlog('firing email');
diff --git a/app/Jobs/Ninja/SystemMaintenance.php b/app/Jobs/Ninja/SystemMaintenance.php
index 2ace08884189..e036a291be62 100644
--- a/app/Jobs/Ninja/SystemMaintenance.php
+++ b/app/Jobs/Ninja/SystemMaintenance.php
@@ -15,14 +15,11 @@ use App\Models\Backup;
use App\Models\Credit;
use App\Models\Invoice;
use App\Models\Quote;
-use App\Utils\Ninja;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
-use Illuminate\Support\Facades\Queue;
-use Illuminate\Support\Facades\Storage;
class SystemMaintenance implements ShouldQueue
{
diff --git a/app/Jobs/Ninja/TaskScheduler.php b/app/Jobs/Ninja/TaskScheduler.php
index 4ee399603b12..46a3fb27b04b 100644
--- a/app/Jobs/Ninja/TaskScheduler.php
+++ b/app/Jobs/Ninja/TaskScheduler.php
@@ -11,10 +11,8 @@
namespace App\Jobs\Ninja;
-use App\Jobs\Report\SendToAdmin;
use App\Libraries\MultiDB;
use App\Models\Scheduler;
-use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
@@ -44,9 +42,7 @@ class TaskScheduler implements ShouldQueue
*/
public function handle()
{
-
if (! config('ninja.db.multi_db_enabled')) {
-
Scheduler::with('company')
->where('is_paused', false)
->where('is_deleted', false)
@@ -82,12 +78,8 @@ class TaskScheduler implements ShouldQueue
try {
$scheduler->service()->runTask();
- }
- catch(\Exception $e){
+ } catch(\Exception $e) {
nlog($e->getMessage());
-
}
}
-
-
}
diff --git a/app/Jobs/Payment/EmailPayment.php b/app/Jobs/Payment/EmailPayment.php
index c05f3172c64d..fab34abbc7b7 100644
--- a/app/Jobs/Payment/EmailPayment.php
+++ b/app/Jobs/Payment/EmailPayment.php
@@ -12,7 +12,6 @@
namespace App\Jobs\Payment;
use App\Events\Payment\PaymentWasEmailed;
-use App\Events\Payment\PaymentWasEmailedAndFailed;
use App\Jobs\Mail\NinjaMailerJob;
use App\Jobs\Mail\NinjaMailerObject;
use App\Libraries\MultiDB;
@@ -27,7 +26,6 @@ use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
-use Illuminate\Support\Facades\Mail;
class EmailPayment implements ShouldQueue
{
diff --git a/app/Jobs/Payment/EmailRefundPayment.php b/app/Jobs/Payment/EmailRefundPayment.php
index c386882936ae..a3ef64cdbb41 100644
--- a/app/Jobs/Payment/EmailRefundPayment.php
+++ b/app/Jobs/Payment/EmailRefundPayment.php
@@ -12,7 +12,6 @@
namespace App\Jobs\Payment;
use App\Events\Payment\PaymentWasEmailed;
-use App\Events\Payment\PaymentWasEmailedAndFailed;
use App\Jobs\Mail\NinjaMailerJob;
use App\Jobs\Mail\NinjaMailerObject;
use App\Libraries\MultiDB;
@@ -28,7 +27,6 @@ use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\App;
-use Illuminate\Support\Facades\Mail;
class EmailRefundPayment implements ShouldQueue
{
diff --git a/app/Jobs/Payment/PaymentNotification.php b/app/Jobs/Payment/PaymentNotification.php
index cd0c92b00562..eabde8021278 100644
--- a/app/Jobs/Payment/PaymentNotification.php
+++ b/app/Jobs/Payment/PaymentNotification.php
@@ -48,7 +48,6 @@ class PaymentNotification implements ShouldQueue
*/
public function handle()
{
-
//notification for the payment.
//
//could mean a email, sms, slack, push
diff --git a/app/Jobs/PostMark/ProcessPostmarkWebhook.php b/app/Jobs/PostMark/ProcessPostmarkWebhook.php
index 82ae0969828c..c2497a3b5677 100644
--- a/app/Jobs/PostMark/ProcessPostmarkWebhook.php
+++ b/app/Jobs/PostMark/ProcessPostmarkWebhook.php
@@ -13,15 +13,8 @@ namespace App\Jobs\PostMark;
use App\DataMapper\Analytics\Mail\EmailBounce;
use App\DataMapper\Analytics\Mail\EmailSpam;
-use App\Events\Payment\PaymentWasEmailed;
-use App\Events\Payment\PaymentWasEmailedAndFailed;
-use App\Jobs\Mail\NinjaMailerJob;
-use App\Jobs\Mail\NinjaMailerObject;
use App\Jobs\Util\SystemLogger;
use App\Libraries\MultiDB;
-use App\Mail\Engine\PaymentEmailEngine;
-use App\Mail\TemplateEmail;
-use App\Models\ClientContact;
use App\Models\Company;
use App\Models\CreditInvitation;
use App\Models\InvoiceInvitation;
@@ -38,7 +31,6 @@ use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
-use Illuminate\Support\Facades\Mail;
use Turbo124\Beacon\Facades\LightLogs;
class ProcessPostmarkWebhook implements ShouldQueue
@@ -71,19 +63,19 @@ class ProcessPostmarkWebhook implements ShouldQueue
*/
public function handle()
{
-
MultiDB::findAndSetDbByCompanyKey($this->request['Tag']);
$this->invitation = $this->discoverInvitation($this->request['MessageID']);
- if(!$this->invitation)
+ if (!$this->invitation) {
return;
+ }
- if(array_key_exists('Details', $this->request))
+ if (array_key_exists('Details', $this->request)) {
$this->invitation->email_error = $this->request['Details'];
+ }
- switch ($this->request['RecordType'])
- {
+ switch ($this->request['RecordType']) {
case 'Delivery':
return $this->processDelivery();
case 'Bounce':
@@ -96,7 +88,6 @@ class ProcessPostmarkWebhook implements ShouldQueue
# code...
break;
}
-
}
// {
@@ -134,22 +125,21 @@ class ProcessPostmarkWebhook implements ShouldQueue
// "ReceivedAt": "2022-02-06T06:37:48Z",
// "Tag": "welcome-email",
// "Recipient": "john@example.com"
-// }
+// }
private function processOpen()
{
-
$this->invitation->opened_date = now();
$this->invitation->save();
- (new SystemLogger($this->request,
- SystemLog::CATEGORY_MAIL,
- SystemLog::EVENT_MAIL_OPENED,
- SystemLog::TYPE_WEBHOOK_RESPONSE,
+ (new SystemLogger(
+ $this->request,
+ SystemLog::CATEGORY_MAIL,
+ SystemLog::EVENT_MAIL_OPENED,
+ SystemLog::TYPE_WEBHOOK_RESPONSE,
$this->invitation->contact->client,
$this->invitation->company
))->handle();
-
}
// {
@@ -171,10 +161,11 @@ class ProcessPostmarkWebhook implements ShouldQueue
$this->invitation->email_status = 'delivered';
$this->invitation->save();
- (new SystemLogger($this->request,
- SystemLog::CATEGORY_MAIL,
- SystemLog::EVENT_MAIL_DELIVERY,
- SystemLog::TYPE_WEBHOOK_RESPONSE,
+ (new SystemLogger(
+ $this->request,
+ SystemLog::CATEGORY_MAIL,
+ SystemLog::EVENT_MAIL_DELIVERY,
+ SystemLog::TYPE_WEBHOOK_RESPONSE,
$this->invitation->contact->client,
$this->invitation->company
))->handle();
@@ -222,8 +213,7 @@ class ProcessPostmarkWebhook implements ShouldQueue
(new SystemLogger($this->request, SystemLog::CATEGORY_MAIL, SystemLog::EVENT_MAIL_BOUNCED, SystemLog::TYPE_WEBHOOK_RESPONSE, $this->invitation->contact->client, $this->invitation->company))->handle();
// if(config('ninja.notification.slack'))
- // $this->invitation->company->notification(new EmailBounceNotification($this->invitation->company->account))->ninja();
-
+ // $this->invitation->company->notification(new EmailBounceNotification($this->invitation->company->account))->ninja();
}
// {
@@ -253,7 +243,6 @@ class ProcessPostmarkWebhook implements ShouldQueue
// }
private function processSpamComplaint()
{
-
$this->invitation->email_status = 'spam';
$this->invitation->save();
@@ -267,26 +256,27 @@ class ProcessPostmarkWebhook implements ShouldQueue
(new SystemLogger($this->request, SystemLog::CATEGORY_MAIL, SystemLog::EVENT_MAIL_SPAM_COMPLAINT, SystemLog::TYPE_WEBHOOK_RESPONSE, $this->invitation->contact->client, $this->invitation->company))->handle();
- if(config('ninja.notification.slack'))
+ if (config('ninja.notification.slack')) {
$this->invitation->company->notification(new EmailSpamNotification($this->invitation->company->account))->ninja();
-
+ }
}
private function discoverInvitation($message_id)
{
$invitation = false;
- if($invitation = InvoiceInvitation::where('message_id', $message_id)->first())
+ if ($invitation = InvoiceInvitation::where('message_id', $message_id)->first()) {
return $invitation;
- elseif($invitation = QuoteInvitation::where('message_id', $message_id)->first())
+ } elseif ($invitation = QuoteInvitation::where('message_id', $message_id)->first()) {
return $invitation;
- elseif($invitation = RecurringInvoiceInvitation::where('message_id', $message_id)->first())
+ } elseif ($invitation = RecurringInvoiceInvitation::where('message_id', $message_id)->first()) {
return $invitation;
- elseif($invitation = CreditInvitation::where('message_id', $message_id)->first())
+ } elseif ($invitation = CreditInvitation::where('message_id', $message_id)->first()) {
return $invitation;
- elseif($invitation = PurchaseOrderInvitation::where('message_id', $message_id)->first())
+ } elseif ($invitation = PurchaseOrderInvitation::where('message_id', $message_id)->first()) {
return $invitation;
- else
+ } else {
return $invitation;
+ }
}
-}
\ No newline at end of file
+}
diff --git a/app/Jobs/Product/UpdateOrCreateProduct.php b/app/Jobs/Product/UpdateOrCreateProduct.php
index 02a6d7e6b5bb..dd3ad2ab5633 100644
--- a/app/Jobs/Product/UpdateOrCreateProduct.php
+++ b/app/Jobs/Product/UpdateOrCreateProduct.php
@@ -85,20 +85,18 @@ class UpdateOrCreateProduct implements ShouldQueue
$product = Product::withTrashed()->firstOrNew(['product_key' => $item->product_key, 'company_id' => $this->invoice->company->id]);
- /* If a user is using placeholders in their descriptions, do not update the products */
- $string_hit = false;
+ /* If a user is using placeholders in their descriptions, do not update the products */
+ $string_hit = false;
- foreach ( [':MONTH',':YEAR',':QUARTER',':WEEK'] as $string )
- {
-
- if(stripos($product->notes, $string) !== FALSE) {
- $string_hit = true;
- }
-
+ foreach ([':MONTH',':YEAR',':QUARTER',':WEEK'] as $string) {
+ if (stripos($product->notes, $string) !== false) {
+ $string_hit = true;
}
+ }
- if($string_hit)
- continue;
+ if ($string_hit) {
+ continue;
+ }
$product->product_key = $item->product_key;
$product->notes = isset($item->notes) ? $item->notes : '';
@@ -115,17 +113,21 @@ class UpdateOrCreateProduct implements ShouldQueue
$product->tax_name3 = isset($item->tax_name3) ? $item->tax_name3 : '';
$product->tax_rate3 = isset($item->tax_rate3) ? $item->tax_rate3 : 0;
- if(isset($item->custom_value1) && strlen($item->custom_value1) >=1)
+ if (isset($item->custom_value1) && strlen($item->custom_value1) >=1) {
$product->custom_value1 = $item->custom_value1;
+ }
- if(isset($item->custom_value2) && strlen($item->custom_value1) >=1)
+ if (isset($item->custom_value2) && strlen($item->custom_value1) >=1) {
$product->custom_value2 = $item->custom_value2;
+ }
- if(isset($item->custom_value3) && strlen($item->custom_value1) >=1)
+ if (isset($item->custom_value3) && strlen($item->custom_value1) >=1) {
$product->custom_value3 = $item->custom_value3;
+ }
- if(isset($item->custom_value4) && strlen($item->custom_value1) >=1)
+ if (isset($item->custom_value4) && strlen($item->custom_value1) >=1) {
$product->custom_value4 = $item->custom_value4;
+ }
$product->user_id = $this->invoice->user_id;
$product->company_id = $this->invoice->company_id;
diff --git a/app/Jobs/PurchaseOrder/PurchaseOrderEmail.php b/app/Jobs/PurchaseOrder/PurchaseOrderEmail.php
index f210e9337dc3..ace474991c4e 100644
--- a/app/Jobs/PurchaseOrder/PurchaseOrderEmail.php
+++ b/app/Jobs/PurchaseOrder/PurchaseOrderEmail.php
@@ -20,7 +20,6 @@ use App\Mail\VendorTemplateEmail;
use App\Models\Company;
use App\Models\PurchaseOrder;
use App\Utils\Ninja;
-use Exception;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
@@ -60,8 +59,7 @@ class PurchaseOrderEmail implements ShouldQueue
$this->purchase_order->last_sent_date = now();
$this->purchase_order->invitations->load('contact.vendor.country', 'purchase_order.vendor.country', 'purchase_order.company')->each(function ($invitation) {
-
- /* Don't fire emails if the company is disabled */
+ /* Don't fire emails if the company is disabled */
if ($this->company->is_disabled) {
return true;
}
@@ -77,10 +75,11 @@ class PurchaseOrderEmail implements ShouldQueue
/* Mark entity sent */
$invitation->purchase_order->service()->markSent()->save();
- if(is_array($this->template_data) && array_key_exists('template', $this->template_data))
+ if (is_array($this->template_data) && array_key_exists('template', $this->template_data)) {
$template = $this->template_data['template'];
- else
+ } else {
$template = 'purchase_order';
+ }
$email_builder = (new PurchaseOrderEmailEngine($invitation, $template, $this->template_data))->build();
diff --git a/app/Jobs/PurchaseOrder/ZipPurchaseOrders.php b/app/Jobs/PurchaseOrder/ZipPurchaseOrders.php
index bc8da551e975..07d37172b28d 100644
--- a/app/Jobs/PurchaseOrder/ZipPurchaseOrders.php
+++ b/app/Jobs/PurchaseOrder/ZipPurchaseOrders.php
@@ -11,25 +11,20 @@
namespace App\Jobs\PurchaseOrder;
-use App\Jobs\Entity\CreateEntityPdf;
use App\Jobs\Mail\NinjaMailerJob;
use App\Jobs\Mail\NinjaMailerObject;
use App\Jobs\Util\UnlinkFile;
use App\Jobs\Vendor\CreatePurchaseOrderPdf;
use App\Libraries\MultiDB;
-use App\Mail\DownloadInvoices;
use App\Mail\DownloadPurchaseOrders;
use App\Models\Company;
use App\Models\User;
-use App\Utils\TempFile;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
-use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Storage;
-use ZipArchive;
class ZipPurchaseOrders implements ShouldQueue
{
diff --git a/app/Jobs/Quote/QuoteCheckExpired.php b/app/Jobs/Quote/QuoteCheckExpired.php
index 5a4061d7bfdd..d1880458b779 100644
--- a/app/Jobs/Quote/QuoteCheckExpired.php
+++ b/app/Jobs/Quote/QuoteCheckExpired.php
@@ -18,7 +18,6 @@ use App\Jobs\Mail\NinjaMailerObject;
use App\Libraries\MultiDB;
use App\Mail\Admin\QuoteExpiredObject;
use App\Models\Quote;
-use App\Repositories\BaseRepository;
use App\Utils\Traits\Notifications\UserNotifies;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
@@ -33,7 +32,9 @@ class QuoteCheckExpired implements ShouldQueue
/**
* Create a new job instance.
*/
- public function __construct() {}
+ public function __construct()
+ {
+ }
/**
* Execute the job.
@@ -42,61 +43,53 @@ class QuoteCheckExpired implements ShouldQueue
*/
public function handle()
{
- if (! config('ninja.db.multi_db_enabled')){
-
+ if (! config('ninja.db.multi_db_enabled')) {
Quote::query()
->where('status_id', Quote::STATUS_SENT)
->where('is_deleted', false)
->whereNull('deleted_at')
->whereNotNull('due_date')
->whereHas('client', function ($query) {
- $query->where('is_deleted', 0)
- ->where('deleted_at', null);
- })
+ $query->where('is_deleted', 0)
+ ->where('deleted_at', null);
+ })
->whereHas('company', function ($query) {
$query->where('is_disabled', 0);
})
// ->where('due_date', '<='. now()->toDateTimeString())
->whereBetween('due_date', [now()->subDay()->startOfDay(), now()->startOfDay()->subSecond()])
->cursor()
- ->each(function ($quote){
- $this->queueExpiredQuoteNotification($quote);
+ ->each(function ($quote) {
+ $this->queueExpiredQuoteNotification($quote);
});
-
- }
- else {
-
- foreach (MultiDB::$dbs as $db)
- {
-
+ } else {
+ foreach (MultiDB::$dbs as $db) {
MultiDB::setDB($db);
- Quote::query()
- ->where('status_id', Quote::STATUS_SENT)
- ->where('is_deleted', false)
- ->whereNull('deleted_at')
- ->whereNotNull('due_date')
- ->whereHas('client', function ($query) {
- $query->where('is_deleted', 0)
- ->where('deleted_at', null);
- })
- ->whereHas('company', function ($query) {
- $query->where('is_disabled', 0);
- })
- // ->where('due_date', '<='. now()->toDateTimeString())
- ->whereBetween('due_date', [now()->subDay()->startOfDay(), now()->startOfDay()->subSecond()])
- ->cursor()
- ->each(function ($quote){
- $this->queueExpiredQuoteNotification($quote);
- });
+ Quote::query()
+ ->where('status_id', Quote::STATUS_SENT)
+ ->where('is_deleted', false)
+ ->whereNull('deleted_at')
+ ->whereNotNull('due_date')
+ ->whereHas('client', function ($query) {
+ $query->where('is_deleted', 0)
+ ->where('deleted_at', null);
+ })
+ ->whereHas('company', function ($query) {
+ $query->where('is_disabled', 0);
+ })
+ // ->where('due_date', '<='. now()->toDateTimeString())
+ ->whereBetween('due_date', [now()->subDay()->startOfDay(), now()->startOfDay()->subSecond()])
+ ->cursor()
+ ->each(function ($quote) {
+ $this->queueExpiredQuoteNotification($quote);
+ });
}
}
-
}
private function checkForExpiredQuotes()
{
-
}
private function queueExpiredQuoteNotification(Quote $quote)
@@ -108,7 +101,6 @@ class QuoteCheckExpired implements ShouldQueue
/* We loop through each user and determine whether they need to be notified */
foreach ($quote->company->company_users as $company_user) {
-
/* The User */
$user = $company_user->user;
@@ -126,9 +118,7 @@ class QuoteCheckExpired implements ShouldQueue
$nmo->to_user = $user;
NinjaMailerJob::dispatch($nmo);
-
}
}
}
-
}
diff --git a/app/Jobs/Quote/ZipQuotes.php b/app/Jobs/Quote/ZipQuotes.php
index bd4e15ff977d..3dd1b7f8967b 100644
--- a/app/Jobs/Quote/ZipQuotes.php
+++ b/app/Jobs/Quote/ZipQuotes.php
@@ -19,15 +19,12 @@ use App\Libraries\MultiDB;
use App\Mail\DownloadQuotes;
use App\Models\Company;
use App\Models\User;
-use App\Utils\TempFile;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
-use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Storage;
-use ZipArchive;
class ZipQuotes implements ShouldQueue
{
@@ -80,11 +77,9 @@ class ZipQuotes implements ShouldQueue
$path = $this->quotes->first()->client->quote_filepath($invitation);
$this->quotes->each(function ($quote) {
-
$quote->service()->createInvitations();
(new CreateEntityPdf($quote->invitations()->first()))->handle();
-
});
try {
diff --git a/app/Jobs/RecurringInvoice/SendRecurring.php b/app/Jobs/RecurringInvoice/SendRecurring.php
index 8833ebfd12b9..2b9269fd1a7a 100644
--- a/app/Jobs/RecurringInvoice/SendRecurring.php
+++ b/app/Jobs/RecurringInvoice/SendRecurring.php
@@ -12,17 +12,14 @@
namespace App\Jobs\RecurringInvoice;
use App\DataMapper\Analytics\SendRecurringFailure;
-use App\Events\Invoice\InvoiceWasEmailed;
use App\Factory\InvoiceInvitationFactory;
use App\Factory\RecurringInvoiceToInvoiceFactory;
use App\Jobs\Cron\AutoBill;
use App\Jobs\Entity\EmailEntity;
use App\Models\Invoice;
use App\Models\RecurringInvoice;
-use App\Utils\Ninja;
use App\Utils\Traits\GeneratesCounter;
use App\Utils\Traits\MakesHash;
-use App\Utils\Traits\MakesInvoiceValues;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
@@ -62,7 +59,6 @@ class SendRecurring implements ShouldQueue
*/
public function handle() : void
{
-
// Generate Standard Invoice
$invoice = RecurringInvoiceToInvoiceFactory::create($this->recurring_invoice, $this->recurring_invoice->client);
@@ -124,7 +120,7 @@ class SendRecurring implements ShouldQueue
$invoice->invitations->each(function ($invitation) use ($invoice) {
if ($invitation->contact && ! $invitation->contact->trashed() && strlen($invitation->contact->email) >= 1 && $invoice->client->getSetting('auto_email_invoice')) {
try {
- EmailEntity::dispatch($invitation, $invoice->company)->delay(rand(1,2));
+ EmailEntity::dispatch($invitation, $invoice->company)->delay(rand(1, 2));
} catch (\Exception $e) {
nlog($e->getMessage());
}
@@ -137,12 +133,11 @@ class SendRecurring implements ShouldQueue
//auto bill, BUT NOT DRAFTS!!
if ($invoice->auto_bill_enabled && $invoice->client->getSetting('auto_bill_date') == 'on_send_date' && $invoice->client->getSetting('auto_email_invoice')) {
nlog("attempting to autobill {$invoice->number}");
- AutoBill::dispatch($invoice->id, $this->db)->delay(rand(1,2));
-
+ AutoBill::dispatch($invoice->id, $this->db)->delay(rand(1, 2));
} elseif ($invoice->auto_bill_enabled && $invoice->client->getSetting('auto_bill_date') == 'on_due_date' && $invoice->client->getSetting('auto_email_invoice')) {
if ($invoice->due_date && Carbon::parse($invoice->due_date)->startOfDay()->lte(now()->startOfDay())) {
nlog("attempting to autobill {$invoice->number}");
- AutoBill::dispatch($invoice->id, $this->db)->delay(rand(1,2));
+ AutoBill::dispatch($invoice->id, $this->db)->delay(rand(1, 2));
}
}
}
@@ -154,8 +149,7 @@ class SendRecurring implements ShouldQueue
*/
private function createRecurringInvitations($invoice) :Invoice
{
-
- if($this->recurring_invoice->invitations->count() == 0) {
+ if ($this->recurring_invoice->invitations->count() == 0) {
$this->recurring_invoice = $this->recurring_invoice->service()->createInvitations()->save();
}
@@ -187,14 +181,14 @@ class SendRecurring implements ShouldQueue
/**
- *
+ *
* 1/8/2022
- *
+ *
* Improvements here include moving the emailentity and autobilling into the queue.
- *
+ *
* Further improvements could using the CompanyRecurringCron.php stub which divides
* the recurring invoices into companies and spins them off into their own queue to
* improve parallel processing.
- *
+ *
* Need to be careful we do not overload redis and OOM.
-*/
\ No newline at end of file
+*/
diff --git a/app/Jobs/Report/SendToAdmin.php b/app/Jobs/Report/SendToAdmin.php
index dce88638ceb3..29caccd7bbd6 100644
--- a/app/Jobs/Report/SendToAdmin.php
+++ b/app/Jobs/Report/SendToAdmin.php
@@ -11,7 +11,6 @@
namespace App\Jobs\Report;
-use App\Http\Requests\Report\GenericReportRequest;
use App\Jobs\Mail\NinjaMailerJob;
use App\Jobs\Mail\NinjaMailerObject;
use App\Libraries\MultiDB;
diff --git a/app/Jobs/Subscription/CleanStaleInvoiceOrder.php b/app/Jobs/Subscription/CleanStaleInvoiceOrder.php
index c7d08602f45c..f58084239c4f 100644
--- a/app/Jobs/Subscription/CleanStaleInvoiceOrder.php
+++ b/app/Jobs/Subscription/CleanStaleInvoiceOrder.php
@@ -15,7 +15,6 @@ use App\Libraries\MultiDB;
use App\Models\Invoice;
use App\Repositories\InvoiceRepository;
use Illuminate\Bus\Queueable;
-use Illuminate\Contracts\Container\BindingResolutionException;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
@@ -30,17 +29,17 @@ class CleanStaleInvoiceOrder implements ShouldQueue
* @param int invoice_id
* @param string $db
*/
- public function __construct(){}
+ public function __construct()
+ {
+ }
/**
- * @param InvoiceRepository $repo
- * @return void
+ * @param InvoiceRepository $repo
+ * @return void
*/
public function handle(InvoiceRepository $repo) : void
{
-
- if (! config('ninja.db.multi_db_enabled')) {
-
+ if (! config('ninja.db.multi_db_enabled')) {
Invoice::query()
->withTrashed()
->where('is_proforma', 1)
@@ -52,12 +51,10 @@ class CleanStaleInvoiceOrder implements ShouldQueue
});
return;
- }
+ }
- foreach (MultiDB::$dbs as $db)
- {
-
+ foreach (MultiDB::$dbs as $db) {
MultiDB::setDB($db);
Invoice::query()
@@ -69,9 +66,7 @@ class CleanStaleInvoiceOrder implements ShouldQueue
$invoice->is_proforma = false;
$repo->delete($invoice);
});
-
}
-
}
public function failed($exception = null)
diff --git a/app/Jobs/User/CreateUser.php b/app/Jobs/User/CreateUser.php
index 2835eed92fff..3e33c6f6c28c 100644
--- a/app/Jobs/User/CreateUser.php
+++ b/app/Jobs/User/CreateUser.php
@@ -12,13 +12,11 @@
namespace App\Jobs\User;
use App\DataMapper\CompanySettings;
-use App\DataMapper\DefaultSettings;
use App\Events\User\UserWasCreated;
use App\Models\User;
use App\Utils\Ninja;
use App\Utils\Traits\MakesHash;
use Illuminate\Foundation\Bus\Dispatchable;
-use Illuminate\Http\Request;
class CreateUser
{
diff --git a/app/Jobs/User/UserEmailChanged.php b/app/Jobs/User/UserEmailChanged.php
index 73a22028f58a..b400684f052b 100644
--- a/app/Jobs/User/UserEmailChanged.php
+++ b/app/Jobs/User/UserEmailChanged.php
@@ -24,7 +24,6 @@ use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\App;
-use Illuminate\Support\Facades\Mail;
use stdClass;
class UserEmailChanged implements ShouldQueue
diff --git a/app/Jobs/User/VerifyPhone.php b/app/Jobs/User/VerifyPhone.php
index 521e5c64413a..e28c77afb420 100644
--- a/app/Jobs/User/VerifyPhone.php
+++ b/app/Jobs/User/VerifyPhone.php
@@ -11,17 +11,12 @@
namespace App\Jobs\User;
-use App\DataMapper\CompanySettings;
-use App\DataMapper\DefaultSettings;
-use App\Events\User\UserWasCreated;
use App\Libraries\MultiDB;
use App\Models\User;
-use App\Utils\Ninja;
use App\Utils\Traits\MakesHash;
-use Illuminate\Foundation\Bus\Dispatchable;
-use Illuminate\Http\Request;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
+use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
@@ -35,7 +30,9 @@ class VerifyPhone implements ShouldQueue
*
* @param User $user
*/
- public function __construct(private User $user){}
+ public function __construct(private User $user)
+ {
+ }
/**
* Execute the job.
@@ -44,41 +41,38 @@ class VerifyPhone implements ShouldQueue
*/
public function handle() : void
{
+ MultiDB::checkUserEmailExists($this->user->email);
- MultiDB::checkUserEmailExists($this->user->email);
+ $sid = config('ninja.twilio_account_sid');
+ $token = config('ninja.twilio_auth_token');
- $sid = config('ninja.twilio_account_sid');
- $token = config('ninja.twilio_auth_token');
+ if (!$sid) {
+ return;
+ } // no twilio api credentials provided, bail.
- if(!$sid)
- return; // no twilio api credentials provided, bail.
+ $twilio = new \Twilio\Rest\Client($sid, $token);
- $twilio = new \Twilio\Rest\Client($sid, $token);
+ $country = $this->user->account?->companies()?->first()?->country();
- $country = $this->user->account?->companies()?->first()?->country();
+ if (!$country || strlen($this->user->phone) < 2) {
+ return;
+ }
- if(!$country || strlen($this->user->phone) < 2)
- return;
+ $countryCode = $country->iso_3166_2;
- $countryCode = $country->iso_3166_2;
+ try {
+ $phone_number = $twilio->lookups->v1->phoneNumbers($this->user->phone)
+ ->fetch(["countryCode" => $countryCode]);
+ } catch(\Exception $e) {
+ $this->user->verified_phone_number = false;
+ $this->user->save();
+ return;
+ }
- try{
-
- $phone_number = $twilio->lookups->v1->phoneNumbers($this->user->phone)
- ->fetch(["countryCode" => $countryCode]);
- }
- catch(\Exception $e) {
- $this->user->verified_phone_number = false;
- $this->user->save();
- return;
- }
-
- if($phone_number && strlen($phone_number->phoneNumber) > 1)
- {
- $this->user->phone = $phone_number->phoneNumber;
- $this->user->verified_phone_number = true;
- $this->user->save();
- }
- }
-
-}
\ No newline at end of file
+ if ($phone_number && strlen($phone_number->phoneNumber) > 1) {
+ $this->user->phone = $phone_number->phoneNumber;
+ $this->user->verified_phone_number = true;
+ $this->user->save();
+ }
+ }
+}
diff --git a/app/Jobs/Util/ApplePayDomain.php b/app/Jobs/Util/ApplePayDomain.php
index 3e3c25b6fc83..b9e424e2e3ef 100644
--- a/app/Jobs/Util/ApplePayDomain.php
+++ b/app/Jobs/Util/ApplePayDomain.php
@@ -11,9 +11,7 @@
namespace App\Jobs\Util;
-use App\Jobs\Util\UnlinkFile;
use App\Libraries\MultiDB;
-use App\Models\Account;
use App\Models\CompanyGateway;
use App\Utils\Ninja;
use Illuminate\Bus\Queueable;
@@ -21,7 +19,6 @@ use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
-use Illuminate\Support\Facades\Storage;
class ApplePayDomain implements ShouldQueue
{
diff --git a/app/Jobs/Util/DiskCleanup.php b/app/Jobs/Util/DiskCleanup.php
index 46c6acfa2d50..9764fc86d26b 100644
--- a/app/Jobs/Util/DiskCleanup.php
+++ b/app/Jobs/Util/DiskCleanup.php
@@ -11,9 +11,6 @@
namespace App\Jobs\Util;
-use App\Jobs\Util\UnlinkFile;
-use App\Models\Account;
-use App\Utils\Ninja;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
diff --git a/app/Jobs/Util/Import.php b/app/Jobs/Util/Import.php
index 20f33d21f733..ca6c8143650c 100644
--- a/app/Jobs/Util/Import.php
+++ b/app/Jobs/Util/Import.php
@@ -15,10 +15,7 @@ use App\DataMapper\Analytics\MigrationFailure;
use App\DataMapper\CompanySettings;
use App\Exceptions\ClientHostedMigrationException;
use App\Exceptions\MigrationValidatorFailed;
-use App\Exceptions\ProcessingMigrationArchiveFailed;
use App\Exceptions\ResourceDependencyMissing;
-use App\Exceptions\ResourceNotAvailableForMigration;
-use App\Factory\ClientContactFactory;
use App\Factory\ClientFactory;
use App\Factory\CompanyLedgerFactory;
use App\Factory\CreditFactory;
@@ -31,19 +28,15 @@ use App\Factory\TaxRateFactory;
use App\Factory\UserFactory;
use App\Factory\VendorFactory;
use App\Http\Requests\Company\UpdateCompanyRequest;
-use App\Http\ValidationRules\User\AttachableUser;
use App\Http\ValidationRules\ValidCompanyGatewayFeesAndLimitsRule;
use App\Http\ValidationRules\ValidUserForCompany;
-use App\Jobs\Company\CreateCompanyTaskStatuses;
use App\Jobs\Company\CreateCompanyToken;
use App\Jobs\Mail\NinjaMailerJob;
use App\Jobs\Mail\NinjaMailerObject;
use App\Jobs\Ninja\CheckCompanyData;
-use App\Jobs\Ninja\CompanySizeCheck;
-use App\Jobs\Util\VersionCheck;
use App\Libraries\MultiDB;
-use App\Mail\MigrationCompleted;
use App\Mail\Migration\StripeConnectMigration;
+use App\Mail\MigrationCompleted;
use App\Models\Activity;
use App\Models\Client;
use App\Models\ClientContact;
@@ -74,7 +67,6 @@ use App\Repositories\CreditRepository;
use App\Repositories\Migration\InvoiceMigrationRepository;
use App\Repositories\Migration\PaymentMigrationRepository;
use App\Repositories\ProductRepository;
-use App\Repositories\QuoteRepository;
use App\Repositories\UserRepository;
use App\Repositories\VendorContactRepository;
use App\Repositories\VendorRepository;
@@ -191,7 +183,7 @@ class Import implements ShouldQueue
}
public function middleware()
- {
+ {
return [(new WithoutOverlapping($this->user->account_id))];
}
@@ -260,43 +252,40 @@ class Import implements ShouldQueue
$this->processNinjaTokens($data['ninja_tokens']);
// $this->fixData();
- try{
+ try {
App::forgetInstance('translator');
$t = app('translator');
$t->replace(Ninja::transformTranslations($this->company->settings));
Mail::to($this->user->email, $this->user->name())
- ->send(new MigrationCompleted($this->company->id, $this->company->db, implode("
",$check_data)));
- }
- catch(\Exception $e) {
+ ->send(new MigrationCompleted($this->company->id, $this->company->db, implode("
", $check_data)));
+ } catch(\Exception $e) {
nlog($e->getMessage());
}
/*After a migration first some basic jobs to ensure the system is up to date*/
- if(Ninja::isSelfHost())
+ if (Ninja::isSelfHost()) {
VersionCheck::dispatch();
+ }
info('Completed🚀🚀🚀🚀🚀 at '.now());
- try{
+ try {
unlink($this->file_path);
- }
- catch(\Exception $e){
+ } catch(\Exception $e) {
nlog("problem unsetting file");
}
}
private function fixData()
{
-
$this->company->clients()->withTrashed()->where('is_deleted', 0)->cursor()->each(function ($client) {
$total_invoice_payments = 0;
$credit_total_applied = 0;
foreach ($client->invoices()->where('is_deleted', false)->where('status_id', '>', 1)->get() as $invoice) {
-
- $total_amount = $invoice->payments()->where('is_deleted', false)->whereIn('status_id', [Payment::STATUS_COMPLETED, Payment:: STATUS_PENDING, Payment::STATUS_PARTIALLY_REFUNDED, Payment::STATUS_REFUNDED])->get()->sum('pivot.amount');
- $total_refund = $invoice->payments()->where('is_deleted', false)->whereIn('status_id', [Payment::STATUS_COMPLETED, Payment:: STATUS_PENDING, Payment::STATUS_PARTIALLY_REFUNDED, Payment::STATUS_REFUNDED])->get()->sum('pivot.refunded');
+ $total_amount = $invoice->payments()->where('is_deleted', false)->whereIn('status_id', [Payment::STATUS_COMPLETED, Payment::STATUS_PENDING, Payment::STATUS_PARTIALLY_REFUNDED, Payment::STATUS_REFUNDED])->get()->sum('pivot.amount');
+ $total_refund = $invoice->payments()->where('is_deleted', false)->whereIn('status_id', [Payment::STATUS_COMPLETED, Payment::STATUS_PENDING, Payment::STATUS_PARTIALLY_REFUNDED, Payment::STATUS_REFUNDED])->get()->sum('pivot.refunded');
$total_invoice_payments += ($total_amount - $total_refund);
}
@@ -308,23 +297,19 @@ class Import implements ShouldQueue
if ($credit_total_applied < 0) {
$total_invoice_payments += $credit_total_applied;
- }
+ }
if (round($total_invoice_payments, 2) != round($client->paid_to_date, 2)) {
-
$client->paid_to_date = $total_invoice_payments;
$client->save();
-
}
});
-
}
private function setInitialCompanyLedgerBalances()
{
Client::where('company_id', $this->company->id)->cursor()->each(function ($client) {
-
$invoice_balances = $client->invoices->where('is_deleted', false)->where('status_id', '>', 1)->sum('balance');
$company_ledger = CompanyLedgerFactory::create($client->company_id, $client->user_id);
@@ -339,13 +324,12 @@ class Import implements ShouldQueue
$client->balance = $invoice_balances;
$client->save();
-
});
}
private function processAccount(array $data) :void
{
- if(array_key_exists('token', $data)){
+ if (array_key_exists('token', $data)) {
$this->token = $data['token'];
unset($data['token']);
}
@@ -353,29 +337,33 @@ class Import implements ShouldQueue
$account = $this->company->account;
/* If the user has upgraded their account, do not wipe their payment plan*/
- if($account->isPaid() || (isset($data['plan']) && $data['plan'] == 'white_label'))
- {
- if(isset($data['plan']))
+ if ($account->isPaid() || (isset($data['plan']) && $data['plan'] == 'white_label')) {
+ if (isset($data['plan'])) {
unset($data['plan']);
+ }
- if(isset($data['plan_term']))
+ if (isset($data['plan_term'])) {
unset($data['plan_term']);
+ }
- if(isset($data['plan_paid']))
+ if (isset($data['plan_paid'])) {
unset($data['plan_paid']);
+ }
- if(isset($data['plan_started']))
+ if (isset($data['plan_started'])) {
unset($data['plan_started']);
+ }
- if(isset($data['plan_expires']))
+ if (isset($data['plan_expires'])) {
unset($data['plan_expires']);
+ }
}
$account->fill($data);
$account->save();
//Prevent hosted users being pushed into a trial
- if(Ninja::isHosted() && $account->plan != ''){
+ if (Ninja::isHosted() && $account->plan != '') {
$account->trial_plan = '';
$account->save();
}
@@ -395,32 +383,35 @@ class Import implements ShouldQueue
) {
$data['settings']['invoice_design_id'] = 1;
}
- $data['settings']['email_sending_method'] = 'default';
+ $data['settings']['email_sending_method'] = 'default';
$data = $this->transformCompanyData($data);
- if(Ninja::isHosted()) {
-
- if(!MultiDB::checkDomainAvailable($data['subdomain']))
+ if (Ninja::isHosted()) {
+ if (!MultiDB::checkDomainAvailable($data['subdomain'])) {
$data['subdomain'] = MultiDB::randomSubdomainGenerator();
+ }
- if(strlen($data['subdomain']) == 0)
+ if (strlen($data['subdomain']) == 0) {
$data['subdomain'] = MultiDB::randomSubdomainGenerator();
-
+ }
}
$rules = (new UpdateCompanyRequest())->rules();
$validator = Validator::make($data, $rules);
- if ($validator->fails())
+ if ($validator->fails()) {
throw new MigrationValidatorFailed(json_encode($validator->errors()));
+ }
- if (isset($data['account_id']))
+ if (isset($data['account_id'])) {
unset($data['account_id']);
+ }
- if(isset($data['version']))
+ if (isset($data['version'])) {
unset($data['version']);
+ }
if (isset($data['referral_code'])) {
$account = $this->company->account;
@@ -438,18 +429,15 @@ class Import implements ShouldQueue
$company_repository->save($data, $this->company);
if (isset($data['settings']->company_logo) && strlen($data['settings']->company_logo) > 0) {
-
try {
$tempImage = tempnam(sys_get_temp_dir(), basename($data['settings']->company_logo));
copy($data['settings']->company_logo, $tempImage);
$this->uploadLogo($tempImage, $this->company, $this->company);
} catch (\Exception $e) {
-
$settings = $this->company->settings;
$settings->company_logo = '';
$this->company->settings = $settings;
$this->company->save();
-
}
}
@@ -464,24 +452,29 @@ class Import implements ShouldQueue
private function parseCustomFields($fields) :array
{
-
- if(array_key_exists('account1', $fields))
+ if (array_key_exists('account1', $fields)) {
$fields['company1'] = $fields['account1'];
+ }
- if(array_key_exists('account2', $fields))
+ if (array_key_exists('account2', $fields)) {
$fields['company2'] = $fields['account2'];
+ }
- if(array_key_exists('invoice1', $fields))
+ if (array_key_exists('invoice1', $fields)) {
$fields['surcharge1'] = $fields['invoice1'];
+ }
- if(array_key_exists('invoice2', $fields))
+ if (array_key_exists('invoice2', $fields)) {
$fields['surcharge2'] = $fields['invoice2'];
+ }
- if(array_key_exists('invoice_text1', $fields))
+ if (array_key_exists('invoice_text1', $fields)) {
$fields['invoice1'] = $fields['invoice_text1'];
+ }
- if(array_key_exists('invoice_text2', $fields))
+ if (array_key_exists('invoice_text2', $fields)) {
$fields['invoice2'] = $fields['invoice_text2'];
+ }
foreach ($fields as &$value) {
$value = (string) $value;
@@ -492,7 +485,6 @@ class Import implements ShouldQueue
private function transformCompanyData(array $data): array
{
-
$company_settings = CompanySettings::defaults();
if (array_key_exists('settings', $data)) {
@@ -500,9 +492,9 @@ class Import implements ShouldQueue
if ($key == 'invoice_design_id' || $key == 'quote_design_id' || $key == 'credit_design_id') {
$value = $this->encodePrimaryKey($value);
- if(!$value)
+ if (!$value) {
$value = $this->encodePrimaryKey(1);
-
+ }
}
/* changes $key = '' to $value == '' and changed the return value from -1 to "0" 06/01/2022 */
@@ -512,17 +504,15 @@ class Import implements ShouldQueue
$company_settings->{$key} = $value;
- if($key == 'payment_terms'){
+ if ($key == 'payment_terms') {
settype($company_settings->payment_terms, 'string');
}
-
}
- if(Ninja::isHosted())
- {
- $data['portal_mode'] = 'subdomain';
- $data['portal_domain'] = '';
- }
+ if (Ninja::isHosted()) {
+ $data['portal_mode'] = 'subdomain';
+ $data['portal_domain'] = '';
+ }
$data['settings'] = $company_settings;
}
@@ -572,7 +562,7 @@ class Import implements ShouldQueue
TaxRate::reguard();
- if(TaxRate::count() > 0){
+ if (TaxRate::count() > 0) {
$this->company->enabled_tax_rates = 2;
$this->company->save();
}
@@ -585,9 +575,9 @@ class Import implements ShouldQueue
private function testUserDbLocationSanity(array $data): bool
{
-
- if(Ninja::isSelfHost())
+ if (Ninja::isSelfHost()) {
return true;
+ }
$current_db = config('database.default');
@@ -596,11 +586,13 @@ class Import implements ShouldQueue
MultiDB::setDb($current_db);
- if($db2_count == 0 && $db1_count == 0)
+ if ($db2_count == 0 && $db1_count == 0) {
return true;
+ }
- if($db1_count >= 1 && $db2_count >= 1)
+ if ($db1_count >= 1 && $db2_count >= 1) {
return false;
+ }
return true;
}
@@ -611,8 +603,9 @@ class Import implements ShouldQueue
*/
private function processUsers(array $data): void
{
- if(!$this->testUserDbLocationSanity($data))
+ if (!$this->testUserDbLocationSanity($data)) {
throw new ClientHostedMigrationException('You have users that belong to different accounts registered in the system, please contact us to resolve.', 400);
+ }
User::unguard();
@@ -642,8 +635,9 @@ class Import implements ShouldQueue
$user->email_verified_at = now();
// $user->confirmation_code = '';
- if($modified['deleted_at'])
+ if ($modified['deleted_at']) {
$user->deleted_at = now();
+ }
$user->password = $modified['password'];
$user->save();
@@ -678,8 +672,9 @@ class Import implements ShouldQueue
->withTrashed()
->exists();
- if($model_query)
+ if ($model_query) {
return $value . '_' . Str::random(5);
+ }
return $value;
}
@@ -714,11 +709,13 @@ class Import implements ShouldQueue
)
);
- if(array_key_exists('created_at', $modified))
+ if (array_key_exists('created_at', $modified)) {
$client->created_at = Carbon::parse($modified['created_at']);
+ }
- if(array_key_exists('updated_at', $modified))
+ if (array_key_exists('updated_at', $modified)) {
$client->updated_at = Carbon::parse($modified['updated_at']);
+ }
$client->country_id = array_key_exists('country_id', $modified) ? $modified['country_id'] : $this->company->settings->country_id;
$client->save(['timestamps' => false]);
@@ -733,7 +730,7 @@ class Import implements ShouldQueue
$modified_contacts[$key]['company_id'] = $this->company->id;
$modified_contacts[$key]['user_id'] = $this->processUserId($resource);
$modified_contacts[$key]['client_id'] = $client->id;
- $modified_contacts[$key]['password'] = Str::random(8);
+ $modified_contacts[$key]['password'] = Str::random(8);
unset($modified_contacts[$key]['id']);
}
@@ -744,7 +741,6 @@ class Import implements ShouldQueue
//link contact ids
foreach ($resource['contacts'] as $key => $old_contact) {
-
$contact_match = ClientContact::where('contact_key', $old_contact['contact_key'])
->where('company_id', $this->company->id)
->where('client_id', $client->id)
@@ -752,12 +748,10 @@ class Import implements ShouldQueue
->first();
if ($contact_match) {
-
$this->ids['client_contacts']['client_contacts_'.$old_contact['id']] = [
'old' => $old_contact['id'],
'new' => $contact_match->id,
];
-
}
}
}
@@ -774,12 +768,10 @@ class Import implements ShouldQueue
Client::reguard();
- Client::withTrashed()->with('contacts')->where('company_id', $this->company->id)->cursor()->each(function ($client){
-
- $contact = $client->contacts->sortByDesc('is_primary')->first();
- $contact->is_primary = true;
- $contact->save();
-
+ Client::withTrashed()->with('contacts')->where('company_id', $this->company->id)->cursor()->each(function ($client) {
+ $contact = $client->contacts->sortByDesc('is_primary')->first();
+ $contact->is_primary = true;
+ $contact->save();
});
@@ -809,11 +801,13 @@ class Import implements ShouldQueue
unset($modified['id']);
unset($modified['contacts']);
- if(array_key_exists('created_at', $modified))
+ if (array_key_exists('created_at', $modified)) {
$modified['created_at'] = Carbon::parse($modified['created_at']);
+ }
- if(array_key_exists('updated_at', $modified))
+ if (array_key_exists('updated_at', $modified)) {
$modified['updated_at'] = Carbon::parse($modified['updated_at']);
+ }
$vendor = $vendor_repository->save(
$modified,
@@ -882,11 +876,13 @@ class Import implements ShouldQueue
$modified['company_id'] = $this->company->id;
$modified['user_id'] = $this->processUserId($resource);
- if(array_key_exists('created_at', $modified))
+ if (array_key_exists('created_at', $modified)) {
$modified['created_at'] = Carbon::parse($modified['created_at']);
+ }
- if(array_key_exists('updated_at', $modified))
+ if (array_key_exists('updated_at', $modified)) {
$modified['updated_at'] = Carbon::parse($modified['updated_at']);
+ }
unset($modified['id']);
@@ -942,11 +938,13 @@ class Import implements ShouldQueue
$expense = RecurringExpense::create($modified);
- if(array_key_exists('created_at', $modified))
+ if (array_key_exists('created_at', $modified)) {
$expense->created_at = Carbon::parse($modified['created_at']);
+ }
- if(array_key_exists('updated_at', $modified))
+ if (array_key_exists('updated_at', $modified)) {
$expense->updated_at = Carbon::parse($modified['updated_at']);
+ }
$expense->save(['timestamps' => false]);
@@ -958,7 +956,6 @@ class Import implements ShouldQueue
'old' => $resource['id'],
'new' => $expense->id,
];
-
}
@@ -996,14 +993,17 @@ class Import implements ShouldQueue
$modified['company_id'] = $this->company->id;
$modified['line_items'] = $this->cleanItems($modified['line_items']);
- if(array_key_exists('next_send_date', $resource))
+ if (array_key_exists('next_send_date', $resource)) {
$modified['next_send_date_client'] = $resource['next_send_date'];
+ }
- if(array_key_exists('created_at', $modified))
+ if (array_key_exists('created_at', $modified)) {
$modified['created_at'] = Carbon::parse($modified['created_at']);
+ }
- if(array_key_exists('updated_at', $modified))
+ if (array_key_exists('updated_at', $modified)) {
$modified['updated_at'] = Carbon::parse($modified['updated_at']);
+ }
unset($modified['id']);
@@ -1016,11 +1016,9 @@ class Import implements ShouldQueue
unset($resource['invitations'][$key]['recurring_invoice_id']);
unset($resource['invitations'][$key]['id']);
-
}
$modified['invitations'] = $this->deDuplicateInvitations($resource['invitations']);
-
}
$invoice = $invoice_repository->save(
@@ -1028,7 +1026,7 @@ class Import implements ShouldQueue
RecurringInvoiceFactory::create($this->company->id, $modified['user_id'])
);
- if($invoice->status_id == 4 && $invoice->remaining_cycles == -1){
+ if ($invoice->status_id == 4 && $invoice->remaining_cycles == -1) {
$invoice->status_id =2;
$invoice->save();
}
@@ -1073,8 +1071,9 @@ class Import implements ShouldQueue
$modified['client_id'] = $this->transformId('clients', $resource['client_id']);
- if(array_key_exists('recurring_id', $resource) && !is_null($resource['recurring_id']))
+ if (array_key_exists('recurring_id', $resource) && !is_null($resource['recurring_id'])) {
$modified['recurring_id'] = $this->transformId('recurring_invoices', (string)$resource['recurring_id']);
+ }
$modified['user_id'] = $this->processUserId($resource);
$modified['company_id'] = $this->company->id;
@@ -1093,7 +1092,6 @@ class Import implements ShouldQueue
}
$modified['invitations'] = $this->deDuplicateInvitations($resource['invitations']);
-
}
$invoice = $invoice_repository->save(
@@ -1119,7 +1117,7 @@ class Import implements ShouldQueue
/* Prevent edge case where V4 has inserted multiple invitations for a resource for a client contact */
private function deDuplicateInvitations($invitations)
- {
+ {
return array_intersect_key($invitations, array_unique(array_column($invitations, 'client_contact_id')));
}
@@ -1150,11 +1148,13 @@ class Import implements ShouldQueue
$modified['user_id'] = $this->processUserId($resource);
$modified['company_id'] = $this->company->id;
- if(array_key_exists('created_at', $modified))
+ if (array_key_exists('created_at', $modified)) {
$modified['created_at'] = Carbon::parse($modified['created_at']);
+ }
- if(array_key_exists('updated_at', $modified))
+ if (array_key_exists('updated_at', $modified)) {
$modified['updated_at'] = Carbon::parse($modified['updated_at']);
+ }
unset($modified['id']);
@@ -1164,7 +1164,7 @@ class Import implements ShouldQueue
);
//remove credit balance from ledger
- if($credit->balance > 0 && $credit->client->balance > 0){
+ if ($credit->balance > 0 && $credit->client->balance > 0) {
$client = $credit->client;
$client->balance -= $credit->balance;
$client->save();
@@ -1184,7 +1184,6 @@ class Import implements ShouldQueue
/*Improve memory handling by setting everything to null when we have finished*/
$data = null;
$credit_repository = null;
-
}
private function processQuotes(array $data): void
@@ -1212,24 +1211,29 @@ class Import implements ShouldQueue
$modified['client_id'] = $this->transformId('clients', $resource['client_id']);
- if(array_key_exists('invoice_id', $resource) && isset($resource['invoice_id']) && $this->tryTransformingId('invoices', $resource['invoice_id']))
+ if (array_key_exists('invoice_id', $resource) && isset($resource['invoice_id']) && $this->tryTransformingId('invoices', $resource['invoice_id'])) {
$modified['invoice_id'] = $this->transformId('invoices', $resource['invoice_id']);
+ }
$modified['user_id'] = $this->processUserId($resource);
$modified['company_id'] = $this->company->id;
- if(array_key_exists('created_at', $modified))
+ if (array_key_exists('created_at', $modified)) {
$modified['created_at'] = Carbon::parse($modified['created_at']);
+ }
- if(array_key_exists('updated_at', $modified))
+ if (array_key_exists('updated_at', $modified)) {
$modified['updated_at'] = Carbon::parse($modified['updated_at']);
+ }
- if(array_key_exists('tax_rate1', $modified) && is_null($modified['tax_rate1']))
+ if (array_key_exists('tax_rate1', $modified) && is_null($modified['tax_rate1'])) {
$modified['tax_rate1'] = 0;
+ }
- if(array_key_exists('tax_rate2', $modified) && is_null($modified['tax_rate2']))
+ if (array_key_exists('tax_rate2', $modified) && is_null($modified['tax_rate2'])) {
$modified['tax_rate2'] = 0;
+ }
unset($modified['id']);
@@ -1245,7 +1249,6 @@ class Import implements ShouldQueue
}
$modified['invitations'] = $this->deDuplicateInvitations($resource['invitations']);
-
}
$quote = $quote_repository->save(
@@ -1253,11 +1256,13 @@ class Import implements ShouldQueue
QuoteFactory::create($this->company->id, $modified['user_id'])
);
- if(array_key_exists('created_at', $modified))
+ if (array_key_exists('created_at', $modified)) {
$quote->created_at = $modified['created_at'];
+ }
- if(array_key_exists('updated_at', $modified))
+ if (array_key_exists('updated_at', $modified)) {
$quote->updated_at = $modified['updated_at'];
+ }
$quote->save(['timestamps' => false]);
@@ -1313,9 +1318,9 @@ class Import implements ShouldQueue
if ($this->tryTransformingId('invoices', $invoice['invoice_id'])) {
$modified['invoices'][$key]['invoice_id'] = $this->transformId('invoices', $invoice['invoice_id']);
} else {
- nlog($modified['invoices']);
- unset($modified['invoices']);
- //if the transformation didn't work - you _must_ unset this data as it will be incorrect!
+ nlog($modified['invoices']);
+ unset($modified['invoices']);
+ //if the transformation didn't work - you _must_ unset this data as it will be incorrect!
}
}
}
@@ -1325,18 +1330,20 @@ class Import implements ShouldQueue
PaymentFactory::create($this->company->id, $modified['user_id'])
);
- if(array_key_exists('created_at', $modified))
+ if (array_key_exists('created_at', $modified)) {
$payment->created_at = Carbon::parse($modified['created_at']);
+ }
- if(array_key_exists('updated_at', $modified))
+ if (array_key_exists('updated_at', $modified)) {
$payment->updated_at = Carbon::parse($modified['updated_at']);
+ }
$payment->save(['timestamps' => false]);
if (array_key_exists('company_gateway_id', $resource) && isset($resource['company_gateway_id']) && $resource['company_gateway_id'] != 'NULL') {
-
- if($this->tryTransformingId('company_gateways', $resource['company_gateway_id']))
+ if ($this->tryTransformingId('company_gateways', $resource['company_gateway_id'])) {
$payment->company_gateway_id = $this->transformId('company_gateways', $resource['company_gateway_id']);
+ }
$payment->save();
}
@@ -1351,11 +1358,9 @@ class Import implements ShouldQueue
],
];
- if(in_array($payment->status_id, [Payment::STATUS_REFUNDED, Payment::STATUS_PARTIALLY_REFUNDED])) {
+ if (in_array($payment->status_id, [Payment::STATUS_REFUNDED, Payment::STATUS_PARTIALLY_REFUNDED])) {
$this->processPaymentRefund($payment);
}
-
-
}
Payment::reguard();
@@ -1369,17 +1374,14 @@ class Import implements ShouldQueue
{
$invoices = $payment->invoices()->get();
- $invoices->each(function ($invoice) use($payment) {
-
+ $invoices->each(function ($invoice) use ($payment) {
if ($payment->refunded > 0 && in_array($invoice->status_id, [Invoice::STATUS_SENT])) {
-
$invoice->service()
->updateBalance($payment->refunded)
->updatePaidToDate($payment->refunded*-1)
->updateStatus()
->save();
}
-
});
}
@@ -1428,7 +1430,6 @@ class Import implements ShouldQueue
/* No validators since data provided by database is already valid. */
foreach ($data as $resource) {
-
$modified = $resource;
if (array_key_exists('invoice_id', $resource) && $resource['invoice_id'] && ! array_key_exists('invoices', $this->ids)) {
@@ -1442,39 +1443,34 @@ class Import implements ShouldQueue
}
if (array_key_exists('invoice_id', $resource) && $resource['invoice_id'] && array_key_exists('invoices', $this->ids)) {
-
$try_quote = false;
$exception = false;
$entity = false;
- try{
+ try {
$invoice_id = $this->transformId('invoices', $resource['invoice_id']);
$entity = Invoice::where('id', $invoice_id)->withTrashed()->first();
- }
- catch(\Exception $e){
+ } catch(\Exception $e) {
nlog("i couldn't find the invoice document {$resource['invoice_id']}, perhaps it is a quote?");
nlog($e->getMessage());
$try_quote = true;
}
- if($try_quote && array_key_exists('quotes', $this->ids) ) {
-
- try{
+ if ($try_quote && array_key_exists('quotes', $this->ids)) {
+ try {
$quote_id = $this->transformId('quotes', $resource['invoice_id']);
$entity = Quote::where('id', $quote_id)->withTrashed()->first();
- }
- catch(\Exception $e){
+ } catch(\Exception $e) {
nlog("i couldn't find the quote document {$resource['invoice_id']}, perhaps it is a quote?");
nlog($e->getMessage());
}
}
- if(!$entity)
+ if (!$entity) {
continue;
+ }
// throw new Exception("Resource invoice/quote document not available.");
-
-
}
@@ -1493,24 +1489,19 @@ class Import implements ShouldQueue
$file_info = $finfo->file($file_path);
$uploaded_file = new UploadedFile(
- $file_path,
- $file_name,
- $file_info,
- filesize($file_path),
- 0,
- false
- );
+ $file_path,
+ $file_name,
+ $file_info,
+ filesize($file_path),
+ 0,
+ false
+ );
$this->saveDocument($uploaded_file, $entity, $is_public = true);
- }
- catch(\Exception $e) {
-
+ } catch(\Exception $e) {
//do nothing, gracefully :)
-
}
-
}
-
}
private function processPaymentTerms(array $data) :void
@@ -1564,12 +1555,12 @@ class Import implements ShouldQueue
$modified['fees_and_limits'] = $this->cleanFeesAndLimits($modified['fees_and_limits']);
}
- if(!array_key_exists('accepted_credit_cards', $modified) || (array_key_exists('accepted_credit_cards', $modified) && empty($modified['accepted_credit_cards'])))
+ if (!array_key_exists('accepted_credit_cards', $modified) || (array_key_exists('accepted_credit_cards', $modified) && empty($modified['accepted_credit_cards']))) {
$modified['accepted_credit_cards'] = 0;
+ }
// /* On Hosted platform we need to advise Stripe users to connect with Stripe Connect */
- if(Ninja::isHosted() && $modified['gateway_key'] == 'd14dd26a37cecc30fdd65700bfb55b23'){
-
+ if (Ninja::isHosted() && $modified['gateway_key'] == 'd14dd26a37cecc30fdd65700bfb55b23') {
$nmo = new NinjaMailerObject;
$nmo->mailable = new StripeConnectMigration($this->company);
$nmo->company = $this->company;
@@ -1578,13 +1569,10 @@ class Import implements ShouldQueue
NinjaMailerJob::dispatch($nmo, true);
$modified['gateway_key'] = 'd14dd26a47cecc30fdd65700bfb67b34';
-
}
- if(Ninja::isSelfHost() && $modified['gateway_key'] == 'd14dd26a47cecc30fdd65700bfb67b34'){
-
+ if (Ninja::isSelfHost() && $modified['gateway_key'] == 'd14dd26a47cecc30fdd65700bfb67b34') {
$modified['gateway_key'] = 'd14dd26a37cecc30fdd65700bfb55b23';
-
}
@@ -1686,7 +1674,6 @@ class Import implements ShouldQueue
'old' => $resource['id'],
'new' => $expense_category->id,
];
-
}
ExpenseCategory::reguard();
@@ -1724,11 +1711,13 @@ class Import implements ShouldQueue
$task = Task::Create($modified);
- if(array_key_exists('created_at', $modified))
+ if (array_key_exists('created_at', $modified)) {
$task->created_at = Carbon::parse($modified['created_at']);
+ }
- if(array_key_exists('updated_at', $modified))
+ if (array_key_exists('updated_at', $modified)) {
$task->updated_at = Carbon::parse($modified['updated_at']);
+ }
@@ -1814,11 +1803,13 @@ class Import implements ShouldQueue
$expense = Expense::Create($modified);
- if(array_key_exists('created_at', $modified))
+ if (array_key_exists('created_at', $modified)) {
$expense->created_at = Carbon::parse($modified['created_at']);
+ }
- if(array_key_exists('updated_at', $modified))
+ if (array_key_exists('updated_at', $modified)) {
$expense->updated_at = Carbon::parse($modified['updated_at']);
+ }
@@ -1832,7 +1823,6 @@ class Import implements ShouldQueue
'old' => $resource['id'],
'new' => $expense->id,
];
-
}
Expense::reguard();
@@ -1873,7 +1863,6 @@ class Import implements ShouldQueue
*/
public function transformId($resource, string $old): int
{
-
if (! array_key_exists($resource, $this->ids)) {
info(print_r($resource, 1));
throw new Exception("Resource {$resource} not available.");
@@ -1934,23 +1923,22 @@ class Import implements ShouldQueue
info(print_r($exception->getMessage(), 1));
- if(Ninja::isHosted())
+ if (Ninja::isHosted()) {
app('sentry')->captureException($exception);
+ }
}
public function curlGet($url, $headers = false)
{
-
return $this->exec('GET', $url, null);
}
public function exec($method, $url, $data)
{
-
- $client = new \GuzzleHttp\Client(['headers' =>
- [
- 'X-Ninja-Token' => $this->token,
+ $client = new \GuzzleHttp\Client(['headers' =>
+ [
+ 'X-Ninja-Token' => $this->token,
]
]);
@@ -1963,20 +1951,15 @@ class Import implements ShouldQueue
private function processNinjaTokens(array $data)
{
-
nlog("attempting to process Ninja Tokens");
- if(Ninja::isHosted()){
-
- try{
+ if (Ninja::isHosted()) {
+ try {
\Modules\Admin\Jobs\Account\NinjaUser::dispatch($data, $this->company);
- }
- catch(\Exception $e){
+ } catch(\Exception $e) {
nlog($e->getMessage());
}
-
}
-
}
/* In V4 we use negative invoices (credits) and add then into the client balance. In V5, these sit off ledger and are applied later.
diff --git a/app/Jobs/Util/RefreshPdfs.php b/app/Jobs/Util/RefreshPdfs.php
index ab8fbadc3e85..cdc5a2c5ccdb 100644
--- a/app/Jobs/Util/RefreshPdfs.php
+++ b/app/Jobs/Util/RefreshPdfs.php
@@ -12,21 +12,16 @@
namespace App\Jobs\Util;
use App\Jobs\Entity\CreateEntityPdf;
-use App\Jobs\Util\UnlinkFile;
use App\Libraries\MultiDB;
-use App\Models\Account;
use App\Models\Company;
use App\Models\CreditInvitation;
use App\Models\InvoiceInvitation;
use App\Models\QuoteInvitation;
-use App\Utils\Ninja;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
-use Illuminate\Support\Facades\DB;
-use Illuminate\Support\Facades\Storage;
class RefreshPdfs implements ShouldQueue
{
diff --git a/app/Jobs/Util/ReminderJob.php b/app/Jobs/Util/ReminderJob.php
index 2e31aa95fa94..2aef984496d4 100644
--- a/app/Jobs/Util/ReminderJob.php
+++ b/app/Jobs/Util/ReminderJob.php
@@ -46,12 +46,9 @@ class ReminderJob implements ShouldQueue
*/
public function handle() :void
{
-
set_time_limit(0);
- if (! config('ninja.db.multi_db_enabled'))
- {
-
+ if (! config('ninja.db.multi_db_enabled')) {
nlog("Sending invoice reminders on ".now()->format('Y-m-d h:i:s'));
Invoice::query()
@@ -68,23 +65,16 @@ class ReminderJob implements ShouldQueue
$query->where('is_disabled', 0);
})
->with('invitations')->chunk(50, function ($invoices) {
-
- foreach($invoices as $invoice)
- {
- $this->sendReminderForInvoice($invoice);
- }
-
- sleep(2);
+ foreach ($invoices as $invoice) {
+ $this->sendReminderForInvoice($invoice);
+ }
+ sleep(2);
});
-
-
} else {
//multiDB environment, need to
- foreach (MultiDB::$dbs as $db)
- {
-
+ foreach (MultiDB::$dbs as $db) {
MultiDB::setDB($db);
nlog("Sending invoice reminders on db {$db} ".now()->format('Y-m-d h:i:s'));
@@ -105,67 +95,58 @@ class ReminderJob implements ShouldQueue
->with('invitations')->chunk(50, function ($invoices) {
// if ($invoice->refresh() && $invoice->isPayable()) {
- foreach($invoices as $invoice)
- {
- $this->sendReminderForInvoice($invoice);
- }
+ foreach ($invoices as $invoice) {
+ $this->sendReminderForInvoice($invoice);
+ }
- sleep(2);
-
+ sleep(2);
});
-
}
-
}
}
- private function sendReminderForInvoice($invoice) {
-
+ private function sendReminderForInvoice($invoice)
+ {
if ($invoice->isPayable()) {
-
//Attempts to prevent duplicates from sending
- if($invoice->reminder_last_sent && Carbon::parse($invoice->reminder_last_sent)->startOfDay()->eq(now()->startOfDay())){
+ if ($invoice->reminder_last_sent && Carbon::parse($invoice->reminder_last_sent)->startOfDay()->eq(now()->startOfDay())) {
nlog("caught a duplicate reminder for invoice {$invoice->number}");
return;
}
- $reminder_template = $invoice->calculateTemplate('invoice');
- nlog("reminder template = {$reminder_template}");
- $invoice->service()->touchReminder($reminder_template)->save();
- $invoice = $this->calcLateFee($invoice, $reminder_template);
+ $reminder_template = $invoice->calculateTemplate('invoice');
+ nlog("reminder template = {$reminder_template}");
+ $invoice->service()->touchReminder($reminder_template)->save();
+ $invoice = $this->calcLateFee($invoice, $reminder_template);
- //20-04-2022 fixes for endless reminders - generic template naming was wrong
- $enabled_reminder = 'enable_'.$reminder_template;
- if ($reminder_template == 'endless_reminder') {
- $enabled_reminder = 'enable_reminder_endless';
- }
+ //20-04-2022 fixes for endless reminders - generic template naming was wrong
+ $enabled_reminder = 'enable_'.$reminder_template;
+ if ($reminder_template == 'endless_reminder') {
+ $enabled_reminder = 'enable_reminder_endless';
+ }
- //check if this reminder needs to be emailed
- //15-01-2022 - insert addition if block if send_reminders is definitely set
- if (in_array($reminder_template, ['reminder1', 'reminder2', 'reminder3', 'reminder_endless', 'endless_reminder']) &&
+ //check if this reminder needs to be emailed
+ //15-01-2022 - insert addition if block if send_reminders is definitely set
+ if (in_array($reminder_template, ['reminder1', 'reminder2', 'reminder3', 'reminder_endless', 'endless_reminder']) &&
$invoice->client->getSetting($enabled_reminder) &&
$invoice->client->getSetting('send_reminders') &&
(Ninja::isSelfHost() || $invoice->company->account->isPaidHostedClient())) {
-
- $invoice->invitations->each(function ($invitation) use ($invoice, $reminder_template) {
-
- if($invitation->contact && !$invitation->contact->trashed() && $invitation->contact->email) {
- EmailEntity::dispatch($invitation, $invitation->company, $reminder_template)->delay(now()->addSeconds(3));
- nlog("Firing reminder email for invoice {$invoice->number} - {$reminder_template}");
+ $invoice->invitations->each(function ($invitation) use ($invoice, $reminder_template) {
+ if ($invitation->contact && !$invitation->contact->trashed() && $invitation->contact->email) {
+ EmailEntity::dispatch($invitation, $invitation->company, $reminder_template)->delay(now()->addSeconds(3));
+ nlog("Firing reminder email for invoice {$invoice->number} - {$reminder_template}");
}
+ });
- });
-
- if ($invoice->invitations->count() > 0) {
- event(new InvoiceWasEmailed($invoice->invitations->first(), $invoice->company, Ninja::eventVars(), $reminder_template));
- }
- }
- $invoice->service()->setReminder()->save();
- } else {
- $invoice->next_send_date = null;
- $invoice->save();
- }
-
+ if ($invoice->invitations->count() > 0) {
+ event(new InvoiceWasEmailed($invoice->invitations->first(), $invoice->company, Ninja::eventVars(), $reminder_template));
+ }
+ }
+ $invoice->service()->setReminder()->save();
+ } else {
+ $invoice->next_send_date = null;
+ $invoice->save();
+ }
}
/**
diff --git a/app/Jobs/Util/SchedulerCheck.php b/app/Jobs/Util/SchedulerCheck.php
index c20508089ed5..6c45287fc384 100644
--- a/app/Jobs/Util/SchedulerCheck.php
+++ b/app/Jobs/Util/SchedulerCheck.php
@@ -11,7 +11,6 @@
namespace App\Jobs\Util;
-use App\Models\Account;
use App\Utils\Ninja;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
@@ -40,8 +39,9 @@ class SchedulerCheck implements ShouldQueue
set_time_limit(0);
- if(Ninja::isHosted())
+ if (Ninja::isHosted()) {
return;
+ }
if (config('ninja.app_version') != base_path('VERSION.txt')) {
try {
diff --git a/app/Jobs/Util/UpdateExchangeRates.php b/app/Jobs/Util/UpdateExchangeRates.php
index 8a4c0cb7f91d..b6437627f721 100644
--- a/app/Jobs/Util/UpdateExchangeRates.php
+++ b/app/Jobs/Util/UpdateExchangeRates.php
@@ -63,28 +63,23 @@ class UpdateExchangeRates implements ShouldQueue
$currencies = Currency::orderBy('name')->get();
Cache::forever('currencies', $currencies);
-
-
}
} else {
-
- $client = new Client();
- $response = $client->get($cc_endpoint);
+ $client = new Client();
+ $response = $client->get($cc_endpoint);
- $currency_api = json_decode($response->getBody());
+ $currency_api = json_decode($response->getBody());
- /* Update all currencies */
- Currency::all()->each(function ($currency) use ($currency_api) {
- $currency->exchange_rate = $currency_api->rates->{$currency->code};
- $currency->save();
- });
+ /* Update all currencies */
+ Currency::all()->each(function ($currency) use ($currency_api) {
+ $currency->exchange_rate = $currency_api->rates->{$currency->code};
+ $currency->save();
+ });
- /* Rebuild the cache */
- $currencies = Currency::orderBy('name')->get();
-
- Cache::forever('currencies', $currencies);
+ /* Rebuild the cache */
+ $currencies = Currency::orderBy('name')->get();
+ Cache::forever('currencies', $currencies);
}
}
-
}
diff --git a/app/Jobs/Util/VersionCheck.php b/app/Jobs/Util/VersionCheck.php
index 552a5d566665..c21fb1d4ac63 100644
--- a/app/Jobs/Util/VersionCheck.php
+++ b/app/Jobs/Util/VersionCheck.php
@@ -42,7 +42,6 @@ class VersionCheck implements ShouldQueue
}
if (Ninja::isSelfHost()) {
-
nlog("latest version = {$version_file}");
$account = Account::first();
diff --git a/app/Jobs/Util/WebhookHandler.php b/app/Jobs/Util/WebhookHandler.php
index fae6d59d3a21..fd5f5d228fb7 100644
--- a/app/Jobs/Util/WebhookHandler.php
+++ b/app/Jobs/Util/WebhookHandler.php
@@ -11,7 +11,6 @@
namespace App\Jobs\Util;
-use App\Jobs\Util\WebhookSingle;
use App\Libraries\MultiDB;
use App\Models\Company;
use App\Models\Webhook;
@@ -22,7 +21,6 @@ use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
-
class WebhookHandler implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
@@ -38,7 +36,9 @@ class WebhookHandler implements ShouldQueue
* @param $event_id
* @param $entity
*/
- public function __construct(private int $event_id, private $entity, private Company $company, private string $includes = ''){}
+ public function __construct(private int $event_id, private $entity, private Company $company, private string $includes = '')
+ {
+ }
/**
* Execute the job.
@@ -47,7 +47,6 @@ class WebhookHandler implements ShouldQueue
*/
public function handle()
{
-
MultiDB::setDb($this->company->db);
//If the company is disabled, or if on hosted, the user is not a paid hosted user return early
@@ -59,15 +58,11 @@ class WebhookHandler implements ShouldQueue
->where('event_id', $this->event_id)
->cursor()
->each(function ($subscription) {
-
- WebhookSingle::dispatch($subscription->id, $this->entity, $this->company->db, $this->includes);
-
- });
-
+ WebhookSingle::dispatch($subscription->id, $this->entity, $this->company->db, $this->includes);
+ });
}
public function failed($exception = null)
{
-
}
}
diff --git a/app/Jobs/Util/WebhookSingle.php b/app/Jobs/Util/WebhookSingle.php
index 6c76c56b68c3..b780fcd523aa 100644
--- a/app/Jobs/Util/WebhookSingle.php
+++ b/app/Jobs/Util/WebhookSingle.php
@@ -11,13 +11,9 @@
namespace App\Jobs\Util;
-use App\Jobs\Util\SystemLogger;
use App\Libraries\MultiDB;
-use App\Models\Client as ClientModel;
use App\Models\Company;
-use App\Models\Product;
use App\Models\SystemLog;
-use App\Models\Vendor;
use App\Models\Webhook;
use App\Transformers\ArraySerializer;
use GuzzleHttp\Client;
@@ -76,15 +72,15 @@ class WebhookSingle implements ShouldQueue
*/
public function handle()
{
-
MultiDB::setDb($this->db);
$subscription = Webhook::with('company')->find($this->subscription_id);
- if($subscription)
+ if ($subscription) {
nlog("firing event ID {$subscription->event_id}");
+ }
- if(!$subscription){
+ if (!$subscription) {
$this->fail();
nlog("failed to fire event, could not find webhook ID {$this->subscription_id}");
@@ -133,10 +129,7 @@ class WebhookSingle implements ShouldQueue
$this->resolveClient(),
$this->company
);
-
- }
- catch(\GuzzleHttp\Exception\ConnectException $e){
-
+ } catch(\GuzzleHttp\Exception\ConnectException $e) {
nlog("connection problem");
nlog($e->getCode());
nlog($e->getMessage());
@@ -149,12 +142,8 @@ class WebhookSingle implements ShouldQueue
$this->resolveClient(),
$this->company
);
-
- }
- catch (BadResponseException $e) {
-
- if ($e->getResponse()->getStatusCode() >= 400 && $e->getResponse()->getStatusCode() < 500){
-
+ } catch (BadResponseException $e) {
+ if ($e->getResponse()->getStatusCode() >= 400 && $e->getResponse()->getStatusCode() < 500) {
$message = "Server encountered a problem when connecting to {$subscription->target_url} => status code ". $e->getResponse()->getStatusCode(). " scheduling retry.";
nlog($message);
@@ -169,10 +158,9 @@ class WebhookSingle implements ShouldQueue
);
$this->release($this->backoff()[$this->attempts()-1]);
-
}
- if($e->getResponse()->getStatusCode() >= 500){
+ if ($e->getResponse()->getStatusCode() >= 500) {
nlog("endpoint returned a 500, failing");
$message = "Server encountered a problem when connecting to {$subscription->target_url} => status code ". $e->getResponse()->getStatusCode(). " no retry attempted.";
@@ -189,11 +177,7 @@ class WebhookSingle implements ShouldQueue
$this->fail();
return;
}
-
-
- }
- catch (ServerException $e) {
-
+ } catch (ServerException $e) {
nlog("Server exception");
$error = json_decode($e->getResponse()->getBody()->getContents());
@@ -205,10 +189,7 @@ class WebhookSingle implements ShouldQueue
$this->resolveClient(),
$this->company
);
-
- }
- catch (ClientException $e) {
-
+ } catch (ClientException $e) {
nlog("Client exception");
$error = json_decode($e->getResponse()->getBody()->getContents());
@@ -220,11 +201,7 @@ class WebhookSingle implements ShouldQueue
$this->resolveClient(),
$this->company
);
-
-
- }
- catch (\Exception $e) {
-
+ } catch (\Exception $e) {
nlog("Exception handler => " . $e->getMessage());
nlog($e->getCode());
@@ -238,22 +215,20 @@ class WebhookSingle implements ShouldQueue
);
$this->release($this->backoff()[$this->attempts()-1]);
-
}
}
private function resolveClient()
- { nlog(get_class($this->entity));
+ {
+ nlog(get_class($this->entity));
//make sure it isn't an instance of the Client Model
- if (!$this->entity instanceof \App\Models\Client &&
- !$this->entity instanceof \App\Models\Vendor &&
- !$this->entity instanceof \App\Models\Product &&
+ if (!$this->entity instanceof \App\Models\Client &&
+ !$this->entity instanceof \App\Models\Vendor &&
+ !$this->entity instanceof \App\Models\Product &&
!$this->entity instanceof \App\Models\PurchaseOrder &&
$this->entity->client()->exists()) {
-
return $this->entity->client;
-
}
@@ -262,8 +237,6 @@ class WebhookSingle implements ShouldQueue
public function failed($exception = null)
{
-
config(['queue.failed.driver' => null]);
-
}
}
diff --git a/app/Jobs/Vendor/CreatePurchaseOrderPdf.php b/app/Jobs/Vendor/CreatePurchaseOrderPdf.php
index 718d96825c0e..83d62ebd7a49 100644
--- a/app/Jobs/Vendor/CreatePurchaseOrderPdf.php
+++ b/app/Jobs/Vendor/CreatePurchaseOrderPdf.php
@@ -13,27 +13,16 @@ namespace App\Jobs\Vendor;
use App\Exceptions\FilePermissionsFailure;
use App\Libraries\MultiDB;
-use App\Models\Account;
-use App\Models\Credit;
-use App\Models\CreditInvitation;
use App\Models\Design;
-use App\Models\Invoice;
-use App\Models\InvoiceInvitation;
-use App\Models\Quote;
-use App\Models\QuoteInvitation;
-use App\Models\RecurringInvoice;
-use App\Models\RecurringInvoiceInvitation;
use App\Services\PdfMaker\Design as PdfDesignModel;
use App\Services\PdfMaker\Design as PdfMakerDesign;
use App\Services\PdfMaker\PdfMaker as PdfMakerService;
use App\Utils\HostedPDF\NinjaPdf;
-use App\Utils\HtmlEngine;
use App\Utils\Ninja;
use App\Utils\PhantomJS\Phantom;
use App\Utils\Traits\MakesHash;
use App\Utils\Traits\MakesInvoiceHtml;
use App\Utils\Traits\NumberFormatter;
-use App\Utils\Traits\Pdf\PDF;
use App\Utils\Traits\Pdf\PageNumbering;
use App\Utils\Traits\Pdf\PdfMaker;
use App\Utils\VendorHtmlEngine;
@@ -43,9 +32,7 @@ use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\App;
-use Illuminate\Support\Facades\Lang;
use Illuminate\Support\Facades\Storage;
-use setasign\Fpdi\PdfParser\StreamReader;
class CreatePurchaseOrderPdf implements ShouldQueue
{
@@ -88,21 +75,16 @@ class CreatePurchaseOrderPdf implements ShouldQueue
$this->vendor->load('company');
$this->disk = $disk ?? config('filesystems.default');
-
}
public function handle()
{
-
$pdf = $this->rawPdf();
if ($pdf) {
-
- try{
+ try {
Storage::disk($this->disk)->put($this->file_path, $pdf);
- }
- catch(\Exception $e)
- {
+ } catch(\Exception $e) {
throw new FilePermissionsFailure($e->getMessage());
}
}
@@ -112,7 +94,6 @@ class CreatePurchaseOrderPdf implements ShouldQueue
public function rawPdf()
{
-
MultiDB::setDb($this->company->db);
/* Forget the singleton*/
@@ -142,8 +123,9 @@ class CreatePurchaseOrderPdf implements ShouldQueue
$design = Design::find($entity_design_id);
/* Catch all in case migration doesn't pass back a valid design */
- if(!$design)
+ if (!$design) {
$design = Design::find(2);
+ }
$html = new VendorHtmlEngine($this->invitation);
@@ -184,27 +166,23 @@ class CreatePurchaseOrderPdf implements ShouldQueue
$pdf = null;
try {
-
- if(config('ninja.invoiceninja_hosted_pdf_generation') || config('ninja.pdf_generator') == 'hosted_ninja'){
+ if (config('ninja.invoiceninja_hosted_pdf_generation') || config('ninja.pdf_generator') == 'hosted_ninja') {
$pdf = (new NinjaPdf())->build($maker->getCompiledHTML(true));
$numbered_pdf = $this->pageNumbering($pdf, $this->company);
- if($numbered_pdf)
+ if ($numbered_pdf) {
$pdf = $numbered_pdf;
-
- }
- else {
-
+ }
+ } else {
$pdf = $this->makePdf(null, null, $maker->getCompiledHTML(true));
$numbered_pdf = $this->pageNumbering($pdf, $this->company);
- if($numbered_pdf)
+ if ($numbered_pdf) {
$pdf = $numbered_pdf;
-
+ }
}
-
} catch (\Exception $e) {
nlog(print_r($e->getMessage(), 1));
}
@@ -217,13 +195,9 @@ class CreatePurchaseOrderPdf implements ShouldQueue
$state = null;
return $pdf;
-
}
public function failed($e)
{
-
}
-
-
}
diff --git a/app/Libraries/MultiDB.php b/app/Libraries/MultiDB.php
index cfca4b64c675..98d78cd71688 100644
--- a/app/Libraries/MultiDB.php
+++ b/app/Libraries/MultiDB.php
@@ -461,19 +461,18 @@ class MultiDB
*/
public static function hasPhoneNumber(string $phone) : bool
{
- if (! config('ninja.db.multi_db_enabled'))
+ if (! config('ninja.db.multi_db_enabled')) {
return Account::where('account_sms_verification_number', $phone)->where('account_sms_verified', true)->exists();
+ }
- $current_db = config('database.default');
+ $current_db = config('database.default');
foreach (self::$dbs as $db) {
-
self::setDB($db);
if ($exists = Account::where('account_sms_verification_number', $phone)->where('account_sms_verified', true)->exists()) {
self::setDb($current_db);
return true;
}
-
}
self::setDb($current_db);
diff --git a/app/Listeners/Activity/RestoreClientActivity.php b/app/Listeners/Activity/RestoreClientActivity.php
index 7f739585ac1c..709ff0f7d1d3 100644
--- a/app/Listeners/Activity/RestoreClientActivity.php
+++ b/app/Listeners/Activity/RestoreClientActivity.php
@@ -51,6 +51,5 @@ class RestoreClientActivity implements ShouldQueue
$fields->activity_type_id = Activity::RESTORE_CLIENT;
$this->activity_repo->save($fields, $event->client, $event->event_vars);
-
}
}
diff --git a/app/Listeners/Credit/CreditCreatedNotification.php b/app/Listeners/Credit/CreditCreatedNotification.php
index ca8b569afd40..79dfa23d5358 100644
--- a/app/Listeners/Credit/CreditCreatedNotification.php
+++ b/app/Listeners/Credit/CreditCreatedNotification.php
@@ -49,7 +49,6 @@ class CreditCreatedNotification implements ShouldQueue
/* We loop through each user and determine whether they need to be notified */
foreach ($event->company->company_users as $company_user) {
-
/* The User */
$user = $company_user->user;
diff --git a/app/Listeners/Invoice/CreateInvoicePdf.php b/app/Listeners/Invoice/CreateInvoicePdf.php
index 6921f0d93c7a..a50c13ef46a3 100644
--- a/app/Listeners/Invoice/CreateInvoicePdf.php
+++ b/app/Listeners/Invoice/CreateInvoicePdf.php
@@ -51,7 +51,6 @@ class CreateInvoicePdf implements ShouldQueue
if (isset($event->credit)) {
$event->credit->invitations->each(function ($invitation) {
(new CreateEntityPdf($invitation->load('credit', 'contact.client.company')))->handle();
-
});
}
}
diff --git a/app/Listeners/Invoice/InvoiceCreatedNotification.php b/app/Listeners/Invoice/InvoiceCreatedNotification.php
index 1436c1b8d809..92f507490168 100644
--- a/app/Listeners/Invoice/InvoiceCreatedNotification.php
+++ b/app/Listeners/Invoice/InvoiceCreatedNotification.php
@@ -51,7 +51,6 @@ class InvoiceCreatedNotification implements ShouldQueue
/* We loop through each user and determine whether they need to be notified */
foreach ($event->company->company_users as $company_user) {
-
/* The User */
$user = $company_user->user;
diff --git a/app/Listeners/Invoice/InvoiceEmailFailedActivity.php b/app/Listeners/Invoice/InvoiceEmailFailedActivity.php
index 1a80be2a01d3..ff6ed1106d50 100644
--- a/app/Listeners/Invoice/InvoiceEmailFailedActivity.php
+++ b/app/Listeners/Invoice/InvoiceEmailFailedActivity.php
@@ -19,7 +19,6 @@ use stdClass;
class InvoiceEmailFailedActivity implements ShouldQueue
{
-
// public $delay = 10;
protected $activity_repo;
diff --git a/app/Listeners/Invoice/InvoiceEmailedNotification.php b/app/Listeners/Invoice/InvoiceEmailedNotification.php
index ffde68b795b1..66cb02145cf2 100644
--- a/app/Listeners/Invoice/InvoiceEmailedNotification.php
+++ b/app/Listeners/Invoice/InvoiceEmailedNotification.php
@@ -53,7 +53,6 @@ class InvoiceEmailedNotification implements ShouldQueue
/* We loop through each user and determine whether they need to be notified */
foreach ($event->invitation->company->company_users as $company_user) {
-
/* The User */
$user = $company_user->user;
diff --git a/app/Listeners/Invoice/InvoiceFailedEmailNotification.php b/app/Listeners/Invoice/InvoiceFailedEmailNotification.php
index c0264f4ebc57..09d28f1870dc 100644
--- a/app/Listeners/Invoice/InvoiceFailedEmailNotification.php
+++ b/app/Listeners/Invoice/InvoiceFailedEmailNotification.php
@@ -16,17 +16,14 @@ use App\Jobs\Mail\NinjaMailerJob;
use App\Jobs\Mail\NinjaMailerObject;
use App\Libraries\MultiDB;
use App\Mail\Admin\EntityFailedSendObject;
-use App\Notifications\Admin\EntitySentNotification;
use App\Utils\Traits\Notifications\UserNotifies;
use Illuminate\Bus\Queueable;
-use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class InvoiceFailedEmailNotification
{
-
use UserNotifies, Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public function __construct()
diff --git a/app/Listeners/Invoice/InvoicePaidActivity.php b/app/Listeners/Invoice/InvoicePaidActivity.php
index 1c7152c01ca4..998783e4c200 100644
--- a/app/Listeners/Invoice/InvoicePaidActivity.php
+++ b/app/Listeners/Invoice/InvoicePaidActivity.php
@@ -39,7 +39,6 @@ class InvoicePaidActivity implements ShouldQueue
*/
public function handle($event)
{
-
MultiDB::setDb($event->company->db);
$fields = new stdClass;
@@ -54,8 +53,7 @@ class InvoicePaidActivity implements ShouldQueue
$this->activity_repo->save($fields, $event->invoice, $event->event_vars);
- if($event->invoice->subscription()->exists())
- {
+ if ($event->invoice->subscription()->exists()) {
$event->invoice->subscription->service()->planPaid($event->invoice);
}
diff --git a/app/Listeners/Mail/MailSentListener.php b/app/Listeners/Mail/MailSentListener.php
index 7eab2a2f813e..9978f076068b 100644
--- a/app/Listeners/Mail/MailSentListener.php
+++ b/app/Listeners/Mail/MailSentListener.php
@@ -20,7 +20,6 @@ use App\Models\RecurringInvoiceInvitation;
use App\Utils\Ninja;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Events\MessageSent;
-use Illuminate\Support\Facades\Notification;
use Symfony\Component\Mime\MessageConverter;
class MailSentListener implements ShouldQueue
@@ -42,55 +41,50 @@ class MailSentListener implements ShouldQueue
*/
public function handle(MessageSent $event)
{
- if(!Ninja::isHosted())
+ if (!Ninja::isHosted()) {
return;
+ }
$message_id = $event->sent->getMessageId();
$message = MessageConverter::toEmail($event->sent->getOriginalMessage());
- if(!$message->getHeaders()->get('x-invitation'))
+ if (!$message->getHeaders()->get('x-invitation')) {
return;
+ }
$invitation_key = $message->getHeaders()->get('x-invitation')->getValue();
- if($message_id && $invitation_key)
- {
-
+ if ($message_id && $invitation_key) {
$invitation = $this->discoverInvitation($invitation_key);
- if(!$invitation)
+ if (!$invitation) {
return;
+ }
$invitation->message_id = $message_id;
- $invitation->save();
+ $invitation->save();
}
-
}
private function discoverInvitation($key)
{
-
$invitation = false;
- foreach (MultiDB::$dbs as $db)
- {
-
- if($invitation = InvoiceInvitation::on($db)->where('key', $key)->first())
+ foreach (MultiDB::$dbs as $db) {
+ if ($invitation = InvoiceInvitation::on($db)->where('key', $key)->first()) {
return $invitation;
- elseif($invitation = QuoteInvitation::on($db)->where('key', $key)->first())
+ } elseif ($invitation = QuoteInvitation::on($db)->where('key', $key)->first()) {
return $invitation;
- elseif($invitation = RecurringInvoiceInvitation::on($db)->where('key', $key)->first())
+ } elseif ($invitation = RecurringInvoiceInvitation::on($db)->where('key', $key)->first()) {
return $invitation;
- elseif($invitation = CreditInvitation::on($db)->where('key', $key)->first())
+ } elseif ($invitation = CreditInvitation::on($db)->where('key', $key)->first()) {
return $invitation;
- elseif($invitation = PurchaseOrderInvitation::on($db)->where('key', $key)->first())
+ } elseif ($invitation = PurchaseOrderInvitation::on($db)->where('key', $key)->first()) {
return $invitation;
-
+ }
}
return $invitation;
-
}
-
}
diff --git a/app/Listeners/Misc/InvitationViewedListener.php b/app/Listeners/Misc/InvitationViewedListener.php
index 7003a464d827..fb8d28afee29 100644
--- a/app/Listeners/Misc/InvitationViewedListener.php
+++ b/app/Listeners/Misc/InvitationViewedListener.php
@@ -16,12 +16,10 @@ use App\Jobs\Mail\NinjaMailerJob;
use App\Jobs\Mail\NinjaMailerObject;
use App\Libraries\MultiDB;
use App\Mail\Admin\EntityViewedObject;
-use App\Notifications\Admin\EntityViewedNotification;
use App\Utils\Ninja;
use App\Utils\Traits\Notifications\UserNotifies;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\App;
-use Illuminate\Support\Facades\Notification;
class InvitationViewedListener implements ShouldQueue
{
diff --git a/app/Listeners/Payment/PaymentNotification.php b/app/Listeners/Payment/PaymentNotification.php
index 40d4071250c5..1899c9ed35f1 100644
--- a/app/Listeners/Payment/PaymentNotification.php
+++ b/app/Listeners/Payment/PaymentNotification.php
@@ -16,11 +16,9 @@ use App\Jobs\Mail\NinjaMailerJob;
use App\Jobs\Mail\NinjaMailerObject;
use App\Libraries\MultiDB;
use App\Mail\Admin\EntityPaidObject;
-use App\Notifications\Admin\NewPaymentNotification;
use App\Utils\Ninja;
use App\Utils\Traits\Notifications\UserNotifies;
use Illuminate\Contracts\Queue\ShouldQueue;
-use Illuminate\Support\Facades\Notification;
class PaymentNotification implements ShouldQueue
{
@@ -62,7 +60,10 @@ class PaymentNotification implements ShouldQueue
foreach ($payment->company->company_users as $company_user) {
$user = $company_user->user;
- $methods = $this->findUserEntityNotificationType($payment, $company_user, [
+ $methods = $this->findUserEntityNotificationType(
+ $payment,
+ $company_user,
+ [
'payment_success',
'payment_success_all',
'payment_success_user',
diff --git a/app/Listeners/PurchaseOrder/PurchaseOrderAcceptedListener.php b/app/Listeners/PurchaseOrder/PurchaseOrderAcceptedListener.php
index 802a82582530..d83b7223d573 100644
--- a/app/Listeners/PurchaseOrder/PurchaseOrderAcceptedListener.php
+++ b/app/Listeners/PurchaseOrder/PurchaseOrderAcceptedListener.php
@@ -15,9 +15,7 @@ use App\Jobs\Mail\NinjaMailer;
use App\Jobs\Mail\NinjaMailerJob;
use App\Jobs\Mail\NinjaMailerObject;
use App\Libraries\MultiDB;
-use App\Mail\Admin\EntityCreatedObject;
use App\Mail\Admin\PurchaseOrderAcceptedObject;
-use App\Notifications\Admin\EntitySentNotification;
use App\Utils\Traits\Notifications\UserNotifies;
use Illuminate\Contracts\Queue\ShouldQueue;
@@ -50,7 +48,6 @@ class PurchaseOrderAcceptedListener implements ShouldQueue
/* We loop through each user and determine whether they need to be notified */
foreach ($event->company->company_users as $company_user) {
-
/* The User */
$user = $company_user->user;
diff --git a/app/Listeners/PurchaseOrder/PurchaseOrderCreatedListener.php b/app/Listeners/PurchaseOrder/PurchaseOrderCreatedListener.php
index 3d22d4fb056e..6b7e146defed 100644
--- a/app/Listeners/PurchaseOrder/PurchaseOrderCreatedListener.php
+++ b/app/Listeners/PurchaseOrder/PurchaseOrderCreatedListener.php
@@ -37,7 +37,6 @@ class PurchaseOrderCreatedListener implements ShouldQueue
*/
public function handle(PurchaseOrderWasCreated $event)
{
-
MultiDB::setDb($event->company->db);
$first_notification_sent = true;
@@ -51,7 +50,6 @@ class PurchaseOrderCreatedListener implements ShouldQueue
/* We loop through each user and determine whether they need to be notified */
foreach ($event->company->company_users as $company_user) {
-
/* The User */
$user = $company_user->user;
diff --git a/app/Listeners/PurchaseOrder/PurchaseOrderEmailedNotification.php b/app/Listeners/PurchaseOrder/PurchaseOrderEmailedNotification.php
index 9def7f062112..22541380768c 100644
--- a/app/Listeners/PurchaseOrder/PurchaseOrderEmailedNotification.php
+++ b/app/Listeners/PurchaseOrder/PurchaseOrderEmailedNotification.php
@@ -53,7 +53,6 @@ class PurchaseOrderEmailedNotification implements ShouldQueue
/* We loop through each user and determine whether they need to be notified */
foreach ($event->invitation->company->company_users as $company_user) {
-
/* The User */
$user = $company_user->user;
diff --git a/app/Listeners/Quote/QuoteApprovedNotification.php b/app/Listeners/Quote/QuoteApprovedNotification.php
index 47bb68867fc0..eae4d21e417a 100644
--- a/app/Listeners/Quote/QuoteApprovedNotification.php
+++ b/app/Listeners/Quote/QuoteApprovedNotification.php
@@ -15,9 +15,7 @@ use App\Jobs\Mail\NinjaMailer;
use App\Jobs\Mail\NinjaMailerJob;
use App\Jobs\Mail\NinjaMailerObject;
use App\Libraries\MultiDB;
-use App\Mail\Admin\EntityCreatedObject;
use App\Mail\Admin\QuoteApprovedObject;
-use App\Notifications\Admin\EntitySentNotification;
use App\Utils\Traits\Notifications\UserNotifies;
use Illuminate\Contracts\Queue\ShouldQueue;
@@ -52,7 +50,6 @@ class QuoteApprovedNotification implements ShouldQueue
/* We loop through each user and determine whether they need to be notified */
foreach ($event->company->company_users as $company_user) {
-
/* The User */
$user = $company_user->user;
diff --git a/app/Listeners/Quote/QuoteCreatedNotification.php b/app/Listeners/Quote/QuoteCreatedNotification.php
index dfecf70cd2bb..6c636605f127 100644
--- a/app/Listeners/Quote/QuoteCreatedNotification.php
+++ b/app/Listeners/Quote/QuoteCreatedNotification.php
@@ -51,7 +51,6 @@ class QuoteCreatedNotification implements ShouldQueue
/* We loop through each user and determine whether they need to be notified */
foreach ($event->company->company_users as $company_user) {
-
/* The User */
$user = $company_user->user;
diff --git a/app/Listeners/SendVerificationNotification.php b/app/Listeners/SendVerificationNotification.php
index f6d722c5e1d2..d4c40f613d5f 100644
--- a/app/Listeners/SendVerificationNotification.php
+++ b/app/Listeners/SendVerificationNotification.php
@@ -11,14 +11,11 @@
namespace App\Listeners;
-use App\Jobs\Mail\NinjaMailer;
use App\Jobs\Mail\NinjaMailerJob;
use App\Jobs\Mail\NinjaMailerObject;
use App\Libraries\MultiDB;
-use App\Mail\Admin\VerifyUserObject;
use App\Mail\User\UserAdded;
use App\Utils\Ninja;
-use Exception;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Events\Dispatchable;
diff --git a/app/Listeners/Subscription/AppStoreRenewSubscription.php b/app/Listeners/Subscription/AppStoreRenewSubscription.php
index 958fd62929de..26c2b41df179 100644
--- a/app/Listeners/Subscription/AppStoreRenewSubscription.php
+++ b/app/Listeners/Subscription/AppStoreRenewSubscription.php
@@ -37,7 +37,6 @@ class AppStoreRenewSubscription implements ShouldQueue
*/
public function handle(DidRenew $event)
{
-
$inapp_transaction_id = $event->getSubscriptionId(); //$subscription_id
nlog("inapp upgrade processing for = {$inapp_transaction_id}");
@@ -46,23 +45,22 @@ class AppStoreRenewSubscription implements ShouldQueue
$account = Account::where('inapp_transaction_id', $inapp_transaction_id)->first();
- if(!$account) {
+ if (!$account) {
$ninja_company = Company::on('db-ninja-01')->find(config('ninja.ninja_default_company_id'));
$ninja_company->notification(new RenewalFailureNotification("{$inapp_transaction_id}"))->ninja();
return;
}
- if($account->plan_term == 'month')
+ if ($account->plan_term == 'month') {
$account->plan_expires = now()->addMonth();
- elseif($account->plan_term == 'year')
+ } elseif ($account->plan_term == 'year') {
$account->plan_expires = now()->addYear();
+ }
$account->save();
// $server_notification = $event->getServerNotification();
// $subscription = $event->getSubscription();
// $subscription_identifier = $event->getSubscriptionIdentifier();
-
}
-
-}
\ No newline at end of file
+}
diff --git a/app/Listeners/User/UpdateUserLastLogin.php b/app/Listeners/User/UpdateUserLastLogin.php
index 015375e4c8bb..4882cfa26554 100644
--- a/app/Listeners/User/UpdateUserLastLogin.php
+++ b/app/Listeners/User/UpdateUserLastLogin.php
@@ -16,7 +16,6 @@ use App\Jobs\Mail\NinjaMailerObject;
use App\Jobs\Util\SystemLogger;
use App\Libraries\MultiDB;
use App\Mail\User\UserLoggedIn;
-use App\Models\Client;
use App\Models\SystemLog;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Queue\ShouldQueue;
diff --git a/app/Mail/Admin/AutoBillingFailureObject.php b/app/Mail/Admin/AutoBillingFailureObject.php
index b40d6d964159..d56642b419ee 100644
--- a/app/Mail/Admin/AutoBillingFailureObject.php
+++ b/app/Mail/Admin/AutoBillingFailureObject.php
@@ -14,7 +14,6 @@ namespace App\Mail\Admin;
use App\Models\Invoice;
use App\Utils\HtmlEngine;
use App\Utils\Ninja;
-use App\Utils\Number;
use App\Utils\Traits\MakesHash;
use Illuminate\Support\Facades\App;
use stdClass;
diff --git a/app/Mail/Admin/EntityCreatedObject.php b/app/Mail/Admin/EntityCreatedObject.php
index 918fc13ba8c0..c75c3ec73316 100644
--- a/app/Mail/Admin/EntityCreatedObject.php
+++ b/app/Mail/Admin/EntityCreatedObject.php
@@ -40,8 +40,8 @@ class EntityCreatedObject
}
/**
- * @return stdClass
- * @throws BindingResolutionException
+ * @return stdClass
+ * @throws BindingResolutionException
*/
public function build() :stdClass
{
@@ -55,32 +55,32 @@ class EntityCreatedObject
$this->setTemplate();
$this->company = $this->entity->company;
- if($this->entity_type == 'purchase_order')
- {
-
+ if ($this->entity_type == 'purchase_order') {
$this->entity->load('vendor.company');
$mail_obj = new stdClass;
$mail_obj->amount = Number::formatMoney($this->entity->amount, $this->entity->vendor);
- $mail_obj->subject = ctrans($this->template_subject,
- [
- 'vendor' => $this->entity->vendor->present()->name(),
- 'purchase_order' => $this->entity->number,
- ]
- );
+ $mail_obj->subject = ctrans(
+ $this->template_subject,
+ [
+ 'vendor' => $this->entity->vendor->present()->name(),
+ 'purchase_order' => $this->entity->number,
+ ]
+ );
$mail_obj->markdown = 'email.admin.generic';
$mail_obj->tag = $this->company->company_key;
$mail_obj->data = [
'title' => $mail_obj->subject,
- 'message' => ctrans($this->template_body,
- [
- 'amount' => $mail_obj->amount,
- 'vendor' => $this->entity->vendor->present()->name(),
- 'purchase_order' => $this->entity->number,
- ]
- ),
+ 'message' => ctrans(
+ $this->template_body,
+ [
+ 'amount' => $mail_obj->amount,
+ 'vendor' => $this->entity->vendor->present()->name(),
+ 'purchase_order' => $this->entity->number,
+ ]
+ ),
'url' => $this->entity->invitations()->first()->getAdminLink(),
'button' => ctrans("texts.view_{$this->entity_type}"),
'signature' => $this->company->settings->email_signature,
@@ -88,11 +88,7 @@ class EntityCreatedObject
'settings' => $this->company->settings,
'whitelabel' => $this->company->account->isPaid() ? true : false,
];
-
-
- }
- else {
-
+ } else {
$this->entity->load('client.country', 'client.company');
$this->client = $this->entity->client;
@@ -102,7 +98,6 @@ class EntityCreatedObject
$mail_obj->data = $this->getData();
$mail_obj->markdown = 'email.admin.generic';
$mail_obj->tag = $this->entity->company->company_key;
-
}
return $mail_obj;
@@ -110,7 +105,6 @@ class EntityCreatedObject
private function setTemplate()
{
-
switch ($this->entity_type) {
case 'invoice':
$this->template_subject = 'texts.notification_invoice_created_subject';
@@ -135,7 +129,7 @@ class EntityCreatedObject
}
}
- private function getAmount()
+ private function getAmount()
{
return Number::formatMoney($this->entity->amount, $this->entity->client);
}
@@ -155,13 +149,13 @@ class EntityCreatedObject
private function getMessage()
{
return ctrans(
- $this->template_body,
- [
- 'amount' => $this->getAmount(),
- 'client' => $this->client->present()->name(),
- 'invoice' => $this->entity->number,
- ]
- );
+ $this->template_body,
+ [
+ 'amount' => $this->getAmount(),
+ 'client' => $this->client->present()->name(),
+ 'invoice' => $this->entity->number,
+ ]
+ );
}
private function getData()
diff --git a/app/Mail/Admin/EntityFailedSendObject.php b/app/Mail/Admin/EntityFailedSendObject.php
index dad2846c4d6c..e51413e42b79 100644
--- a/app/Mail/Admin/EntityFailedSendObject.php
+++ b/app/Mail/Admin/EntityFailedSendObject.php
@@ -15,7 +15,7 @@ use App\Utils\HtmlEngine;
use App\Utils\Ninja;
use App\Utils\Number;
use Illuminate\Support\Facades\App;
- use stdClass;
+use stdClass;
class EntityFailedSendObject
{
diff --git a/app/Mail/Admin/EntitySentObject.php b/app/Mail/Admin/EntitySentObject.php
index 9eb7717bd102..c3bc4eaa503e 100644
--- a/app/Mail/Admin/EntitySentObject.php
+++ b/app/Mail/Admin/EntitySentObject.php
@@ -58,12 +58,11 @@ class EntitySentObject
$this->setTemplate();
- if($this->template == 'purchase_order')
- {
-
+ if ($this->template == 'purchase_order') {
$mail_obj = new stdClass;
$mail_obj->amount = Number::formatMoney($this->entity->amount, $this->entity->vendor);
- $mail_obj->subject = ctrans($this->template_subject,
+ $mail_obj->subject = ctrans(
+ $this->template_subject,
[
'vendor' => $this->contact->vendor->present()->name(),
'purchase_order' => $this->entity->number,
@@ -71,13 +70,14 @@ class EntitySentObject
);
$mail_obj->data = [
'title' => $mail_obj->subject,
- 'message' => ctrans($this->template_body,
- [
- 'amount' => $mail_obj->amount,
- 'vendor' => $this->contact->vendor->present()->name(),
- 'purchase_order' => $this->entity->number,
- ]
- ),
+ 'message' => ctrans(
+ $this->template_body,
+ [
+ 'amount' => $mail_obj->amount,
+ 'vendor' => $this->contact->vendor->present()->name(),
+ 'purchase_order' => $this->entity->number,
+ ]
+ ),
'url' => $this->invitation->getAdminLink(),
'button' => ctrans("texts.view_{$this->entity_type}"),
'signature' => $this->company->settings->email_signature,
@@ -87,17 +87,13 @@ class EntitySentObject
];
$mail_obj->markdown = 'email.admin.generic';
$mail_obj->tag = $this->company->company_key;
-
- }
- else {
-
+ } else {
$mail_obj = new stdClass;
$mail_obj->amount = $this->getAmount();
$mail_obj->subject = $this->getSubject();
$mail_obj->data = $this->getData();
$mail_obj->markdown = 'email.admin.generic';
$mail_obj->tag = $this->company->company_key;
-
}
return $mail_obj;
@@ -167,13 +163,13 @@ class EntitySentObject
private function getMessage()
{
return ctrans(
- $this->template_body,
- [
- 'amount' => $this->getAmount(),
- 'client' => $this->contact->client->present()->name(),
- 'invoice' => $this->entity->number,
- ]
- );
+ $this->template_body,
+ [
+ 'amount' => $this->getAmount(),
+ 'client' => $this->contact->client->present()->name(),
+ 'invoice' => $this->entity->number,
+ ]
+ );
}
private function getData()
diff --git a/app/Mail/Admin/InventoryNotificationObject.php b/app/Mail/Admin/InventoryNotificationObject.php
index bc74e85a2200..3a414c8dacdb 100644
--- a/app/Mail/Admin/InventoryNotificationObject.php
+++ b/app/Mail/Admin/InventoryNotificationObject.php
@@ -12,11 +12,9 @@
namespace App\Mail\Admin;
-use App\Mail\Engine\PaymentEmailEngine;
use App\Models\Company;
use App\Models\Product;
use App\Utils\Ninja;
-use App\Utils\Number;
use Illuminate\Support\Facades\App;
use stdClass;
diff --git a/app/Mail/Admin/PaymentFailureObject.php b/app/Mail/Admin/PaymentFailureObject.php
index 5c2c2e6b2dc2..8b484be26ee8 100644
--- a/app/Mail/Admin/PaymentFailureObject.php
+++ b/app/Mail/Admin/PaymentFailureObject.php
@@ -13,7 +13,6 @@ namespace App\Mail\Admin;
use App\Models\Client;
use App\Models\Company;
-use App\Models\Invoice;
use App\Models\PaymentHash;
use App\Utils\Ninja;
use App\Utils\Number;
@@ -110,7 +109,8 @@ class PaymentFailureObject
'client' => $this->client->present()->name(),
'invoice' => $this->getDescription(),
'amount' => Number::formatMoney($this->amount, $this->client),
- ]),
+ ]
+ ),
'signature' => $signature,
'logo' => $this->company->present()->logo(),
'settings' => $this->client->getMergedSettings(),
diff --git a/app/Mail/BouncedEmail.php b/app/Mail/BouncedEmail.php
index 71a837c5ff59..891e353ccdb8 100644
--- a/app/Mail/BouncedEmail.php
+++ b/app/Mail/BouncedEmail.php
@@ -11,11 +11,7 @@
namespace App\Mail;
-use App\Models\User;
-use Illuminate\Bus\Queueable;
-use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
-use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\App;
class BouncedEmail extends Mailable
diff --git a/app/Mail/Client/ClientStatement.php b/app/Mail/Client/ClientStatement.php
index 80ea6d52788e..ec34f05d77c0 100644
--- a/app/Mail/Client/ClientStatement.php
+++ b/app/Mail/Client/ClientStatement.php
@@ -11,23 +11,21 @@
namespace App\Mail\Client;
-use Illuminate\Bus\Queueable;
-use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Attachment;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
-use Illuminate\Queue\SerializesModels;
class ClientStatement extends Mailable
{
-
/**
* Create a new message instance.
*
* @return void
*/
- public function __construct(public array $data){}
+ public function __construct(public array $data)
+ {
+ }
/**
* Get the message envelope.
@@ -79,16 +77,12 @@ class ClientStatement extends Mailable
{
$array_of_attachments = [];
- foreach($this->data['attachments'] as $attachment)
- {
-
- $array_of_attachments[] =
+ foreach ($this->data['attachments'] as $attachment) {
+ $array_of_attachments[] =
Attachment::fromData(fn () => base64_decode($attachment['file']), $attachment['name'])
->withMime('application/pdf');
-
}
return $array_of_attachments;
-
}
}
diff --git a/app/Mail/ContactPasswordlessLogin.php b/app/Mail/ContactPasswordlessLogin.php
index 4bcf5278a098..f7779d874c31 100644
--- a/app/Mail/ContactPasswordlessLogin.php
+++ b/app/Mail/ContactPasswordlessLogin.php
@@ -14,10 +14,7 @@ namespace App\Mail;
use App\Models\Company;
use App\Utils\ClientPortal\MagicLink;
-use Illuminate\Bus\Queueable;
-use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
-use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\App;
class ContactPasswordlessLogin extends Mailable
diff --git a/app/Mail/DownloadBackup.php b/app/Mail/DownloadBackup.php
index a28f118002ca..ffc89d21d000 100644
--- a/app/Mail/DownloadBackup.php
+++ b/app/Mail/DownloadBackup.php
@@ -13,9 +13,7 @@
namespace App\Mail;
use App\Models\Company;
-use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
-use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\App;
class DownloadBackup extends Mailable
diff --git a/app/Mail/DownloadReport.php b/app/Mail/DownloadReport.php
index 9a713809bef2..f2c53725d777 100644
--- a/app/Mail/DownloadReport.php
+++ b/app/Mail/DownloadReport.php
@@ -13,7 +13,6 @@ namespace App\Mail;
use App\Models\Company;
use Illuminate\Bus\Queueable;
-use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\App;
diff --git a/app/Mail/Engine/CreditEmailEngine.php b/app/Mail/Engine/CreditEmailEngine.php
index 19989905bb18..2bf98f78410d 100644
--- a/app/Mail/Engine/CreditEmailEngine.php
+++ b/app/Mail/Engine/CreditEmailEngine.php
@@ -17,7 +17,6 @@ use App\Utils\HtmlEngine;
use App\Utils\Ninja;
use App\Utils\Number;
use Illuminate\Support\Facades\App;
-use Illuminate\Support\Facades\Lang;
use Illuminate\Support\Facades\URL;
class CreditEmailEngine extends BaseEmailEngine
@@ -96,16 +95,15 @@ class CreditEmailEngine extends BaseEmailEngine
}
$text_body = trans(
- 'texts.credit_message',
- [
- 'credit' => $this->credit->number,
- 'company' => $this->credit->company->present()->name(),
- 'amount' => Number::formatMoney($this->credit->balance, $this->client),
- ],
- null,
- $this->client->locale()
-
- )."\n\n".$this->invitation->getLink();
+ 'texts.credit_message',
+ [
+ 'credit' => $this->credit->number,
+ 'company' => $this->credit->company->present()->name(),
+ 'amount' => Number::formatMoney($this->credit->balance, $this->client),
+ ],
+ null,
+ $this->client->locale()
+ )."\n\n".$this->invitation->getLink();
$this->setTemplate($this->client->getSetting('email_style'))
->setContact($this->contact)
@@ -125,31 +123,28 @@ class CreditEmailEngine extends BaseEmailEngine
// $this->setAttachments([$this->credit->pdf_file_path($this->invitation)]);
// }
- $pdf = ((new CreateRawPdf($this->invitation, $this->invitation->company->db))->handle());
-
- $this->setAttachments([['file' => base64_encode($pdf), 'name' => $this->credit->numberFormatter().'.pdf']]);
-
+ $pdf = ((new CreateRawPdf($this->invitation, $this->invitation->company->db))->handle());
+ $this->setAttachments([['file' => base64_encode($pdf), 'name' => $this->credit->numberFormatter().'.pdf']]);
}
//attach third party documents
if ($this->client->getSetting('document_email_attachment') !== false && $this->credit->company->account->hasFeature(Account::FEATURE_DOCUMENTS)) {
-
// Storage::url
foreach ($this->credit->documents as $document) {
-
- if($document->size > $this->max_attachment_size)
+ if ($document->size > $this->max_attachment_size) {
$this->setAttachmentLinks([" $document->hash]) ."'>". $document->name .""]);
- else
- $this->setAttachments([['path' => $document->filePath(), 'name' => $document->name, 'mime' => NULL, 'file' => base64_encode($document->getFile())]]);
+ } else {
+ $this->setAttachments([['path' => $document->filePath(), 'name' => $document->name, 'mime' => null, 'file' => base64_encode($document->getFile())]]);
+ }
}
foreach ($this->credit->company->documents as $document) {
-
- if($document->size > $this->max_attachment_size)
+ if ($document->size > $this->max_attachment_size) {
$this->setAttachmentLinks([" $document->hash]) ."'>". $document->name .""]);
- else
- $this->setAttachments([['path' => $document->filePath(), 'name' => $document->name, 'mime' => NULL, 'file' => base64_encode($document->getFile())]]);
+ } else {
+ $this->setAttachments([['path' => $document->filePath(), 'name' => $document->name, 'mime' => null, 'file' => base64_encode($document->getFile())]]);
+ }
}
}
diff --git a/app/Mail/Engine/InvoiceEmailEngine.php b/app/Mail/Engine/InvoiceEmailEngine.php
index 598db7a00a3d..9ba08c127f86 100644
--- a/app/Mail/Engine/InvoiceEmailEngine.php
+++ b/app/Mail/Engine/InvoiceEmailEngine.php
@@ -12,7 +12,6 @@
namespace App\Mail\Engine;
use App\DataMapper\EmailTemplateDefaults;
-use App\Jobs\Entity\CreateEntityPdf;
use App\Jobs\Entity\CreateRawPdf;
use App\Models\Account;
use App\Models\Expense;
@@ -22,7 +21,6 @@ use App\Utils\Ninja;
use App\Utils\Number;
use App\Utils\Traits\MakesHash;
use Illuminate\Support\Facades\App;
-use Illuminate\Support\Facades\Lang;
use Illuminate\Support\Facades\URL;
class InvoiceEmailEngine extends BaseEmailEngine
@@ -86,15 +84,15 @@ class InvoiceEmailEngine extends BaseEmailEngine
}
$text_body = trans(
- 'texts.invoice_message',
- [
- 'invoice' => $this->invoice->number,
- 'company' => $this->invoice->company->present()->name(),
- 'amount' => Number::formatMoney($this->invoice->balance, $this->client),
- ],
- null,
- $this->client->locale()
- )."\n\n".$this->invitation->getLink();
+ 'texts.invoice_message',
+ [
+ 'invoice' => $this->invoice->number,
+ 'company' => $this->invoice->company->present()->name(),
+ 'amount' => Number::formatMoney($this->invoice->balance, $this->client),
+ ],
+ null,
+ $this->client->locale()
+ )."\n\n".$this->invitation->getLink();
if (is_array($this->template_data) && array_key_exists('subject', $this->template_data) && strlen($this->template_data['subject']) > 0) {
$subject_template = $this->template_data['subject'];
@@ -128,42 +126,38 @@ class InvoiceEmailEngine extends BaseEmailEngine
->setTextBody($text_body);
if ($this->client->getSetting('pdf_email_attachment') !== false && $this->invoice->company->account->hasFeature(Account::FEATURE_PDF_ATTACHMENT)) {
-
$pdf = ((new CreateRawPdf($this->invitation, $this->invitation->company->db))->handle());
- $this->setAttachments([['file' => base64_encode($pdf), 'name' => $this->invoice->numberFormatter().'.pdf']]);
+ $this->setAttachments([['file' => base64_encode($pdf), 'name' => $this->invoice->numberFormatter().'.pdf']]);
}
//attach third party documents
if ($this->client->getSetting('document_email_attachment') !== false && $this->invoice->company->account->hasFeature(Account::FEATURE_DOCUMENTS)) {
-
-
- if($this->invoice->recurring_invoice()->exists())
- {
+ if ($this->invoice->recurring_invoice()->exists()) {
foreach ($this->invoice->recurring_invoice->documents as $document) {
-
- if($document->size > $this->max_attachment_size)
+ if ($document->size > $this->max_attachment_size) {
$this->setAttachmentLinks([" $document->hash]) ."'>". $document->name .""]);
- else
- $this->setAttachments([['file' => base64_encode($document->getFile()), 'path' => $document->filePath(), 'name' => $document->name, 'mime' => NULL, ]]);
+ } else {
+ $this->setAttachments([['file' => base64_encode($document->getFile()), 'path' => $document->filePath(), 'name' => $document->name, 'mime' => null, ]]);
+ }
}
}
// Storage::url
foreach ($this->invoice->documents as $document) {
-
- if($document->size > $this->max_attachment_size)
+ if ($document->size > $this->max_attachment_size) {
$this->setAttachmentLinks([" $document->hash]) ."'>". $document->name .""]);
- else
- $this->setAttachments([['file' => base64_encode($document->getFile()), 'path' => $document->filePath(), 'name' => $document->name, 'mime' => NULL, ]]);
+ } else {
+ $this->setAttachments([['file' => base64_encode($document->getFile()), 'path' => $document->filePath(), 'name' => $document->name, 'mime' => null, ]]);
+ }
}
foreach ($this->invoice->company->documents as $document) {
-
- if($document->size > $this->max_attachment_size)
+ if ($document->size > $this->max_attachment_size) {
$this->setAttachmentLinks([" $document->hash]) ."'>". $document->name .""]);
- else
- $this->setAttachments([['file' => base64_encode($document->getFile()), 'path' => $document->filePath(), 'name' => $document->name, 'mime' => NULL, ]]);
+ } else {
+ $this->setAttachments([['file' => base64_encode($document->getFile()), 'path' => $document->filePath(), 'name' => $document->name, 'mime' => null, ]]);
+ }
}
$line_items = $this->invoice->line_items;
@@ -181,12 +175,11 @@ class InvoiceEmailEngine extends BaseEmailEngine
->cursor()
->each(function ($expense) {
foreach ($expense->documents as $document) {
-
- if($document->size > $this->max_attachment_size)
- $this->setAttachmentLinks([" $document->hash]) ."'>". $document->name .""]);
- else
- $this->setAttachments([['path' => $document->filePath(), 'name' => $document->name, 'mime' => NULL, ]]);
-
+ if ($document->size > $this->max_attachment_size) {
+ $this->setAttachmentLinks([" $document->hash]) ."'>". $document->name .""]);
+ } else {
+ $this->setAttachments([['path' => $document->filePath(), 'name' => $document->name, 'mime' => null, ]]);
+ }
}
});
}
@@ -202,17 +195,15 @@ class InvoiceEmailEngine extends BaseEmailEngine
->cursor()
->each(function ($task) {
foreach ($task->documents as $document) {
-
- if($document->size > $this->max_attachment_size)
- $this->setAttachmentLinks([" $document->hash]) ."'>". $document->name .""]);
- else
- $this->setAttachments([['path' => $document->filePath(), 'name' => $document->name, 'mime' => NULL, ]]);
-
+ if ($document->size > $this->max_attachment_size) {
+ $this->setAttachmentLinks([" $document->hash]) ."'>". $document->name .""]);
+ } else {
+ $this->setAttachments([['path' => $document->filePath(), 'name' => $document->name, 'mime' => null, ]]);
+ }
}
});
}
}
-
}
return $this;
diff --git a/app/Mail/Engine/PaymentEmailEngine.php b/app/Mail/Engine/PaymentEmailEngine.php
index 8213215fbc9f..b32cfb4efe65 100644
--- a/app/Mail/Engine/PaymentEmailEngine.php
+++ b/app/Mail/Engine/PaymentEmailEngine.php
@@ -90,28 +90,22 @@ class PaymentEmailEngine extends BaseEmailEngine
->setViewText('');
if ($this->client->getSetting('pdf_email_attachment') !== false && $this->company->account->hasFeature(Account::FEATURE_PDF_ATTACHMENT)) {
-
$this->payment->invoices->each(function ($invoice) {
-
$pdf = ((new CreateRawPdf($invoice->invitations->first(), $invoice->company->db))->handle());
- $this->setAttachments([['file' => base64_encode($pdf), 'name' => $invoice->numberFormatter().'.pdf']]);
+ $this->setAttachments([['file' => base64_encode($pdf), 'name' => $invoice->numberFormatter().'.pdf']]);
//attach invoice documents also to payments
- if ($this->client->getSetting('document_email_attachment') !== false)
- {
+ if ($this->client->getSetting('document_email_attachment') !== false) {
foreach ($invoice->documents as $document) {
-
- if($document->size > $this->max_attachment_size)
+ if ($document->size > $this->max_attachment_size) {
$this->setAttachmentLinks([" $document->hash]) ."'>". $document->name .""]);
- else
- $this->setAttachments([['path' => $document->filePath(), 'name' => $document->name, 'mime' => NULL, ]]);
+ } else {
+ $this->setAttachments([['path' => $document->filePath(), 'name' => $document->name, 'mime' => null, ]]);
+ }
}
}
-
});
-
-
}
return $this;
@@ -268,11 +262,11 @@ class PaymentEmailEngine extends BaseEmailEngine
$data['$invoices.po_number'] = ['value' => $this->formatInvoiceField('po_number'), 'label' => ctrans('texts.invoices')];
- if($this->payment->status_id == 4) {
+ if ($this->payment->status_id == 4) {
$data['$status_logo'] = ['value' => ' ' . ctrans('texts.paid') .'
', 'label' => ''];
- }
- else
+ } else {
$data['$status_logo'] = ['value' => '', 'label' => ''];
+ }
$arrKeysLength = array_map('strlen', array_keys($data));
@@ -286,21 +280,20 @@ class PaymentEmailEngine extends BaseEmailEngine
$invoicex = '';
foreach ($this->payment->invoices as $invoice) {
-
$invoice_field = $invoice->{$field};
- if(in_array($field, ['amount', 'balance']))
+ if (in_array($field, ['amount', 'balance'])) {
$invoice_field = Number::formatMoney($invoice_field, $this->client);
+ }
- if($field == 'due_date')
+ if ($field == 'due_date') {
$invoice_field = $this->translateDate($invoice_field, $this->client->date_format(), $this->client->locale());
+ }
$invoicex .= ctrans('texts.invoice_number_short') . "{$invoice->number} {$invoice_field}";
-
}
return $invoicex;
-
}
private function formatInvoice()
@@ -341,15 +334,14 @@ class PaymentEmailEngine extends BaseEmailEngine
$invoice_list = '
';
foreach ($this->payment->invoices as $invoice) {
-
- if(strlen($invoice->po_number) > 1)
+ if (strlen($invoice->po_number) > 1) {
$invoice_list .= ctrans('texts.po_number')." {$invoice->po_number}
";
+ }
$invoice_list .= ctrans('texts.invoice_number_short')." {$invoice->number}
";
$invoice_list .= ctrans('texts.invoice_amount').' '.Number::formatMoney($invoice->pivot->amount, $this->client).'
';
$invoice_list .= ctrans('texts.invoice_balance').' '.Number::formatMoney($invoice->fresh()->balance, $this->client).'
';
$invoice_list .= '-----
';
-
}
return $invoice_list;
@@ -406,5 +398,4 @@ class PaymentEmailEngine extends BaseEmailEngine
';
}
-
}
diff --git a/app/Mail/Engine/PurchaseOrderEmailEngine.php b/app/Mail/Engine/PurchaseOrderEmailEngine.php
index 4f4722381e02..4d104cc2d149 100644
--- a/app/Mail/Engine/PurchaseOrderEmailEngine.php
+++ b/app/Mail/Engine/PurchaseOrderEmailEngine.php
@@ -12,21 +12,16 @@
namespace App\Mail\Engine;
use App\DataMapper\EmailTemplateDefaults;
-use App\Jobs\Entity\CreateEntityPdf;
use App\Jobs\Vendor\CreatePurchaseOrderPdf;
use App\Models\Account;
-use App\Models\Expense;
use App\Models\PurchaseOrder;
-use App\Models\Task;
use App\Models\Vendor;
-use App\Models\VendorContact;
use App\Utils\HtmlEngine;
use App\Utils\Ninja;
use App\Utils\Number;
use App\Utils\Traits\MakesHash;
use App\Utils\VendorHtmlEngine;
use Illuminate\Support\Facades\App;
-use Illuminate\Support\Facades\Lang;
use Illuminate\Support\Facades\URL;
class PurchaseOrderEmailEngine extends BaseEmailEngine
@@ -85,15 +80,15 @@ class PurchaseOrderEmailEngine extends BaseEmailEngine
$body_template .= '$view_button
';
}
$text_body = trans(
- 'texts.purchase_order_message',
- [
- 'purchase_order' => $this->purchase_order->number,
- 'company' => $this->purchase_order->company->present()->name(),
- 'amount' => Number::formatMoney($this->purchase_order->balance, $this->vendor),
- ],
- null,
- $this->vendor->company->locale()
- )."\n\n".$this->invitation->getLink();
+ 'texts.purchase_order_message',
+ [
+ 'purchase_order' => $this->purchase_order->number,
+ 'company' => $this->purchase_order->company->present()->name(),
+ 'amount' => Number::formatMoney($this->purchase_order->balance, $this->vendor),
+ ],
+ null,
+ $this->vendor->company->locale()
+ )."\n\n".$this->invitation->getLink();
if (is_array($this->template_data) && array_key_exists('subject', $this->template_data) && strlen($this->template_data['subject']) > 0) {
$subject_template = $this->template_data['subject'];
@@ -127,33 +122,29 @@ class PurchaseOrderEmailEngine extends BaseEmailEngine
->setTextBody($text_body);
if ($this->vendor->getSetting('pdf_email_attachment') !== false && $this->purchase_order->company->account->hasFeature(Account::FEATURE_PDF_ATTACHMENT)) {
-
$pdf = (new CreatePurchaseOrderPdf($this->invitation))->rawPdf();
- $this->setAttachments([['file' => base64_encode($pdf), 'name' => $this->purchase_order->numberFormatter().'.pdf']]);
-
+ $this->setAttachments([['file' => base64_encode($pdf), 'name' => $this->purchase_order->numberFormatter().'.pdf']]);
}
//attach third party documents
if ($this->vendor->getSetting('document_email_attachment') !== false && $this->purchase_order->company->account->hasFeature(Account::FEATURE_DOCUMENTS)) {
-
// Storage::url
foreach ($this->purchase_order->documents as $document) {
-
- if($document->size > $this->max_attachment_size)
+ if ($document->size > $this->max_attachment_size) {
$this->setAttachmentLinks([" $document->hash]) ."'>". $document->name .""]);
- else
+ } else {
$this->setAttachments([['path' => $document->filePath(), 'name' => $document->name, 'mime' => null]]);
+ }
}
foreach ($this->purchase_order->company->documents as $document) {
-
- if($document->size > $this->max_attachment_size)
+ if ($document->size > $this->max_attachment_size) {
$this->setAttachmentLinks([" $document->hash]) ."'>". $document->name .""]);
- else
+ } else {
$this->setAttachments([['path' => $document->filePath(), 'name' => $document->name, 'mime' => null]]);
+ }
}
-
}
return $this;
diff --git a/app/Mail/Engine/QuoteEmailEngine.php b/app/Mail/Engine/QuoteEmailEngine.php
index 03a3be65f988..440624a3975f 100644
--- a/app/Mail/Engine/QuoteEmailEngine.php
+++ b/app/Mail/Engine/QuoteEmailEngine.php
@@ -17,7 +17,6 @@ use App\Utils\HtmlEngine;
use App\Utils\Ninja;
use App\Utils\Number;
use Illuminate\Support\Facades\App;
-use Illuminate\Support\Facades\Lang;
use Illuminate\Support\Facades\URL;
class QuoteEmailEngine extends BaseEmailEngine
@@ -95,16 +94,15 @@ class QuoteEmailEngine extends BaseEmailEngine
}
$text_body = trans(
- 'texts.quote_message',
- [
- 'quote' => $this->quote->number,
- 'company' => $this->quote->company->present()->name(),
- 'amount' => Number::formatMoney($this->quote->amount, $this->client),
- ],
- null,
- $this->client->locale()
-
- )."\n\n".$this->invitation->getLink();
+ 'texts.quote_message',
+ [
+ 'quote' => $this->quote->number,
+ 'company' => $this->quote->company->present()->name(),
+ 'amount' => Number::formatMoney($this->quote->amount, $this->client),
+ ],
+ null,
+ $this->client->locale()
+ )."\n\n".$this->invitation->getLink();
$this->setTemplate($this->client->getSetting('email_style'))
->setContact($this->contact)
@@ -118,30 +116,28 @@ class QuoteEmailEngine extends BaseEmailEngine
->setTextBody($text_body);
if ($this->client->getSetting('pdf_email_attachment') !== false && $this->quote->company->account->hasFeature(Account::FEATURE_PDF_ATTACHMENT)) {
-
$pdf = ((new CreateRawPdf($this->invitation, $this->invitation->company->db))->handle());
- $this->setAttachments([['file' => base64_encode($pdf), 'name' => $this->quote->numberFormatter().'.pdf']]);
+ $this->setAttachments([['file' => base64_encode($pdf), 'name' => $this->quote->numberFormatter().'.pdf']]);
}
//attach third party documents
if ($this->client->getSetting('document_email_attachment') !== false && $this->quote->company->account->hasFeature(Account::FEATURE_DOCUMENTS)) {
-
// Storage::url
foreach ($this->quote->documents as $document) {
-
- if($document->size > $this->max_attachment_size)
+ if ($document->size > $this->max_attachment_size) {
$this->setAttachmentLinks([" $document->hash]) ."'>". $document->name .""]);
- else
- $this->setAttachments([['file' => base64_encode($document->getFile()), 'path' => $document->filePath(), 'name' => $document->name, 'mime' => NULL, ]]);
+ } else {
+ $this->setAttachments([['file' => base64_encode($document->getFile()), 'path' => $document->filePath(), 'name' => $document->name, 'mime' => null, ]]);
+ }
}
foreach ($this->quote->company->documents as $document) {
-
- if($document->size > $this->max_attachment_size)
+ if ($document->size > $this->max_attachment_size) {
$this->setAttachmentLinks([" $document->hash]) ."'>". $document->name .""]);
- else
- $this->setAttachments([['file' => base64_encode($document->getFile()), 'path' => $document->filePath(), 'name' => $document->name, 'mime' => NULL, ]]);
+ } else {
+ $this->setAttachments([['file' => base64_encode($document->getFile()), 'path' => $document->filePath(), 'name' => $document->name, 'mime' => null, ]]);
+ }
}
}
diff --git a/app/Mail/Import/CsvImportCompleted.php b/app/Mail/Import/CsvImportCompleted.php
index 73944eef34e5..ac00b1a31c9e 100644
--- a/app/Mail/Import/CsvImportCompleted.php
+++ b/app/Mail/Import/CsvImportCompleted.php
@@ -34,7 +34,7 @@ class CsvImportCompleted extends Mailable
* 'company' => Company $company,
* 'entity_count' => (array) $entity_count
* ];
- */
+ */
public $data;
/**
diff --git a/app/Mail/MigrationCompleted.php b/app/Mail/MigrationCompleted.php
index daddca816c82..43e2672789e0 100644
--- a/app/Mail/MigrationCompleted.php
+++ b/app/Mail/MigrationCompleted.php
@@ -40,7 +40,6 @@ class MigrationCompleted extends Mailable
*/
public function build()
{
-
MultiDB::setDb($this->db);
$this->company = Company::find($this->company_id);
diff --git a/app/Mail/MigrationFailed.php b/app/Mail/MigrationFailed.php
index 44be3af46b41..f235cdc1dd3b 100644
--- a/app/Mail/MigrationFailed.php
+++ b/app/Mail/MigrationFailed.php
@@ -51,8 +51,9 @@ class MigrationFailed extends Mailable
$special_message = '';
- if($this->exception instanceof ClientHostedMigrationException)
+ if ($this->exception instanceof ClientHostedMigrationException) {
$special_message = $this->content;
+ }
return $this
->from(config('mail.from.address'), config('mail.from.name'))
diff --git a/app/Mail/Ninja/EmailQuotaExceeded.php b/app/Mail/Ninja/EmailQuotaExceeded.php
index 859ef0f11200..6746c3a1d2d6 100644
--- a/app/Mail/Ninja/EmailQuotaExceeded.php
+++ b/app/Mail/Ninja/EmailQuotaExceeded.php
@@ -11,9 +11,7 @@
namespace App\Mail\Ninja;
-use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
-use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\App;
class EmailQuotaExceeded extends Mailable
diff --git a/app/Mail/Ninja/GmailTokenInvalid.php b/app/Mail/Ninja/GmailTokenInvalid.php
index 116afca8663d..98e401506249 100644
--- a/app/Mail/Ninja/GmailTokenInvalid.php
+++ b/app/Mail/Ninja/GmailTokenInvalid.php
@@ -11,9 +11,7 @@
namespace App\Mail\Ninja;
-use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
-use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\App;
class GmailTokenInvalid extends Mailable
diff --git a/app/Mail/RecurringInvoice/ClientContactRequestCancellationObject.php b/app/Mail/RecurringInvoice/ClientContactRequestCancellationObject.php
index ed46041a30fb..0ae4682d1c70 100644
--- a/app/Mail/RecurringInvoice/ClientContactRequestCancellationObject.php
+++ b/app/Mail/RecurringInvoice/ClientContactRequestCancellationObject.php
@@ -18,8 +18,9 @@ use Illuminate\Support\Facades\App;
class ClientContactRequestCancellationObject
{
-
- public function __construct(public RecurringInvoice $recurring_invoice, public ClientContact $client_contact, private bool $gateway_refund_attempted){}
+ public function __construct(public RecurringInvoice $recurring_invoice, public ClientContact $client_contact, private bool $gateway_refund_attempted)
+ {
+ }
public function build()
{
@@ -32,8 +33,9 @@ class ClientContactRequestCancellationObject
$t->replace(Ninja::transformTranslations($this->company->settings));
$content = ctrans('texts.recurring_cancellation_request_body', ['contact' => $this->client_contact->present()->name(), 'client' => $this->client_contact->client->present()->name(), 'invoice' => $this->recurring_invoice->number]);
- if($this->gateway_refund_attempted)
+ if ($this->gateway_refund_attempted) {
$content .= "\n\n" . ctrans('texts.status') . " : " . ctrans('texts.payment_status_6');
+ }
$data = [
'title' => ctrans('texts.recurring_cancellation_request', ['contact' => $this->client_contact->present()->name()]),
diff --git a/app/Mail/SupportMessageSent.php b/app/Mail/SupportMessageSent.php
index 7258aa19bf01..ea8f34f49373 100644
--- a/app/Mail/SupportMessageSent.php
+++ b/app/Mail/SupportMessageSent.php
@@ -6,9 +6,9 @@ use App\Utils\Ninja;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
+use Illuminate\Support\Carbon;
use LimitIterator;
use SplFileObject;
-use Illuminate\Support\Carbon;
class SupportMessageSent extends Mailable
{
@@ -73,8 +73,9 @@ class SupportMessageSent extends Mailable
$plan_status = '';
- if($account->plan_expires && Carbon::parse($account->plan_expires)->lt(now()))
+ if ($account->plan_expires && Carbon::parse($account->plan_expires)->lt(now())) {
$plan_status = 'Plan Expired :: ';
+ }
if (Ninja::isHosted()) {
$subject = "{$priority}Hosted-{$db}-{$is_large}{$platform}{$migrated}{$trial} :: {$plan} :: {$plan_status} ".date('M jS, g:ia');
diff --git a/app/Mail/TemplateEmail.php b/app/Mail/TemplateEmail.php
index f3550899aee5..6d8dd1ffaac8 100644
--- a/app/Mail/TemplateEmail.php
+++ b/app/Mail/TemplateEmail.php
@@ -11,20 +11,13 @@
namespace App\Mail;
-use App\Jobs\Entity\CreateEntityPdf;
use App\Jobs\Invoice\CreateUbl;
use App\Models\Account;
-use App\Models\Client;
use App\Models\ClientContact;
-use App\Models\User;
use App\Services\PdfMaker\Designs\Utilities\DesignHelpers;
use App\Utils\HtmlEngine;
use App\Utils\Ninja;
-use App\Utils\TemplateEngine;
-use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
-use Illuminate\Queue\SerializesModels;
-use Illuminate\Support\Facades\Storage;
class TemplateEmail extends Mailable
{
@@ -52,34 +45,32 @@ class TemplateEmail extends Mailable
}
/**
- * Supports inline attachments for large
+ * Supports inline attachments for large
* attachments in custom designs
- *
+ *
* @return string
*/
private function buildLinksForCustomDesign(): string
{
$links = $this->build_email->getAttachmentLinks();
- if(count($links) == 0)
+ if (count($links) == 0) {
return '';
+ }
$link_string = '';
- foreach($this->build_email->getAttachmentLinks() as $link)
- {
+ foreach ($this->build_email->getAttachmentLinks() as $link) {
$link_string .= "- {$link}
";
}
$link_string .= '
';
return $link_string;
-
}
public function build()
{
-
$template_name = 'email.template.'.$this->build_email->getTemplate();
if ($this->build_email->getTemplate() == 'light' || $this->build_email->getTemplate() == 'dark') {
@@ -119,7 +110,7 @@ class TemplateEmail extends Mailable
if (Ninja::isHosted()) {
$bccs = explode(',', str_replace(' ', '', $settings->bcc_email));
$this->bcc(array_slice($bccs, 0, 2));
- //$this->bcc(reset($bccs)); //remove whitespace if any has been inserted.
+ //$this->bcc(reset($bccs)); //remove whitespace if any has been inserted.
} else {
$this->bcc(explode(',', str_replace(' ', '', $settings->bcc_email)));
}//remove whitespace if any has been inserted.
@@ -147,10 +138,11 @@ class TemplateEmail extends Mailable
]);
foreach ($this->build_email->getAttachments() as $file) {
- if(array_key_exists('file', $file))
+ if (array_key_exists('file', $file)) {
$this->attachData(base64_decode($file['file']), $file['name']);
- else
+ } else {
$this->attach($file['path'], ['as' => $file['name'], 'mime' => null]);
+ }
}
if ($this->invitation && $this->invitation->invoice && $settings->ubl_email_attachment && $this->company->account->hasFeature(Account::FEATURE_PDF_ATTACHMENT)) {
diff --git a/app/Mail/VendorTemplateEmail.php b/app/Mail/VendorTemplateEmail.php
index 4ea8e8493b34..2ac0987b8045 100644
--- a/app/Mail/VendorTemplateEmail.php
+++ b/app/Mail/VendorTemplateEmail.php
@@ -11,21 +11,10 @@
namespace App\Mail;
-use App\Jobs\Invoice\CreateUbl;
-use App\Jobs\Vendor\CreatePurchaseOrderPdf;
-use App\Models\Account;
-use App\Models\Client;
-use App\Models\User;
use App\Models\VendorContact;
use App\Services\PdfMaker\Designs\Utilities\DesignHelpers;
-use App\Utils\HtmlEngine;
-use App\Utils\Ninja;
-use App\Utils\TemplateEngine;
use App\Utils\VendorHtmlEngine;
-use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
-use Illuminate\Queue\SerializesModels;
-use Illuminate\Support\Facades\Storage;
class VendorTemplateEmail extends Mailable
{
@@ -53,29 +42,28 @@ class VendorTemplateEmail extends Mailable
}
/**
- * Supports inline attachments for large
+ * Supports inline attachments for large
* attachments in custom designs
- *
+ *
* @return string
*/
private function buildLinksForCustomDesign(): string
{
$links = $this->build_email->getAttachmentLinks();
- if(count($links) == 0)
+ if (count($links) == 0) {
return '';
+ }
$link_string = '';
- foreach($this->build_email->getAttachmentLinks() as $link)
- {
+ foreach ($this->build_email->getAttachmentLinks() as $link) {
$link_string .= "- {$link}
";
}
$link_string .= '
';
return $link_string;
-
}
public function build()
@@ -140,12 +128,11 @@ class VendorTemplateEmail extends Mailable
foreach ($this->build_email->getAttachments() as $file) {
-
- if(array_key_exists('file', $file))
+ if (array_key_exists('file', $file)) {
$this->attachData(base64_decode($file['file']), $file['name']);
- else
+ } else {
$this->attach($file['path'], ['as' => $file['name'], 'mime' => null]);
-
+ }
}
return $this;
diff --git a/app/Models/Account.php b/app/Models/Account.php
index a4ec1d5d568b..ff66c29599c4 100644
--- a/app/Models/Account.php
+++ b/app/Models/Account.php
@@ -157,8 +157,9 @@ class Account extends BaseModel
public function getPlan()
{
- if(Carbon::parse($this->plan_expires)->lt(now()))
+ if (Carbon::parse($this->plan_expires)->lt(now())) {
return '';
+ }
return $this->plan ?: '';
}
@@ -169,7 +170,6 @@ class Account extends BaseModel
$self_host = ! Ninja::isNinja();
switch ($feature) {
-
case self::FEATURE_TASKS:
case self::FEATURE_EXPENSES:
case self::FEATURE_QUOTES:
@@ -190,11 +190,11 @@ class Account extends BaseModel
case self::FEATURE_CUSTOM_URL:
return $self_host || ! empty($plan_details);
- // Pro; No trial allowed, unless they're trialing enterprise with an active pro plan
+ // Pro; No trial allowed, unless they're trialing enterprise with an active pro plan
case self::FEATURE_MORE_CLIENTS:
return $self_host || ! empty($plan_details) && (! $plan_details['trial'] || ! empty($this->getPlanDetails(false, false)));
- // White Label
+ // White Label
case self::FEATURE_WHITE_LABEL:
if (! $self_host && $plan_details && ! $plan_details['expires']) {
return false;
@@ -213,7 +213,7 @@ class Account extends BaseModel
return $self_host || ! empty($plan_details) && ($plan_details['plan'] == self::PLAN_ENTERPRISE);
- // Enterprise; No Trial allowed
+ // Enterprise; No Trial allowed
case self::FEATURE_DOCUMENTS:
case self::FEATURE_USER_PERMISSIONS:
return $self_host || ! empty($plan_details) && $plan_details['plan'] == self::PLAN_ENTERPRISE && ! $plan_details['trial'];
@@ -234,8 +234,9 @@ class Account extends BaseModel
return false;
}
- if($this->plan_expires && Carbon::parse($this->plan_expires)->lt(now()))
+ if ($this->plan_expires && Carbon::parse($this->plan_expires)->lt(now())) {
return false;
+ }
return $this->plan == 'pro' || $this->plan == 'enterprise';
}
@@ -246,8 +247,9 @@ class Account extends BaseModel
return false;
}
- if($this->plan_expires && Carbon::parse($this->plan_expires)->lt(now()))
+ if ($this->plan_expires && Carbon::parse($this->plan_expires)->lt(now())) {
return true;
+ }
return $this->plan == 'free' || is_null($this->plan) || empty($this->plan);
}
@@ -306,10 +308,9 @@ class Account extends BaseModel
$trial_started = $this->trial_started;
$trial_expires = Carbon::parse($this->trial_started)->addSeconds($duration);
- if($trial_expires->greaterThan(now())){
+ if ($trial_expires->greaterThan(now())) {
$trial_active = true;
- }
-
+ }
}
$plan_active = false;
@@ -386,20 +387,22 @@ class Account extends BaseModel
public function getDailyEmailLimit()
{
- if($this->is_flagged)
+ if ($this->is_flagged) {
return 0;
+ }
- if(Carbon::createFromTimestamp($this->created_at)->diffInWeeks() == 0)
+ if (Carbon::createFromTimestamp($this->created_at)->diffInWeeks() == 0) {
return 20;
+ }
- if(Carbon::createFromTimestamp($this->created_at)->diffInWeeks() <= 2 && !$this->payment_id)
+ if (Carbon::createFromTimestamp($this->created_at)->diffInWeeks() <= 2 && !$this->payment_id) {
return 20;
+ }
- if($this->isPaid()){
+ if ($this->isPaid()) {
$limit = $this->paid_plan_email_quota;
$limit += Carbon::createFromTimestamp($this->created_at)->diffInMonths() * 50;
- }
- else{
+ } else {
$limit = $this->free_plan_email_quota;
$limit += Carbon::createFromTimestamp($this->created_at)->diffInMonths() * 10;
}
@@ -409,22 +412,22 @@ class Account extends BaseModel
public function emailsSent()
{
- if(is_null(Cache::get($this->key)))
+ if (is_null(Cache::get($this->key))) {
return 0;
+ }
return Cache::get($this->key);
- }
+ }
public function emailQuotaExceeded() :bool
{
- if(is_null(Cache::get($this->key)))
+ if (is_null(Cache::get($this->key))) {
return false;
+ }
try {
- if(Cache::get($this->key) > $this->getDailyEmailLimit()) {
-
- if(is_null(Cache::get("throttle_notified:{$this->key}"))) {
-
+ if (Cache::get($this->key) > $this->getDailyEmailLimit()) {
+ if (is_null(Cache::get("throttle_notified:{$this->key}"))) {
App::forgetInstance('translator');
$t = app('translator');
$t->replace(Ninja::transformTranslations($this->companies()->first()->settings));
@@ -438,14 +441,14 @@ class Account extends BaseModel
Cache::put("throttle_notified:{$this->key}", true, 60 * 24);
- if(config('ninja.notification.slack'))
+ if (config('ninja.notification.slack')) {
$this->companies()->first()->notification(new EmailQuotaNotification($this))->ninja();
+ }
}
return true;
}
- }
- catch(\Exception $e){
+ } catch(\Exception $e) {
\Sentry\captureMessage("I encountered an error with email quotas for account {$this->key} - defaulting to SEND");
}
@@ -456,15 +459,14 @@ class Account extends BaseModel
{
nlog("checking if gmail credential notification has already been sent");
- if(is_null(Cache::get($this->key)))
+ if (is_null(Cache::get($this->key))) {
return false;
+ }
nlog("Sending notification");
try {
-
- if(is_null(Cache::get("gmail_credentials_notified:{$this->key}"))) {
-
+ if (is_null(Cache::get("gmail_credentials_notified:{$this->key}"))) {
App::forgetInstance('translator');
$t = app('translator');
$t->replace(Ninja::transformTranslations($this->companies()->first()->settings));
@@ -478,20 +480,17 @@ class Account extends BaseModel
Cache::put("gmail_credentials_notified:{$this->key}", true, 60 * 24);
- if(config('ninja.notification.slack'))
+ if (config('ninja.notification.slack')) {
$this->companies()->first()->notification(new GmailCredentialNotification($this))->ninja();
+ }
}
return true;
-
- }
- catch(\Exception $e){
+ } catch(\Exception $e) {
\Sentry\captureMessage("I encountered an error with sending with gmail for account {$this->key}");
}
return false;
-
-
}
public function resolveRouteBinding($value, $field = null)
@@ -507,22 +506,21 @@ class Account extends BaseModel
public function getTrialDays()
{
- if($this->payment_id)
+ if ($this->payment_id) {
return 0;
+ }
$plan_expires = Carbon::parse($this->plan_expires);
- if(!$this->payment_id && $plan_expires->gt(now())){
-
+ if (!$this->payment_id && $plan_expires->gt(now())) {
$diff = $plan_expires->diffInDays();
- if($diff > 14);
- return 0;
+ if ($diff > 14);
+ return 0;
return $diff;
}
return 0;
}
-
}
diff --git a/app/Models/Activity.php b/app/Models/Activity.php
index 5c2af53d3ab9..aa8107cfc4ad 100644
--- a/app/Models/Activity.php
+++ b/app/Models/Activity.php
@@ -12,7 +12,6 @@
namespace App\Models;
use App\Utils\Traits\MakesHash;
-use Illuminate\Database\Eloquent\ModelNotFoundException as ModelNotFoundException;
class Activity extends StaticModel
{
@@ -374,5 +373,4 @@ class Activity extends StaticModel
{
return $this->belongsTo(Company::class);
}
-
-}
\ No newline at end of file
+}
diff --git a/app/Models/Backup.php b/app/Models/Backup.php
index bb3b890142ef..c4920e64adf5 100644
--- a/app/Models/Backup.php
+++ b/app/Models/Backup.php
@@ -11,7 +11,6 @@
namespace App\Models;
-use App\Models\Client;
use Illuminate\Support\Facades\Storage;
class Backup extends BaseModel
@@ -38,17 +37,17 @@ class Backup extends BaseModel
Storage::disk(config('filesystems.default'))->put($file_path, $html);
- $this->filename = $file_path;
- $this->save();
-
+ $this->filename = $file_path;
+ $this->save();
}
public function deleteFile()
{
nlog('deleting => '.$this->filename);
- if(!$this->filename)
+ if (!$this->filename) {
return;
+ }
try {
Storage::disk(config('filesystems.default'))->delete($this->filename);
diff --git a/app/Models/BankIntegration.php b/app/Models/BankIntegration.php
index c6455f2d8004..00d94d562b70 100644
--- a/app/Models/BankIntegration.php
+++ b/app/Models/BankIntegration.php
@@ -11,7 +11,6 @@
namespace App\Models;
-use App\Models\Filterable;
use App\Models\Traits\Excludable;
use Illuminate\Database\Eloquent\SoftDeletes;
@@ -60,5 +59,4 @@ class BankIntegration extends BaseModel
{
return $this->hasMany(BankTransaction::class)->withTrashed();
}
-
-}
\ No newline at end of file
+}
diff --git a/app/Models/BankTransaction.php b/app/Models/BankTransaction.php
index 0798492d6f3a..0cf098a6f866 100644
--- a/app/Models/BankTransaction.php
+++ b/app/Models/BankTransaction.php
@@ -11,9 +11,6 @@
namespace App\Models;
-use App\Models\BankTransactionRule;
-use App\Models\Filterable;
-use App\Models\Invoice;
use App\Services\Bank\BankService;
use App\Utils\Traits\MakesHash;
use Illuminate\Database\Eloquent\SoftDeletes;
@@ -51,15 +48,12 @@ class BankTransaction extends BaseModel
$invoices = explode(",", $this->invoice_ids);
- if(count($invoices) >= 1)
- {
-
- foreach($invoices as $invoice){
-
- if(is_string($invoice) && strlen($invoice) > 1)
+ if (count($invoices) >= 1) {
+ foreach ($invoices as $invoice) {
+ if (is_string($invoice) && strlen($invoice) > 1) {
$collection->push($this->decodePrimaryKey($invoice));
+ }
}
-
}
return $collection;
@@ -104,5 +98,4 @@ class BankTransaction extends BaseModel
{
return new BankService($this);
}
-
-}
\ No newline at end of file
+}
diff --git a/app/Models/BankTransactionRule.php b/app/Models/BankTransactionRule.php
index b7c879d722cd..817e4495cefd 100644
--- a/app/Models/BankTransactionRule.php
+++ b/app/Models/BankTransactionRule.php
@@ -11,8 +11,6 @@
namespace App\Models;
-use App\Models\Filterable;
-use App\Utils\Traits\MakesHash;
use Illuminate\Database\Eloquent\SoftDeletes;
class BankTransactionRule extends BaseModel
@@ -167,6 +165,4 @@ class BankTransactionRule extends BaseModel
// //search expenses
// }
// }
-
-
-}
\ No newline at end of file
+}
diff --git a/app/Models/BaseModel.php b/app/Models/BaseModel.php
index 08ad4823838d..dbb56e5876c8 100644
--- a/app/Models/BaseModel.php
+++ b/app/Models/BaseModel.php
@@ -21,7 +21,6 @@ use Illuminate\Database\Eloquent\ModelNotFoundException as ModelNotFoundExceptio
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;
-
/**
* Class BaseModel
*
@@ -139,7 +138,7 @@ class BaseModel extends Model
$this->company->settings = $settings;
$this->company->save();
break;
- //todo check that saving any other entity (Invoice:: RecurringInvoice::) settings is valid using the default:
+ //todo check that saving any other entity (Invoice:: RecurringInvoice::) settings is valid using the default:
default:
$this->client->settings = $settings;
$this->client->save();
@@ -168,7 +167,6 @@ class BaseModel extends Model
*/
public function resolveRouteBinding($value, $field = null)
{
-
if (is_numeric($value)) {
throw new ModelNotFoundException("Record with value {$value} not found");
}
@@ -208,11 +206,11 @@ class BaseModel extends Model
/**
* Model helper to send events for webhooks
- *
- * @param int $event_id
+ *
+ * @param int $event_id
* @param string $additional_data optional includes
- *
- * @return void
+ *
+ * @return void
*/
public function sendEvent(int $event_id, string $additional_data = ""): void
{
@@ -224,6 +222,4 @@ class BaseModel extends Model
WebhookHandler::dispatch($event_id, $this, $this->company, $additional_data);
}
}
-
-
}
diff --git a/app/Models/Client.php b/app/Models/Client.php
index 8895377e14f3..173bd945310f 100644
--- a/app/Models/Client.php
+++ b/app/Models/Client.php
@@ -14,14 +14,9 @@ namespace App\Models;
use App\DataMapper\ClientSettings;
use App\DataMapper\CompanySettings;
use App\DataMapper\FeesAndLimits;
-use App\Models\CompanyGateway;
-use App\Models\Expense;
use App\Models\Presenters\ClientPresenter;
-use App\Models\Project;
-use App\Models\Quote;
-use App\Models\Task;
-use App\Services\Client\ClientService;
use App\Models\Traits\Excludable;
+use App\Services\Client\ClientService;
use App\Utils\Traits\AppSetup;
use App\Utils\Traits\ClientGroupSettingsSaver;
use App\Utils\Traits\GeneratesCounter;
@@ -375,7 +370,6 @@ class Client extends BaseModel implements HasLocalePreference
*/
public function getSetting($setting)
{
-
/*Client Settings*/
if ($this->settings && property_exists($this->settings, $setting) && isset($this->settings->{$setting})) {
/*need to catch empty string here*/
diff --git a/app/Models/ClientContact.php b/app/Models/ClientContact.php
index 229cf262fd0f..9c91224b4825 100644
--- a/app/Models/ClientContact.php
+++ b/app/Models/ClientContact.php
@@ -16,7 +16,6 @@ use App\Jobs\Mail\NinjaMailerJob;
use App\Jobs\Mail\NinjaMailerObject;
use App\Mail\ClientContact\ClientContactResetPasswordObject;
use App\Models\Presenters\ClientContactPresenter;
-use App\Notifications\ClientContactResetPassword;
use App\Utils\Ninja;
use App\Utils\Traits\MakesHash;
use Illuminate\Contracts\Translation\HasLocalePreference;
@@ -208,7 +207,6 @@ class ClientContact extends Authenticatable implements HasLocalePreference
$nmo->settings = $this->company->settings;
NinjaMailerJob::dispatch($nmo);
-
}
public function preferredLocale()
@@ -289,7 +287,5 @@ class ClientContact extends Authenticatable implements HasLocalePreference
return '';
break;
}
-
-
}
}
diff --git a/app/Models/ClientGatewayToken.php b/app/Models/ClientGatewayToken.php
index 5efcea44ad83..8b41d65508a8 100644
--- a/app/Models/ClientGatewayToken.php
+++ b/app/Models/ClientGatewayToken.php
@@ -12,7 +12,6 @@
namespace App\Models;
use App\Utils\Traits\MakesDates;
-use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class ClientGatewayToken extends BaseModel
@@ -69,5 +68,4 @@ class ClientGatewayToken extends BaseModel
{
return $this->belongsTo(User::class)->withTrashed();
}
-
}
diff --git a/app/Models/Company.php b/app/Models/Company.php
index 54a4b5f718a0..ccb8514a6592 100644
--- a/app/Models/Company.php
+++ b/app/Models/Company.php
@@ -12,12 +12,7 @@
namespace App\Models;
use App\DataMapper\CompanySettings;
-use App\Models\BankTransaction;
-use App\Models\BankTransactionRule;
-use App\Models\Language;
use App\Models\Presenters\CompanyPresenter;
-use App\Models\PurchaseOrder;
-use App\Models\User;
use App\Services\Notification\NotificationService;
use App\Utils\Ninja;
use App\Utils\Traits\AppSetup;
@@ -384,7 +379,6 @@ class Company extends BaseModel
$this->buildCache(true);
$companies = Cache::get('countries');
-
}
return $companies->filter(function ($item) {
@@ -449,14 +443,13 @@ class Company extends BaseModel
}
//if the cache is still dead, get from DB
- if(!$languages && property_exists($this->settings, 'language_id'))
+ if (!$languages && property_exists($this->settings, 'language_id')) {
return Language::find($this->settings->language_id);
+ }
return $languages->filter(function ($item) {
return $item->id == $this->settings->language_id;
})->first();
-
-
}
public function getLocale()
@@ -686,5 +679,4 @@ class Company extends BaseModel
return $item->id == $this->getSetting('date_format_id');
})->first()->format;
}
-
}
diff --git a/app/Models/CompanyGateway.php b/app/Models/CompanyGateway.php
index bdee65f7fe5f..9dc1f03c2453 100644
--- a/app/Models/CompanyGateway.php
+++ b/app/Models/CompanyGateway.php
@@ -11,12 +11,8 @@
namespace App\Models;
-use App\Models\Filterable;
-use App\Models\GatewayType;
use App\Utils\Number;
use Illuminate\Database\Eloquent\SoftDeletes;
-use PDO;
-use stdClass;
class CompanyGateway extends BaseModel
{
@@ -106,7 +102,6 @@ class CompanyGateway extends BaseModel
public function system_logs()
{
-
return $this->company
->system_log_relation
->where('type_id', $this->gateway_consts[$this->gateway->key])
@@ -138,11 +133,11 @@ class CompanyGateway extends BaseModel
{
$class = static::driver_class();
- if(!$class)
+ if (!$class) {
return false;
+ }
return new $class($this, $client);
-
}
private function driver_class()
@@ -150,8 +145,9 @@ class CompanyGateway extends BaseModel
$class = 'App\\PaymentDrivers\\'.$this->gateway->provider.'PaymentDriver';
$class = str_replace('_', '', $class);
- if (class_exists($class))
+ if (class_exists($class)) {
return $class;
+ }
return false;
@@ -308,25 +304,20 @@ class CompanyGateway extends BaseModel
$fee = $this->calcGatewayFee($amount, $gateway_type_id);
- if($fee > 0) {
-
+ if ($fee > 0) {
$fees_and_limits = $this->fees_and_limits->{$gateway_type_id};
- if(strlen($fees_and_limits->fee_percent) >=1)
+ if (strlen($fees_and_limits->fee_percent) >=1) {
$label .= $fees_and_limits->fee_percent . '%';
+ }
- if(strlen($fees_and_limits->fee_amount) >=1 && $fees_and_limits->fee_amount > 0){
-
- if(strlen($label) > 1) {
-
+ if (strlen($fees_and_limits->fee_amount) >=1 && $fees_and_limits->fee_amount > 0) {
+ if (strlen($label) > 1) {
$label .= ' + ' . Number::formatMoney($fees_and_limits->fee_amount, $client);
-
- }else {
+ } else {
$label .= Number::formatMoney($fees_and_limits->fee_amount, $client);
}
}
-
-
}
@@ -344,44 +335,38 @@ class CompanyGateway extends BaseModel
$fee = 0;
- if($fees_and_limits->adjust_fee_percent)
- {
- $adjusted_fee = 0;
+ if ($fees_and_limits->adjust_fee_percent) {
+ $adjusted_fee = 0;
- if ($fees_and_limits->fee_amount) {
- $adjusted_fee += $fees_and_limits->fee_amount + $amount;
+ if ($fees_and_limits->fee_amount) {
+ $adjusted_fee += $fees_and_limits->fee_amount + $amount;
+ } else {
+ $adjusted_fee = $amount;
+ }
+
+ if ($fees_and_limits->fee_percent) {
+ $divisor = 1 - ($fees_and_limits->fee_percent/100);
+
+ $gross_amount = round($adjusted_fee/$divisor, 2);
+ $fee = $gross_amount - $amount;
+ }
+ } else {
+ if ($fees_and_limits->fee_amount) {
+ $fee += $fees_and_limits->fee_amount;
+ }
+
+ if ($fees_and_limits->fee_percent) {
+ if ($fees_and_limits->fee_percent == 100) { //unusual edge case if the user wishes to charge a fee of 100% 09/01/2022
+ $fee += $amount;
+ } else {
+ $fee += round(($amount * $fees_and_limits->fee_percent / 100), 2);
}
- else
- $adjusted_fee = $amount;
-
- if ($fees_and_limits->fee_percent) {
-
- $divisor = 1 - ($fees_and_limits->fee_percent/100);
-
- $gross_amount = round($adjusted_fee/$divisor,2);
- $fee = $gross_amount - $amount;
-
- }
-
- }
- else
- {
- if ($fees_and_limits->fee_amount) {
- $fee += $fees_and_limits->fee_amount;
- }
-
- if ($fees_and_limits->fee_percent) {
- if($fees_and_limits->fee_percent == 100){ //unusual edge case if the user wishes to charge a fee of 100% 09/01/2022
- $fee += $amount;
- }
- else
- $fee += round(($amount * $fees_and_limits->fee_percent / 100), 2);
- //elseif ($fees_and_limits->adjust_fee_percent) {
- // $fee += round(($amount / (1 - $fees_and_limits->fee_percent / 100) - $amount), 2);
- //} else {
+ //elseif ($fees_and_limits->adjust_fee_percent) {
+ // $fee += round(($amount / (1 - $fees_and_limits->fee_percent / 100) - $amount), 2);
+ //} else {
- //}
- }
+ //}
+ }
}
/* Cap fee if we have to here. */
if ($fees_and_limits->fee_cap > 0 && ($fee > $fees_and_limits->fee_cap)) {
@@ -415,5 +400,4 @@ class CompanyGateway extends BaseModel
{
return route('payment_webhook', ['company_key' => $this->company->company_key, 'company_gateway_id' => $this->hashed_id]);
}
-
}
diff --git a/app/Models/Country.php b/app/Models/Country.php
index 1bd3ecb33a60..7e6c467b7098 100644
--- a/app/Models/Country.php
+++ b/app/Models/Country.php
@@ -35,8 +35,8 @@ class Country extends StaticModel
{
return trans('texts.country_'.$this->name);
}
- public function getID() :string
- {
- return $this->id;
- }
+ public function getID() :string
+ {
+ return $this->id;
+ }
}
diff --git a/app/Models/Credit.php b/app/Models/Credit.php
index 060301f525ad..577501ee9c28 100644
--- a/app/Models/Credit.php
+++ b/app/Models/Credit.php
@@ -11,7 +11,6 @@
namespace App\Models;
-use App\Events\Credit\CreditWasUpdated;
use App\Helpers\Invoice\InvoiceSum;
use App\Helpers\Invoice\InvoiceSumInclusive;
use App\Jobs\Entity\CreateEntityPdf;
diff --git a/app/Models/Document.php b/app/Models/Document.php
index ee0be33a276f..27de8d36514f 100644
--- a/app/Models/Document.php
+++ b/app/Models/Document.php
@@ -12,7 +12,6 @@
namespace App\Models;
use App\Helpers\Document\WithTypeHelpers;
-use App\Models\Filterable;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Storage;
diff --git a/app/Models/ExpenseCategory.php b/app/Models/ExpenseCategory.php
index 0b24741f09f0..92f07ac0f0e0 100644
--- a/app/Models/ExpenseCategory.php
+++ b/app/Models/ExpenseCategory.php
@@ -11,7 +11,6 @@
namespace App\Models;
-use App\Models\Filterable;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;
diff --git a/app/Models/GroupSetting.php b/app/Models/GroupSetting.php
index b465c8a03039..f8ac3bc1e959 100644
--- a/app/Models/GroupSetting.php
+++ b/app/Models/GroupSetting.php
@@ -13,8 +13,8 @@ namespace App\Models;
use App\Utils\Traits\MakesHash;
use Illuminate\Database\Eloquent\Model;
-use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\ModelNotFoundException as ModelNotFoundException;
+use Illuminate\Database\Eloquent\SoftDeletes;
class GroupSetting extends StaticModel
{
@@ -73,7 +73,6 @@ class GroupSetting extends StaticModel
*/
public function resolveRouteBinding($value, $field = null)
{
-
if (is_numeric($value)) {
throw new ModelNotFoundException("Record with value {$value} not found");
}
@@ -82,7 +81,5 @@ class GroupSetting extends StaticModel
->withTrashed()
->company()
->where('id', $this->decodePrimaryKey($value))->firstOrFail();
-
}
}
-
diff --git a/app/Models/Invoice.php b/app/Models/Invoice.php
index 4b0a89b2bbb5..c3a6bf966536 100644
--- a/app/Models/Invoice.php
+++ b/app/Models/Invoice.php
@@ -16,9 +16,7 @@ use App\Events\Invoice\InvoiceWasEmailed;
use App\Helpers\Invoice\InvoiceSum;
use App\Helpers\Invoice\InvoiceSumInclusive;
use App\Jobs\Entity\CreateEntityPdf;
-use App\Models\Expense;
use App\Models\Presenters\InvoicePresenter;
-use App\Models\Task;
use App\Services\Invoice\InvoiceService;
use App\Services\Ledger\LedgerService;
use App\Utils\Ninja;
@@ -579,52 +577,40 @@ class Invoice extends BaseModel
public function expense_documents()
{
-
$line_items = $this->line_items;
$expense_ids = [];
- foreach($line_items as $item)
- {
-
- if(property_exists($item, 'expense_id'))
- {
+ foreach ($line_items as $item) {
+ if (property_exists($item, 'expense_id')) {
$expense_ids[] = $item->expense_id;
}
-
}
return Expense::whereIn('id', $this->transformKeys($expense_ids))
->where('invoice_documents', 1)
->where('company_id', $this->company_id)
->cursor();
-
}
public function task_documents()
{
-
$line_items = $this->line_items;
$task_ids = [];
- foreach($line_items as $item)
- {
-
- if(property_exists($item, 'task_id'))
- {
+ foreach ($line_items as $item) {
+ if (property_exists($item, 'task_id')) {
$task_ids[] = $item->task_id;
}
-
}
return Task::whereIn('id', $this->transformKeys($task_ids))
- ->whereHas('company', function($query){
- $query->where('invoice_task_documents', 1);
+ ->whereHas('company', function ($query) {
+ $query->where('invoice_task_documents', 1);
})
->where('company_id', $this->company_id)
->cursor();
-
}
public function translate_entity()
diff --git a/app/Models/Payment.php b/app/Models/Payment.php
index 32a3e2cf3101..88d936dc1360 100644
--- a/app/Models/Payment.php
+++ b/app/Models/Payment.php
@@ -13,7 +13,6 @@ namespace App\Models;
use App\Events\Payment\PaymentWasRefunded;
use App\Events\Payment\PaymentWasVoided;
-use App\Models\GatewayType;
use App\Services\Ledger\LedgerService;
use App\Services\Payment\PaymentService;
use App\Utils\Ninja;
@@ -23,7 +22,6 @@ use App\Utils\Traits\MakesDates;
use App\Utils\Traits\MakesHash;
use App\Utils\Traits\Payment\Refundable;
use Illuminate\Database\Eloquent\SoftDeletes;
-use Illuminate\Support\Facades\Cache;
class Payment extends BaseModel
{
diff --git a/app/Models/PaymentTerm.php b/app/Models/PaymentTerm.php
index fa8c40a13af2..28240282d320 100644
--- a/app/Models/PaymentTerm.php
+++ b/app/Models/PaymentTerm.php
@@ -11,7 +11,6 @@
namespace App\Models;
-use App\Models\Filterable;
use Illuminate\Database\Eloquent\SoftDeletes;
/**
diff --git a/app/Models/Paymentable.php b/app/Models/Paymentable.php
index a06e9579e2bb..0a6df1e8fbd2 100644
--- a/app/Models/Paymentable.php
+++ b/app/Models/Paymentable.php
@@ -43,5 +43,4 @@ class Paymentable extends Pivot
{
return $this->belongsTo(Payment::class);
}
-
}
diff --git a/app/Models/Presenters/CompanyPresenter.php b/app/Models/Presenters/CompanyPresenter.php
index d4ba609c7913..092bf2a5a9e4 100644
--- a/app/Models/Presenters/CompanyPresenter.php
+++ b/app/Models/Presenters/CompanyPresenter.php
@@ -12,8 +12,8 @@
namespace App\Models\Presenters;
use App\Models\Country;
-use Illuminate\Support\Str;
use Illuminate\Support\Facades\Storage;
+use Illuminate\Support\Str;
/**
* Class CompanyPresenter.
@@ -28,7 +28,6 @@ class CompanyPresenter extends EntityPresenter
$settings = $this->entity->settings;
return $this->settings->name ?: ctrans('texts.untitled_account');
-
}
@@ -38,20 +37,18 @@ class CompanyPresenter extends EntityPresenter
$settings = $this->entity->settings;
}
- if(strlen($settings->company_logo) >= 1 && (strpos($settings->company_logo, 'http') !== false))
+ if (strlen($settings->company_logo) >= 1 && (strpos($settings->company_logo, 'http') !== false)) {
return $settings->company_logo;
- else if(strlen($settings->company_logo) >= 1)
+ } elseif (strlen($settings->company_logo) >= 1) {
return url('') . $settings->company_logo;
- else{
+ } else {
return "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";
//return asset('images/new_logo.png');
}
-
}
public function logoDocker($settings = null)
{
-
if (! $settings) {
$settings = $this->entity->settings;
}
@@ -60,11 +57,11 @@ class CompanyPresenter extends EntityPresenter
$logo = Storage::get("{$this->company_key}/{$basename}");
- if(!$logo)
+ if (!$logo) {
return $this->logo($settings);
+ }
return "data:image/png;base64, ". base64_encode($logo);
-
}
/**
@@ -76,25 +73,25 @@ class CompanyPresenter extends EntityPresenter
$settings = $this->entity->settings;
}
- if(config('ninja.is_docker') || config('ninja.local_download'))
+ if (config('ninja.is_docker') || config('ninja.local_download')) {
return $this->logoDocker($settings);
+ }
- $context_options =array(
- "ssl"=>array(
+ $context_options =[
+ "ssl"=>[
"verify_peer"=>false,
"verify_peer_name"=>false,
- ),
- );
+ ],
+ ];
- if(strlen($settings->company_logo) >= 1 && (strpos($settings->company_logo, 'http') !== false))
+ if (strlen($settings->company_logo) >= 1 && (strpos($settings->company_logo, 'http') !== false)) {
return "data:image/png;base64, ". base64_encode(@file_get_contents($settings->company_logo, false, stream_context_create($context_options)));
- else if(strlen($settings->company_logo) >= 1)
+ } elseif (strlen($settings->company_logo) >= 1) {
return "data:image/png;base64, ". base64_encode(@file_get_contents(url('') . $settings->company_logo, false, stream_context_create($context_options)));
- else{
+ } else {
return "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";
//return "data:image/png;base64, ". base64_encode(@file_get_contents(asset('images/new_logo.png'), false, stream_context_create($context_options)));
}
-
}
public function address($settings = null)
@@ -185,8 +182,8 @@ class CompanyPresenter extends EntityPresenter
/**
* Return company website URL.
- *
- * @return string
+ *
+ * @return string
*/
public function website(): string
{
diff --git a/app/Models/Presenters/EntityPresenter.php b/app/Models/Presenters/EntityPresenter.php
index 1f32c25cde84..ccfe0ca364da 100644
--- a/app/Models/Presenters/EntityPresenter.php
+++ b/app/Models/Presenters/EntityPresenter.php
@@ -13,7 +13,6 @@ namespace App\Models\Presenters;
use App\Utils\Traits\MakesHash;
use Laracasts\Presenter\Presenter;
-use URL;
/**
* Class EntityPresenter.
diff --git a/app/Models/Presenters/RecurringInvoicePresenter.php b/app/Models/Presenters/RecurringInvoicePresenter.php
index a6631248812e..2c2a3793016c 100644
--- a/app/Models/Presenters/RecurringInvoicePresenter.php
+++ b/app/Models/Presenters/RecurringInvoicePresenter.php
@@ -11,10 +11,6 @@
namespace App\Models\Presenters;
-use App\Utils\Number;
-use App\Utils\Traits\MakesDates;
-use Laracasts\Presenter\PresentableTrait;
-
/**
* Class InvoicePresenter.
*
diff --git a/app/Models/Presenters/RecurringQuotePresenter.php b/app/Models/Presenters/RecurringQuotePresenter.php
index 7e87051265a3..aecf3e640d1c 100644
--- a/app/Models/Presenters/RecurringQuotePresenter.php
+++ b/app/Models/Presenters/RecurringQuotePresenter.php
@@ -11,10 +11,6 @@
namespace App\Models\Presenters;
-use App\Utils\Number;
-use App\Utils\Traits\MakesDates;
-use Laracasts\Presenter\PresentableTrait;
-
/**
* Class QuotePresenter.
*
diff --git a/app/Models/PurchaseOrder.php b/app/Models/PurchaseOrder.php
index cb369b180a78..ec01acec204e 100644
--- a/app/Models/PurchaseOrder.php
+++ b/app/Models/PurchaseOrder.php
@@ -11,10 +11,8 @@
namespace App\Models;
-
use App\Helpers\Invoice\InvoiceSum;
use App\Helpers\Invoice\InvoiceSumInclusive;
-use App\Jobs\Entity\CreateEntityPdf;
use App\Jobs\Vendor\CreatePurchaseOrderPdf;
use App\Services\PurchaseOrder\PurchaseOrderService;
use App\Utils\Ninja;
@@ -198,31 +196,30 @@ class PurchaseOrder extends BaseModel
public function pdf_file_path($invitation = null, string $type = 'path', bool $portal = false)
{
if (! $invitation) {
-
- if($this->invitations()->exists())
+ if ($this->invitations()->exists()) {
$invitation = $this->invitations()->first();
- else{
+ } else {
$this->service()->createInvitations();
$invitation = $this->invitations()->first();
}
-
}
- if(!$invitation)
+ if (!$invitation) {
throw new \Exception('Hard fail, could not create an invitation - is there a valid contact?');
+ }
$file_path = $this->vendor->purchase_order_filepath($invitation).$this->numberFormatter().'.pdf';
- if(Ninja::isHosted() && $portal && Storage::disk(config('filesystems.default'))->exists($file_path)){
+ if (Ninja::isHosted() && $portal && Storage::disk(config('filesystems.default'))->exists($file_path)) {
return Storage::disk(config('filesystems.default'))->{$type}($file_path);
- }
- elseif(Ninja::isHosted() && $portal){
- $file_path = (new CreatePurchaseOrderPdf($invitation,config('filesystems.default')))->handle();
+ } elseif (Ninja::isHosted() && $portal) {
+ $file_path = (new CreatePurchaseOrderPdf($invitation, config('filesystems.default')))->handle();
return Storage::disk(config('filesystems.default'))->{$type}($file_path);
}
- if(Storage::disk('public')->exists($file_path))
+ if (Storage::disk('public')->exists($file_path)) {
return Storage::disk('public')->{$type}($file_path);
+ }
$file_path = (new CreatePurchaseOrderPdf($invitation))->handle();
return Storage::disk('public')->{$type}($file_path);
diff --git a/app/Models/Quote.php b/app/Models/Quote.php
index f03d8c9ff5d9..f0e35a5c57e3 100644
--- a/app/Models/Quote.php
+++ b/app/Models/Quote.php
@@ -11,7 +11,6 @@
namespace App\Models;
-use App\Events\Quote\QuoteWasUpdated;
use App\Helpers\Invoice\InvoiceSum;
use App\Helpers\Invoice\InvoiceSumInclusive;
use App\Jobs\Entity\CreateEntityPdf;
@@ -242,7 +241,6 @@ class Quote extends BaseModel
if (Ninja::isHosted() && $portal && Storage::disk(config('filesystems.default'))->exists($file_path)) {
return Storage::disk(config('filesystems.default'))->{$type}($file_path);
} elseif (Ninja::isHosted() && $portal) {
-
$file_path = (new CreateEntityPdf($invitation, config('filesystems.default')))->handle();
return Storage::disk(config('filesystems.default'))->{$type}($file_path);
}
@@ -362,5 +360,4 @@ class Quote extends BaseModel
{
return $entity_string;
}
-
}
diff --git a/app/Models/RecurringExpense.php b/app/Models/RecurringExpense.php
index 47e5c6571287..502a568409e7 100644
--- a/app/Models/RecurringExpense.php
+++ b/app/Models/RecurringExpense.php
@@ -11,7 +11,6 @@
namespace App\Models;
-use App\Models\RecurringInvoice;
use App\Services\Recurring\RecurringService;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Carbon;
@@ -203,7 +202,6 @@ class RecurringExpense extends BaseModel
public function recurringDates()
{
-
/* Return early if nothing to send back! */
if ($this->status_id == RecurringInvoice::STATUS_COMPLETED ||
$this->remaining_cycles == 0 ||
diff --git a/app/Models/RecurringInvoice.php b/app/Models/RecurringInvoice.php
index ba388e38b848..a5b78f379627 100644
--- a/app/Models/RecurringInvoice.php
+++ b/app/Models/RecurringInvoice.php
@@ -250,8 +250,7 @@ class RecurringInvoice extends BaseModel
/* If this setting is enabled, the recurring invoice may be set in the past */
if ($this->company->stop_on_unpaid_recurring) {
-
- /* Lets set the next send date to now so we increment from today, rather than in the past*/
+ /* Lets set the next send date to now so we increment from today, rather than in the past*/
if (Carbon::parse($this->next_send_date)->lt(now()->subDays(3))) {
$this->next_send_date_client = now()->format('Y-m-d');
}
@@ -296,8 +295,7 @@ class RecurringInvoice extends BaseModel
/* If this setting is enabled, the recurring invoice may be set in the past */
if ($this->company->stop_on_unpaid_recurring) {
-
- /* Lets set the next send date to now so we increment from today, rather than in the past*/
+ /* Lets set the next send date to now so we increment from today, rather than in the past*/
if (Carbon::parse($this->next_send_date)->lt(now()->subDays(3))) {
$this->next_send_date_client = now()->format('Y-m-d');
}
@@ -499,7 +497,6 @@ class RecurringInvoice extends BaseModel
*/
public function recurringDates()
{
-
/* Return early if nothing to send back! */
if ($this->status_id == self::STATUS_COMPLETED ||
$this->remaining_cycles == 0 ||
@@ -553,7 +550,7 @@ class RecurringInvoice extends BaseModel
case '0':
return $this->calculateDateFromTerms($date);
break;
-
+
case 'on_receipt':
return Carbon::parse($date)->copy();
break;
diff --git a/app/Models/RecurringQuote.php b/app/Models/RecurringQuote.php
index 55ece05b0dce..67d710942d0b 100644
--- a/app/Models/RecurringQuote.php
+++ b/app/Models/RecurringQuote.php
@@ -14,8 +14,6 @@ namespace App\Models;
use App\Helpers\Invoice\InvoiceSum;
use App\Helpers\Invoice\InvoiceSumInclusive;
use App\Models\Presenters\RecurringQuotePresenter;
-use App\Models\Quote;
-use App\Models\RecurringQuoteInvitation;
use App\Services\Recurring\RecurringService;
use App\Utils\Traits\MakesDates;
use App\Utils\Traits\MakesHash;
@@ -418,7 +416,6 @@ class RecurringQuote extends BaseModel
*/
public function recurringDates()
{
-
/* Return early if nothing to send back! */
if ($this->status_id == self::STATUS_COMPLETED ||
$this->remaining_cycles == 0 ||
diff --git a/app/Models/RecurringQuoteInvitation.php b/app/Models/RecurringQuoteInvitation.php
index 20ec337aa49c..ea9888312250 100644
--- a/app/Models/RecurringQuoteInvitation.php
+++ b/app/Models/RecurringQuoteInvitation.php
@@ -11,7 +11,6 @@
namespace App\Models;
-use App\Models\RecurringQuote;
use App\Utils\Traits\Inviteable;
use App\Utils\Traits\MakesDates;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
diff --git a/app/Models/StaticModel.php b/app/Models/StaticModel.php
index 5f5b9df0bd13..cb86f5126bd9 100644
--- a/app/Models/StaticModel.php
+++ b/app/Models/StaticModel.php
@@ -51,13 +51,11 @@ class StaticModel extends Model
*/
public function resolveRouteBinding($value, $field = null)
{
-
if (is_numeric($value)) {
throw new ModelNotFoundException("Record with value {$value} not found");
}
return $this
->where('id', $this->decodePrimaryKey($value))->firstOrFail();
-
}
}
diff --git a/app/Models/Subscription.php b/app/Models/Subscription.php
index 5aa543d65a2a..a9c788be1162 100644
--- a/app/Models/Subscription.php
+++ b/app/Models/Subscription.php
@@ -11,11 +11,8 @@
namespace App\Models;
-use App\Models\Filterable;
-use App\Models\RecurringInvoice;
use App\Services\Subscription\SubscriptionService;
use Illuminate\Database\Eloquent\Factories\HasFactory;
-use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Subscription extends BaseModel
@@ -96,7 +93,6 @@ class Subscription extends BaseModel
public function nextDateByInterval($date, $frequency_id)
{
switch ($frequency_id) {
-
case RecurringInvoice::FREQUENCY_DAILY:
return $date->addDay();
case RecurringInvoice::FREQUENCY_WEEKLY:
diff --git a/app/Models/TaskStatus.php b/app/Models/TaskStatus.php
index f476cc1b1c79..6b1a7fd67139 100644
--- a/app/Models/TaskStatus.php
+++ b/app/Models/TaskStatus.php
@@ -11,7 +11,6 @@
namespace App\Models;
-use App\Models\Filterable;
use Illuminate\Database\Eloquent\SoftDeletes;
/**
diff --git a/app/Models/TaxRate.php b/app/Models/TaxRate.php
index 5e29f2ddbee0..9a893b001538 100644
--- a/app/Models/TaxRate.php
+++ b/app/Models/TaxRate.php
@@ -11,7 +11,6 @@
namespace App\Models;
-use App\Models\Filterable;
use App\Utils\Traits\MakesHash;
use Illuminate\Database\Eloquent\SoftDeletes;
diff --git a/app/Models/Traits/Excludable.php b/app/Models/Traits/Excludable.php
index 1d23541f3c3b..ba8f87431da2 100644
--- a/app/Models/Traits/Excludable.php
+++ b/app/Models/Traits/Excludable.php
@@ -11,14 +11,15 @@
namespace App\Models\Traits;
-trait Excludable {
-
+trait Excludable
+{
/**
* Get the array of columns
- *
+ *
* @return mixed
*/
- private function getTableColumns() {
+ private function getTableColumns()
+ {
return $this->getConnection()->getSchemaBuilder()->getColumnListing($this->getTable());
}
@@ -26,13 +27,11 @@ trait Excludable {
* Exclude an array of elements from the result.
* @param $query
* @param $columns
- *
+ *
* @return mixed
*/
public function scopeExclude($query, $columns)
{
return $query->select(array_diff($this->getTableColumns(), (array) $columns));
}
-
}
-
diff --git a/app/Models/User.php b/app/Models/User.php
index d0c09fb1270e..d0b59d4f1248 100644
--- a/app/Models/User.php
+++ b/app/Models/User.php
@@ -29,9 +29,7 @@ use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Carbon;
-use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Auth;
-use Illuminate\Support\Facades\Cache;
use Laracasts\Presenter\PresentableTrait;
class User extends Authenticatable implements MustVerifyEmail
@@ -319,7 +317,7 @@ class User extends Authenticatable implements MustVerifyEmail
/**
* Returns true is user is an admin _or_ owner
- *
+ *
* @return boolean
*/
public function isSuperUser() :bool
@@ -367,18 +365,17 @@ class User extends Authenticatable implements MustVerifyEmail
*/
public function hasPermission($permission) : bool
{
-
- /**
- * We use the limit parameter here to ensure we don't split on permissions that have multiple underscores.
- *
- * For example view_recurring_invoice without the limit would split to view bank recurring invoice
- *
- * Using only part 0 and 1 would search for permission view_recurring / edit_recurring so this would
- * leak permissions for other recurring_* entities
- *
- * The solution here will split the word - consistently - into view _ {entity} and edit _ {entity}
- *
- */
+ /**
+ * We use the limit parameter here to ensure we don't split on permissions that have multiple underscores.
+ *
+ * For example view_recurring_invoice without the limit would split to view bank recurring invoice
+ *
+ * Using only part 0 and 1 would search for permission view_recurring / edit_recurring so this would
+ * leak permissions for other recurring_* entities
+ *
+ * The solution here will split the word - consistently - into view _ {entity} and edit _ {entity}
+ *
+ */
$parts = explode('_', $permission, 2);
$all_permission = '____';
$edit_all = '____';
@@ -389,11 +386,10 @@ class User extends Authenticatable implements MustVerifyEmail
$all_permission = $parts[0].'_all';
/*If this is a view search, make sure we add in the edit_{entity} AND edit_all permission into the checks*/
- if($parts[0] == 'view') {
+ if ($parts[0] == 'view') {
$edit_all = 'edit_all';
$edit_entity = "edit_{$parts[1]}";
}
-
}
return $this->isOwner() ||
@@ -402,7 +398,6 @@ class User extends Authenticatable implements MustVerifyEmail
(stripos($this->token()->cu->permissions, $all_permission) !== false) ||
(stripos($this->token()->cu->permissions, $edit_all) !== false) ||
(stripos($this->token()->cu->permissions, $edit_entity) !== false);
-
}
/**
@@ -411,13 +406,12 @@ class User extends Authenticatable implements MustVerifyEmail
*
* This method is used when we need to scope down the query
* and display a limited subset.
- *
+ *
* @param string $permission '["view_all"]'
- * @return boolean
+ * @return boolean
*/
public function hasExactPermission(string $permission = '___'): bool
{
-
$parts = explode('_', $permission);
$all_permission = '__';
@@ -427,7 +421,6 @@ class User extends Authenticatable implements MustVerifyEmail
return (stripos($this->token()->cu->permissions, $all_permission) !== false) ||
(stripos($this->token()->cu->permissions, $permission) !== false);
-
}
/**
@@ -436,23 +429,19 @@ class User extends Authenticatable implements MustVerifyEmail
*
* This method is used when we need to scope down the query
* and display a limited subset.
- *
- * @param array $permissions
- * @return boolean
+ *
+ * @param array $permissions
+ * @return boolean
*/
public function hasIntersectPermissions(array $permissions = []): bool
{
-
- foreach($permissions as $permission)
- {
-
- if($this->hasExactPermission($permission))
+ foreach ($permissions as $permission) {
+ if ($this->hasExactPermission($permission)) {
return true;
-
+ }
}
return false;
-
}
/**
@@ -461,26 +450,23 @@ class User extends Authenticatable implements MustVerifyEmail
*
* This method is used when we need to scope down the query
* and display a limited subset.
- *
- * @param array $permissions
- * @return boolean
+ *
+ * @param array $permissions
+ * @return boolean
*/
public function hasIntersectPermissionsOrAdmin(array $permissions = []): bool
{
-
- if($this->isSuperUser())
+ if ($this->isSuperUser()) {
return true;
+ }
- foreach($permissions as $permission)
- {
-
- if($this->hasExactPermission($permission))
+ foreach ($permissions as $permission) {
+ if ($this->hasExactPermission($permission)) {
return true;
-
+ }
}
return false;
-
}
diff --git a/app/Models/Vendor.php b/app/Models/Vendor.php
index 333f99bab0b0..20582ad23ab0 100644
--- a/app/Models/Vendor.php
+++ b/app/Models/Vendor.php
@@ -15,7 +15,6 @@ use App\DataMapper\CompanySettings;
use App\Models\Presenters\VendorPresenter;
use App\Utils\Traits\AppSetup;
use App\Utils\Traits\GeneratesCounter;
-use App\Utils\Traits\NumberFormatter;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Cache;
use Laracasts\Presenter\PresentableTrait;
@@ -114,7 +113,6 @@ class Vendor extends BaseModel
return $currencies->filter(function ($item) {
return $item->id == $this->currency_id;
})->first();
-
}
public function timezone()
@@ -192,5 +190,4 @@ class Vendor extends BaseModel
{
return $this->company->date_format();
}
-
}
diff --git a/app/Models/VendorContact.php b/app/Models/VendorContact.php
index 75fb8a4eb692..68dccb66ea32 100644
--- a/app/Models/VendorContact.php
+++ b/app/Models/VendorContact.php
@@ -157,10 +157,8 @@ class VendorContact extends Authenticatable implements HasLocalePreference
public function getLoginLink()
{
-
$domain = isset($this->company->portal_domain) ? $this->company->portal_domain : $this->company->domain();
return $domain.'/vendor/key_login/'.$this->contact_key;
-
}
}
diff --git a/app/Notifications/Admin/EntitySentNotification.php b/app/Notifications/Admin/EntitySentNotification.php
index 42e7e9cf060d..11b40dbb8650 100644
--- a/app/Notifications/Admin/EntitySentNotification.php
+++ b/app/Notifications/Admin/EntitySentNotification.php
@@ -12,14 +12,9 @@
namespace App\Notifications\Admin;
use App\Utils\Number;
-use Illuminate\Bus\Queueable;
-use Illuminate\Contracts\Queue\ShouldQueue;
-use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Messages\SlackMessage;
use Illuminate\Notifications\Notification;
-use Illuminate\Queue\InteractsWithQueue;
-use Illuminate\Queue\SerializesModels;
//@deprecated
class EntitySentNotification extends Notification
diff --git a/app/Notifications/Admin/EntityViewedNotification.php b/app/Notifications/Admin/EntityViewedNotification.php
index 48541a6f3774..4b916800a173 100644
--- a/app/Notifications/Admin/EntityViewedNotification.php
+++ b/app/Notifications/Admin/EntityViewedNotification.php
@@ -12,14 +12,9 @@
namespace App\Notifications\Admin;
use App\Utils\Number;
-use Illuminate\Bus\Queueable;
-use Illuminate\Contracts\Queue\ShouldQueue;
-use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Messages\SlackMessage;
use Illuminate\Notifications\Notification;
-use Illuminate\Queue\InteractsWithQueue;
-use Illuminate\Queue\SerializesModels;
class EntityViewedNotification extends Notification
{
diff --git a/app/Notifications/Admin/NewPaymentNotification.php b/app/Notifications/Admin/NewPaymentNotification.php
index 5d27ec1e24be..082f70b7fe6c 100644
--- a/app/Notifications/Admin/NewPaymentNotification.php
+++ b/app/Notifications/Admin/NewPaymentNotification.php
@@ -12,14 +12,9 @@
namespace App\Notifications\Admin;
use App\Utils\Number;
-use Illuminate\Bus\Queueable;
-use Illuminate\Contracts\Queue\ShouldQueue;
-use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Messages\SlackMessage;
use Illuminate\Notifications\Notification;
-use Illuminate\Queue\InteractsWithQueue;
-use Illuminate\Queue\SerializesModels;
class NewPaymentNotification extends Notification
{
diff --git a/app/Notifications/BaseNotification.php b/app/Notifications/BaseNotification.php
index db2335dc4797..6985f8c731ce 100644
--- a/app/Notifications/BaseNotification.php
+++ b/app/Notifications/BaseNotification.php
@@ -16,7 +16,6 @@ use App\Models\Invoice;
use App\Utils\TempFile;
use App\Utils\Traits\MakesInvoiceHtml;
use Illuminate\Bus\Queueable;
-use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
diff --git a/app/Notifications/ClientContactRequestCancellation.php b/app/Notifications/ClientContactRequestCancellation.php
index e0c66ae5e454..69ea4b2ef52f 100644
--- a/app/Notifications/ClientContactRequestCancellation.php
+++ b/app/Notifications/ClientContactRequestCancellation.php
@@ -13,7 +13,6 @@ namespace App\Notifications;
use Closure;
use Illuminate\Bus\Queueable;
-use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Messages\SlackMessage;
diff --git a/app/Notifications/NewAccountCreated.php b/app/Notifications/NewAccountCreated.php
index e0337b35d20d..997b8ab0e51b 100644
--- a/app/Notifications/NewAccountCreated.php
+++ b/app/Notifications/NewAccountCreated.php
@@ -12,7 +12,6 @@
namespace App\Notifications;
use Illuminate\Bus\Queueable;
-use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Messages\SlackMessage;
diff --git a/app/Notifications/Ninja/ClientAccountNotFound.php b/app/Notifications/Ninja/ClientAccountNotFound.php
index 5a2418cedd2d..d913d9c4f001 100644
--- a/app/Notifications/Ninja/ClientAccountNotFound.php
+++ b/app/Notifications/Ninja/ClientAccountNotFound.php
@@ -11,26 +11,21 @@
namespace App\Notifications\Ninja;
-use App\Models\User;
-use Illuminate\Bus\Queueable;
-use Illuminate\Contracts\Queue\ShouldQueue;
-use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Messages\SlackMessage;
use Illuminate\Notifications\Notification;
-use Illuminate\Queue\InteractsWithQueue;
-use Illuminate\Queue\SerializesModels;
-class ClientAccountNotFound extends Notification
+class ClientAccountNotFound extends Notification
{
-
/**
* Create a new notification instance.
*
* @return void
*/
- public function __construct(protected string $account_key, protected string $email){}
+ public function __construct(protected string $account_key, protected string $email)
+ {
+ }
/**
* Get the notification's delivery channels.
@@ -68,7 +63,6 @@ class ClientAccountNotFound extends Notification
public function toSlack($notifiable)
{
-
$content = "Client not found, unable to remove account\n";
$content .= "Account: {$this->account_key }\n";
$content .= "Email: {$this->email}\n";
diff --git a/app/Notifications/Ninja/DomainFailureNotification.php b/app/Notifications/Ninja/DomainFailureNotification.php
index 9fdcdf8ff1a5..f22f08926572 100644
--- a/app/Notifications/Ninja/DomainFailureNotification.php
+++ b/app/Notifications/Ninja/DomainFailureNotification.php
@@ -11,20 +11,12 @@
namespace App\Notifications\Ninja;
-use App\Models\Account;
-use App\Models\Client;
-use Illuminate\Bus\Queueable;
-use Illuminate\Contracts\Queue\ShouldQueue;
-use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Messages\SlackMessage;
use Illuminate\Notifications\Notification;
-use Illuminate\Queue\InteractsWithQueue;
-use Illuminate\Queue\SerializesModels;
-class DomainFailureNotification extends Notification
+class DomainFailureNotification extends Notification
{
-
/**
* Create a new notification instance.
*
@@ -75,7 +67,7 @@ class DomainFailureNotification extends Notification
public function toSlack($notifiable)
{
$content = "Domain Certificate failure:\n";
- $content .= "{$this->domain}\n";
+ $content .= "{$this->domain}\n";
return (new SlackMessage)
->success()
diff --git a/app/Notifications/Ninja/DomainRenewalFailureNotification.php b/app/Notifications/Ninja/DomainRenewalFailureNotification.php
index 3c31d5df9cd9..860c6ae8b65f 100644
--- a/app/Notifications/Ninja/DomainRenewalFailureNotification.php
+++ b/app/Notifications/Ninja/DomainRenewalFailureNotification.php
@@ -11,20 +11,12 @@
namespace App\Notifications\Ninja;
-use App\Models\Account;
-use App\Models\Client;
-use Illuminate\Bus\Queueable;
-use Illuminate\Contracts\Queue\ShouldQueue;
-use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Messages\SlackMessage;
use Illuminate\Notifications\Notification;
-use Illuminate\Queue\InteractsWithQueue;
-use Illuminate\Queue\SerializesModels;
-class DomainRenewalFailureNotification extends Notification
+class DomainRenewalFailureNotification extends Notification
{
-
/**
* Create a new notification instance.
*
@@ -75,7 +67,7 @@ class DomainRenewalFailureNotification extends Notification
public function toSlack($notifiable)
{
$content = "Domain Certificate _renewal_ failure:\n";
- $content .= "{$this->domain}\n";
+ $content .= "{$this->domain}\n";
return (new SlackMessage)
->success()
diff --git a/app/Notifications/Ninja/EmailBounceNotification.php b/app/Notifications/Ninja/EmailBounceNotification.php
index 61d4128fca2f..9af33db98043 100644
--- a/app/Notifications/Ninja/EmailBounceNotification.php
+++ b/app/Notifications/Ninja/EmailBounceNotification.php
@@ -11,14 +11,9 @@
namespace App\Notifications\Ninja;
-use Illuminate\Bus\Queueable;
-use Illuminate\Contracts\Queue\ShouldQueue;
-use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Messages\SlackMessage;
use Illuminate\Notifications\Notification;
-use Illuminate\Queue\InteractsWithQueue;
-use Illuminate\Queue\SerializesModels;
class EmailBounceNotification extends Notification
{
diff --git a/app/Notifications/Ninja/EmailQualityNotification.php b/app/Notifications/Ninja/EmailQualityNotification.php
index 4c6b0f3ed91c..3ec56255ad65 100644
--- a/app/Notifications/Ninja/EmailQualityNotification.php
+++ b/app/Notifications/Ninja/EmailQualityNotification.php
@@ -12,18 +12,12 @@
namespace App\Notifications\Ninja;
use App\Models\Company;
-use Illuminate\Bus\Queueable;
-use Illuminate\Contracts\Queue\ShouldQueue;
-use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Messages\SlackMessage;
use Illuminate\Notifications\Notification;
-use Illuminate\Queue\InteractsWithQueue;
-use Illuminate\Queue\SerializesModels;
-class EmailQualityNotification extends Notification
+class EmailQualityNotification extends Notification
{
-
/**
* Create a new notification instance.
*
@@ -76,7 +70,6 @@ class EmailQualityNotification extends Notification
public function toSlack($notifiable)
{
-
$content = "Email Quality notification for Company {$this->company->company_key} \n";
$owner = $this->company->owner();
diff --git a/app/Notifications/Ninja/EmailQuotaNotification.php b/app/Notifications/Ninja/EmailQuotaNotification.php
index cfb2cf851eff..24eab8d21664 100644
--- a/app/Notifications/Ninja/EmailQuotaNotification.php
+++ b/app/Notifications/Ninja/EmailQuotaNotification.php
@@ -11,14 +11,9 @@
namespace App\Notifications\Ninja;
-use Illuminate\Bus\Queueable;
-use Illuminate\Contracts\Queue\ShouldQueue;
-use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Messages\SlackMessage;
use Illuminate\Notifications\Notification;
-use Illuminate\Queue\InteractsWithQueue;
-use Illuminate\Queue\SerializesModels;
class EmailQuotaNotification extends Notification
{
diff --git a/app/Notifications/Ninja/EmailSpamNotification.php b/app/Notifications/Ninja/EmailSpamNotification.php
index 567a1f71d015..b3b95c7f8ca3 100644
--- a/app/Notifications/Ninja/EmailSpamNotification.php
+++ b/app/Notifications/Ninja/EmailSpamNotification.php
@@ -11,14 +11,9 @@
namespace App\Notifications\Ninja;
-use Illuminate\Bus\Queueable;
-use Illuminate\Contracts\Queue\ShouldQueue;
-use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Messages\SlackMessage;
use Illuminate\Notifications\Notification;
-use Illuminate\Queue\InteractsWithQueue;
-use Illuminate\Queue\SerializesModels;
class EmailSpamNotification extends Notification
{
diff --git a/app/Notifications/Ninja/GmailCredentialNotification.php b/app/Notifications/Ninja/GmailCredentialNotification.php
index 63a5706ceb59..df9aee792fe9 100644
--- a/app/Notifications/Ninja/GmailCredentialNotification.php
+++ b/app/Notifications/Ninja/GmailCredentialNotification.php
@@ -11,14 +11,9 @@
namespace App\Notifications\Ninja;
-use Illuminate\Bus\Queueable;
-use Illuminate\Contracts\Queue\ShouldQueue;
-use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Messages\SlackMessage;
use Illuminate\Notifications\Notification;
-use Illuminate\Queue\InteractsWithQueue;
-use Illuminate\Queue\SerializesModels;
class GmailCredentialNotification extends Notification
{
diff --git a/app/Notifications/Ninja/NewAccountCreated.php b/app/Notifications/Ninja/NewAccountCreated.php
index 2ec30a7b930e..f0e47d8cbdc2 100644
--- a/app/Notifications/Ninja/NewAccountCreated.php
+++ b/app/Notifications/Ninja/NewAccountCreated.php
@@ -12,7 +12,6 @@
namespace App\Notifications\Ninja;
use Illuminate\Bus\Queueable;
-use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Messages\SlackMessage;
diff --git a/app/Notifications/Ninja/NewAccountNotification.php b/app/Notifications/Ninja/NewAccountNotification.php
index 34149107e516..6c32ef582446 100644
--- a/app/Notifications/Ninja/NewAccountNotification.php
+++ b/app/Notifications/Ninja/NewAccountNotification.php
@@ -13,18 +13,12 @@ namespace App\Notifications\Ninja;
use App\Models\Account;
use App\Models\Client;
-use Illuminate\Bus\Queueable;
-use Illuminate\Contracts\Queue\ShouldQueue;
-use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Messages\SlackMessage;
use Illuminate\Notifications\Notification;
-use Illuminate\Queue\InteractsWithQueue;
-use Illuminate\Queue\SerializesModels;
-class NewAccountNotification extends Notification
+class NewAccountNotification extends Notification
{
-
/**
* Create a new notification instance.
*
diff --git a/app/Notifications/Ninja/RenewalFailureNotification.php b/app/Notifications/Ninja/RenewalFailureNotification.php
index 5dbbbe8a6d05..1ed7b15aed1f 100644
--- a/app/Notifications/Ninja/RenewalFailureNotification.php
+++ b/app/Notifications/Ninja/RenewalFailureNotification.php
@@ -11,25 +11,21 @@
namespace App\Notifications\Ninja;
-use Illuminate\Bus\Queueable;
-use Illuminate\Contracts\Queue\ShouldQueue;
-use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Messages\SlackMessage;
use Illuminate\Notifications\Notification;
-use Illuminate\Queue\InteractsWithQueue;
-use Illuminate\Queue\SerializesModels;
-class RenewalFailureNotification extends Notification
+class RenewalFailureNotification extends Notification
{
-
/**
* Create a new notification instance.
*
* @return void
*/
- public function __construct(protected string $notification_message){}
+ public function __construct(protected string $notification_message)
+ {
+ }
/**
* Get the notification's delivery channels.
diff --git a/app/Notifications/Ninja/SpamNotification.php b/app/Notifications/Ninja/SpamNotification.php
index b1535c9a1831..27569488cde8 100644
--- a/app/Notifications/Ninja/SpamNotification.php
+++ b/app/Notifications/Ninja/SpamNotification.php
@@ -11,18 +11,12 @@
namespace App\Notifications\Ninja;
-use Illuminate\Bus\Queueable;
-use Illuminate\Contracts\Queue\ShouldQueue;
-use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Messages\SlackMessage;
use Illuminate\Notifications\Notification;
-use Illuminate\Queue\InteractsWithQueue;
-use Illuminate\Queue\SerializesModels;
-class SpamNotification extends Notification
+class SpamNotification extends Notification
{
-
/**
* Create a new notification instance.
*
@@ -77,38 +71,30 @@ class SpamNotification extends Notification
// foreach($this->spam_lists as $spam_list)
// {
- if(array_key_exists('companies', $this->spam_list))
- {
- $content .= " Companies \n";
+ if (array_key_exists('companies', $this->spam_list)) {
+ $content .= " Companies \n";
- foreach($this->spam_list['companies'] as $company)
- {
- $content .= "{$company['name']} - c_key={$company['company_key']} - a_key={$company['account_key']} - {$company['owner']} \n";
- }
+ foreach ($this->spam_list['companies'] as $company) {
+ $content .= "{$company['name']} - c_key={$company['company_key']} - a_key={$company['account_key']} - {$company['owner']} \n";
}
+ }
- if(array_key_exists('templates', $this->spam_list))
- {
- $content .= " Templates \n";
+ if (array_key_exists('templates', $this->spam_list)) {
+ $content .= " Templates \n";
- foreach($this->spam_list['templates'] as $company)
- {
- $content .= "{$company['name']} - c_key={$company['company_key']} - a_key={$company['account_key']} - {$company['owner']} \n";
- }
+ foreach ($this->spam_list['templates'] as $company) {
+ $content .= "{$company['name']} - c_key={$company['company_key']} - a_key={$company['account_key']} - {$company['owner']} \n";
}
+ }
- if(array_key_exists('users', $this->spam_list))
- {
-
- $content .= ' Users \n';
-
- foreach($this->spam_list['users'] as $user)
- {
- $content .= "{$user['email']} - a_key={$user['account_key']} - created={$user['created']} \n";
- }
+ if (array_key_exists('users', $this->spam_list)) {
+ $content .= ' Users \n';
+ foreach ($this->spam_list['users'] as $user) {
+ $content .= "{$user['email']} - a_key={$user['account_key']} - created={$user['created']} \n";
}
+ }
// }
diff --git a/app/Notifications/Ninja/UserQualityNotification.php b/app/Notifications/Ninja/UserQualityNotification.php
index ec079bb2c68a..385f1c0ca9c8 100644
--- a/app/Notifications/Ninja/UserQualityNotification.php
+++ b/app/Notifications/Ninja/UserQualityNotification.php
@@ -12,18 +12,12 @@
namespace App\Notifications\Ninja;
use App\Models\User;
-use Illuminate\Bus\Queueable;
-use Illuminate\Contracts\Queue\ShouldQueue;
-use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Messages\SlackMessage;
use Illuminate\Notifications\Notification;
-use Illuminate\Queue\InteractsWithQueue;
-use Illuminate\Queue\SerializesModels;
-class UserQualityNotification extends Notification
+class UserQualityNotification extends Notification
{
-
/**
* Create a new notification instance.
*
@@ -76,7 +70,6 @@ class UserQualityNotification extends Notification
public function toSlack($notifiable)
{
-
$content = "User Quality notification {$this->user->present()->name()} \n";
$content .= "Account: {$this->account_key }\n";
diff --git a/app/Notifications/Ninja/VerifyUser.php b/app/Notifications/Ninja/VerifyUser.php
index 9fd8f22444c1..c1311fba5d64 100644
--- a/app/Notifications/Ninja/VerifyUser.php
+++ b/app/Notifications/Ninja/VerifyUser.php
@@ -12,7 +12,6 @@
namespace App\Notifications\Ninja;
use Illuminate\Bus\Queueable;
-use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
diff --git a/app/Notifications/Ninja/WePayFailureNotification.php b/app/Notifications/Ninja/WePayFailureNotification.php
index b1951801e545..1cbf759d5a6f 100644
--- a/app/Notifications/Ninja/WePayFailureNotification.php
+++ b/app/Notifications/Ninja/WePayFailureNotification.php
@@ -11,14 +11,9 @@
namespace App\Notifications\Ninja;
-use Illuminate\Bus\Queueable;
-use Illuminate\Contracts\Queue\ShouldQueue;
-use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Messages\SlackMessage;
use Illuminate\Notifications\Notification;
-use Illuminate\Queue\InteractsWithQueue;
-use Illuminate\Queue\SerializesModels;
class WePayFailureNotification extends Notification
{
diff --git a/app/Observers/ClientContactObserver.php b/app/Observers/ClientContactObserver.php
index b570d2d1ea88..7f7fee3a98a9 100644
--- a/app/Observers/ClientContactObserver.php
+++ b/app/Observers/ClientContactObserver.php
@@ -58,33 +58,29 @@ class ClientContactObserver
//ensure entity state is preserved
- InvoiceInvitation::withTrashed()->where('client_contact_id', $client_contact_id)->cursor()->each(function ($invite){
-
- if($invite->invoice()->doesnthave('invitations'))
- $invite->invoice->service()->createInvitations();
-
+ InvoiceInvitation::withTrashed()->where('client_contact_id', $client_contact_id)->cursor()->each(function ($invite) {
+ if ($invite->invoice()->doesnthave('invitations')) {
+ $invite->invoice->service()->createInvitations();
+ }
});
- QuoteInvitation::withTrashed()->where('client_contact_id', $client_contact_id)->cursor()->each(function ($invite){
-
- if($invite->quote()->doesnthave('invitations'))
- $invite->quote->service()->createInvitations();
-
+ QuoteInvitation::withTrashed()->where('client_contact_id', $client_contact_id)->cursor()->each(function ($invite) {
+ if ($invite->quote()->doesnthave('invitations')) {
+ $invite->quote->service()->createInvitations();
+ }
});
- RecurringInvoiceInvitation::withTrashed()->where('client_contact_id', $client_contact_id)->cursor()->each(function ($invite){
-
- if($invite->recurring_invoice()->doesnthave('invitations'))
- $invite->recurring_invoice->service()->createInvitations();
-
+ RecurringInvoiceInvitation::withTrashed()->where('client_contact_id', $client_contact_id)->cursor()->each(function ($invite) {
+ if ($invite->recurring_invoice()->doesnthave('invitations')) {
+ $invite->recurring_invoice->service()->createInvitations();
+ }
});
- CreditInvitation::withTrashed()->where('client_contact_id', $client_contact_id)->cursor()->each(function ($invite){
-
- if($invite->credit()->doesnthave('invitations'))
- $invite->credit->service()->createInvitations();
-
+ CreditInvitation::withTrashed()->where('client_contact_id', $client_contact_id)->cursor()->each(function ($invite) {
+ if ($invite->credit()->doesnthave('invitations')) {
+ $invite->credit->service()->createInvitations();
+ }
});
}
diff --git a/app/Observers/ClientObserver.php b/app/Observers/ClientObserver.php
index de79d6c862e0..ed0a1e7c3310 100644
--- a/app/Observers/ClientObserver.php
+++ b/app/Observers/ClientObserver.php
@@ -31,9 +31,9 @@ class ClientObserver
->where('event_id', Webhook::EVENT_CREATE_CLIENT)
->exists();
- if ($subscriptions)
+ if ($subscriptions) {
WebhookHandler::dispatch(Webhook::EVENT_CREATE_CLIENT, $client, $client->company)->delay(0);
-
+ }
}
/**
@@ -44,24 +44,24 @@ class ClientObserver
*/
public function updated(Client $client)
{
-
$event = Webhook::EVENT_UPDATE_CLIENT;
- if($client->getOriginal('deleted_at') && !$client->deleted_at)
+ if ($client->getOriginal('deleted_at') && !$client->deleted_at) {
$event = Webhook::EVENT_RESTORE_CLIENT;
+ }
- if($client->is_deleted)
- $event = Webhook::EVENT_DELETE_CLIENT;
+ if ($client->is_deleted) {
+ $event = Webhook::EVENT_DELETE_CLIENT;
+ }
$subscriptions = Webhook::where('company_id', $client->company_id)
->where('event_id', $event)
->exists();
- if ($subscriptions)
+ if ($subscriptions) {
WebhookHandler::dispatch($event, $client, $client->company, 'client')->delay(0);
-
-
+ }
}
/**
@@ -72,16 +72,16 @@ class ClientObserver
*/
public function deleted(Client $client)
{
- if($client->is_deleted)
+ if ($client->is_deleted) {
return;
+ }
$subscriptions = Webhook::where('company_id', $client->company_id)
->where('event_id', Webhook::EVENT_ARCHIVE_CLIENT)
->exists();
- if ($subscriptions)
+ if ($subscriptions) {
WebhookHandler::dispatch(Webhook::EVENT_ARCHIVE_CLIENT, $client, $client->company)->delay(0);
-
+ }
}
-
}
diff --git a/app/Observers/CompanyGatewayObserver.php b/app/Observers/CompanyGatewayObserver.php
index 22e0c8e8fa96..bc40e9fb0232 100644
--- a/app/Observers/CompanyGatewayObserver.php
+++ b/app/Observers/CompanyGatewayObserver.php
@@ -15,7 +15,6 @@ class CompanyGatewayObserver
*/
public function created(CompanyGateway $company_gateway)
{
-
/* Set company gateway if not exists*/
if (! $company_gateway->label) {
$company_gateway->label = $company_gateway->gateway->name;
diff --git a/app/Observers/CreditObserver.php b/app/Observers/CreditObserver.php
index 43fc322fe4bd..d0bcb982d1be 100644
--- a/app/Observers/CreditObserver.php
+++ b/app/Observers/CreditObserver.php
@@ -11,7 +11,6 @@
namespace App\Observers;
-use App\Jobs\Util\UnlinkFile;
use App\Jobs\Util\WebhookHandler;
use App\Models\Client;
use App\Models\Credit;
@@ -19,7 +18,6 @@ use App\Models\Webhook;
class CreditObserver
{
-
public $afterCommit = true;
/**
@@ -49,19 +47,21 @@ class CreditObserver
{
$event = Webhook::EVENT_UPDATE_CREDIT;
- if($credit->getOriginal('deleted_at') && !$credit->deleted_at)
+ if ($credit->getOriginal('deleted_at') && !$credit->deleted_at) {
$event = Webhook::EVENT_RESTORE_CREDIT;
+ }
- if($credit->is_deleted)
- $event = Webhook::EVENT_DELETE_CREDIT;
+ if ($credit->is_deleted) {
+ $event = Webhook::EVENT_DELETE_CREDIT;
+ }
$subscriptions = Webhook::where('company_id', $credit->company_id)
->where('event_id', $event)
->exists();
- if ($subscriptions)
+ if ($subscriptions) {
WebhookHandler::dispatch($event, $credit, $credit->company)->delay(0);
-
+ }
}
/**
@@ -72,16 +72,17 @@ class CreditObserver
*/
public function deleted(Credit $credit)
{
- if($credit->is_deleted)
+ if ($credit->is_deleted) {
return;
+ }
$subscriptions = Webhook::where('company_id', $credit->company_id)
->where('event_id', Webhook::EVENT_ARCHIVE_CREDIT)
->exists();
- if ($subscriptions)
+ if ($subscriptions) {
WebhookHandler::dispatch(Webhook::EVENT_ARCHIVE_CREDIT, $credit, $credit->company)->delay(0);
-
+ }
}
/**
diff --git a/app/Observers/ExpenseObserver.php b/app/Observers/ExpenseObserver.php
index 84ec3e7d6cf9..c725f3edb5f3 100644
--- a/app/Observers/ExpenseObserver.php
+++ b/app/Observers/ExpenseObserver.php
@@ -31,9 +31,9 @@ class ExpenseObserver
->where('event_id', Webhook::EVENT_CREATE_EXPENSE)
->exists();
- if ($subscriptions)
+ if ($subscriptions) {
WebhookHandler::dispatch(Webhook::EVENT_CREATE_EXPENSE, $expense, $expense->company)->delay(0);
-
+ }
}
/**
@@ -46,20 +46,22 @@ class ExpenseObserver
{
$event = Webhook::EVENT_UPDATE_EXPENSE;
- if($expense->getOriginal('deleted_at') && !$expense->deleted_at)
+ if ($expense->getOriginal('deleted_at') && !$expense->deleted_at) {
$event = Webhook::EVENT_RESTORE_EXPENSE;
+ }
- if($expense->is_deleted)
- $event = Webhook::EVENT_DELETE_EXPENSE;
+ if ($expense->is_deleted) {
+ $event = Webhook::EVENT_DELETE_EXPENSE;
+ }
$subscriptions = Webhook::where('company_id', $expense->company_id)
->where('event_id', $event)
->exists();
- if ($subscriptions)
+ if ($subscriptions) {
WebhookHandler::dispatch($event, $expense, $expense->company)->delay(0);
-
+ }
}
/**
@@ -70,16 +72,17 @@ class ExpenseObserver
*/
public function deleted(Expense $expense)
{
- if($expense->is_deleted)
+ if ($expense->is_deleted) {
return;
+ }
$subscriptions = Webhook::where('company_id', $expense->company_id)
->where('event_id', Webhook::EVENT_ARCHIVE_EXPENSE)
->exists();
- if ($subscriptions)
+ if ($subscriptions) {
WebhookHandler::dispatch(Webhook::EVENT_ARCHIVE_EXPENSE, $expense, $expense->company)->delay(0);
-
+ }
}
/**
diff --git a/app/Observers/InvoiceObserver.php b/app/Observers/InvoiceObserver.php
index 2dc5431a6fc6..f78522e0a7d4 100644
--- a/app/Observers/InvoiceObserver.php
+++ b/app/Observers/InvoiceObserver.php
@@ -46,19 +46,22 @@ class InvoiceObserver
{
$event = Webhook::EVENT_UPDATE_INVOICE;
- if($invoice->getOriginal('deleted_at') && !$invoice->deleted_at)
+ if ($invoice->getOriginal('deleted_at') && !$invoice->deleted_at) {
$event = Webhook::EVENT_RESTORE_INVOICE;
+ }
- if($invoice->is_deleted)
- $event = Webhook::EVENT_DELETE_INVOICE;
+ if ($invoice->is_deleted) {
+ $event = Webhook::EVENT_DELETE_INVOICE;
+ }
$subscriptions = Webhook::where('company_id', $invoice->company->id)
->where('event_id', $event)
->exists();
- if ($subscriptions)
+ if ($subscriptions) {
WebhookHandler::dispatch($event, $invoice, $invoice->company, 'client')->delay(0);
+ }
}
/**
@@ -69,16 +72,17 @@ class InvoiceObserver
*/
public function deleted(Invoice $invoice)
{
- if($invoice->is_deleted)
+ if ($invoice->is_deleted) {
return;
+ }
$subscriptions = Webhook::where('company_id', $invoice->company_id)
->where('event_id', Webhook::EVENT_ARCHIVE_INVOICE)
->exists();
- if ($subscriptions)
+ if ($subscriptions) {
WebhookHandler::dispatch(Webhook::EVENT_ARCHIVE_INVOICE, $invoice, $invoice->company, 'client')->delay(0);
-
+ }
}
/**
diff --git a/app/Observers/PaymentObserver.php b/app/Observers/PaymentObserver.php
index 8b31dffdddad..b3c0f79fad41 100644
--- a/app/Observers/PaymentObserver.php
+++ b/app/Observers/PaymentObserver.php
@@ -17,7 +17,6 @@ use App\Models\Webhook;
class PaymentObserver
{
-
public $afterCommit = true;
/**
@@ -32,9 +31,9 @@ class PaymentObserver
->where('event_id', Webhook::EVENT_CREATE_PAYMENT)
->exists();
- if ($subscriptions)
+ if ($subscriptions) {
WebhookHandler::dispatch(Webhook::EVENT_CREATE_PAYMENT, $payment, $payment->company, 'invoices,client')->delay(20);
-
+ }
}
/**
@@ -47,19 +46,22 @@ class PaymentObserver
{
$event = Webhook::EVENT_UPDATE_PAYMENT;
- if($payment->getOriginal('deleted_at') && !$payment->deleted_at)
+ if ($payment->getOriginal('deleted_at') && !$payment->deleted_at) {
$event = Webhook::EVENT_RESTORE_PAYMENT;
+ }
- if($payment->is_deleted)
- $event = Webhook::EVENT_DELETE_PAYMENT;
+ if ($payment->is_deleted) {
+ $event = Webhook::EVENT_DELETE_PAYMENT;
+ }
$subscriptions = Webhook::where('company_id', $payment->company_id)
->where('event_id', $event)
->exists();
- if ($subscriptions)
+ if ($subscriptions) {
WebhookHandler::dispatch($event, $payment, $payment->company, 'invoices,client')->delay(25);
+ }
}
/**
@@ -70,8 +72,9 @@ class PaymentObserver
*/
public function deleted(Payment $payment)
{
- if($payment->is_deleted)
+ if ($payment->is_deleted) {
return;
+ }
$subscriptions = Webhook::where('company_id', $payment->company_id)
->where('event_id', Webhook::EVENT_ARCHIVE_PAYMENT)
diff --git a/app/Observers/ProductObserver.php b/app/Observers/ProductObserver.php
index 0ef5cac0d575..7e24377dc571 100644
--- a/app/Observers/ProductObserver.php
+++ b/app/Observers/ProductObserver.php
@@ -17,7 +17,6 @@ use App\Models\Webhook;
class ProductObserver
{
-
public $afterCommit = true;
/**
@@ -32,8 +31,9 @@ class ProductObserver
->where('event_id', Webhook::EVENT_CREATE_PRODUCT)
->exists();
- if ($subscriptions)
+ if ($subscriptions) {
WebhookHandler::dispatch(Webhook::EVENT_CREATE_PRODUCT, $product, $product->company)->delay(0);
+ }
}
/**
@@ -44,23 +44,24 @@ class ProductObserver
*/
public function updated(Product $product)
{
-
$event = Webhook::EVENT_UPDATE_PRODUCT;
- if($product->getOriginal('deleted_at') && !$product->deleted_at)
+ if ($product->getOriginal('deleted_at') && !$product->deleted_at) {
$event = Webhook::EVENT_RESTORE_PRODUCT;
+ }
- if($product->is_deleted)
- $event = Webhook::EVENT_DELETE_PRODUCT;
+ if ($product->is_deleted) {
+ $event = Webhook::EVENT_DELETE_PRODUCT;
+ }
$subscriptions = Webhook::where('company_id', $product->company_id)
->where('event_id', $event)
->exists();
- if ($subscriptions)
+ if ($subscriptions) {
WebhookHandler::dispatch($event, $product, $product->company)->delay(0);
-
+ }
}
/**
@@ -71,15 +72,17 @@ class ProductObserver
*/
public function deleted(Product $product)
{
- if($product->is_deleted)
+ if ($product->is_deleted) {
return;
+ }
$subscriptions = Webhook::where('company_id', $product->company_id)
->where('event_id', Webhook::EVENT_ARCHIVE_PRODUCT)
->exists();
- if ($subscriptions)
+ if ($subscriptions) {
WebhookHandler::dispatch(Webhook::EVENT_ARCHIVE_PRODUCT, $product, $product->company)->delay(0);
+ }
}
/**
diff --git a/app/Observers/ProjectObserver.php b/app/Observers/ProjectObserver.php
index 41f3028a8649..c6f169372831 100644
--- a/app/Observers/ProjectObserver.php
+++ b/app/Observers/ProjectObserver.php
@@ -31,9 +31,9 @@ class ProjectObserver
->where('event_id', Webhook::EVENT_PROJECT_CREATE)
->exists();
- if ($subscriptions)
+ if ($subscriptions) {
WebhookHandler::dispatch(Webhook::EVENT_PROJECT_CREATE, $project, $project->company, 'client')->delay(0);
-
+ }
}
/**
@@ -44,23 +44,24 @@ class ProjectObserver
*/
public function updated(Project $project)
{
-
$event = Webhook::EVENT_PROJECT_UPDATE;
- if($project->getOriginal('deleted_at') && !$project->deleted_at)
+ if ($project->getOriginal('deleted_at') && !$project->deleted_at) {
$event = Webhook::EVENT_RESTORE_PROJECT;
+ }
- if($project->is_deleted)
- $event = Webhook::EVENT_PROJECT_DELETE;
+ if ($project->is_deleted) {
+ $event = Webhook::EVENT_PROJECT_DELETE;
+ }
$subscriptions = Webhook::where('company_id', $project->company_id)
->where('event_id', $event)
->exists();
- if ($subscriptions)
+ if ($subscriptions) {
WebhookHandler::dispatch($event, $project, $project->company, 'client')->delay(0);
-
+ }
}
/**
@@ -71,16 +72,17 @@ class ProjectObserver
*/
public function deleted(Project $project)
{
- if($project->is_deleted)
+ if ($project->is_deleted) {
return;
+ }
$subscriptions = Webhook::where('company_id', $project->company_id)
->where('event_id', Webhook::EVENT_ARCHIVE_PROJECT)
->exists();
- if ($subscriptions)
+ if ($subscriptions) {
WebhookHandler::dispatch(Webhook::EVENT_ARCHIVE_PROJECT, $project, $project->company, 'client')->delay(0);
-
+ }
}
/**
diff --git a/app/Observers/PurchaseOrderObserver.php b/app/Observers/PurchaseOrderObserver.php
index b6675c0d74a5..a0cf35c28883 100644
--- a/app/Observers/PurchaseOrderObserver.php
+++ b/app/Observers/PurchaseOrderObserver.php
@@ -17,7 +17,6 @@ use App\Models\Webhook;
class PurchaseOrderObserver
{
-
public $afterCommit = true;
/**
@@ -28,14 +27,13 @@ class PurchaseOrderObserver
*/
public function created(PurchaseOrder $purchase_order)
{
-
$subscriptions = Webhook::where('company_id', $purchase_order->company_id)
->where('event_id', Webhook::EVENT_CREATE_PURCHASE_ORDER)
->exists();
- if ($subscriptions)
+ if ($subscriptions) {
WebhookHandler::dispatch(Webhook::EVENT_CREATE_PURCHASE_ORDER, $purchase_order, $purchase_order->company, 'vendor')->delay(0);
-
+ }
}
/**
@@ -46,23 +44,24 @@ class PurchaseOrderObserver
*/
public function updated(PurchaseOrder $purchase_order)
{
-
$event = Webhook::EVENT_UPDATE_PURCHASE_ORDER;
- if($purchase_order->getOriginal('deleted_at') && !$purchase_order->deleted_at)
+ if ($purchase_order->getOriginal('deleted_at') && !$purchase_order->deleted_at) {
$event = Webhook::EVENT_RESTORE_PURCHASE_ORDER;
+ }
- if($purchase_order->is_deleted)
- $event = Webhook::EVENT_DELETE_PURCHASE_ORDER;
+ if ($purchase_order->is_deleted) {
+ $event = Webhook::EVENT_DELETE_PURCHASE_ORDER;
+ }
$subscriptions = Webhook::where('company_id', $purchase_order->company_id)
->where('event_id', $event)
->exists();
- if ($subscriptions)
+ if ($subscriptions) {
WebhookHandler::dispatch($event, $purchase_order, $purchase_order->company, 'vendor')->delay(0);
-
+ }
}
/**
@@ -73,16 +72,17 @@ class PurchaseOrderObserver
*/
public function deleted(PurchaseOrder $purchase_order)
{
- if($purchase_order->is_deleted)
+ if ($purchase_order->is_deleted) {
return;
+ }
$subscriptions = Webhook::where('company_id', $purchase_order->company_id)
->where('event_id', Webhook::EVENT_ARCHIVE_PURCHASE_ORDER)
->exists();
- if ($subscriptions)
+ if ($subscriptions) {
WebhookHandler::dispatch(Webhook::EVENT_ARCHIVE_PURCHASE_ORDER, $purchase_order, $purchase_order->company, 'vendor')->delay(0);
-
+ }
}
/**
diff --git a/app/Observers/QuoteObserver.php b/app/Observers/QuoteObserver.php
index db2bdf67247b..1b12609f091a 100644
--- a/app/Observers/QuoteObserver.php
+++ b/app/Observers/QuoteObserver.php
@@ -17,7 +17,6 @@ use App\Models\Webhook;
class QuoteObserver
{
-
public $afterCommit = true;
/**
@@ -28,14 +27,13 @@ class QuoteObserver
*/
public function created(Quote $quote)
{
-
$subscriptions = Webhook::where('company_id', $quote->company_id)
->where('event_id', Webhook::EVENT_CREATE_QUOTE)
->exists();
- if ($subscriptions)
+ if ($subscriptions) {
WebhookHandler::dispatch(Webhook::EVENT_CREATE_QUOTE, $quote, $quote->company, 'client')->delay(0);
-
+ }
}
/**
@@ -46,23 +44,24 @@ class QuoteObserver
*/
public function updated(Quote $quote)
{
-
$event = Webhook::EVENT_UPDATE_QUOTE;
- if($quote->getOriginal('deleted_at') && !$quote->deleted_at)
+ if ($quote->getOriginal('deleted_at') && !$quote->deleted_at) {
$event = Webhook::EVENT_RESTORE_QUOTE;
+ }
- if($quote->is_deleted)
- $event = Webhook::EVENT_DELETE_QUOTE;
+ if ($quote->is_deleted) {
+ $event = Webhook::EVENT_DELETE_QUOTE;
+ }
$subscriptions = Webhook::where('company_id', $quote->company_id)
->where('event_id', $event)
->exists();
- if ($subscriptions)
+ if ($subscriptions) {
WebhookHandler::dispatch($event, $quote, $quote->company, 'client')->delay(0);
-
+ }
}
/**
@@ -73,16 +72,17 @@ class QuoteObserver
*/
public function deleted(Quote $quote)
{
- if($quote->is_deleted)
+ if ($quote->is_deleted) {
return;
+ }
$subscriptions = Webhook::where('company_id', $quote->company_id)
->where('event_id', Webhook::EVENT_ARCHIVE_QUOTE)
->exists();
- if ($subscriptions)
+ if ($subscriptions) {
WebhookHandler::dispatch(Webhook::EVENT_ARCHIVE_QUOTE, $quote, $quote->company, 'client')->delay(0);
-
+ }
}
/**
diff --git a/app/Observers/TaskObserver.php b/app/Observers/TaskObserver.php
index ff3e6d1a0260..3626fe9d0d6e 100644
--- a/app/Observers/TaskObserver.php
+++ b/app/Observers/TaskObserver.php
@@ -17,7 +17,6 @@ use App\Models\Webhook;
class TaskObserver
{
-
public $afterCommit = true;
/**
@@ -32,9 +31,9 @@ class TaskObserver
->where('event_id', Webhook::EVENT_CREATE_TASK)
->exists();
- if ($subscriptions)
+ if ($subscriptions) {
WebhookHandler::dispatch(Webhook::EVENT_CREATE_TASK, $task, $task->company)->delay(0);
-
+ }
}
/**
@@ -47,19 +46,22 @@ class TaskObserver
{
$event = Webhook::EVENT_UPDATE_TASK;
- if($task->getOriginal('deleted_at') && !$task->deleted_at)
+ if ($task->getOriginal('deleted_at') && !$task->deleted_at) {
$event = Webhook::EVENT_RESTORE_TASK;
+ }
- if($task->is_deleted)
- $event = Webhook::EVENT_DELETE_TASK;
+ if ($task->is_deleted) {
+ $event = Webhook::EVENT_DELETE_TASK;
+ }
$subscriptions = Webhook::where('company_id', $task->company_id)
->where('event_id', $event)
->exists();
- if ($subscriptions)
+ if ($subscriptions) {
WebhookHandler::dispatch($event, $task, $task->company)->delay(0);
+ }
}
/**
@@ -70,16 +72,17 @@ class TaskObserver
*/
public function deleted(Task $task)
{
- if($task->is_deleted)
+ if ($task->is_deleted) {
return;
+ }
$subscriptions = Webhook::where('company_id', $task->company_id)
->where('event_id', Webhook::EVENT_ARCHIVE_TASK)
->exists();
- if ($subscriptions)
+ if ($subscriptions) {
WebhookHandler::dispatch(Webhook::EVENT_ARCHIVE_TASK, $task, $task->company)->delay(0);
-
+ }
}
/**
diff --git a/app/Observers/UserObserver.php b/app/Observers/UserObserver.php
index 7efa008f74c8..003f027e7fd8 100644
--- a/app/Observers/UserObserver.php
+++ b/app/Observers/UserObserver.php
@@ -38,14 +38,12 @@ class UserObserver
*/
public function updated(User $user)
{
-
if (Ninja::isHosted() && $user->isDirty('email') && $user->company_users()->where('is_owner', true)->exists()) {
//ensure they are owner user and update email on file.
- if(class_exists(\Modules\Admin\Jobs\Account\UpdateOwnerUser::class))
+ if (class_exists(\Modules\Admin\Jobs\Account\UpdateOwnerUser::class)) {
\Modules\Admin\Jobs\Account\UpdateOwnerUser::dispatch($user->account->key, $user, $user->getOriginal('email'));
-
+ }
}
-
}
/**
diff --git a/app/Observers/VendorContactObserver.php b/app/Observers/VendorContactObserver.php
index a0065cac2bad..64677305b57d 100644
--- a/app/Observers/VendorContactObserver.php
+++ b/app/Observers/VendorContactObserver.php
@@ -46,19 +46,15 @@ class VendorContactObserver
*/
public function deleted(VendorContact $vendorContact)
{
-
$vendor_contact_id = $vendorContact->id;
$vendorContact->purchase_order_invitations()->delete();
- PurchaseOrderInvitation::withTrashed()->where('vendor_contact_id', $vendor_contact_id)->cursor()->each(function ($invite){
-
- if($invite->purchase_order()->doesnthave('invitations'))
- $invite->purchase_order->service()->createInvitations();
-
+ PurchaseOrderInvitation::withTrashed()->where('vendor_contact_id', $vendor_contact_id)->cursor()->each(function ($invite) {
+ if ($invite->purchase_order()->doesnthave('invitations')) {
+ $invite->purchase_order->service()->createInvitations();
+ }
});
-
-
}
/**
@@ -69,7 +65,6 @@ class VendorContactObserver
*/
public function restored(VendorContact $vendorContact)
{
-
}
/**
diff --git a/app/Observers/VendorObserver.php b/app/Observers/VendorObserver.php
index 4e280a4a64a3..801591526425 100644
--- a/app/Observers/VendorObserver.php
+++ b/app/Observers/VendorObserver.php
@@ -17,7 +17,6 @@ use App\Models\Webhook;
class VendorObserver
{
-
public $afterCommit = true;
/**
@@ -32,9 +31,9 @@ class VendorObserver
->where('event_id', Webhook::EVENT_CREATE_VENDOR)
->exists();
- if ($subscriptions)
+ if ($subscriptions) {
WebhookHandler::dispatch(Webhook::EVENT_CREATE_VENDOR, $vendor, $vendor->company)->delay(0);
-
+ }
}
/**
@@ -47,19 +46,22 @@ class VendorObserver
{
$event = Webhook::EVENT_UPDATE_VENDOR;
- if($vendor->getOriginal('deleted_at') && !$vendor->deleted_at)
+ if ($vendor->getOriginal('deleted_at') && !$vendor->deleted_at) {
$event = Webhook::EVENT_RESTORE_VENDOR;
+ }
- if($vendor->is_deleted)
- $event = Webhook::EVENT_DELETE_VENDOR;
+ if ($vendor->is_deleted) {
+ $event = Webhook::EVENT_DELETE_VENDOR;
+ }
$subscriptions = Webhook::where('company_id', $vendor->company_id)
->where('event_id', $event)
->exists();
- if ($subscriptions)
+ if ($subscriptions) {
WebhookHandler::dispatch($event, $vendor, $vendor->company)->delay(0);
+ }
}
/**
@@ -70,8 +72,9 @@ class VendorObserver
*/
public function deleted(Vendor $vendor)
{
- if($vendor->is_deleted)
+ if ($vendor->is_deleted) {
return;
+ }
$subscriptions = Webhook::where('company_id', $vendor->company_id)
->where('event_id', Webhook::EVENT_ARCHIVE_VENDOR)
@@ -103,5 +106,4 @@ class VendorObserver
{
//
}
-
}
diff --git a/app/PaymentDrivers/Authorize/AuthorizeCreateCustomer.php b/app/PaymentDrivers/Authorize/AuthorizeCreateCustomer.php
index c7e806e9df98..06e2162cf435 100644
--- a/app/PaymentDrivers/Authorize/AuthorizeCreateCustomer.php
+++ b/app/PaymentDrivers/Authorize/AuthorizeCreateCustomer.php
@@ -164,8 +164,3 @@ class AuthorizeCreateCustomer
// }
-
-
-
-
-
diff --git a/app/PaymentDrivers/Authorize/AuthorizeCreditCard.php b/app/PaymentDrivers/Authorize/AuthorizeCreditCard.php
index a15c12dfa0a8..c49a7831b64a 100644
--- a/app/PaymentDrivers/Authorize/AuthorizeCreditCard.php
+++ b/app/PaymentDrivers/Authorize/AuthorizeCreditCard.php
@@ -102,18 +102,18 @@ class AuthorizeCreditCard
}
// Delete a customer profile
- // $request = new DeleteCustomerProfileRequest();
- // $request->setMerchantAuthentication($this->authorize->merchant_authentication);
- // $request->setCustomerProfileId( $customer_profile_id );
+ // $request = new DeleteCustomerProfileRequest();
+ // $request->setMerchantAuthentication($this->authorize->merchant_authentication);
+ // $request->setCustomerProfileId( $customer_profile_id );
- // $controller = new DeleteCustomerProfileController($request);
- // $response = $controller->executeWithApiResponse($this->authorize->mode());
- // if (($response != null) && ($response->getMessages()->getResultCode() == "Ok") )
- // {
+ // $controller = new DeleteCustomerProfileController($request);
+ // $response = $controller->executeWithApiResponse($this->authorize->mode());
+ // if (($response != null) && ($response->getMessages()->getResultCode() == "Ok") )
+ // {
// nlog("SUCCESS: Delete Customer Payment Profile SUCCESS");
- // }
- // else
- // nlog("unable to delete profile {$customer_profile_id}");
+ // }
+ // else
+ // nlog("unable to delete profile {$customer_profile_id}");
}
private function processTokenPayment($request)
diff --git a/app/PaymentDrivers/Authorize/AuthorizeCustomer.php b/app/PaymentDrivers/Authorize/AuthorizeCustomer.php
index d7926da241bc..3e51b270db8e 100644
--- a/app/PaymentDrivers/Authorize/AuthorizeCustomer.php
+++ b/app/PaymentDrivers/Authorize/AuthorizeCustomer.php
@@ -12,7 +12,6 @@
namespace App\PaymentDrivers\Authorize;
-use App\Exceptions\GenericPaymentDriverFailure;
use App\Factory\ClientContactFactory;
use App\Factory\ClientFactory;
use App\Models\Client;
@@ -21,11 +20,8 @@ use App\Models\ClientGatewayToken;
use App\Models\GatewayType;
use App\PaymentDrivers\AuthorizePaymentDriver;
use Illuminate\Support\Facades\Cache;
-use net\authorize\api\contract\v1\CreateCustomerProfileRequest;
-use net\authorize\api\contract\v1\CustomerProfileType;
use net\authorize\api\contract\v1\GetCustomerProfileIdsRequest;
use net\authorize\api\contract\v1\GetCustomerProfileRequest;
-use net\authorize\api\controller\CreateCustomerProfileController;
use net\authorize\api\controller\GetCustomerProfileController;
use net\authorize\api\controller\GetCustomerProfileIdsController;
@@ -43,7 +39,6 @@ class AuthorizeCustomer
private function getCustomerProfileIds()
{
-
// Get all existing customer profile ID's
$request = new GetCustomerProfileIdsRequest();
$request->setMerchantAuthentication($this->authorize->merchant_authentication);
diff --git a/app/PaymentDrivers/AuthorizePaymentDriver.php b/app/PaymentDrivers/AuthorizePaymentDriver.php
index ab6e98f05f24..dcb37d597d22 100644
--- a/app/PaymentDrivers/AuthorizePaymentDriver.php
+++ b/app/PaymentDrivers/AuthorizePaymentDriver.php
@@ -66,7 +66,6 @@ class AuthorizePaymentDriver extends BaseDriver
public function getClientRequiredFields(): array
{
-
$data = [
['name' => 'client_name', 'label' => ctrans('texts.name'), 'type' => 'text', 'validation' => 'required|min:2'],
['name' => 'contact_email', 'label' => ctrans('texts.email'), 'type' => 'text', 'validation' => 'required|email:rfc'],
@@ -88,33 +87,24 @@ class AuthorizePaymentDriver extends BaseDriver
}
if ($this->company_gateway->require_custom_value1) {
-
$fields[] = ['name' => 'client_custom_value1', 'label' => $this->helpers->makeCustomField($this->client->company->custom_fields, 'client1'), 'type' => 'text', 'validation' => 'required'];
-
}
if ($this->company_gateway->require_custom_value2) {
-
$fields[] = ['name' => 'client_custom_value2', 'label' => $this->helpers->makeCustomField($this->client->company->custom_fields, 'client2'), 'type' => 'text', 'validation' => 'required'];
-
}
if ($this->company_gateway->require_custom_value3) {
-
$fields[] = ['name' => 'client_custom_value3', 'label' => $this->helpers->makeCustomField($this->client->company->custom_fields, 'client3'), 'type' => 'text', 'validation' => 'required'];
-
}
if ($this->company_gateway->require_custom_value4) {
-
$fields[] = ['name' => 'client_custom_value4', 'label' => $this->helpers->makeCustomField($this->client->company->custom_fields, 'client4'), 'type' => 'text', 'validation' => 'required'];
-
}
return array_merge($data, $fields);
-
}
public function authorizeView($payment_method)
diff --git a/app/PaymentDrivers/BaseDriver.php b/app/PaymentDrivers/BaseDriver.php
index af1ba7d446ee..8321961048ad 100644
--- a/app/PaymentDrivers/BaseDriver.php
+++ b/app/PaymentDrivers/BaseDriver.php
@@ -20,7 +20,6 @@ use App\Jobs\Mail\NinjaMailer;
use App\Jobs\Mail\NinjaMailerJob;
use App\Jobs\Mail\NinjaMailerObject;
use App\Jobs\Mail\PaymentFailedMailer;
-use App\Jobs\Ninja\TransactionLog;
use App\Jobs\Util\SystemLogger;
use App\Mail\Admin\ClientPaymentFailureObject;
use App\Models\Client;
@@ -31,16 +30,12 @@ use App\Models\GatewayType;
use App\Models\Invoice;
use App\Models\Payment;
use App\Models\PaymentHash;
-use App\Models\PaymentType;
use App\Models\SystemLog;
-use App\Models\TransactionEvent;
use App\Services\Subscription\SubscriptionService;
use App\Utils\Helpers;
use App\Utils\Ninja;
use App\Utils\Traits\MakesHash;
use App\Utils\Traits\SystemLogTrait;
-use Checkout\Library\Exceptions\CheckoutHttpException;
-use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;
@@ -150,33 +145,24 @@ class BaseDriver extends AbstractPaymentDriver
}
if ($this->company_gateway->require_custom_value1) {
-
$fields[] = ['name' => 'client_custom_value1', 'label' => $this->helpers->makeCustomField($this->client->company->custom_fields, 'client1'), 'type' => 'text', 'validation' => 'required'];
-
}
if ($this->company_gateway->require_custom_value2) {
-
$fields[] = ['name' => 'client_custom_value2', 'label' => $this->helpers->makeCustomField($this->client->company->custom_fields, 'client2'), 'type' => 'text', 'validation' => 'required'];
-
}
if ($this->company_gateway->require_custom_value3) {
-
$fields[] = ['name' => 'client_custom_value3', 'label' => $this->helpers->makeCustomField($this->client->company->custom_fields, 'client3'), 'type' => 'text', 'validation' => 'required'];
-
}
if ($this->company_gateway->require_custom_value4) {
-
$fields[] = ['name' => 'client_custom_value4', 'label' => $this->helpers->makeCustomField($this->client->company->custom_fields, 'client4'), 'type' => 'text', 'validation' => 'required'];
-
}
return $fields;
-
}
/**
@@ -369,11 +355,11 @@ class BaseDriver extends AbstractPaymentDriver
event(new PaymentWasCreated($payment, $payment->company, Ninja::eventVars()));
if (property_exists($this->payment_hash->data, 'billing_context') && $status == Payment::STATUS_COMPLETED) {
-
- if(is_int($this->payment_hash->data->billing_context->subscription_id))
+ if (is_int($this->payment_hash->data->billing_context->subscription_id)) {
$billing_subscription = \App\Models\Subscription::find($this->payment_hash->data->billing_context->subscription_id);
- else
+ } else {
$billing_subscription = \App\Models\Subscription::find($this->decodePrimaryKey($this->payment_hash->data->billing_context->subscription_id));
+ }
// To access campaign hash => $this->payment_hash->data->billing_context->campaign;
// To access campaign data => Cache::get(CAMPAIGN_HASH)
@@ -394,7 +380,6 @@ class BaseDriver extends AbstractPaymentDriver
*/
public function confirmGatewayFee() :void
{
-
/*Payment invoices*/
$payment_invoices = $this->payment_hash->invoices();
@@ -408,7 +393,6 @@ class BaseDriver extends AbstractPaymentDriver
if (collect($invoice->line_items)->contains('type_id', '3')) {
$invoice->service()->toggleFeesPaid()->save();
}
-
});
}
@@ -506,7 +490,7 @@ class BaseDriver extends AbstractPaymentDriver
public function sendFailureMail($error)
{
- if(is_object($error)){
+ if (is_object($error)) {
$error = 'Payment Aborted';
}
diff --git a/app/PaymentDrivers/Braintree/CreditCard.php b/app/PaymentDrivers/Braintree/CreditCard.php
index 22b5efe2385d..0dc9f8760002 100644
--- a/app/PaymentDrivers/Braintree/CreditCard.php
+++ b/app/PaymentDrivers/Braintree/CreditCard.php
@@ -230,7 +230,6 @@ class CreditCard
*/
private function processUnsuccessfulPayment($response)
{
-
$this->braintree->sendFailureMail($response?->transaction?->additionalProcessorResponse);
$message = [
diff --git a/app/PaymentDrivers/Braintree/PayPal.php b/app/PaymentDrivers/Braintree/PayPal.php
index 76b630d00fb1..fe95842bbc0c 100644
--- a/app/PaymentDrivers/Braintree/PayPal.php
+++ b/app/PaymentDrivers/Braintree/PayPal.php
@@ -111,10 +111,11 @@ class PayPal
'paymentMethodNonce' => $gateway_response->nonce,
]);
- if($payment_method->success)
+ if ($payment_method->success) {
return $payment_method->paymentMethod->token;
- else
+ } else {
throw new PaymentFailed(property_exists($payment_method, 'message') ? $payment_method->message : 'Undefined error storing payment token.', 0);
+ }
}
/**
diff --git a/app/PaymentDrivers/BraintreePaymentDriver.php b/app/PaymentDrivers/BraintreePaymentDriver.php
index 6f2101fbecfc..374f4cfc2b2c 100644
--- a/app/PaymentDrivers/BraintreePaymentDriver.php
+++ b/app/PaymentDrivers/BraintreePaymentDriver.php
@@ -126,17 +126,16 @@ class BraintreePaymentDriver extends BaseDriver
return $result->customer;
}
- //12-08-2022 catch when the customer is not created.
- $data = [
- 'transaction_reference' => null,
- 'transaction_response' => $result,
- 'success' => false,
- 'description' => 'Could not create customer',
- 'code' => 500,
- ];
-
- SystemLogger::dispatch(['server_response' => $result, 'data' => $data], SystemLog::CATEGORY_GATEWAY_RESPONSE, SystemLog::EVENT_GATEWAY_FAILURE, SystemLog::TYPE_BRAINTREE, $this->client, $this->client->company);
+ //12-08-2022 catch when the customer is not created.
+ $data = [
+ 'transaction_reference' => null,
+ 'transaction_response' => $result,
+ 'success' => false,
+ 'description' => 'Could not create customer',
+ 'code' => 500,
+ ];
+ SystemLogger::dispatch(['server_response' => $result, 'data' => $data], SystemLog::CATEGORY_GATEWAY_RESPONSE, SystemLog::EVENT_GATEWAY_FAILURE, SystemLog::TYPE_BRAINTREE, $this->client, $this->client->company);
}
public function refund(Payment $payment, $amount, $return_client_response = false)
@@ -272,7 +271,8 @@ class BraintreePaymentDriver extends BaseDriver
$this->init();
$webhookNotification = $this->gateway->webhookNotification()->parse(
- $request->input('bt_signature'), $request->input('bt_payload')
+ $request->input('bt_signature'),
+ $request->input('bt_payload')
);
nlog('braintree webhook');
diff --git a/app/PaymentDrivers/CheckoutCom/CreditCard.php b/app/PaymentDrivers/CheckoutCom/CreditCard.php
index ffd93680a863..6aefc0845180 100644
--- a/app/PaymentDrivers/CheckoutCom/CreditCard.php
+++ b/app/PaymentDrivers/CheckoutCom/CreditCard.php
@@ -17,7 +17,6 @@ use App\Http\Requests\ClientPortal\Payments\PaymentResponseRequest;
use App\Jobs\Util\SystemLogger;
use App\Models\ClientGatewayToken;
use App\Models\GatewayType;
-use App\Models\Payment;
use App\Models\SystemLog;
use App\PaymentDrivers\CheckoutComPaymentDriver;
use App\PaymentDrivers\Common\MethodInterface;
@@ -25,8 +24,6 @@ use App\Utils\Traits\MakesHash;
use Checkout\CheckoutApiException;
use Checkout\CheckoutArgumentException;
use Checkout\CheckoutAuthorizationException;
-use Checkout\Library\Exceptions\CheckoutHttpException;
-use Checkout\Models\Payments\IdSource;
use Checkout\Payments\Four\Request\PaymentRequest;
use Checkout\Payments\Four\Request\Source\RequestTokenSource;
use Checkout\Payments\PaymentRequest as PaymentsPaymentRequest;
@@ -128,7 +125,7 @@ class CreditCard implements MethodInterface
$http_status_code = $e->http_status_code ?: '';
$error_details = $e->error_details;
- if(is_array($error_details)) {
+ if (is_array($error_details)) {
$error_details = end($e->error_details['error_codes']);
}
@@ -137,13 +134,12 @@ class CreditCard implements MethodInterface
$human_exception = "{$human_exception} - Request ID: {$request_id}";
throw new PaymentFailed($human_exception, $http_status_code);
-
} catch (CheckoutArgumentException $e) {
// Bad arguments
$error_details = $e->error_details;
- if(is_array($error_details)) {
+ if (is_array($error_details)) {
$error_details = end($e->error_details['error_codes']);
}
@@ -155,7 +151,7 @@ class CreditCard implements MethodInterface
$error_details = $e->error_details;
- if(is_array($error_details)) {
+ if (is_array($error_details)) {
$error_details = end($e->error_details['error_codes']);
}
@@ -230,7 +226,7 @@ class CreditCard implements MethodInterface
private function completePayment($paymentRequest, PaymentResponseRequest $request)
{
$paymentRequest->amount = $this->checkout->payment_hash->data->value;
- $paymentRequest->reference = substr($this->checkout->getDescription(),0 , 49);
+ $paymentRequest->reference = substr($this->checkout->getDescription(), 0, 49);
$paymentRequest->customer = $this->checkout->getCustomer();
$paymentRequest->metadata = ['udf1' => 'Invoice Ninja'];
$paymentRequest->currency = $this->checkout->client->getCurrencyCode();
@@ -255,7 +251,6 @@ class CreditCard implements MethodInterface
}
try {
-
$response = $this->checkout->gateway->getPaymentsClient()->requestPayment($paymentRequest);
if ($response['status'] == 'Authorized') {
@@ -289,7 +284,7 @@ class CreditCard implements MethodInterface
$http_status_code = $e->http_status_code;
$error_details = $e->error_details;
- if(is_array($error_details)) {
+ if (is_array($error_details)) {
$error_details = end($e->error_details['error_codes']);
}
@@ -297,14 +292,14 @@ class CreditCard implements MethodInterface
$human_exception = $error_details ? new \Exception($error_details, 400) : $e;
- SystemLogger::dispatch(
- $human_exception->getMessage(),
- SystemLog::CATEGORY_GATEWAY_RESPONSE,
- SystemLog::EVENT_GATEWAY_ERROR,
- SystemLog::TYPE_CHECKOUT,
- $this->checkout->client,
- $this->checkout->client->company,
- );
+ SystemLogger::dispatch(
+ $human_exception->getMessage(),
+ SystemLog::CATEGORY_GATEWAY_RESPONSE,
+ SystemLog::EVENT_GATEWAY_ERROR,
+ SystemLog::TYPE_CHECKOUT,
+ $this->checkout->client,
+ $this->checkout->client->company,
+ );
return $this->checkout->processInternallyFailedPayment($this->checkout, $human_exception);
} catch (CheckoutArgumentException $e) {
@@ -312,7 +307,7 @@ class CreditCard implements MethodInterface
$error_details = $e->error_details;
- if(is_array($error_details)) {
+ if (is_array($error_details)) {
$error_details = end($e->error_details['error_codes']);
}
@@ -320,14 +315,14 @@ class CreditCard implements MethodInterface
$human_exception = $error_details ? new \Exception($error_details, 400) : $e;
- SystemLogger::dispatch(
- $human_exception->getMessage(),
- SystemLog::CATEGORY_GATEWAY_RESPONSE,
- SystemLog::EVENT_GATEWAY_ERROR,
- SystemLog::TYPE_CHECKOUT,
- $this->checkout->client,
- $this->checkout->client->company,
- );
+ SystemLogger::dispatch(
+ $human_exception->getMessage(),
+ SystemLog::CATEGORY_GATEWAY_RESPONSE,
+ SystemLog::EVENT_GATEWAY_ERROR,
+ SystemLog::TYPE_CHECKOUT,
+ $this->checkout->client,
+ $this->checkout->client->company,
+ );
return $this->checkout->processInternallyFailedPayment($this->checkout, $human_exception);
} catch (CheckoutAuthorizationException $e) {
@@ -335,7 +330,7 @@ class CreditCard implements MethodInterface
$error_details = $e->error_details;
- if(is_array($error_details)) {
+ if (is_array($error_details)) {
$error_details = end($e->error_details['error_codes']);
}
@@ -344,14 +339,14 @@ class CreditCard implements MethodInterface
$human_exception = $error_details ? new \Exception($error_details, 400) : $e;
- SystemLogger::dispatch(
- $human_exception->getMessage(),
- SystemLog::CATEGORY_GATEWAY_RESPONSE,
- SystemLog::EVENT_GATEWAY_ERROR,
- SystemLog::TYPE_CHECKOUT,
- $this->checkout->client,
- $this->checkout->client->company,
- );
+ SystemLogger::dispatch(
+ $human_exception->getMessage(),
+ SystemLog::CATEGORY_GATEWAY_RESPONSE,
+ SystemLog::EVENT_GATEWAY_ERROR,
+ SystemLog::TYPE_CHECKOUT,
+ $this->checkout->client,
+ $this->checkout->client->company,
+ );
return $this->checkout->processInternallyFailedPayment($this->checkout, $human_exception);
}
diff --git a/app/PaymentDrivers/CheckoutCom/Utilities.php b/app/PaymentDrivers/CheckoutCom/Utilities.php
index 121406289b20..764eb224c07e 100644
--- a/app/PaymentDrivers/CheckoutCom/Utilities.php
+++ b/app/PaymentDrivers/CheckoutCom/Utilities.php
@@ -15,9 +15,7 @@ namespace App\PaymentDrivers\CheckoutCom;
use App\Exceptions\PaymentFailed;
use App\Jobs\Util\SystemLogger;
use App\Models\GatewayType;
-use App\Models\PaymentType;
use App\Models\SystemLog;
-use Checkout\Models\Payments\Payment;
use Exception;
use stdClass;
@@ -84,7 +82,6 @@ trait Utilities
public function processUnsuccessfulPayment($_payment, $throw_exception = true)
{
-
$error_message = '';
nlog("checkout failure");
@@ -92,8 +89,7 @@ trait Utilities
if (is_array($_payment) && array_key_exists('status', $_payment)) {
$error_message = $_payment['status'];
- }
- else {
+ } else {
$error_message = 'Error processing payment.';
}
diff --git a/app/PaymentDrivers/CheckoutComPaymentDriver.php b/app/PaymentDrivers/CheckoutComPaymentDriver.php
index 74a33e8fc751..d9c2dab2d5c2 100644
--- a/app/PaymentDrivers/CheckoutComPaymentDriver.php
+++ b/app/PaymentDrivers/CheckoutComPaymentDriver.php
@@ -38,8 +38,6 @@ use Checkout\Common\Phone;
use Checkout\Customers\CustomerRequest;
use Checkout\Customers\Four\CustomerRequest as FourCustomerRequest;
use Checkout\Environment;
-use Checkout\Library\Exceptions\CheckoutHttpException;
-use Checkout\Models\Payments\IdSource;
use Checkout\Models\Payments\Refund;
use Checkout\Payments\Four\Request\PaymentRequest;
use Checkout\Payments\Four\Request\Source\RequestIdSource as SourceRequestIdSource;
@@ -214,7 +212,6 @@ class CheckoutComPaymentDriver extends BaseDriver
} catch (CheckoutApiException $e) {
// API error
throw new PaymentFailed($e->getMessage(), $e->getCode());
-
} catch (CheckoutArgumentException $e) {
// Bad arguments
@@ -248,73 +245,69 @@ class CheckoutComPaymentDriver extends BaseDriver
$response = $this->gateway->getCustomersClient()->get($this->client->present()->email());
return $response;
-
} catch (\Exception $e) {
-
if ($this->is_four_api) {
$request = new FourCustomerRequest();
- }
- else{
+ } else {
$request = new CustomerRequest();
}
- $phone = new Phone();
- // $phone->number = $this->client->present()->phone();
- $phone->number = substr(str_pad($this->client->present()->phone(),6, "0", STR_PAD_RIGHT), 0 , 24);
+ $phone = new Phone();
+ // $phone->number = $this->client->present()->phone();
+ $phone->number = substr(str_pad($this->client->present()->phone(), 6, "0", STR_PAD_RIGHT), 0, 24);
- $request->email = $this->client->present()->email();
- $request->name = $this->client->present()->name();
- $request->phone = $phone;
+ $request->email = $this->client->present()->email();
+ $request->name = $this->client->present()->name();
+ $request->phone = $phone;
- try {
- $response = $this->gateway->getCustomersClient()->create($request);
- }
- catch (CheckoutApiException $e) {
- // API error
- $request_id = $e->request_id;
- $http_status_code = $e->http_status_code;
- $error_details = $e->error_details;
+ try {
+ $response = $this->gateway->getCustomersClient()->create($request);
+ } catch (CheckoutApiException $e) {
+ // API error
+ $request_id = $e->request_id;
+ $http_status_code = $e->http_status_code;
+ $error_details = $e->error_details;
- if(is_array($error_details)) {
- $error_details = end($e->error_details['error_codes']);
- }
-
- $human_exception = $error_details ? new \Exception($error_details, 400) : $e;
-
-
- throw new PaymentFailed($human_exception);
- } catch (CheckoutArgumentException $e) {
- // Bad arguments
-
- $error_details = $e->error_details;
-
- if(is_array($error_details)) {
- $error_details = end($e->error_details['error_codes']);
- }
-
- $human_exception = $error_details ? new \Exception($error_details, 400) : $e;
-
- throw new PaymentFailed($human_exception);
- } catch (CheckoutAuthorizationException $e) {
- // Bad Invalid authorization
-
- $error_details = $e->error_details;
-
- if(is_array($error_details)) {
- $error_details = end($e->error_details['error_codes']);
- }
-
- $human_exception = $error_details ? new \Exception($error_details, 400) : $e;
-
- throw new PaymentFailed($human_exception);
+ if (is_array($error_details)) {
+ $error_details = end($e->error_details['error_codes']);
}
+ $human_exception = $error_details ? new \Exception($error_details, 400) : $e;
- // catch (\Exception $e) {
+ throw new PaymentFailed($human_exception);
+ } catch (CheckoutArgumentException $e) {
+ // Bad arguments
+
+ $error_details = $e->error_details;
+
+ if (is_array($error_details)) {
+ $error_details = end($e->error_details['error_codes']);
+ }
+
+ $human_exception = $error_details ? new \Exception($error_details, 400) : $e;
+
+ throw new PaymentFailed($human_exception);
+ } catch (CheckoutAuthorizationException $e) {
+ // Bad Invalid authorization
+
+ $error_details = $e->error_details;
+
+ if (is_array($error_details)) {
+ $error_details = end($e->error_details['error_codes']);
+ }
+
+ $human_exception = $error_details ? new \Exception($error_details, 400) : $e;
+
+ throw new PaymentFailed($human_exception);
+ }
+
+
+
+ // catch (\Exception $e) {
// // API error
// throw new PaymentFailed($e->getMessage(), $e->getCode());
- // }
+ // }
return $response;
}
@@ -408,8 +401,9 @@ class CheckoutComPaymentDriver extends BaseDriver
$error_details = '';
- if(property_exists($e, 'error_details'))
+ if (property_exists($e, 'error_details')) {
$error_details = $e->error_details;
+ }
$data = [
'status' => $e->error_details,
@@ -439,7 +433,6 @@ class CheckoutComPaymentDriver extends BaseDriver
public function process3dsConfirmation(Checkout3dsRequest $request)
{
-
$this->init();
$this->setPaymentHash($request->getPaymentHash());
diff --git a/app/PaymentDrivers/CustomPaymentDriver.php b/app/PaymentDrivers/CustomPaymentDriver.php
index 6a95a6f05643..6cc437e53494 100644
--- a/app/PaymentDrivers/CustomPaymentDriver.php
+++ b/app/PaymentDrivers/CustomPaymentDriver.php
@@ -17,7 +17,6 @@ use App\Models\GatewayType;
use App\Models\Invoice;
use App\Models\Payment;
use App\Utils\HtmlEngine;
-use App\Utils\Number;
use App\Utils\Traits\MakesHash;
/**
diff --git a/app/PaymentDrivers/Eway/CreditCard.php b/app/PaymentDrivers/Eway/CreditCard.php
index 9c9690aafc90..f93057719b34 100644
--- a/app/PaymentDrivers/Eway/CreditCard.php
+++ b/app/PaymentDrivers/Eway/CreditCard.php
@@ -14,18 +14,11 @@ namespace App\PaymentDrivers\Eway;
use App\Exceptions\PaymentFailed;
use App\Jobs\Util\SystemLogger;
-use App\Models\ClientGatewayToken;
use App\Models\GatewayType;
-use App\Models\Payment;
-use App\Models\PaymentHash;
use App\Models\PaymentType;
use App\Models\SystemLog;
-use App\PaymentDrivers\Eway\ErrorCode;
use App\PaymentDrivers\EwayPaymentDriver;
use App\Utils\Traits\MakesHash;
-use Illuminate\Http\Request;
-use Illuminate\Support\Facades\Cache;
-use Illuminate\Support\Str;
class CreditCard
{
diff --git a/app/PaymentDrivers/Eway/Token.php b/app/PaymentDrivers/Eway/Token.php
index 7207ef13fa97..8deaf344bee0 100644
--- a/app/PaymentDrivers/Eway/Token.php
+++ b/app/PaymentDrivers/Eway/Token.php
@@ -12,20 +12,12 @@
namespace App\PaymentDrivers\Eway;
-use App\Exceptions\PaymentFailed;
-use App\Jobs\Util\SystemLogger;
use App\Models\ClientGatewayToken;
use App\Models\GatewayType;
-use App\Models\Payment;
use App\Models\PaymentHash;
use App\Models\PaymentType;
-use App\Models\SystemLog;
-use App\PaymentDrivers\Eway\ErrorCode;
use App\PaymentDrivers\EwayPaymentDriver;
use App\Utils\Traits\MakesHash;
-use Illuminate\Http\Request;
-use Illuminate\Support\Facades\Cache;
-use Illuminate\Support\Str;
class Token
{
diff --git a/app/PaymentDrivers/EwayPaymentDriver.php b/app/PaymentDrivers/EwayPaymentDriver.php
index 1db813f41120..3e7dca733f8b 100644
--- a/app/PaymentDrivers/EwayPaymentDriver.php
+++ b/app/PaymentDrivers/EwayPaymentDriver.php
@@ -192,28 +192,20 @@ class EwayPaymentDriver extends BaseDriver
}
if ($this->company_gateway->require_custom_value1) {
-
$fields[] = ['name' => 'client_custom_value1', 'label' => $this->helpers->makeCustomField($this->client->company->custom_fields, 'client1'), 'type' => 'text', 'validation' => 'required'];
-
}
if ($this->company_gateway->require_custom_value2) {
-
$fields[] = ['name' => 'client_custom_value2', 'label' => $this->helpers->makeCustomField($this->client->company->custom_fields, 'client2'), 'type' => 'text', 'validation' => 'required'];
-
}
if ($this->company_gateway->require_custom_value3) {
-
$fields[] = ['name' => 'client_custom_value3', 'label' => $this->helpers->makeCustomField($this->client->company->custom_fields, 'client3'), 'type' => 'text', 'validation' => 'required'];
-
}
if ($this->company_gateway->require_custom_value4) {
-
$fields[] = ['name' => 'client_custom_value4', 'label' => $this->helpers->makeCustomField($this->client->company->custom_fields, 'client4'), 'type' => 'text', 'validation' => 'required'];
-
}
diff --git a/app/PaymentDrivers/Forte/ACH.php b/app/PaymentDrivers/Forte/ACH.php
index 21c30530250e..87ad4d3d1013 100644
--- a/app/PaymentDrivers/Forte/ACH.php
+++ b/app/PaymentDrivers/Forte/ACH.php
@@ -12,16 +12,16 @@
namespace App\PaymentDrivers\Forte;
-use App\Models\Payment;
+use App\Http\Requests\Request;
+use App\Jobs\Util\SystemLogger;
use App\Models\GatewayType;
+use App\Models\Payment;
use App\Models\PaymentHash;
use App\Models\PaymentType;
-use App\Http\Requests\Request;
+use App\Models\SystemLog;
+use App\PaymentDrivers\FortePaymentDriver;
use App\Utils\Traits\MakesHash;
use Illuminate\Support\Facades\Validator;
-use App\PaymentDrivers\FortePaymentDriver;
-use App\Jobs\Util\SystemLogger;
-use App\Models\SystemLog;
class ACH
{
@@ -41,7 +41,7 @@ class ACH
$this->forte = $forte;
$this->forte_base_uri = "https://sandbox.forte.net/api/v3/";
- if($this->forte->company_gateway->getConfigField('testMode') == false){
+ if ($this->forte->company_gateway->getConfigField('testMode') == false) {
$this->forte_base_uri = "https://api.forte.net/v3/";
}
$this->forte_api_access_id = $this->forte->company_gateway->getConfigField('apiAccessId');
@@ -60,7 +60,6 @@ class ACH
public function authorizeResponse(Request $request)
{
-
$payment_meta = new \stdClass;
$payment_meta->brand = (string)ctrans('texts.ach');
$payment_meta->last4 = (string) $request->last_4;
@@ -93,7 +92,7 @@ class ACH
try {
$curl = curl_init();
- curl_setopt_array($curl, array(
+ curl_setopt_array($curl, [
CURLOPT_URL => $this->forte_base_uri.'organizations/'.$this->forte_organization_id.'/locations/'.$this->forte_location_id.'/transactions',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
@@ -116,13 +115,13 @@ class ACH
"one_time_token":"'.$request->payment_token.'"
}
}',
- CURLOPT_HTTPHEADER => array(
+ CURLOPT_HTTPHEADER => [
'X-Forte-Auth-Organization-Id: '.$this->forte_organization_id,
'Content-Type: application/json',
'Authorization: Basic '.base64_encode($this->forte_api_access_id.':'.$this->forte_secure_key),
'Cookie: visid_incap_621087=u18+3REYR/iISgzZxOF5s2ODW2IAAAAAQUIPAAAAAADuGqKgECQLS81FcSDrmhGe; nlbi_621087=YHngadhJ2VU+yr7/R1efXgAAAAD3mQyhqmnLls8PRu4iN58G; incap_ses_1136_621087=CVdrXUdhIlm9WJNDieLDD4QVXGIAAAAAvBwvkUcwhM0+OwvdPm2stg=='
- ),
- ));
+ ],
+ ]);
$response = curl_exec($curl);
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
diff --git a/app/PaymentDrivers/Forte/CreditCard.php b/app/PaymentDrivers/Forte/CreditCard.php
index 2b851a88b7fb..c4a893a4fb02 100644
--- a/app/PaymentDrivers/Forte/CreditCard.php
+++ b/app/PaymentDrivers/Forte/CreditCard.php
@@ -12,17 +12,16 @@
namespace App\PaymentDrivers\Forte;
-use App\Models\Payment;
-use App\Models\GatewayType;
-use App\Models\PaymentHash;
-use App\Models\PaymentType;
-use App\Utils\Traits\MakesHash;
-use Illuminate\Support\Facades\Session;
-use Illuminate\Support\Facades\Validator;
-use App\PaymentDrivers\FortePaymentDriver;
use App\Http\Requests\ClientPortal\Payments\PaymentResponseRequest;
use App\Jobs\Util\SystemLogger;
+use App\Models\GatewayType;
+use App\Models\Payment;
+use App\Models\PaymentHash;
+use App\Models\PaymentType;
use App\Models\SystemLog;
+use App\PaymentDrivers\FortePaymentDriver;
+use App\Utils\Traits\MakesHash;
+use Illuminate\Support\Facades\Validator;
class CreditCard
{
@@ -42,9 +41,9 @@ class CreditCard
$this->forte = $forte;
$this->forte_base_uri = "https://sandbox.forte.net/api/v3/";
- if($this->forte->company_gateway->getConfigField('testMode') == false){
- $this->forte_base_uri = "https://api.forte.net/v3/";
- }
+ if ($this->forte->company_gateway->getConfigField('testMode') == false) {
+ $this->forte_base_uri = "https://api.forte.net/v3/";
+ }
$this->forte_api_access_id = $this->forte->company_gateway->getConfigField('apiAccessId');
$this->forte_secure_key = $this->forte->company_gateway->getConfigField('secureKey');
$this->forte_auth_organization_id = $this->forte->company_gateway->getConfigField('authOrganizationId');
@@ -96,15 +95,14 @@ class CreditCard
$fees_and_limits = $this->forte->company_gateway->getFeesAndLimits(GatewayType::CREDIT_CARD);
- if(property_exists($fees_and_limits, 'fee_percent') && $fees_and_limits->fee_percent > 0)
- {
+ if (property_exists($fees_and_limits, 'fee_percent') && $fees_and_limits->fee_percent > 0) {
$fee_total = 0;
- for ($i = ($invoice_totals * 100) ; $i < ($amount_with_fee * 100); $i++) {
- $calculated_fee = ( 3 * $i) / 100;
- $calculated_amount_with_fee = round(($i + $calculated_fee) / 100,2);
+ for ($i = ($invoice_totals * 100) ; $i < ($amount_with_fee * 100); $i++) {
+ $calculated_fee = (3 * $i) / 100;
+ $calculated_amount_with_fee = round(($i + $calculated_fee) / 100, 2);
if ($calculated_amount_with_fee == $amount_with_fee) {
- $fee_total = round($calculated_fee / 100,2);
+ $fee_total = round($calculated_fee / 100, 2);
$amount_with_fee = $calculated_amount_with_fee;
break;
}
@@ -114,7 +112,7 @@ class CreditCard
try {
$curl = curl_init();
- curl_setopt_array($curl, array(
+ curl_setopt_array($curl, [
CURLOPT_URL => $this->forte_base_uri.'organizations/'.$this->forte_organization_id.'/locations/'.$this->forte_location_id.'/transactions',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
@@ -135,12 +133,12 @@ class CreditCard
"one_time_token":"'.$request->payment_token.'"
}
}',
- CURLOPT_HTTPHEADER => array(
+ CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'X-Forte-Auth-Organization-Id: '.$this->forte_organization_id,
'Authorization: Basic '.base64_encode($this->forte_api_access_id.':'.$this->forte_secure_key)
- ),
- ));
+ ],
+ ]);
$response = curl_exec($curl);
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
diff --git a/app/PaymentDrivers/FortePaymentDriver.php b/app/PaymentDrivers/FortePaymentDriver.php
index c867a09198c8..0622f33c9b6b 100644
--- a/app/PaymentDrivers/FortePaymentDriver.php
+++ b/app/PaymentDrivers/FortePaymentDriver.php
@@ -11,13 +11,13 @@
namespace App\PaymentDrivers;
-use App\Models\Payment;
use App\Jobs\Util\SystemLogger;
-use App\Models\SystemLog;
use App\Models\GatewayType;
-use App\Utils\Traits\MakesHash;
+use App\Models\Payment;
+use App\Models\SystemLog;
use App\PaymentDrivers\Forte\ACH;
use App\PaymentDrivers\Forte\CreditCard;
+use App\Utils\Traits\MakesHash;
class FortePaymentDriver extends BaseDriver
{
@@ -45,8 +45,8 @@ class FortePaymentDriver extends BaseDriver
{
$types = [];
- $types[] = GatewayType::CREDIT_CARD;
- $types[] = GatewayType::BANK_TRANSFER;
+ $types[] = GatewayType::CREDIT_CARD;
+ $types[] = GatewayType::BANK_TRANSFER;
return $types;
}
@@ -83,9 +83,9 @@ class FortePaymentDriver extends BaseDriver
public function refund(Payment $payment, $amount, $return_client_response = false)
{
$forte_base_uri = "https://sandbox.forte.net/api/v3/";
- if($this->company_gateway->getConfigField('testMode') == false){
- $forte_base_uri = "https://api.forte.net/v3/";
- }
+ if ($this->company_gateway->getConfigField('testMode') == false) {
+ $forte_base_uri = "https://api.forte.net/v3/";
+ }
$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');
@@ -95,7 +95,7 @@ class FortePaymentDriver extends BaseDriver
try {
$curl = curl_init();
- curl_setopt_array($curl, array(
+ curl_setopt_array($curl, [
CURLOPT_URL => $forte_base_uri.'organizations/'.$forte_organization_id.'/locations/'.$forte_location_id.'/transactions',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
@@ -110,12 +110,12 @@ class FortePaymentDriver extends BaseDriver
"original_transaction_id":"'.$payment->transaction_reference.'",
"authorization_code": "9ZQ754"
}',
- CURLOPT_HTTPHEADER => array(
+ CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'X-Forte-Auth-Organization-Id: '.$forte_organization_id,
'Authorization: Basic '.base64_encode($forte_api_access_id.':'.$forte_secure_key)
- ),
- ));
+ ],
+ ]);
$response = curl_exec($curl);
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
@@ -123,7 +123,6 @@ class FortePaymentDriver extends BaseDriver
curl_close($curl);
$response=json_decode($response);
-
} catch (\Throwable $th) {
$message = [
'action' => 'error',
diff --git a/app/PaymentDrivers/GoCardless/ACH.php b/app/PaymentDrivers/GoCardless/ACH.php
index ad9838d0c3cb..f84b319e9199 100644
--- a/app/PaymentDrivers/GoCardless/ACH.php
+++ b/app/PaymentDrivers/GoCardless/ACH.php
@@ -15,7 +15,6 @@ namespace App\PaymentDrivers\GoCardless;
use App\Exceptions\PaymentFailed;
use App\Http\Requests\ClientPortal\Payments\PaymentResponseRequest;
use App\Jobs\Util\SystemLogger;
-use App\Models\ClientGatewayToken;
use App\Models\GatewayType;
use App\Models\Invoice;
use App\Models\Payment;
diff --git a/app/PaymentDrivers/GoCardless/DirectDebit.php b/app/PaymentDrivers/GoCardless/DirectDebit.php
index 382fda70c872..edb853ba3d85 100644
--- a/app/PaymentDrivers/GoCardless/DirectDebit.php
+++ b/app/PaymentDrivers/GoCardless/DirectDebit.php
@@ -16,7 +16,6 @@ use App\Exceptions\PaymentFailed;
use App\Http\Requests\ClientPortal\Payments\PaymentResponseRequest;
use App\Jobs\Mail\PaymentFailureMailer;
use App\Jobs\Util\SystemLogger;
-use App\Models\ClientGatewayToken;
use App\Models\GatewayType;
use App\Models\Invoice;
use App\Models\Payment;
diff --git a/app/PaymentDrivers/GoCardless/SEPA.php b/app/PaymentDrivers/GoCardless/SEPA.php
index ee0e2a264c6f..df92a500b3a6 100644
--- a/app/PaymentDrivers/GoCardless/SEPA.php
+++ b/app/PaymentDrivers/GoCardless/SEPA.php
@@ -15,7 +15,6 @@ namespace App\PaymentDrivers\GoCardless;
use App\Exceptions\PaymentFailed;
use App\Http\Requests\ClientPortal\Payments\PaymentResponseRequest;
use App\Jobs\Util\SystemLogger;
-use App\Models\ClientGatewayToken;
use App\Models\GatewayType;
use App\Models\Invoice;
use App\Models\Payment;
diff --git a/app/PaymentDrivers/GoCardlessPaymentDriver.php b/app/PaymentDrivers/GoCardlessPaymentDriver.php
index 2b57a6578f1e..a1f6f49ee709 100644
--- a/app/PaymentDrivers/GoCardlessPaymentDriver.php
+++ b/app/PaymentDrivers/GoCardlessPaymentDriver.php
@@ -11,7 +11,6 @@
namespace App\PaymentDrivers;
-use App\Events\Payment\PaymentFailed;
use App\Http\Requests\Payments\PaymentWebhookRequest;
use App\Jobs\Util\SystemLogger;
use App\Models\ClientGatewayToken;
@@ -282,11 +281,10 @@ class GoCardlessPaymentDriver extends BaseDriver
//after i resolve the payment hash, ensure the invoice has not been marked as paid and the payment does not already exist.
//if it does exist, ensure it is completed and not pending.
- if($event['action'] == 'fulfilled' && array_key_exists('billing_request', $event['links'])) {
-
+ if ($event['action'] == 'fulfilled' && array_key_exists('billing_request', $event['links'])) {
$hash = PaymentHash::whereJsonContains('data->billing_request', $event['links']['billing_request'])->first();
- if(!$hash){
+ if (!$hash) {
nlog("GoCardless: couldn't find a hash, need to abort => Billing Request => " . $event['links']['billing_request']);
return response()->json([], 200);
}
@@ -302,40 +300,34 @@ class GoCardlessPaymentDriver extends BaseDriver
);
if ($billing_request->status === 'fulfilled') {
-
$invoices = Invoice::whereIn('id', $this->transformKeys(array_column($hash->invoices(), 'invoice_id')))->withTrashed()->get();
$this->client = $invoices->first()->client;
- $invoices->each(function ($invoice){
-
+ $invoices->each(function ($invoice) {
//if payments exist already, they just need to be confirmed.
- if($invoice->payments()->exists()){
-
- $invoice->payments()->where('status_id', 1)->cursor()->each(function ($payment){
+ if ($invoice->payments()->exists()) {
+ $invoice->payments()->where('status_id', 1)->cursor()->each(function ($payment) {
$payment->status_id = 4;
$payment->save();
});
-
}
});
// remove all paid invoices
- $invoices->filter(function ($invoice){
+ $invoices->filter(function ($invoice) {
return $invoice->isPayable();
});
//return early if nothing to do
- if($invoices->count() == 0){
+ if ($invoices->count() == 0) {
nlog("GoCardless: Could not harvest any invoices - probably all paid!!");
return response()->json([], 200);
}
$this->processSuccessfulPayment($payment);
}
-
}
-
}
return response()->json([], 200);
@@ -364,7 +356,6 @@ class GoCardlessPaymentDriver extends BaseDriver
$this->client,
$this->client->company,
);
-
}
diff --git a/app/PaymentDrivers/Mollie/CreditCard.php b/app/PaymentDrivers/Mollie/CreditCard.php
index 4049750d7801..252ca0356d5a 100644
--- a/app/PaymentDrivers/Mollie/CreditCard.php
+++ b/app/PaymentDrivers/Mollie/CreditCard.php
@@ -72,7 +72,7 @@ class CreditCard
'sequenceType' => 'recurring',
'description' => $description,
'webhookUrl' => $this->mollie->company_gateway->webhookUrl(),
- 'idempotencyKey' => uniqid("st",true),
+ 'idempotencyKey' => uniqid("st", true),
'metadata' => [
'client_id' => $this->mollie->client->hashed_id,
'hash' => $this->mollie->payment_hash->hash,
@@ -93,11 +93,11 @@ class CreditCard
if ($payment->status === 'open') {
$this->mollie->payment_hash->withData('payment_id', $payment->id);
- if(!$payment->getCheckoutUrl())
+ if (!$payment->getCheckoutUrl()) {
return render('gateways.mollie.mollie_placeholder');
- else
+ } else {
return redirect()->away($payment->getCheckoutUrl());
-
+ }
}
} catch (\Exception $e) {
return $this->processUnsuccessfulPayment($e);
@@ -111,7 +111,7 @@ class CreditCard
'value' => $amount,
],
'description' => $description,
- 'idempotencyKey' => uniqid("st",true),
+ 'idempotencyKey' => uniqid("st", true),
'redirectUrl' => route('mollie.3ds_redirect', [
'company_key' => $this->mollie->client->company->company_key,
'company_gateway_id' => $this->mollie->company_gateway->hashed_id,
@@ -161,10 +161,11 @@ class CreditCard
nlog("Mollie");
nlog($payment);
- if(!$payment->getCheckoutUrl())
+ if (!$payment->getCheckoutUrl()) {
return render('gateways.mollie.mollie_placeholder');
- else
+ } else {
return redirect()->away($payment->getCheckoutUrl());
+ }
}
} catch (\Exception $e) {
$this->processUnsuccessfulPayment($e);
diff --git a/app/PaymentDrivers/MolliePaymentDriver.php b/app/PaymentDrivers/MolliePaymentDriver.php
index 51835b17c2d6..4572fb06711e 100644
--- a/app/PaymentDrivers/MolliePaymentDriver.php
+++ b/app/PaymentDrivers/MolliePaymentDriver.php
@@ -321,7 +321,6 @@ class MolliePaymentDriver extends BaseDriver
// record from the meta data in the payment hash.
if ($payment && property_exists($payment->metadata, 'hash') && $payment->metadata->hash) {
-
/* Harvest Payment Hash*/
$payment_hash = PaymentHash::where('hash', $payment->metadata->hash)->first();
diff --git a/app/PaymentDrivers/PayFast/CreditCard.php b/app/PaymentDrivers/PayFast/CreditCard.php
index 0125d5ffb1b1..393de3b9c697 100644
--- a/app/PaymentDrivers/PayFast/CreditCard.php
+++ b/app/PaymentDrivers/PayFast/CreditCard.php
@@ -14,10 +14,8 @@ namespace App\PaymentDrivers\PayFast;
use App\Exceptions\PaymentFailed;
use App\Jobs\Util\SystemLogger;
-use App\Models\ClientGatewayToken;
use App\Models\GatewayType;
use App\Models\Payment;
-use App\Models\PaymentHash;
use App\Models\PaymentType;
use App\Models\SystemLog;
use App\PaymentDrivers\PayFastPaymentDriver;
diff --git a/app/PaymentDrivers/PayFast/Token.php b/app/PaymentDrivers/PayFast/Token.php
index b7734ff4ff70..4d0ef8caea2a 100644
--- a/app/PaymentDrivers/PayFast/Token.php
+++ b/app/PaymentDrivers/PayFast/Token.php
@@ -12,19 +12,10 @@
namespace App\PaymentDrivers\PayFast;
-use App\Exceptions\PaymentFailed;
-use App\Jobs\Util\SystemLogger;
use App\Models\ClientGatewayToken;
-use App\Models\GatewayType;
-use App\Models\Payment;
use App\Models\PaymentHash;
-use App\Models\PaymentType;
-use App\Models\SystemLog;
use App\PaymentDrivers\PayFastPaymentDriver;
use GuzzleHttp\RequestOptions;
-use Illuminate\Http\Request;
-use Illuminate\Support\Facades\Cache;
-use Illuminate\Support\Str;
class Token
{
@@ -62,7 +53,6 @@ class Token
protected function generate_parameter_string($api_data, $sort_data_before_merge = true, $skip_empty_values = true)
{
-
// if sorting is required the passphrase should be added in before sort.
if (! empty($this->payfast->company_gateway->getConfigField('passphrase')) && $sort_data_before_merge) {
$api_data['passphrase'] = $this->payfast->company_gateway->getConfigField('passphrase');
@@ -118,9 +108,10 @@ class Token
private function send($headers, $body, $token)
{
$client = new \GuzzleHttp\Client(
- [
- 'headers' => $headers,
- ]);
+ [
+ 'headers' => $headers,
+ ]
+ );
try {
$response = $client->post("https://api.payfast.co.za/subscriptions/{$token}/adhoc?testing=true", [
diff --git a/app/PaymentDrivers/PayTrace/CreditCard.php b/app/PaymentDrivers/PayTrace/CreditCard.php
index 4783126f4b50..a07f17e5ea4e 100644
--- a/app/PaymentDrivers/PayTrace/CreditCard.php
+++ b/app/PaymentDrivers/PayTrace/CreditCard.php
@@ -12,20 +12,15 @@
namespace App\PaymentDrivers\PayTrace;
-use App\Exceptions\PaymentFailed;
-use App\Jobs\Util\SystemLogger;
use App\Models\ClientGatewayToken;
use App\Models\GatewayType;
use App\Models\Invoice;
use App\Models\Payment;
-use App\Models\PaymentHash;
use App\Models\PaymentType;
use App\Models\SystemLog;
-use App\PaymentDrivers\PayFastPaymentDriver;
use App\PaymentDrivers\PaytracePaymentDriver;
use App\Utils\Traits\MakesHash;
use Illuminate\Http\Request;
-use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;
class CreditCard
diff --git a/app/PaymentDrivers/PaytracePaymentDriver.php b/app/PaymentDrivers/PaytracePaymentDriver.php
index 2aeb6d8e3079..33196ee1d32e 100644
--- a/app/PaymentDrivers/PaytracePaymentDriver.php
+++ b/app/PaymentDrivers/PaytracePaymentDriver.php
@@ -90,7 +90,6 @@ class PaytracePaymentDriver extends BaseDriver
public function refund(Payment $payment, $amount, $return_client_response = false)
{
-
$data = [
'amount' => $amount,
'transaction_id' => $payment->transaction_reference,
diff --git a/app/PaymentDrivers/Razorpay/Hosted.php b/app/PaymentDrivers/Razorpay/Hosted.php
index 240b8e008d6e..24493c780b22 100644
--- a/app/PaymentDrivers/Razorpay/Hosted.php
+++ b/app/PaymentDrivers/Razorpay/Hosted.php
@@ -21,7 +21,6 @@ use App\Models\PaymentType;
use App\Models\SystemLog;
use App\PaymentDrivers\Common\MethodInterface;
use App\PaymentDrivers\RazorpayPaymentDriver;
-use Illuminate\Contracts\Container\BindingResolutionException;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
diff --git a/app/PaymentDrivers/Sample/CreditCard.php b/app/PaymentDrivers/Sample/CreditCard.php
index 2567e6a170ef..2165a56d83a2 100644
--- a/app/PaymentDrivers/Sample/CreditCard.php
+++ b/app/PaymentDrivers/Sample/CreditCard.php
@@ -12,18 +12,10 @@
namespace App\PaymentDrivers\Sample;
-use App\Exceptions\PaymentFailed;
-use App\Jobs\Util\SystemLogger;
-use App\Models\ClientGatewayToken;
use App\Models\GatewayType;
use App\Models\Payment;
-use App\Models\PaymentHash;
use App\Models\PaymentType;
-use App\Models\SystemLog;
use App\Utils\Traits\MakesHash;
-use Illuminate\Http\Request;
-use Illuminate\Support\Facades\Cache;
-use Illuminate\Support\Str;
class CreditCard
{
diff --git a/app/PaymentDrivers/Square/CreditCard.php b/app/PaymentDrivers/Square/CreditCard.php
index cbb1f129a427..a8b75426caf4 100644
--- a/app/PaymentDrivers/Square/CreditCard.php
+++ b/app/PaymentDrivers/Square/CreditCard.php
@@ -203,7 +203,6 @@ class CreditCard implements MethodInterface
private function createClient()
{
-
$country = $this->square_driver->client->country ? $this->square_driver->client->country->iso_3166_2 : $this->square_driver->client->company->country()->iso_3166_2;
/* Step two - create the customer */
diff --git a/app/PaymentDrivers/SquarePaymentDriver.php b/app/PaymentDrivers/SquarePaymentDriver.php
index eb4a0bfec9ba..bb2e9f6fef1e 100644
--- a/app/PaymentDrivers/SquarePaymentDriver.php
+++ b/app/PaymentDrivers/SquarePaymentDriver.php
@@ -105,7 +105,6 @@ class SquarePaymentDriver extends BaseDriver
/** @var ApiResponse */
$response = $this->square->getRefundsApi()->refund($body);
-
}
public function tokenBilling(ClientGatewayToken $cgt, PaymentHash $payment_hash)
diff --git a/app/PaymentDrivers/Stripe/ACH.php b/app/PaymentDrivers/Stripe/ACH.php
index 066bd30a8533..cc1dee538202 100644
--- a/app/PaymentDrivers/Stripe/ACH.php
+++ b/app/PaymentDrivers/Stripe/ACH.php
@@ -13,7 +13,6 @@
namespace App\PaymentDrivers\Stripe;
use App\Exceptions\PaymentFailed;
-use App\Http\Requests\ClientPortal\PaymentMethod\VerifyPaymentMethodRequest;
use App\Http\Requests\Request;
use App\Jobs\Mail\NinjaMailerJob;
use App\Jobs\Mail\NinjaMailerObject;
@@ -27,6 +26,7 @@ use App\Models\PaymentHash;
use App\Models\PaymentType;
use App\Models\SystemLog;
use App\PaymentDrivers\StripePaymentDriver;
+use App\Utils\Number;
use App\Utils\Traits\MakesHash;
use Exception;
use Stripe\Customer;
@@ -36,7 +36,6 @@ use Stripe\Exception\CardException;
use Stripe\Exception\InvalidRequestException;
use Stripe\Exception\RateLimitException;
use Stripe\PaymentIntent;
-use App\Utils\Number;
class ACH
{
@@ -69,7 +68,7 @@ class ACH
$customer = $this->stripe->findOrCreateCustomer();
try {
- $source = Customer::createSource($customer->id, ['source' => $stripe_response->token->id], array_merge($this->stripe->stripe_connect_auth, ['idempotency_key' => uniqid("st",true)]));
+ $source = Customer::createSource($customer->id, ['source' => $stripe_response->token->id], array_merge($this->stripe->stripe_connect_auth, ['idempotency_key' => uniqid("st", true)]));
} catch (InvalidRequestException $e) {
throw new PaymentFailed($e->getMessage(), $e->getCode());
}
@@ -96,22 +95,18 @@ class ACH
public function updateBankAccount(array $event)
{
-
$stripe_event = $event['data']['object'];
$token = ClientGatewayToken::where('token', $stripe_event['id'])
->where('gateway_customer_reference', $stripe_event['customer'])
->first();
- if($token && isset($stripe_event['object']) && $stripe_event['object'] == 'bank_account' && isset($stripe_event['status']) && $stripe_event['status'] == 'verified') {
-
+ if ($token && isset($stripe_event['object']) && $stripe_event['object'] == 'bank_account' && isset($stripe_event['status']) && $stripe_event['status'] == 'verified') {
$meta = $token->meta;
$meta->state = 'authorized';
$token->meta = $meta;
$token->save();
-
}
-
}
public function verificationView(ClientGatewayToken $token)
@@ -128,8 +123,7 @@ class ACH
$bank_account = Customer::retrieveSource($token->gateway_customer_reference, $token->token, [], $this->stripe->stripe_connect_auth);
/* Catch externally validated bank accounts and mark them as verified */
- if(isset($bank_account->status) && $bank_account->status == 'verified'){
-
+ if (isset($bank_account->status) && $bank_account->status == 'verified') {
$meta = $token->meta;
$meta->state = 'authorized';
$token->meta = $meta;
@@ -138,7 +132,6 @@ class ACH
return redirect()
->route('client.payment_methods.show', $token->hashed_id)
->with('message', __('texts.payment_method_verified'));
-
}
$data = [
@@ -222,7 +215,8 @@ class ACH
if (count($data['tokens']) == 0) {
$intent =
- $this->stripe->createPaymentIntent([
+ $this->stripe->createPaymentIntent(
+ [
'amount' => $data['amount'],
'currency' => $data['currency'],
'setup_future_usage' => 'off_session',
@@ -338,23 +332,23 @@ class ACH
$data['error_code'] = $e->getError()->code;
$data['param'] = $e->getError()->param;
$data['message'] = $e->getError()->message;
- break;
+ break;
case $e instanceof RateLimitException:
$data['message'] = 'Too many requests made to the API too quickly';
- break;
+ break;
case $e instanceof InvalidRequestException:
$data['message'] = 'Invalid parameters were supplied to Stripe\'s API';
- break;
+ break;
case $e instanceof AuthenticationException:
$data['message'] = 'Authentication with Stripe\'s API failed';
- break;
+ break;
case $e instanceof ApiErrorException:
$data['message'] = 'Network communication with Stripe failed';
- break;
+ break;
default:
$data['message'] = $e->getMessage();
- break;
+ break;
}
$this->stripe->processInternallyFailedPayment($this->stripe, $e);
diff --git a/app/PaymentDrivers/Stripe/ACSS.php b/app/PaymentDrivers/Stripe/ACSS.php
index e9b0bdc09602..fb364ce25dab 100644
--- a/app/PaymentDrivers/Stripe/ACSS.php
+++ b/app/PaymentDrivers/Stripe/ACSS.php
@@ -55,7 +55,7 @@ class ACSS
$customer = $this->stripe->findOrCreateCustomer();
try {
- $source = Customer::createSource($customer->id, ['source' => $stripe_response->token->id], array_merge($this->stripe->stripe_connect_auth, ['idempotency_key' => uniqid("st",true)]));
+ $source = Customer::createSource($customer->id, ['source' => $stripe_response->token->id], array_merge($this->stripe->stripe_connect_auth, ['idempotency_key' => uniqid("st", true)]));
} catch (InvalidRequestException $e) {
throw new PaymentFailed($e->getMessage(), $e->getCode());
}
diff --git a/app/PaymentDrivers/Stripe/ApplePay.php b/app/PaymentDrivers/Stripe/ApplePay.php
index 461eb0a48d90..d8aa015abe4c 100644
--- a/app/PaymentDrivers/Stripe/ApplePay.php
+++ b/app/PaymentDrivers/Stripe/ApplePay.php
@@ -12,14 +12,9 @@
namespace App\PaymentDrivers\Stripe;
-use App\Exceptions\PaymentFailed;
use App\Http\Requests\ClientPortal\Payments\PaymentResponseRequest;
-use App\Jobs\Util\SystemLogger;
use App\Models\GatewayType;
-use App\Models\Payment;
-use App\Models\PaymentType;
use App\Models\SystemLog;
-use App\PaymentDrivers\Stripe\CreditCard;
use App\PaymentDrivers\StripePaymentDriver;
use App\Utils\Ninja;
diff --git a/app/PaymentDrivers/Stripe/BECS.php b/app/PaymentDrivers/Stripe/BECS.php
index 02233112ef6b..f2ccc0a69674 100644
--- a/app/PaymentDrivers/Stripe/BECS.php
+++ b/app/PaymentDrivers/Stripe/BECS.php
@@ -60,7 +60,7 @@ class BECS
'payment_hash' => $this->stripe->payment_hash->hash,
'gateway_type_id' => GatewayType::BECS,
],
- ], array_merge($this->stripe->stripe_connect_auth, ['idempotency_key' => uniqid("st",true)]));
+ ], array_merge($this->stripe->stripe_connect_auth, ['idempotency_key' => uniqid("st", true)]));
$data['pi_client_secret'] = $intent->client_secret;
diff --git a/app/PaymentDrivers/Stripe/Bancontact.php b/app/PaymentDrivers/Stripe/Bancontact.php
index 169b814bf952..f4aa0ba1c3c6 100644
--- a/app/PaymentDrivers/Stripe/Bancontact.php
+++ b/app/PaymentDrivers/Stripe/Bancontact.php
@@ -57,7 +57,7 @@ class Bancontact
'gateway_type_id' => GatewayType::BANCONTACT,
],
- ], array_merge($this->stripe->stripe_connect_auth, ['idempotency_key' => uniqid("st",true)]));
+ ], array_merge($this->stripe->stripe_connect_auth, ['idempotency_key' => uniqid("st", true)]));
$data['pi_client_secret'] = $intent->client_secret;
@@ -81,7 +81,7 @@ class Bancontact
$this->stripe->payment_hash->data = array_merge((array) $this->stripe->payment_hash->data, $request->all());
$this->stripe->payment_hash->save();
- if (in_array($request->redirect_status, ['succeeded','pending'])) {
+ if (in_array($request->redirect_status, ['succeeded','pending'])) {
return $this->processSuccessfulPayment($request->payment_intent);
}
diff --git a/app/PaymentDrivers/Stripe/Charge.php b/app/PaymentDrivers/Stripe/Charge.php
index b65a594ba222..f40918129707 100644
--- a/app/PaymentDrivers/Stripe/Charge.php
+++ b/app/PaymentDrivers/Stripe/Charge.php
@@ -12,7 +12,6 @@
namespace App\PaymentDrivers\Stripe;
-use App\Events\Payment\PaymentWasCreated;
use App\Jobs\Util\SystemLogger;
use App\Models\ClientGatewayToken;
use App\Models\GatewayType;
@@ -22,17 +21,13 @@ use App\Models\PaymentHash;
use App\Models\PaymentType;
use App\Models\SystemLog;
use App\PaymentDrivers\StripePaymentDriver;
-use App\PaymentDrivers\Stripe\ACH;
-use App\Utils\Ninja;
+use App\Utils\Number;
use App\Utils\Traits\MakesHash;
-use Stripe\Exception\ApiConnectionException;
use Stripe\Exception\ApiErrorException;
use Stripe\Exception\AuthenticationException;
use Stripe\Exception\CardException;
use Stripe\Exception\InvalidRequestException;
use Stripe\Exception\RateLimitException;
-use Stripe\StripeClient;
-use App\Utils\Number;
class Charge
{
@@ -95,7 +90,7 @@ class Charge
$data['off_session'] = true;
}
- $response = $this->stripe->createPaymentIntent($data, array_merge($this->stripe->stripe_connect_auth, ['idempotency_key' => uniqid("st",true)]));
+ $response = $this->stripe->createPaymentIntent($data, array_merge($this->stripe->stripe_connect_auth, ['idempotency_key' => uniqid("st", true)]));
SystemLogger::dispatch($response, SystemLog::CATEGORY_GATEWAY_RESPONSE, SystemLog::EVENT_GATEWAY_SUCCESS, SystemLog::TYPE_STRIPE, $this->stripe->client, $this->stripe->client->company);
} catch (\Exception $e) {
@@ -114,23 +109,23 @@ class Charge
$data['error_code'] = $e->getError()->code;
$data['param'] = $e->getError()->param;
$data['message'] = $e->getError()->message;
- break;
+ break;
case $e instanceof RateLimitException:
$data['message'] = 'Too many requests made to the API too quickly';
- break;
+ break;
case $e instanceof InvalidRequestException:
$data['message'] = 'Invalid parameters were supplied to Stripe\'s API';
- break;
+ break;
case $e instanceof AuthenticationException:
$data['message'] = 'Authentication with Stripe\'s API failed';
- break;
+ break;
case $e instanceof ApiErrorException:
$data['message'] = 'Network communication with Stripe failed';
- break;
+ break;
default:
$data['message'] = $e->getMessage();
- break;
+ break;
}
$this->stripe->processInternallyFailedPayment($this->stripe, $e);
@@ -146,21 +141,20 @@ class Charge
$payment_method_type = PaymentType::SEPA;
$status = Payment::STATUS_PENDING;
} else {
-
- if(isset($response->latest_charge)) {
+ if (isset($response->latest_charge)) {
$charge = \Stripe\Charge::retrieve($response->latest_charge, $this->stripe->stripe_connect_auth);
$payment_method_type = $charge->payment_method_details->card->brand;
- }
- elseif(isset($response->charges->data[0]->payment_method_details->card->brand))
+ } elseif (isset($response->charges->data[0]->payment_method_details->card->brand)) {
$payment_method_type = $response->charges->data[0]->payment_method_details->card->brand;
- else
+ } else {
$payment_method_type = 'visa';
+ }
$status = Payment::STATUS_COMPLETED;
}
- if(!in_array($response?->status, ['succeeded', 'processing'])){
- $this->stripe->processInternallyFailedPayment($this->stripe, new \Exception('Auto billing failed.',400));
+ if (!in_array($response?->status, ['succeeded', 'processing'])) {
+ $this->stripe->processInternallyFailedPayment($this->stripe, new \Exception('Auto billing failed.', 400));
}
$data = [
diff --git a/app/PaymentDrivers/Stripe/Connect/Verify.php b/app/PaymentDrivers/Stripe/Connect/Verify.php
index 50909b23fe19..01d165db5103 100644
--- a/app/PaymentDrivers/Stripe/Connect/Verify.php
+++ b/app/PaymentDrivers/Stripe/Connect/Verify.php
@@ -12,25 +12,10 @@
namespace App\PaymentDrivers\Stripe\Connect;
-use App\Exceptions\PaymentFailed;
use App\Exceptions\StripeConnectFailure;
-use App\Http\Requests\ClientPortal\PaymentMethod\VerifyPaymentMethodRequest;
-use App\Http\Requests\Request;
-use App\Jobs\Mail\NinjaMailerJob;
-use App\Jobs\Mail\NinjaMailerObject;
-use App\Jobs\Util\SystemLogger;
-use App\Mail\Gateways\ACHVerificationNotification;
-use App\Models\ClientGatewayToken;
-use App\Models\GatewayType;
-use App\Models\Payment;
-use App\Models\PaymentType;
-use App\Models\SystemLog;
use App\PaymentDrivers\StripePaymentDriver;
use App\Utils\Traits\MakesHash;
-use Exception;
use Stripe\Customer;
-use Stripe\Exception\CardException;
-use Stripe\Exception\InvalidRequestException;
class Verify
{
diff --git a/app/PaymentDrivers/Stripe/CreditCard.php b/app/PaymentDrivers/Stripe/CreditCard.php
index eba69f01d373..fadce23f6ac7 100644
--- a/app/PaymentDrivers/Stripe/CreditCard.php
+++ b/app/PaymentDrivers/Stripe/CreditCard.php
@@ -19,11 +19,11 @@ use App\Models\GatewayType;
use App\Models\Payment;
use App\Models\PaymentType;
use App\Models\SystemLog;
-use App\PaymentDrivers\StripePaymentDriver;
use App\PaymentDrivers\Stripe\Jobs\UpdateCustomer;
+use App\PaymentDrivers\StripePaymentDriver;
+use App\Utils\Number;
use Stripe\PaymentIntent;
use Stripe\PaymentMethod;
-use App\Utils\Number;
class CreditCard
{
@@ -60,7 +60,6 @@ class CreditCard
public function paymentView(array $data)
{
-
$invoice_numbers = collect($data['invoices'])->pluck('invoice_number')->implode(',');
$description = ctrans('texts.stripe_payment_text', ['invoicenumber' => $invoice_numbers, 'amount' => Number::formatMoney($data['total']['amount_with_fee'], $this->stripe->client), 'client' => $this->stripe->client->present()->name()], $this->stripe->client->company->locale());
@@ -111,7 +110,7 @@ class CreditCard
$state['store_card'] = false;
}
- $state['payment_intent'] = PaymentIntent::retrieve($state['server_response']->id, array_merge($this->stripe->stripe_connect_auth, ['idempotency_key' => uniqid("st",true)]));
+ $state['payment_intent'] = PaymentIntent::retrieve($state['server_response']->id, array_merge($this->stripe->stripe_connect_auth, ['idempotency_key' => uniqid("st", true)]));
$state['customer'] = $state['payment_intent']->customer;
$this->stripe->payment_hash->data = array_merge((array) $this->stripe->payment_hash->data, $state);
@@ -169,12 +168,12 @@ class CreditCard
//If the user has come from a subscription double check here if we need to redirect.
//08-08-2022
- if($payment->invoices()->whereHas('subscription')->exists()){
+ if ($payment->invoices()->whereHas('subscription')->exists()) {
$subscription = $payment->invoices()->first()->subscription;
- if($subscription && array_key_exists('return_url', $subscription->webhook_configuration) && strlen($subscription->webhook_configuration['return_url']) >=1)
- return redirect($subscription->webhook_configuration['return_url']);
-
+ if ($subscription && array_key_exists('return_url', $subscription->webhook_configuration) && strlen($subscription->webhook_configuration['return_url']) >=1) {
+ return redirect($subscription->webhook_configuration['return_url']);
+ }
}
//08-08-2022
diff --git a/app/PaymentDrivers/Stripe/EPS.php b/app/PaymentDrivers/Stripe/EPS.php
index 8dbed6cae3ff..0608c715c4eb 100644
--- a/app/PaymentDrivers/Stripe/EPS.php
+++ b/app/PaymentDrivers/Stripe/EPS.php
@@ -56,7 +56,7 @@ class EPS
'payment_hash' => $this->stripe->payment_hash->hash,
'gateway_type_id' => GatewayType::EPS,
],
- ], array_merge($this->stripe->stripe_connect_auth, ['idempotency_key' => uniqid("st",true)]));
+ ], array_merge($this->stripe->stripe_connect_auth, ['idempotency_key' => uniqid("st", true)]));
$data['pi_client_secret'] = $intent->client_secret;
@@ -80,7 +80,7 @@ class EPS
$this->stripe->payment_hash->data = array_merge((array) $this->stripe->payment_hash->data, $request->all());
$this->stripe->payment_hash->save();
- if (in_array($request->redirect_status, ['succeeded','pending'])) {
+ if (in_array($request->redirect_status, ['succeeded','pending'])) {
return $this->processSuccessfulPayment($request->payment_intent);
}
diff --git a/app/PaymentDrivers/Stripe/FPX.php b/app/PaymentDrivers/Stripe/FPX.php
index 5fc7010f8297..fa835e4eb59e 100644
--- a/app/PaymentDrivers/Stripe/FPX.php
+++ b/app/PaymentDrivers/Stripe/FPX.php
@@ -57,7 +57,7 @@ class FPX
'payment_hash' => $this->stripe->payment_hash->hash,
'gateway_type_id' => GatewayType::FPX,
],
- ], array_merge($this->stripe->stripe_connect_auth, ['idempotency_key' => uniqid("st",true)]));
+ ], array_merge($this->stripe->stripe_connect_auth, ['idempotency_key' => uniqid("st", true)]));
$data['pi_client_secret'] = $intent->client_secret;
@@ -81,7 +81,7 @@ class FPX
$this->stripe->payment_hash->data = array_merge((array) $this->stripe->payment_hash->data, $request->all());
$this->stripe->payment_hash->save();
- if (in_array($request->redirect_status, ['succeeded','pending'])) {
+ if (in_array($request->redirect_status, ['succeeded','pending'])) {
return $this->processSuccessfulPayment($request->payment_intent);
}
diff --git a/app/PaymentDrivers/Stripe/GIROPAY.php b/app/PaymentDrivers/Stripe/GIROPAY.php
index ff52848fe5cf..167d790eeab0 100644
--- a/app/PaymentDrivers/Stripe/GIROPAY.php
+++ b/app/PaymentDrivers/Stripe/GIROPAY.php
@@ -56,7 +56,7 @@ class GIROPAY
'payment_hash' => $this->stripe->payment_hash->hash,
'gateway_type_id' => GatewayType::GIROPAY,
],
- ], array_merge($this->stripe->stripe_connect_auth, ['idempotency_key' => uniqid("st",true)]));
+ ], array_merge($this->stripe->stripe_connect_auth, ['idempotency_key' => uniqid("st", true)]));
$data['pi_client_secret'] = $intent->client_secret;
@@ -80,7 +80,7 @@ class GIROPAY
$this->stripe->payment_hash->data = array_merge((array) $this->stripe->payment_hash->data, $request->all());
$this->stripe->payment_hash->save();
- if (in_array($request->redirect_status, ['succeeded','pending'])) {
+ if (in_array($request->redirect_status, ['succeeded','pending'])) {
return $this->processSuccessfulPayment($request->payment_intent);
}
diff --git a/app/PaymentDrivers/Stripe/ImportCustomers.php b/app/PaymentDrivers/Stripe/ImportCustomers.php
index 7395428d4231..387544bdb2c8 100644
--- a/app/PaymentDrivers/Stripe/ImportCustomers.php
+++ b/app/PaymentDrivers/Stripe/ImportCustomers.php
@@ -15,20 +15,16 @@ namespace App\PaymentDrivers\Stripe;
use App\Exceptions\StripeConnectFailure;
use App\Factory\ClientContactFactory;
use App\Factory\ClientFactory;
-use App\Factory\ClientGatewayTokenFactory;
use App\Models\Client;
use App\Models\ClientGatewayToken;
use App\Models\Country;
use App\Models\Currency;
-use App\Models\GatewayType;
-use App\PaymentDrivers\Stripe\UpdatePaymentMethods;
use App\PaymentDrivers\StripePaymentDriver;
use App\Utils\Ninja;
use App\Utils\Traits\GeneratesCounter;
use App\Utils\Traits\MakesHash;
use Illuminate\Database\QueryException;
use Stripe\Customer;
-use Stripe\PaymentMethod;
class ImportCustomers
{
@@ -66,7 +62,7 @@ class ImportCustomers
$this->addCustomer($customer);
}
- //handle
+ //handle
// if(is_array($customers->data) && end($customers->data) && array_key_exists('id', end($customers->data)))
// $starting_after = end($customers->data)['id'];
// else
@@ -74,9 +70,9 @@ class ImportCustomers
$starting_after = isset(end($customers->data)['id']) ? end($customers->data)['id'] : false;
- if(!$starting_after)
+ if (!$starting_after) {
break;
-
+ }
} while ($customers->has_more);
}
@@ -140,7 +136,6 @@ class ImportCustomers
$client->name = $customer->name ? $customer->name : $customer->email;
if (! isset($client->number) || empty($client->number)) {
-
$x = 1;
do {
@@ -157,11 +152,7 @@ class ImportCustomers
}
}
} while ($this->completed);
-
-
-
- }
- else{
+ } else {
$client->save();
}
diff --git a/app/PaymentDrivers/Stripe/Jobs/PaymentIntentFailureWebhook.php b/app/PaymentDrivers/Stripe/Jobs/PaymentIntentFailureWebhook.php
index ab466ed19afc..466c0c49dbf0 100644
--- a/app/PaymentDrivers/Stripe/Jobs/PaymentIntentFailureWebhook.php
+++ b/app/PaymentDrivers/Stripe/Jobs/PaymentIntentFailureWebhook.php
@@ -12,16 +12,10 @@
namespace App\PaymentDrivers\Stripe\Jobs;
use App\Jobs\Mail\PaymentFailedMailer;
-use App\Jobs\Util\SystemLogger;
use App\Libraries\MultiDB;
use App\Models\Company;
-use App\Models\CompanyGateway;
-use App\Models\GatewayType;
-use App\Models\Invoice;
use App\Models\Payment;
use App\Models\PaymentHash;
-use App\Models\PaymentType;
-use App\Models\SystemLog;
use App\PaymentDrivers\Stripe\Utilities;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
@@ -99,11 +93,11 @@ class PaymentIntentFailureWebhook implements ShouldQueue
}
PaymentFailedMailer::dispatch(
- $payment_hash,
- $client->company,
- $client,
- $error
- );
+ $payment_hash,
+ $client->company,
+ $client,
+ $error
+ );
}
}
}
diff --git a/app/PaymentDrivers/Stripe/Jobs/PaymentIntentProcessingWebhook.php b/app/PaymentDrivers/Stripe/Jobs/PaymentIntentProcessingWebhook.php
index e6ae4ea7f602..06ce90182ef3 100644
--- a/app/PaymentDrivers/Stripe/Jobs/PaymentIntentProcessingWebhook.php
+++ b/app/PaymentDrivers/Stripe/Jobs/PaymentIntentProcessingWebhook.php
@@ -22,7 +22,6 @@ use App\Models\Payment;
use App\Models\PaymentHash;
use App\Models\PaymentType;
use App\Models\SystemLog;
-use App\PaymentDrivers\Stripe\UpdatePaymentMethods;
use App\PaymentDrivers\Stripe\Utilities;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
@@ -56,53 +55,50 @@ class PaymentIntentProcessingWebhook implements ShouldQueue
/* Stub processing payment intents with a pending payment */
public function handle()
{
-
MultiDB::findAndSetDbByCompanyKey($this->company_key);
$company = Company::where('company_key', $this->company_key)->first();
- foreach ($this->stripe_request as $transaction) {
-
- if(array_key_exists('payment_intent', $transaction))
- {
- $payment = Payment::query()
- ->where('company_id', $company->id)
- ->where('transaction_reference', $transaction['payment_intent'])
- ->first();
-
- }
- else
- {
- $payment = Payment::query()
- ->where('company_id', $company->id)
- ->where('transaction_reference', $transaction['id'])
- ->first();
- }
-
- if ($payment) {
- $payment->status_id = Payment::STATUS_PENDING;
- $payment->save();
-
- $this->payment_completed = true;
- }
+ foreach ($this->stripe_request as $transaction) {
+ if (array_key_exists('payment_intent', $transaction)) {
+ $payment = Payment::query()
+ ->where('company_id', $company->id)
+ ->where('transaction_reference', $transaction['payment_intent'])
+ ->first();
+ } else {
+ $payment = Payment::query()
+ ->where('company_id', $company->id)
+ ->where('transaction_reference', $transaction['id'])
+ ->first();
}
+ if ($payment) {
+ $payment->status_id = Payment::STATUS_PENDING;
+ $payment->save();
+
+ $this->payment_completed = true;
+ }
+ }
- if($this->payment_completed)
+
+ if ($this->payment_completed) {
return;
+ }
$company_gateway = CompanyGateway::find($this->company_gateway_id);
$stripe_driver = $company_gateway->driver()->init();
$charge_id = false;
- if(isset($this->stripe_request['object']['charges']) && optional($this->stripe_request['object']['charges']['data'][0])['id'])
- $charge_id = $this->stripe_request['object']['charges']['data'][0]['id']; // API VERSION 2018
- elseif (isset($this->stripe_request['object']['latest_charge']))
- $charge_id = $this->stripe_request['object']['latest_charge']; // API VERSION 2022-11-15
+ if (isset($this->stripe_request['object']['charges']) && optional($this->stripe_request['object']['charges']['data'][0])['id']) {
+ $charge_id = $this->stripe_request['object']['charges']['data'][0]['id'];
+ } // API VERSION 2018
+ elseif (isset($this->stripe_request['object']['latest_charge'])) {
+ $charge_id = $this->stripe_request['object']['latest_charge'];
+ } // API VERSION 2022-11-15
- if(!$charge_id){
+ if (!$charge_id) {
nlog("could not resolve charge");
return;
}
@@ -111,8 +107,7 @@ class PaymentIntentProcessingWebhook implements ShouldQueue
$charge = \Stripe\Charge::retrieve($charge_id, $stripe_driver->stripe_connect_auth);
- if(!$charge)
- {
+ if (!$charge) {
nlog("no charge found");
nlog($this->stripe_request);
return;
@@ -125,25 +120,26 @@ class PaymentIntentProcessingWebhook implements ShouldQueue
->where('transaction_reference', $charge['id'])
->first();
- //return early
- if($payment && $payment->status_id == Payment::STATUS_PENDING){
- nlog(" payment found and status correct - returning ");
+ //return early
+ if ($payment && $payment->status_id == Payment::STATUS_PENDING) {
+ nlog(" payment found and status correct - returning ");
return;
- }
- elseif($payment){
+ } elseif ($payment) {
$payment->status_id = Payment::STATUS_PENDING;
$payment->save();
}
$hash = isset($charge['metadata']['payment_hash']) ? $charge['metadata']['payment_hash'] : false;
- if(!$hash)
+ if (!$hash) {
return;
+ }
$payment_hash = PaymentHash::where('hash', $hash)->first();
- if(!$payment_hash)
+ if (!$payment_hash) {
return;
+ }
$stripe_driver->client = $payment_hash->fee_invoice->client;
@@ -164,18 +160,16 @@ class PaymentIntentProcessingWebhook implements ShouldQueue
$company,
);
- if(isset($pi['payment_method_types']) && in_array('us_bank_account', $pi['payment_method_types']))
- {
-
+ if (isset($pi['payment_method_types']) && in_array('us_bank_account', $pi['payment_method_types'])) {
$invoice = Invoice::with('client')->withTrashed()->find($payment_hash->fee_invoice_id);
$client = $invoice->client;
- if($invoice->is_deleted)
+ if ($invoice->is_deleted) {
return;
+ }
$this->updateAchPayment($payment_hash, $client, $meta);
}
-
}
private function updateAchPayment($payment_hash, $client, $meta)
@@ -208,7 +202,6 @@ class PaymentIntentProcessingWebhook implements ShouldQueue
);
try {
-
$customer = $driver->getCustomer($meta['customer']);
$method = $driver->getStripePaymentMethod($meta['payment_method']);
$payment_method = $meta['payment_method'];
@@ -244,12 +237,9 @@ class PaymentIntentProcessingWebhook implements ShouldQueue
}
$driver->storeGatewayToken($data, $additional_data);
-
- }
- catch(\Exception $e){
+ } catch(\Exception $e) {
nlog("failed to import payment methods");
nlog($e->getMessage());
}
}
-
-}
\ No newline at end of file
+}
diff --git a/app/PaymentDrivers/Stripe/Jobs/PaymentIntentWebhook.php b/app/PaymentDrivers/Stripe/Jobs/PaymentIntentWebhook.php
index a79679d39bf9..5881d1196d82 100644
--- a/app/PaymentDrivers/Stripe/Jobs/PaymentIntentWebhook.php
+++ b/app/PaymentDrivers/Stripe/Jobs/PaymentIntentWebhook.php
@@ -22,7 +22,6 @@ use App\Models\Payment;
use App\Models\PaymentHash;
use App\Models\PaymentType;
use App\Models\SystemLog;
-use App\PaymentDrivers\Stripe\UpdatePaymentMethods;
use App\PaymentDrivers\Stripe\Utilities;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
@@ -55,53 +54,50 @@ class PaymentIntentWebhook implements ShouldQueue
public function handle()
{
-
MultiDB::findAndSetDbByCompanyKey($this->company_key);
$company = Company::where('company_key', $this->company_key)->first();
- foreach ($this->stripe_request as $transaction) {
-
- if(array_key_exists('payment_intent', $transaction))
- {
- $payment = Payment::query()
- ->where('company_id', $company->id)
- ->where('transaction_reference', $transaction['payment_intent'])
- ->first();
-
- }
- else
- {
- $payment = Payment::query()
- ->where('company_id', $company->id)
- ->where('transaction_reference', $transaction['id'])
- ->first();
- }
-
- if ($payment) {
- $payment->status_id = Payment::STATUS_COMPLETED;
- $payment->save();
-
- $this->payment_completed = true;
- }
+ foreach ($this->stripe_request as $transaction) {
+ if (array_key_exists('payment_intent', $transaction)) {
+ $payment = Payment::query()
+ ->where('company_id', $company->id)
+ ->where('transaction_reference', $transaction['payment_intent'])
+ ->first();
+ } else {
+ $payment = Payment::query()
+ ->where('company_id', $company->id)
+ ->where('transaction_reference', $transaction['id'])
+ ->first();
}
+ if ($payment) {
+ $payment->status_id = Payment::STATUS_COMPLETED;
+ $payment->save();
+
+ $this->payment_completed = true;
+ }
+ }
- if($this->payment_completed)
+
+ if ($this->payment_completed) {
return;
+ }
$company_gateway = CompanyGateway::find($this->company_gateway_id);
$stripe_driver = $company_gateway->driver()->init();
$charge_id = false;
- if(isset($this->stripe_request['object']['charges']) && optional($this->stripe_request['object']['charges']['data'][0])['id'])
- $charge_id = $this->stripe_request['object']['charges']['data'][0]['id']; // API VERSION 2018
- elseif (isset($this->stripe_request['object']['latest_charge']))
- $charge_id = $this->stripe_request['object']['latest_charge']; // API VERSION 2022-11-15
+ if (isset($this->stripe_request['object']['charges']) && optional($this->stripe_request['object']['charges']['data'][0])['id']) {
+ $charge_id = $this->stripe_request['object']['charges']['data'][0]['id'];
+ } // API VERSION 2018
+ elseif (isset($this->stripe_request['object']['latest_charge'])) {
+ $charge_id = $this->stripe_request['object']['latest_charge'];
+ } // API VERSION 2022-11-15
- if(!$charge_id){
+ if (!$charge_id) {
nlog("could not resolve charge");
return;
}
@@ -110,8 +106,7 @@ class PaymentIntentWebhook implements ShouldQueue
$charge = \Stripe\Charge::retrieve($charge_id, $stripe_driver->stripe_connect_auth);
- if(!$charge)
- {
+ if (!$charge) {
nlog("no charge found");
nlog($this->stripe_request);
return;
@@ -124,25 +119,26 @@ class PaymentIntentWebhook implements ShouldQueue
->where('transaction_reference', $charge['id'])
->first();
- //return early
- if($payment && $payment->status_id == Payment::STATUS_COMPLETED){
- nlog(" payment found and status correct - returning ");
+ //return early
+ if ($payment && $payment->status_id == Payment::STATUS_COMPLETED) {
+ nlog(" payment found and status correct - returning ");
return;
- }
- elseif($payment){
+ } elseif ($payment) {
$payment->status_id = Payment::STATUS_COMPLETED;
$payment->save();
}
$hash = isset($charge['metadata']['payment_hash']) ? $charge['metadata']['payment_hash'] : false;
- if(!$hash)
+ if (!$hash) {
return;
+ }
$payment_hash = PaymentHash::where('hash', $hash)->first();
- if(!$payment_hash)
+ if (!$payment_hash) {
return;
+ }
$stripe_driver->client = $payment_hash->fee_invoice->client;
@@ -163,40 +159,34 @@ class PaymentIntentWebhook implements ShouldQueue
$company,
);
- if(isset($pi['allowed_source_types']) && in_array('card', $pi['allowed_source_types']))
- {
-
+ if (isset($pi['allowed_source_types']) && in_array('card', $pi['allowed_source_types'])) {
$invoice = Invoice::with('client')->withTrashed()->find($payment_hash->fee_invoice_id);
$client = $invoice->client;
- if($invoice->is_deleted)
+ if ($invoice->is_deleted) {
return;
+ }
$this->updateCreditCardPayment($payment_hash, $client, $meta);
- }
- elseif(isset($pi['payment_method_types']) && in_array('card', $pi['payment_method_types']))
- {
-
+ } elseif (isset($pi['payment_method_types']) && in_array('card', $pi['payment_method_types'])) {
$invoice = Invoice::with('client')->withTrashed()->find($payment_hash->fee_invoice_id);
$client = $invoice->client;
- if($invoice->is_deleted)
+ if ($invoice->is_deleted) {
return;
+ }
$this->updateCreditCardPayment($payment_hash, $client, $meta);
- }
- elseif(isset($pi['payment_method_types']) && in_array('us_bank_account', $pi['payment_method_types']))
- {
-
+ } elseif (isset($pi['payment_method_types']) && in_array('us_bank_account', $pi['payment_method_types'])) {
$invoice = Invoice::with('client')->withTrashed()->find($payment_hash->fee_invoice_id);
$client = $invoice->client;
- if($invoice->is_deleted)
+ if ($invoice->is_deleted) {
return;
+ }
$this->updateAchPayment($payment_hash, $client, $meta);
}
-
}
private function updateAchPayment($payment_hash, $client, $meta)
@@ -229,7 +219,6 @@ class PaymentIntentWebhook implements ShouldQueue
);
try {
-
$customer = $driver->getCustomer($meta['customer']);
$method = $driver->getStripePaymentMethod($meta['payment_method']);
$payment_method = $meta['payment_method'];
@@ -265,9 +254,7 @@ class PaymentIntentWebhook implements ShouldQueue
}
$driver->storeGatewayToken($data, $additional_data);
-
- }
- catch(\Exception $e){
+ } catch(\Exception $e) {
nlog("failed to import payment methods");
nlog($e->getMessage());
}
@@ -335,7 +322,5 @@ class PaymentIntentWebhook implements ShouldQueue
$client,
$client->company,
);
-
}
-
-}
\ No newline at end of file
+}
diff --git a/app/PaymentDrivers/Stripe/Jobs/StripeWebhook.php b/app/PaymentDrivers/Stripe/Jobs/StripeWebhook.php
index 444bb4b55f4f..13a25a8bce1c 100644
--- a/app/PaymentDrivers/Stripe/Jobs/StripeWebhook.php
+++ b/app/PaymentDrivers/Stripe/Jobs/StripeWebhook.php
@@ -11,17 +11,9 @@
namespace App\PaymentDrivers\Stripe\Jobs;
-use App\Jobs\Mail\PaymentFailedMailer;
-use App\Jobs\Util\SystemLogger;
use App\Libraries\MultiDB;
use App\Models\Company;
use App\Models\CompanyGateway;
-use App\Models\GatewayType;
-use App\Models\Invoice;
-use App\Models\Payment;
-use App\Models\PaymentHash;
-use App\Models\PaymentType;
-use App\Models\SystemLog;
use App\PaymentDrivers\Stripe\Utilities;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
diff --git a/app/PaymentDrivers/Stripe/Jobs/UpdateCustomer.php b/app/PaymentDrivers/Stripe/Jobs/UpdateCustomer.php
index 07de063c7dfd..af6e9d490646 100644
--- a/app/PaymentDrivers/Stripe/Jobs/UpdateCustomer.php
+++ b/app/PaymentDrivers/Stripe/Jobs/UpdateCustomer.php
@@ -11,18 +11,10 @@
namespace App\PaymentDrivers\Stripe\Jobs;
-use App\Jobs\Mail\PaymentFailedMailer;
-use App\Jobs\Util\SystemLogger;
use App\Libraries\MultiDB;
use App\Models\Client;
use App\Models\Company;
use App\Models\CompanyGateway;
-use App\Models\GatewayType;
-use App\Models\Invoice;
-use App\Models\Payment;
-use App\Models\PaymentHash;
-use App\Models\PaymentType;
-use App\Models\SystemLog;
use App\PaymentDrivers\Stripe\Utilities;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
@@ -53,7 +45,6 @@ class UpdateCustomer implements ShouldQueue
public function handle()
{
-
MultiDB::findAndSetDbByCompanyKey($this->company_key);
$company = Company::where('company_key', $this->company_key)->first();
@@ -61,8 +52,9 @@ class UpdateCustomer implements ShouldQueue
$company_gateway = CompanyGateway::find($this->company_gateway_id);
$client = Client::withTrashed()->find($this->client_id);
- if(!$company_gateway->update_details)
+ if (!$company_gateway->update_details) {
return;
+ }
$stripe = $company_gateway->driver($client)->init();
@@ -87,6 +79,5 @@ class UpdateCustomer implements ShouldQueue
$data['shipping']['address']['country'] = $client->shipping_country ? $client->shipping_country->iso_3166_2 : '';
\Stripe\Customer::update($customer->id, $data, $stripe->stripe_connect_auth);
-
}
}
diff --git a/app/PaymentDrivers/Stripe/Klarna.php b/app/PaymentDrivers/Stripe/Klarna.php
index 1a4cedd588a3..c15660c867c1 100644
--- a/app/PaymentDrivers/Stripe/Klarna.php
+++ b/app/PaymentDrivers/Stripe/Klarna.php
@@ -20,7 +20,6 @@ use App\Models\PaymentType;
use App\Models\SystemLog;
use App\PaymentDrivers\StripePaymentDriver;
use App\Utils\Number;
-use Illuminate\Support\Facades\Cache;
class Klarna
{
@@ -68,7 +67,7 @@ class Klarna
'payment_hash' => $this->stripe->payment_hash->hash,
'gateway_type_id' => GatewayType::KLARNA,
],
- ], array_merge($this->stripe->stripe_connect_auth, ['idempotency_key' => uniqid("st",true)]));
+ ], array_merge($this->stripe->stripe_connect_auth, ['idempotency_key' => uniqid("st", true)]));
$data['pi_client_secret'] = $intent->client_secret;
@@ -92,7 +91,7 @@ class Klarna
$this->stripe->payment_hash->data = array_merge((array) $this->stripe->payment_hash->data, $request->all());
$this->stripe->payment_hash->save();
- if (in_array($request->redirect_status, ['succeeded','pending'])) {
+ if (in_array($request->redirect_status, ['succeeded','pending'])) {
return $this->processSuccessfulPayment($request->payment_intent);
}
@@ -101,7 +100,6 @@ class Klarna
public function processSuccessfulPayment(string $payment_intent)
{
-
$this->stripe->init();
//catch duplicate submissions.
diff --git a/app/PaymentDrivers/Stripe/PRZELEWY24.php b/app/PaymentDrivers/Stripe/PRZELEWY24.php
index 190b4e5dce37..206633034944 100644
--- a/app/PaymentDrivers/Stripe/PRZELEWY24.php
+++ b/app/PaymentDrivers/Stripe/PRZELEWY24.php
@@ -56,7 +56,7 @@ class PRZELEWY24
'payment_hash' => $this->stripe->payment_hash->hash,
'gateway_type_id' => GatewayType::PRZELEWY24,
],
- ], array_merge($this->stripe->stripe_connect_auth, ['idempotency_key' => uniqid("st",true)]));
+ ], array_merge($this->stripe->stripe_connect_auth, ['idempotency_key' => uniqid("st", true)]));
$data['pi_client_secret'] = $intent->client_secret;
@@ -80,7 +80,7 @@ class PRZELEWY24
$this->stripe->payment_hash->data = array_merge((array) $this->stripe->payment_hash->data, $request->all());
$this->stripe->payment_hash->save();
- if (in_array($request->redirect_status, ['succeeded','pending'])) {
+ if (in_array($request->redirect_status, ['succeeded','pending'])) {
return $this->processSuccessfulPayment($request->payment_intent);
}
diff --git a/app/PaymentDrivers/Stripe/SEPA.php b/app/PaymentDrivers/Stripe/SEPA.php
index 0500d46ee948..407aac4edc11 100644
--- a/app/PaymentDrivers/Stripe/SEPA.php
+++ b/app/PaymentDrivers/Stripe/SEPA.php
@@ -67,7 +67,7 @@ class SEPA
],
];
- $intent = \Stripe\PaymentIntent::create($intent_data, array_merge($this->stripe->stripe_connect_auth, ['idempotency_key' => uniqid("st",true)]));
+ $intent = \Stripe\PaymentIntent::create($intent_data, array_merge($this->stripe->stripe_connect_auth, ['idempotency_key' => uniqid("st", true)]));
$data['pi_client_secret'] = $intent->client_secret;
diff --git a/app/PaymentDrivers/Stripe/SOFORT.php b/app/PaymentDrivers/Stripe/SOFORT.php
index 276fbe86347b..58067b9d5f18 100644
--- a/app/PaymentDrivers/Stripe/SOFORT.php
+++ b/app/PaymentDrivers/Stripe/SOFORT.php
@@ -56,7 +56,7 @@ class SOFORT
'payment_hash' => $this->stripe->payment_hash->hash,
'gateway_type_id' => GatewayType::SOFORT,
],
- ], array_merge($this->stripe->stripe_connect_auth, ['idempotency_key' => uniqid("st",true)]));
+ ], array_merge($this->stripe->stripe_connect_auth, ['idempotency_key' => uniqid("st", true)]));
$data['pi_client_secret'] = $intent->client_secret;
@@ -77,11 +77,10 @@ class SOFORT
public function paymentResponse($request)
{
-
$this->stripe->payment_hash->data = array_merge((array) $this->stripe->payment_hash->data, $request->all());
$this->stripe->payment_hash->save();
- if (in_array($request->redirect_status, ['succeeded','pending'])) {
+ if (in_array($request->redirect_status, ['succeeded','pending'])) {
return $this->processSuccessfulPayment($request->payment_intent);
}
diff --git a/app/PaymentDrivers/Stripe/UpdatePaymentMethods.php b/app/PaymentDrivers/Stripe/UpdatePaymentMethods.php
index 7df5b27a3042..c52a43ea63bf 100644
--- a/app/PaymentDrivers/Stripe/UpdatePaymentMethods.php
+++ b/app/PaymentDrivers/Stripe/UpdatePaymentMethods.php
@@ -37,31 +37,37 @@ class UpdatePaymentMethods
{
$this->stripe->client = $client;
- $card_methods = PaymentMethod::all([
+ $card_methods = PaymentMethod::all(
+ [
'customer' => $customer->id,
'type' => 'card',
],
- $this->stripe->stripe_connect_auth);
+ $this->stripe->stripe_connect_auth
+ );
foreach ($card_methods as $method) {
$this->addOrUpdateCard($method, $customer->id, $client, GatewayType::CREDIT_CARD);
}
- $alipay_methods = PaymentMethod::all([
+ $alipay_methods = PaymentMethod::all(
+ [
'customer' => $customer->id,
'type' => 'alipay',
],
- $this->stripe->stripe_connect_auth);
+ $this->stripe->stripe_connect_auth
+ );
foreach ($alipay_methods as $method) {
$this->addOrUpdateCard($method, $customer->id, $client, GatewayType::ALIPAY);
}
- $sofort_methods = PaymentMethod::all([
+ $sofort_methods = PaymentMethod::all(
+ [
'customer' => $customer->id,
'type' => 'sofort',
],
- $this->stripe->stripe_connect_auth);
+ $this->stripe->stripe_connect_auth
+ );
foreach ($sofort_methods as $method) {
$this->addOrUpdateCard($method, $customer->id, $client, GatewayType::SOFORT);
@@ -74,8 +80,9 @@ class UpdatePaymentMethods
{
$sources = $customer->sources;
- if(!$customer || is_null($sources) || !property_exists($sources, 'data'))
+ if (!$customer || is_null($sources) || !property_exists($sources, 'data')) {
return;
+ }
foreach ($sources->data as $method) {
$token_exists = ClientGatewayToken::where([
diff --git a/app/PaymentDrivers/Stripe/iDeal.php b/app/PaymentDrivers/Stripe/iDeal.php
index bb36c3b2fb71..dd32756e0be8 100644
--- a/app/PaymentDrivers/Stripe/iDeal.php
+++ b/app/PaymentDrivers/Stripe/iDeal.php
@@ -56,7 +56,7 @@ class iDeal
'payment_hash' => $this->stripe->payment_hash->hash,
'gateway_type_id' => GatewayType::IDEAL,
],
- ], array_merge($this->stripe->stripe_connect_auth, ['idempotency_key' => uniqid("st",true)]));
+ ], array_merge($this->stripe->stripe_connect_auth, ['idempotency_key' => uniqid("st", true)]));
$data['pi_client_secret'] = $intent->client_secret;
@@ -80,7 +80,7 @@ class iDeal
$this->stripe->payment_hash->data = array_merge((array) $this->stripe->payment_hash->data, $request->all());
$this->stripe->payment_hash->save();
- if (in_array($request->redirect_status, ['succeeded','pending'])) {
+ if (in_array($request->redirect_status, ['succeeded','pending'])) {
return $this->processSuccessfulPayment($request->payment_intent);
}
diff --git a/app/PaymentDrivers/StripeConnectPaymentDriver.php b/app/PaymentDrivers/StripeConnectPaymentDriver.php
index 3d33fcf962fa..f6a4b30211c3 100644
--- a/app/PaymentDrivers/StripeConnectPaymentDriver.php
+++ b/app/PaymentDrivers/StripeConnectPaymentDriver.php
@@ -12,34 +12,8 @@
namespace App\PaymentDrivers;
-use App\Factory\PaymentFactory;
-use App\Http\Requests\Payments\PaymentWebhookRequest;
-use App\Http\Requests\Request;
-use App\Jobs\Util\SystemLogger;
use App\Models\Client;
-use App\Models\ClientGatewayToken;
use App\Models\CompanyGateway;
-use App\Models\GatewayType;
-use App\Models\Payment;
-use App\Models\PaymentHash;
-use App\Models\SystemLog;
-use App\PaymentDrivers\Stripe\ACH;
-use App\PaymentDrivers\Stripe\Alipay;
-use App\PaymentDrivers\Stripe\Charge;
-use App\PaymentDrivers\Stripe\CreditCard;
-use App\PaymentDrivers\Stripe\SEPA;
-use App\PaymentDrivers\Stripe\SOFORT;
-use App\PaymentDrivers\Stripe\Utilities;
-use App\Utils\Traits\MakesHash;
-use Exception;
-use Illuminate\Support\Carbon;
-use Stripe\Customer;
-use Stripe\Exception\ApiErrorException;
-use Stripe\PaymentIntent;
-use Stripe\PaymentMethod;
-use Stripe\SetupIntent;
-use Stripe\Stripe;
-use Stripe\StripeClient;
class StripeConnectPaymentDriver extends StripePaymentDriver
{
diff --git a/app/PaymentDrivers/StripePaymentDriver.php b/app/PaymentDrivers/StripePaymentDriver.php
index 71530b9c989b..2e0a352d53f4 100644
--- a/app/PaymentDrivers/StripePaymentDriver.php
+++ b/app/PaymentDrivers/StripePaymentDriver.php
@@ -14,23 +14,19 @@ namespace App\PaymentDrivers;
use App\Exceptions\PaymentFailed;
use App\Exceptions\StripeConnectFailure;
-use App\Factory\PaymentFactory;
use App\Http\Requests\Payments\PaymentWebhookRequest;
use App\Http\Requests\Request;
use App\Jobs\Util\SystemLogger;
use App\Models\ClientGatewayToken;
-use App\Models\Country;
use App\Models\GatewayType;
use App\Models\Payment;
use App\Models\PaymentHash;
-use App\Models\PaymentType;
use App\Models\SystemLog;
use App\PaymentDrivers\Stripe\ACH;
use App\PaymentDrivers\Stripe\ACSS;
use App\PaymentDrivers\Stripe\Alipay;
-use App\PaymentDrivers\Stripe\ApplePay;
-use App\PaymentDrivers\Stripe\BECS;
use App\PaymentDrivers\Stripe\Bancontact;
+use App\PaymentDrivers\Stripe\BECS;
use App\PaymentDrivers\Stripe\BrowserPay;
use App\PaymentDrivers\Stripe\Charge;
use App\PaymentDrivers\Stripe\Connect\Verify;
@@ -38,6 +34,7 @@ use App\PaymentDrivers\Stripe\CreditCard;
use App\PaymentDrivers\Stripe\EPS;
use App\PaymentDrivers\Stripe\FPX;
use App\PaymentDrivers\Stripe\GIROPAY;
+use App\PaymentDrivers\Stripe\iDeal;
use App\PaymentDrivers\Stripe\ImportCustomers;
use App\PaymentDrivers\Stripe\Jobs\PaymentIntentFailureWebhook;
use App\PaymentDrivers\Stripe\Jobs\PaymentIntentProcessingWebhook;
@@ -48,12 +45,9 @@ use App\PaymentDrivers\Stripe\SEPA;
use App\PaymentDrivers\Stripe\SOFORT;
use App\PaymentDrivers\Stripe\UpdatePaymentMethods;
use App\PaymentDrivers\Stripe\Utilities;
-use App\PaymentDrivers\Stripe\iDeal;
use App\Utils\Traits\MakesHash;
use Exception;
-use Google\Service\ServiceConsumerManagement\CustomError;
use Illuminate\Http\RedirectResponse;
-use Illuminate\Support\Carbon;
use Laracasts\Presenter\Exceptions\PresenterException;
use Stripe\Account;
use Stripe\Customer;
@@ -120,14 +114,12 @@ class StripePaymentDriver extends BaseDriver
throw new StripeConnectFailure('Stripe Connect has not been configured');
}
} else {
-
$this->stripe = new StripeClient(
$this->company_gateway->getConfigField('apiKey')
);
Stripe::setApiKey($this->company_gateway->getConfigField('apiKey'));
Stripe::setApiVersion('2022-11-15');
-
}
return $this;
@@ -161,7 +153,7 @@ class StripePaymentDriver extends BaseDriver
if ($this->client
&& isset($this->client->country)
&& in_array($this->client->country->iso_3166_3, ['USA'])
- ) {
+ ) {
$types[] = GatewayType::BANK_TRANSFER;
}
@@ -355,30 +347,22 @@ class StripePaymentDriver extends BaseDriver
}
if ($this->company_gateway->require_custom_value1) {
-
$fields[] = ['name' => 'client_custom_value1', 'label' => $this->helpers->makeCustomField($this->client->company->custom_fields, 'client1'), 'type' => 'text', 'validation' => 'required'];
-
}
if ($this->company_gateway->require_custom_value2) {
-
$fields[] = ['name' => 'client_custom_value2', 'label' => $this->helpers->makeCustomField($this->client->company->custom_fields, 'client2'), 'type' => 'text', 'validation' => 'required'];
-
}
if ($this->company_gateway->require_custom_value3) {
-
$fields[] = ['name' => 'client_custom_value3', 'label' => $this->helpers->makeCustomField($this->client->company->custom_fields, 'client3'), 'type' => 'text', 'validation' => 'required'];
-
}
if ($this->company_gateway->require_custom_value4) {
-
$fields[] = ['name' => 'client_custom_value4', 'label' => $this->helpers->makeCustomField($this->client->company->custom_fields, 'client4'), 'type' => 'text', 'validation' => 'required'];
-
}
@@ -436,7 +420,7 @@ class StripePaymentDriver extends BaseDriver
$meta = $this->stripe_connect_auth;
- return PaymentIntent::create($data, array_merge($meta, ['idempotency_key' => uniqid("st",true)]));
+ return PaymentIntent::create($data, array_merge($meta, ['idempotency_key' => uniqid("st", true)]));
}
/**
@@ -453,7 +437,7 @@ class StripePaymentDriver extends BaseDriver
$params = ['usage' => 'off_session'];
$meta = $this->stripe_connect_auth;
- return SetupIntent::create($params, array_merge($meta, ['idempotency_key' => uniqid("st",true)]));
+ return SetupIntent::create($params, array_merge($meta, ['idempotency_key' => uniqid("st", true)]));
}
/**
@@ -530,7 +514,7 @@ class StripePaymentDriver extends BaseDriver
$data['address']['state'] = $this->client->state;
$data['address']['country'] = $this->client->country ? $this->client->country->iso_3166_2 : '';
- $customer = Customer::create($data, array_merge($this->stripe_connect_auth, ['idempotency_key' => uniqid("st",true)]));
+ $customer = Customer::create($data, array_merge($this->stripe_connect_auth, ['idempotency_key' => uniqid("st", true)]));
if (! $customer) {
throw new Exception('Unable to create gateway customer');
@@ -565,9 +549,7 @@ class StripePaymentDriver extends BaseDriver
public function updateCustomer()
{
- if($this->client)
- {
-
+ if ($this->client) {
$customer = $this->findOrCreateCustomer();
//Else create a new record
$data['name'] = $this->client->present()->name();
@@ -589,7 +571,6 @@ class StripePaymentDriver extends BaseDriver
$data['shipping']['address']['country'] = $this->client->shipping_country ? $this->client->shipping_country->iso_3166_2 : '';
\Stripe\Customer::update($customer->id, $data, $this->stripe_connect_auth);
-
}
}
@@ -659,12 +640,12 @@ class StripePaymentDriver extends BaseDriver
// if($request->type === 'payment_intent.requires_action')
// nlog($request->all());
- if($request->type === 'customer.source.updated') {
+ if ($request->type === 'customer.source.updated') {
$ach = new ACH($this);
$ach->updateBankAccount($request->all());
}
- if($request->type === 'payment_intent.processing') {
+ if ($request->type === 'payment_intent.processing') {
PaymentIntentProcessingWebhook::dispatch($request->data, $request->company_key, $this->company_gateway->id)->delay(now()->addSeconds(2));
return response()->json([], 200);
}
@@ -719,17 +700,14 @@ class StripePaymentDriver extends BaseDriver
], $this->stripe_connect_auth);
if ($charge->captured) {
-
$payment = false;
- if(isset($transaction['payment_intent']))
- {
+ if (isset($transaction['payment_intent'])) {
$payment = Payment::query()
->where('transaction_reference', $transaction['payment_intent'])
->where('company_id', $request->getCompany()->id)
->first();
- }
- elseif(isset($transaction['id'])) {
+ } elseif (isset($transaction['id'])) {
$payment = Payment::query()
->where('transaction_reference', $transaction['id'])
->where('company_id', $request->getCompany()->id)
@@ -770,14 +748,17 @@ class StripePaymentDriver extends BaseDriver
} catch (ApiErrorException | Exception $e) {
nlog($e->getMessage());
- SystemLogger::dispatch([
+ SystemLogger::dispatch(
+ [
'server_response' => $e->getMessage(),
'data' => request()->all(),
],
- SystemLog::CATEGORY_GATEWAY_RESPONSE,
- SystemLog::EVENT_GATEWAY_FAILURE,
- SystemLog::TYPE_STRIPE,
- $this->client, $this->client->company);
+ SystemLog::CATEGORY_GATEWAY_RESPONSE,
+ SystemLog::EVENT_GATEWAY_FAILURE,
+ SystemLog::TYPE_STRIPE,
+ $this->client,
+ $this->client->company
+ );
}
}
@@ -798,14 +779,17 @@ class StripePaymentDriver extends BaseDriver
} catch (ApiErrorException | Exception $e) {
nlog($e->getMessage());
- SystemLogger::dispatch([
+ SystemLogger::dispatch(
+ [
'server_response' => $e->getMessage(),
'data' => request()->all(),
],
- SystemLog::CATEGORY_GATEWAY_RESPONSE,
- SystemLog::EVENT_GATEWAY_FAILURE,
- SystemLog::TYPE_STRIPE,
- $this->client, $this->client->company);
+ SystemLog::CATEGORY_GATEWAY_RESPONSE,
+ SystemLog::EVENT_GATEWAY_FAILURE,
+ SystemLog::TYPE_STRIPE,
+ $this->client,
+ $this->client->company
+ );
}
}
diff --git a/app/PaymentDrivers/WePay/ACH.php b/app/PaymentDrivers/WePay/ACH.php
index 8b5e91131324..7143bda330a0 100644
--- a/app/PaymentDrivers/WePay/ACH.php
+++ b/app/PaymentDrivers/WePay/ACH.php
@@ -19,11 +19,9 @@ use App\Models\GatewayType;
use App\Models\Payment;
use App\Models\SystemLog;
use App\Notifications\Ninja\WePayFailureNotification;
-use App\PaymentDrivers\WePay\WePayCommon;
use App\PaymentDrivers\WePayPaymentDriver;
use App\Utils\Traits\MakesHash;
use Illuminate\Http\Request;
-use Illuminate\Notifications\Messages\SlackMessage;
use Illuminate\Support\Str;
class ACH
diff --git a/app/PaymentDrivers/WePay/CreditCard.php b/app/PaymentDrivers/WePay/CreditCard.php
index f7b5f6ecd7bc..6d1c00a6b969 100644
--- a/app/PaymentDrivers/WePay/CreditCard.php
+++ b/app/PaymentDrivers/WePay/CreditCard.php
@@ -17,9 +17,7 @@ use App\Http\Requests\ClientPortal\Payments\PaymentResponseRequest;
use App\Jobs\Util\SystemLogger;
use App\Models\GatewayType;
use App\Models\Payment;
-use App\Models\PaymentType;
use App\Models\SystemLog;
-use App\PaymentDrivers\WePay\WePayCommon;
use App\PaymentDrivers\WePayPaymentDriver;
use Illuminate\Support\Str;
diff --git a/app/PaymentDrivers/WePay/Setup.php b/app/PaymentDrivers/WePay/Setup.php
index 66ca2b29c99a..e8af7f5e9d7d 100644
--- a/app/PaymentDrivers/WePay/Setup.php
+++ b/app/PaymentDrivers/WePay/Setup.php
@@ -12,7 +12,6 @@
namespace App\PaymentDrivers\WePay;
use App\PaymentDrivers\WePayPaymentDriver;
-use Illuminate\Http\Request;
class Setup
{
diff --git a/app/PaymentDrivers/WePayPaymentDriver.php b/app/PaymentDrivers/WePayPaymentDriver.php
index 862329adeea9..fde608b67937 100644
--- a/app/PaymentDrivers/WePayPaymentDriver.php
+++ b/app/PaymentDrivers/WePayPaymentDriver.php
@@ -345,29 +345,21 @@ class WePayPaymentDriver extends BaseDriver
if ($this->company_gateway->require_custom_value1) {
-
$fields[] = ['name' => 'client_custom_value1', 'label' => $this->helpers->makeCustomField($this->client->company->custom_fields, 'client1'), 'type' => 'text', 'validation' => 'required'];
-
}
if ($this->company_gateway->require_custom_value2) {
-
$fields[] = ['name' => 'client_custom_value2', 'label' => $this->helpers->makeCustomField($this->client->company->custom_fields, 'client2'), 'type' => 'text', 'validation' => 'required'];
-
}
if ($this->company_gateway->require_custom_value3) {
-
$fields[] = ['name' => 'client_custom_value3', 'label' => $this->helpers->makeCustomField($this->client->company->custom_fields, 'client3'), 'type' => 'text', 'validation' => 'required'];
-
}
if ($this->company_gateway->require_custom_value4) {
-
$fields[] = ['name' => 'client_custom_value4', 'label' => $this->helpers->makeCustomField($this->client->company->custom_fields, 'client4'), 'type' => 'text', 'validation' => 'required'];
-
}
diff --git a/app/Policies/EntityPolicy.php b/app/Policies/EntityPolicy.php
index 621f8668380a..f5c6f33fc5ea 100644
--- a/app/Policies/EntityPolicy.php
+++ b/app/Policies/EntityPolicy.php
@@ -32,7 +32,7 @@ class EntityPolicy
public function before($user, $ability)
{
//if($user->isAdmin())
- // return true;
+ // return true;
}
/**
diff --git a/app/Policies/WebhookPolicy.php b/app/Policies/WebhookPolicy.php
index 36344a1c0bd5..2bdb0713b2b6 100644
--- a/app/Policies/WebhookPolicy.php
+++ b/app/Policies/WebhookPolicy.php
@@ -28,5 +28,4 @@ class WebhookPolicy extends EntityPolicy
{
return $user->isAdmin();
}
-
}
diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php
index a0c93ab683fb..92e3bbee8124 100644
--- a/app/Providers/AppServiceProvider.php
+++ b/app/Providers/AppServiceProvider.php
@@ -40,7 +40,6 @@ class AppServiceProvider extends ServiceProvider
*/
public function boot()
{
-
// DB::listen(function($query) {
// nlog(
// $query->sql,
@@ -94,18 +93,15 @@ class AppServiceProvider extends ServiceProvider
});
Mailer::macro('postmark_config', function (string $postmark_key) {
-
Mailer::setSymfonyTransport(app('mail.manager')->createSymfonyTransport([
'transport' => 'postmark',
'token' => $postmark_key
]));
return $this;
-
});
Mailer::macro('mailgun_config', function ($secret, $domain) {
-
Mailer::setSymfonyTransport(app('mail.manager')->createSymfonyTransport([
'transport' => 'mailgun',
'secret' => $secret,
@@ -124,7 +120,5 @@ class AppServiceProvider extends ServiceProvider
ParallelTesting::setUpTestDatabase(function ($database, $token) {
Artisan::call('db:seed');
});
-
}
-
}
diff --git a/app/Providers/EventServiceProvider.php b/app/Providers/EventServiceProvider.php
index 11671d396697..1b7d2ba1a4d4 100644
--- a/app/Providers/EventServiceProvider.php
+++ b/app/Providers/EventServiceProvider.php
@@ -65,7 +65,6 @@ use App\Events\PurchaseOrder\PurchaseOrderWasArchived;
use App\Events\PurchaseOrder\PurchaseOrderWasCreated;
use App\Events\PurchaseOrder\PurchaseOrderWasDeleted;
use App\Events\PurchaseOrder\PurchaseOrderWasEmailed;
-use App\Events\PurchaseOrder\PurchaseOrderWasMarkedSent;
use App\Events\PurchaseOrder\PurchaseOrderWasRestored;
use App\Events\PurchaseOrder\PurchaseOrderWasUpdated;
use App\Events\PurchaseOrder\PurchaseOrderWasViewed;
@@ -163,8 +162,8 @@ use App\Listeners\Invoice\InvoiceCancelledActivity;
use App\Listeners\Invoice\InvoiceCreatedNotification;
use App\Listeners\Invoice\InvoiceDeletedActivity;
use App\Listeners\Invoice\InvoiceEmailActivity;
-use App\Listeners\Invoice\InvoiceEmailFailedActivity;
use App\Listeners\Invoice\InvoiceEmailedNotification;
+use App\Listeners\Invoice\InvoiceEmailFailedActivity;
use App\Listeners\Invoice\InvoiceFailedEmailNotification;
use App\Listeners\Invoice\InvoicePaidActivity;
use App\Listeners\Invoice\InvoiceReminderEmailActivity;
@@ -174,8 +173,8 @@ use App\Listeners\Invoice\InvoiceViewedActivity;
use App\Listeners\Invoice\UpdateInvoiceActivity;
use App\Listeners\Mail\MailSentListener;
use App\Listeners\Misc\InvitationViewedListener;
-use App\Listeners\Payment\PaymentEmailFailureActivity;
use App\Listeners\Payment\PaymentEmailedActivity;
+use App\Listeners\Payment\PaymentEmailFailureActivity;
use App\Listeners\Payment\PaymentNotification;
use App\Listeners\Payment\PaymentRestoredActivity;
use App\Listeners\PurchaseOrder\CreatePurchaseOrderActivity;
@@ -188,7 +187,6 @@ use App\Listeners\PurchaseOrder\PurchaseOrderEmailActivity;
use App\Listeners\PurchaseOrder\PurchaseOrderEmailedNotification;
use App\Listeners\PurchaseOrder\PurchaseOrderRestoredActivity;
use App\Listeners\PurchaseOrder\PurchaseOrderViewedActivity;
-use App\Listeners\PurchaseOrder\PurchaseOrderViewedNotification;
use App\Listeners\PurchaseOrder\UpdatePurchaseOrderActivity;
use App\Listeners\Quote\QuoteApprovedActivity;
use App\Listeners\Quote\QuoteApprovedNotification;
@@ -221,8 +219,8 @@ use App\Listeners\User\ArchivedUserActivity;
use App\Listeners\User\CreatedUserActivity;
use App\Listeners\User\DeletedUserActivity;
use App\Listeners\User\RestoredUserActivity;
-use App\Listeners\User\UpdateUserLastLogin;
use App\Listeners\User\UpdatedUserActivity;
+use App\Listeners\User\UpdateUserLastLogin;
use App\Models\Account;
use App\Models\Client;
use App\Models\ClientContact;
diff --git a/app/Providers/MailCssInlinerServiceProvider.php b/app/Providers/MailCssInlinerServiceProvider.php
index de53679d80fb..c1c5984c1c93 100644
--- a/app/Providers/MailCssInlinerServiceProvider.php
+++ b/app/Providers/MailCssInlinerServiceProvider.php
@@ -12,8 +12,6 @@
namespace App\Providers;
use App\Utils\CssInlinerPlugin;
-use Illuminate\Container\Container;
-use Illuminate\Mail\MailManager;
use Illuminate\Support\ServiceProvider;
class MailCssInlinerServiceProvider extends ServiceProvider
diff --git a/app/Providers/NinjaTranslationServiceProvider.php b/app/Providers/NinjaTranslationServiceProvider.php
index 0c7676f263bb..a9d83915d5f6 100644
--- a/app/Providers/NinjaTranslationServiceProvider.php
+++ b/app/Providers/NinjaTranslationServiceProvider.php
@@ -18,7 +18,6 @@ class NinjaTranslationServiceProvider extends TranslationServiceProvider
{
public function boot()
{
-
/*
* To reset the translator instance we call
*
diff --git a/app/Providers/RouteServiceProvider.php b/app/Providers/RouteServiceProvider.php
index 5fdacb276c3d..e476a7943ecb 100644
--- a/app/Providers/RouteServiceProvider.php
+++ b/app/Providers/RouteServiceProvider.php
@@ -31,7 +31,6 @@ class RouteServiceProvider extends ServiceProvider
parent::boot();
Route::bind('task_scheduler', function ($value) {
-
if (is_numeric($value)) {
throw new ModelNotFoundException("Record with value {$value} not found");
}
@@ -40,10 +39,7 @@ class RouteServiceProvider extends ServiceProvider
->withTrashed()
->company()
->where('id', $this->decodePrimaryKey($value))->firstOrFail();
-
});
-
-
}
/**
diff --git a/app/Repositories/ActivityRepository.php b/app/Repositories/ActivityRepository.php
index b90c6751835f..91ede279b5fd 100644
--- a/app/Repositories/ActivityRepository.php
+++ b/app/Repositories/ActivityRepository.php
@@ -60,7 +60,7 @@ class ActivityRepository extends BaseRepository
$activity->save();
//rate limiter
- $this->createBackup($entity, $activity);
+ $this->createBackup($entity, $activity);
}
/**
diff --git a/app/Repositories/BankIntegrationRepository.php b/app/Repositories/BankIntegrationRepository.php
index 8eabfd05176b..d4d8d543ce12 100644
--- a/app/Repositories/BankIntegrationRepository.php
+++ b/app/Repositories/BankIntegrationRepository.php
@@ -12,23 +12,18 @@
namespace App\Repositories;
use App\Models\BankIntegration;
-use App\Models\Task;
-use App\Models\TaskStatus;
/**
* Class for bank integration repository.
*/
class BankIntegrationRepository extends BaseRepository
{
-
public function save($data, BankIntegration $bank_integration)
{
-
//stub to store
$bank_integration->fill($data);
$bank_integration->save();
return $bank_integration->fresh();
}
-
}
diff --git a/app/Repositories/BankTransactionRepository.php b/app/Repositories/BankTransactionRepository.php
index 35e2ea73e1f6..2f2cd569dc22 100644
--- a/app/Repositories/BankTransactionRepository.php
+++ b/app/Repositories/BankTransactionRepository.php
@@ -13,20 +13,17 @@ namespace App\Repositories;
use App\Jobs\Bank\MatchBankTransactions;
use App\Models\BankTransaction;
-use App\Models\Task;
-use App\Models\TaskStatus;
/**
* Class for bank transaction repository.
*/
class BankTransactionRepository extends BaseRepository
{
-
public function save($data, BankTransaction $bank_transaction)
{
-
- if(array_key_exists('bank_integration_id', $data))
+ if (array_key_exists('bank_integration_id', $data)) {
$bank_transaction->bank_integration_id = $data['bank_integration_id'];
+ }
$bank_transaction->fill($data);
$bank_transaction->save();
@@ -38,16 +35,10 @@ class BankTransactionRepository extends BaseRepository
public function convert_matched($bank_transactions)
{
-
- $data['transactions'] = $bank_transactions->map(function ($bt){
+ $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(auth()->user()->company()->id, auth()->user()->company()->db, $data))->handle();
-
-
}
-
-
}
diff --git a/app/Repositories/BankTransactionRuleRepository.php b/app/Repositories/BankTransactionRuleRepository.php
index 87c2c3170578..4d8d1515e2f8 100644
--- a/app/Repositories/BankTransactionRuleRepository.php
+++ b/app/Repositories/BankTransactionRuleRepository.php
@@ -12,24 +12,18 @@
namespace App\Repositories;
use App\Models\BankTransactionRule;
-use App\Models\Task;
-use App\Models\TaskStatus;
/**
* Class for bank transaction rule repository.
*/
class BankTransactionRuleRepository extends BaseRepository
{
-
public function save($data, BankTransactionRule $bank_transaction_rule)
{
-
$bank_transaction_rule->fill($data);
$bank_transaction_rule->save();
return $bank_transaction_rule;
-
}
-
}
diff --git a/app/Repositories/BaseRepository.php b/app/Repositories/BaseRepository.php
index 713559736639..3678a789829a 100644
--- a/app/Repositories/BaseRepository.php
+++ b/app/Repositories/BaseRepository.php
@@ -12,33 +12,24 @@
namespace App\Repositories;
use App\Jobs\Product\UpdateOrCreateProduct;
-use App\Jobs\Util\WebhookHandler;
use App\Models\Client;
use App\Models\ClientContact;
use App\Models\Company;
use App\Models\Credit;
-use App\Models\Expense;
use App\Models\Invoice;
-use App\Models\Payment;
-use App\Models\Project;
use App\Models\Quote;
use App\Models\RecurringInvoice;
-use App\Models\Task;
-use App\Models\Vendor;
-use App\Models\Webhook;
use App\Utils\Helpers;
use App\Utils\Ninja;
use App\Utils\Traits\MakesHash;
use App\Utils\Traits\SavesDocuments;
-use Google\Service\Vision\Property;
-use ReflectionClass;
class BaseRepository
{
use MakesHash;
use SavesDocuments;
- public bool $import_mode = false;
+ public bool $import_mode = false;
private bool $new_model = false;
/**
@@ -68,7 +59,6 @@ class BaseRepository
if (class_exists($className)) {
event(new $className($entity, $entity->company, Ninja::eventVars(auth()->user() ? auth()->user()->id : null)));
}
-
}
/**
@@ -95,7 +85,6 @@ class BaseRepository
if (class_exists($className)) {
event(new $className($entity, $fromDeleted, $entity->company, Ninja::eventVars(auth()->user() ? auth()->user()->id : null)));
}
-
}
/**
@@ -122,8 +111,9 @@ class BaseRepository
/* Returns an invoice if defined as a key in the $resource array*/
public function getInvitation($invitation, $resource)
{
- if (is_array($invitation) && ! array_key_exists('key', $invitation))
+ if (is_array($invitation) && ! array_key_exists('key', $invitation)) {
return false;
+ }
$invitation_class = sprintf('App\\Models\\%sInvitation', $resource);
@@ -158,8 +148,9 @@ class BaseRepository
protected function alternativeSave($data, $model)
{ //$start = microtime(true);
//forces the client_id if it doesn't exist
- if(array_key_exists('client_id', $data))
+ if (array_key_exists('client_id', $data)) {
$model->client_id = $data['client_id'];
+ }
$client = Client::with('group_settings')->where('id', $model->client_id)->withTrashed()->firstOrFail();
@@ -180,11 +171,13 @@ class BaseRepository
$tmp_data = $data; //preserves the $data array
/* We need to unset some variable as we sometimes unguard the model */
- if (isset($tmp_data['invitations']))
+ if (isset($tmp_data['invitations'])) {
unset($tmp_data['invitations']);
+ }
- if (isset($tmp_data['client_contacts']))
+ if (isset($tmp_data['client_contacts'])) {
unset($tmp_data['client_contacts']);
+ }
$model->fill($tmp_data);
@@ -193,17 +186,14 @@ class BaseRepository
$model->custom_surcharge_tax3 = $client->company->custom_surcharge_taxes3;
$model->custom_surcharge_tax4 = $client->company->custom_surcharge_taxes4;
- if(!$model->id){
+ if (!$model->id) {
$this->new_model = true;
- if(is_array($model->line_items) && !($model instanceof RecurringInvoice))
- {
- $model->line_items = (collect($model->line_items))->map(function ($item) use($model,$client) {
-
+ if (is_array($model->line_items) && !($model instanceof RecurringInvoice)) {
+ $model->line_items = (collect($model->line_items))->map(function ($item) use ($model, $client) {
$item->notes = Helpers::processReservedKeywords($item->notes, $client);
return $item;
-
});
}
}
@@ -212,15 +202,18 @@ class BaseRepository
/* Model now persisted, now lets do some child tasks */
- if($model instanceof Invoice)
+ if ($model instanceof Invoice) {
$model->service()->setReminder()->save();
+ }
/* Save any documents */
- if (array_key_exists('documents', $data))
+ if (array_key_exists('documents', $data)) {
$this->saveDocuments($data['documents'], $model);
+ }
- if (array_key_exists('file', $data))
+ if (array_key_exists('file', $data)) {
$this->saveDocuments($data['file'], $model);
+ }
/* If invitations are present we need to filter existing invitations with the new ones */
if (isset($data['invitations'])) {
@@ -231,25 +224,22 @@ class BaseRepository
$invitation_class = sprintf('App\\Models\\%sInvitation', $resource);
$invitation = $invitation_class::where('key', $invitation)->first();
- if ($invitation){
+ if ($invitation) {
$invitation->delete();
}
-
});
foreach ($data['invitations'] as $invitation) {
-
//if no invitations are present - create one.
if (! $this->getInvitation($invitation, $resource)) {
-
- if (isset($invitation['id']))
+ if (isset($invitation['id'])) {
unset($invitation['id']);
+ }
//make sure we are creating an invite for a contact who belongs to the client only!
$contact = ClientContact::find($invitation['client_contact_id']);
if ($contact && $model->client_id == $contact->client_id) {
-
$invitation_class = sprintf('App\\Models\\%sInvitation', $resource);
$new_invitation = $invitation_class::withTrashed()
@@ -259,16 +249,13 @@ class BaseRepository
if ($new_invitation && $new_invitation->trashed()) {
$new_invitation->restore();
-
} else {
-
$invitation_factory_class = sprintf('App\\Factory\\%sInvitationFactory', $resource);
$new_invitation = $invitation_factory_class::create($model->company_id, $model->user_id);
$new_invitation->{$lcfirst_resource_id} = $model->id;
$new_invitation->client_contact_id = $contact->id;
$new_invitation->key = $this->createDbHash($model->company->db);
$new_invitation->saveQuietly();
-
}
}
}
@@ -276,8 +263,9 @@ class BaseRepository
}
/* If no invitations have been created, this is our fail safe to maintain state*/
- if ($model->invitations()->count() == 0)
+ if ($model->invitations()->count() == 0) {
$model->service()->createInvitations();
+ }
/* Recalculate invoice amounts */
$model = $model->calc()->getInvoice();
@@ -289,85 +277,88 @@ class BaseRepository
$model = $model->service()->applyNumber()->save();
/* Handle attempts where the deposit is greater than the amount/balance of the invoice */
- if((int)$model->balance != 0 && $model->partial > $model->amount && $model->amount > 0)
+ if ((int)$model->balance != 0 && $model->partial > $model->amount && $model->amount > 0) {
$model->partial = min($model->amount, $model->balance);
+ }
/* Update product details if necessary - if we are inside a transaction - do nothing */
- if ($model->company->update_products && $model->id && \DB::transactionLevel() == 0)
+ if ($model->company->update_products && $model->id && \DB::transactionLevel() == 0) {
UpdateOrCreateProduct::dispatch($model->line_items, $model, $model->company);
+ }
/* Perform model specific tasks */
if ($model instanceof Invoice) {
-
if (($state['finished_amount'] != $state['starting_amount']) && ($model->status_id != Invoice::STATUS_DRAFT)) {
-
$model->service()->updateStatus()->save();
$model->client->service()->updateBalance(($state['finished_amount'] - $state['starting_amount']))->save();
$model->ledger()->updateInvoiceBalance(($state['finished_amount'] - $state['starting_amount']), "Update adjustment for invoice {$model->number}");
-
}
- if (! $model->design_id)
+ if (! $model->design_id) {
$model->design_id = $this->decodePrimaryKey($client->getSetting('invoice_design_id'));
+ }
//links tasks and expenses back to the invoice, but only if we are not in the middle of a transaction.
- if (\DB::transactionLevel() == 0)
+ if (\DB::transactionLevel() == 0) {
$model->service()->linkEntities()->save();
+ }
- if($this->new_model)
+ if ($this->new_model) {
event('eloquent.created: App\Models\Invoice', $model);
- else
+ } else {
event('eloquent.updated: App\Models\Invoice', $model);
-
+ }
}
if ($model instanceof Credit) {
-
$model = $model->calc()->getCredit();
- if (! $model->design_id)
+ if (! $model->design_id) {
$model->design_id = $this->decodePrimaryKey($client->getSetting('credit_design_id'));
-
- if(array_key_exists('invoice_id', $data) && $data['invoice_id'])
- $model->invoice_id = $data['invoice_id'];
-
- if($this->new_model)
- event('eloquent.created: App\Models\Credit', $model);
- else
- event('eloquent.updated: App\Models\Credit', $model);
-
- if (($state['finished_amount'] != $state['starting_amount']) && ($model->status_id != Credit::STATUS_DRAFT)) {
-
- $model->client->service()->adjustCreditBalance(($state['finished_amount'] - $state['starting_amount']))->save();
}
+ if (array_key_exists('invoice_id', $data) && $data['invoice_id']) {
+ $model->invoice_id = $data['invoice_id'];
+ }
+
+ if ($this->new_model) {
+ event('eloquent.created: App\Models\Credit', $model);
+ } else {
+ event('eloquent.updated: App\Models\Credit', $model);
+ }
+
+ if (($state['finished_amount'] != $state['starting_amount']) && ($model->status_id != Credit::STATUS_DRAFT)) {
+ $model->client->service()->adjustCreditBalance(($state['finished_amount'] - $state['starting_amount']))->save();
+ }
}
if ($model instanceof Quote) {
-
- if (! $model->design_id)
+ if (! $model->design_id) {
$model->design_id = $this->decodePrimaryKey($client->getSetting('quote_design_id'));
+ }
$model = $model->calc()->getQuote();
- if($this->new_model)
+ if ($this->new_model) {
event('eloquent.created: App\Models\Quote', $model);
- else
+ } else {
event('eloquent.updated: App\Models\Quote', $model);
+ }
}
if ($model instanceof RecurringInvoice) {
-
- if (! $model->design_id)
+ if (! $model->design_id) {
$model->design_id = $this->decodePrimaryKey($client->getSetting('invoice_design_id'));
+ }
$model = $model->calc()->getRecurringInvoice();
- if($this->new_model)
+ if ($this->new_model) {
event('eloquent.created: App\Models\RecurringInvoice', $model);
- else
+ } else {
event('eloquent.updated: App\Models\RecurringInvoice', $model);
+ }
}
$model->saveQuietly();
diff --git a/app/Repositories/ClientContactRepository.php b/app/Repositories/ClientContactRepository.php
index 5356175e792a..ed1b81be267c 100644
--- a/app/Repositories/ClientContactRepository.php
+++ b/app/Repositories/ClientContactRepository.php
@@ -30,19 +30,12 @@ class ClientContactRepository extends BaseRepository
{
//06-09-2022 sometimes users pass a contact object instead of a nested array, this sequence handles this scenario
if (isset($data['contacts']) && (count($data['contacts']) !== count($data['contacts'], COUNT_RECURSIVE))) {
-
$contacts = collect($data['contacts']);
-
- } elseif(isset($data['contacts'])){
-
+ } elseif (isset($data['contacts'])) {
$temp_array[] = $data['contacts'];
$contacts = collect($temp_array);
-
- }
- else {
-
+ } else {
$contacts = collect();
-
}
$client->contacts->pluck('id')->diff($contacts->pluck('id'))->each(function ($contact) {
@@ -56,7 +49,6 @@ class ClientContactRepository extends BaseRepository
/* Set first record to primary - always */
$contacts = $contacts->sortByDesc('is_primary')->map(function ($contact) {
-
$contact['is_primary'] = $this->is_primary;
$this->is_primary = false;
diff --git a/app/Repositories/ClientRepository.php b/app/Repositories/ClientRepository.php
index d776977c48e3..851dd83e7d06 100644
--- a/app/Repositories/ClientRepository.php
+++ b/app/Repositories/ClientRepository.php
@@ -14,7 +14,6 @@ namespace App\Repositories;
use App\Factory\ClientFactory;
use App\Models\Client;
use App\Models\Company;
-use App\Utils\Traits\ClientGroupSettingsSaver;
use App\Utils\Traits\GeneratesCounter;
use App\Utils\Traits\SavesDocuments;
use Illuminate\Database\QueryException;
@@ -79,7 +78,6 @@ class ClientRepository extends BaseRepository
$client->save();
if (! isset($client->number) || empty($client->number) || strlen($client->number) == 0) {
-
$x = 1;
do {
@@ -104,8 +102,9 @@ class ClientRepository extends BaseRepository
//24-01-2023 when a logo is uploaded, no other data is set, so we need to catch here and not update
//the contacts array UNLESS there are no contacts and we need to maintain state.
- if(array_key_exists('contacts', $contact_data) || $client->contacts()->count() == 0)
+ if (array_key_exists('contacts', $contact_data) || $client->contacts()->count() == 0) {
$this->contact_repo->save($contact_data, $client);
+ }
return $client;
}
diff --git a/app/Repositories/CreditRepository.php b/app/Repositories/CreditRepository.php
index 572fb85dc470..f5097e8f9adf 100644
--- a/app/Repositories/CreditRepository.php
+++ b/app/Repositories/CreditRepository.php
@@ -53,7 +53,6 @@ class CreditRepository extends BaseRepository
$credit = $credit->service()->deleteCredit()->save();
return parent::delete($credit);
-
}
public function restore($credit)
@@ -69,5 +68,4 @@ class CreditRepository extends BaseRepository
return $credit;
}
-
}
diff --git a/app/Repositories/DocumentRepository.php b/app/Repositories/DocumentRepository.php
index 74206fa6f117..2740c847a54c 100644
--- a/app/Repositories/DocumentRepository.php
+++ b/app/Repositories/DocumentRepository.php
@@ -12,7 +12,6 @@
namespace App\Repositories;
use App\Models\Document;
-use App\Utils\Ninja;
/**
* Class for document repository.
@@ -27,7 +26,6 @@ class DocumentRepository extends BaseRepository
public function restore($document)
{
-
// if (! $document->trashed()) {
// return;
// }
diff --git a/app/Repositories/ExpenseRepository.php b/app/Repositories/ExpenseRepository.php
index e83d8c608f58..3d7c2a08285c 100644
--- a/app/Repositories/ExpenseRepository.php
+++ b/app/Repositories/ExpenseRepository.php
@@ -17,8 +17,8 @@ use App\Libraries\Currency\Conversion\CurrencyApi;
use App\Models\Expense;
use App\Utils\Traits\GeneratesCounter;
use Carbon\Exceptions\InvalidFormatException;
-use Illuminate\Support\Carbon;
use Illuminate\Database\QueryException;
+use Illuminate\Support\Carbon;
/**
* ExpenseRepository.
@@ -35,7 +35,7 @@ class ExpenseRepository extends BaseRepository
* @param array $data The data
* @param \App\Models\Expense $expense The expense
*
- * @return \App\Models\Expense
+ * @return \App\Models\Expense
*/
public function save(array $data, Expense $expense): Expense
{
@@ -45,8 +45,9 @@ class ExpenseRepository extends BaseRepository
$expense = $this->processExchangeRates($data, $expense);
}
- if (empty($expense->number))
+ if (empty($expense->number)) {
$expense = $this->findAndSaveNumber($expense);
+ }
$expense->saveQuietly();
@@ -73,10 +74,10 @@ class ExpenseRepository extends BaseRepository
}
/**
- * @param mixed $data
- * @param mixed $expense
- * @return Expense
- * @throws InvalidFormatException
+ * @param mixed $data
+ * @param mixed $expense
+ * @return Expense
+ * @throws InvalidFormatException
*/
public function processExchangeRates($data, $expense): Expense
{
@@ -106,23 +107,20 @@ class ExpenseRepository extends BaseRepository
*/
private function findAndSaveNumber($expense): Expense
{
-
$x = 1;
do {
-
try {
-
$expense->number = $this->getNextExpenseNumber($expense);
$expense->saveQuietly();
$this->completed = false;
} catch (QueryException $e) {
-
$x++;
- if ($x > 50)
+ if ($x > 50) {
$this->completed = false;
+ }
}
} while ($this->completed);
diff --git a/app/Repositories/Migration/InvoiceMigrationRepository.php b/app/Repositories/Migration/InvoiceMigrationRepository.php
index 5f5d53e05604..40725e62020e 100644
--- a/app/Repositories/Migration/InvoiceMigrationRepository.php
+++ b/app/Repositories/Migration/InvoiceMigrationRepository.php
@@ -11,7 +11,6 @@
namespace App\Repositories\Migration;
-use App\Jobs\Product\UpdateOrCreateProduct;
use App\Models\Client;
use App\Models\ClientContact;
use App\Models\Credit;
diff --git a/app/Repositories/Migration/PaymentMigrationRepository.php b/app/Repositories/Migration/PaymentMigrationRepository.php
index cd25c7ade5fe..11d40e8f976c 100644
--- a/app/Repositories/Migration/PaymentMigrationRepository.php
+++ b/app/Repositories/Migration/PaymentMigrationRepository.php
@@ -69,7 +69,6 @@ class PaymentMigrationRepository extends BaseRepository
*/
private function applyPayment(array $data, Payment $payment): ?Payment
{
-
//check currencies here and fill the exchange rate data if necessary
if (! $payment->id) {
$this->processExchangeRates($data, $payment);
diff --git a/app/Repositories/PaymentRepository.php b/app/Repositories/PaymentRepository.php
index 7d06feb822d6..305cdbd28bf3 100644
--- a/app/Repositories/PaymentRepository.php
+++ b/app/Repositories/PaymentRepository.php
@@ -14,13 +14,11 @@ namespace App\Repositories;
use App\Events\Payment\PaymentWasCreated;
use App\Events\Payment\PaymentWasDeleted;
use App\Jobs\Credit\ApplyCreditPayment;
-use App\Jobs\Ninja\TransactionLog;
use App\Libraries\Currency\Conversion\CurrencyApi;
use App\Models\Client;
use App\Models\Credit;
use App\Models\Invoice;
use App\Models\Payment;
-use App\Models\TransactionEvent;
use App\Utils\Ninja;
use App\Utils\Traits\MakesHash;
use App\Utils\Traits\SavesDocuments;
@@ -30,20 +28,22 @@ use Illuminate\Support\Carbon;
/**
* PaymentRepository.
*/
-class PaymentRepository extends BaseRepository {
- use MakesHash;
- use SavesDocuments;
+class PaymentRepository extends BaseRepository
+{
+ use MakesHash;
+ use SavesDocuments;
- protected $credit_repo;
+ protected $credit_repo;
- public function __construct( CreditRepository $credit_repo ) {
- $this->credit_repo = $credit_repo;
- }
+ public function __construct(CreditRepository $credit_repo)
+ {
+ $this->credit_repo = $credit_repo;
+ }
- /**
- * Saves and updates a payment. //todo refactor to handle refunds and payments.
- *
- * @param array $data the request object
+ /**
+ * Saves and updates a payment. //todo refactor to handle refunds and payments.
+ *
+ * @param array $data the request object
* @param Payment $payment The Payment object
* @return Payment|null Payment $payment
*/
@@ -60,7 +60,6 @@ class PaymentRepository extends BaseRepository {
*/
private function applyPayment(array $data, Payment $payment): ?Payment
{
-
$is_existing_payment = true;
$client = false;
@@ -69,13 +68,13 @@ class PaymentRepository extends BaseRepository {
$payment = $this->processExchangeRates($data, $payment);
/* This is needed here otherwise the ->fill() overwrites anything that exists*/
- if($payment->exchange_rate != 1)
+ if ($payment->exchange_rate != 1) {
unset($data['exchange_rate']);
+ }
$is_existing_payment = false;
\DB::connection(config('database.default'))->transaction(function () use ($data) {
-
$client = Client::where('id', $data['client_id'])->withTrashed()->lockForUpdate()->first();
/*We only update the paid to date ONCE per payment*/
@@ -86,9 +85,7 @@ class PaymentRepository extends BaseRepository {
$client->service()->updatePaidToDate($data['amount'])->save();
$client->saveQuietly();
- }
-
- else{
+ } else {
//this fixes an edge case with unapplied payments
$client->service()->updatePaidToDate($data['amount'])->save();
// $client->paid_to_date += $data['amount'];
@@ -102,9 +99,7 @@ class PaymentRepository extends BaseRepository {
// $client->paid_to_date += $_credit_totals;
$client->saveQuietly();
}
-
- }, 1);
-
+ }, 1);
}
/*Fill the payment*/
@@ -113,12 +108,11 @@ class PaymentRepository extends BaseRepository {
$payment->status_id = Payment::STATUS_COMPLETED;
if (! $payment->currency_id && $client) {
-
- if(property_exists($client->settings, 'currency_id'))
+ if (property_exists($client->settings, 'currency_id')) {
$payment->currency_id = $client->settings->currency_id;
- else
+ } else {
$payment->currency_id = $client->company->settings->currency_id;
-
+ }
}
$payment->saveQuietly();
@@ -140,7 +134,6 @@ class PaymentRepository extends BaseRepository {
/*Iterate through invoices and apply payments*/
if (array_key_exists('invoices', $data) && is_array($data['invoices']) && count($data['invoices']) > 0) {
-
$invoice_totals = array_sum(array_column($data['invoices'], 'amount'));
$invoices = Invoice::withTrashed()->whereIn('id', array_column($data['invoices'], 'invoice_id'))->get();
@@ -186,15 +179,15 @@ class PaymentRepository extends BaseRepository {
}
}
- if ( ! $is_existing_payment && ! $this->import_mode ) {
-
- if (array_key_exists('email_receipt', $data) && $data['email_receipt'] == 'true')
+ if (! $is_existing_payment && ! $this->import_mode) {
+ if (array_key_exists('email_receipt', $data) && $data['email_receipt'] == 'true') {
$payment->service()->sendEmail();
- elseif(!array_key_exists('email_receipt', $data) && $payment->client->getSetting('client_manual_payment_notification'))
+ } elseif (!array_key_exists('email_receipt', $data) && $payment->client->getSetting('client_manual_payment_notification')) {
$payment->service()->sendEmail();
+ }
- event( new PaymentWasCreated( $payment, $payment->company, Ninja::eventVars(auth()->user() ? auth()->user()->id : null) ) );
- }
+ event(new PaymentWasCreated($payment, $payment->company, Ninja::eventVars(auth()->user() ? auth()->user()->id : null)));
+ }
$payment->applied += ($invoice_totals - $credit_totals); //wont work because - check tests
@@ -212,8 +205,7 @@ class PaymentRepository extends BaseRepository {
*/
public function processExchangeRates($data, $payment)
{
-
- if(array_key_exists('exchange_rate', $data) && isset($data['exchange_rate']) && $data['exchange_rate'] != 1){
+ if (array_key_exists('exchange_rate', $data) && isset($data['exchange_rate']) && $data['exchange_rate'] != 1) {
return $payment;
}
@@ -223,7 +215,6 @@ class PaymentRepository extends BaseRepository {
$company_currency = $client->company->settings->currency_id;
if ($company_currency != $client_currency) {
-
$exchange_rate = new CurrencyApi();
$payment->exchange_rate = $exchange_rate->exchangeRate($client_currency, $company_currency, Carbon::parse($payment->date));
@@ -247,11 +238,11 @@ class PaymentRepository extends BaseRepository {
$payment = $payment->service()->deletePayment();
- if($payment)
+ if ($payment) {
event(new PaymentWasDeleted($payment, $payment->company, Ninja::eventVars(auth()->user() ? auth()->user()->id : null)));
+ }
return $payment;
-
}
public function restore($payment)
diff --git a/app/Repositories/PurchaseOrderRepository.php b/app/Repositories/PurchaseOrderRepository.php
index e1b514b25ca0..321b4fa89891 100644
--- a/app/Repositories/PurchaseOrderRepository.php
+++ b/app/Repositories/PurchaseOrderRepository.php
@@ -44,7 +44,6 @@ class PurchaseOrderRepository extends BaseRepository
});
foreach ($data['invitations'] as $invitation) {
-
//if no invitations are present - create one.
if (! $this->getInvitation($invitation)) {
if (isset($invitation['id'])) {
diff --git a/app/Repositories/RecurringInvoiceRepository.php b/app/Repositories/RecurringInvoiceRepository.php
index f5d19e731390..c0b4e87f121e 100644
--- a/app/Repositories/RecurringInvoiceRepository.php
+++ b/app/Repositories/RecurringInvoiceRepository.php
@@ -11,7 +11,6 @@
namespace App\Repositories;
-use App\Helpers\Invoice\InvoiceSum;
use App\Models\RecurringInvoice;
use App\Models\RecurringInvoiceInvitation;
diff --git a/app/Repositories/SchedulerRepository.php b/app/Repositories/SchedulerRepository.php
index f03ca0213481..f067984b1027 100644
--- a/app/Repositories/SchedulerRepository.php
+++ b/app/Repositories/SchedulerRepository.php
@@ -15,24 +15,20 @@ use App\Models\Scheduler;
class SchedulerRepository extends BaseRepository
{
-
/**
* Saves the scheduler.
*
* @param array $data The data
* @param \App\Models\Scheduler $scheduler The scheduler
*
- * @return \App\Models\Scheduler
+ * @return \App\Models\Scheduler
*/
public function save(array $data, Scheduler $scheduler): Scheduler
{
-
$scheduler->fill($data);
$scheduler->save();
return $scheduler;
-
}
-
}
diff --git a/app/Repositories/SubscriptionRepository.php b/app/Repositories/SubscriptionRepository.php
index 8a8b25972a32..dd647ca5d32f 100644
--- a/app/Repositories/SubscriptionRepository.php
+++ b/app/Repositories/SubscriptionRepository.php
@@ -17,7 +17,6 @@ use App\DataMapper\InvoiceItem;
use App\Factory\InvoiceFactory;
use App\Models\Client;
use App\Models\ClientContact;
-use App\Models\Invoice;
use App\Models\InvoiceInvitation;
use App\Models\Subscription;
use App\Utils\Traits\CleanLineItems;
@@ -45,7 +44,6 @@ class SubscriptionRepository extends BaseRepository
private function calculatePrice($subscription) :array
{
-
// DB::beginTransaction();
DB::connection(config('database.default'))->beginTransaction();
$data = [];
@@ -124,21 +122,16 @@ class SubscriptionRepository extends BaseRepository
$line_items = [];
- $line_items = collect($bundle)->filter(function ($item){
-
+ $line_items = collect($bundle)->filter(function ($item) {
return $item->is_recurring;
-
- })->map(function ($item){
-
- $line_item = new InvoiceItem;
- $line_item->product_key = $item->product_key;
- $line_item->quantity = (float)$item->qty;
- $line_item->cost = (float)$item->unit_cost;
- $line_item->notes = $item->description;
-
- return $line_item;
-
+ })->map(function ($item) {
+ $line_item = new InvoiceItem;
+ $line_item->product_key = $item->product_key;
+ $line_item->quantity = (float)$item->qty;
+ $line_item->cost = (float)$item->unit_cost;
+ $line_item->notes = $item->description;
+ return $line_item;
})->toArray();
diff --git a/app/Repositories/TaskRepository.php b/app/Repositories/TaskRepository.php
index 4d5749a73db0..562a7a7c3d36 100644
--- a/app/Repositories/TaskRepository.php
+++ b/app/Repositories/TaskRepository.php
@@ -251,30 +251,22 @@ class TaskRepository extends BaseRepository
private function trySaving(Task $task)
{
-
$x=1;
- do{
-
- try{
-
+ do {
+ try {
$task->number = $this->getNextTaskNumber($task);
$task->saveQuietly();
$this->completed = false;
-
- }
- catch(QueryException $e){
-
+ } catch(QueryException $e) {
$x++;
- if($x>50)
+ if ($x>50) {
$this->completed = false;
+ }
}
-
- }
- while($this->completed);
+ } while ($this->completed);
return $task->number;
-
}
}
diff --git a/app/Repositories/TaskStatusRepository.php b/app/Repositories/TaskStatusRepository.php
index 88f7bbb83df4..8692ed51fd35 100644
--- a/app/Repositories/TaskStatusRepository.php
+++ b/app/Repositories/TaskStatusRepository.php
@@ -19,9 +19,8 @@ use App\Models\TaskStatus;
*/
class TaskStatusRepository extends BaseRepository
{
-
- public function delete($task_status)
- {
+ public function delete($task_status)
+ {
$ts = TaskStatus::where('company_id', $task_status->company_id)
->first();
@@ -35,11 +34,10 @@ class TaskStatusRepository extends BaseRepository
parent::delete($task_status);
return $task_status;
-
- }
+ }
- public function archive($task_status)
- {
+ public function archive($task_status)
+ {
$task_status = TaskStatus::where('id', $task_status->id)
->where('company_id', $task_status->company_id)
->first();
@@ -54,6 +52,5 @@ class TaskStatusRepository extends BaseRepository
parent::archive($task_status);
return $task_status;
-
- }
+ }
}
diff --git a/app/Repositories/UserRepository.php b/app/Repositories/UserRepository.php
index cf66bf09a9ee..6b8707d158a9 100644
--- a/app/Repositories/UserRepository.php
+++ b/app/Repositories/UserRepository.php
@@ -59,7 +59,7 @@ class UserRepository extends BaseRepository
// if(array_key_exists('oauth_provider_id', $details))
// unset($details['oauth_provider_id']);
- if (request()->has('validated_phone')){
+ if (request()->has('validated_phone')) {
$details['phone'] = request()->input('validated_phone');
$user->verified_phone_number = false;
}
@@ -93,17 +93,15 @@ class UserRepository extends BaseRepository
$user->companies()->attach($company->id, $data['company_user']);
} else {
if (auth()->user()->isAdmin()) {
-
$cu->fill($data['company_user']);
$cu->restore();
$cu->tokens()->restore();
$cu->save();
//05-08-2022
- if($cu->tokens()->count() == 0){
+ if ($cu->tokens()->count() == 0) {
(new CreateCompanyToken($cu->company, $cu->user, 'restored_user'))->handle();
}
-
} else {
$cu->notifications = $data['company_user']['notifications'];
$cu->settings = $data['company_user']['settings'];
@@ -221,28 +219,23 @@ class UserRepository extends BaseRepository
* and there are some that are not admins,
* we force all companies to large to ensure
* the queries are appropriate for all users
- *
- * @param User $user
+ *
+ * @param User $user
* @return void
*/
private function verifyCorrectCompanySizeForPermissions(User $user): void
{
-
- if(Ninja::isSelfHost() || (Ninja::isHosted() && $user->account->isEnterpriseClient()))
- {
-
+ if (Ninja::isSelfHost() || (Ninja::isHosted() && $user->account->isEnterpriseClient())) {
$user->account()
- ->whereHas('companies', function ($query){
- $query->where('is_large',0);
+ ->whereHas('companies', function ($query) {
+ $query->where('is_large', 0);
})
- ->whereHas('company_users', function ($query){
- $query->where('is_admin', 0);
- })
- ->cursor()->each(function ($account){
- $account->companies()->update(['is_large' => true]);
+ ->whereHas('company_users', function ($query) {
+ $query->where('is_admin', 0);
+ })
+ ->cursor()->each(function ($account) {
+ $account->companies()->update(['is_large' => true]);
});
-
}
-
}
}
diff --git a/app/Services/Bank/BankMatchingService.php b/app/Services/Bank/BankMatchingService.php
index 663e7204114a..906e21fe918d 100644
--- a/app/Services/Bank/BankMatchingService.php
+++ b/app/Services/Bank/BankMatchingService.php
@@ -11,50 +11,37 @@
namespace App\Services\Bank;
-use App\Factory\ExpenseCategoryFactory;
-use App\Factory\ExpenseFactory;
use App\Libraries\MultiDB;
use App\Models\BankTransaction;
-use App\Models\Company;
-use App\Models\ExpenseCategory;
-use App\Models\Invoice;
-use App\Services\Bank\BankService;
-use App\Utils\Traits\GeneratesCounter;
use Illuminate\Bus\Queueable;
-use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\Middleware\WithoutOverlapping;
use Illuminate\Queue\SerializesModels;
-use Illuminate\Support\Carbon;
-use Illuminate\Support\Facades\Cache;
class BankMatchingService implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
- public function __construct(public $company_id, public $db){}
+ public function __construct(public $company_id, public $db)
+ {
+ }
public function handle() :void
{
-
MultiDB::setDb($this->db);
BankTransaction::where('company_id', $this->company_id)
->where('status_id', BankTransaction::STATUS_UNMATCHED)
->cursor()
- ->each(function ($bt){
-
+ ->each(function ($bt) {
(new BankService($bt))->processRules();
-
});
-
}
public function middleware()
- {
+ {
return [(new WithoutOverlapping($this->company_id))];
}
-
}
diff --git a/app/Services/Bank/BankService.php b/app/Services/Bank/BankService.php
index 94916752a57c..1fc3a77ba946 100644
--- a/app/Services/Bank/BankService.php
+++ b/app/Services/Bank/BankService.php
@@ -13,20 +13,17 @@ namespace App\Services\Bank;
use App\Models\BankTransaction;
use App\Models\Invoice;
-use App\Services\Bank\ProcessBankRules;
class BankService
{
-
- public function __construct(public BankTransaction $bank_transaction) {}
+ public function __construct(public BankTransaction $bank_transaction)
+ {
+ }
public function matchInvoiceNumber()
{
-
- if(strlen($this->bank_transaction->description) > 1)
- {
-
+ if (strlen($this->bank_transaction->description) > 1) {
$i = Invoice::where('company_id', $this->bank_transaction->company_id)
->whereIn('status_id', [1,2,3])
->where('is_deleted', 0)
@@ -37,12 +34,10 @@ class BankService
}
return false;
-
}
public function processRules()
{
(new ProcessBankRules($this->bank_transaction))->run();
}
-
-}
\ No newline at end of file
+}
diff --git a/app/Services/Bank/ProcessBankRules.php b/app/Services/Bank/ProcessBankRules.php
index 2077fb244242..54277d5f693d 100644
--- a/app/Services/Bank/ProcessBankRules.php
+++ b/app/Services/Bank/ProcessBankRules.php
@@ -31,91 +31,76 @@ class ProcessBankRules extends AbstractService
protected $categories;
- public function __construct(public BankTransaction $bank_transaction){}
+ public function __construct(public BankTransaction $bank_transaction)
+ {
+ }
public function run()
{
- if($this->bank_transaction->base_type == 'DEBIT')
+ if ($this->bank_transaction->base_type == 'DEBIT') {
$this->matchDebit();
- else
+ } else {
$this->matchCredit();
+ }
}
private function matchCredit()
{
-
$this->invoices = Invoice::where('company_id', $this->bank_transaction->company_id)
->whereIn('status_id', [1,2,3])
->where('is_deleted', 0)
->get();
- $invoice = $this->invoices->first(function ($value, $key){
-
+ $invoice = $this->invoices->first(function ($value, $key) {
return str_contains($this->bank_transaction->description, $value->number);
-
});
- if($invoice)
- {
+ if ($invoice) {
$this->bank_transaction->invoice_ids = $invoice->hashed_id;
$this->bank_transaction->status_id = BankTransaction::STATUS_MATCHED;
- $this->bank_transaction->save();
+ $this->bank_transaction->save();
return;
}
$this->credit_rules = $this->bank_transaction->company->credit_rules();
//stub for credit rules
- foreach($this->credit_rules as $rule)
- {
+ foreach ($this->credit_rules as $rule) {
// $this->bank_transaction->bank_transaction_rule_id = $bank_transaction_rule->id;
-
}
-
}
private function matchDebit()
{
-
$this->debit_rules = $this->bank_transaction->company->debit_rules();
$this->categories = collect(Cache::get('bank_categories'));
- foreach($this->debit_rules as $bank_transaction_rule)
- {
-
+ foreach ($this->debit_rules as $bank_transaction_rule) {
$matches = 0;
- if(!is_array($bank_transaction_rule['rules']))
+ if (!is_array($bank_transaction_rule['rules'])) {
continue;
+ }
- foreach($bank_transaction_rule['rules'] as $rule)
- {
+ foreach ($bank_transaction_rule['rules'] as $rule) {
$rule_count = count($bank_transaction_rule['rules']);
- if($rule['search_key'] == 'description')
- {
-
- if($this->matchStringOperator($this->bank_transaction->description, $rule['value'], $rule['operator'])){
+ if ($rule['search_key'] == 'description') {
+ if ($this->matchStringOperator($this->bank_transaction->description, $rule['value'], $rule['operator'])) {
$matches++;
}
-
}
- if($rule['search_key'] == 'amount')
- {
-
- if($this->matchNumberOperator($this->bank_transaction->amount, $rule['value'] , $rule['operator'])){
+ if ($rule['search_key'] == 'amount') {
+ if ($this->matchNumberOperator($this->bank_transaction->amount, $rule['value'], $rule['operator'])) {
$matches++;
}
-
}
- if(($bank_transaction_rule['matches_on_all'] && ($matches == $rule_count)) || (!$bank_transaction_rule['matches_on_all'] && $matches > 0))
- {
-
+ if (($bank_transaction_rule['matches_on_all'] && ($matches == $rule_count)) || (!$bank_transaction_rule['matches_on_all'] && $matches > 0)) {
// $this->bank_transaction->client_id = empty($rule['client_id']) ? null : $rule['client_id'];
$this->bank_transaction->vendor_id = $bank_transaction_rule->vendor_id;
$this->bank_transaction->ninja_category_id = $bank_transaction_rule->category_id;
@@ -123,9 +108,7 @@ class ProcessBankRules extends AbstractService
$this->bank_transaction->bank_transaction_rule_id = $bank_transaction_rule->id;
$this->bank_transaction->save();
- if($bank_transaction_rule['auto_convert'])
- {
-
+ if ($bank_transaction_rule['auto_convert']) {
$expense = ExpenseFactory::create($this->bank_transaction->company_id, $this->bank_transaction->user_id);
$expense->category_id = $bank_transaction_rule->category_id ?: $this->resolveCategory();
$expense->amount = $this->bank_transaction->amount;
@@ -145,14 +128,10 @@ class ProcessBankRules extends AbstractService
$this->bank_transaction->save();
break;
-
}
-
}
}
-
}
-
}
private function resolveCategory()
@@ -161,11 +140,11 @@ class ProcessBankRules extends AbstractService
$ec = ExpenseCategory::where('company_id', $this->bank_transaction->company_id)->where('bank_category_id', $this->bank_transaction->category_id)->first();
- if($ec)
+ if ($ec) {
return $ec->id;
+ }
- if($category)
- {
+ if ($category) {
$ec = ExpenseCategoryFactory::create($this->bank_transaction->company_id, $this->bank_transaction->user_id);
$ec->bank_category_id = $this->bank_transaction->category_id;
$ec->name = $category->highLevelCategoryName;
@@ -177,7 +156,6 @@ class ProcessBankRules extends AbstractService
private function matchNumberOperator($bt_value, $rule_value, $operator) :bool
{
-
return match ($operator) {
'>' => floatval($bt_value) > floatval($rule_value),
'>=' => floatval($bt_value) >= floatval($rule_value),
@@ -186,7 +164,6 @@ class ProcessBankRules extends AbstractService
'<=' => floatval($bt_value) <= floatval($rule_value),
default => false,
};
-
}
private function matchStringOperator($bt_value, $rule_value, $operator) :bool
@@ -202,10 +179,5 @@ class ProcessBankRules extends AbstractService
'is_empty' => empty($bt_value),
default => false,
};
-
}
-
-
-
-
-}
\ No newline at end of file
+}
diff --git a/app/Services/Chart/ChartQueries.php b/app/Services/Chart/ChartQueries.php
index 4cd2fc73c020..fc996b00d32f 100644
--- a/app/Services/Chart/ChartQueries.php
+++ b/app/Services/Chart/ChartQueries.php
@@ -11,9 +11,6 @@
namespace App\Services\Chart;
-use App\Models\Expense;
-use App\Models\Invoice;
-use App\Models\Payment;
use Illuminate\Support\Facades\DB;
/**
diff --git a/app/Services/Chart/ChartService.php b/app/Services/Chart/ChartService.php
index 85d0ef8bf7eb..6c7c9914e82f 100644
--- a/app/Services/Chart/ChartService.php
+++ b/app/Services/Chart/ChartService.php
@@ -14,8 +14,6 @@ namespace App\Services\Chart;
use App\Models\Client;
use App\Models\Company;
use App\Models\Expense;
-use App\Models\Payment;
-use App\Services\Chart\ChartQueries;
use Illuminate\Support\Facades\Cache;
class ChartService
diff --git a/app/Services/Client/ClientService.php b/app/Services/Client/ClientService.php
index ad74f22c0c84..df0641c2eda8 100644
--- a/app/Services/Client/ClientService.php
+++ b/app/Services/Client/ClientService.php
@@ -13,8 +13,6 @@ namespace App\Services\Client;
use App\Models\Client;
use App\Models\Credit;
-use App\Services\Client\Merge;
-use App\Services\Client\PaymentMethod;
use App\Services\Email\EmailObject;
use App\Services\Email\EmailService;
use App\Utils\Number;
@@ -30,76 +28,61 @@ class ClientService
private string $client_end_date;
- public function __construct(private Client $client){}
+ public function __construct(private Client $client)
+ {
+ }
public function updateBalance(float $amount)
{
-
try {
- DB::connection(config('database.default'))->transaction(function () use($amount) {
-
+ DB::connection(config('database.default'))->transaction(function () use ($amount) {
$this->client = Client::withTrashed()->where('id', $this->client->id)->lockForUpdate()->first();
$this->client->balance += $amount;
$this->client->saveQuietly();
-
}, 2);
- }
- catch (\Throwable $throwable) {
+ } catch (\Throwable $throwable) {
nlog("DB ERROR " . $throwable->getMessage());
}
return $this;
-
}
public function updateBalanceAndPaidToDate(float $balance, float $paid_to_date)
{
-
try {
- DB::connection(config('database.default'))->transaction(function () use($balance, $paid_to_date) {
-
+ DB::connection(config('database.default'))->transaction(function () use ($balance, $paid_to_date) {
$this->client = Client::withTrashed()->where('id', $this->client->id)->lockForUpdate()->first();
$this->client->balance += $balance;
$this->client->paid_to_date += $paid_to_date;
$this->client->saveQuietly();
-
}, 2);
- }
- catch (\Throwable $throwable) {
+ } catch (\Throwable $throwable) {
nlog("DB ERROR " . $throwable->getMessage());
}
return $this;
-
}
public function updatePaidToDate(float $amount)
{
-
- DB::connection(config('database.default'))->transaction(function () use($amount) {
-
+ DB::connection(config('database.default'))->transaction(function () use ($amount) {
$this->client = Client::withTrashed()->where('id', $this->client->id)->lockForUpdate()->first();
$this->client->paid_to_date += $amount;
$this->client->saveQuietly();
-
}, 2);
return $this;
-
}
public function adjustCreditBalance(float $amount)
{
-
$this->client->credit_balance += $amount;
return $this;
-
}
public function getCreditBalance() :float
{
-
$credits = Credit::withTrashed()->where('client_id', $this->client->id)
->where('is_deleted', false)
->where(function ($query) {
@@ -109,7 +92,6 @@ class ClientService
->orderBy('created_at', 'ASC');
return Number::roundValue($credits->sum('balance'), $this->client->currency()->precision);
-
}
public function getCredits()
@@ -148,40 +130,38 @@ class ClientService
$pdf = $statement->run();
- if($send_email)
+ if ($send_email) {
return $this->emailStatement($pdf, $statement->options);
+ }
return $pdf;
}
/**
* Emails the statement to the client
- *
+ *
* @param mixed $pdf The pdf blob
* @param array $options The statement options array
- * @return void
+ * @return void
*/
private function emailStatement($pdf, array $options): void
{
-
$this->client_start_date = $this->translateDate($options['start_date'], $this->client->date_format(), $this->client->locale());
$this->client_end_date = $this->translateDate($options['end_date'], $this->client->date_format(), $this->client->locale());
$email_service = new EmailService($this->buildStatementMailableData($pdf), $this->client->company);
$email_service->send();
-
}
/**
* Builds and returns an EmailObject for Client Statements
- *
+ *
* @param mixed $pdf The PDF to send
* @return EmailObject The EmailObject to send
*/
public function buildStatementMailableData($pdf) :EmailObject
{
-
$email_object = new EmailObject;
$email_object->to = [new Address($this->client->present()->email(), $this->client->present()->name())];
$email_object->attachments = [['file' => base64_encode($pdf), 'name' => ctrans('texts.statement') . ".pdf"]];
@@ -197,12 +177,11 @@ class ClientService
];
return $email_object;
-
}
/**
* Saves the client instance
- *
+ *
* @return Client The Client Model
*/
public function save() :Client
diff --git a/app/Services/Client/Merge.php b/app/Services/Client/Merge.php
index b8700b458bb2..eeef8e5632e5 100644
--- a/app/Services/Client/Merge.php
+++ b/app/Services/Client/Merge.php
@@ -14,14 +14,8 @@ namespace App\Services\Client;
use App\Factory\CompanyLedgerFactory;
use App\Models\Activity;
use App\Models\Client;
-use App\Models\CompanyGateway;
use App\Models\CompanyLedger;
-use App\Models\GatewayType;
-use App\Models\Invoice;
-use App\Models\Payment;
use App\Services\AbstractService;
-use App\Utils\Ninja;
-use App\Utils\Traits\MakesHash;
class Merge extends AbstractService
{
diff --git a/app/Services/Client/PaymentMethod.php b/app/Services/Client/PaymentMethod.php
index 56b850c1db64..8f095ea22fa3 100644
--- a/app/Services/Client/PaymentMethod.php
+++ b/app/Services/Client/PaymentMethod.php
@@ -14,9 +14,7 @@ namespace App\Services\Client;
use App\Models\Client;
use App\Models\CompanyGateway;
use App\Models\GatewayType;
-use App\Models\Invoice;
use App\Models\Payment;
-use App\Utils\Ninja;
use App\Utils\Traits\MakesHash;
class PaymentMethod
@@ -121,7 +119,6 @@ class PaymentMethod
$this->payment_methods = [];
foreach ($this->gateways as $gateway) {
-
//if gateway doesn't exist or is not implemented - continue here //todo
if (! $gateway->driver($this->client)) {
continue;
@@ -187,7 +184,6 @@ class PaymentMethod
}
if (($this->client->getSetting('use_credits_payment') == 'option' || $this->client->getSetting('use_credits_payment') == 'always') && $this->client->service()->getCreditBalance() > 0) {
-
// Show credits as only payment option if both statements are true.
if (
$this->client->service()->getCreditBalance() > $this->amount
diff --git a/app/Services/Client/Statement.php b/app/Services/Client/Statement.php
index 1d02a4c77f89..4881aa83156d 100644
--- a/app/Services/Client/Statement.php
+++ b/app/Services/Client/Statement.php
@@ -40,7 +40,9 @@ class Statement
protected bool $rollback = false;
- public function __construct(protected Client $client, public array $options){}
+ public function __construct(protected Client $client, public array $options)
+ {
+ }
public function run() :?string
{
diff --git a/app/Services/ClientPortal/InstantPayment.php b/app/Services/ClientPortal/InstantPayment.php
index b1136f5d605b..359d1e9b8b73 100644
--- a/app/Services/ClientPortal/InstantPayment.php
+++ b/app/Services/ClientPortal/InstantPayment.php
@@ -13,9 +13,6 @@
namespace App\Services\ClientPortal;
use App\Exceptions\PaymentFailed;
-use App\Factory\PaymentFactory;
-use App\Http\Controllers\Controller;
-use App\Http\Requests\ClientPortal\Payments\PaymentResponseRequest;
use App\Jobs\Invoice\CheckGatewayFee;
use App\Jobs\Invoice\InjectSignature;
use App\Jobs\Util\SystemLogger;
@@ -24,17 +21,13 @@ use App\Models\Invoice;
use App\Models\Payment;
use App\Models\PaymentHash;
use App\Models\SystemLog;
-use App\Services\Subscription\SubscriptionService;
use App\Utils\Ninja;
use App\Utils\Number;
use App\Utils\Traits\MakesDates;
use App\Utils\Traits\MakesHash;
-use Illuminate\Contracts\View\Factory;
-use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;
-use Illuminate\View\View;
class InstantPayment
{
@@ -50,7 +43,6 @@ class InstantPayment
public function run()
{
-
$is_credit_payment = false;
$tokens = [];
@@ -96,7 +88,6 @@ class InstantPayment
/* This loop checks for under / over payments and returns the user if a check fails */
foreach ($payable_invoices as $payable_invoice) {
-
/*Match the payable invoice to the Model Invoice*/
$invoice = $invoices->first(function ($inv) use ($payable_invoice) {
@@ -197,8 +188,9 @@ class InstantPayment
$starting_invoice_amount = $first_invoice->balance;
/* Schedule a job to check the gateway fees for this invoice*/
- if(Ninja::isHosted())
+ if (Ninja::isHosted()) {
CheckGatewayFee::dispatch($first_invoice->id, $client->company->db)->delay(600);
+ }
if ($gateway) {
$first_invoice->service()->addGatewayFee($gateway, $payment_method_id, $invoice_totals)->save();
@@ -226,17 +218,12 @@ class InstantPayment
if ($this->request->query('hash')) {
$hash_data['billing_context'] = Cache::get($this->request->query('hash'));
- }
- elseif($this->request->hash){
+ } elseif ($this->request->hash) {
$hash_data['billing_context'] = Cache::get($this->request->hash);
- }
- elseif($old_hash = PaymentHash::where('fee_invoice_id', $first_invoice->id)->whereNull('payment_id')->first()) {
-
- if(isset($old_hash->data->billing_context))
- {
+ } elseif ($old_hash = PaymentHash::where('fee_invoice_id', $first_invoice->id)->whereNull('payment_id')->first()) {
+ if (isset($old_hash->data->billing_context)) {
$hash_data['billing_context'] = $old_hash->data->billing_context;
}
-
}
$payment_hash = new PaymentHash;
@@ -297,7 +284,7 @@ class InstantPayment
}
public function processCreditPayment(Request $request, array $data)
- {
+ {
return render('gateways.credit.index', $data);
}
}
diff --git a/app/Services/Credit/ApplyPayment.php b/app/Services/Credit/ApplyPayment.php
index f5494a4a2291..f9eeb7ec46e8 100644
--- a/app/Services/Credit/ApplyPayment.php
+++ b/app/Services/Credit/ApplyPayment.php
@@ -42,7 +42,6 @@ class ApplyPayment
public function run() :Credit
{
-
//$available_credit_balance = $this->credit->balance;
$applicable_amount = min($this->amount, $this->credit->balance);
$invoice_balance = $this->invoice->balance;
diff --git a/app/Services/Credit/CreditService.php b/app/Services/Credit/CreditService.php
index db02b1127d46..d9051df17224 100644
--- a/app/Services/Credit/CreditService.php
+++ b/app/Services/Credit/CreditService.php
@@ -19,8 +19,6 @@ use App\Models\Payment;
use App\Models\PaymentType;
use App\Repositories\CreditRepository;
use App\Repositories\PaymentRepository;
-use App\Services\Credit\CreateInvitations;
-use App\Services\Credit\TriggeredActions;
use App\Utils\Traits\MakesHash;
class CreditService
@@ -271,7 +269,6 @@ class CreditService
public function restoreCredit()
{
-
$this->credit
->client
->service()
diff --git a/app/Services/Credit/GetCreditPdf.php b/app/Services/Credit/GetCreditPdf.php
index ed8e8e2619ca..0ad1d9aac220 100644
--- a/app/Services/Credit/GetCreditPdf.php
+++ b/app/Services/Credit/GetCreditPdf.php
@@ -13,8 +13,6 @@ namespace App\Services\Credit;
use App\Jobs\Entity\CreateEntityPdf;
use App\Services\AbstractService;
-use App\Utils\TempFile;
-use Illuminate\Support\Facades\Storage;
class GetCreditPdf extends AbstractService
{
diff --git a/app/Services/Credit/MarkSent.php b/app/Services/Credit/MarkSent.php
index d8ad848dbc70..3402a019aab9 100644
--- a/app/Services/Credit/MarkSent.php
+++ b/app/Services/Credit/MarkSent.php
@@ -12,7 +12,6 @@
namespace App\Services\Credit;
use App\Events\Credit\CreditWasMarkedSent;
-use App\Jobs\Util\WebhookHandler;
use App\Models\Credit;
use App\Models\Webhook;
use App\Utils\Ninja;
@@ -31,7 +30,6 @@ class MarkSent
public function run()
{
-
/* Return immediately if status is not draft */
if ($this->credit->status_id != Credit::STATUS_DRAFT) {
return $this->credit;
diff --git a/app/Services/Credit/SendEmail.php b/app/Services/Credit/SendEmail.php
index 6c0c5154d266..1f01f6ba67f1 100644
--- a/app/Services/Credit/SendEmail.php
+++ b/app/Services/Credit/SendEmail.php
@@ -11,8 +11,6 @@
namespace App\Services\Credit;
-use App\Helpers\Email\CreditEmail;
-use App\Jobs\Credit\EmailCredit;
use App\Jobs\Entity\EmailEntity;
use App\Models\ClientContact;
diff --git a/app/Services/Credit/TriggeredActions.php b/app/Services/Credit/TriggeredActions.php
index e08151736c48..fb909373959b 100644
--- a/app/Services/Credit/TriggeredActions.php
+++ b/app/Services/Credit/TriggeredActions.php
@@ -45,7 +45,7 @@ class TriggeredActions extends AbstractService
$this->credit = $this->credit->service()->markSent()->save();
}
- if($this->request->has('save_default_footer') && $this->request->input('save_default_footer') == 'true') {
+ if ($this->request->has('save_default_footer') && $this->request->input('save_default_footer') == 'true') {
$company = $this->credit->company;
$settings = $company->settings;
$settings->credit_footer = $this->credit->footer;
@@ -53,7 +53,7 @@ class TriggeredActions extends AbstractService
$company->save();
}
- if($this->request->has('save_default_terms') && $this->request->input('save_default_terms') == 'true') {
+ if ($this->request->has('save_default_terms') && $this->request->input('save_default_terms') == 'true') {
$company = $this->credit->company;
$settings = $company->settings;
$settings->credit_terms = $this->credit->terms;
diff --git a/app/Services/Email/EmailDefaults.php b/app/Services/Email/EmailDefaults.php
index 698705dba8a1..153d14c2e349 100644
--- a/app/Services/Email/EmailDefaults.php
+++ b/app/Services/Email/EmailDefaults.php
@@ -13,14 +13,10 @@ namespace App\Services\Email;
use App\DataMapper\EmailTemplateDefaults;
use App\Models\Account;
-use App\Models\Company;
-use App\Services\Email\EmailObject;
use App\Utils\Ninja;
use Illuminate\Mail\Mailables\Address;
use Illuminate\Support\Facades\App;
-use Illuminate\Support\Facades\Mail;
use League\CommonMark\CommonMarkConverter;
-use Illuminate\Mail\Attachment;
class EmailDefaults
{
@@ -46,12 +42,14 @@ class EmailDefaults
* @param EmailService $email_service The email service class
* @param EmailObject $email_object the email object class
*/
- public function __construct(protected EmailService $email_service, public EmailObject $email_object){}
+ public function __construct(protected EmailService $email_service, public EmailObject $email_object)
+ {
+ }
/**
- * Entry point for generating
+ * Entry point for generating
* the defaults for the email object
- *
+ *
* @return EmailObject $email_object The email object
*/
public function run()
@@ -70,7 +68,6 @@ class EmailDefaults
->setVariables();
return $this->email_object;
-
}
/**
@@ -78,7 +75,6 @@ class EmailDefaults
*/
private function setMetaData(): self
{
-
$this->email_object->company_key = $this->email_service->company->company_key;
$this->email_object->logo = $this->email_service->company->present()->logo();
@@ -88,7 +84,6 @@ class EmailDefaults
$this->email_object->whitelabel = $this->email_object->company->account->isPaid() ? true : false;
return $this;
-
}
/**
@@ -96,13 +91,13 @@ class EmailDefaults
*/
private function setLocale(): self
{
-
- if($this->email_object->client)
+ if ($this->email_object->client) {
$this->locale = $this->email_object->client->locale();
- elseif($this->email_object->vendor)
+ } elseif ($this->email_object->vendor) {
$this->locale = $this->email_object->vendor->locale();
- else
+ } else {
$this->locale = $this->email_service->company->locale();
+ }
App::setLocale($this->locale);
App::forgetInstance('translator');
@@ -119,14 +114,14 @@ class EmailDefaults
{
$this->template = $this->email_object->settings->email_style;
- match($this->email_object->settings->email_style){
+ match ($this->email_object->settings->email_style) {
'light' => $this->template = 'email.template.client',
'dark' => $this->template = 'email.template.client',
'custom' => $this->template = 'email.template.custom',
default => $this->template = 'email.template.client',
- };
+ };
- $this->email_object->html_template = $this->template;
+ $this->email_object->html_template = $this->template;
return $this;
}
@@ -135,44 +130,39 @@ class EmailDefaults
* Sets the FROM address
*/
private function setFrom(): self
- {
-
- if(Ninja::isHosted() && $this->email_object->settings->email_sending_method == 'default'){
+ {
+ if (Ninja::isHosted() && $this->email_object->settings->email_sending_method == 'default') {
$this->email_object->from = new Address(config('mail.from.address'), $this->email_service->company->owner()->name());
return $this;
}
- if($this->email_object->from)
+ if ($this->email_object->from) {
return $this;
+ }
$this->email_object->from = new Address($this->email_service->company->owner()->email, $this->email_service->company->owner()->name());
return $this;
-
}
- /**
+ /**
* Sets the body of the email
*/
private function setBody(): self
{
-
- if($this->email_object->body){
+ if ($this->email_object->body) {
$this->email_object->body = $this->email_object->body;
- }
- elseif(strlen($this->email_object->settings->{$this->email_object->email_template_body}) > 3){
+ } elseif (strlen($this->email_object->settings->{$this->email_object->email_template_body}) > 3) {
$this->email_object->body = $this->email_object->settings->{$this->email_object->email_template_body};
- }
- else{
+ } else {
$this->email_object->body = EmailTemplateDefaults::getDefaultTemplate($this->email_object->email_template_body, $this->locale);
}
- if($this->template == 'email.template.custom'){
- $this->email_object->body = (str_replace('$body', $this->email_object->body, $this->email_object->settings->email_style_custom));
+ if ($this->template == 'email.template.custom') {
+ $this->email_object->body = (str_replace('$body', $this->email_object->body, $this->email_object->settings->email_style_custom));
}
return $this;
-
}
/**
@@ -180,16 +170,15 @@ class EmailDefaults
*/
private function setSubject(): self
{
-
- if ($this->email_object->subject) //where the user updates the subject from the UI
+ if ($this->email_object->subject) { //where the user updates the subject from the UI
return $this;
- elseif(strlen($this->email_object->settings->{$this->email_object->email_template_subject}) > 3)
+ } elseif (strlen($this->email_object->settings->{$this->email_object->email_template_subject}) > 3) {
$this->email_object->subject = $this->email_object->settings->{$this->email_object->email_template_subject};
- else
+ } else {
$this->email_object->subject = EmailTemplateDefaults::getDefaultTemplate($this->email_object->email_template_subject, $this->locale);
+ }
return $this;
-
}
/**
@@ -197,7 +186,6 @@ class EmailDefaults
*/
private function setReplyTo(): self
{
-
$reply_to_email = str_contains($this->email_object->settings->reply_to_email, "@") ? $this->email_object->settings->reply_to_email : $this->email_service->company->owner()->email;
$reply_to_name = strlen($this->email_object->settings->reply_to_name) > 3 ? $this->email_object->settings->reply_to_name : $this->email_service->company->owner()->present()->name();
@@ -208,18 +196,18 @@ class EmailDefaults
}
/**
- * Replaces the template placeholders
+ * Replaces the template placeholders
* with variable values.
*/
public function setVariables(): self
{
-
$this->email_object->body = strtr($this->email_object->body, $this->email_object->variables);
$this->email_object->subject = strtr($this->email_object->subject, $this->email_object->variables);
- if($this->template != 'custom')
+ if ($this->template != 'custom') {
$this->email_object->body = $this->parseMarkdownToHtml($this->email_object->body);
+ }
return $this;
}
@@ -233,16 +221,14 @@ class EmailDefaults
$bcc_array = [];
if (strlen($this->email_object->settings->bcc_email) > 1) {
-
if (Ninja::isHosted() && $this->email_service->company->account->isPaid()) {
$bccs = array_slice(explode(',', str_replace(' ', '', $this->email_object->settings->bcc_email)), 0, 2);
- } elseif(Ninja::isSelfHost()) {
+ } elseif (Ninja::isSelfHost()) {
$bccs = (explode(',', str_replace(' ', '', $this->email_object->settings->bcc_email)));
}
}
- foreach($bccs as $bcc)
- {
+ foreach ($bccs as $bcc) {
$bcc_array[] = new Address($bcc);
}
@@ -262,10 +248,10 @@ class EmailDefaults
];
}
- /**
+ /**
* Sets the attachments for the email
*
- * Note that we base64 encode these, as they
+ * Note that we base64 encode these, as they
* sometimes may not survive serialization.
*
* We decode these in the Mailable later
@@ -275,19 +261,14 @@ class EmailDefaults
$attachments = [];
if ($this->email_object->settings->document_email_attachment && $this->email_service->company->account->hasFeature(Account::FEATURE_DOCUMENTS)) {
-
foreach ($this->email_service->company->documents as $document) {
-
$attachments[] = ['file' => base64_encode($document->getFile()), 'name' => $document->name];
-
}
-
}
$this->email_object->attachments = array_merge($this->email_object->attachments, $attachments);
return $this;
-
}
/**
@@ -295,15 +276,16 @@ class EmailDefaults
*/
private function setHeaders(): self
{
- if($this->email_object->invitation_key)
+ if ($this->email_object->invitation_key) {
$this->email_object->headers = array_merge($this->email_object->headers, ['x-invitation-key' => $this->email_object->invitation_key]);
+ }
return $this;
}
/**
* Converts any markdown to HTML in the email
- *
+ *
* @param string $markdown The body to convert
* @return string The parsed markdown response
*/
@@ -315,5 +297,4 @@ class EmailDefaults
return $converter->convert($markdown);
}
-
-}
\ No newline at end of file
+}
diff --git a/app/Services/Email/EmailMailable.php b/app/Services/Email/EmailMailable.php
index fef31ca3ab30..116317e80e53 100644
--- a/app/Services/Email/EmailMailable.php
+++ b/app/Services/Email/EmailMailable.php
@@ -11,25 +11,22 @@
namespace App\Services\Email;
-use App\Services\Email\EmailObject;
-use Illuminate\Bus\Queueable;
-use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Attachment;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
-use Illuminate\Queue\SerializesModels;
use Illuminate\Mail\Mailables\Headers;
class EmailMailable extends Mailable
{
-
/**
* Create a new message instance.
*
* @return void
*/
- public function __construct(public EmailObject $email_object){}
+ public function __construct(public EmailObject $email_object)
+ {
+ }
/**
* Get the message envelope.
@@ -78,16 +75,13 @@ class EmailMailable extends Mailable
*/
public function attachments()
{
-
$attachments = [];
- foreach($this->email_object->attachments as $file)
- {
+ foreach ($this->email_object->attachments as $file) {
$attachments[] = Attachment::fromData(fn () => base64_decode($file['file']), $file['name']);
}
return $attachments;
-
}
/**
@@ -97,13 +91,10 @@ class EmailMailable extends Mailable
*/
public function headers()
{
-
return new Headers(
messageId: null,
references: [],
text: $this->email_object->headers,
);
-
}
-
}
diff --git a/app/Services/Email/EmailMailer.php b/app/Services/Email/EmailMailer.php
index 55fac55979ad..265b4f574c61 100644
--- a/app/Services/Email/EmailMailer.php
+++ b/app/Services/Email/EmailMailer.php
@@ -55,7 +55,9 @@ class EmailMailer implements ShouldQueue
protected $client_mailgun_domain = false;
- public function __construct(public EmailService $email_service, public Mailable $email_mailable){}
+ public function __construct(public EmailService $email_service, public Mailable $email_mailable)
+ {
+ }
public function backoff()
{
@@ -64,40 +66,39 @@ class EmailMailer implements ShouldQueue
public function handle(): void
{
-
- MultiDB::setDb($this->email_service->company->db);
+ MultiDB::setDb($this->email_service->company->db);
/* Perform final checks */
- if($this->email_service->preFlightChecksFail())
+ if ($this->email_service->preFlightChecksFail()) {
return;
+ }
/* Boot the required driver*/
- $this->setMailDriver();
+ $this->setMailDriver();
/* Init the mailer*/
- $mailer = Mail::mailer($this->mailer);
+ $mailer = Mail::mailer($this->mailer);
/* Additional configuration if using a client third party mailer */
- if($this->client_postmark_secret)
+ if ($this->client_postmark_secret) {
$mailer->postmark_config($this->client_postmark_secret);
+ }
- if($this->client_mailgun_secret)
+ if ($this->client_mailgun_secret) {
$mailer->mailgun_config($this->client_mailgun_secret, $this->client_mailgun_domain);
+ }
/* Attempt the send! */
try {
+ nlog("Using mailer => ". $this->mailer. " ". now()->toDateTimeString());
- nlog("Using mailer => ". $this->mailer. " ". now()->toDateTimeString());
-
- $mailer->send($this->email_mailable);
+ $mailer->send($this->email_mailable);
- Cache::increment($this->email_service->company->account->key);
-
- LightLogs::create(new EmailSuccess($this->email_service->company->company_key))
- ->send();
+ Cache::increment($this->email_service->company->account->key);
+ LightLogs::create(new EmailSuccess($this->email_service->company->company_key))
+ ->send();
} catch (\Exception | \RuntimeException | \Google\Service\Exception $e) {
-
nlog("Mailer failed with {$e->getMessage()}");
$message = $e->getMessage();
@@ -107,12 +108,11 @@ class EmailMailer implements ShouldQueue
* this merges a text string with a json object
* need to harvest the ->Message property using the following
*/
- if($e instanceof ClientException) { //postmark specific failure
-
+ if ($e instanceof ClientException) { //postmark specific failure
$response = $e->getResponse();
$message_body = json_decode($response->getBody()->getContents());
- if($message_body && property_exists($message_body, 'Message')){
+ if ($message_body && property_exists($message_body, 'Message')) {
$message = $message_body->Message;
nlog($message);
}
@@ -120,20 +120,17 @@ class EmailMailer implements ShouldQueue
$this->fail();
$this->cleanUpMailers();
return;
-
}
//only report once, not on all tries
- if($this->attempts() == $this->tries)
- {
-
+ if ($this->attempts() == $this->tries) {
/* If the is an entity attached to the message send a failure mailer */
$this->entityEmailFailed($message);
/* Don't send postmark failures to Sentry */
- if(Ninja::isHosted() && (!$e instanceof ClientException))
+ if (Ninja::isHosted() && (!$e instanceof ClientException)) {
app('sentry')->captureException($e);
-
+ }
}
@@ -141,12 +138,9 @@ class EmailMailer implements ShouldQueue
$this->release($this->backoff()[$this->attempts()-1]);
$message = null;
-
-
}
$this->cleanUpMailers();
-
}
/**
@@ -158,38 +152,39 @@ class EmailMailer implements ShouldQueue
*/
private function entityEmailFailed($message)
{
-
- if(!$this->email_service->email_object->entity_id)
+ if (!$this->email_service->email_object->entity_id) {
return;
+ }
switch ($this->email_service->email_object->entity_class) {
case Invoice::class:
- $invitation = InvoiceInvitation::withTrashed()->find($this->email_service->email_object->entity_id);
- if($invitation)
- event(new InvoiceWasEmailedAndFailed($invitation, $this->email_service->company, $message, $this->email_service->email_object->reminder_template, Ninja::eventVars(auth()->user() ? auth()->user()->id : null)));
+ $invitation = InvoiceInvitation::withTrashed()->find($this->email_service->email_object->entity_id);
+ if ($invitation) {
+ event(new InvoiceWasEmailedAndFailed($invitation, $this->email_service->company, $message, $this->email_service->email_object->reminder_template, Ninja::eventVars(auth()->user() ? auth()->user()->id : null)));
+ }
break;
case Payment::class:
- $payment = Payment::withTrashed()->find($this->email_service->email_object->entity_id);
- if($payment)
- event(new PaymentWasEmailedAndFailed($payment, $this->email_service->company, $message, Ninja::eventVars(auth()->user() ? auth()->user()->id : null)));
+ $payment = Payment::withTrashed()->find($this->email_service->email_object->entity_id);
+ if ($payment) {
+ event(new PaymentWasEmailedAndFailed($payment, $this->email_service->company, $message, Ninja::eventVars(auth()->user() ? auth()->user()->id : null)));
+ }
break;
default:
# code...
break;
}
- if ($this->email_service->email_object->client_contact instanceof ClientContact)
+ if ($this->email_service->email_object->client_contact instanceof ClientContact) {
$this->logMailError($message, $this->email_service->email_object->client_contact);
-
+ }
}
- /**
- * Sets the mail driver to use and applies any specific configuration
+ /**
+ * Sets the mail driver to use and applies any specific configuration
* the the mailable
*/
- private function setMailDriver(): self
+ private function setMailDriver(): self
{
-
switch ($this->email_service->email_object->settings->email_sending_method) {
case 'default':
$this->mailer = config('mail.default');
@@ -215,11 +210,11 @@ class EmailMailer implements ShouldQueue
break;
}
- if(Ninja::isSelfHost())
+ if (Ninja::isSelfHost()) {
$this->setSelfHostMultiMailer();
+ }
return $this;
-
}
/**
@@ -228,10 +223,7 @@ class EmailMailer implements ShouldQueue
*/
private function setSelfHostMultiMailer(): void
{
-
- if (env($this->email_service->company->id . '_MAIL_HOST'))
- {
-
+ if (env($this->email_service->company->id . '_MAIL_HOST')) {
config([
'mail.mailers.smtp' => [
'transport' => 'smtp',
@@ -242,20 +234,17 @@ class EmailMailer implements ShouldQueue
],
]);
- if(env($this->email_service->company->id . '_MAIL_FROM_ADDRESS'))
- {
- $this->email_mailable
- ->from(env($this->email_service->company->id . '_MAIL_FROM_ADDRESS', env('MAIL_FROM_ADDRESS')), env($this->email_service->company->id . '_MAIL_FROM_NAME', env('MAIL_FROM_NAME')));
+ if (env($this->email_service->company->id . '_MAIL_FROM_ADDRESS')) {
+ $this->email_mailable
+ ->from(env($this->email_service->company->id . '_MAIL_FROM_ADDRESS', env('MAIL_FROM_ADDRESS')), env($this->email_service->company->id . '_MAIL_FROM_NAME', env('MAIL_FROM_NAME')));
}
-
}
-
}
/**
* Ensure we discard any data that is not required
- *
+ *
* @return void
*/
private function cleanUpMailers(): void
@@ -266,21 +255,20 @@ class EmailMailer implements ShouldQueue
$this->client_mailgun_domain = false;
- //always dump the drivers to prevent reuse
+ //always dump the drivers to prevent reuse
app('mail.manager')->forgetMailers();
}
- /**
+ /**
* Check to ensure no cross account
* emails can be sent.
- *
+ *
* @param User $user
*/
private function checkValidSendingUser($user)
{
/* Always ensure the user is set on the correct account */
- if($user->account_id != $this->email_service->company->account_id)
- {
+ if ($user->account_id != $this->email_service->company->account_id) {
$this->email_service->email_object->settings->email_sending_method = 'default';
return $this->setMailDriver();
@@ -291,17 +279,18 @@ class EmailMailer implements ShouldQueue
* Resolves the sending user
* when configuring the Mailer
* on behalf of the client
- *
+ *
* @return User $user
*/
private function resolveSendingUser(): ?User
{
$sending_user = $this->email_service->email_object->settings->gmail_sending_user_id;
- if($sending_user == "0")
+ if ($sending_user == "0") {
$user = $this->email_service->company->owner();
- else
+ } else {
$user = User::find($this->decodePrimaryKey($sending_user));
+ }
return $user;
}
@@ -311,11 +300,10 @@ class EmailMailer implements ShouldQueue
*/
private function setMailgunMailer()
{
- if(strlen($this->email_service->email_object->settings->mailgun_secret) > 2 && strlen($this->email_service->email_object->settings->mailgun_domain) > 2){
+ if (strlen($this->email_service->email_object->settings->mailgun_secret) > 2 && strlen($this->email_service->email_object->settings->mailgun_domain) > 2) {
$this->client_mailgun_secret = $this->email_service->email_object->settings->mailgun_secret;
$this->client_mailgun_domain = $this->email_service->email_object->settings->mailgun_domain;
- }
- else{
+ } else {
$this->email_service->email_object->settings->email_sending_method = 'default';
return $this->setMailDriver();
}
@@ -325,8 +313,8 @@ class EmailMailer implements ShouldQueue
$sending_email = (isset($this->email_service->email_object->settings->custom_sending_email) && stripos($this->email_service->email_object->settings->custom_sending_email, "@")) ? $this->email_service->email_object->settings->custom_sending_email : $user->email;
$sending_user = (isset($this->email_service->email_object->settings->email_from_name) && strlen($this->email_service->email_object->settings->email_from_name) > 2) ? $this->email_service->email_object->settings->email_from_name : $user->name();
- $this->email_mailable
- ->from($sending_email, $sending_user);
+ $this->email_mailable
+ ->from($sending_email, $sending_user);
}
/**
@@ -335,10 +323,9 @@ class EmailMailer implements ShouldQueue
*/
private function setPostmarkMailer()
{
- if(strlen($this->email_service->email_object->settings->postmark_secret) > 2){
+ if (strlen($this->email_service->email_object->settings->postmark_secret) > 2) {
$this->client_postmark_secret = $this->email_service->email_object->settings->postmark_secret;
- }
- else{
+ } else {
$this->email_service->email_object->settings->email_sending_method = 'default';
return $this->setMailDriver();
}
@@ -348,8 +335,8 @@ class EmailMailer implements ShouldQueue
$sending_email = (isset($this->email_service->email_object->settings->custom_sending_email) && stripos($this->email_service->email_object->settings->custom_sending_email, "@")) ? $this->email_service->email_object->settings->custom_sending_email : $user->email;
$sending_user = (isset($this->email_service->email_object->settings->email_from_name) && strlen($this->email_service->email_object->settings->email_from_name) > 2) ? $this->email_service->email_object->settings->email_from_name : $user->name();
- $this->email_mailable
- ->from($sending_email, $sending_user);
+ $this->email_mailable
+ ->from($sending_email, $sending_user);
}
/**
@@ -366,25 +353,19 @@ class EmailMailer implements ShouldQueue
$token = $this->refreshOfficeToken($user);
- if($token)
- {
+ if ($token) {
$user->oauth_user_token = $token;
$user->save();
-
- }
- else {
-
+ } else {
$this->email_service->email_object->settings->email_sending_method = 'default';
return $this->setMailDriver();
-
}
$this->email_mailable
->from($user->email, $user->name())
- ->withSymfonyMessage(function ($message) use($token) {
- $message->getHeaders()->addTextHeader('gmailtoken', $token);
+ ->withSymfonyMessage(function ($message) use ($token) {
+ $message->getHeaders()->addTextHeader('gmailtoken', $token);
});
-
}
/**
@@ -393,7 +374,6 @@ class EmailMailer implements ShouldQueue
*/
private function setGmailMailer()
{
-
$user = $this->resolveSendingUser();
$this->checkValidSendingUser($user);
@@ -402,17 +382,14 @@ class EmailMailer implements ShouldQueue
$google = (new Google())->init();
- try{
-
+ try {
if ($google->getClient()->isAccessTokenExpired()) {
$google->refreshToken($user);
$user = $user->fresh();
}
$google->getClient()->setAccessToken(json_encode($user->oauth_user_token));
-
- }
- catch(\Exception $e) {
+ } catch(\Exception $e) {
$this->logMailError('Gmail Token Invalid', $this->email_service->company->clients()->first());
$this->email_service->email_object->settings->email_sending_method = 'default';
return $this->setMailDriver();
@@ -422,7 +399,7 @@ class EmailMailer implements ShouldQueue
* If the user doesn't have a valid token, notify them
*/
- if(!$user->oauth_user_token) {
+ if (!$user->oauth_user_token) {
$this->email_service->company->account->gmailCredentialNotification();
$this->email_service->email_object->settings->email_sending_method = 'default';
return $this->setMailDriver();
@@ -436,7 +413,7 @@ class EmailMailer implements ShouldQueue
$token = $user->oauth_user_token->access_token;
- if(!$token) {
+ if (!$token) {
$this->email_service->company->account->gmailCredentialNotification();
$this->email_service->email_object->settings->email_sending_method = 'default';
return $this->setMailDriver();
@@ -444,22 +421,20 @@ class EmailMailer implements ShouldQueue
$this->email_mailable
->from($user->email, $user->name())
- ->withSymfonyMessage(function ($message) use($token) {
- $message->getHeaders()->addTextHeader('gmailtoken', $token);
+ ->withSymfonyMessage(function ($message) use ($token) {
+ $message->getHeaders()->addTextHeader('gmailtoken', $token);
});
-
}
/**
* Logs any errors to the SystemLog
- *
+ *
* @param string $errors
* @param App\Models\User | App\Models\Client $recipient_object
* @return void
*/
private function logMailError($errors, $recipient_object) :void
{
-
(new SystemLogger(
$errors,
SystemLog::CATEGORY_MAIL,
@@ -477,12 +452,11 @@ class EmailMailer implements ShouldQueue
->send();
$job_failure = null;
-
}
/**
* Attempts to refresh the Microsoft refreshToken
- *
+ *
* @param App\Models\User
* @return mixed
*/
@@ -490,10 +464,9 @@ class EmailMailer implements ShouldQueue
{
$expiry = $user->oauth_user_token_expiry ?: now()->subDay();
- if($expiry->lt(now()))
- {
- $guzzle = new \GuzzleHttp\Client();
- $url = 'https://login.microsoftonline.com/common/oauth2/v2.0/token';
+ if ($expiry->lt(now())) {
+ $guzzle = new \GuzzleHttp\Client();
+ $url = 'https://login.microsoftonline.com/common/oauth2/v2.0/token';
$token = json_decode($guzzle->post($url, [
'form_params' => [
@@ -505,8 +478,7 @@ class EmailMailer implements ShouldQueue
],
])->getBody()->getContents());
- if($token){
-
+ if ($token) {
$user->oauth_user_refresh_token = property_exists($token, 'refresh_token') ? $token->refresh_token : $user->oauth_user_refresh_token;
$user->oauth_user_token = $token->access_token;
$user->oauth_user_token_expiry = now()->addSeconds($token->expires_in);
@@ -519,12 +491,9 @@ class EmailMailer implements ShouldQueue
}
return $user->oauth_user_token;
-
}
public function failed($exception = null)
{
-
}
-
}
diff --git a/app/Services/Email/EmailObject.php b/app/Services/Email/EmailObject.php
index 30edec78ccde..a7da351727b6 100644
--- a/app/Services/Email/EmailObject.php
+++ b/app/Services/Email/EmailObject.php
@@ -13,7 +13,6 @@ namespace App\Services\Email;
use App\Models\Client;
use App\Models\ClientContact;
-use App\Models\Company;
use App\Models\User;
use App\Models\Vendor;
use App\Models\VendorContact;
@@ -24,61 +23,59 @@ use Illuminate\Mail\Mailables\Address;
*/
class EmailObject
{
+ public array $to = [];
- public array $to = [];
+ public ?Address $from = null;
- public ?Address $from = null;
+ public array $reply_to = [];
- public array $reply_to = [];
+ public array $cc = [];
- public array $cc = [];
+ public array $bcc = [];
- public array $bcc = [];
+ public ?string $subject = null;
- public ?string $subject = null;
+ public ?string $body = null;
- public ?string $body = null;
+ public array $attachments = [];
- public array $attachments = [];
+ public string $company_key;
- public string $company_key;
+ public ?object $settings = null;
- public ?object $settings = null;
+ public bool $whitelabel = false;
- public bool $whitelabel = false;
+ public ?string $logo = null;
- public ?string $logo = null;
+ public ?string $signature = null;
- public ?string $signature = null;
+ public ?string $greeting = null;
- public ?string $greeting = null;
+ public ?Client $client = null;
- public ?Client $client = null;
+ public ?Vendor $vendor = null;
- public ?Vendor $vendor = null;
+ public ?User $user = null;
- public ?User $user = null;
+ public ?ClientContact $client_contact = null;
- public ?ClientContact $client_contact = null;
+ public ?VendorContact $vendor_contact = null;
- public ?VendorContact $vendor_contact = null;
+ public ?string $email_template_body = null;
- public ?string $email_template_body = null;
+ public ?string $email_template_subject = null;
- public ?string $email_template_subject = null;
+ public ?string $html_template = null;
- public ?string $html_template = null;
+ public ?string $text_template = 'email.template.text';
- public ?string $text_template = 'email.template.text';
+ public array $headers = [];
- public array $headers = [];
+ public ?string $invitation_key = null;
+
+ public ?int $entity_id = null;
- public ?string $invitation_key = null;
-
- public ?int $entity_id = null;
+ public ?string $entity_class = null;
- public ?string $entity_class = null;
-
- public array $variables = [];
-
-}
\ No newline at end of file
+ public array $variables = [];
+}
diff --git a/app/Services/Email/EmailService.php b/app/Services/Email/EmailService.php
index 5d2ddcc37da3..731815deaefc 100644
--- a/app/Services/Email/EmailService.php
+++ b/app/Services/Email/EmailService.php
@@ -12,23 +12,23 @@
namespace App\Services\Email;
use App\Models\Company;
-use App\Services\Email\EmailObject;
use App\Utils\Ninja;
use Illuminate\Mail\Mailable;
class EmailService
{
-
/**
* Used to flag whether we force send the email regardless
- *
+ *
* @var bool $override;
*/
protected bool $override;
public Mailable $mailable;
- public function __construct(public EmailObject $email_object, public Company $company){}
+ public function __construct(public EmailObject $email_object, public Company $company)
+ {
+ }
/**
* Sends the email via a dispatched job
@@ -53,11 +53,11 @@ class EmailService
private function email($force = false): void
{
- if($force)
+ if ($force) {
(new EmailMailer($this, $this->mailable))->handle();
- else
+ } else {
EmailMailer::dispatch($this, $this->mailable)->delay(2);
-
+ }
}
private function setDefaults(): self
@@ -76,41 +76,45 @@ class EmailService
}
/**
- * On the hosted platform we scan all outbound email for
+ * On the hosted platform we scan all outbound email for
* spam. This sequence processes the filters we use on all
* emails.
- *
+ *
* @return bool
*/
public function preFlightChecksFail(): bool
{
-
/* If we are migrating data we don't want to fire any emails */
- if($this->company->is_disabled && !$this->override)
+ if ($this->company->is_disabled && !$this->override) {
return true;
+ }
- if(Ninja::isSelfHost())
+ if (Ninja::isSelfHost()) {
return false;
+ }
/* To handle spam users we drop all emails from flagged accounts */
- if($this->company->account && $this->company->account->is_flagged)
+ if ($this->company->account && $this->company->account->is_flagged) {
return true;
+ }
/* On the hosted platform we set default contacts a @example.com email address - we shouldn't send emails to these types of addresses */
- if($this->hasInValidEmails())
+ if ($this->hasInValidEmails()) {
return true;
+ }
/* GMail users are uncapped */
- if(in_array($this->email_object->settings->email_sending_method, ['gmail', 'office365', 'client_postmark', 'client_mailgun']))
+ if (in_array($this->email_object->settings->email_sending_method, ['gmail', 'office365', 'client_postmark', 'client_mailgun'])) {
return false;
+ }
/* On the hosted platform, if the user is over the email quotas, we do not send the email. */
- if($this->company->account && $this->company->account->emailQuotaExceeded())
+ if ($this->company->account && $this->company->account->emailQuotaExceeded()) {
return true;
+ }
/* If the account is verified, we allow emails to flow */
- if($this->company->account && $this->company->account->is_verified_account) {
-
+ if ($this->company->account && $this->company->account->is_verified_account) {
//11-01-2022
/* Continue to analyse verified accounts in case they later start sending poor quality emails*/
@@ -121,40 +125,39 @@ class EmailService
}
/* On the hosted platform if the user has not verified their account we fail here - but still check what they are trying to send! */
- if($this->company->account && !$this->company->account->account_sms_verified){
-
- if(class_exists(\Modules\Admin\Jobs\Account\EmailFilter::class))
+ if ($this->company->account && !$this->company->account->account_sms_verified) {
+ if (class_exists(\Modules\Admin\Jobs\Account\EmailFilter::class)) {
return (new \Modules\Admin\Jobs\Account\EmailFilter($this->email_object, $this->company))->run();
+ }
return true;
}
/* On the hosted platform we actively scan all outbound emails to ensure outbound email quality remains high */
- if(class_exists(\Modules\Admin\Jobs\Account\EmailFilter::class))
+ if (class_exists(\Modules\Admin\Jobs\Account\EmailFilter::class)) {
return (new \Modules\Admin\Jobs\Account\EmailFilter($this->email_object, $this->company))->run();
+ }
return false;
}
private function hasInValidEmails(): bool
{
-
- foreach($this->email_object->to as $address_object)
- {
-
- if(strpos($address_object->address, '@example.com') !== false)
+ foreach ($this->email_object->to as $address_object) {
+ if (strpos($address_object->address, '@example.com') !== false) {
return true;
+ }
- if(!str_contains($address_object->address, "@"))
+ if (!str_contains($address_object->address, "@")) {
return true;
+ }
- if($address_object->address == " ")
+ if ($address_object->address == " ") {
return true;
+ }
}
return false;
}
-
-
-}
\ No newline at end of file
+}
diff --git a/app/Services/Email/MailBuild.php b/app/Services/Email/MailBuild.php
index 4117a9b72ff7..51ac2a89e452 100644
--- a/app/Services/Email/MailBuild.php
+++ b/app/Services/Email/MailBuild.php
@@ -11,36 +11,35 @@
namespace App\Services\Email;
-use App\Models\Task;
-use App\Utils\Ninja;
-use App\Models\Quote;
-use App\Models\Client;
-use App\Models\Credit;
-use App\Models\Vendor;
+use App\DataMapper\EmailTemplateDefaults;
+use App\Jobs\Entity\CreateRawPdf;
+use App\Jobs\Vendor\CreatePurchaseOrderPdf;
use App\Models\Account;
+use App\Models\Client;
+use App\Models\ClientContact;
+use App\Models\Credit;
use App\Models\Expense;
use App\Models\Invoice;
-use App\Utils\HtmlEngine;
-use App\Models\ClientContact;
use App\Models\PurchaseOrder;
+use App\Models\Quote;
+use App\Models\Task;
+use App\Models\Vendor;
use App\Models\VendorContact;
+use App\Utils\HtmlEngine;
+use App\Utils\Ninja;
use App\Utils\Traits\MakesHash;
use App\Utils\VendorHtmlEngine;
-use App\Jobs\Entity\CreateRawPdf;
+use Illuminate\Contracts\Mail\Mailable;
+use Illuminate\Mail\Mailables\Address;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\URL;
-use App\Services\Email\MailMailable;
-use Illuminate\Mail\Mailables\Address;
-use Illuminate\Contracts\Mail\Mailable;
-use App\DataMapper\EmailTemplateDefaults;
use League\CommonMark\CommonMarkConverter;
-use App\Jobs\Vendor\CreatePurchaseOrderPdf;
class MailBuild
{
use MakesHash;
- /** @var mixed $settings */
+ /** @var mixed $settings */
protected $settings;
/** @var string $template */
@@ -70,7 +69,9 @@ class MailBuild
* @param MailEntity $mail_entity
* @return void
*/
- public function __construct(public MailEntity $mail_entity){}
+ public function __construct(public MailEntity $mail_entity)
+ {
+ }
/**
* Builds the mailable
@@ -113,7 +114,6 @@ class MailBuild
*/
private function resolveEntities(): self
{
-
$client_contact = $this->mail_entity?->invitation?->client_contact_id ? ClientContact::withTrashed()->find($this->mail_entity->invitation->client_contact_id) : null;
$this->client = $client_contact?->client;
@@ -122,26 +122,24 @@ class MailBuild
$this->vendor = $vendor_contact?->vendor;
- if($this->mail_entity?->invitation){
-
-
- if($this->mail_entity->invitation?->invoice){
+ if ($this->mail_entity?->invitation) {
+ if ($this->mail_entity->invitation?->invoice) {
$this->mail_entity->mail_object->entity_string = 'invoice';
$this->mail_entity->mail_object->entity_class = Invoice::class;
}
- if($this->mail_entity->invitation?->quote){
- $this->mail_entity->mail_object->entity_string = 'quote';
+ if ($this->mail_entity->invitation?->quote) {
+ $this->mail_entity->mail_object->entity_string = 'quote';
$this->mail_entity->mail_object->entity_class = Quote::class;
}
- if($this->mail_entity->invitation?->credit){
- $this->mail_entity->mail_object->entity_string = 'credit';
+ if ($this->mail_entity->invitation?->credit) {
+ $this->mail_entity->mail_object->entity_string = 'credit';
$this->mail_entity->mail_object->entity_class = Credit::class;
}
- if($this->mail_entity->invitation?->puchase_order){
- $this->mail_entity->mail_object->entity_string = 'purchase_order';
+ if ($this->mail_entity->invitation?->puchase_order) {
+ $this->mail_entity->mail_object->entity_string = 'purchase_order';
$this->mail_entity->mail_object->entity_class = PurchaseOrder::class;
}
}
@@ -158,31 +156,23 @@ class MailBuild
*/
private function setLocale(): self
{
-
- if($this->client){
-
+ if ($this->client) {
$this->locale = $this->client->locale();
$this->settings = $this->client->getMergedSettings();
- if($this->mail_entity->invitation)
+ if ($this->mail_entity->invitation) {
$this->variables = (new HtmlEngine($this->mail_entity->invitation))->makeValues();
-
- }
- elseif($this->vendor){
-
+ }
+ } elseif ($this->vendor) {
$this->locale = $this->vendor->locale();
$this->settings = $this->mail_entity->company->settings;
- if($this->mail_entity->invitation)
+ if ($this->mail_entity->invitation) {
$this->variables = (new VendorHtmlEngine($this->mail_entity->invitation))->makeValues();
-
-
- }
- else{
-
+ }
+ } else {
$this->locale = $this->mail_entity->company->locale();
$this->settings = $this->mail_entity->company->settings;
-
}
$this->mail_entity->mail_object->settings = $this->settings;
@@ -202,7 +192,6 @@ class MailBuild
*/
private function setMetaData(): self
{
-
$this->mail_entity->mail_object->company_key = $this->mail_entity->company->company_key;
$this->mail_entity->mail_object->logo = $this->mail_entity->company->present()->logo();
@@ -214,7 +203,6 @@ class MailBuild
$this->mail_entity->mail_object->company = $this->mail_entity->company;
return $this;
-
}
/**
@@ -226,14 +214,14 @@ class MailBuild
{
$this->template = $this->settings->email_style;
- match($this->settings->email_style){
+ match ($this->settings->email_style) {
'light' => $this->template = 'email.template.client',
'dark' => $this->template = 'email.template.client',
'custom' => $this->template = 'email.template.custom',
default => $this->template = 'email.template.client',
- };
+ };
- $this->mail_entity->mail_object->html_template = $this->template;
+ $this->mail_entity->mail_object->html_template = $this->template;
return $this;
}
@@ -245,11 +233,10 @@ class MailBuild
*/
private function setTo(): self
{
-
$this->mail_entity->mail_object->to = array_merge(
- $this->mail_entity->mail_object->to ,
- [new Address($this->mail_entity->invitation->contact->email, $this->mail_entity->invitation->contact->present()->name())]
- );
+ $this->mail_entity->mail_object->to,
+ [new Address($this->mail_entity->invitation->contact->email, $this->mail_entity->invitation->contact->present()->name())]
+ );
return $this;
}
@@ -260,20 +247,19 @@ class MailBuild
* @return self
*/
private function setFrom(): self
- {
-
- if(Ninja::isHosted() && $this->settings->email_sending_method == 'default'){
+ {
+ if (Ninja::isHosted() && $this->settings->email_sending_method == 'default') {
$this->mail_entity->mail_object->from = new Address(config('mail.from.address'), $this->mail_entity->company->owner()->name());
return $this;
}
- if($this->mail_entity->mail_object->from)
+ if ($this->mail_entity->mail_object->from) {
return $this;
+ }
$this->mail_entity->mail_object->from = new Address($this->mail_entity->company->owner()->email, $this->mail_entity->company->owner()->name());
return $this;
-
}
/**
@@ -283,16 +269,15 @@ class MailBuild
*/
private function setSubject(): self
{
-
- if ($this->mail_entity->mail_object->subject) //where the user updates the subject from the UI
+ if ($this->mail_entity->mail_object->subject) { //where the user updates the subject from the UI
return $this;
- elseif(is_string($this->mail_entity->mail_object->email_template) && strlen($this->settings->{$this->resolveBaseEntityTemplate()}) > 3)
+ } elseif (is_string($this->mail_entity->mail_object->email_template) && strlen($this->settings->{$this->resolveBaseEntityTemplate()}) > 3) {
$this->mail_entity->mail_object->subject = $this->settings->{$this->resolveBaseEntityTemplate()};
- else
+ } else {
$this->mail_entity->mail_object->subject = EmailTemplateDefaults::getDefaultTemplate($this->resolveBaseEntityTemplate(), $this->locale);
+ }
return $this;
-
}
/**
@@ -302,27 +287,23 @@ class MailBuild
*/
private function setBody(): self
{
-
- if($this->mail_entity->mail_object->body){
+ if ($this->mail_entity->mail_object->body) {
$this->mail_entity->mail_object->body = $this->mail_entity->mail_object->body;
- }
- elseif(is_string($this->mail_entity->mail_object->email_template) && strlen($this->settings->{$this->resolveBaseEntityTemplate('body')}) > 3){
+ } elseif (is_string($this->mail_entity->mail_object->email_template) && strlen($this->settings->{$this->resolveBaseEntityTemplate('body')}) > 3) {
$this->mail_entity->mail_object->body = $this->settings->{$this->resolveBaseEntityTemplate('body')};
- }
- else{
+ } else {
$this->mail_entity->mail_object->body = EmailTemplateDefaults::getDefaultTemplate($this->resolveBaseEntityTemplate('body'), $this->locale);
}
- if($this->template == 'email.template.custom'){
- $this->mail_entity->mail_object->body = (str_replace('$body', $this->mail_entity->mail_object->body, $this->settings->email_style_custom));
+ if ($this->template == 'email.template.custom') {
+ $this->mail_entity->mail_object->body = (str_replace('$body', $this->mail_entity->mail_object->body, $this->settings->email_style_custom));
}
return $this;
-
}
/**
- * Where no template is explicitly passed, we need to infer by the entity type -
+ * Where no template is explicitly passed, we need to infer by the entity type -
* which is hopefully resolvable.
*
* @param string $type
@@ -330,9 +311,8 @@ class MailBuild
*/
private function resolveBaseEntityTemplate(string $type = 'subject'): string
{
- if($this->mail_entity->mail_object->email_template){
-
- match($type){
+ if ($this->mail_entity->mail_object->email_template) {
+ match ($type) {
'subject' => $template = "email_subject_{$this->mail_entity->mail_object->email_template}",
'body' => $template = "email_template_{$this->mail_entity->mail_object->email_template}",
default => $template = "email_template_invoice",
@@ -343,52 +323,48 @@ class MailBuild
//handle statements being emailed
//handle custom templates these types won't have a resolvable entity_string
- if(!$this->mail_entity->mail_object->entity_string)
+ if (!$this->mail_entity->mail_object->entity_string) {
return 'email_template_invoice';
+ }
- match($type){
+ match ($type) {
'subject' => $template = "email_subject_{$this->mail_entity->mail_object->entity_string}",
'body' => $template = "email_template_{$this->mail_entity->mail_object->entity_string}",
default => $template = "email_template_invoice",
- };
+ };
- return $template;
+ return $template;
}
- /**
+ /**
* Sets the attachments for the email
*
- * Note that we base64 encode these, as they
+ * Note that we base64 encode these, as they
* sometimes may not survive serialization.
*
* We decode these in the Mailable later
- *
+ *
* @return self
- */
+ */
private function setAttachments(): self
{
$this->setContextAttachments();
if ($this->settings->document_email_attachment && $this->mail_entity->company->account->hasFeature(Account::FEATURE_DOCUMENTS)) {
-
$this->attachDocuments($this->mail_entity->company->documents);
-
}
return $this;
-
}
private function attachDocuments($documents): self
{
-
foreach ($documents as $document) {
-
- if($document->size > $this->max_attachment_size)
+ if ($document->size > $this->max_attachment_size) {
$this->mail_entity->mail_object->attachment_links = array_merge($this->mail_entity->mail_object->attachment_links, [[" $document->hash]) ."'>". $document->name .""]]);
- else
- $this->mail_entity->mail_object->attachments = array_merge($this->mail_entity->mail_object->attachments,[['file' => base64_encode($document->getFile()), 'name' => $document->name]]);
-
+ } else {
+ $this->mail_entity->mail_object->attachments = array_merge($this->mail_entity->mail_object->attachments, [['file' => base64_encode($document->getFile()), 'name' => $document->name]]);
+ }
}
return $this;
@@ -397,7 +373,7 @@ class MailBuild
/**
* Depending on context we may need to resolve the
* attachment dependencies.
- *
+ *
* ie. Resolve the entity.
* ie. Resolve if we should attach the Entity PDF
* ie. Create the Entity PDF
@@ -407,52 +383,43 @@ class MailBuild
*/
private function setContextAttachments(): self
{
-
- if(!$this->settings->pdf_email_attachment || !$this->mail_entity->company->account->hasFeature(Account::FEATURE_PDF_ATTACHMENT))
+ if (!$this->settings->pdf_email_attachment || !$this->mail_entity->company->account->hasFeature(Account::FEATURE_PDF_ATTACHMENT)) {
return $this;
+ }
- if($this->mail_entity->invitation?->purchase_order){
-
+ if ($this->mail_entity->invitation?->purchase_order) {
$pdf = (new CreatePurchaseOrderPdf($this->mail_entity->invitation))->rawPdf();
$this->mail_entity->mail_object->attachments = array_merge($this->mail_entity->mail_object->attachments, [['file' => base64_encode($pdf), 'name' => $this->mail_entity->invitation->purchase_order->numberFormatter().'.pdf']]);
if ($this->vendor->getSetting('document_email_attachment') !== false && $this->mail_entity->company->account->hasFeature(Account::FEATURE_DOCUMENTS)) {
-
$this->attachDocuments($this->mail_entity->invitation->purchase_order->documents);
-
}
return $this;
-
}
- if(!$this->mail_entity->mail_object->entity_string)
+ if (!$this->mail_entity->mail_object->entity_string) {
return $this;
+ }
$pdf = ((new CreateRawPdf($this->mail_entity->invitation, $this->mail_entity->invitation->company->db))->handle());
$this->mail_entity->mail_object->attachments = array_merge($this->mail_entity->mail_object->attachments, [['file' => base64_encode($pdf), 'name' => $this->mail_entity->invitation->{$this->mail_entity->mail_object->entity_string}->numberFormatter().'.pdf']]);
if ($this->client->getSetting('document_email_attachment') !== false && $this->mail_entity->company->account->hasFeature(Account::FEATURE_DOCUMENTS)) {
-
$this->attachDocuments($this->mail_entity->invitation->{$this->mail_entity->mail_object->entity_string}->documents);
-
}
- return $this;
+ return $this;
- if($this->settings->ubl_email_attachment && $this->mail_entity->mail_object->entity_string == 'invoice')
- {
-
- }
+ if ($this->settings->ubl_email_attachment && $this->mail_entity->mail_object->entity_string == 'invoice') {
+ }
- if($this->mail_entity->mail_object->entity_string == 'invoice')
- {
-
+ if ($this->mail_entity->mail_object->entity_string == 'invoice') {
$line_items = $this->mail_entity->invitation->invoice->line_items;
foreach ($line_items as $item) {
@@ -467,9 +434,7 @@ class MailBuild
->where('invoice_documents', 1)
->cursor()
->each(function ($expense) {
-
- $this->attachDocuments($expense->documents);
-
+ $this->attachDocuments($expense->documents);
});
}
@@ -483,28 +448,24 @@ class MailBuild
$tasks = Task::whereIn('id', $this->transformKeys($task_ids))
->cursor()
->each(function ($task) {
-
- $this->attachDocuments($task->documents);
-
+ $this->attachDocuments($task->documents);
});
}
}
}
- return $this;
-
+ return $this;
}
/**
* Sets the reply to of the email
- *
+ *
* @return self
*/
private function setReplyTo(): self
{
-
$reply_to_email = str_contains($this->settings->reply_to_email, "@") ? $this->settings->reply_to_email : $this->mail_entity->company->owner()->email;
$reply_to_name = strlen($this->settings->reply_to_name) > 3 ? $this->settings->reply_to_name : $this->mail_entity->company->owner()->present()->name();
@@ -515,15 +476,14 @@ class MailBuild
}
/**
- * Replaces the template placeholders
+ * Replaces the template placeholders
* with variable values.
- *
+ *
* @return self
*/
public function setVariables(): self
{
-
- if($this->mail_entity->mail_object->variables){
+ if ($this->mail_entity->mail_object->variables) {
$this->mail_entity->mail_object->subject = strtr($this->mail_entity->mail_object->subject, $this->mail_entity->mail_object->variables);
$this->mail_entity->mail_object->body = strtr($this->mail_entity->mail_object->body, $this->mail_entity->mail_object->variables);
}
@@ -531,16 +491,16 @@ class MailBuild
$this->mail_entity->mail_object->subject = strtr($this->mail_entity->mail_object->subject, $this->variables);
$this->mail_entity->mail_object->body = strtr($this->mail_entity->mail_object->body, $this->variables);
- if($this->template != 'custom')
+ if ($this->template != 'custom') {
$this->mail_entity->mail_object->body = $this->parseMarkdownToHtml($this->mail_entity->mail_object->body);
+ }
return $this;
-
}
/**
* Sets the BCC of the email
- *
+ *
* @return self
*/
private function setBcc(): self
@@ -549,16 +509,14 @@ class MailBuild
$bcc_array = [];
if (strlen($this->settings->bcc_email) > 1) {
-
if (Ninja::isHosted() && $this->mail_entity->company->account->isPaid()) {
$bccs = array_slice(explode(',', str_replace(' ', '', $this->settings->bcc_email)), 0, 2);
- } elseif(Ninja::isSelfHost()) {
+ } elseif (Ninja::isSelfHost()) {
$bccs = (explode(',', str_replace(' ', '', $this->settings->bcc_email)));
}
}
- foreach($bccs as $bcc)
- {
+ foreach ($bccs as $bcc) {
$bcc_array[] = new Address($bcc);
}
@@ -581,22 +539,23 @@ class MailBuild
/**
* Sets the headers for the email
- *
+ *
* @return self
*/
private function setHeaders(): self
{
- if($this->mail_entity->mail_object->invitation_key)
+ if ($this->mail_entity->mail_object->invitation_key) {
$this->mail_entity->mail_object->headers = array_merge($this->mail_entity->mail_object->headers, ['x-invitation-key' => $this->mail_entity->mail_object->invitation_key]);
- elseif($this->mail_entity->invitation)
+ } elseif ($this->mail_entity->invitation) {
$this->mail_entity->mail_object->headers = array_merge($this->mail_entity->mail_object->headers, ['x-invitation-key' => $this->mail_entity->invitation->key]);
+ }
return $this;
}
/**
* Converts any markdown to HTML in the email
- *
+ *
* @param string $markdown The body to convert
* @return string The parsed markdown response
*/
@@ -608,8 +567,4 @@ class MailBuild
return $converter->convert($markdown);
}
-
-
-
-
}
diff --git a/app/Services/Email/MailEntity.php b/app/Services/Email/MailEntity.php
index 3ba13719f267..14e6b2a7b392 100644
--- a/app/Services/Email/MailEntity.php
+++ b/app/Services/Email/MailEntity.php
@@ -11,24 +11,23 @@
namespace App\Services\Email;
+use App\DataMapper\Analytics\EmailSuccess;
+use App\Libraries\Google\Google;
+use App\Libraries\MultiDB;
+use App\Models\Company;
use App\Models\User;
use App\Utils\Ninja;
-use App\Models\Company;
-use App\Libraries\MultiDB;
-use Illuminate\Bus\Queueable;
-use Illuminate\Mail\Mailable;
use App\Utils\Traits\MakesHash;
-use App\Libraries\Google\Google;
-use App\Services\Email\MailBuild;
-use Illuminate\Support\Facades\Mail;
-use Illuminate\Support\Facades\Cache;
-use Illuminate\Queue\SerializesModels;
-use Turbo124\Beacon\Facades\LightLogs;
-use Illuminate\Queue\InteractsWithQueue;
use GuzzleHttp\Exception\ClientException;
-use App\DataMapper\Analytics\EmailSuccess;
+use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
+use Illuminate\Mail\Mailable;
+use Illuminate\Queue\InteractsWithQueue;
+use Illuminate\Queue\SerializesModels;
+use Illuminate\Support\Facades\Cache;
+use Illuminate\Support\Facades\Mail;
+use Turbo124\Beacon\Facades\LightLogs;
class MailEntity implements ShouldQueue
{
@@ -62,7 +61,9 @@ class MailEntity implements ShouldQueue
* @param mixed $mail_object
* @return void
*/
- public function __construct(public mixed $invitation, private ?string $db, public MailObject $mail_object){}
+ public function __construct(public mixed $invitation, private ?string $db, public MailObject $mail_object)
+ {
+ }
/**
* Handle the job
@@ -71,7 +72,6 @@ class MailEntity implements ShouldQueue
*/
public function handle(): void
{
-
MultiDB::setDb($this->db);
/* Where there are no invitations, we need to harvest the company and also use the correct context to build the mailable*/
@@ -81,19 +81,19 @@ class MailEntity implements ShouldQueue
$builder = new MailBuild($this);
- /* Construct Mailable */
+ /* Construct Mailable */
$builder->run($this);
$this->mailable = $builder->getMailable();
/* Email quality checks */
- if($this->preFlightChecksFail())
+ if ($this->preFlightChecksFail()) {
return;
+ }
/* Try sending email */
$this->setMailDriver()
->trySending();
-
}
public function configureMailer(): self
@@ -106,13 +106,12 @@ class MailEntity implements ShouldQueue
}
- /**
- * Sets the mail driver to use and applies any specific configuration
+ /**
+ * Sets the mail driver to use and applies any specific configuration
* the the mailable
*/
- private function setMailDriver(): self
+ private function setMailDriver(): self
{
-
switch ($this->mail_object->settings->email_sending_method) {
case 'default':
$this->mailer = config('mail.default');
@@ -138,11 +137,11 @@ class MailEntity implements ShouldQueue
break;
}
- if(Ninja::isSelfHost())
+ if (Ninja::isSelfHost()) {
$this->setSelfHostMultiMailer();
+ }
return $this;
-
}
/**
@@ -151,10 +150,7 @@ class MailEntity implements ShouldQueue
*/
private function setSelfHostMultiMailer(): void
{
-
- if (env($this->company->id . '_MAIL_HOST'))
- {
-
+ if (env($this->company->id . '_MAIL_HOST')) {
config([
'mail.mailers.smtp' => [
'transport' => 'smtp',
@@ -165,20 +161,17 @@ class MailEntity implements ShouldQueue
],
]);
- if(env($this->company->id . '_MAIL_FROM_ADDRESS'))
- {
- $this->mailable
- ->from(env($this->company->id . '_MAIL_FROM_ADDRESS', env('MAIL_FROM_ADDRESS')), env($this->company->id . '_MAIL_FROM_NAME', env('MAIL_FROM_NAME')));
+ if (env($this->company->id . '_MAIL_FROM_ADDRESS')) {
+ $this->mailable
+ ->from(env($this->company->id . '_MAIL_FROM_ADDRESS', env('MAIL_FROM_ADDRESS')), env($this->company->id . '_MAIL_FROM_NAME', env('MAIL_FROM_NAME')));
}
-
}
-
}
/**
* Ensure we discard any data that is not required
- *
+ *
* @return void
*/
private function cleanUpMailers(): void
@@ -201,7 +194,6 @@ class MailEntity implements ShouldQueue
public function trySending(): void
{
try {
-
$mail = Mail::mailer($this->mailer);
$mail->send($this->mailable);
@@ -210,24 +202,19 @@ class MailEntity implements ShouldQueue
LightLogs::create(new EmailSuccess($this->company->company_key))
->send();
-
- }
- 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){
- nlog("Mailer failed with a Logic Exception {$e->getMessage()}");
- $this->fail();
- $this->cleanUpMailers();
- // $this->logMailError($e->getMessage(), $this->company->clients()->first());
- return;
- }
- catch (\Exception | \Google\Service\Exception $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) {
+ nlog("Mailer failed with a Logic Exception {$e->getMessage()}");
+ $this->fail();
+ $this->cleanUpMailers();
+ // $this->logMailError($e->getMessage(), $this->company->clients()->first());
+ return;
+ } catch (\Exception | \Google\Service\Exception $e) {
nlog("Mailer failed with {$e->getMessage()}");
$message = $e->getMessage();
@@ -236,9 +223,7 @@ class MailEntity implements ShouldQueue
* this merges a text string with a json object
* need to harvest the ->Message property using the following
*/
- if(stripos($e->getMessage(), 'code 406') || stripos($e->getMessage(), 'code 300') || stripos($e->getMessage(), 'code 413'))
- {
-
+ if (stripos($e->getMessage(), 'code 406') || stripos($e->getMessage(), 'code 300') || stripos($e->getMessage(), 'code 413')) {
$message = "Either Attachment too large, or recipient has been suppressed.";
$this->fail();
@@ -246,63 +231,65 @@ class MailEntity implements ShouldQueue
$this->cleanUpMailers();
return;
-
}
//only report once, not on all tries
- if($this->attempts() == $this->tries)
- {
-
+ if ($this->attempts() == $this->tries) {
/* If the is an entity attached to the message send a failure mailer */
- if($this->mail_object->entity_id)
+ if ($this->mail_object->entity_id) {
// $this->entityEmailFailed($message);
- /* Don't send postmark failures to Sentry */
- if(Ninja::isHosted() && (!$e instanceof ClientException))
- app('sentry')->captureException($e);
-
+ /* Don't send postmark failures to Sentry */
+ if (Ninja::isHosted() && (!$e instanceof ClientException)) {
+ app('sentry')->captureException($e);
+ }
+ }
}
/* Releasing immediately does not add in the backoff */
$this->release($this->backoff()[$this->attempts()-1]);
-
}
}
/**
- * On the hosted platform we scan all outbound email for
+ * On the hosted platform we scan all outbound email for
* spam. This sequence processes the filters we use on all
* emails.
*/
public function preFlightChecksFail(): bool
{
/* Handle bad state */
- if(!$this->company)
+ if (!$this->company) {
return true;
+ }
/* Handle deactivated company */
- if($this->company->is_disabled && !$this->override)
+ if ($this->company->is_disabled && !$this->override) {
return true;
+ }
/* To handle spam users we drop all emails from flagged accounts */
- if(Ninja::isHosted() && $this->company->account && $this->company->account->is_flagged)
+ if (Ninja::isHosted() && $this->company->account && $this->company->account->is_flagged) {
return true;
+ }
/* On the hosted platform we set default contacts a @example.com email address - we shouldn't send emails to these types of addresses */
- if($this->hasInValidEmails())
+ if ($this->hasInValidEmails()) {
return true;
+ }
/* GMail users are uncapped */
- if(in_array($this->mail_object->settings->email_sending_method, ['gmail', 'office365', 'client_postmark', 'client_mailgun']))
+ if (in_array($this->mail_object->settings->email_sending_method, ['gmail', 'office365', 'client_postmark', 'client_mailgun'])) {
return false;
+ }
/* On the hosted platform, if the user is over the email quotas, we do not send the email. */
- if(Ninja::isHosted() && $this->company->account && $this->company->account->emailQuotaExceeded())
+ if (Ninja::isHosted() && $this->company->account && $this->company->account->emailQuotaExceeded()) {
return true;
+ }
/* If the account is verified, we allow emails to flow */
- if(Ninja::isHosted() && $this->company->account && $this->company->account->is_verified_account) {
-
+ if (Ninja::isHosted() && $this->company->account && $this->company->account->is_verified_account) {
//11-01-2022
/* Continue to analyse verified accounts in case they later start sending poor quality emails*/
@@ -314,21 +301,20 @@ class MailEntity implements ShouldQueue
/* On the hosted platform if the user has not verified their account we fail here - but still check what they are trying to send! */
- if($this->company->account && !$this->company->account->account_sms_verified){
-
- if(class_exists(\Modules\Admin\Jobs\Account\EmailFilter::class))
+ if ($this->company->account && !$this->company->account->account_sms_verified) {
+ if (class_exists(\Modules\Admin\Jobs\Account\EmailFilter::class)) {
(new \Modules\Admin\Jobs\Account\EmailFilter($this->mail_object, $this->company))->run();
+ }
return true;
-
}
/* On the hosted platform we actively scan all outbound emails to ensure outbound email quality remains high */
- if(class_exists(\Modules\Admin\Jobs\Account\EmailFilter::class))
+ if (class_exists(\Modules\Admin\Jobs\Account\EmailFilter::class)) {
(new \Modules\Admin\Jobs\Account\EmailFilter($this->mail_object, $this->company))->run();
+ }
return false;
-
}
@@ -339,20 +325,22 @@ class MailEntity implements ShouldQueue
*/
private function hasInValidEmails(): bool
{
- if(Ninja::isSelfHost())
+ if (Ninja::isSelfHost()) {
return false;
+ }
- foreach($this->mail_object->to as $address_object)
- {
-
- if(strpos($address_object->address, '@example.com') !== false)
+ foreach ($this->mail_object->to as $address_object) {
+ if (strpos($address_object->address, '@example.com') !== false) {
return true;
+ }
- if(!str_contains($address_object->address, "@"))
+ if (!str_contains($address_object->address, "@")) {
return true;
+ }
- if($address_object->address == " ")
+ if ($address_object->address == " ") {
return true;
+ }
}
@@ -360,17 +348,16 @@ class MailEntity implements ShouldQueue
}
- /**
+ /**
* Check to ensure no cross account
* emails can be sent.
- *
+ *
* @param User $user
*/
private function checkValidSendingUser($user)
{
/* Always ensure the user is set on the correct account */
- if($user->account_id != $this->company->account_id){
-
+ if ($user->account_id != $this->company->account_id) {
$this->mail_object->settings->email_sending_method = 'default';
return $this->setMailDriver();
}
@@ -380,17 +367,18 @@ class MailEntity implements ShouldQueue
* Resolves the sending user
* when configuring the Mailer
* on behalf of the client
- *
+ *
* @return User $user
*/
private function resolveSendingUser(): ?User
{
$sending_user = $this->mail_object->settings->gmail_sending_user_id;
- if($sending_user == "0")
+ if ($sending_user == "0") {
$user = $this->company->owner();
- else
+ } else {
$user = User::find($this->decodePrimaryKey($sending_user));
+ }
return $user;
}
@@ -401,11 +389,10 @@ class MailEntity implements ShouldQueue
*/
private function setMailgunMailer()
{
- if(strlen($this->mail_object->settings->mailgun_secret) > 2 && strlen($this->mail_object->settings->mailgun_domain) > 2){
+ if (strlen($this->mail_object->settings->mailgun_secret) > 2 && strlen($this->mail_object->settings->mailgun_domain) > 2) {
$this->client_mailgun_secret = $this->mail_object->settings->mailgun_secret;
$this->client_mailgun_domain = $this->mail_object->settings->mailgun_domain;
- }
- else{
+ } else {
$this->mail_object->settings->email_sending_method = 'default';
return $this->setMailDriver();
}
@@ -415,8 +402,8 @@ class MailEntity implements ShouldQueue
$sending_email = (isset($this->mail_object->settings->custom_sending_email) && stripos($this->mail_object->settings->custom_sending_email, "@")) ? $this->mail_object->settings->custom_sending_email : $user->email;
$sending_user = (isset($this->mail_object->settings->email_from_name) && strlen($this->mail_object->settings->email_from_name) > 2) ? $this->mail_object->settings->email_from_name : $user->name();
- $this->mailable
- ->from($sending_email, $sending_user);
+ $this->mailable
+ ->from($sending_email, $sending_user);
}
/**
@@ -425,10 +412,9 @@ class MailEntity implements ShouldQueue
*/
private function setPostmarkMailer()
{
- if(strlen($this->mail_object->settings->postmark_secret) > 2){
+ if (strlen($this->mail_object->settings->postmark_secret) > 2) {
$this->client_postmark_secret = $this->mail_object->settings->postmark_secret;
- }
- else{
+ } else {
$this->mail_object->settings->email_sending_method = 'default';
return $this->setMailDriver();
}
@@ -438,8 +424,8 @@ class MailEntity implements ShouldQueue
$sending_email = (isset($this->mail_object->settings->custom_sending_email) && stripos($this->mail_object->settings->custom_sending_email, "@")) ? $this->mail_object->settings->custom_sending_email : $user->email;
$sending_user = (isset($this->mail_object->settings->email_from_name) && strlen($this->mail_object->settings->email_from_name) > 2) ? $this->mail_object->settings->email_from_name : $user->name();
- $this->mailable
- ->from($sending_email, $sending_user);
+ $this->mailable
+ ->from($sending_email, $sending_user);
}
/**
@@ -456,25 +442,19 @@ class MailEntity implements ShouldQueue
$token = $this->refreshOfficeToken($user);
- if($token)
- {
+ if ($token) {
$user->oauth_user_token = $token;
$user->save();
-
- }
- else {
-
+ } else {
$this->mail_object->settings->email_sending_method = 'default';
return $this->setMailDriver();
-
}
$this->mailable
->from($user->email, $user->name())
- ->withSymfonyMessage(function ($message) use($token) {
- $message->getHeaders()->addTextHeader('gmailtoken', $token);
+ ->withSymfonyMessage(function ($message) use ($token) {
+ $message->getHeaders()->addTextHeader('gmailtoken', $token);
});
-
}
/**
@@ -483,7 +463,6 @@ class MailEntity implements ShouldQueue
*/
private function setGmailMailer()
{
-
$user = $this->resolveSendingUser();
$this->checkValidSendingUser($user);
@@ -492,17 +471,14 @@ class MailEntity implements ShouldQueue
$google = (new Google())->init();
- try{
-
+ try {
if ($google->getClient()->isAccessTokenExpired()) {
$google->refreshToken($user);
$user = $user->fresh();
}
$google->getClient()->setAccessToken(json_encode($user->oauth_user_token));
-
- }
- catch(\Exception $e) {
+ } catch(\Exception $e) {
// $this->logMailError('Gmail Token Invalid', $this->company->clients()->first());
$this->mail_object->settings->email_sending_method = 'default';
return $this->setMailDriver();
@@ -512,7 +488,7 @@ class MailEntity implements ShouldQueue
* If the user doesn't have a valid token, notify them
*/
- if(!$user->oauth_user_token) {
+ if (!$user->oauth_user_token) {
$this->company->account->gmailCredentialNotification();
$this->mail_object->settings->email_sending_method = 'default';
return $this->setMailDriver();
@@ -526,7 +502,7 @@ class MailEntity implements ShouldQueue
$token = $user->oauth_user_token->access_token;
- if(!$token) {
+ if (!$token) {
$this->company->account->gmailCredentialNotification();
$this->mail_object->settings->email_sending_method = 'default';
return $this->setMailDriver();
@@ -534,15 +510,14 @@ class MailEntity implements ShouldQueue
$this->mailable
->from($user->email, $user->name())
- ->withSymfonyMessage(function ($message) use($token) {
- $message->getHeaders()->addTextHeader('gmailtoken', $token);
+ ->withSymfonyMessage(function ($message) use ($token) {
+ $message->getHeaders()->addTextHeader('gmailtoken', $token);
});
-
}
/**
* Attempts to refresh the Microsoft refreshToken
- *
+ *
* @param App\Models\User
* @return string | boool
*/
@@ -550,10 +525,9 @@ class MailEntity implements ShouldQueue
{
$expiry = $user->oauth_user_token_expiry ?: now()->subDay();
- if($expiry->lt(now()))
- {
- $guzzle = new \GuzzleHttp\Client();
- $url = 'https://login.microsoftonline.com/common/oauth2/v2.0/token';
+ if ($expiry->lt(now())) {
+ $guzzle = new \GuzzleHttp\Client();
+ $url = 'https://login.microsoftonline.com/common/oauth2/v2.0/token';
$token = json_decode($guzzle->post($url, [
'form_params' => [
@@ -565,8 +539,7 @@ class MailEntity implements ShouldQueue
],
])->getBody()->getContents());
- if($token){
-
+ if ($token) {
$user->oauth_user_refresh_token = property_exists($token, 'refresh_token') ? $token->refresh_token : $user->oauth_user_refresh_token;
$user->oauth_user_token = $token->access_token;
$user->oauth_user_token_expiry = now()->addSeconds($token->expires_in);
@@ -579,7 +552,6 @@ class MailEntity implements ShouldQueue
}
return $user->oauth_user_token;
-
}
/**
diff --git a/app/Services/Email/MailMailable.php b/app/Services/Email/MailMailable.php
index 4d0dd5008e66..31fb9e3b238c 100644
--- a/app/Services/Email/MailMailable.php
+++ b/app/Services/Email/MailMailable.php
@@ -11,8 +11,6 @@
namespace App\Services\Email;
-use App\Services\Email\MailObject;
-
use Illuminate\Mail\Attachment;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
@@ -21,13 +19,14 @@ use Illuminate\Mail\Mailables\Headers;
class MailMailable extends Mailable
{
-
/**
* Create a new message instance.
*
* @return void
*/
- public function __construct(public MailObject $mail_object){}
+ public function __construct(public MailObject $mail_object)
+ {
+ }
/**
* Get the message envelope.
@@ -57,7 +56,7 @@ class MailMailable extends Mailable
view: $this->mail_object->html_template,
text: $this->mail_object->text_template,
with: [
- 'text_body' => str_replace("
","\n", strip_tags($this->mail_object->body,"
")), //@todo this is a bit hacky here.
+ 'text_body' => str_replace("
", "\n", strip_tags($this->mail_object->body, "
")), //@todo this is a bit hacky here.
'body' => $this->mail_object->body,
'settings' => $this->mail_object->settings,
'whitelabel' => $this->mail_object->whitelabel,
@@ -76,16 +75,13 @@ class MailMailable extends Mailable
*/
public function attachments()
{
-
$attachments = [];
- foreach($this->mail_object->attachments as $file)
- {
+ foreach ($this->mail_object->attachments as $file) {
$attachments[] = Attachment::fromData(fn () => base64_decode($file['file']), $file['name']);
}
return $attachments;
-
}
/**
@@ -95,13 +91,10 @@ class MailMailable extends Mailable
*/
public function headers()
{
-
return new Headers(
messageId: null,
references: [],
text: $this->mail_object->headers,
);
-
}
-
}
diff --git a/app/Services/Email/MailObject.php b/app/Services/Email/MailObject.php
index d5788ce00c42..d42a71a12ccb 100644
--- a/app/Services/Email/MailObject.php
+++ b/app/Services/Email/MailObject.php
@@ -19,73 +19,71 @@ use Illuminate\Mail\Mailables\Address;
*/
class MailObject
{
+ public ?string $db = null;
- public ?string $db = null;
+ public array $to = [];
- public array $to = [];
+ public ?Address $from = null;
- public ?Address $from = null;
+ public array $reply_to = [];
- public array $reply_to = [];
+ public array $cc = [];
- public array $cc = [];
+ public array $bcc = [];
- public array $bcc = [];
+ public ?string $subject = null;
- public ?string $subject = null;
+ public ?string $body = null;
- public ?string $body = null;
+ public array $attachments = [];
- public array $attachments = [];
+ public array $attachment_links = [];
- public array $attachment_links = [];
+ public string $company_key;
- public string $company_key;
+ public ?object $settings = null;
- public ?object $settings = null;
+ public bool $whitelabel = false;
- public bool $whitelabel = false;
+ public ?string $logo = null;
- public ?string $logo = null;
+ public ?string $signature = null;
- public ?string $signature = null;
+ public ?string $greeting = null;
- public ?string $greeting = null;
+ public ?int $client_id = null;
- public ?int $client_id = null;
+ public ?int $vendor_id = null;
- public ?int $vendor_id = null;
+ public ?int $user_id = null;
- public ?int $user_id = null;
+ public ?int $client_contact_id = null;
- public ?int $client_contact_id = null;
+ public ?int $vendor_contact_id = null;
- public ?int $vendor_contact_id = null;
+ public ?string $email_template = null; //this defines the template in short notation WITH the email_template prefix
- public ?string $email_template = null; //this defines the template in short notation WITH the email_template prefix
+ public ?string $html_template = null;
- public ?string $html_template = null;
+ public ?string $text_template = 'email.template.text';
- public ?string $text_template = 'email.template.text';
+ public array $headers = [];
- public array $headers = [];
+ public ?string $invitation_key = null;
+
+ public ?int $entity_id = null;
- public ?string $invitation_key = null;
-
- public ?int $entity_id = null;
+ public ?string $entity_class = null;
- public ?string $entity_class = null;
+ public ?string $entity_string = null;
- public ?string $entity_string = null;
+ public array $variables = [];
+
+ public ?string $template = null;
- public array $variables = [];
-
- public ?string $template = null;
+ public ?string $template_data = null;
- public ?string $template_data = null;
+ public bool $override = false;
- public bool $override = false;
-
- public ?Company $company = null;
-
-}
\ No newline at end of file
+ public ?Company $company = null;
+}
diff --git a/app/Services/Invoice/AddGatewayFee.php b/app/Services/Invoice/AddGatewayFee.php
index 437791edbe86..341da8789444 100644
--- a/app/Services/Invoice/AddGatewayFee.php
+++ b/app/Services/Invoice/AddGatewayFee.php
@@ -12,10 +12,8 @@
namespace App\Services\Invoice;
use App\DataMapper\InvoiceItem;
-use App\Models\Client;
use App\Models\CompanyGateway;
use App\Models\Invoice;
-use App\Models\Payment;
use App\Services\AbstractService;
use App\Utils\Ninja;
use Illuminate\Support\Facades\App;
diff --git a/app/Services/Invoice/ApplyNumber.php b/app/Services/Invoice/ApplyNumber.php
index 7bb10ec8e887..ee4368f557b3 100644
--- a/app/Services/Invoice/ApplyNumber.php
+++ b/app/Services/Invoice/ApplyNumber.php
@@ -36,7 +36,6 @@ class ApplyNumber extends AbstractService
public function run()
{
-
if ($this->invoice->number != '') {
return $this->invoice;
}
@@ -60,32 +59,24 @@ class ApplyNumber extends AbstractService
private function trySaving()
{
-
$x=1;
- do{
-
- try{
-
+ do {
+ try {
$this->invoice->number = $this->getNextInvoiceNumber($this->client, $this->invoice, $this->invoice->recurring_id);
$this->invoice->saveQuietly();
$this->completed = false;
-
- }
- catch(QueryException $e){
-
+ } catch(QueryException $e) {
$x++;
- if($x>50)
+ if ($x>50) {
$this->completed = false;
+ }
}
-
- }
- while($this->completed);
+ } while ($this->completed);
return $this;
}
-
}
diff --git a/app/Services/Invoice/ApplyPayment.php b/app/Services/Invoice/ApplyPayment.php
index 84e87b0a2586..a18746f0fdfd 100644
--- a/app/Services/Invoice/ApplyPayment.php
+++ b/app/Services/Invoice/ApplyPayment.php
@@ -41,7 +41,6 @@ class ApplyPayment extends AbstractService
if ($this->invoice->hasPartial()) {
if ($this->invoice->partial == $this->payment_amount) {
-
//is partial and amount is exactly the partial amount
$amount_paid = $this->payment_amount * -1;
diff --git a/app/Services/Invoice/ApplyPaymentAmount.php b/app/Services/Invoice/ApplyPaymentAmount.php
index ef7524e807d8..690d54f86146 100644
--- a/app/Services/Invoice/ApplyPaymentAmount.php
+++ b/app/Services/Invoice/ApplyPaymentAmount.php
@@ -26,7 +26,9 @@ class ApplyPaymentAmount extends AbstractService
{
use GeneratesCounter;
- public function __construct(private Invoice $invoice, private float $amount, private ?string $reference){}
+ public function __construct(private Invoice $invoice, private float $amount, private ?string $reference)
+ {
+ }
public function run()
{
diff --git a/app/Services/Invoice/AutoBillInvoice.php b/app/Services/Invoice/AutoBillInvoice.php
index 5a0624b1d73c..e0070d981dee 100644
--- a/app/Services/Invoice/AutoBillInvoice.php
+++ b/app/Services/Invoice/AutoBillInvoice.php
@@ -23,7 +23,6 @@ use App\Models\PaymentType;
use App\Services\AbstractService;
use App\Utils\Ninja;
use Illuminate\Support\Str;
-use PDO;
class AutoBillInvoice extends AbstractService
{
@@ -73,8 +72,9 @@ class AutoBillInvoice extends AbstractService
}
//If this returns true, it means a partial invoice amount was paid as a credit and there is no further balance payable
- if($this->is_partial_amount && $this->invoice->partial == 0)
+ if ($this->is_partial_amount && $this->invoice->partial == 0) {
return;
+ }
$amount = 0;
@@ -251,7 +251,6 @@ class AutoBillInvoice extends AbstractService
foreach ($available_credits as $key => $credit) {
if ($this->is_partial_amount) {
-
//more credit than needed
if ($credit->balance > $this->invoice->partial) {
$this->used_credit[$key]['credit_id'] = $credit->id;
@@ -266,10 +265,8 @@ class AutoBillInvoice extends AbstractService
$this->invoice->partial -= $credit->balance;
$this->invoice->balance -= $credit->balance;
$this->invoice->paid_to_date += $credit->balance;
-
}
} else {
-
//more credit than needed
if ($credit->balance > $this->invoice->balance) {
$this->used_credit[$key]['credit_id'] = $credit->id;
@@ -283,7 +280,6 @@ class AutoBillInvoice extends AbstractService
$this->used_credit[$key]['amount'] = $credit->balance;
$this->invoice->balance -= $credit->balance;
$this->invoice->paid_to_date += $credit->balance;
-
}
}
}
@@ -322,7 +318,6 @@ class AutoBillInvoice extends AbstractService
*/
public function getGateway($amount)
{
-
//get all client gateway tokens and set the is_default one to the first record
$gateway_tokens = $this->client
->gateway_tokens()
@@ -363,8 +358,7 @@ class AutoBillInvoice extends AbstractService
*/
private function addFeeToInvoice(float $fee)
{
-
- //todo if we increase the invoice balance here, we will also need to adjust UP the client balance and ledger?
+ //todo if we increase the invoice balance here, we will also need to adjust UP the client balance and ledger?
$starting_amount = $this->invoice->amount;
$item = new InvoiceItem;
diff --git a/app/Services/Invoice/GetInvoicePdf.php b/app/Services/Invoice/GetInvoicePdf.php
index b4ad06f81f4a..518d59c5f608 100644
--- a/app/Services/Invoice/GetInvoicePdf.php
+++ b/app/Services/Invoice/GetInvoicePdf.php
@@ -15,7 +15,6 @@ use App\Jobs\Entity\CreateEntityPdf;
use App\Models\ClientContact;
use App\Models\Invoice;
use App\Services\AbstractService;
-use App\Utils\TempFile;
use Illuminate\Support\Facades\Storage;
class GetInvoicePdf extends AbstractService
diff --git a/app/Services/Invoice/HandleRestore.php b/app/Services/Invoice/HandleRestore.php
index a61f42dccfb2..b2878a38b56b 100644
--- a/app/Services/Invoice/HandleRestore.php
+++ b/app/Services/Invoice/HandleRestore.php
@@ -46,10 +46,9 @@ class HandleRestore extends AbstractService
//cannot restore an invoice with a deleted payment
foreach ($this->invoice->payments as $payment) {
-
- if(($this->invoice->paid_to_date == 0) && $payment->is_deleted)
+ if (($this->invoice->paid_to_date == 0) && $payment->is_deleted) {
return $this->invoice;
-
+ }
}
//adjust ledger balance
@@ -57,7 +56,7 @@ class HandleRestore extends AbstractService
$this->invoice->client
->service()
- ->updateBalanceAndPaidToDate($this->invoice->balance,$this->invoice->paid_to_date)
+ ->updateBalanceAndPaidToDate($this->invoice->balance, $this->invoice->paid_to_date)
->save();
$this->windBackInvoiceNumber();
@@ -81,14 +80,12 @@ class HandleRestore extends AbstractService
private function restorePaymentables()
{
$this->invoice->payments->each(function ($payment) {
-
Paymentable::query()
->withTrashed()
->where('payment_id', $payment->id)
->where('paymentable_type', '=', 'invoices')
->where('paymentable_id', $this->invoice->id)
->update(['deleted_at' => null]);
-
});
return $this;
@@ -112,7 +109,7 @@ class HandleRestore extends AbstractService
$this->total_payments = $this->invoice->payments->sum('amount') - $this->invoice->payments->sum('refunded');
return $this;
- }
+ }
private function adjustPayments()
{
@@ -120,27 +117,27 @@ class HandleRestore extends AbstractService
if ($this->adjustment_amount == $this->total_payments) {
$this->invoice->payments()->update(['payments.deleted_at' => null, 'payments.is_deleted' => false]);
- }
+ }
- //adjust payments down by the amount applied to the invoice payment.
+ //adjust payments down by the amount applied to the invoice payment.
- $this->invoice->payments->fresh()->each(function ($payment) {
- $payment_adjustment = $payment->paymentables
- ->where('paymentable_type', '=', 'invoices')
- ->where('paymentable_id', $this->invoice->id)
- ->sum(DB::raw('amount'));
+ $this->invoice->payments->fresh()->each(function ($payment) {
+ $payment_adjustment = $payment->paymentables
+ ->where('paymentable_type', '=', 'invoices')
+ ->where('paymentable_id', $this->invoice->id)
+ ->sum(DB::raw('amount'));
- $payment_adjustment -= $payment->paymentables
- ->where('paymentable_type', '=', 'invoices')
- ->where('paymentable_id', $this->invoice->id)
- ->sum(DB::raw('refunded'));
+ $payment_adjustment -= $payment->paymentables
+ ->where('paymentable_type', '=', 'invoices')
+ ->where('paymentable_id', $this->invoice->id)
+ ->sum(DB::raw('refunded'));
- $payment->amount += $payment_adjustment;
- $payment->applied += $payment_adjustment;
- $payment->is_deleted = false;
- $payment->restore();
- $payment->saveQuietly();
- });
+ $payment->amount += $payment_adjustment;
+ $payment->applied += $payment_adjustment;
+ $payment->is_deleted = false;
+ $payment->restore();
+ $payment->saveQuietly();
+ });
return $this;
}
diff --git a/app/Services/Invoice/HandleReversal.php b/app/Services/Invoice/HandleReversal.php
index dafce85bc5d2..8000ecf4caee 100644
--- a/app/Services/Invoice/HandleReversal.php
+++ b/app/Services/Invoice/HandleReversal.php
@@ -59,7 +59,6 @@ class HandleReversal extends AbstractService
->get();
$paymentables->each(function ($paymentable) use ($total_paid) {
-
//new concept - when reversing, we unwind the payments
$payment = Payment::withTrashed()->find($paymentable->payment_id);
diff --git a/app/Services/Invoice/InvoiceService.php b/app/Services/Invoice/InvoiceService.php
index fa1149d281eb..34919ad37ad8 100644
--- a/app/Services/Invoice/InvoiceService.php
+++ b/app/Services/Invoice/InvoiceService.php
@@ -14,18 +14,12 @@ namespace App\Services\Invoice;
use App\Events\Invoice\InvoiceWasArchived;
use App\Jobs\Entity\CreateEntityPdf;
use App\Jobs\Inventory\AdjustProductInventory;
-use App\Jobs\Invoice\InvoiceWorkflowSettings;
-use App\Jobs\Util\UnlinkFile;
use App\Libraries\Currency\Conversion\CurrencyApi;
use App\Models\CompanyGateway;
use App\Models\Expense;
use App\Models\Invoice;
use App\Models\Payment;
use App\Models\Task;
-use App\Repositories\BaseRepository;
-use App\Services\Client\ClientService;
-use App\Services\Invoice\ApplyPaymentAmount;
-use App\Services\Invoice\UpdateReminder;
use App\Utils\Ninja;
use App\Utils\Traits\MakesHash;
use Illuminate\Support\Carbon;
@@ -35,7 +29,9 @@ class InvoiceService
{
use MakesHash;
- public function __construct(public Invoice $invoice){}
+ public function __construct(public Invoice $invoice)
+ {
+ }
/**
* Marks as invoice as paid
@@ -266,10 +262,11 @@ class InvoiceService
}
//12-10-2022
- if($this->invoice->partial > 0 && !$this->invoice->partial_due_date)
+ if ($this->invoice->partial > 0 && !$this->invoice->partial_due_date) {
$this->invoice->partial_due_date = Carbon::parse($this->invoice->date)->addDays($this->invoice->client->getSetting('payment_terms'));
- else
+ } else {
$this->invoice->due_date = Carbon::parse($this->invoice->date)->addDays($this->invoice->client->getSetting('payment_terms'));
+ }
return $this;
}
@@ -294,8 +291,7 @@ class InvoiceService
$this->setStatus(Invoice::STATUS_PAID);
} elseif ($this->invoice->balance > 0 && $this->invoice->balance < $this->invoice->amount) {
$this->setStatus(Invoice::STATUS_PARTIAL);
- }
- elseif ($this->invoice->balance < 0 || $this->invoice->balance > 0) {
+ } elseif ($this->invoice->balance < 0 || $this->invoice->balance > 0) {
$this->invoice->status_id = Invoice::STATUS_SENT;
}
@@ -312,8 +308,7 @@ class InvoiceService
$this->invoice->status_id = Invoice::STATUS_PAID;
} elseif ($this->invoice->balance > 0 && $this->invoice->balance < $this->invoice->amount) {
$this->invoice->status_id = Invoice::STATUS_PARTIAL;
- }
- elseif ($this->invoice->balance < 0 || $this->invoice->balance > 0) {
+ } elseif ($this->invoice->balance < 0 || $this->invoice->balance > 0) {
$this->invoice->status_id = Invoice::STATUS_SENT;
}
diff --git a/app/Services/Invoice/MarkInvoiceDeleted.php b/app/Services/Invoice/MarkInvoiceDeleted.php
index 145af4ea543b..d3ed85a2808e 100644
--- a/app/Services/Invoice/MarkInvoiceDeleted.php
+++ b/app/Services/Invoice/MarkInvoiceDeleted.php
@@ -12,9 +12,7 @@
namespace App\Services\Invoice;
use App\Jobs\Inventory\AdjustProductInventory;
-use App\Jobs\Ninja\TransactionLog;
use App\Models\Invoice;
-use App\Models\TransactionEvent;
use App\Services\AbstractService;
use App\Utils\Traits\GeneratesCounter;
use Illuminate\Support\Facades\DB;
@@ -66,7 +64,6 @@ class MarkInvoiceDeleted extends AbstractService
private function adjustPaidToDateAndBalance()
{
-
// 06-09-2022
$this->invoice
->client
@@ -82,27 +79,28 @@ class MarkInvoiceDeleted extends AbstractService
{
//if total payments = adjustment amount - that means we need to delete the payments as well.
- if ($this->adjustment_amount == $this->total_payments)
+ if ($this->adjustment_amount == $this->total_payments) {
$this->invoice->payments()->update(['payments.deleted_at' => now(), 'payments.is_deleted' => true]);
+ }
- //adjust payments down by the amount applied to the invoice payment.
+ //adjust payments down by the amount applied to the invoice payment.
- $this->invoice->payments->each(function ($payment) {
- $payment_adjustment = $payment->paymentables
- ->where('paymentable_type', '=', 'invoices')
- ->where('paymentable_id', $this->invoice->id)
- ->sum(DB::raw('amount'));
+ $this->invoice->payments->each(function ($payment) {
+ $payment_adjustment = $payment->paymentables
+ ->where('paymentable_type', '=', 'invoices')
+ ->where('paymentable_id', $this->invoice->id)
+ ->sum(DB::raw('amount'));
- $payment_adjustment -= $payment->paymentables
- ->where('paymentable_type', '=', 'invoices')
- ->where('paymentable_id', $this->invoice->id)
- ->sum(DB::raw('refunded'));
+ $payment_adjustment -= $payment->paymentables
+ ->where('paymentable_type', '=', 'invoices')
+ ->where('paymentable_id', $this->invoice->id)
+ ->sum(DB::raw('refunded'));
- $payment->amount -= $payment_adjustment;
- $payment->applied -= $payment_adjustment;
- $payment->save();
- });
+ $payment->amount -= $payment_adjustment;
+ $payment->applied -= $payment_adjustment;
+ $payment->save();
+ });
return $this;
diff --git a/app/Services/Invoice/MarkPaid.php b/app/Services/Invoice/MarkPaid.php
index b4f69a6f3e30..a056da4b6038 100644
--- a/app/Services/Invoice/MarkPaid.php
+++ b/app/Services/Invoice/MarkPaid.php
@@ -28,11 +28,12 @@ class MarkPaid extends AbstractService
private $payable_balance;
- public function __construct(private Invoice $invoice, private ?string $reference){}
+ public function __construct(private Invoice $invoice, private ?string $reference)
+ {
+ }
public function run()
{
-
/*Don't double pay*/
if ($this->invoice->status_id == Invoice::STATUS_PAID) {
return $this->invoice;
@@ -43,11 +44,9 @@ class MarkPaid extends AbstractService
}
\DB::connection(config('database.default'))->transaction(function () {
-
$this->invoice = Invoice::withTrashed()->where('id', $this->invoice->id)->lockForUpdate()->first();
- if($this->invoice)
- {
+ if ($this->invoice) {
$this->payable_balance = $this->invoice->balance;
$this->invoice
@@ -58,7 +57,6 @@ class MarkPaid extends AbstractService
->setStatus(Invoice::STATUS_PAID)
->save();
}
-
}, 1);
/* Create Payment */
@@ -91,8 +89,9 @@ class MarkPaid extends AbstractService
'amount' => $this->payable_balance,
]);
- if($payment->company->getSetting('send_email_on_mark_paid'))
+ if ($payment->company->getSetting('send_email_on_mark_paid')) {
$payment->service()->sendEmail();
+ }
$this->setExchangeRate($payment);
diff --git a/app/Services/Invoice/MarkSent.php b/app/Services/Invoice/MarkSent.php
index f9e3519f3b00..557fb37ec55e 100644
--- a/app/Services/Invoice/MarkSent.php
+++ b/app/Services/Invoice/MarkSent.php
@@ -12,7 +12,6 @@
namespace App\Services\Invoice;
use App\Events\Invoice\InvoiceWasUpdated;
-use App\Jobs\Util\WebhookHandler;
use App\Models\Client;
use App\Models\Invoice;
use App\Models\Webhook;
@@ -34,7 +33,6 @@ class MarkSent extends AbstractService
public function run($fire_webhook = false)
{
-
/* Return immediately if status is not draft or invoice has been deleted */
if ($this->invoice && ($this->invoice->fresh()->status_id != Invoice::STATUS_DRAFT || $this->invoice->is_deleted)) {
return $this->invoice;
@@ -70,8 +68,9 @@ class MarkSent extends AbstractService
event(new InvoiceWasUpdated($this->invoice, $this->invoice->company, Ninja::eventVars(auth()->user() ? auth()->user()->id : null)));
- if($fire_webhook)
+ if ($fire_webhook) {
event('eloquent.updated: App\Models\Invoice', $this->invoice);
+ }
$this->invoice->sendEvent(Webhook::EVENT_SENT_INVOICE, "client");
diff --git a/app/Services/Invoice/TriggeredActions.php b/app/Services/Invoice/TriggeredActions.php
index 82f5b580af95..d607de6d140b 100644
--- a/app/Services/Invoice/TriggeredActions.php
+++ b/app/Services/Invoice/TriggeredActions.php
@@ -67,7 +67,7 @@ class TriggeredActions extends AbstractService
$this->updated = false;
}
- if($this->request->has('save_default_footer') && $this->request->input('save_default_footer') == 'true') {
+ if ($this->request->has('save_default_footer') && $this->request->input('save_default_footer') == 'true') {
$company = $this->invoice->company;
$settings = $company->settings;
$settings->invoice_footer = $this->invoice->footer;
@@ -75,7 +75,7 @@ class TriggeredActions extends AbstractService
$company->save();
}
- if($this->request->has('save_default_terms') && $this->request->input('save_default_terms') == 'true') {
+ if ($this->request->has('save_default_terms') && $this->request->input('save_default_terms') == 'true') {
$company = $this->invoice->company;
$settings = $company->settings;
$settings->invoice_terms = $this->invoice->terms;
@@ -83,8 +83,9 @@ class TriggeredActions extends AbstractService
$company->save();
}
- if($this->updated)
+ if ($this->updated) {
event('eloquent.updated: App\Models\Invoice', $this->invoice);
+ }
return $this->invoice;
diff --git a/app/Services/Invoice/UpdateReminder.php b/app/Services/Invoice/UpdateReminder.php
index c86021242237..6109eb54c400 100644
--- a/app/Services/Invoice/UpdateReminder.php
+++ b/app/Services/Invoice/UpdateReminder.php
@@ -182,7 +182,7 @@ class UpdateReminder extends AbstractService
switch ($endless_reminder_frequency_id) {
case RecurringInvoice::FREQUENCY_DAILY:
return Carbon::parse($date)->addDay()->startOfDay();
- case RecurringInvoice::FREQUENCY_WEEKLY:
+ case RecurringInvoice::FREQUENCY_WEEKLY:
return Carbon::parse($date)->addWeek()->startOfDay();
case RecurringInvoice::FREQUENCY_TWO_WEEKS:
return Carbon::parse($date)->addWeeks(2)->startOfDay();
diff --git a/app/Services/Ledger/LedgerService.php b/app/Services/Ledger/LedgerService.php
index 219aa04bd96d..9d9935fc5e02 100644
--- a/app/Services/Ledger/LedgerService.php
+++ b/app/Services/Ledger/LedgerService.php
@@ -14,7 +14,6 @@ namespace App\Services\Ledger;
use App\Factory\CompanyLedgerFactory;
use App\Jobs\Ledger\ClientLedgerBalanceUpdate;
use App\Models\Activity;
-use App\Models\CompanyLedger;
class LedgerService
{
@@ -36,7 +35,7 @@ class LedgerService
$this->entity->company_ledger()->save($company_ledger);
- ClientLedgerBalanceUpdate::dispatch($this->entity->company, $this->entity->client)->delay(now()->addSeconds(rand(30,300)));
+ ClientLedgerBalanceUpdate::dispatch($this->entity->company, $this->entity->client)->delay(now()->addSeconds(rand(30, 300)));
return $this;
}
@@ -52,7 +51,7 @@ class LedgerService
$this->entity->company_ledger()->save($company_ledger);
- ClientLedgerBalanceUpdate::dispatch($this->entity->company, $this->entity->client)->delay(now()->addSeconds(rand(30,300)));
+ ClientLedgerBalanceUpdate::dispatch($this->entity->company, $this->entity->client)->delay(now()->addSeconds(rand(30, 300)));
return $this;
}
@@ -68,7 +67,7 @@ class LedgerService
$this->entity->company_ledger()->save($company_ledger);
- ClientLedgerBalanceUpdate::dispatch($this->entity->company, $this->entity->client)->delay(now()->addSeconds(rand(30,300)));
+ ClientLedgerBalanceUpdate::dispatch($this->entity->company, $this->entity->client)->delay(now()->addSeconds(rand(30, 300)));
return $this;
}
diff --git a/app/Services/Payment/DeletePayment.php b/app/Services/Payment/DeletePayment.php
index bd41bcd8af0e..b327287fcb60 100644
--- a/app/Services/Payment/DeletePayment.php
+++ b/app/Services/Payment/DeletePayment.php
@@ -11,12 +11,9 @@
namespace App\Services\Payment;
-use App\Jobs\Ninja\TransactionLog;
use App\Models\Credit;
use App\Models\Invoice;
use App\Models\Payment;
-use App\Models\TransactionEvent;
-use App\Repositories\ActivityRepository;
use Illuminate\Contracts\Container\BindingResolutionException;
class DeletePayment
@@ -24,37 +21,33 @@ class DeletePayment
private float $_paid_to_date_deleted = 0;
/**
- * @param mixed $payment
- * @return void
+ * @param mixed $payment
+ * @return void
*/
- public function __construct(public Payment $payment, private bool $update_client_paid_to_date) {}
+ public function __construct(public Payment $payment, private bool $update_client_paid_to_date)
+ {
+ }
/**
- * @return mixed
- * @throws BindingResolutionException
+ * @return mixed
+ * @throws BindingResolutionException
*/
public function run()
{
-
\DB::connection(config('database.default'))->transaction(function () {
-
$this->payment = Payment::withTrashed()->where('id', $this->payment->id)->lockForUpdate()->first();
if ($this->payment && !$this->payment->is_deleted) {
-
$this->setStatus(Payment::STATUS_CANCELLED) //sets status of payment
->updateCreditables() //return the credits first
->adjustInvoices()
->deletePaymentables()
->cleanupPayment()
->save();
-
}
-
}, 2);
return $this->payment;
-
}
/** @return $this */
@@ -111,19 +104,16 @@ class DeletePayment
$paymentable_invoice->service()->setStatus(Invoice::STATUS_PARTIAL)->save();
}
} else {
-
$paymentable_invoice->restore();
$paymentable_invoice->service()
->updatePaidToDate($net_deletable * -1)
->save();
}
-
});
}
//sometimes the payment is NOT created properly, this catches the payment and prevents the paid to date reducing inappropriately.
- if($this->update_client_paid_to_date)
- {
+ if ($this->update_client_paid_to_date) {
$this->payment
->client
->service()
@@ -138,7 +128,7 @@ class DeletePayment
private function updateCreditables()
{
if ($this->payment->credits()->exists()) {
- $this->payment->credits()->where('is_deleted',0)->each(function ($paymentable_credit) {
+ $this->payment->credits()->where('is_deleted', 0)->each(function ($paymentable_credit) {
$multiplier = 1;
if ($paymentable_credit->pivot->amount < 0) {
@@ -165,8 +155,8 @@ class DeletePayment
}
/**
- * @param mixed $status
- * @return $this
+ * @param mixed $status
+ * @return $this
*/
private function setStatus($status)
{
diff --git a/app/Services/Payment/PaymentService.php b/app/Services/Payment/PaymentService.php
index f521ff52a973..9dc72e088258 100644
--- a/app/Services/Payment/PaymentService.php
+++ b/app/Services/Payment/PaymentService.php
@@ -142,31 +142,30 @@ class PaymentService
public function applyCreditsToInvoice($invoice)
{
+ $amount = $invoice->amount;
- $amount = $invoice->amount;
+ $credits = $invoice->client
+ ->service()
+ ->getCredits();
- $credits = $invoice->client
- ->service()
- ->getCredits();
+ foreach ($credits as $credit) {
+ //starting invoice balance
+ $invoice_balance = $invoice->balance;
- foreach ($credits as $credit) {
- //starting invoice balance
- $invoice_balance = $invoice->balance;
+ //credit payment applied
+ $credit->service()->applyPayment($invoice, $amount, $this->payment);
- //credit payment applied
- $credit->service()->applyPayment($invoice, $amount, $this->payment);
+ //amount paid from invoice calculated
+ $remaining_balance = ($invoice_balance - $invoice->fresh()->balance);
- //amount paid from invoice calculated
- $remaining_balance = ($invoice_balance - $invoice->fresh()->balance);
+ //reduce the amount to be paid on the invoice from the NEXT credit
+ $amount -= $remaining_balance;
- //reduce the amount to be paid on the invoice from the NEXT credit
- $amount -= $remaining_balance;
-
- //break if the invoice is no longer PAYABLE OR there is no more amount to be applied
- if (! $invoice->isPayable() || (int) $amount == 0) {
- break;
- }
+ //break if the invoice is no longer PAYABLE OR there is no more amount to be applied
+ if (! $invoice->isPayable() || (int) $amount == 0) {
+ break;
}
+ }
return $this;
diff --git a/app/Services/Payment/RefundPayment.php b/app/Services/Payment/RefundPayment.php
index c288736eecc3..99747a392a2b 100644
--- a/app/Services/Payment/RefundPayment.php
+++ b/app/Services/Payment/RefundPayment.php
@@ -12,17 +12,11 @@
namespace App\Services\Payment;
use App\Exceptions\PaymentRefundFailed;
-use App\Factory\CreditFactory;
-use App\Factory\InvoiceItemFactory;
-use App\Jobs\Ninja\TransactionLog;
use App\Jobs\Payment\EmailRefundPayment;
-use App\Jobs\Util\SystemLogger;
use App\Models\Activity;
use App\Models\Credit;
use App\Models\Invoice;
use App\Models\Payment;
-use App\Models\SystemLog;
-use App\Models\TransactionEvent;
use App\Repositories\ActivityRepository;
use App\Utils\Ninja;
use stdClass;
@@ -200,7 +194,6 @@ class RefundPayment
if ($this->payment->credits()->exists()) {
//Adjust credits first!!!
foreach ($this->payment->credits as $paymentable_credit) {
-
$available_credit = $paymentable_credit->pivot->amount - $paymentable_credit->pivot->refunded;
if ($available_credit > $this->total_refund) {
@@ -244,7 +237,6 @@ class RefundPayment
*/
private function adjustInvoices()
{
-
if (isset($this->refund_data['invoices']) && count($this->refund_data['invoices']) > 0) {
foreach ($this->refund_data['invoices'] as $refunded_invoice) {
$invoice = Invoice::withTrashed()->find($refunded_invoice['invoice_id']);
@@ -291,7 +283,6 @@ class RefundPayment
}
$client->service()->updatePaidToDate(-1 * $refunded_invoice['amount'])->save();
-
} else {
//if we are refunding and no payments have been tagged, then we need to decrement the client->paid_to_date by the total refund amount.
@@ -302,7 +293,6 @@ class RefundPayment
}
$client->service()->updatePaidToDate(-1 * $this->total_refund)->save();
-
}
return $this;
@@ -319,5 +309,4 @@ class RefundPayment
return $this->payment;
}
-
}
diff --git a/app/Services/Payment/SendEmail.php b/app/Services/Payment/SendEmail.php
index 2846b4ef5736..770b54de7248 100644
--- a/app/Services/Payment/SendEmail.php
+++ b/app/Services/Payment/SendEmail.php
@@ -32,7 +32,7 @@ class SendEmail
*/
public function run()
{
- $this->payment->load('company', 'client.contacts','invoices');
+ $this->payment->load('company', 'client.contacts', 'invoices');
$contact = $this->payment->client->contacts()->first();
@@ -40,19 +40,12 @@ class SendEmail
// EmailPayment::dispatch($this->payment, $this->payment->company, $contact)->delay(now()->addSeconds(2));
- $this->payment->invoices->sortByDesc('id')->first(function ($invoice){
-
+ $this->payment->invoices->sortByDesc('id')->first(function ($invoice) {
$invoice->invitations->each(function ($invitation) {
-
- if(!$invitation->contact->trashed() && $invitation->contact->email) {
-
+ if (!$invitation->contact->trashed() && $invitation->contact->email) {
EmailPayment::dispatch($this->payment, $this->payment->company, $invitation->contact)->delay(now()->addSeconds(2));
-
}
-
});
-
});
-
}
}
diff --git a/app/Services/Payment/UpdateInvoicePayment.php b/app/Services/Payment/UpdateInvoicePayment.php
index 5035b4cb2a71..9ffdbe5b02d2 100644
--- a/app/Services/Payment/UpdateInvoicePayment.php
+++ b/app/Services/Payment/UpdateInvoicePayment.php
@@ -12,13 +12,9 @@
namespace App\Services\Payment;
use App\Events\Invoice\InvoiceWasUpdated;
-use App\Jobs\Invoice\InvoiceWorkflowSettings;
-use App\Jobs\Ninja\TransactionLog;
-use App\Models\Client;
use App\Models\Invoice;
use App\Models\Payment;
use App\Models\PaymentHash;
-use App\Models\TransactionEvent;
use App\Utils\Ninja;
use App\Utils\Traits\MakesHash;
@@ -44,17 +40,18 @@ class UpdateInvoicePayment
$client = $this->payment->client;
- if($client->trashed())
+ if ($client->trashed()) {
$client->restore();
+ }
collect($paid_invoices)->each(function ($paid_invoice) use ($invoices, $client) {
-
$invoice = $invoices->first(function ($inv) use ($paid_invoice) {
return $paid_invoice->invoice_id == $inv->hashed_id;
});
- if($invoice->trashed())
+ if ($invoice->trashed()) {
$invoice->restore();
+ }
if ($invoice->id == $this->payment_hash->fee_invoice_id) {
$paid_amount = $paid_invoice->amount + $this->payment_hash->fee_total;
@@ -65,8 +62,9 @@ class UpdateInvoicePayment
$client->service()->updatePaidToDate($paid_amount); //always use the payment->amount
/* Need to determine here is we have an OVER payment - if YES only apply the max invoice amount */
- if($paid_amount > $invoice->partial && $paid_amount > $invoice->balance)
+ if ($paid_amount > $invoice->partial && $paid_amount > $invoice->balance) {
$paid_amount = $invoice->balance;
+ }
$client->service()->updateBalance($paid_amount*-1); //only ever use the amount applied to the invoice
@@ -76,18 +74,17 @@ class UpdateInvoicePayment
$invoice->paid_to_date += $paid_amount;
$invoice->save();
- $invoice = $invoice->service()
+ $invoice = $invoice->service()
->clearPartial()
->updateStatus()
->touchPdf()
->workFlow()
->save();
- if($invoice->is_proforma)
- {
-
- if(strlen($invoice->number) > 1 && str_starts_with($invoice->number,"####"))
- $invoice->number = '';
+ if ($invoice->is_proforma) {
+ if (strlen($invoice->number) > 1 && str_starts_with($invoice->number, "####")) {
+ $invoice->number = '';
+ }
$invoice->is_proforma = false;
@@ -112,7 +109,6 @@ class UpdateInvoicePayment
$pivot_invoice->pivot->save();
$this->payment->applied += $paid_amount;
-
});
/* Remove the event updater from within the loop to prevent race conditions */
@@ -120,9 +116,7 @@ class UpdateInvoicePayment
$this->payment->saveQuietly();
$invoices->each(function ($invoice) {
-
event(new InvoiceWasUpdated($invoice, $invoice->company, Ninja::eventVars(auth()->user() ? auth()->user()->id : null)));
-
});
return $this->payment->fresh();
diff --git a/app/Services/PdfMaker/Design.php b/app/Services/PdfMaker/Design.php
index 1b275c2dff90..095146bba08f 100644
--- a/app/Services/PdfMaker/Design.php
+++ b/app/Services/PdfMaker/Design.php
@@ -13,9 +13,7 @@
namespace App\Services\PdfMaker;
use App\Models\Credit;
-use App\Models\GatewayType;
use App\Models\Invoice;
-use App\Models\Payment;
use App\Models\Quote;
use App\Services\PdfMaker\Designs\Utilities\BaseDesign;
use App\Services\PdfMaker\Designs\Utilities\DesignHelpers;
@@ -85,7 +83,6 @@ class Design extends BaseDesign
Str::endsWith('.html', $design) ? $this->design = $design : $this->design = "{$design}.html";
$this->options = $options;
-
}
public function html(): ?string
@@ -184,15 +181,17 @@ class Design extends BaseDesign
public function swissQrCodeElement() :array
{
- if($this->type == self::DELIVERY_NOTE)
+ if ($this->type == self::DELIVERY_NOTE) {
return [];
+ }
$elements = [];
- if(strlen($this->company->getSetting('qr_iban')) > 5 && strlen($this->company->getSetting('besr_id')) > 1)
+ if (strlen($this->company->getSetting('qr_iban')) > 5 && strlen($this->company->getSetting('besr_id')) > 1) {
$elements[] = ['element' => 'qr_code', 'content' => '$swiss_qr', 'show_empty' => false, 'properties' => ['data-ref' => 'swiss-qr-code']];
+ }
- return $elements;
+ return $elements;
}
public function companyDetails(): array
@@ -225,8 +224,9 @@ class Design extends BaseDesign
{
$elements = [];
- if(!$this->vendor)
+ if (!$this->vendor) {
return $elements;
+ }
$variables = $this->context['pdf_variables']['vendor_details'];
@@ -241,8 +241,9 @@ class Design extends BaseDesign
{
$elements = [];
- if(!$this->client)
+ if (!$this->client) {
return $elements;
+ }
if ($this->type == self::DELIVERY_NOTE) {
$elements = [
@@ -276,10 +277,7 @@ class Design extends BaseDesign
public function entityDetails(): array
{
-
-
if ($this->type === 'statement') {
-
// $s_date = $this->translateDate(now(), $this->client->date_format(), $this->client->locale());
$s_date = $this->translateDate($this->options['start_date'], $this->client->date_format(), $this->client->locale()) . " - " . $this->translateDate($this->options['end_date'], $this->client->date_format(), $this->client->locale());
@@ -314,10 +312,8 @@ class Design extends BaseDesign
$variables = $this->context['pdf_variables']['credit_details'];
}
- if($this->vendor){
-
+ if ($this->vendor) {
$variables = $this->context['pdf_variables']['purchase_order_details'];
-
}
$elements = [];
@@ -503,9 +499,9 @@ class Design extends BaseDesign
//24-03-2022 show payments per invoice
foreach ($this->invoices as $invoice) {
foreach ($invoice->payments as $payment) {
-
- if($payment->is_deleted)
+ if ($payment->is_deleted) {
continue;
+ }
$element = ['element' => 'tr', 'elements' => []];
@@ -706,7 +702,7 @@ class Design extends BaseDesign
$element['elements'][] = ['element' => 'td', 'content' => $row[$cell], 'properties' => ['data-ref' => 'product_table-product.tax2-td']];
} elseif ($cell == '$product.tax_rate3') {
$element['elements'][] = ['element' => 'td', 'content' => $row[$cell], 'properties' => ['data-ref' => 'product_table-product.tax3-td']];
- } else if ($cell == '$product.unit_cost' || $cell == '$task.rate') {
+ } elseif ($cell == '$product.unit_cost' || $cell == '$task.rate') {
$element['elements'][] = ['element' => 'td', 'content' => $row[$cell], 'properties' => ['style' => 'white-space: nowrap;', 'data-ref' => "{$_type}_table-" . substr($cell, 1) . '-td']];
} else {
$element['elements'][] = ['element' => 'td', 'content' => $row[$cell], 'properties' => ['data-ref' => "{$_type}_table-" . substr($cell, 1) . '-td']];
@@ -777,7 +773,6 @@ class Design extends BaseDesign
if (in_array('$paid_to_date', $variables)) {
$variables = \array_diff($variables, ['$paid_to_date']);
}
-
}
foreach (['discount'] as $property) {
diff --git a/app/Services/PdfMaker/PdfMerge.php b/app/Services/PdfMaker/PdfMerge.php
index d0c8f7bdc8bd..8f515f63146e 100644
--- a/app/Services/PdfMaker/PdfMerge.php
+++ b/app/Services/PdfMaker/PdfMerge.php
@@ -12,18 +12,18 @@
namespace App\Services\PdfMaker;
-use Illuminate\Support\Facades\Storage;
use \setasign\Fpdi\Fpdi;
+use Illuminate\Support\Facades\Storage;
use setasign\Fpdi\PdfParser\StreamReader;
class PdfMerge
{
-
- public function __construct(private array $file_paths) {}
+ public function __construct(private array $file_paths)
+ {
+ }
public function run()
{
-
$pdf = new FPDI();
foreach ($this->file_paths as $file) {
@@ -36,7 +36,5 @@ class PdfMerge
}
return $pdf->Output('S');
-
}
-
}
diff --git a/app/Services/PurchaseOrder/GetPurchaseOrderPdf.php b/app/Services/PurchaseOrder/GetPurchaseOrderPdf.php
index 4f263597983e..dde550a269c7 100644
--- a/app/Services/PurchaseOrder/GetPurchaseOrderPdf.php
+++ b/app/Services/PurchaseOrder/GetPurchaseOrderPdf.php
@@ -15,7 +15,6 @@ use App\Jobs\Vendor\CreatePurchaseOrderPdf;
use App\Models\PurchaseOrder;
use App\Models\VendorContact;
use App\Services\AbstractService;
-use App\Utils\TempFile;
use Illuminate\Support\Facades\Storage;
class GetPurchaseOrderPdf extends AbstractService
diff --git a/app/Services/PurchaseOrder/MarkSent.php b/app/Services/PurchaseOrder/MarkSent.php
index a81d91b45433..f458bb8a8216 100644
--- a/app/Services/PurchaseOrder/MarkSent.php
+++ b/app/Services/PurchaseOrder/MarkSent.php
@@ -11,10 +11,8 @@
namespace App\Services\PurchaseOrder;
-use App\Jobs\Util\WebhookHandler;
use App\Models\PurchaseOrder;
use App\Models\Webhook;
-use App\Utils\Ninja;
class MarkSent
{
@@ -30,7 +28,6 @@ class MarkSent
public function run()
{
-
/* Return immediately if status is not draft */
if ($this->purchase_order->status_id != PurchaseOrder::STATUS_DRAFT) {
return $this->purchase_order;
diff --git a/app/Services/PurchaseOrder/PurchaseOrderExpense.php b/app/Services/PurchaseOrder/PurchaseOrderExpense.php
index bb65fffe3fff..d206efbb28fb 100644
--- a/app/Services/PurchaseOrder/PurchaseOrderExpense.php
+++ b/app/Services/PurchaseOrder/PurchaseOrderExpense.php
@@ -28,7 +28,6 @@ class PurchaseOrderExpense
public function run()
{
-
$expense = ExpenseFactory::create($this->purchase_order->company_id, $this->purchase_order->user_id);
$expense->amount = $this->purchase_order->uses_inclusive_taxes ? $this->purchase_order->amount : ($this->purchase_order->amount - $this->purchase_order->total_taxes);
@@ -45,19 +44,18 @@ class PurchaseOrderExpense
$expense->public_notes = '';
- foreach($line_items as $line_item){
+ foreach ($line_items as $line_item) {
$expense->public_notes .= $line_item->quantity . " x " . $line_item->product_key. " [ " .$line_item->notes . " ]\n";
}
$tax_map = $this->purchase_order->calc()->getTaxMap();
- if($this->purchase_order->total_taxes > 0)
- {
+ if ($this->purchase_order->total_taxes > 0) {
$expense->tax_amount1 = $this->purchase_order->total_taxes;
$expense->tax_name1 = ctrans("texts.tax");
}
- $expense->number = empty($expense->number) ? $this->getNextExpenseNumber($expense) : $expense->number;
+ $expense->number = empty($expense->number) ? $this->getNextExpenseNumber($expense) : $expense->number;
$expense->save();
event('eloquent.created: App\Models\Expense', $expense);
@@ -66,6 +64,5 @@ class PurchaseOrderExpense
$this->purchase_order->saveQuietly();
return $expense;
-
}
}
diff --git a/app/Services/PurchaseOrder/PurchaseOrderInventory.php b/app/Services/PurchaseOrder/PurchaseOrderInventory.php
index 2c7b58d71c76..298c5718f617 100644
--- a/app/Services/PurchaseOrder/PurchaseOrderInventory.php
+++ b/app/Services/PurchaseOrder/PurchaseOrderInventory.php
@@ -11,17 +11,11 @@
namespace App\Services\PurchaseOrder;
-use App\Factory\ExpenseFactory;
-use App\Jobs\Mail\NinjaMailer;
-use App\Jobs\Mail\NinjaMailerJob;
-use App\Jobs\Mail\NinjaMailerObject;
-use App\Mail\Admin\InventoryNotificationObject;
use App\Models\Product;
use App\Models\PurchaseOrder;
class PurchaseOrderInventory
{
-
private PurchaseOrder $purchase_order;
public function __construct(PurchaseOrder $purchase_order)
@@ -31,27 +25,22 @@ class PurchaseOrderInventory
public function run()
{
-
$line_items = $this->purchase_order->line_items;
- foreach($line_items as $item)
- {
-
+ foreach ($line_items as $item) {
$p = Product::where('product_key', $item->product_key)->where('company_id', $this->purchase_order->company_id)->first();
- if(!$p)
+ if (!$p) {
continue;
+ }
$p->in_stock_quantity += $item->quantity;
$p->saveQuietly();
-
}
$this->purchase_order->status_id = PurchaseOrder::STATUS_RECEIVED;
$this->purchase_order->save();
return $this->purchase_order;
-
}
-
}
diff --git a/app/Services/PurchaseOrder/PurchaseOrderService.php b/app/Services/PurchaseOrder/PurchaseOrderService.php
index 80bfb889e4ba..d1ab465d262c 100644
--- a/app/Services/PurchaseOrder/PurchaseOrderService.php
+++ b/app/Services/PurchaseOrder/PurchaseOrderService.php
@@ -13,11 +13,6 @@ namespace App\Services\PurchaseOrder;
use App\Jobs\Vendor\CreatePurchaseOrderPdf;
use App\Models\PurchaseOrder;
-use App\Services\PurchaseOrder\ApplyNumber;
-use App\Services\PurchaseOrder\CreateInvitations;
-use App\Services\PurchaseOrder\GetPurchaseOrderPdf;
-use App\Services\PurchaseOrder\PurchaseOrderExpense;
-use App\Services\PurchaseOrder\TriggeredActions;
use App\Utils\Traits\MakesHash;
class PurchaseOrderService
@@ -33,7 +28,6 @@ class PurchaseOrderService
public function createInvitations()
{
-
$this->purchase_order = (new CreateInvitations($this->purchase_order))->run();
return $this;
@@ -48,27 +42,29 @@ class PurchaseOrderService
public function fillDefaults()
{
-
$settings = $this->purchase_order->company->settings;
- if (! $this->purchase_order->design_id)
+ if (! $this->purchase_order->design_id) {
$this->purchase_order->design_id = $this->decodePrimaryKey($settings->purchase_order_design_id);
+ }
- if (!isset($this->purchase_order->footer) || empty($this->purchase_order->footer))
+ if (!isset($this->purchase_order->footer) || empty($this->purchase_order->footer)) {
$this->purchase_order->footer = $settings->purchase_order_footer;
+ }
- if (!isset($this->purchase_order->terms) || empty($this->purchase_order->terms))
+ if (!isset($this->purchase_order->terms) || empty($this->purchase_order->terms)) {
$this->purchase_order->terms = $settings->purchase_order_terms;
+ }
- if (!isset($this->purchase_order->public_notes) || empty($this->purchase_order->public_notes))
+ if (!isset($this->purchase_order->public_notes) || empty($this->purchase_order->public_notes)) {
$this->purchase_order->public_notes = $this->purchase_order->vendor->public_notes;
+ }
- if($settings->counter_number_applied == 'when_saved'){
+ if ($settings->counter_number_applied == 'when_saved') {
$this->applyNumber()->save();
}
return $this;
-
}
public function triggeredActions($request)
@@ -107,9 +103,7 @@ class PurchaseOrderService
public function touchPdf($force = false)
{
try {
-
- if($force){
-
+ if ($force) {
$this->purchase_order->invitations->each(function ($invitation) {
(new CreatePurchaseOrderPdf($invitation))->handle();
});
@@ -120,12 +114,8 @@ class PurchaseOrderService
$this->purchase_order->invitations->each(function ($invitation) {
CreatePurchaseOrderPdf::dispatch($invitation);
});
-
- }
- catch(\Exception $e){
-
+ } catch(\Exception $e) {
nlog("failed creating purchase orders in Touch PDF");
-
}
return $this;
@@ -133,8 +123,9 @@ class PurchaseOrderService
public function add_to_inventory()
{
- if($this->purchase_order->status_id >= PurchaseOrder::STATUS_RECEIVED)
+ if ($this->purchase_order->status_id >= PurchaseOrder::STATUS_RECEIVED) {
return $this->purchase_order;
+ }
$this->purchase_order = (new PurchaseOrderInventory($this->purchase_order))->run();
@@ -145,8 +136,9 @@ class PurchaseOrderService
{
$this->markSent();
- if($this->purchase_order->expense()->exists())
+ if ($this->purchase_order->expense()->exists()) {
return $this;
+ }
$expense = (new PurchaseOrderExpense($this->purchase_order))->run();
@@ -163,5 +155,4 @@ class PurchaseOrderService
return $this->purchase_order;
}
-
}
diff --git a/app/Services/PurchaseOrder/TriggeredActions.php b/app/Services/PurchaseOrder/TriggeredActions.php
index 8e2ef3f3ea33..02e9e0bdc871 100644
--- a/app/Services/PurchaseOrder/TriggeredActions.php
+++ b/app/Services/PurchaseOrder/TriggeredActions.php
@@ -11,14 +11,9 @@
namespace App\Services\PurchaseOrder;
-use App\Events\Invoice\InvoiceWasEmailed;
-use App\Events\PurchaseOrder\PurchaseOrderWasEmailed;
-use App\Jobs\Entity\EmailEntity;
use App\Jobs\PurchaseOrder\PurchaseOrderEmail;
-use App\Models\Invoice;
use App\Models\PurchaseOrder;
use App\Services\AbstractService;
-use App\Utils\Ninja;
use App\Utils\Traits\GeneratesCounter;
use Illuminate\Http\Request;
@@ -52,7 +47,7 @@ class TriggeredActions extends AbstractService
// $this->purchase_order = $this->purchase_order->service()->handleCancellation()->save();
// }
- if($this->request->has('save_default_footer') && $this->request->input('save_default_footer') == 'true') {
+ if ($this->request->has('save_default_footer') && $this->request->input('save_default_footer') == 'true') {
$company = $this->purchase_order->company;
$settings = $company->settings;
$settings->purchase_order_footer = $this->purchase_order->footer;
@@ -60,7 +55,7 @@ class TriggeredActions extends AbstractService
$company->save();
}
- if($this->request->has('save_default_terms') && $this->request->input('save_default_terms') == 'true') {
+ if ($this->request->has('save_default_terms') && $this->request->input('save_default_terms') == 'true') {
$company = $this->purchase_order->company;
$settings = $company->settings;
$settings->purchase_order_terms = $this->purchase_order->terms;
diff --git a/app/Services/Quote/GetQuotePdf.php b/app/Services/Quote/GetQuotePdf.php
index 88a4f55b0db4..09249ec9ff95 100644
--- a/app/Services/Quote/GetQuotePdf.php
+++ b/app/Services/Quote/GetQuotePdf.php
@@ -15,7 +15,6 @@ use App\Jobs\Entity\CreateEntityPdf;
use App\Models\ClientContact;
use App\Models\Quote;
use App\Services\AbstractService;
-use App\Utils\TempFile;
use Illuminate\Support\Facades\Storage;
class GetQuotePdf extends AbstractService
diff --git a/app/Services/Quote/MarkSent.php b/app/Services/Quote/MarkSent.php
index 76a4687db885..fa9c75a565b9 100644
--- a/app/Services/Quote/MarkSent.php
+++ b/app/Services/Quote/MarkSent.php
@@ -12,7 +12,6 @@
namespace App\Services\Quote;
use App\Events\Quote\QuoteWasMarkedSent;
-use App\Jobs\Util\WebhookHandler;
use App\Models\Quote;
use App\Models\Webhook;
use App\Utils\Ninja;
@@ -32,7 +31,6 @@ class MarkSent
public function run()
{
-
/* Return immediately if status is not draft */
if ($this->quote->status_id != Quote::STATUS_DRAFT) {
return $this->quote;
diff --git a/app/Services/Quote/QuoteService.php b/app/Services/Quote/QuoteService.php
index 72fb91374d53..56ab95d8eb38 100644
--- a/app/Services/Quote/QuoteService.php
+++ b/app/Services/Quote/QuoteService.php
@@ -12,13 +12,11 @@
namespace App\Services\Quote;
use App\Events\Quote\QuoteWasApproved;
-use App\Factory\InvoiceInvitationFactory;
use App\Jobs\Entity\CreateEntityPdf;
use App\Jobs\Util\UnlinkFile;
use App\Models\Invoice;
use App\Models\Quote;
use App\Repositories\QuoteRepository;
-use App\Services\Quote\TriggeredActions;
use App\Utils\Ninja;
use App\Utils\Traits\MakesHash;
@@ -129,7 +127,7 @@ class QuoteService
/**
* Sometimes we need to refresh the
* PDF when it is updated etc.
- *
+ *
* @return QuoteService
*/
public function touchPdf($force = false)
diff --git a/app/Services/Quote/SendEmail.php b/app/Services/Quote/SendEmail.php
index 9e05fbb74f2c..1d40bc51835f 100644
--- a/app/Services/Quote/SendEmail.php
+++ b/app/Services/Quote/SendEmail.php
@@ -50,13 +50,12 @@ class SendEmail
$this->quote->service()->markSent()->save();
- $this->quote->invitations->each(function ($invitation) use ($mo){
+ $this->quote->invitations->each(function ($invitation) use ($mo) {
if (! $invitation->contact->trashed() && $invitation->contact->email) {
EmailEntity::dispatch($invitation, $invitation->company, $this->reminder_template);
// MailEntity::dispatch($invitation, $invitation->company->db, $mo);
}
});
-
}
}
diff --git a/app/Services/Quote/TriggeredActions.php b/app/Services/Quote/TriggeredActions.php
index ba44a3d34fb9..0d59dc672b31 100644
--- a/app/Services/Quote/TriggeredActions.php
+++ b/app/Services/Quote/TriggeredActions.php
@@ -53,7 +53,7 @@ class TriggeredActions extends AbstractService
$this->quote = $this->quote->service()->approveWithNoCoversion()->save();
}
- if($this->request->has('save_default_footer') && $this->request->input('save_default_footer') == 'true') {
+ if ($this->request->has('save_default_footer') && $this->request->input('save_default_footer') == 'true') {
$company = $this->quote->company;
$settings = $company->settings;
$settings->quote_footer = $this->quote->footer;
@@ -61,7 +61,7 @@ class TriggeredActions extends AbstractService
$company->save();
}
- if($this->request->has('save_default_terms') && $this->request->input('save_default_terms') == 'true') {
+ if ($this->request->has('save_default_terms') && $this->request->input('save_default_terms') == 'true') {
$company = $this->quote->company;
$settings = $company->settings;
$settings->quote_terms = $this->quote->terms;
diff --git a/app/Services/Recurring/CreateRecurringInvitations.php b/app/Services/Recurring/CreateRecurringInvitations.php
index 6fed3f7e5dee..128c3bab1934 100644
--- a/app/Services/Recurring/CreateRecurringInvitations.php
+++ b/app/Services/Recurring/CreateRecurringInvitations.php
@@ -64,15 +64,14 @@ class CreateRecurringInvitations extends AbstractService
}
if ($this->entity->invitations()->count() == 0) {
-
$invitation = $this->invitation_class::where('company_id', $this->entity->company_id)
->where($this->entity_id_name, $this->entity->id)
->withTrashed()
->first();
- if ($invitation)
+ if ($invitation) {
$invitation->restore();
-
+ }
}
diff --git a/app/Services/Recurring/GetInvoicePdf.php b/app/Services/Recurring/GetInvoicePdf.php
index 54776e4c57ad..448663f8e0cc 100644
--- a/app/Services/Recurring/GetInvoicePdf.php
+++ b/app/Services/Recurring/GetInvoicePdf.php
@@ -13,9 +13,7 @@ namespace App\Services\Recurring;
use App\Jobs\Entity\CreateEntityPdf;
use App\Models\ClientContact;
-use App\Models\Invoice;
use App\Services\AbstractService;
-use App\Utils\TempFile;
use Illuminate\Support\Facades\Storage;
class GetInvoicePdf extends AbstractService
diff --git a/app/Services/Recurring/RecurringService.php b/app/Services/Recurring/RecurringService.php
index 057a5b939a7d..06595f6d2aa3 100644
--- a/app/Services/Recurring/RecurringService.php
+++ b/app/Services/Recurring/RecurringService.php
@@ -14,7 +14,6 @@ namespace App\Services\Recurring;
use App\Jobs\RecurringInvoice\SendRecurring;
use App\Jobs\Util\UnlinkFile;
use App\Models\RecurringInvoice;
-use App\Services\Recurring\GetInvoicePdf;
use Illuminate\Support\Carbon;
class RecurringService
@@ -35,8 +34,9 @@ class RecurringService
*/
public function stop()
{
- if($this->recurring_entity->status_id < RecurringInvoice::STATUS_PAUSED)
+ if ($this->recurring_entity->status_id < RecurringInvoice::STATUS_PAUSED) {
$this->recurring_entity->status_id = RecurringInvoice::STATUS_PAUSED;
+ }
return $this;
}
@@ -50,7 +50,6 @@ class RecurringService
public function start()
{
-
if ($this->recurring_entity->remaining_cycles == 0) {
return $this;
}
@@ -85,11 +84,8 @@ class RecurringService
public function deletePdf()
{
-
- $this->recurring_entity->invitations->each(function ($invitation){
-
- (new UnlinkFile(config('filesystems.default'), $this->recurring_entity->client->recurring_invoice_filepath($invitation) . $this->recurring_entity->numberFormatter().'.pdf'))->handle();
-
+ $this->recurring_entity->invitations->each(function ($invitation) {
+ (new UnlinkFile(config('filesystems.default'), $this->recurring_entity->client->recurring_invoice_filepath($invitation) . $this->recurring_entity->numberFormatter().'.pdf'))->handle();
});
@@ -98,7 +94,6 @@ class RecurringService
public function triggeredActions($request)
{
-
if ($request->has('start') && $request->input('start') == 'true') {
$this->start();
}
@@ -113,8 +108,7 @@ class RecurringService
return $this;
}
- if(isset($this->recurring_entity->client))
- {
+ if (isset($this->recurring_entity->client)) {
$offset = $this->recurring_entity->client->timezone_offset();
$this->recurring_entity->next_send_date = Carbon::parse($this->recurring_entity->next_send_date_client)->startOfDay()->addSeconds($offset);
}
@@ -124,21 +118,18 @@ class RecurringService
public function sendNow()
{
-
- if($this->recurring_entity instanceof RecurringInvoice && $this->recurring_entity->status_id == RecurringInvoice::STATUS_DRAFT){
+ if ($this->recurring_entity instanceof RecurringInvoice && $this->recurring_entity->status_id == RecurringInvoice::STATUS_DRAFT) {
$this->start()->save();
- (new SendRecurring($this->recurring_entity, $this->recurring_entity->company->db))->handle();
+ (new SendRecurring($this->recurring_entity, $this->recurring_entity->company->db))->handle();
}
$this->recurring_entity = $this->recurring_entity->fresh();
return $this;
-
}
public function fillDefaults()
{
-
return $this;
}
diff --git a/app/Services/Report/ProfitLoss.php b/app/Services/Report/ProfitLoss.php
index 7e07fa57a0fb..2415a9b02444 100644
--- a/app/Services/Report/ProfitLoss.php
+++ b/app/Services/Report/ProfitLoss.php
@@ -104,10 +104,8 @@ class ProfitLoss
MultiDB::setDb($this->company->db);
if ($this->is_income_billed) { //get invoiced amounts
-
$this->filterIncome();
} else {
-
//$this->filterPaymentIncome();
$this->filterInvoicePaymentIncome();
}
@@ -592,48 +590,55 @@ class ProfitLoss
}
switch ($date_range) {
-
case 'all':
$this->start_date = now()->subYears(50);
$this->end_date = now();
// return $query;
+ // no break
case 'last7':
$this->start_date = now()->subDays(7);
$this->end_date = now();
// return $query->whereBetween($this->date_key, [now()->subDays(7), now()])->orderBy($this->date_key, 'ASC');
+ // no break
case 'last30':
$this->start_date = now()->subDays(30);
$this->end_date = now();
// return $query->whereBetween($this->date_key, [now()->subDays(30), now()])->orderBy($this->date_key, 'ASC');
+ // no break
case 'this_month':
$this->start_date = now()->startOfMonth();
$this->end_date = now();
//return $query->whereBetween($this->date_key, [now()->startOfMonth(), now()])->orderBy($this->date_key, 'ASC');
+ // no break
case 'last_month':
$this->start_date = now()->startOfMonth()->subMonth();
$this->end_date = now()->startOfMonth()->subMonth()->endOfMonth();
//return $query->whereBetween($this->date_key, [now()->startOfMonth()->subMonth(), now()->startOfMonth()->subMonth()->endOfMonth()])->orderBy($this->date_key, 'ASC');
+ // no break
case 'this_quarter':
$this->start_date = (new \Carbon\Carbon('-3 months'))->firstOfQuarter();
$this->end_date = (new \Carbon\Carbon('-3 months'))->lastOfQuarter();
//return $query->whereBetween($this->date_key, [(new \Carbon\Carbon('-3 months'))->firstOfQuarter(), (new \Carbon\Carbon('-3 months'))->lastOfQuarter()])->orderBy($this->date_key, 'ASC');
+ // no break
case 'last_quarter':
$this->start_date = (new \Carbon\Carbon('-6 months'))->firstOfQuarter();
$this->end_date = (new \Carbon\Carbon('-6 months'))->lastOfQuarter();
//return $query->whereBetween($this->date_key, [(new \Carbon\Carbon('-6 months'))->firstOfQuarter(), (new \Carbon\Carbon('-6 months'))->lastOfQuarter()])->orderBy($this->date_key, 'ASC');
+ // no break
case 'this_year':
$this->start_date = now()->startOfYear();
$this->end_date = now();
//return $query->whereBetween($this->date_key, [now()->startOfYear(), now()])->orderBy($this->date_key, 'ASC');
+ // no break
case 'custom':
$this->start_date = $custom_start_date;
$this->end_date = $custom_end_date;
//return $query->whereBetween($this->date_key, [$custom_start_date, $custom_end_date])->orderBy($this->date_key, 'ASC');
+ // no break
default:
$this->start_date = now()->startOfYear();
$this->end_date = now();
// return $query->whereBetween($this->date_key, [now()->startOfYear(), now()])->orderBy($this->date_key, 'ASC');
-
}
return $this;
diff --git a/app/Services/Scheduler/SchedulerService.php b/app/Services/Scheduler/SchedulerService.php
index 413bbdc78f12..854ff8efce4c 100644
--- a/app/Services/Scheduler/SchedulerService.php
+++ b/app/Services/Scheduler/SchedulerService.php
@@ -16,7 +16,6 @@ use App\Models\RecurringInvoice;
use App\Models\Scheduler;
use App\Utils\Traits\MakesDates;
use App\Utils\Traits\MakesHash;
-use Carbon\Carbon;
class SchedulerService
{
@@ -27,12 +26,14 @@ class SchedulerService
private Client $client;
- public function __construct(public Scheduler $scheduler) {}
+ public function __construct(public Scheduler $scheduler)
+ {
+ }
/**
* Called from the TaskScheduler Cron
- *
- * @return void
+ *
+ * @return void
*/
public function runTask(): void
{
@@ -40,35 +41,33 @@ class SchedulerService
}
private function client_statement()
- {
+ {
$query = Client::query()
->where('company_id', $this->scheduler->company_id)
- ->where('is_deleted',0);
+ ->where('is_deleted', 0);
//Email only the selected clients
- if(count($this->scheduler->parameters['clients']) >= 1)
+ if (count($this->scheduler->parameters['clients']) >= 1) {
$query->whereIn('id', $this->transformKeys($this->scheduler->parameters['clients']));
+ }
$query->cursor()
- ->each(function ($_client){
+ ->each(function ($_client) {
+ $this->client = $_client;
- $this->client = $_client;
+ //work out the date range
+ $statement_properties = $this->calculateStatementProperties();
- //work out the date range
- $statement_properties = $this->calculateStatementProperties();
-
- $_client->service()->statement($statement_properties,true);
-
- });
+ $_client->service()->statement($statement_properties, true);
+ });
//calculate next run dates;
$this->calculateNextRun();
-
}
/**
* Hydrates the array needed to generate the statement
- *
+ *
* @return array The statement options array
*/
private function calculateStatementProperties(): array
@@ -76,18 +75,17 @@ class SchedulerService
$start_end = $this->calculateStartAndEndDates();
return [
- 'start_date' =>$start_end[0],
- 'end_date' =>$start_end[1],
- 'show_payments_table' => $this->scheduler->parameters['show_payments_table'],
- 'show_aging_table' => $this->scheduler->parameters['show_aging_table'],
+ 'start_date' =>$start_end[0],
+ 'end_date' =>$start_end[1],
+ 'show_payments_table' => $this->scheduler->parameters['show_payments_table'],
+ 'show_aging_table' => $this->scheduler->parameters['show_aging_table'],
'status' => $this->scheduler->parameters['status']
];
-
}
/**
* Start and end date of the statement
- *
+ *
* @return array [$start_date, $end_date];
*/
private function calculateStartAndEndDates(): array
@@ -100,14 +98,14 @@ class SchedulerService
'previous_quarter' => [now()->startOfDay()->subQuarterNoOverflow()->firstOfQuarter()->format('Y-m-d'), now()->startOfDay()->subQuarterNoOverflow()->lastOfQuarter()->format('Y-m-d')],
'previous_year' => [now()->startOfDay()->subYearNoOverflow()->firstOfYear()->format('Y-m-d'), now()->startOfDay()->subYearNoOverflow()->lastOfYear()->format('Y-m-d')],
'custom_range' => [$this->scheduler->parameters['start_date'], $this->scheduler->parameters['end_date']],
- default => [now()->startOfDay()->firstOfMonth()->format('Y-m-d'), now()->startOfDay()->lastOfMonth()->format('Y-m-d')],
+ default => [now()->startOfDay()->firstOfMonth()->format('Y-m-d'), now()->startOfDay()->lastOfMonth()->format('Y-m-d')],
};
}
/**
* Sets the next run date of the scheduled task
- *
+ *
*/
private function calculateNextRun()
{
@@ -159,13 +157,10 @@ class SchedulerService
}
- $this->scheduler->next_run_client = $next_run ?: null;
+ $this->scheduler->next_run_client = $next_run ?: null;
$this->scheduler->next_run = $next_run ? $next_run->copy()->addSeconds($offset) : null;
$this->scheduler->save();
-
}
//handle when the scheduler has been paused.
-
-
-}
\ No newline at end of file
+}
diff --git a/app/Services/Subscription/SubscriptionService.php b/app/Services/Subscription/SubscriptionService.php
index e2c0e9f56383..08d803d52ef5 100644
--- a/app/Services/Subscription/SubscriptionService.php
+++ b/app/Services/Subscription/SubscriptionService.php
@@ -14,13 +14,11 @@ namespace App\Services\Subscription;
use App\DataMapper\InvoiceItem;
use App\Factory\CreditFactory;
use App\Factory\InvoiceFactory;
-use App\Factory\InvoiceToRecurringInvoiceFactory;
use App\Factory\PaymentFactory;
use App\Factory\RecurringInvoiceFactory;
use App\Jobs\Mail\NinjaMailer;
use App\Jobs\Mail\NinjaMailerJob;
use App\Jobs\Mail\NinjaMailerObject;
-use App\Jobs\Util\SubscriptionWebhookHandler;
use App\Jobs\Util\SystemLogger;
use App\Libraries\MultiDB;
use App\Mail\RecurringInvoice\ClientContactRequestCancellationObject;
@@ -39,14 +37,11 @@ use App\Repositories\InvoiceRepository;
use App\Repositories\PaymentRepository;
use App\Repositories\RecurringInvoiceRepository;
use App\Repositories\SubscriptionRepository;
-use App\Services\Subscription\ZeroCostProduct;
-use App\Utils\Ninja;
use App\Utils\Traits\CleanLineItems;
use App\Utils\Traits\MakesHash;
use App\Utils\Traits\Notifications\UserNotifies;
use App\Utils\Traits\SubscriptionHooker;
use Carbon\Carbon;
-use GuzzleHttp\RequestOptions;
use Illuminate\Contracts\Container\BindingResolutionException;
class SubscriptionService
@@ -72,22 +67,21 @@ class SubscriptionService
*/
public function completePurchase(PaymentHash $payment_hash)
{
-
if (!property_exists($payment_hash->data, 'billing_context')) {
throw new \Exception("Illegal entrypoint into method, payload must contain billing context");
}
- if($payment_hash->data->billing_context->context == 'change_plan') {
+ if ($payment_hash->data->billing_context->context == 'change_plan') {
return $this->handlePlanChange($payment_hash);
}
// if we have a recurring product - then generate a recurring invoice
- if(strlen($this->subscription->recurring_product_ids) >=1){
-
- if(isset($payment_hash->data->billing_context->bundle))
+ if (strlen($this->subscription->recurring_product_ids) >=1) {
+ if (isset($payment_hash->data->billing_context->bundle)) {
$recurring_invoice = $this->convertInvoiceToRecurringBundle($payment_hash->payment->client_id, $payment_hash->data->billing_context->bundle);
- else
+ } else {
$recurring_invoice = $this->convertInvoiceToRecurring($payment_hash->payment->client_id);
+ }
$recurring_invoice_repo = new RecurringInvoiceRepository();
@@ -120,10 +114,7 @@ class SubscriptionService
$response = $this->triggerWebhook($context);
$this->handleRedirect('/client/recurring_invoices/'.$recurring_invoice->hashed_id);
-
- }
- else
- {
+ } else {
$invoice = Invoice::withTrashed()->find($payment_hash->fee_invoice_id);
$context = [
@@ -139,9 +130,9 @@ class SubscriptionService
/* 06-04-2022 */
/* We may not be in a state where the user is present */
- if(auth()->guard('contact'))
+ if (auth()->guard('contact')) {
$this->handleRedirect('/client/invoices/'.$this->encodePrimaryKey($payment_hash->fee_invoice_id));
-
+ }
}
}
@@ -172,27 +163,29 @@ class SubscriptionService
// Redirects from here work just fine. Livewire will respect it.
$client_contact = ClientContact::find($this->decodePrimaryKey($data['contact_id']));
- if(!$this->subscription->trial_enabled)
+ if (!$this->subscription->trial_enabled) {
return new \Exception("Trials are disabled for this product");
+ }
//create recurring invoice with start date = trial_duration + 1 day
$recurring_invoice_repo = new RecurringInvoiceRepository();
- if(isset($data['bundle']))
- $recurring_invoice = $this->convertInvoiceToRecurringBundle($client_contact->client_id, $data['bundle']->map(function ($bundle){ return (object) $bundle;}));
- else
+ if (isset($data['bundle'])) {
+ $recurring_invoice = $this->convertInvoiceToRecurringBundle($client_contact->client_id, $data['bundle']->map(function ($bundle) {
+ return (object) $bundle;
+ }));
+ } else {
$recurring_invoice = $this->convertInvoiceToRecurring($client_contact->client_id);
+ }
$recurring_invoice->next_send_date = now()->addSeconds($this->subscription->trial_duration);
$recurring_invoice->next_send_date_client = now()->addSeconds($this->subscription->trial_duration);
$recurring_invoice->backup = 'is_trial';
- if(array_key_exists('coupon', $data) && ($data['coupon'] == $this->subscription->promo_code) && $this->subscription->promo_discount > 0)
- {
+ if (array_key_exists('coupon', $data) && ($data['coupon'] == $this->subscription->promo_code) && $this->subscription->promo_discount > 0) {
$recurring_invoice->discount = $this->subscription->promo_discount;
$recurring_invoice->is_amount_discount = $this->subscription->is_amount_discount;
- }
- elseif(strlen($this->subscription->promo_code) == 0 && $this->subscription->promo_discount > 0) {
+ } elseif (strlen($this->subscription->promo_code) == 0 && $this->subscription->promo_discount > 0) {
$recurring_invoice->discount = $this->subscription->promo_discount;
$recurring_invoice->is_amount_discount = $this->subscription->is_amount_discount;
}
@@ -204,13 +197,13 @@ class SubscriptionService
->start()
->save();
- $context = [
- 'context' => 'trial',
- 'recurring_invoice' => $recurring_invoice->hashed_id,
- 'client' => $recurring_invoice->client->hashed_id,
- 'subscription' => $this->subscription->hashed_id,
- 'account_key' => $recurring_invoice->client->custom_value2,
- ];
+ $context = [
+ 'context' => 'trial',
+ 'recurring_invoice' => $recurring_invoice->hashed_id,
+ 'client' => $recurring_invoice->client->hashed_id,
+ 'subscription' => $this->subscription->hashed_id,
+ 'account_key' => $recurring_invoice->client->custom_value2,
+ ];
//execute any webhooks
$response = $this->triggerWebhook($context);
@@ -231,7 +224,6 @@ class SubscriptionService
*/
public function calculateUpgradePriceV2(RecurringInvoice $recurring_invoice, Subscription $target) :?float
{
-
$outstanding_credit = 0;
$use_credit_setting = $recurring_invoice->client->getSetting('use_credits_payment');
@@ -244,22 +236,18 @@ class SubscriptionService
$refund = $this->calculateProRataRefundForSubscription($last_invoice);
- if($use_credit_setting != 'off')
- {
-
+ if ($use_credit_setting != 'off') {
$outstanding_credit = Credit::query()
->where('client_id', $recurring_invoice->client_id)
->whereIn('status_id', [Credit::STATUS_SENT,Credit::STATUS_PARTIAL])
->where('is_deleted', 0)
->where('balance', '>', 0)
->sum('balance');
-
}
nlog("{$target->price} - {$refund} - {$outstanding_credit}");
return $target->price - $refund - $outstanding_credit;
-
}
/**
@@ -275,7 +263,6 @@ class SubscriptionService
*/
public function calculateUpgradePrice(RecurringInvoice $recurring_invoice, Subscription $target) :?float
{
-
//calculate based on daily prices
$current_amount = $recurring_invoice->amount;
$currency_frequency = $recurring_invoice->frequency_id;
@@ -283,7 +270,7 @@ class SubscriptionService
$outstanding = Invoice::query()
->where('recurring_id', $recurring_invoice->id)
->where('is_deleted', 0)
- ->where('is_proforma',0)
+ ->where('is_proforma', 0)
->whereIn('status_id', [Invoice::STATUS_SENT, Invoice::STATUS_PARTIAL])
->where('balance', '>', 0);
@@ -291,67 +278,60 @@ class SubscriptionService
$outstanding_invoice = Invoice::where('client_id', $recurring_invoice->client_id)
->where('is_deleted', 0)
- ->where('is_proforma',0)
+ ->where('is_proforma', 0)
->where('subscription_id', $this->subscription->id)
->orderBy('id', 'desc')
->first();
- //sometimes the last document could be a credit if the user is paying for their service with credits.
- if(!$outstanding_invoice){
-
- $outstanding_invoice = Credit::where('subscription_id', $this->subscription->id)
- ->where('client_id', $recurring_invoice->client_id)
- ->where('is_proforma',0)
- ->where('is_deleted', 0)
- ->orderBy('id', 'desc')
- ->first();
+ //sometimes the last document could be a credit if the user is paying for their service with credits.
+ if (!$outstanding_invoice) {
+ $outstanding_invoice = Credit::where('subscription_id', $this->subscription->id)
+ ->where('client_id', $recurring_invoice->client_id)
+ ->where('is_proforma', 0)
+ ->where('is_deleted', 0)
+ ->orderBy('id', 'desc')
+ ->first();
}
//need to ensure at this point that a refund is appropriate!!
//28-02-2022
- if($recurring_invoice->invoices()->count() == 0){
+ if ($recurring_invoice->invoices()->count() == 0) {
return $target->price;
- }
- elseif ($outstanding->count() == 0){
+ } elseif ($outstanding->count() == 0) {
//nothing outstanding
return $target->price - $this->calculateProRataRefundForSubscription($outstanding_invoice);
- }
- elseif ($outstanding->count() == 1){
+ } elseif ($outstanding->count() == 1) {
//user has multiple amounts outstanding
return $target->price - $this->calculateProRataRefundForSubscription($outstanding_invoice);
- }
- elseif ($outstanding->count() > 1) {
+ } elseif ($outstanding->count() > 1) {
//user is changing plan mid frequency cycle
//we cannot handle this if there are more than one invoice outstanding.
return $target->price;
}
return $target->price;
-
}
/**
* We refund unused days left.
*
* @param Invoice $invoice
- *
+ *
* @return float
*/
private function calculateProRataRefundForSubscription($invoice) :float
{
- if(!$invoice || !$invoice->date || $invoice->status_id != Invoice::STATUS_PAID)
+ if (!$invoice || !$invoice->date || $invoice->status_id != Invoice::STATUS_PAID) {
return 0;
+ }
/*Remove previous refunds from the calculation of the amount*/
- $invoice->line_items = collect($invoice->line_items)->filter(function($item){
-
- if($item->product_key == ctrans("texts.refund"))
- {
+ $invoice->line_items = collect($invoice->line_items)->filter(function ($item) {
+ if ($item->product_key == ctrans("texts.refund")) {
return false;
}
return true;
-
})->toArray();
$amount = $invoice->calc()->getTotal();
@@ -364,11 +344,10 @@ class SubscriptionService
$days_in_frequency = $this->getDaysInFrequency();
- $pro_rata_refund = round((($days_in_frequency - $days_of_subscription_used)/$days_in_frequency) * $amount ,2);
+ $pro_rata_refund = round((($days_in_frequency - $days_of_subscription_used)/$days_in_frequency) * $amount, 2);
return max(0, $pro_rata_refund);
-
- }
+ }
/**
* We refund unused days left.
@@ -378,8 +357,9 @@ class SubscriptionService
*/
private function calculateProRataRefund($invoice) :float
{
- if(!$invoice || !$invoice->date)
+ if (!$invoice || !$invoice->date) {
return 0;
+ }
$start_date = Carbon::parse($invoice->date);
@@ -389,13 +369,13 @@ class SubscriptionService
$days_in_frequency = $this->getDaysInFrequency();
- if($days_of_subscription_used >= $days_in_frequency)
+ if ($days_of_subscription_used >= $days_in_frequency) {
return 0;
+ }
- $pro_rata_refund = round((($days_in_frequency - $days_of_subscription_used)/$days_in_frequency) * $invoice->amount ,2);
+ $pro_rata_refund = round((($days_in_frequency - $days_of_subscription_used)/$days_in_frequency) * $invoice->amount, 2);
return $pro_rata_refund;
-
}
/**
@@ -408,8 +388,9 @@ class SubscriptionService
*/
private function calculateProRataRefundItems($invoice, $is_credit = false) :array
{
- if(!$invoice)
+ if (!$invoice) {
return [];
+ }
$handle_discount = false;
@@ -430,32 +411,28 @@ class SubscriptionService
//Handle when we are refunding a discounted invoice. Need to consider the
//total discount and also the line item discount.
- if($invoice->discount > 0)
+ if ($invoice->discount > 0) {
$handle_discount = true;
+ }
- foreach($invoice->line_items as $item)
- {
-
- if($item->product_key != ctrans('texts.refund') && ($item->type_id == "1" || $item->type_id == "2"))
- {
-
+ foreach ($invoice->line_items as $item) {
+ if ($item->product_key != ctrans('texts.refund') && ($item->type_id == "1" || $item->type_id == "2")) {
$discount_ratio = 1;
- if($handle_discount)
+ if ($handle_discount) {
$discount_ratio = $this->calculateDiscountRatio($invoice);
+ }
$item->cost = ($item->cost*$ratio*$multiplier*$discount_ratio);
$item->product_key = ctrans('texts.refund');
$item->notes = ctrans('texts.refund') . ": ". $item->notes;
$line_items[] = $item;
-
}
}
return $line_items;
-
}
@@ -467,12 +444,11 @@ class SubscriptionService
*/
public function calculateDiscountRatio($invoice) : float
{
-
- if($invoice->is_amount_discount)
+ if ($invoice->is_amount_discount) {
return $invoice->discount / ($invoice->amount + $invoice->discount);
- else
+ } else {
return $invoice->discount / 100;
-
+ }
}
/**
@@ -483,7 +459,6 @@ class SubscriptionService
*/
private function calculateProRataCharge($invoice) :float
{
-
$start_date = Carbon::parse($invoice->date);
$current_date = now();
@@ -494,7 +469,7 @@ class SubscriptionService
nlog("days to charge = {$days_to_charge} days in frequency = {$days_in_frequency}");
- $pro_rata_charge = round(($days_to_charge/$days_in_frequency) * $invoice->amount ,2);
+ $pro_rata_charge = round(($days_to_charge/$days_in_frequency) * $invoice->amount, 2);
nlog("pro rata charge = {$pro_rata_charge}");
@@ -504,10 +479,10 @@ class SubscriptionService
/**
* This entry point assumes the user does not have to make a
* payment for the service.
- *
+ *
* In this case, we generate a credit note for the old service
* Generate a new invoice for the new service
- * Apply credits to the invoice
+ * Apply credits to the invoice
*
* @param array $data
*/
@@ -526,7 +501,7 @@ class SubscriptionService
/* Get last invoice */
$last_invoice = Invoice::where('subscription_id', $recurring_invoice->subscription_id)
->where('client_id', $recurring_invoice->client_id)
- ->where('is_proforma',0)
+ ->where('is_proforma', 0)
->where('is_deleted', 0)
->whereIn('status_id', [Invoice::STATUS_SENT, Invoice::STATUS_PARTIAL, Invoice::STATUS_PAID])
->withTrashed()
@@ -535,18 +510,11 @@ class SubscriptionService
//if last payment was created from a credit, do not generate a new credit, refund the old one.
- if($last_invoice) {
-
-
- $last_invoice->payments->each(function ($payment){
-
- $payment->credits()->where('is_deleted', 0)->each(function ($credit){
-
- $this->credit_payments += $credit->pivot->sum('amount');
-
+ if ($last_invoice) {
+ $last_invoice->payments->each(function ($payment) {
+ $payment->credits()->where('is_deleted', 0)->each(function ($credit) {
+ $this->credit_payments += $credit->pivot->sum('amount');
});
-
-
});
$invoice_repo = new InvoiceRepository();
@@ -555,15 +523,15 @@ class SubscriptionService
$payment_repo = new PaymentRepository(new CreditRepository());
- $last_invoice->payments->each(function ($payment) use ($payment_repo){
- $payment_repo->delete($payment);
- });
-
+ $last_invoice->payments->each(function ($payment) use ($payment_repo) {
+ $payment_repo->delete($payment);
+ });
}
//if there are existing credit payments, then we refund directly to the credit.
- if($this->calculateProRataRefundForSubscription($last_invoice) > 0 && $this->credit_payments == 0)
+ if ($this->calculateProRataRefundForSubscription($last_invoice) > 0 && $this->credit_payments == 0) {
$credit = $this->createCredit($last_invoice, $target_subscription, false);
+ }
$new_recurring_invoice = $this->createNewRecurringInvoice($recurring_invoice);
@@ -580,20 +548,19 @@ class SubscriptionService
$payment->service()->applyNumber()->applyCreditsToInvoice($invoice);
- $context = [
- 'context' => 'change_plan',
- 'recurring_invoice' => $new_recurring_invoice->hashed_id,
- 'credit' => $credit ? $credit->hashed_id : null,
- 'client' => $new_recurring_invoice->client->hashed_id,
- 'subscription' => $target_subscription->hashed_id,
- 'contact' => auth()->guard('contact')->user()->hashed_id,
- 'account_key' => $new_recurring_invoice->client->custom_value2,
- ];
+ $context = [
+ 'context' => 'change_plan',
+ 'recurring_invoice' => $new_recurring_invoice->hashed_id,
+ 'credit' => $credit ? $credit->hashed_id : null,
+ 'client' => $new_recurring_invoice->client->hashed_id,
+ 'subscription' => $target_subscription->hashed_id,
+ 'contact' => auth()->guard('contact')->user()->hashed_id,
+ 'account_key' => $new_recurring_invoice->client->custom_value2,
+ ];
- $response = $this->triggerWebhook($context);
-
- return '/client/recurring_invoices/'.$new_recurring_invoice->hashed_id;
+ $response = $this->triggerWebhook($context);
+ return '/client/recurring_invoices/'.$new_recurring_invoice->hashed_id;
}
/**
@@ -620,11 +587,9 @@ class SubscriptionService
->orderBy('id', 'desc')
->first();
- if($recurring_invoice->invoices()->count() == 0){
+ if ($recurring_invoice->invoices()->count() == 0) {
$pro_rata_refund_amount = 0;
- }
- elseif(!$last_invoice){
-
+ } elseif (!$last_invoice) {
$is_credit = true;
$last_invoice = Credit::where('subscription_id', $recurring_invoice->subscription_id)
@@ -632,19 +597,13 @@ class SubscriptionService
->where('is_deleted', 0)
->withTrashed()
->orderBy('id', 'desc')
- ->first();
+ ->first();
$pro_rata_refund_amount = $this->calculateProRataRefund($last_invoice, $old_subscription);
-
- }
-
- elseif($last_invoice->balance > 0)
- {
+ } elseif ($last_invoice->balance > 0) {
$pro_rata_charge_amount = $this->calculateProRataCharge($last_invoice, $old_subscription);
nlog("pro rata charge = {$pro_rata_charge_amount}");
- }
- else
- {
+ } else {
$pro_rata_refund_amount = $this->calculateProRataRefund($last_invoice, $old_subscription) * -1;
nlog("pro rata refund = {$pro_rata_refund_amount}");
}
@@ -656,39 +615,37 @@ class SubscriptionService
$credit = false;
/* Only generate a credit if the previous invoice was paid in full. */
- if($last_invoice && $last_invoice->balance == 0)
+ if ($last_invoice && $last_invoice->balance == 0) {
$credit = $this->createCredit($last_invoice, $target_subscription, $is_credit);
+ }
$new_recurring_invoice = $this->createNewRecurringInvoice($recurring_invoice);
- $context = [
- 'context' => 'change_plan',
- 'recurring_invoice' => $new_recurring_invoice->hashed_id,
- 'credit' => $credit ? $credit->hashed_id : null,
- 'client' => $new_recurring_invoice->client->hashed_id,
- 'subscription' => $target_subscription->hashed_id,
- 'contact' => auth()->guard('contact')->user()->hashed_id,
- 'account_key' => $new_recurring_invoice->client->custom_value2,
- ];
+ $context = [
+ 'context' => 'change_plan',
+ 'recurring_invoice' => $new_recurring_invoice->hashed_id,
+ 'credit' => $credit ? $credit->hashed_id : null,
+ 'client' => $new_recurring_invoice->client->hashed_id,
+ 'subscription' => $target_subscription->hashed_id,
+ 'contact' => auth()->guard('contact')->user()->hashed_id,
+ 'account_key' => $new_recurring_invoice->client->custom_value2,
+ ];
- $response = $this->triggerWebhook($context);
+ $response = $this->triggerWebhook($context);
- nlog($response);
-
- if($credit){
- // return $this->handleRedirect('/client/credits/'.$credit->hashed_id);
- return '/client/credits/'.$credit->hashed_id;
- }
- else{
- // return $this->handleRedirect('/client/credits');
- return '/client/credits';
- }
+ nlog($response);
+ if ($credit) {
+ // return $this->handleRedirect('/client/credits/'.$credit->hashed_id);
+ return '/client/credits/'.$credit->hashed_id;
+ } else {
+ // return $this->handleRedirect('/client/credits');
+ return '/client/credits';
+ }
}
public function changePlanPaymentCheck($data)
{
-
$recurring_invoice = $data['recurring_invoice'];
$old_subscription = $data['subscription'];
$target_subscription = $data['target'];
@@ -698,22 +655,19 @@ class SubscriptionService
$last_invoice = Invoice::where('subscription_id', $recurring_invoice->subscription_id)
->where('client_id', $recurring_invoice->client_id)
- ->where('is_proforma',0)
+ ->where('is_proforma', 0)
->where('is_deleted', 0)
->withTrashed()
->orderBy('id', 'desc')
->first();
- if(!$last_invoice)
+ if (!$last_invoice) {
return true;
+ }
- if($last_invoice->balance > 0)
- {
+ if ($last_invoice->balance > 0) {
$pro_rata_charge_amount = $this->calculateProRataCharge($last_invoice, $old_subscription);
nlog("pro rata charge = {$pro_rata_charge_amount}");
-
- }
- else
- {
+ } else {
$pro_rata_refund_amount = $this->calculateProRataRefund($last_invoice, $old_subscription) * -1;
nlog("pro rata refund = {$pro_rata_refund_amount}");
}
@@ -722,11 +676,11 @@ class SubscriptionService
$total_payable = $pro_rata_refund_amount + $pro_rata_charge_amount + $this->subscription->price;
- if($total_payable > 0)
+ if ($total_payable > 0) {
return true;
+ }
return false;
-
}
/**
@@ -737,7 +691,6 @@ class SubscriptionService
*/
public function createChangePlanInvoice($data)
{
-
$recurring_invoice = $data['recurring_invoice'];
$old_subscription = $data['subscription'];
$target_subscription = $data['target'];
@@ -748,22 +701,18 @@ class SubscriptionService
$last_invoice = Invoice::where('subscription_id', $recurring_invoice->subscription_id)
->where('client_id', $recurring_invoice->client_id)
->where('is_deleted', 0)
- ->where('is_proforma',0)
+ ->where('is_proforma', 0)
->withTrashed()
->orderBy('id', 'desc')
->first();
- if(!$last_invoice){
+ if (!$last_invoice) {
//do nothing
- }
- else if($last_invoice->balance > 0)
- {
+ } elseif ($last_invoice->balance > 0) {
$last_invoice = null;
- // $pro_rata_charge_amount = $this->calculateProRataCharge($last_invoice, $old_subscription);
- // nlog("pro rata charge = {$pro_rata_charge_amount}");
- }
- else
- {
+ // $pro_rata_charge_amount = $this->calculateProRataCharge($last_invoice, $old_subscription);
+ // nlog("pro rata charge = {$pro_rata_charge_amount}");
+ } else {
$pro_rata_refund_amount = $this->calculateProRataRefund($last_invoice, $old_subscription) * -1;
nlog("pro rata refund = {$pro_rata_refund_amount}");
}
@@ -771,7 +720,6 @@ class SubscriptionService
$total_payable = $pro_rata_refund_amount + $pro_rata_charge_amount + $this->subscription->price;
return $this->proRataInvoice($last_invoice, $target_subscription, $recurring_invoice->client_id);
-
}
/**
@@ -786,8 +734,9 @@ class SubscriptionService
$old_recurring_invoice = RecurringInvoice::find($this->decodePrimaryKey($payment_hash->data->billing_context->recurring_invoice));
- if(!$old_recurring_invoice)
+ if (!$old_recurring_invoice) {
return $this->handleRedirect('/client/recurring_invoices/');
+ }
$recurring_invoice = $this->createNewRecurringInvoice($old_recurring_invoice);
@@ -813,7 +762,6 @@ class SubscriptionService
nlog($response);
return $this->handleRedirect('/client/recurring_invoices/'.$recurring_invoice->hashed_id);
-
}
/**
@@ -825,26 +773,24 @@ class SubscriptionService
*/
public function createNewRecurringInvoice($old_recurring_invoice) :RecurringInvoice
{
-
$old_recurring_invoice->service()->stop()->save();
$recurring_invoice_repo = new RecurringInvoiceRepository();
$recurring_invoice_repo->delete($old_recurring_invoice);
- $recurring_invoice = $this->convertInvoiceToRecurring($old_recurring_invoice->client_id);
- $recurring_invoice = $recurring_invoice_repo->save([], $recurring_invoice);
- $recurring_invoice->next_send_date = now()->format('Y-m-d');
- $recurring_invoice->next_send_date_client = now()->format('Y-m-d');
- $recurring_invoice->next_send_date = $recurring_invoice->nextSendDate();
- $recurring_invoice->next_send_date_client = $recurring_invoice->nextSendDateClient();
+ $recurring_invoice = $this->convertInvoiceToRecurring($old_recurring_invoice->client_id);
+ $recurring_invoice = $recurring_invoice_repo->save([], $recurring_invoice);
+ $recurring_invoice->next_send_date = now()->format('Y-m-d');
+ $recurring_invoice->next_send_date_client = now()->format('Y-m-d');
+ $recurring_invoice->next_send_date = $recurring_invoice->nextSendDate();
+ $recurring_invoice->next_send_date_client = $recurring_invoice->nextSendDateClient();
- /* Start the recurring service */
- $recurring_invoice->service()
- ->start()
- ->save();
-
- return $recurring_invoice;
+ /* Start the recurring service */
+ $recurring_invoice->service()
+ ->start()
+ ->save();
+ return $recurring_invoice;
}
/**
@@ -856,7 +802,6 @@ class SubscriptionService
*/
private function createCredit($last_invoice, $target, $is_credit = false)
{
-
$last_invoice_is_credit = $is_credit ? false : true;
$subscription_repo = new SubscriptionRepository();
@@ -877,7 +822,6 @@ class SubscriptionService
];
return $credit_repo->save($data, $credit)->service()->markSent()->fillDefaults()->save();
-
}
/**
@@ -911,7 +855,6 @@ class SubscriptionService
->markSent()
->fillDefaults()
->save();
-
}
/**
@@ -944,13 +887,11 @@ class SubscriptionService
->markSent()
->fillDefaults()
->save();
-
}
public function createInvoiceV2($bundle, $client_id, $valid_coupon = false)
{
-
$invoice_repo = new InvoiceRepository();
$subscription_repo = new SubscriptionRepository();
@@ -958,9 +899,8 @@ class SubscriptionService
$invoice->subscription_id = $this->subscription->id;
$invoice->client_id = $client_id;
$invoice->is_proforma = true;
- $invoice->number = "####" . ctrans('texts.subscription') . "_" . now()->format('Y-m-d') . "_" . rand(0,100000);
- $line_items = $bundle->map(function ($item){
-
+ $invoice->number = "####" . ctrans('texts.subscription') . "_" . now()->format('Y-m-d') . "_" . rand(0, 100000);
+ $line_items = $bundle->map(function ($item) {
$line_item = new InvoiceItem;
$line_item->product_key = $item['product_key'];
$line_item->quantity = (float)$item['qty'];
@@ -968,18 +908,16 @@ class SubscriptionService
$line_item->notes = $item['description'];
return $line_item;
-
})->toArray();
$invoice->line_items = $line_items;
- if($valid_coupon){
+ if ($valid_coupon) {
$invoice->discount = $this->subscription->promo_discount;
$invoice->is_amount_discount = $this->subscription->is_amount_discount;
}
return $invoice_repo->save([], $invoice);
-
}
/**
@@ -990,7 +928,6 @@ class SubscriptionService
*/
public function createInvoice($data, $quantity = 1): ?\App\Models\Invoice
{
-
$invoice_repo = new InvoiceRepository();
$subscription_repo = new SubscriptionRepository();
$subscription_repo->quantity = $quantity;
@@ -1000,18 +937,15 @@ class SubscriptionService
$invoice->subscription_id = $this->subscription->id;
$invoice->is_proforma = true;
- if(strlen($data['coupon']) >=1 && ($data['coupon'] == $this->subscription->promo_code) && $this->subscription->promo_discount > 0)
- {
+ if (strlen($data['coupon']) >=1 && ($data['coupon'] == $this->subscription->promo_code) && $this->subscription->promo_discount > 0) {
$invoice->discount = $this->subscription->promo_discount;
$invoice->is_amount_discount = $this->subscription->is_amount_discount;
- }
- elseif(strlen($this->subscription->promo_code) == 0 && $this->subscription->promo_discount > 0) {
+ } elseif (strlen($this->subscription->promo_code) == 0 && $this->subscription->promo_discount > 0) {
$invoice->discount = $this->subscription->promo_discount;
$invoice->is_amount_discount = $this->subscription->is_amount_discount;
}
return $invoice_repo->save($data, $invoice);
-
}
/**
@@ -1088,7 +1022,6 @@ class SubscriptionService
}
return false;
-
}
/**
@@ -1098,7 +1031,6 @@ class SubscriptionService
*/
public function triggerWebhook($context)
{
-
if (empty($this->subscription->webhook_configuration['post_purchase_url']) || is_null($this->subscription->webhook_configuration['post_purchase_url']) || strlen($this->subscription->webhook_configuration['post_purchase_url']) < 1) {
return ["message" => "Success", "status_code" => 200];
}
@@ -1112,35 +1044,30 @@ class SubscriptionService
$response = $this->sendLoad($this->subscription, $body);
/* Append the response to the system logger body */
- if(is_array($response)){
-
+ if (is_array($response)) {
$body = $response;
-
- }
- else {
-
+ } else {
$body = $response->getStatusCode();
-
}
$client = Client::where('id', $this->decodePrimaryKey($body['client']))->withTrashed()->first();
- SystemLogger::dispatch(
- $body,
- SystemLog::CATEGORY_WEBHOOK,
- SystemLog::EVENT_WEBHOOK_RESPONSE,
- SystemLog::TYPE_WEBHOOK_RESPONSE,
- $client,
- $client->company,
- );
+ SystemLogger::dispatch(
+ $body,
+ SystemLog::CATEGORY_WEBHOOK,
+ SystemLog::EVENT_WEBHOOK_RESPONSE,
+ SystemLog::TYPE_WEBHOOK_RESPONSE,
+ $client,
+ $client->company,
+ );
nlog("ready to fire back");
- if(is_array($body))
- return $response;
- else
- return ['message' => 'There was a problem encountered with the webhook', 'status_code' => 500];
-
+ if (is_array($body)) {
+ return $response;
+ } else {
+ return ['message' => 'There was a problem encountered with the webhook', 'status_code' => 500];
+ }
}
public function fireNotifications()
@@ -1155,15 +1082,17 @@ class SubscriptionService
*/
public function products()
{
- if(!$this->subscription->product_ids)
+ if (!$this->subscription->product_ids) {
return collect();
+ }
$keys = $this->transformKeys(explode(",", $this->subscription->product_ids));
- if(is_array($keys))
+ if (is_array($keys)) {
return Product::whereIn('id', $keys)->get();
- else
+ } else {
return Product::where('id', $keys)->get();
+ }
}
/**
@@ -1173,18 +1102,17 @@ class SubscriptionService
*/
public function recurring_products()
{
- if(!$this->subscription->recurring_product_ids)
+ if (!$this->subscription->recurring_product_ids) {
return collect();
+ }
$keys = $this->transformKeys(explode(",", $this->subscription->recurring_product_ids));
- if(is_array($keys)){
+ if (is_array($keys)) {
return Product::whereIn('id', $keys)->get();
- }
- else{
+ } else {
return Product::where('id', $keys)->get();
}
-
}
/* OPTIONAL PRODUCTS*/
@@ -1195,15 +1123,17 @@ class SubscriptionService
*/
public function optional_products()
{
- if(!$this->subscription->optional_product_ids)
+ if (!$this->subscription->optional_product_ids) {
return collect();
+ }
$keys = $this->transformKeys(explode(",", $this->subscription->optional_product_ids));
- if(is_array($keys))
+ if (is_array($keys)) {
return Product::whereIn('id', $keys)->get();
- else
+ } else {
return Product::where('id', $keys)->get();
+ }
}
/**
@@ -1213,18 +1143,17 @@ class SubscriptionService
*/
public function optional_recurring_products()
{
- if(!$this->subscription->optional_recurring_product_ids)
+ if (!$this->subscription->optional_recurring_product_ids) {
return collect();
+ }
$keys = $this->transformKeys(explode(",", $this->subscription->optional_recurring_product_ids));
- if(is_array($keys)){
+ if (is_array($keys)) {
return Product::whereIn('id', $keys)->get();
- }
- else{
+ } else {
return Product::where('id', $keys)->get();
}
-
}
@@ -1265,13 +1194,12 @@ class SubscriptionService
->where('client_id', $recurring_invoice->client_id)
->where('status_id', Invoice::STATUS_PAID)
->where('is_deleted', 0)
- ->where('is_proforma',0)
- ->where('balance',0)
+ ->where('is_proforma', 0)
+ ->where('balance', 0)
->orderBy('id', 'desc')
->first();
- if($outstanding_invoice)
- {
+ if ($outstanding_invoice) {
$invoice_start_date = Carbon::parse($outstanding_invoice->date);
$refund_end_date = $invoice_start_date->addSeconds($this->subscription->refund_period);
}
@@ -1282,11 +1210,8 @@ class SubscriptionService
$recurring_invoice_repo->archive($recurring_invoice);
/* Refund only if we are in the window - and there is nothing outstanding on the invoice */
- if($refund_end_date && $refund_end_date->greaterThan(now()))
- {
-
- if($outstanding_invoice->payments()->exists())
- {
+ if ($refund_end_date && $refund_end_date->greaterThan(now())) {
+ if ($outstanding_invoice->payments()->exists()) {
$payment = $outstanding_invoice->payments()->first();
$data = [
@@ -1305,50 +1230,44 @@ class SubscriptionService
}
}
- $context = [
- 'context' => 'cancellation',
- 'subscription' => $this->subscription->hashed_id,
- 'recurring_invoice' => $recurring_invoice->hashed_id,
- 'client' => $recurring_invoice->client->hashed_id,
- 'contact' => auth()->guard('contact')->user()->hashed_id,
- 'account_key' => $recurring_invoice->client->custom_value2,
- ];
+ $context = [
+ 'context' => 'cancellation',
+ 'subscription' => $this->subscription->hashed_id,
+ 'recurring_invoice' => $recurring_invoice->hashed_id,
+ 'client' => $recurring_invoice->client->hashed_id,
+ 'contact' => auth()->guard('contact')->user()->hashed_id,
+ 'account_key' => $recurring_invoice->client->custom_value2,
+ ];
- $this->triggerWebhook($context);
+ $this->triggerWebhook($context);
- $nmo = new NinjaMailerObject;
- $nmo->mailable = (new NinjaMailer((new ClientContactRequestCancellationObject($recurring_invoice, auth()->guard('contact')->user(), $gateway_refund_attempted))->build()));
- $nmo->company = $recurring_invoice->company;
- $nmo->settings = $recurring_invoice->company->settings;
+ $nmo = new NinjaMailerObject;
+ $nmo->mailable = (new NinjaMailer((new ClientContactRequestCancellationObject($recurring_invoice, auth()->guard('contact')->user(), $gateway_refund_attempted))->build()));
+ $nmo->company = $recurring_invoice->company;
+ $nmo->settings = $recurring_invoice->company->settings;
- $recurring_invoice->company->company_users->each(function ($company_user) use ($nmo){
+ $recurring_invoice->company->company_users->each(function ($company_user) use ($nmo) {
+ $methods = $this->findCompanyUserNotificationType($company_user, ['recurring_cancellation', 'all_notifications']);
- $methods = $this->findCompanyUserNotificationType($company_user, ['recurring_cancellation', 'all_notifications']);
+ //if mail is a method type -fire mail!!
+ if (($key = array_search('mail', $methods)) !== false) {
+ unset($methods[$key]);
- //if mail is a method type -fire mail!!
- if (($key = array_search('mail', $methods)) !== false) {
- unset($methods[$key]);
-
- $nmo->to_user = $company_user->user;
- NinjaMailerJob::dispatch($nmo);
-
- }
-
-
- });
-
- return $this->handleRedirect('client/subscriptions');
+ $nmo->to_user = $company_user->user;
+ NinjaMailerJob::dispatch($nmo);
+ }
+ });
+ return $this->handleRedirect('client/subscriptions');
}
/**
* Get the number of days in the currency frequency
- *
+ *
* @return int Number of days
*/
private function getDaysInFrequency() :int
{
-
switch ($this->subscription->frequency_id) {
case RecurringInvoice::FREQUENCY_DAILY:
return 1;
@@ -1377,15 +1296,14 @@ class SubscriptionService
default:
return 0;
}
-
}
/**
* Get the next date by frequency_id
- *
+ *
* @param Carbon $date The current carbon date
* @param int $frequency The frequncy_id of the subscription
- *
+ *
* @return ?Carbon The next date carbon object
*/
public function getNextDateForFrequency($date, $frequency) :?Carbon
@@ -1417,7 +1335,7 @@ class SubscriptionService
return $date->addYears(3);
default:
return null;
- }
+ }
}
@@ -1426,15 +1344,15 @@ class SubscriptionService
* @param Invoice $invoice The Invoice
* @param array $bundle The bundle array
* @param ClientContact $contact The Client Contact
- *
+ *
* @return \Illuminate\Routing\Redirector|\Illuminate\Http\RedirectResponse
*/
public function handleNoPaymentFlow(Invoice $invoice, $bundle, ClientContact $contact)
{
-
if (strlen($this->subscription->recurring_product_ids) >= 1) {
-
- $recurring_invoice = $this->convertInvoiceToRecurringBundle($contact->client_id, collect($bundle)->map(function ($bund){ return (object) $bund;}));
+ $recurring_invoice = $this->convertInvoiceToRecurringBundle($contact->client_id, collect($bundle)->map(function ($bund) {
+ return (object) $bund;
+ }));
/* Start the recurring service */
$recurring_invoice->service()
@@ -1457,13 +1375,11 @@ class SubscriptionService
$this->triggerWebhook($context);
return $this->handleRedirect($context['redirect_url']);
-
}
$redirect_url = "/client/invoices/{$invoice->hashed_id}";
return $this->handleRedirect($redirect_url);
-
}
/**
@@ -1473,16 +1389,15 @@ class SubscriptionService
*/
public function handleNoPaymentRequired(array $data)
{
-
$context = (new ZeroCostProduct($this->subscription, $data))->run();
// Forward payload to webhook
- if(array_key_exists('context', $context))
+ if (array_key_exists('context', $context)) {
$response = $this->triggerWebhook($context);
+ }
// Hit the redirect
return $this->handleRedirect($context['redirect_url']);
-
}
/**
@@ -1490,31 +1405,31 @@ class SubscriptionService
*/
private function handleRedirect($default_redirect)
{
-
- if(array_key_exists('return_url', $this->subscription->webhook_configuration) && strlen($this->subscription->webhook_configuration['return_url']) >=1)
+ if (array_key_exists('return_url', $this->subscription->webhook_configuration) && strlen($this->subscription->webhook_configuration['return_url']) >=1) {
return redirect($this->subscription->webhook_configuration['return_url']);
+ }
return redirect($default_redirect);
}
/**
- * @param Invoice $invoice
- * @return true
- * @throws BindingResolutionException
+ * @param Invoice $invoice
+ * @return true
+ * @throws BindingResolutionException
*/
public function planPaid(Invoice $invoice)
{
$recurring_invoice_hashed_id = $invoice->recurring_invoice()->exists() ? $invoice->recurring_invoice->hashed_id : null;
- $context = [
- 'context' => 'plan_paid',
- 'subscription' => $this->subscription->hashed_id,
- 'recurring_invoice' => $recurring_invoice_hashed_id,
- 'client' => $invoice->client->hashed_id,
- 'contact' => $invoice->client->primary_contact()->first() ? $invoice->client->primary_contact()->first()->hashed_id: $invoice->client->contacts->first()->hashed_id,
- 'invoice' => $invoice->hashed_id,
- 'account_key' => $invoice->client->custom_value2,
- ];
+ $context = [
+ 'context' => 'plan_paid',
+ 'subscription' => $this->subscription->hashed_id,
+ 'recurring_invoice' => $recurring_invoice_hashed_id,
+ 'client' => $invoice->client->hashed_id,
+ 'contact' => $invoice->client->primary_contact()->first() ? $invoice->client->primary_contact()->first()->hashed_id: $invoice->client->contacts->first()->hashed_id,
+ 'invoice' => $invoice->hashed_id,
+ 'account_key' => $invoice->client->custom_value2,
+ ];
$response = $this->triggerWebhook($context);
diff --git a/app/Services/TaskScheduler/TaskSchedulerService.php b/app/Services/TaskScheduler/TaskSchedulerService.php
index 8bdf5f57b938..b5533ca8d2ee 100644
--- a/app/Services/TaskScheduler/TaskSchedulerService.php
+++ b/app/Services/TaskScheduler/TaskSchedulerService.php
@@ -25,25 +25,20 @@ use App\Export\CSV\QuoteItemExport;
use App\Export\CSV\RecurringInvoiceExport;
use App\Export\CSV\TaskExport;
use App\Http\Requests\Report\GenericReportRequest;
-use App\Http\Requests\Report\ProfitLossRequest;
use App\Http\Requests\TaskScheduler\CreateScheduledTaskRequest;
use App\Http\Requests\TaskScheduler\UpdateScheduledJobRequest;
use App\Http\Requests\TaskScheduler\UpdateScheduleRequest;
use App\Jobs\Report\ProfitAndLoss;
-use App\Models\Company;
use App\Models\Scheduler;
-use App\Utils\Ninja;
use Carbon\Carbon;
-use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Validator;
-use Symfony\Component\HttpFoundation\Request;
-
//@deprecated - never used....
class TaskSchedulerService
{
-
- public function __construct(public Scheduler $scheduler) {}
+ public function __construct(public Scheduler $scheduler)
+ {
+ }
public function store(Scheduler $scheduler, CreateScheduledTaskRequest $request)
{
@@ -152,7 +147,6 @@ class TaskSchedulerService
$scheduler->action_class = $this->getClassPath(TaskExport::class);
$scheduler->parameters = $this->runValidation(GenericReportRequest::class, $request->all());
break;
-
}
return $scheduler;
diff --git a/app/Services/User/UserService.php b/app/Services/User/UserService.php
index 326348d1cdfb..c6be461916de 100644
--- a/app/Services/User/UserService.php
+++ b/app/Services/User/UserService.php
@@ -15,7 +15,6 @@ use App\Jobs\Mail\NinjaMailer;
use App\Jobs\Mail\NinjaMailerJob;
use App\Jobs\Mail\NinjaMailerObject;
use App\Mail\Admin\VerifyUserObject;
-use App\Models\Company;
use App\Models\User;
use App\Utils\Ninja;
diff --git a/app/Transformers/AccountTransformer.php b/app/Transformers/AccountTransformer.php
index 638fb3a66542..032324a0a23e 100644
--- a/app/Transformers/AccountTransformer.php
+++ b/app/Transformers/AccountTransformer.php
@@ -112,6 +112,5 @@ class AccountTransformer extends EntityTransformer
$transformer = new UserTransformer($this->serializer);
return $this->includeItem(auth()->user(), $transformer, User::class);
-
}
}
diff --git a/app/Transformers/ActivityTransformer.php b/app/Transformers/ActivityTransformer.php
index 3b467aa0a639..9bcf5b66dd63 100644
--- a/app/Transformers/ActivityTransformer.php
+++ b/app/Transformers/ActivityTransformer.php
@@ -20,9 +20,6 @@ use App\Models\Task;
use App\Models\User;
use App\Models\Vendor;
use App\Models\VendorContact;
-use App\Transformers\PurchaseOrderTransformer;
-use App\Transformers\VendorContactTransformer;
-use App\Transformers\VendorTransformer;
use App\Utils\Traits\MakesHash;
class ActivityTransformer extends EntityTransformer
diff --git a/app/Transformers/BankIntegrationTransformer.php b/app/Transformers/BankIntegrationTransformer.php
index ad5275107330..b5eeb0ebea3c 100644
--- a/app/Transformers/BankIntegrationTransformer.php
+++ b/app/Transformers/BankIntegrationTransformer.php
@@ -88,5 +88,4 @@ class BankIntegrationTransformer extends EntityTransformer
return $this->includeCollection($bank_integration->transactions, $transformer, BankTransaction::class);
}
-
}
diff --git a/app/Transformers/BankTransactionRuleTransformer.php b/app/Transformers/BankTransactionRuleTransformer.php
index ca5628abb32b..588a802b492e 100644
--- a/app/Transformers/BankTransactionRuleTransformer.php
+++ b/app/Transformers/BankTransactionRuleTransformer.php
@@ -17,9 +17,6 @@ use App\Models\Client;
use App\Models\Company;
use App\Models\ExpenseCategory;
use App\Models\Vendor;
-use App\Transformers\ExpenseCategoryTransformer;
-use App\Transformers\ExpenseCateogryTransformer;
-use App\Transformers\VendorTransformer;
use App\Utils\Traits\MakesHash;
/**
@@ -77,9 +74,9 @@ class BankTransactionRuleTransformer extends EntityTransformer
public function includeClient(BankTransactionRule $bank_transaction_rule)
{
-
- if(!$bank_transaction_rule->client)
+ if (!$bank_transaction_rule->client) {
return null;
+ }
$transformer = new ClientTransformer($this->serializer);
@@ -88,9 +85,9 @@ class BankTransactionRuleTransformer extends EntityTransformer
public function includeVendor(BankTransactionRule $bank_transaction_rule)
{
-
- if(!$bank_transaction_rule->vendor)
+ if (!$bank_transaction_rule->vendor) {
return null;
+ }
$transformer = new VendorTransformer($this->serializer);
@@ -99,13 +96,12 @@ class BankTransactionRuleTransformer extends EntityTransformer
public function includeExpenseCategory(BankTransactionRule $bank_transaction_rule)
{
-
- if(!$bank_transaction_rule->expense_category)
+ if (!$bank_transaction_rule->expense_category) {
return null;
+ }
$transformer = new ExpenseCategoryTransformer($this->serializer);
return $this->includeItem($bank_transaction_rule->expense_category, $transformer, ExpenseCategory::class);
}
-
}
diff --git a/app/Transformers/BankTransactionTransformer.php b/app/Transformers/BankTransactionTransformer.php
index 3aa95d6bcceb..b99aac92a702 100644
--- a/app/Transformers/BankTransactionTransformer.php
+++ b/app/Transformers/BankTransactionTransformer.php
@@ -15,8 +15,6 @@ use App\Models\Account;
use App\Models\BankTransaction;
use App\Models\Company;
use App\Models\Expense;
-use App\Models\Invoice;
-use App\Transformers\VendorTransformer;
use App\Utils\Traits\MakesHash;
/**
@@ -111,5 +109,4 @@ class BankTransactionTransformer extends EntityTransformer
return $this->includeItem($bank_transaction->payment, $transformer, Payment::class);
}
-
}
diff --git a/app/Transformers/CompanyGatewayTransformer.php b/app/Transformers/CompanyGatewayTransformer.php
index 6ac1aed2aeab..d1f214086512 100644
--- a/app/Transformers/CompanyGatewayTransformer.php
+++ b/app/Transformers/CompanyGatewayTransformer.php
@@ -13,7 +13,6 @@ namespace App\Transformers;
use App\Models\CompanyGateway;
use App\Models\SystemLog;
-use App\Transformers\SystemLogTransformer;
use App\Utils\Traits\MakesHash;
use Illuminate\Database\Eloquent\SoftDeletes;
use stdClass;
diff --git a/app/Transformers/CompanyTransformer.php b/app/Transformers/CompanyTransformer.php
index fee6318ce638..a167c6812fd7 100644
--- a/app/Transformers/CompanyTransformer.php
+++ b/app/Transformers/CompanyTransformer.php
@@ -43,11 +43,6 @@ use App\Models\TaskStatus;
use App\Models\TaxRate;
use App\Models\User;
use App\Models\Webhook;
-use App\Transformers\BankIntegrationTransformer;
-use App\Transformers\BankTransactionRuleTransformer;
-use App\Transformers\BankTransactionTransformer;
-use App\Transformers\PurchaseOrderTransformer;
-use App\Transformers\RecurringExpenseTransformer;
use App\Utils\Traits\MakesHash;
use stdClass;
diff --git a/app/Transformers/CreditTransformer.php b/app/Transformers/CreditTransformer.php
index 7050003bfd98..4846b56a336e 100644
--- a/app/Transformers/CreditTransformer.php
+++ b/app/Transformers/CreditTransformer.php
@@ -16,7 +16,6 @@ use App\Models\Backup;
use App\Models\Credit;
use App\Models\CreditInvitation;
use App\Models\Document;
-use App\Transformers\ActivityTransformer;
use App\Utils\Traits\MakesHash;
use League\Fractal\Resource\Item;
diff --git a/app/Transformers/GroupSettingTransformer.php b/app/Transformers/GroupSettingTransformer.php
index 5bea9f734d74..3a7695ccee8a 100644
--- a/app/Transformers/GroupSettingTransformer.php
+++ b/app/Transformers/GroupSettingTransformer.php
@@ -13,7 +13,6 @@ namespace App\Transformers;
use App\Models\Document;
use App\Models\GroupSetting;
-use App\Transformers\DocumentTransformer;
use App\Utils\Traits\MakesHash;
use stdClass;
diff --git a/app/Transformers/InvoiceTransformer.php b/app/Transformers/InvoiceTransformer.php
index 7da68ad9aa64..a35e1d4c2082 100644
--- a/app/Transformers/InvoiceTransformer.php
+++ b/app/Transformers/InvoiceTransformer.php
@@ -18,7 +18,6 @@ use App\Models\Document;
use App\Models\Invoice;
use App\Models\InvoiceInvitation;
use App\Models\Payment;
-use App\Transformers\ActivityTransformer;
use App\Utils\Traits\MakesHash;
class InvoiceTransformer extends EntityTransformer
diff --git a/app/Transformers/PurchaseOrderTransformer.php b/app/Transformers/PurchaseOrderTransformer.php
index 14ad85b57fa7..360e1edcf922 100644
--- a/app/Transformers/PurchaseOrderTransformer.php
+++ b/app/Transformers/PurchaseOrderTransformer.php
@@ -11,11 +11,9 @@
namespace App\Transformers;
-
use App\Models\PurchaseOrder;
use App\Models\PurchaseOrderInvitation;
use App\Models\Vendor;
-use App\Transformers\DocumentTransformer;
use App\Utils\Traits\MakesHash;
class PurchaseOrderTransformer extends EntityTransformer
@@ -135,5 +133,4 @@ class PurchaseOrderTransformer extends EntityTransformer
'currency_id' => $purchase_order->currency_id ? (string) $purchase_order->currency_id : '',
];
}
-
}
diff --git a/app/Transformers/QuoteTransformer.php b/app/Transformers/QuoteTransformer.php
index 60b08c1aa18e..ca2d092057fd 100644
--- a/app/Transformers/QuoteTransformer.php
+++ b/app/Transformers/QuoteTransformer.php
@@ -16,7 +16,6 @@ use App\Models\Backup;
use App\Models\Document;
use App\Models\Quote;
use App\Models\QuoteInvitation;
-use App\Transformers\ActivityTransformer;
use App\Utils\Traits\MakesHash;
use League\Fractal\Resource\Item;
diff --git a/app/Transformers/RecurringInvoiceTransformer.php b/app/Transformers/RecurringInvoiceTransformer.php
index ba3b81ad6d0d..5fcd576d89fe 100644
--- a/app/Transformers/RecurringInvoiceTransformer.php
+++ b/app/Transformers/RecurringInvoiceTransformer.php
@@ -15,12 +15,8 @@ use App\Models\Activity;
use App\Models\Backup;
use App\Models\Client;
use App\Models\Document;
-use App\Models\Invoice;
use App\Models\RecurringInvoice;
use App\Models\RecurringInvoiceInvitation;
-use App\Transformers\ActivityTransformer;
-use App\Transformers\ClientTransformer;
-use App\Transformers\InvoiceHistoryTransformer;
use App\Utils\Traits\MakesHash;
class RecurringInvoiceTransformer extends EntityTransformer
diff --git a/app/Transformers/RecurringQuoteTransformer.php b/app/Transformers/RecurringQuoteTransformer.php
index 8cd884f805d5..905329c2282e 100644
--- a/app/Transformers/RecurringQuoteTransformer.php
+++ b/app/Transformers/RecurringQuoteTransformer.php
@@ -14,11 +14,8 @@ namespace App\Transformers;
use App\Models\Activity;
use App\Models\Backup;
use App\Models\Document;
-use App\Models\Quote;
use App\Models\RecurringQuote;
use App\Models\RecurringQuoteInvitation;
-use App\Transformers\ActivityTransformer;
-use App\Transformers\QuoteHistoryTransformer;
use App\Utils\Traits\MakesHash;
class RecurringQuoteTransformer extends EntityTransformer
diff --git a/app/Transformers/TaskTransformer.php b/app/Transformers/TaskTransformer.php
index 4f18d54fdeb4..71b6d7c3436b 100644
--- a/app/Transformers/TaskTransformer.php
+++ b/app/Transformers/TaskTransformer.php
@@ -14,7 +14,6 @@ namespace App\Transformers;
use App\Models\Document;
use App\Models\Task;
use App\Models\TaskStatus;
-use App\Transformers\TaskStatusTransformer;
use App\Utils\Traits\MakesHash;
use League\Fractal\Resource\Item;
@@ -48,8 +47,9 @@ class TaskTransformer extends EntityTransformer
{
$transformer = new ClientTransformer($this->serializer);
- if(!$task->client)
+ if (!$task->client) {
return null;
+ }
return $this->includeItem($task->client, $transformer, Client::class);
}
@@ -58,8 +58,9 @@ class TaskTransformer extends EntityTransformer
{
$transformer = new TaskStatusTransformer($this->serializer);
- if(!$task->status)
+ if (!$task->status) {
return null;
+ }
return $this->includeItem($task->status, $transformer, TaskStatus::class);
}
diff --git a/app/Utils/Helpers.php b/app/Utils/Helpers.php
index 92b41c6ed83a..5bef865ce085 100644
--- a/app/Utils/Helpers.php
+++ b/app/Utils/Helpers.php
@@ -118,17 +118,15 @@ class Helpers
// 04-10-2022 Return Early if no reserved keywords are present, this is a very expensive process
$string_hit = false;
- foreach ( [':MONTH',':YEAR',':QUARTER',':WEEK'] as $string )
- {
-
- if(stripos($value, $string) !== FALSE) {
- $string_hit = true;
+ foreach ([':MONTH',':YEAR',':QUARTER',':WEEK'] as $string) {
+ if (stripos($value, $string) !== false) {
+ $string_hit = true;
}
-
}
- if(!$string_hit)
+ if (!$string_hit) {
return $value;
+ }
// 04-10-2022 Return Early if no reserved keywords are present, this is a very expensive process
Carbon::setLocale($entity->locale());
@@ -248,7 +246,10 @@ class Helpers
$replacement = sprintf('%s to %s', $_left, $_right);
$value = preg_replace(
- sprintf('/%s/', preg_quote($match)), $replacement, $value, 1
+ sprintf('/%s/', preg_quote($match)),
+ $replacement,
+ $value,
+ 1
);
}
}
@@ -269,7 +270,10 @@ class Helpers
if (! Str::contains($match, ['-', '+', '/', '*'])) {
$value = preg_replace(
- sprintf('/%s/', $matches->keys()->first()), $replacements['literal'][$matches->keys()->first()], $value, 1
+ sprintf('/%s/', $matches->keys()->first()),
+ $replacements['literal'][$matches->keys()->first()],
+ $value,
+ 1
);
}
@@ -312,20 +316,22 @@ class Helpers
$final_date = $currentDateTime->copy()->addMonths($output - $currentDateTime->month);
$output = \sprintf(
- '%s %s',
- $final_date->translatedFormat('F'),
- $final_date->year,
- );
+ '%s %s',
+ $final_date->translatedFormat('F'),
+ $final_date->year,
+ );
}
$value = preg_replace(
- $target, $output, $value, 1
+ $target,
+ $output,
+ $value,
+ 1
);
}
}
return $value;
-
}
/**
diff --git a/app/Utils/HtmlEngine.php b/app/Utils/HtmlEngine.php
index aea963783fa1..f528512f21ab 100644
--- a/app/Utils/HtmlEngine.php
+++ b/app/Utils/HtmlEngine.php
@@ -20,8 +20,6 @@ use App\Models\GatewayType;
use App\Models\InvoiceInvitation;
use App\Models\QuoteInvitation;
use App\Models\RecurringInvoiceInvitation;
-use App\Utils\Ninja;
-use App\Utils\Number;
use App\Utils\Traits\AppSetup;
use App\Utils\Traits\DesignCalculator;
use App\Utils\Traits\MakesDates;
@@ -67,7 +65,7 @@ class HtmlEngine
$this->contact = $invitation->contact->load('client');
- $this->client = $this->contact->client->load('company','country');
+ $this->client = $this->contact->client->load('company', 'country');
$this->entity->load('client');
@@ -187,29 +185,26 @@ class HtmlEngine
$data['$credit.custom3'] = &$data['$invoice.custom3'];
$data['$credit.custom4'] = &$data['$invoice.custom4'];
- if($this->entity->project) {
+ if ($this->entity->project) {
$data['$project.name'] = ['value' => $this->entity->project->name, 'label' => ctrans('texts.project')];
$data['$invoice.project'] = &$data['$project.name'];
}
- if($this->entity->status_id == 4) {
+ if ($this->entity->status_id == 4) {
$data['$status_logo'] = ['value' => ' ' . ctrans('texts.paid') .'
', 'label' => ''];
}
- if($this->entity->vendor) {
+ if ($this->entity->vendor) {
$data['$invoice.vendor'] = ['value' => $this->entity->vendor->present()->name(), 'label' => ctrans('texts.vendor_name')];
}
- if(strlen($this->company->getSetting('qr_iban')) > 5)
- {
- try{
+ if (strlen($this->company->getSetting('qr_iban')) > 5) {
+ try {
$data['$swiss_qr'] = ['value' => (new SwissQrGenerator($this->entity, $this->company))->run(), 'label' => ''];
- }
- catch(\Exception $e){
+ } catch(\Exception $e) {
$data['$swiss_qr'] = ['value' => '', 'label' => ''];
}
}
-
}
if ($this->entity_string == 'quote') {
@@ -246,15 +241,14 @@ class HtmlEngine
$data['$credit.custom3'] = &$data['$quote.custom3'];
$data['$credit.custom4'] = &$data['$quote.custom4'];
- if($this->entity->project) {
+ if ($this->entity->project) {
$data['$project.name'] = ['value' => $this->entity->project->name, 'label' => ctrans('texts.project_name')];
$data['$invoice.project'] = &$data['$project.name'];
}
- if($this->entity->vendor) {
+ if ($this->entity->vendor) {
$data['$invoice.vendor'] = ['value' => $this->entity->vendor->present()->name(), 'label' => ctrans('texts.vendor_name')];
}
-
}
if ($this->entity_string == 'credit') {
@@ -290,7 +284,6 @@ class HtmlEngine
$data['$invoice.custom2'] = &$data['$credit.custom2'];
$data['$invoice.custom3'] = &$data['$credit.custom3'];
$data['$invoice.custom4'] = &$data['$credit.custom4'];
-
}
$data['$portal_url'] = ['value' => $this->invitation->getPortalLink(), 'label' =>''];
@@ -301,10 +294,11 @@ class HtmlEngine
$data['$subtotal'] = ['value' => Number::formatMoney($this->entity_calc->getSubTotal(), $this->client) ?: ' ', 'label' => ctrans('texts.subtotal')];
$data['$gross_subtotal'] = ['value' => Number::formatMoney($this->entity_calc->getGrossSubTotal(), $this->client) ?: ' ', 'label' => ctrans('texts.subtotal')];
- if($this->entity->uses_inclusive_taxes)
+ if ($this->entity->uses_inclusive_taxes) {
$data['$net_subtotal'] = ['value' => Number::formatMoney(($this->entity_calc->getSubTotal() - $this->entity->total_taxes - $this->entity_calc->getTotalDiscount()), $this->client) ?: ' ', 'label' => ctrans('texts.net_subtotal')];
- else
+ } else {
$data['$net_subtotal'] = ['value' => Number::formatMoney($this->entity_calc->getSubTotal() - $this->entity_calc->getTotalDiscount(), $this->client) ?: ' ', 'label' => ctrans('texts.net_subtotal')];
+ }
$data['$invoice.subtotal'] = &$data['$subtotal'];
@@ -314,15 +308,12 @@ class HtmlEngine
$data['$balance_due_raw'] = ['value' => $this->entity->partial, 'label' => ctrans('texts.partial_due')];
$data['$amount_raw'] = ['value' => $this->entity->partial, 'label' => ctrans('texts.partial_due')];
$data['$due_date'] = ['value' => $this->translateDate($this->entity->partial_due_date, $this->client->date_format(), $this->client->locale()) ?: ' ', 'label' => ctrans('texts.'.$this->entity_string.'_due_date')];
-
} else {
-
- if($this->entity->status_id == 1){
+ if ($this->entity->status_id == 1) {
$data['$balance_due'] = ['value' => Number::formatMoney($this->entity->amount, $this->client) ?: ' ', 'label' => ctrans('texts.balance_due')];
$data['$balance_due_raw'] = ['value' => $this->entity->amount, 'label' => ctrans('texts.balance_due')];
$data['$amount_raw'] = ['value' => $this->entity->amount, 'label' => ctrans('texts.amount')];
- }
- else{
+ } else {
$data['$balance_due'] = ['value' => Number::formatMoney($this->entity->balance, $this->client) ?: ' ', 'label' => ctrans('texts.balance_due')];
$data['$balance_due_raw'] = ['value' => $this->entity->balance, 'label' => ctrans('texts.balance_due')];
$data['$amount_raw'] = ['value' => $this->entity->amount, 'label' => ctrans('texts.amount')];
@@ -336,13 +327,13 @@ class HtmlEngine
if ($this->entity_string == 'credit') {
$data['$balance_due'] = ['value' => Number::formatMoney($this->entity->balance, $this->client) ?: ' ', 'label' => ctrans('texts.credit_balance')];
$data['$balance_due_raw'] = ['value' => $this->entity->balance, 'label' => ctrans('texts.credit_balance')];
- $data['$amount_raw'] = ['value' => $this->entity->amount, 'label' => ctrans('texts.amount')];
+ $data['$amount_raw'] = ['value' => $this->entity->amount, 'label' => ctrans('texts.amount')];
}
if ($this->entity_string == 'credit' && $this->entity->status_id == 1) {
$data['$balance_due'] = ['value' => Number::formatMoney($this->entity->amount, $this->client) ?: ' ', 'label' => ctrans('texts.credit_balance')];
$data['$balance_due_raw'] = ['value' => $this->entity->amount, 'label' => ctrans('texts.credit_balance')];
- $data['$amount_raw'] = ['value' => $this->entity->amount, 'label' => ctrans('texts.amount')];
+ $data['$amount_raw'] = ['value' => $this->entity->amount, 'label' => ctrans('texts.amount')];
}
/* Do not change the order of these */
@@ -425,8 +416,9 @@ class HtmlEngine
$data['$country_2'] = ['value' => isset($this->client->country) ? $this->client->country->iso_3166_2 : '', 'label' => ctrans('texts.country')];
$data['$email'] = ['value' => isset($this->contact) ? $this->contact->email : 'no contact email on record', 'label' => ctrans('texts.email')];
- if(str_contains($data['$email']['value'], 'example.com'))
+ if (str_contains($data['$email']['value'], 'example.com')) {
$data['$email'] = ['value' => '', 'label' => ctrans('texts.email')];
+ }
$data['$client_name'] = ['value' => $this->entity->present()->clientName() ?: ' ', 'label' => ctrans('texts.client_name')];
$data['$client.name'] = &$data['$client_name'];
@@ -642,7 +634,6 @@ class HtmlEngine
$data['$payments'] = ['value' => '', 'label' => ctrans('texts.payments')];
if ($this->entity_string == 'invoice' && $this->entity->payments()->exists()) {
-
$payment_list = '
';
foreach ($this->entity->payments as $payment) {
@@ -652,9 +643,8 @@ class HtmlEngine
$data['$payments'] = ['value' => $payment_list, 'label' => ctrans('texts.payments')];
}
- if(($this->entity_string == 'invoice' || $this->entity_string == 'recurring_invoice') && isset($this->company?->custom_fields?->company1))
- {
- $data['$sepa_qr_code'] = ['value' => (new EpcQrGenerator($this->company, $this->entity,$data['$amount_raw']['value']))->getQrCode(), 'label' => ''];
+ if (($this->entity_string == 'invoice' || $this->entity_string == 'recurring_invoice') && isset($this->company?->custom_fields?->company1)) {
+ $data['$sepa_qr_code'] = ['value' => (new EpcQrGenerator($this->company, $this->entity, $data['$amount_raw']['value']))->getQrCode(), 'label' => ''];
}
$arrKeysLength = array_map('strlen', array_keys($data));
@@ -735,27 +725,21 @@ class HtmlEngine
private function getCountryName() :string
{
-
$countries = Cache::get('countries');
if (! $countries) {
$this->buildCache(true);
$countries = Cache::get('countries');
-
}
- if($countries){
-
-
+ if ($countries) {
$country = $countries->filter(function ($item) {
return $item->id == $this->settings->country_id;
})->first();
-
-
- }
- else
+ } else {
$country = Country::find($this->settings->country_id);
+ }
if ($country) {
return ctrans('texts.country_' . $country->name);
@@ -769,8 +753,9 @@ class HtmlEngine
{
$country = Country::find($this->settings->country_id);
- if($country)
+ if ($country) {
return $country->iso_3166_2;
+ }
// if ($country) {
// return ctrans('texts.country_' . $country->iso_3166_2);
// }
@@ -948,8 +933,8 @@ html {
/**
* Generate markup for HTML images on entity.
- *
- * @return string|void
+ *
+ * @return string|void
*/
protected function generateEntityImagesMarkup()
{
diff --git a/app/Utils/Ninja.php b/app/Utils/Ninja.php
index b66d40b8260d..3274983d540e 100644
--- a/app/Utils/Ninja.php
+++ b/app/Utils/Ninja.php
@@ -193,8 +193,7 @@ class Ninja
*/
public static function isBase64Encoded(string $s) : bool
{
-
- // Check if there are valid base64 characters
+ // Check if there are valid base64 characters
if (! preg_match('/^[a-zA-Z0-9\/\r\n+]*={0,2}$/', $s)) {
return false;
}
diff --git a/app/Utils/Number.php b/app/Utils/Number.php
index e2891b7c54b9..4d23798394c6 100644
--- a/app/Utils/Number.php
+++ b/app/Utils/Number.php
@@ -13,7 +13,6 @@ namespace App\Utils;
use App\Models\Company;
use App\Models\Currency;
-use App\Models\Vendor;
/**
* Class Number.
@@ -136,7 +135,6 @@ class Number
*/
public static function formatMoney($value, $entity) :string
{
-
$value = floatval($value);
$currency = $entity->currency();
@@ -227,8 +225,7 @@ class Number
/* 08-02-2023 special if block to render $0.5 to $0.50*/
if ($v < 1 && strlen($v) == 3) {
$precision = 2;
- }
- elseif ($v < 1) {
+ } elseif ($v < 1) {
$precision = strlen($v) - strrpos($v, '.') - 1;
}
diff --git a/app/Utils/PhantomJS/Phantom.php b/app/Utils/PhantomJS/Phantom.php
index 0ec93ddcdc32..00b3b206b55e 100644
--- a/app/Utils/PhantomJS/Phantom.php
+++ b/app/Utils/PhantomJS/Phantom.php
@@ -27,7 +27,6 @@ use App\Utils\HtmlEngine;
use App\Utils\Traits\MakesHash;
use App\Utils\Traits\Pdf\PageNumbering;
use Illuminate\Support\Facades\App;
-use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
@@ -112,8 +111,9 @@ class Phantom
$instance = Storage::disk(config('filesystems.default'))->put($file_path, $pdf);
- if($return_pdf)
+ if ($return_pdf) {
return $pdf;
+ }
return $file_path;
}
diff --git a/app/Utils/Statics.php b/app/Utils/Statics.php
index f1d6e86d96e5..cd6f9bcdd3f6 100644
--- a/app/Utils/Statics.php
+++ b/app/Utils/Statics.php
@@ -71,7 +71,6 @@ class Statics
foreach (config('ninja.cached_tables') as $name => $class) {
if (! Cache::has($name)) {
-
// check that the table exists in case the migration is pending
if (! Schema::hasTable((new $class())->getTable())) {
continue;
diff --git a/app/Utils/SystemHealth.php b/app/Utils/SystemHealth.php
index 04e4165a1255..be4fce4fa454 100644
--- a/app/Utils/SystemHealth.php
+++ b/app/Utils/SystemHealth.php
@@ -13,7 +13,6 @@ namespace App\Utils;
use App\Libraries\MultiDB;
use App\Mail\TestMailServer;
-use App\Models\Company;
use Exception;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
@@ -89,33 +88,30 @@ class SystemHealth
private static function checkCurrencySanity()
{
-
- if(!self::simpleDbCheck())
+ if (!self::simpleDbCheck()) {
return true;
-
- if(strlen(config('ninja.currency_converter_api_key')) == 0){
-
- try{
- $cs = DB::table('clients')
- ->select('settings->currency_id as id')
- ->get();
- }
- catch(\Exception $e){
- return true; //fresh installs, there may be no DB connection, nor migrations could have run yet.
}
- $currency_count = $cs->unique('id')->filter(function ($value){
- return !is_null($value->id);
- })->count();
+ if (strlen(config('ninja.currency_converter_api_key')) == 0) {
+ try {
+ $cs = DB::table('clients')
+ ->select('settings->currency_id as id')
+ ->get();
+ } catch(\Exception $e) {
+ return true; //fresh installs, there may be no DB connection, nor migrations could have run yet.
+ }
+
+ $currency_count = $cs->unique('id')->filter(function ($value) {
+ return !is_null($value->id);
+ })->count();
- if($currency_count > 1)
+ if ($currency_count > 1) {
return true;
-
+ }
}
return false;
-
}
private static function checkQueueSize()
@@ -217,8 +213,9 @@ class SystemHealth
private static function checkPhpCli()
{
- if(!function_exists('exec'))
+ if (!function_exists('exec')) {
return "Unable to check CLI version";
+ }
try {
exec('php -v', $foo, $exitCode);
@@ -278,7 +275,7 @@ class SystemHealth
$x = DB::connection()->getDatabaseName();
$result['success'] = true;
} catch (Exception $e) {
- // $x = [config('database.connections.'.config('database.default').'.database') => false];
+ // $x = [config('database.connections.'.config('database.default').'.database') => false];
$result['success'] = false;
$result['message'] = $e->getMessage();
}
diff --git a/app/Utils/TemplateEngine.php b/app/Utils/TemplateEngine.php
index 31e8d23eb199..ca10200a882e 100644
--- a/app/Utils/TemplateEngine.php
+++ b/app/Utils/TemplateEngine.php
@@ -26,17 +26,13 @@ use App\Models\QuoteInvitation;
use App\Models\Vendor;
use App\Models\VendorContact;
use App\Services\PdfMaker\Designs\Utilities\DesignHelpers;
-use App\Utils\Ninja;
use App\Utils\Traits\MakesHash;
use App\Utils\Traits\MakesInvoiceHtml;
use App\Utils\Traits\MakesTemplateData;
-use App\Utils\VendorHtmlEngine;
use DB;
use Illuminate\Support\Facades\App;
-use Illuminate\Support\Facades\Lang;
use Illuminate\Support\Str;
use League\CommonMark\CommonMarkConverter;
-use TijsVerkoyen\CssToInlineStyles\CssToInlineStyles;
class TemplateEngine
{
@@ -88,7 +84,6 @@ class TemplateEngine
public function build()
{
-
return $this->setEntity()
->setSettingsObject()
->setTemplates()
@@ -188,12 +183,13 @@ class TemplateEngine
private function entityValues($contact)
{
- if (in_array($this->entity, ['purchaseOrder', 'purchase_order']))
+ if (in_array($this->entity, ['purchaseOrder', 'purchase_order'])) {
$this->labels_and_values = (new VendorHtmlEngine($this->entity_obj->invitations->first()))->generateLabelsAndValues();
- elseif($this->entity == 'payment')
+ } elseif ($this->entity == 'payment') {
$this->labels_and_values = (new PaymentEmailEngine($this->entity_obj, $this->entity_obj->client->contacts->first()))->generateLabelsAndValues();
- else
+ } else {
$this->labels_and_values = (new HtmlEngine($this->entity_obj->invitations->first()))->generateLabelsAndValues();
+ }
$this->body = strtr($this->body, $this->labels_and_values['labels']);
@@ -219,10 +215,9 @@ class TemplateEngine
$data['footer'] = '';
$data['logo'] = auth()->user()->company()->present()->logo();
- if ($this->entity_obj->client()->exists())
+ if ($this->entity_obj->client()->exists()) {
$data = array_merge($data, Helpers::sharedEmailVariables($this->entity_obj->client));
- else {
-
+ } else {
$data['signature'] = $this->settings->email_signature;
$data['settings'] = $this->settings;
$data['whitelabel'] = $this->entity_obj ? $this->entity_obj->company->account->isPaid() : true;
@@ -269,10 +264,11 @@ class TemplateEngine
private function mockEntity()
{
- if (!$this->entity && $this->template && str_contains($this->template, 'purchase_order'))
+ if (!$this->entity && $this->template && str_contains($this->template, 'purchase_order')) {
$this->entity = 'purchaseOrder';
- elseif(str_contains($this->template, 'payment'))
+ } elseif (str_contains($this->template, 'payment')) {
$this->entity = 'payment';
+ }
DB::connection(config('database.default'))->beginTransaction();
@@ -292,8 +288,6 @@ class TemplateEngine
]);
if ($this->entity == 'payment') {
-
-
$this->entity_obj = Payment::factory()->create([
'user_id' => auth()->user()->id,
'company_id' => auth()->user()->company()->id,
@@ -309,7 +303,7 @@ class TemplateEngine
'client_id' => $client->id,
'amount' => 10,
'balance' => 10,
- 'number' => rand(1,10000)
+ 'number' => rand(1, 10000)
]);
$invitation = InvoiceInvitation::factory()->create([
@@ -322,7 +316,6 @@ class TemplateEngine
$this->entity_obj->invoices()->attach($invoice->id, [
'amount' => 10,
]);
-
}
if (!$this->entity || $this->entity == 'invoice') {
@@ -356,7 +349,6 @@ class TemplateEngine
}
if ($this->entity == 'purchaseOrder') {
-
$vendor = Vendor::factory()->create([
'user_id' => auth()->user()->id,
'company_id' => auth()->user()->company()->id,
@@ -386,7 +378,6 @@ class TemplateEngine
}
if ($vendor) {
-
$this->entity_obj->setRelation('invitations', $invitation);
$this->entity_obj->setRelation('vendor', $vendor);
$this->entity_obj->setRelation('company', auth()->user()->company());
diff --git a/app/Utils/Traits/AppSetup.php b/app/Utils/Traits/AppSetup.php
index c2a04d631a53..97f6cc6c47c6 100644
--- a/app/Utils/Traits/AppSetup.php
+++ b/app/Utils/Traits/AppSetup.php
@@ -14,9 +14,7 @@ namespace App\Utils\Traits;
use App\DataMapper\EmailTemplateDefaults;
use App\Utils\Ninja;
use App\Utils\SystemHealth;
-use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Cache;
-use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
trait AppSetup
@@ -38,7 +36,6 @@ trait AppSetup
foreach ($cached_tables as $name => $class) {
if (! Cache::has($name) || $force) {
-
if ($name == 'payment_terms') {
$orderBy = 'num_days';
} elseif ($name == 'fonts') {
diff --git a/app/Utils/Traits/CleanLineItems.php b/app/Utils/Traits/CleanLineItems.php
index 8eed99a8c6f8..4e16d287326f 100644
--- a/app/Utils/Traits/CleanLineItems.php
+++ b/app/Utils/Traits/CleanLineItems.php
@@ -46,7 +46,6 @@ trait CleanLineItems
unset($invoice_item->casts);
foreach ($invoice_item as $key => $value) {
-
//if the key has not been set, we set it to a default value
if (! array_key_exists($key, $item) || ! isset($item[$key])) {
$item[$key] = $value;
diff --git a/app/Utils/Traits/ClientGroupSettingsSaver.php b/app/Utils/Traits/ClientGroupSettingsSaver.php
index 2bfe99f8fd2c..fa9d5fca2ae3 100644
--- a/app/Utils/Traits/ClientGroupSettingsSaver.php
+++ b/app/Utils/Traits/ClientGroupSettingsSaver.php
@@ -11,7 +11,6 @@
namespace App\Utils\Traits;
-use App\DataMapper\ClientSettings;
use App\DataMapper\CompanySettings;
use stdClass;
@@ -234,7 +233,7 @@ trait ClientGroupSettingsSaver
case 'json':
json_decode($value);
- return json_last_error() == JSON_ERROR_NONE;
+ return json_last_error() == JSON_ERROR_NONE;
default:
return false;
}
diff --git a/app/Utils/Traits/CompanyGatewayFeesAndLimitsSaver.php b/app/Utils/Traits/CompanyGatewayFeesAndLimitsSaver.php
index 28e3e1069d9f..2b4a894094f1 100644
--- a/app/Utils/Traits/CompanyGatewayFeesAndLimitsSaver.php
+++ b/app/Utils/Traits/CompanyGatewayFeesAndLimitsSaver.php
@@ -62,7 +62,7 @@ trait CompanyGatewayFeesAndLimitsSaver
case 'real':
case 'float':
case 'double':
- return ! is_string($value) && (is_float($value) || is_numeric(strval($value)));
+ return ! is_string($value) && (is_float($value) || is_numeric(strval($value)));
// return is_float($value) || is_numeric(strval($value));
case 'string':
return (is_string($value) && method_exists($value, '__toString')) || is_null($value) || is_string($value);
@@ -76,7 +76,7 @@ trait CompanyGatewayFeesAndLimitsSaver
case 'json':
json_decode($value);
- return json_last_error() == JSON_ERROR_NONE;
+ return json_last_error() == JSON_ERROR_NONE;
default:
return false;
}
diff --git a/app/Utils/Traits/CompanySettingsSaver.php b/app/Utils/Traits/CompanySettingsSaver.php
index 5f2ff03025db..6f0c3217df8f 100644
--- a/app/Utils/Traits/CompanySettingsSaver.php
+++ b/app/Utils/Traits/CompanySettingsSaver.php
@@ -36,7 +36,6 @@ trait CompanySettingsSaver
*/
public function saveSettings($settings, $entity)
{
-
/* No Settings, No Save!*/
if (! $settings) {
return;
@@ -114,8 +113,9 @@ trait CompanySettingsSaver
elseif (substr($key, -3) == '_id' || substr($key, -14) == 'number_counter') {
$value = 'integer';
- if($key == 'besr_id')
+ if ($key == 'besr_id') {
$value = 'string';
+ }
if (! property_exists($settings, $key)) {
continue;
@@ -185,8 +185,9 @@ trait CompanySettingsSaver
$value = 'string';
}
- if($key == 'besr_id')
+ if ($key == 'besr_id') {
$value = 'string';
+ }
if (! property_exists($settings, $key)) {
continue;
@@ -260,7 +261,7 @@ trait CompanySettingsSaver
case 'json':
json_decode($value);
- return json_last_error() == JSON_ERROR_NONE;
+ return json_last_error() == JSON_ERROR_NONE;
default:
return false;
}
diff --git a/app/Utils/Traits/DesignCalculator.php b/app/Utils/Traits/DesignCalculator.php
index 97e887dfe39f..83bf016a13d3 100644
--- a/app/Utils/Traits/DesignCalculator.php
+++ b/app/Utils/Traits/DesignCalculator.php
@@ -13,7 +13,6 @@ namespace App\Utils\Traits;
trait DesignCalculator
{
-
private function resolveCompanyLogoSize()
{
$design_map = [
@@ -48,23 +47,26 @@ trait DesignCalculator
"11221" => "65%", //"C-DB1"
];
- if(isset($this->settings->company_logo_size) && strlen($this->settings->company_logo_size) > 1)
+ if (isset($this->settings->company_logo_size) && strlen($this->settings->company_logo_size) > 1) {
return $this->settings->company_logo_size;
+ }
- if($this->entity->design_id && array_key_exists($this->entity->design_id, $design_int_map))
+ if ($this->entity->design_id && array_key_exists($this->entity->design_id, $design_int_map)) {
return $design_int_map[$this->entity->design_id];
+ }
$default_design_id = $this->entity_string."_design_id";
- if($default_design_id == 'recurring_invoice_design_id')
+ if ($default_design_id == 'recurring_invoice_design_id') {
$default_design_id = 'invoice_design_id';
+ }
$design_id = $this->settings->{$default_design_id};
- if(array_key_exists($design_id, $design_map))
+ if (array_key_exists($design_id, $design_map)) {
return $design_map[$design_id];
+ }
return '65%';
-
}
-}
\ No newline at end of file
+}
diff --git a/app/Utils/Traits/GeneratesConvertedQuoteCounter.php b/app/Utils/Traits/GeneratesConvertedQuoteCounter.php
index 4de13e640f93..1c331694d46a 100644
--- a/app/Utils/Traits/GeneratesConvertedQuoteCounter.php
+++ b/app/Utils/Traits/GeneratesConvertedQuoteCounter.php
@@ -33,7 +33,6 @@ use Illuminate\Support\Str;
*/
trait GeneratesConvertedQuoteCounter
{
-
private int $update_counter;
private function harvestQuoteCounter($quote, $invoice, Client $client)
@@ -369,8 +368,7 @@ trait GeneratesConvertedQuoteCounter
}
//if ($type == 'credit') {
- return (bool) $client->getSetting('shared_invoice_credit_counter');
-
+ return (bool) $client->getSetting('shared_invoice_credit_counter');
}
/**
@@ -479,15 +477,12 @@ trait GeneratesConvertedQuoteCounter
$reset_counter_frequency = (int) $client->getSetting('reset_counter_frequency_id');
if ($reset_counter_frequency == 0) {
-
- if($client->getSetting('reset_counter_date')){
-
- $settings = $client->company->settings;
- $settings->reset_counter_date = "";
- $client->company->settings = $settings;
- $client->company->save();
-
- }
+ if ($client->getSetting('reset_counter_date')) {
+ $settings = $client->company->settings;
+ $settings->reset_counter_date = "";
+ $client->company->settings = $settings;
+ $client->company->save();
+ }
return;
}
@@ -536,7 +531,7 @@ trait GeneratesConvertedQuoteCounter
$new_reset_date = $reset_date->addYears(2);
break;
- default:
+ default:
$new_reset_date = $reset_date->addYear();
break;
}
diff --git a/app/Utils/Traits/GeneratesCounter.php b/app/Utils/Traits/GeneratesCounter.php
index 0b67f9a124e1..b4596f981cfa 100644
--- a/app/Utils/Traits/GeneratesCounter.php
+++ b/app/Utils/Traits/GeneratesCounter.php
@@ -34,7 +34,6 @@ use Illuminate\Support\Str;
*/
trait GeneratesCounter
{
-
private int $update_counter;
//todo in the form validation, we need to ensure that if a prefix and pattern is set we throw a validation error,
@@ -161,7 +160,6 @@ trait GeneratesCounter
default:
return 'default_number_counter';
-
}
}
@@ -400,7 +398,7 @@ trait GeneratesCounter
}
//credit
- return (bool) $client->getSetting('shared_invoice_credit_counter');
+ return (bool) $client->getSetting('shared_invoice_credit_counter');
}
/**
@@ -421,7 +419,6 @@ trait GeneratesCounter
$check_counter = 1;
do {
-
$number = $this->padCounter($counter, $padding);
$number = $this->applyNumberPattern($entity, $number, $pattern);
@@ -434,13 +431,10 @@ trait GeneratesCounter
$check_counter++;
if ($check_counter > 100) {
-
$this->update_counter = $counter--;
return $number.'_'.Str::random(5);
-
}
-
} while ($check);
$this->update_counter = $counter--;
@@ -518,15 +512,12 @@ trait GeneratesCounter
$reset_counter_frequency = (int) $client->getSetting('reset_counter_frequency_id');
if ($reset_counter_frequency == 0) {
-
- if($client->getSetting('reset_counter_date')){
-
- $settings = $client->company->settings;
- $settings->reset_counter_date = "";
- $client->company->settings = $settings;
- $client->company->save();
-
- }
+ if ($client->getSetting('reset_counter_date')) {
+ $settings = $client->company->settings;
+ $settings->reset_counter_date = "";
+ $client->company->settings = $settings;
+ $client->company->save();
+ }
return;
}
@@ -574,7 +565,7 @@ trait GeneratesCounter
$new_reset_date = $reset_date->addYears(2);
break;
- default:
+ default:
$new_reset_date = $reset_date->addYear();
break;
}
@@ -611,14 +602,11 @@ trait GeneratesCounter
$reset_counter_frequency = (int) $settings->reset_counter_frequency_id;
if ($reset_counter_frequency == 0) {
-
- if($settings->reset_counter_date){
-
- $settings->reset_counter_date = "";
- $company->settings = $settings;
- $company->save();
-
- }
+ if ($settings->reset_counter_date) {
+ $settings->reset_counter_date = "";
+ $company->settings = $settings;
+ $company->save();
+ }
return;
}
@@ -658,7 +646,7 @@ trait GeneratesCounter
$new_reset_date = $reset_date->addYears(2);
break;
- default:
+ default:
$new_reset_date = $reset_date->addYear();
break;
}
diff --git a/app/Utils/Traits/Inviteable.php b/app/Utils/Traits/Inviteable.php
index 161d66587f45..5fd1efbbca4b 100644
--- a/app/Utils/Traits/Inviteable.php
+++ b/app/Utils/Traits/Inviteable.php
@@ -12,12 +12,11 @@
namespace App\Utils\Traits;
use App\Utils\Ninja;
-use Illuminate\Support\Str;
-use BaconQrCode\Renderer\ImageRenderer;
use BaconQrCode\Renderer\Image\SvgImageBackEnd;
+use BaconQrCode\Renderer\ImageRenderer;
use BaconQrCode\Renderer\RendererStyle\RendererStyle;
use BaconQrCode\Writer;
-
+use Illuminate\Support\Str;
/**
* Class Inviteable.
@@ -61,7 +60,6 @@ trait Inviteable
public function getPaymentQrCode()
{
-
$renderer = new ImageRenderer(
new RendererStyle(200),
new SvgImageBackEnd()
@@ -72,7 +70,6 @@ trait Inviteable
return "";
-
}
public function getUnsubscribeLink()
diff --git a/app/Utils/Traits/MakesInvoiceHtml.php b/app/Utils/Traits/MakesInvoiceHtml.php
index 529544c7661e..cd203329f28e 100644
--- a/app/Utils/Traits/MakesInvoiceHtml.php
+++ b/app/Utils/Traits/MakesInvoiceHtml.php
@@ -11,9 +11,7 @@
namespace App\Utils\Traits;
-use App\Designs\Designer;
use Exception;
-use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\Facades\File;
use Illuminate\View\Factory;
diff --git a/app/Utils/Traits/MakesInvoiceValues.php b/app/Utils/Traits/MakesInvoiceValues.php
index eb4c83d1e916..69c44fff9f82 100644
--- a/app/Utils/Traits/MakesInvoiceValues.php
+++ b/app/Utils/Traits/MakesInvoiceValues.php
@@ -11,10 +11,7 @@
namespace App\Utils\Traits;
-use App\Models\Country;
-use App\Models\Credit;
use App\Models\Invoice;
-use App\Models\Quote;
use App\Utils\Helpers;
use App\Utils\Number;
use Carbon\Carbon;
@@ -263,7 +260,6 @@ trait MakesInvoiceValues
*/
public function transformLineItems($items, $table_type = '$product') :array
{ //$start = microtime(true);
-
$entity = $this->client ? $this->client : $this->vendor;
$data = [];
@@ -284,7 +280,7 @@ trait MakesInvoiceValues
if ($table_type == '$task' && $item->type_id != 2) {
// if ($item->type_id != 4 && $item->type_id != 5) {
- continue;
+ continue;
// }
}
diff --git a/app/Utils/Traits/MakesReminders.php b/app/Utils/Traits/MakesReminders.php
index 58fb5d3ef155..2d9f8b80b607 100644
--- a/app/Utils/Traits/MakesReminders.php
+++ b/app/Utils/Traits/MakesReminders.php
@@ -21,7 +21,6 @@ trait MakesReminders
{
public function inReminderWindow($schedule_reminder, $num_days_reminder)
{
-
switch ($schedule_reminder) {
case 'after_invoice_date':
return Carbon::parse($this->date)->addDays($num_days_reminder)->startOfDay()->eq(Carbon::now()->startOfDay());
@@ -93,7 +92,7 @@ trait MakesReminders
switch ($endless_reminder_frequency_id) {
case RecurringInvoice::FREQUENCY_DAILY:
return Carbon::parse($date)->addDay()->startOfDay();
- case RecurringInvoice::FREQUENCY_WEEKLY:
+ case RecurringInvoice::FREQUENCY_WEEKLY:
return Carbon::parse($date)->addWeek()->startOfDay();
case RecurringInvoice::FREQUENCY_TWO_WEEKS:
return Carbon::parse($date)->addWeeks(2)->startOfDay();
diff --git a/app/Utils/Traits/MakesTemplateData.php b/app/Utils/Traits/MakesTemplateData.php
index cff45b82cfd1..c4a9fcb7ba12 100644
--- a/app/Utils/Traits/MakesTemplateData.php
+++ b/app/Utils/Traits/MakesTemplateData.php
@@ -203,7 +203,8 @@ trait MakesTemplateData
$data['$task.tax_name3'] = ['value' => 'CA Sales Tax', 'label' => ctrans('texts.tax')];
$data['$task.line_total'] = ['value' => '$100.00', 'label' => ctrans('texts.line_total')];
- $data['$vendor_name'] = ['value' => 'Joey Diaz Denkins', 'label' => ctrans('texts.vendor_name')];;
+ $data['$vendor_name'] = ['value' => 'Joey Diaz Denkins', 'label' => ctrans('texts.vendor_name')];
+ ;
$data['$vendor.name'] = &$data['$vendor_name'];
$data['$vendor'] = &$data['$vendor_name'];
diff --git a/app/Utils/Traits/Notifications/UserNotifies.php b/app/Utils/Traits/Notifications/UserNotifies.php
index 89cddfbd93ec..7f0e7f5d16ad 100644
--- a/app/Utils/Traits/Notifications/UserNotifies.php
+++ b/app/Utils/Traits/Notifications/UserNotifies.php
@@ -162,12 +162,12 @@ trait UserNotifies
/**
* Underrated method right here, last ones
* are always the best
- *
- * @param CompanyUser $company_user
+ *
+ * @param CompanyUser $company_user
* @param Invoice | Quote | Credit | PurchaseOrder | Product $entity
- * @param array $required_notification
- *
- * @return bool
+ * @param array $required_notification
+ *
+ * @return bool
*/
private function checkNotificationExists($company_user, $entity, $required_notification): bool
{
diff --git a/app/Utils/Traits/NumberFormatter.php b/app/Utils/Traits/NumberFormatter.php
index f0778a3d0dba..96684e03650f 100644
--- a/app/Utils/Traits/NumberFormatter.php
+++ b/app/Utils/Traits/NumberFormatter.php
@@ -21,7 +21,6 @@ trait NumberFormatter
/* 08-01-2022 allow increased precision means we need to transform from scientific notation to a regular string */
return number_format($this->parseFloat(rtrim(sprintf('%f', $value), '0')), $precision, '.', '');
-
}
/**
@@ -33,7 +32,6 @@ trait NumberFormatter
*/
private function parseFloat($value) : float
{
-
// check for comma as decimal separator
if (preg_match('/,[\d]{1,2}$/', $value)) {
$value = str_replace(',', '.', $value);
diff --git a/app/Utils/Traits/Pdf/PageNumbering.php b/app/Utils/Traits/Pdf/PageNumbering.php
index d46dfc83d23b..5e930ffaa2c0 100644
--- a/app/Utils/Traits/Pdf/PageNumbering.php
+++ b/app/Utils/Traits/Pdf/PageNumbering.php
@@ -11,7 +11,6 @@
namespace App\Utils\Traits\Pdf;
-use App\Utils\Traits\Pdf\PDF;
use setasign\Fpdi\PdfParser\StreamReader;
trait PageNumbering
diff --git a/app/Utils/Traits/SavesDocuments.php b/app/Utils/Traits/SavesDocuments.php
index 28526da97f9a..b7ffd0cda2c4 100644
--- a/app/Utils/Traits/SavesDocuments.php
+++ b/app/Utils/Traits/SavesDocuments.php
@@ -33,8 +33,9 @@ trait SavesDocuments
return false;
}
- if(!is_array($document_array))
+ if (!is_array($document_array)) {
return;
+ }
foreach ($document_array as $document) {
$document = (new UploadFile(
diff --git a/app/Utils/Traits/SettingsSaver.php b/app/Utils/Traits/SettingsSaver.php
index f14a87e80f2b..e53a764318f9 100644
--- a/app/Utils/Traits/SettingsSaver.php
+++ b/app/Utils/Traits/SettingsSaver.php
@@ -35,9 +35,8 @@ trait SettingsSaver
ksort($casts);
foreach ($casts as $key => $value) {
-
//try casting floats here
- if($value == 'float' && property_exists($settings, $key)){
+ if ($value == 'float' && property_exists($settings, $key)) {
$settings->{$key} = floatval($settings->{$key});
}
@@ -52,11 +51,12 @@ trait SettingsSaver
continue;
}
/*Separate loop if it is a _id field which is an integer cast as a string*/
- elseif (substr($key, -3) == '_id' || substr($key, -14) == 'number_counter' || ($key == 'payment_terms' && property_exists($settings, $key) && strlen($settings->{$key}) >= 1) || ($key == 'valid_until' && property_exists($settings, $key) && strlen($settings->{$key}) >= 1)) {
+ elseif (substr($key, -3) == '_id' || substr($key, -14) == 'number_counter' || ($key == 'payment_terms' && property_exists($settings, $key) && strlen($settings->{$key}) >= 1) || ($key == 'valid_until' && property_exists($settings, $key) && strlen($settings->{$key}) >= 1)) {
$value = 'integer';
- if($key == 'gmail_sending_user_id' || $key == 'besr_id')
+ if ($key == 'gmail_sending_user_id' || $key == 'besr_id') {
$value = 'string';
+ }
if (! property_exists($settings, $key)) {
continue;
@@ -100,7 +100,7 @@ trait SettingsSaver
case 'double':
return !is_string($value) && (is_float($value) || is_numeric(strval($value)));
case 'string':
- return !is_int($value) || ( is_string( $value ) && method_exists($value, '__toString') ) || is_null($value) || is_string($value);
+ return !is_int($value) || (is_string($value) && method_exists($value, '__toString')) || is_null($value) || is_string($value);
case 'bool':
case 'boolean':
return is_bool($value) || (int) filter_var($value, FILTER_VALIDATE_BOOLEAN);
@@ -111,7 +111,7 @@ trait SettingsSaver
case 'json':
json_decode($value);
- return json_last_error() == JSON_ERROR_NONE;
+ return json_last_error() == JSON_ERROR_NONE;
default:
return false;
}
diff --git a/app/Utils/Traits/SubscriptionHooker.php b/app/Utils/Traits/SubscriptionHooker.php
index 6896a8ac78f7..df03068464b7 100644
--- a/app/Utils/Traits/SubscriptionHooker.php
+++ b/app/Utils/Traits/SubscriptionHooker.php
@@ -11,9 +11,8 @@
namespace App\Utils\Traits;
-use GuzzleHttp\RequestOptions;
use GuzzleHttp\Exception\ClientException;
-use GuzzleHttp\Psr7\Message;
+use GuzzleHttp\RequestOptions;
/**
* Class SubscriptionHooker.
@@ -27,17 +26,19 @@ trait SubscriptionHooker
'X-Requested-With' => 'XMLHttpRequest',
];
- if(!isset($subscription->webhook_configuration['post_purchase_url']) && !isset($subscription->webhook_configuration['post_purchase_rest_method']))
+ if (!isset($subscription->webhook_configuration['post_purchase_url']) && !isset($subscription->webhook_configuration['post_purchase_rest_method'])) {
return [];
+ }
if (count($subscription->webhook_configuration['post_purchase_headers']) >= 1) {
$headers = array_merge($headers, $subscription->webhook_configuration['post_purchase_headers']);
}
$client = new \GuzzleHttp\Client(
- [
- 'headers' => $headers,
- ]);
+ [
+ 'headers' => $headers,
+ ]
+ );
$post_purchase_rest_method = (string) $subscription->webhook_configuration['post_purchase_rest_method'];
$post_purchase_url = (string) $subscription->webhook_configuration['post_purchase_url'];
@@ -49,22 +50,21 @@ trait SubscriptionHooker
return array_merge($body, json_decode($response->getBody(), true));
} catch (ClientException $e) {
-
$message = $e->getMessage();
$error = json_decode($e->getResponse()->getBody()->getContents());
- if(is_null($error)){
- nlog("empty response");
+ if (is_null($error)) {
+ nlog("empty response");
nlog($e->getMessage());
}
- if($error && property_exists($error, 'message'))
+ if ($error && property_exists($error, 'message')) {
$message = $error->message;
+ }
return array_merge($body, ['message' => $message, 'status_code' => 500]);
- }
- catch (\Exception $e) {
+ } catch (\Exception $e) {
return array_merge($body, ['message' => $e->getMessage(), 'status_code' => 500]);
}
}
diff --git a/app/Utils/Traits/Uploadable.php b/app/Utils/Traits/Uploadable.php
index 3100a9c6c58d..69be5021f470 100644
--- a/app/Utils/Traits/Uploadable.php
+++ b/app/Utils/Traits/Uploadable.php
@@ -23,7 +23,7 @@ trait Uploadable
public function removeLogo($company)
{
//if (Storage::disk(config('filesystems.default'))->exists($company->settings->company_logo)) {
- (new UnlinkFile(config('filesystems.default'), $company->settings->company_logo))->handle();
+ (new UnlinkFile(config('filesystems.default'), $company->settings->company_logo))->handle();
//}
}
diff --git a/app/Utils/VendorHtmlEngine.php b/app/Utils/VendorHtmlEngine.php
index c57d79d44870..b8d28390cdac 100644
--- a/app/Utils/VendorHtmlEngine.php
+++ b/app/Utils/VendorHtmlEngine.php
@@ -14,18 +14,13 @@ namespace App\Utils;
use App\Models\Country;
use App\Models\CreditInvitation;
-use App\Models\GatewayType;
use App\Models\InvoiceInvitation;
use App\Models\PurchaseOrderInvitation;
use App\Models\QuoteInvitation;
use App\Models\RecurringInvoiceInvitation;
-use App\Services\PdfMaker\Designs\Utilities\DesignHelpers;
-use App\Utils\Ninja;
-use App\Utils\Number;
use App\Utils\Traits\AppSetup;
use App\Utils\Traits\DesignCalculator;
use App\Utils\Traits\MakesDates;
-use App\Utils\transformTranslations;
use Exception;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Cache;
@@ -71,9 +66,9 @@ class VendorHtmlEngine
$this->contact = $invitation->contact->load('vendor');
- $this->vendor = $this->contact->vendor->load('company','country');
+ $this->vendor = $this->contact->vendor->load('company', 'country');
- if(!$this->vendor->currency_id){
+ if (!$this->vendor->currency_id) {
$this->vendor->currency_id = $this->company->settings->currency_id;
$this->vendor->save();
}
@@ -116,7 +111,7 @@ class VendorHtmlEngine
public function buildEntityDataArray() :array
{
- if (! $this->vendor->currency()) {
+ if (! $this->vendor->currency()) {
throw new Exception(debug_backtrace()[1]['function'], 1);
exit;
}
@@ -176,25 +171,23 @@ class VendorHtmlEngine
$data['$subtotal'] = ['value' => Number::formatMoney($this->entity_calc->getSubTotal(), $this->vendor) ?: ' ', 'label' => ctrans('texts.subtotal')];
$data['$gross_subtotal'] = ['value' => Number::formatMoney($this->entity_calc->getGrossSubTotal(), $this->vendor) ?: ' ', 'label' => ctrans('texts.subtotal')];
- if($this->entity->uses_inclusive_taxes)
+ if ($this->entity->uses_inclusive_taxes) {
$data['$net_subtotal'] = ['value' => Number::formatMoney(($this->entity_calc->getSubTotal() - $this->entity->total_taxes - $this->entity_calc->getTotalDiscount()), $this->vendor) ?: ' ', 'label' => ctrans('texts.net_subtotal')];
- else
+ } else {
$data['$net_subtotal'] = ['value' => Number::formatMoney($this->entity_calc->getSubTotal() - $this->entity_calc->getTotalDiscount(), $this->vendor) ?: ' ', 'label' => ctrans('texts.net_subtotal')];
+ }
if ($this->entity->partial > 0) {
$data['$balance_due'] = ['value' => Number::formatMoney($this->entity->partial, $this->vendor) ?: ' ', 'label' => ctrans('texts.partial_due')];
$data['$balance_due_raw'] = ['value' => $this->entity->partial, 'label' => ctrans('texts.partial_due')];
$data['$amount_raw'] = ['value' => $this->entity->partial, 'label' => ctrans('texts.partial_due')];
$data['$due_date'] = ['value' => $this->translateDate($this->entity->partial_due_date, $this->company->date_format(), $this->company->locale()) ?: ' ', 'label' => ctrans('texts.'.$this->entity_string.'_due_date')];
-
} else {
-
- if($this->entity->status_id == 1){
+ if ($this->entity->status_id == 1) {
$data['$balance_due'] = ['value' => Number::formatMoney($this->entity->amount, $this->vendor) ?: ' ', 'label' => ctrans('texts.balance_due')];
$data['$balance_due_raw'] = ['value' => $this->entity->amount, 'label' => ctrans('texts.balance_due')];
$data['$amount_raw'] = ['value' => $this->entity->amount, 'label' => ctrans('texts.amount')];
- }
- else{
+ } else {
$data['$balance_due'] = ['value' => Number::formatMoney($this->entity->balance, $this->vendor) ?: ' ', 'label' => ctrans('texts.balance_due')];
$data['$balance_due_raw'] = ['value' => $this->entity->balance, 'label' => ctrans('texts.balance_due')];
$data['$amount_raw'] = ['value' => $this->entity->amount, 'label' => ctrans('texts.amount')];
@@ -255,8 +248,9 @@ class VendorHtmlEngine
$data['$country_2'] = ['value' => isset($this->vendor->country) ? $this->vendor->country->iso_3166_2 : '', 'label' => ctrans('texts.country')];
$data['$email'] = ['value' => isset($this->contact) ? $this->contact->email : 'no contact email on record', 'label' => ctrans('texts.email')];
- if(str_contains($data['$email']['value'], 'example.com'))
+ if (str_contains($data['$email']['value'], 'example.com')) {
$data['$email'] = ['value' => '', 'label' => ctrans('texts.email')];
+ }
$data['$vendor_name'] = ['value' => $this->vendor->present()->name() ?: ' ', 'label' => ctrans('texts.vendor_name')];
$data['$vendor.name'] = &$data['$vendor_name'];
@@ -426,9 +420,7 @@ class VendorHtmlEngine
$data['$payments'] = ['value' => '', 'label' => ctrans('texts.payments')];
- if($this->entity->client()->exists())
- {
-
+ if ($this->entity->client()->exists()) {
$data['$client1'] = ['value' => $this->helpers->formatCustomFieldValue($this->company->custom_fields, 'client1', $this->entity->client->custom_value1, $this->entity->client) ?: ' ', 'label' => $this->helpers->makeCustomField($this->company->custom_fields, 'client1')];
$data['$client2'] = ['value' => $this->helpers->formatCustomFieldValue($this->company->custom_fields, 'client2', $this->entity->client->custom_value2, $this->entity->client) ?: ' ', 'label' => $this->helpers->makeCustomField($this->company->custom_fields, 'client2')];
$data['$client3'] = ['value' => $this->helpers->formatCustomFieldValue($this->company->custom_fields, 'client3', $this->entity->client->custom_value3, $this->entity->client) ?: ' ', 'label' => $this->helpers->makeCustomField($this->company->custom_fields, 'client3')];
@@ -486,7 +478,6 @@ class VendorHtmlEngine
$data['$client.balance'] = ['value' => Number::formatMoney($this->entity->client->balance, $this->entity->client), 'label' => ctrans('texts.account_balance')];
$data['$client_balance'] = ['value' => Number::formatMoney($this->entity->client->balance, $this->entity->client), 'label' => ctrans('texts.account_balance')];
-
}
@@ -568,27 +559,21 @@ class VendorHtmlEngine
private function getCountryName() :string
{
-
$countries = Cache::get('countries');
if (! $countries) {
$this->buildCache(true);
$countries = Cache::get('countries');
-
}
- if($countries){
-
-
+ if ($countries) {
$country = $countries->filter(function ($item) {
return $item->id == $this->settings->country_id;
})->first();
-
-
- }
- else
+ } else {
$country = Country::find($this->settings->country_id);
+ }
if ($country) {
return ctrans('texts.country_' . $country->name);
@@ -602,8 +587,9 @@ class VendorHtmlEngine
{
$country = Country::find($this->settings->country_id);
- if($country)
+ if ($country) {
return $country->iso_3166_2;
+ }
// if ($country) {
// return ctrans('texts.country_' . $country->iso_3166_2);
// }
@@ -780,8 +766,8 @@ html {
/**
* Generate markup for HTML images on entity.
- *
- * @return string|void
+ *
+ * @return string|void
*/
protected function generateEntityImagesMarkup()
{
@@ -831,5 +817,4 @@ html {
';
}
-
}
diff --git a/config/flare.php b/config/flare.php
index a4896f353761..ebb9eabdebc1 100644
--- a/config/flare.php
+++ b/config/flare.php
@@ -1,16 +1,16 @@
env('NINJA_COMPANY_ID', null),
'ninja_default_company_gateway_id' => env('NINJA_COMPANY_GATEWAY_ID', null),
'ninja_hosted_secret' => env('NINJA_HOSTED_SECRET', ''),
- 'ninja_hosted_header' =>env('NINJA_HEADER',''),
+ 'ninja_hosted_header' =>env('NINJA_HEADER', ''),
'internal_queue_enabled' => env('INTERNAL_QUEUE_ENABLED', true),
'ninja_apple_api_key' => env('APPLE_API_KEY', false),
'ninja_apple_private_key' => env('APPLE_PRIVATE_KEY', false),
@@ -199,17 +199,17 @@ return [
'ninja_apple_issuer_id' => env('APPLE_ISSUER_ID', false),
'react_app_enabled' => env('REACT_APP_ENABLED', false),
'ninja_apple_client_id' => env('APPLE_CLIENT_ID', false),
- 'ninja_apple_client_secret' => env('APPLE_CLIENT_SECRET',false),
- 'ninja_apple_redirect_url' => env('APPLE_REDIRECT_URI',false),
- 'twilio_account_sid' => env('TWILIO_ACCOUNT_SID',false),
- 'twilio_auth_token' => env('TWILIO_AUTH_TOKEN',false),
- 'twilio_verify_sid' => env('TWILIO_VERIFY_SID',false),
+ 'ninja_apple_client_secret' => env('APPLE_CLIENT_SECRET', false),
+ 'ninja_apple_redirect_url' => env('APPLE_REDIRECT_URI', false),
+ 'twilio_account_sid' => env('TWILIO_ACCOUNT_SID', false),
+ 'twilio_auth_token' => env('TWILIO_AUTH_TOKEN', false),
+ 'twilio_verify_sid' => env('TWILIO_VERIFY_SID', false),
'yodlee' => [
- 'client_id' => env('YODLEE_CLIENT_ID',false),
+ 'client_id' => env('YODLEE_CLIENT_ID', false),
'client_secret' => env('YODLEE_CLIENT_SECRET', false),
'admin_name' => env('YODLEE_LOGIN_ADMIN_NAME', false),
'test_mode' => env("YODLEE_TEST_MODE", false),
'dev_mode' => env("YODLEE_DEV_MODE", false),
'config_name' => env("YODLEE_CONFIG_NAME", false),
],
-];
\ No newline at end of file
+];
diff --git a/config/purchase.php b/config/purchase.php
index 2791bd868288..b461c41559c8 100644
--- a/config/purchase.php
+++ b/config/purchase.php
@@ -17,8 +17,8 @@ use Imdhemy\Purchases\Events\GooglePlay\SubscriptionDeferred;
use Imdhemy\Purchases\Events\GooglePlay\SubscriptionExpired;
use Imdhemy\Purchases\Events\GooglePlay\SubscriptionInGracePeriod;
use Imdhemy\Purchases\Events\GooglePlay\SubscriptionOnHold;
-use Imdhemy\Purchases\Events\GooglePlay\SubscriptionPauseScheduleChanged;
use Imdhemy\Purchases\Events\GooglePlay\SubscriptionPaused;
+use Imdhemy\Purchases\Events\GooglePlay\SubscriptionPauseScheduleChanged;
use Imdhemy\Purchases\Events\GooglePlay\SubscriptionPriceChangeConfirmed;
use Imdhemy\Purchases\Events\GooglePlay\SubscriptionPurchased;
use Imdhemy\Purchases\Events\GooglePlay\SubscriptionRecovered;
diff --git a/config/services.php b/config/services.php
index 36d6a704ec6b..78d3df8341d6 100644
--- a/config/services.php
+++ b/config/services.php
@@ -19,14 +19,14 @@ return [
*/
'mailgun' => [
- 'domain' => env('MAILGUN_DOMAIN',''),
- 'secret' => env('MAILGUN_SECRET',''),
+ 'domain' => env('MAILGUN_DOMAIN', ''),
+ 'secret' => env('MAILGUN_SECRET', ''),
'endpoint' => env('MAILGUN_ENDPOINT', 'api.mailgun.net'),
'scheme' => 'https',
],
'postmark' => [
- 'token' => env('POSTMARK_SECRET',''),
+ 'token' => env('POSTMARK_SECRET', ''),
],
'microsoft' => [
diff --git a/database/factories/AccountFactory.php b/database/factories/AccountFactory.php
index 66220630d833..371c2a3f9193 100644
--- a/database/factories/AccountFactory.php
+++ b/database/factories/AccountFactory.php
@@ -11,7 +11,6 @@
namespace Database\Factories;
-use App\Models\Account;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
diff --git a/database/factories/BankIntegrationFactory.php b/database/factories/BankIntegrationFactory.php
index ad588f872a84..2cc88e5f7ad8 100644
--- a/database/factories/BankIntegrationFactory.php
+++ b/database/factories/BankIntegrationFactory.php
@@ -11,9 +11,7 @@
namespace Database\Factories;
-use App\Models\Account;
use Illuminate\Database\Eloquent\Factories\Factory;
-use Illuminate\Support\Str;
class BankIntegrationFactory extends Factory
{
@@ -38,4 +36,4 @@ class BankIntegrationFactory extends Factory
'is_deleted' => false,
];
}
-}
\ No newline at end of file
+}
diff --git a/database/factories/BankTransactionFactory.php b/database/factories/BankTransactionFactory.php
index 404f268d5787..e47a822100cd 100644
--- a/database/factories/BankTransactionFactory.php
+++ b/database/factories/BankTransactionFactory.php
@@ -11,9 +11,7 @@
namespace Database\Factories;
-use App\Models\Account;
use Illuminate\Database\Eloquent\Factories\Factory;
-use Illuminate\Support\Str;
class BankTransactionFactory extends Factory
{
@@ -26,7 +24,7 @@ class BankTransactionFactory extends Factory
{
return [
'transaction_id' => $this->faker->randomNumber(9, true) ,
- 'amount' => $this->faker->randomFloat(2,10,10000) ,
+ 'amount' => $this->faker->randomFloat(2, 10, 10000) ,
'currency_id' => '1',
'account_type' => 'creditCard',
'category_id' => 1,
@@ -35,7 +33,7 @@ class BankTransactionFactory extends Factory
'bank_account_id' => 1 ,
'description' =>$this->faker->words(5, true) ,
'status_id'=> 1,
- 'base_type' => (bool)rand(0,1) ? 'CREDIT' : 'DEBIT',
+ 'base_type' => (bool)rand(0, 1) ? 'CREDIT' : 'DEBIT',
];
}
}
diff --git a/database/factories/BankTransactionRuleFactory.php b/database/factories/BankTransactionRuleFactory.php
index af30349dffcc..c257902c84ac 100644
--- a/database/factories/BankTransactionRuleFactory.php
+++ b/database/factories/BankTransactionRuleFactory.php
@@ -11,9 +11,7 @@
namespace Database\Factories;
-use App\Models\Account;
use Illuminate\Database\Eloquent\Factories\Factory;
-use Illuminate\Support\Str;
class BankTransactionRuleFactory extends Factory
{
@@ -27,8 +25,8 @@ class BankTransactionRuleFactory extends Factory
return [
'name' => $this->faker->name(),
// 'applies_to' => (bool)rand(0,1) ? 'CREDIT' : 'DEBIT',
- 'matches_on_all' => (bool)rand(0,1),
- 'auto_convert' => (bool)rand(0,1),
+ 'matches_on_all' => (bool)rand(0, 1),
+ 'auto_convert' => (bool)rand(0, 1),
];
}
}
diff --git a/database/factories/ClientContactFactory.php b/database/factories/ClientContactFactory.php
index 473f919c30c3..706c2bc30fb4 100644
--- a/database/factories/ClientContactFactory.php
+++ b/database/factories/ClientContactFactory.php
@@ -11,7 +11,6 @@
namespace Database\Factories;
-use App\Models\ClientContact;
use Illuminate\Database\Eloquent\Factories\Factory;
class ClientContactFactory extends Factory
diff --git a/database/factories/ClientFactory.php b/database/factories/ClientFactory.php
index 045bdddf041f..5535cca440fa 100644
--- a/database/factories/ClientFactory.php
+++ b/database/factories/ClientFactory.php
@@ -12,7 +12,6 @@
namespace Database\Factories;
use App\DataMapper\ClientSettings;
-use App\Models\Client;
use Illuminate\Database\Eloquent\Factories\Factory;
class ClientFactory extends Factory
diff --git a/database/factories/CompanyFactory.php b/database/factories/CompanyFactory.php
index 2b08b87101c4..d70a899bfbf4 100644
--- a/database/factories/CompanyFactory.php
+++ b/database/factories/CompanyFactory.php
@@ -12,7 +12,6 @@
namespace Database\Factories;
use App\DataMapper\CompanySettings;
-use App\Models\Company;
use App\Utils\Traits\MakesHash;
use Illuminate\Database\Eloquent\Factories\Factory;
diff --git a/database/factories/CreditInvitationFactory.php b/database/factories/CreditInvitationFactory.php
index 950d6e84363a..ebf0b2895aea 100644
--- a/database/factories/CreditInvitationFactory.php
+++ b/database/factories/CreditInvitationFactory.php
@@ -11,7 +11,6 @@
namespace Database\Factories;
-use App\Models\CreditInvitation;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
diff --git a/database/factories/DocumentFactory.php b/database/factories/DocumentFactory.php
index 0b2642a84e99..b3183de7fff0 100644
--- a/database/factories/DocumentFactory.php
+++ b/database/factories/DocumentFactory.php
@@ -11,9 +11,7 @@
namespace Database\Factories;
-use App\Models\Document;
use Illuminate\Database\Eloquent\Factories\Factory;
-use Illuminate\Support\Str;
class DocumentFactory extends Factory
{
diff --git a/database/factories/ExpenseCategoryFactory.php b/database/factories/ExpenseCategoryFactory.php
index b158299b826d..1069882a6bf7 100644
--- a/database/factories/ExpenseCategoryFactory.php
+++ b/database/factories/ExpenseCategoryFactory.php
@@ -11,7 +11,6 @@
namespace Database\Factories;
-use App\Models\ExpenseCategory;
use Illuminate\Database\Eloquent\Factories\Factory;
class ExpenseCategoryFactory extends Factory
diff --git a/database/factories/ExpenseFactory.php b/database/factories/ExpenseFactory.php
index 8560fc2ceec2..0de98a169e83 100644
--- a/database/factories/ExpenseFactory.php
+++ b/database/factories/ExpenseFactory.php
@@ -11,7 +11,6 @@
namespace Database\Factories;
-use App\Models\Expense;
use Illuminate\Database\Eloquent\Factories\Factory;
class ExpenseFactory extends Factory
diff --git a/database/factories/GatewayFactory.php b/database/factories/GatewayFactory.php
index d21f6ddcbc8c..4750d76d51f8 100644
--- a/database/factories/GatewayFactory.php
+++ b/database/factories/GatewayFactory.php
@@ -11,7 +11,6 @@
namespace Database\Factories;
-use App\Models\Gateway;
use Illuminate\Database\Eloquent\Factories\Factory;
class GatewayFactory extends Factory
diff --git a/database/factories/InvoiceInvitationFactory.php b/database/factories/InvoiceInvitationFactory.php
index e5d6edc56a0e..fb23d37fb9f8 100644
--- a/database/factories/InvoiceInvitationFactory.php
+++ b/database/factories/InvoiceInvitationFactory.php
@@ -11,7 +11,6 @@
namespace Database\Factories;
-use App\Models\InvoiceInvitation;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
diff --git a/database/factories/ProductFactory.php b/database/factories/ProductFactory.php
index 7f8f25833838..ca66833b3d35 100644
--- a/database/factories/ProductFactory.php
+++ b/database/factories/ProductFactory.php
@@ -11,7 +11,6 @@
namespace Database\Factories;
-use App\Models\Product;
use Illuminate\Database\Eloquent\Factories\Factory;
class ProductFactory extends Factory
@@ -30,7 +29,7 @@ class ProductFactory extends Factory
'price' => $this->faker->numberBetween(1, 1000),
'quantity' => $this->faker->numberBetween(1, 100),
'custom_value1' => 'https://picsum.photos/200',
- 'custom_value2' => rand(0,100),
+ 'custom_value2' => rand(0, 100),
'custom_value3' => $this->faker->text(20),
'custom_value4' => $this->faker->text(20),
'is_deleted' => false,
diff --git a/database/factories/ProjectFactory.php b/database/factories/ProjectFactory.php
index 46f0276dae62..a5dfb9515459 100644
--- a/database/factories/ProjectFactory.php
+++ b/database/factories/ProjectFactory.php
@@ -11,7 +11,6 @@
namespace Database\Factories;
-use App\Models\Project;
use Illuminate\Database\Eloquent\Factories\Factory;
class ProjectFactory extends Factory
diff --git a/database/factories/PurchaseOrderFactory.php b/database/factories/PurchaseOrderFactory.php
index df91de22f5ba..ddfaface41f1 100644
--- a/database/factories/PurchaseOrderFactory.php
+++ b/database/factories/PurchaseOrderFactory.php
@@ -6,7 +6,7 @@
*
* @copyright Copyright (c) 2021. Invoice Ninja LLC (https://invoiceninja.com)
*
- * @license https://www.elastic.co/licensing/elastic-license
+ * @license https://www.elastic.co/licensing/elastic-license
*/
namespace Database\Factories;
diff --git a/database/factories/PurchaseOrderInvitationFactory.php b/database/factories/PurchaseOrderInvitationFactory.php
index a775099731d6..0e72088d25df 100644
--- a/database/factories/PurchaseOrderInvitationFactory.php
+++ b/database/factories/PurchaseOrderInvitationFactory.php
@@ -2,7 +2,6 @@
namespace Database\Factories;
-use App\Models\PurchaseOrderInvitation;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
diff --git a/database/factories/QuoteInvitationFactory.php b/database/factories/QuoteInvitationFactory.php
index 7fcaa1a3016c..fbeba27f48b1 100644
--- a/database/factories/QuoteInvitationFactory.php
+++ b/database/factories/QuoteInvitationFactory.php
@@ -11,7 +11,6 @@
namespace Database\Factories;
-use App\Models\QuoteInvitation;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
diff --git a/database/factories/RecurringExpenseFactory.php b/database/factories/RecurringExpenseFactory.php
index fb58a0f3dd27..68b109451aee 100644
--- a/database/factories/RecurringExpenseFactory.php
+++ b/database/factories/RecurringExpenseFactory.php
@@ -11,7 +11,6 @@
namespace Database\Factories;
-use App\Models\RecurringExpense;
use Illuminate\Database\Eloquent\Factories\Factory;
class RecurringExpenseFactory extends Factory
diff --git a/database/factories/SchedulerFactory.php b/database/factories/SchedulerFactory.php
index 8b839c5e6b2e..aba12d2f257f 100644
--- a/database/factories/SchedulerFactory.php
+++ b/database/factories/SchedulerFactory.php
@@ -12,7 +12,6 @@
namespace Database\Factories;
use App\Models\RecurringInvoice;
-use App\Models\Scheduler;
use Illuminate\Database\Eloquent\Factories\Factory;
class SchedulerFactory extends Factory
@@ -26,12 +25,12 @@ class SchedulerFactory extends Factory
{
return [
'name' => $this->faker->name(),
- 'is_paused' => rand(0,1),
- 'is_deleted' => rand(0,1),
+ 'is_paused' => rand(0, 1),
+ 'is_deleted' => rand(0, 1),
'parameters' => [],
'frequency_id' => RecurringInvoice::FREQUENCY_MONTHLY,
- 'next_run' => now()->addSeconds(rand(86400,8640000)),
- 'next_run_client' => now()->addSeconds(rand(86400,8640000)),
+ 'next_run' => now()->addSeconds(rand(86400, 8640000)),
+ 'next_run_client' => now()->addSeconds(rand(86400, 8640000)),
'template' => 'client_statement',
];
}
diff --git a/database/factories/SubscriptionFactory.php b/database/factories/SubscriptionFactory.php
index f8bbf991da5a..81607dd83bd7 100644
--- a/database/factories/SubscriptionFactory.php
+++ b/database/factories/SubscriptionFactory.php
@@ -13,7 +13,6 @@
namespace Database\Factories;
use App\Models\RecurringInvoice;
-use App\Models\Subscription;
use Illuminate\Database\Eloquent\Factories\Factory;
class SubscriptionFactory extends Factory
diff --git a/database/factories/TaskFactory.php b/database/factories/TaskFactory.php
index b252652d0b69..326607e8efba 100644
--- a/database/factories/TaskFactory.php
+++ b/database/factories/TaskFactory.php
@@ -11,7 +11,6 @@
namespace Database\Factories;
-use App\Models\Task;
use Illuminate\Database\Eloquent\Factories\Factory;
class TaskFactory extends Factory
diff --git a/database/factories/TaskStatusFactory.php b/database/factories/TaskStatusFactory.php
index 0ac62f60bfa3..940aef5373bc 100644
--- a/database/factories/TaskStatusFactory.php
+++ b/database/factories/TaskStatusFactory.php
@@ -11,7 +11,6 @@
namespace Database\Factories;
-use App\Models\TaskStatus;
use Illuminate\Database\Eloquent\Factories\Factory;
class TaskStatusFactory extends Factory
diff --git a/database/factories/TaxRateFactory.php b/database/factories/TaxRateFactory.php
index ef1be4c3a7be..2b2a65023781 100644
--- a/database/factories/TaxRateFactory.php
+++ b/database/factories/TaxRateFactory.php
@@ -11,9 +11,7 @@
namespace Database\Factories;
-use App\Models\TaxRate;
use Illuminate\Database\Eloquent\Factories\Factory;
-use Illuminate\Support\Str;
class TaxRateFactory extends Factory
{
diff --git a/database/factories/UserFactory.php b/database/factories/UserFactory.php
index 8e8edc2f2192..ce391a46a8aa 100644
--- a/database/factories/UserFactory.php
+++ b/database/factories/UserFactory.php
@@ -11,7 +11,6 @@
namespace Database\Factories;
-use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
class UserFactory extends Factory
diff --git a/database/factories/VendorContactFactory.php b/database/factories/VendorContactFactory.php
index f0bede1531c3..03b8556e8b74 100644
--- a/database/factories/VendorContactFactory.php
+++ b/database/factories/VendorContactFactory.php
@@ -11,7 +11,6 @@
namespace Database\Factories;
-use App\Models\VendorContact;
use Illuminate\Database\Eloquent\Factories\Factory;
class VendorContactFactory extends Factory
diff --git a/database/factories/VendorFactory.php b/database/factories/VendorFactory.php
index 7fd4b0668857..bfcec1759227 100644
--- a/database/factories/VendorFactory.php
+++ b/database/factories/VendorFactory.php
@@ -11,7 +11,6 @@
namespace Database\Factories;
-use App\Models\Vendor;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
diff --git a/database/migrations/2021_03_08_205030_add_russian_lang.php b/database/migrations/2021_03_08_205030_add_russian_lang.php
index 2298d3e5b239..f13e1357068f 100644
--- a/database/migrations/2021_03_08_205030_add_russian_lang.php
+++ b/database/migrations/2021_03_08_205030_add_russian_lang.php
@@ -2,7 +2,6 @@
use App\Models\Company;
use App\Models\Language;
-use App\Models\User;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
diff --git a/database/migrations/2021_03_19_221024_add_unique_constraints_on_all_entities.php b/database/migrations/2021_03_19_221024_add_unique_constraints_on_all_entities.php
index 07791c4d9b89..2e82dc28520d 100644
--- a/database/migrations/2021_03_19_221024_add_unique_constraints_on_all_entities.php
+++ b/database/migrations/2021_03_19_221024_add_unique_constraints_on_all_entities.php
@@ -1,8 +1,6 @@
id = 59;
- $forte->name = 'Forte';
- $forte->key = 'kivcvjexxvdiyqtj3mju5d6yhpeht2xs';
+ $forte->name = 'Forte';
+ $forte->key = 'kivcvjexxvdiyqtj3mju5d6yhpeht2xs';
$forte->provider = 'Forte';
$forte->is_offsite = true;
$forte->fields = \json_encode($fields);
diff --git a/database/migrations/2022_04_22_115838_client_settings_parse_for_types.php b/database/migrations/2022_04_22_115838_client_settings_parse_for_types.php
index 78a1d443e1b0..45702dc09ab8 100644
--- a/database/migrations/2022_04_22_115838_client_settings_parse_for_types.php
+++ b/database/migrations/2022_04_22_115838_client_settings_parse_for_types.php
@@ -4,8 +4,6 @@ use App\Models\Client;
use App\Utils\Ninja;
use App\Utils\Traits\ClientGroupSettingsSaver;
use Illuminate\Database\Migrations\Migration;
-use Illuminate\Database\Schema\Blueprint;
-use Illuminate\Support\Facades\Schema;
return new class extends Migration {
use ClientGroupSettingsSaver;
diff --git a/database/migrations/2022_04_26_032252_convert_custom_fields_column_from_varchar_to_text.php b/database/migrations/2022_04_26_032252_convert_custom_fields_column_from_varchar_to_text.php
index 5592b0da8d8f..fe35bd53fad2 100644
--- a/database/migrations/2022_04_26_032252_convert_custom_fields_column_from_varchar_to_text.php
+++ b/database/migrations/2022_04_26_032252_convert_custom_fields_column_from_varchar_to_text.php
@@ -1,6 +1,5 @@
id = 47;
$type->name = 'Klarna';
@@ -28,8 +25,7 @@ return new class extends Migration {
$pt = PaymentType::find(48);
- if(!$pt)
- {
+ if (!$pt) {
$type = new PaymentType();
$type->id = 48;
$type->name = 'Interac E-Transfer';
@@ -38,8 +34,7 @@ return new class extends Migration {
$gt = GatewayType::find(23);
- if(!$gt)
- {
+ if (!$gt) {
$type = new GatewayType();
$type->id = 23;
$type->alias = 'klarna';
diff --git a/database/migrations/2022_05_18_162443_create_schedulers_table.php b/database/migrations/2022_05_18_162443_create_schedulers_table.php
index 26a9c7ce90d4..6b4abb51a4d2 100644
--- a/database/migrations/2022_05_18_162443_create_schedulers_table.php
+++ b/database/migrations/2022_05_18_162443_create_schedulers_table.php
@@ -41,6 +41,5 @@ return new class extends Migration {
*/
public function down()
{
-
}
};
diff --git a/database/migrations/2022_05_30_181109_drop_scheduled_jobs_table.php b/database/migrations/2022_05_30_181109_drop_scheduled_jobs_table.php
index 0f1d48dd59c7..caac82143cc0 100644
--- a/database/migrations/2022_05_30_181109_drop_scheduled_jobs_table.php
+++ b/database/migrations/2022_05_30_181109_drop_scheduled_jobs_table.php
@@ -9,7 +9,6 @@
* @license https://www.elastic.co/licensing/elastic-license
*/
use Illuminate\Database\Migrations\Migration;
-use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration {
diff --git a/database/migrations/2022_06_01_215859_set_recurring_client_timestamp.php b/database/migrations/2022_06_01_215859_set_recurring_client_timestamp.php
index 5011d72ac5b6..0a228f8b18b1 100644
--- a/database/migrations/2022_06_01_215859_set_recurring_client_timestamp.php
+++ b/database/migrations/2022_06_01_215859_set_recurring_client_timestamp.php
@@ -32,7 +32,6 @@ return new class extends Migration {
});
RecurringInvoice::withTrashed()->whereNotNull('next_send_date')->cursor()->each(function ($recurring_invoice) {
-
// $offset = $recurring_invoice->client->timezone_offset();
// $re = Carbon::parse($recurring_invoice->next_send_date)->subSeconds($offset)->format('Y-m-d');
$re = Carbon::parse($recurring_invoice->next_send_date)->format('Y-m-d');
diff --git a/database/migrations/2022_06_10_030503_set_account_flag_for_react.php b/database/migrations/2022_06_10_030503_set_account_flag_for_react.php
index 89051c861910..ac80d2b13247 100644
--- a/database/migrations/2022_06_10_030503_set_account_flag_for_react.php
+++ b/database/migrations/2022_06_10_030503_set_account_flag_for_react.php
@@ -9,8 +9,6 @@
* @license https://www.elastic.co/licensing/elastic-license
*/
use Illuminate\Database\Migrations\Migration;
-use Illuminate\Database\Schema\Blueprint;
-use Illuminate\Support\Facades\Schema;
return new class extends Migration {
/**
diff --git a/database/migrations/2022_06_21_104350_fixes_for_description_in_pdf_designs.php b/database/migrations/2022_06_21_104350_fixes_for_description_in_pdf_designs.php
index 616114139785..6fb71e56d8a1 100644
--- a/database/migrations/2022_06_21_104350_fixes_for_description_in_pdf_designs.php
+++ b/database/migrations/2022_06_21_104350_fixes_for_description_in_pdf_designs.php
@@ -9,8 +9,6 @@
* @license https://www.elastic.co/licensing/elastic-license
*/
use Illuminate\Database\Migrations\Migration;
-use Illuminate\Database\Schema\Blueprint;
-use Illuminate\Support\Facades\Schema;
class FixesForDescriptionInPdfDesigns extends Migration
{
@@ -31,6 +29,5 @@ class FixesForDescriptionInPdfDesigns extends Migration
*/
public function down()
{
-
}
}
diff --git a/database/migrations/2022_06_24_141018_upgrade_failed_jobs_table.php b/database/migrations/2022_06_24_141018_upgrade_failed_jobs_table.php
index 6ff0098e5689..3567d00a6ca8 100644
--- a/database/migrations/2022_06_24_141018_upgrade_failed_jobs_table.php
+++ b/database/migrations/2022_06_24_141018_upgrade_failed_jobs_table.php
@@ -4,8 +4,7 @@ use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
-return new class extends Migration
-{
+return new class extends Migration {
/**
* Run the migrations.
*
diff --git a/database/migrations/2022_06_30_000126_add_flag_to_accounts_table.php b/database/migrations/2022_06_30_000126_add_flag_to_accounts_table.php
index 3e3ab2fc78ab..116d611f6a76 100644
--- a/database/migrations/2022_06_30_000126_add_flag_to_accounts_table.php
+++ b/database/migrations/2022_06_30_000126_add_flag_to_accounts_table.php
@@ -34,6 +34,5 @@ class AddFlagToAccountsTable extends Migration
*/
public function down()
{
-
}
}
diff --git a/database/migrations/2022_07_06_080127_add_purchase_order_to_expense.php b/database/migrations/2022_07_06_080127_add_purchase_order_to_expense.php
index b99bfc84968f..741b54b3999b 100644
--- a/database/migrations/2022_07_06_080127_add_purchase_order_to_expense.php
+++ b/database/migrations/2022_07_06_080127_add_purchase_order_to_expense.php
@@ -33,15 +33,12 @@ class AddPurchaseOrderToExpense extends Migration
$language = Language::find(36);
- if(!$language){
-
+ if (!$language) {
Language::unguard();
Language::create(['id' => 36, 'name' => 'Bulgarian', 'locale' => 'bg']);
$this->buildCache(true);
-
}
-
}
/**
diff --git a/database/migrations/2022_07_09_235510_add_index_to_payment_hash.php b/database/migrations/2022_07_09_235510_add_index_to_payment_hash.php
index e5495b50a8b3..35cecc5360f8 100644
--- a/database/migrations/2022_07_09_235510_add_index_to_payment_hash.php
+++ b/database/migrations/2022_07_09_235510_add_index_to_payment_hash.php
@@ -25,7 +25,7 @@ class AddIndexToPaymentHash extends Migration
});
Schema::table('products', function (Blueprint $table) {
- $table->index(['company_id', 'user_id', 'assigned_user_id', 'updated_at'],'pro_co_us_up_index');
+ $table->index(['company_id', 'user_id', 'assigned_user_id', 'updated_at'], 'pro_co_us_up_index');
});
}
diff --git a/database/migrations/2022_07_12_45766_add_matomo.php b/database/migrations/2022_07_12_45766_add_matomo.php
index 6eb354c2784a..68f5ae670dd5 100644
--- a/database/migrations/2022_07_12_45766_add_matomo.php
+++ b/database/migrations/2022_07_12_45766_add_matomo.php
@@ -4,8 +4,7 @@ use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
-return new class extends Migration
-{
+return new class extends Migration {
/**
* Run the migrations.
*
@@ -14,9 +13,8 @@ return new class extends Migration
public function up()
{
Schema::table('companies', function (Blueprint $table) {
- $table->string('matomo_url',191)->nullable();
+ $table->string('matomo_url', 191)->nullable();
$table->bigInteger('matomo_id')->nullable();
});
-
}
-};
\ No newline at end of file
+};
diff --git a/database/migrations/2022_07_18_033756_fixes_for_date_formats_table_react.php b/database/migrations/2022_07_18_033756_fixes_for_date_formats_table_react.php
index 78b1adec8a09..de837a9f9619 100644
--- a/database/migrations/2022_07_18_033756_fixes_for_date_formats_table_react.php
+++ b/database/migrations/2022_07_18_033756_fixes_for_date_formats_table_react.php
@@ -1,11 +1,8 @@
format_moment = 'ddd MMM D, YYYY';
$df->save();
}
- if($df = App\Models\DateFormat::find(14))
- {
-
+ if ($df = App\Models\DateFormat::find(14)) {
$df->format_moment = 'DD/MM/YYYY';
$df->save();
-
}
}
diff --git a/database/migrations/2022_07_21_023805_add_hebrew_language.php b/database/migrations/2022_07_21_023805_add_hebrew_language.php
index aa29ad54c727..47ec6122e772 100644
--- a/database/migrations/2022_07_21_023805_add_hebrew_language.php
+++ b/database/migrations/2022_07_21_023805_add_hebrew_language.php
@@ -2,8 +2,6 @@
use App\Models\Language;
use Illuminate\Database\Migrations\Migration;
-use Illuminate\Database\Schema\Blueprint;
-use Illuminate\Support\Facades\Schema;
class AddHebrewLanguage extends Migration
{
@@ -17,41 +15,30 @@ class AddHebrewLanguage extends Migration
Language::unguard();
- if(!Language::find(33)) {
-
+ if (!Language::find(33)) {
$serbian = ['id' => 33, 'name' => 'Serbian', 'locale' => 'sr'];
Language::create($serbian);
-
}
- if(!Language::find(34)) {
-
+ if (!Language::find(34)) {
$slovak = ['id' => 34, 'name' => 'Slovak', 'locale' => 'sk'];
Language::create($slovak);
-
}
- if(!Language::find(35)) {
-
+ if (!Language::find(35)) {
$estonia = ['id' => 35, 'name' => 'Estonian', 'locale' => 'et'];
Language::create($estonia);
-
}
- if(!Language::find(36)) {
-
+ if (!Language::find(36)) {
$bulgarian = ['id' => 36, 'name' => 'Bulgarian', 'locale' => 'bg'];
Language::create($bulgarian);
-
}
- if(!Language::find(37)) {
-
+ if (!Language::find(37)) {
$hebrew = ['id' => 37, 'name' => 'Hebrew', 'locale' => 'he'];
Language::create($hebrew);
-
}
-
}
/**
diff --git a/database/migrations/2022_07_26_091216_add_sms_verification_to_hosted_account.php b/database/migrations/2022_07_26_091216_add_sms_verification_to_hosted_account.php
index 7ef526562963..703780d29218 100644
--- a/database/migrations/2022_07_26_091216_add_sms_verification_to_hosted_account.php
+++ b/database/migrations/2022_07_26_091216_add_sms_verification_to_hosted_account.php
@@ -19,11 +19,9 @@ class AddSmsVerificationToHostedAccount extends Migration
$table->boolean('account_sms_verified')->default(0);
});
- App\Models\Account::query()->cursor()->each(function ($account){
-
+ App\Models\Account::query()->cursor()->each(function ($account) {
$account->account_sms_verified = true;
$account->save();
-
});
}
@@ -34,6 +32,5 @@ class AddSmsVerificationToHostedAccount extends Migration
*/
public function down()
{
-
}
}
diff --git a/database/migrations/2022_07_28_232340_enabled_expense_tax_rates_to_companies_table.php b/database/migrations/2022_07_28_232340_enabled_expense_tax_rates_to_companies_table.php
index 04a07d8f7d22..8f820e7c3507 100644
--- a/database/migrations/2022_07_28_232340_enabled_expense_tax_rates_to_companies_table.php
+++ b/database/migrations/2022_07_28_232340_enabled_expense_tax_rates_to_companies_table.php
@@ -5,8 +5,7 @@ use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
-return new class extends Migration
-{
+return new class extends Migration {
/**
* Run the migrations.
*
@@ -18,11 +17,9 @@ return new class extends Migration
$table->boolean('enabled_expense_tax_rates')->default(0);
});
- Company::query()->where('enabled_item_tax_rates', true)->cursor()->each(function ($company){
-
+ Company::query()->where('enabled_item_tax_rates', true)->cursor()->each(function ($company) {
$company->enabled_expense_tax_rates = true;
$company->save();
-
});
}
@@ -33,6 +30,5 @@ return new class extends Migration
*/
public function down()
{
-
}
};
diff --git a/database/migrations/2022_07_29_091235_correction_for_companies_table_types.php b/database/migrations/2022_07_29_091235_correction_for_companies_table_types.php
index 45564710b6a5..0a5d7bf5cf1c 100644
--- a/database/migrations/2022_07_29_091235_correction_for_companies_table_types.php
+++ b/database/migrations/2022_07_29_091235_correction_for_companies_table_types.php
@@ -5,8 +5,7 @@ use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
-return new class extends Migration
-{
+return new class extends Migration {
/**
* Run the migrations.
*
@@ -18,11 +17,9 @@ return new class extends Migration
$table->unsignedInteger('enabled_expense_tax_rates')->default(0)->change();
});
- Company::query()->where('enabled_item_tax_rates', true)->cursor()->each(function ($company){
-
+ Company::query()->where('enabled_item_tax_rates', true)->cursor()->each(function ($company) {
$company->enabled_expense_tax_rates = $company->enabled_item_tax_rates;
$company->save();
-
});
}
diff --git a/database/migrations/2022_08_05_023357_bank_integration.php b/database/migrations/2022_08_05_023357_bank_integration.php
index 1375b50af314..55639c89208b 100644
--- a/database/migrations/2022_08_05_023357_bank_integration.php
+++ b/database/migrations/2022_08_05_023357_bank_integration.php
@@ -4,8 +4,7 @@ use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
-return new class extends Migration
-{
+return new class extends Migration {
/**
* Run the migrations.
*
@@ -13,7 +12,6 @@ return new class extends Migration
*/
public function up()
{
-
Schema::create('bank_integrations', function (Blueprint $table) {
$table->id();
$table->unsignedInteger('account_id');
@@ -44,9 +42,9 @@ return new class extends Migration
Schema::table('accounts', function (Blueprint $table) {
$table->text('bank_integration_account_id')->nullable();
- });
+ });
- Schema::create('bank_transactions', function (Blueprint $table){
+ Schema::create('bank_transactions', function (Blueprint $table) {
$table->id();
$table->unsignedInteger('company_id');
$table->unsignedInteger('user_id');
@@ -75,21 +73,19 @@ return new class extends Migration
$table->foreign('bank_integration_id')->references('id')->on('bank_integrations')->onDelete('cascade')->onUpdate('cascade');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade')->onUpdate('cascade');
$table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade')->onUpdate('cascade');
-
});
Schema::table('expense_categories', function (Blueprint $table) {
$table->unsignedInteger('bank_category_id')->nullable();
- });
+ });
Schema::table('payments', function (Blueprint $table) {
$table->unsignedBigInteger('transaction_id')->nullable();
- });
+ });
Schema::table('expenses', function (Illuminate\Database\Schema\Blueprint $table) {
$table->unsignedBigInteger('transaction_id')->nullable()->change();
- });
-
+ });
}
/**
@@ -99,6 +95,5 @@ return new class extends Migration
*/
public function down()
{
-
}
};
diff --git a/database/migrations/2022_08_11_011534_licenses_table_for_self_host.php b/database/migrations/2022_08_11_011534_licenses_table_for_self_host.php
index 8fffec838a07..44169f6abb4c 100644
--- a/database/migrations/2022_08_11_011534_licenses_table_for_self_host.php
+++ b/database/migrations/2022_08_11_011534_licenses_table_for_self_host.php
@@ -4,8 +4,7 @@ use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
-return new class extends Migration
-{
+return new class extends Migration {
/**
* Run the migrations.
*
diff --git a/database/migrations/2022_08_24_215917_invoice_task_project_companies_table.php b/database/migrations/2022_08_24_215917_invoice_task_project_companies_table.php
index 1e9e8e1d05a6..ffa4de323603 100644
--- a/database/migrations/2022_08_24_215917_invoice_task_project_companies_table.php
+++ b/database/migrations/2022_08_24_215917_invoice_task_project_companies_table.php
@@ -4,8 +4,7 @@ use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
-return new class extends Migration
-{
+return new class extends Migration {
/**
* Run the migrations.
*
diff --git a/database/migrations/2022_08_26_232500_add_email_status_column_to_purchase_order_invitations_table.php b/database/migrations/2022_08_26_232500_add_email_status_column_to_purchase_order_invitations_table.php
index 944b55b346f1..ad3a80544983 100644
--- a/database/migrations/2022_08_26_232500_add_email_status_column_to_purchase_order_invitations_table.php
+++ b/database/migrations/2022_08_26_232500_add_email_status_column_to_purchase_order_invitations_table.php
@@ -4,8 +4,7 @@ use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
-return new class extends Migration
-{
+return new class extends Migration {
/**
* Run the migrations.
*
@@ -13,11 +12,9 @@ return new class extends Migration
*/
public function up()
{
-
Schema::table('purchase_order_invitations', function (Blueprint $table) {
- $table->enum('email_status', ['delivered', 'bounced', 'spam'])->nullable();
+ $table->enum('email_status', ['delivered', 'bounced', 'spam'])->nullable();
});
-
}
/**
@@ -27,6 +24,5 @@ return new class extends Migration
*/
public function down()
{
-
}
};
diff --git a/database/migrations/2022_08_28_210111_add_index_to_payments_table.php b/database/migrations/2022_08_28_210111_add_index_to_payments_table.php
index 7f798db6a48d..029fc3e8d0d6 100644
--- a/database/migrations/2022_08_28_210111_add_index_to_payments_table.php
+++ b/database/migrations/2022_08_28_210111_add_index_to_payments_table.php
@@ -4,8 +4,7 @@ use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
-return new class extends Migration
-{
+return new class extends Migration {
/**
* Run the migrations.
*
@@ -29,7 +28,6 @@ return new class extends Migration
Schema::table('quotes', function (Blueprint $table) {
$table->index(['company_id','updated_at']);
});
-
}
/**
diff --git a/database/migrations/2022_09_05_024719_update_designs_for_tech_template.php b/database/migrations/2022_09_05_024719_update_designs_for_tech_template.php
index f0f45d4a4bb2..9b6265db822b 100644
--- a/database/migrations/2022_09_05_024719_update_designs_for_tech_template.php
+++ b/database/migrations/2022_09_05_024719_update_designs_for_tech_template.php
@@ -1,11 +1,8 @@
fields);
$fields->threeds = false;
@@ -27,16 +22,13 @@ return new class extends Migration
$g->save();
}
- CompanyGateway::where('gateway_key', 'f7ec488676d310683fb51802d076d713')->cursor()->each(function ($cg){
-
+ CompanyGateway::where('gateway_key', 'f7ec488676d310683fb51802d076d713')->cursor()->each(function ($cg) {
$config = $cg->getConfig();
$config->threeds = false;
$cg->setConfig($config);
$cg->save();
-
});
-
}
/**
diff --git a/database/migrations/2022_09_30_235337_add_idempotency_key_to_payments.php b/database/migrations/2022_09_30_235337_add_idempotency_key_to_payments.php
index 7f95df32434d..1171c3ea3c42 100644
--- a/database/migrations/2022_09_30_235337_add_idempotency_key_to_payments.php
+++ b/database/migrations/2022_09_30_235337_add_idempotency_key_to_payments.php
@@ -4,8 +4,7 @@ use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
-return new class extends Migration
-{
+return new class extends Migration {
/**
* Run the migrations.
*
@@ -17,7 +16,6 @@ return new class extends Migration
$table->string('idempotency_key', 64)->nullable()->index();
$table->unique(['company_id', 'idempotency_key']);
-
});
}
@@ -28,6 +26,5 @@ return new class extends Migration
*/
public function down()
{
-
}
};
diff --git a/database/migrations/2022_10_05_205645_add_indexes_to_client_hash.php b/database/migrations/2022_10_05_205645_add_indexes_to_client_hash.php
index 09658b6e71ed..ff3cef56bb1c 100644
--- a/database/migrations/2022_10_05_205645_add_indexes_to_client_hash.php
+++ b/database/migrations/2022_10_05_205645_add_indexes_to_client_hash.php
@@ -4,8 +4,7 @@ use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
-return new class extends Migration
-{
+return new class extends Migration {
/**
* Run the migrations.
*
@@ -27,7 +26,6 @@ return new class extends Migration
$table->index([\DB::raw('contact_key(20)')]);
$table->index('email');
});
-
}
/**
diff --git a/database/migrations/2022_10_06_011344_add_key_to_products.php b/database/migrations/2022_10_06_011344_add_key_to_products.php
index 3b5e03f21566..b45f0d2baee1 100644
--- a/database/migrations/2022_10_06_011344_add_key_to_products.php
+++ b/database/migrations/2022_10_06_011344_add_key_to_products.php
@@ -4,8 +4,7 @@ use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
-return new class extends Migration
-{
+return new class extends Migration {
/**
* Run the migrations.
*
@@ -26,7 +25,6 @@ return new class extends Migration
Schema::table('accounts', function (Blueprint $table) {
$table->index('key');
});
-
}
/**
@@ -36,6 +34,5 @@ return new class extends Migration
*/
public function down()
{
-
}
};
diff --git a/database/migrations/2022_10_07_065455_add_key_to_company_tokens_table.php b/database/migrations/2022_10_07_065455_add_key_to_company_tokens_table.php
index 4811e76d33f1..9603ff640cd8 100644
--- a/database/migrations/2022_10_07_065455_add_key_to_company_tokens_table.php
+++ b/database/migrations/2022_10_07_065455_add_key_to_company_tokens_table.php
@@ -4,8 +4,7 @@ use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
-return new class extends Migration
-{
+return new class extends Migration {
/**
* Run the migrations.
*
@@ -25,6 +24,5 @@ return new class extends Migration
*/
public function down()
{
-
}
};
diff --git a/database/migrations/2022_10_10_070137_add_documentable_index.php b/database/migrations/2022_10_10_070137_add_documentable_index.php
index c97c96501319..598f50920c3e 100644
--- a/database/migrations/2022_10_10_070137_add_documentable_index.php
+++ b/database/migrations/2022_10_10_070137_add_documentable_index.php
@@ -4,8 +4,7 @@ use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
-return new class extends Migration
-{
+return new class extends Migration {
/**
* Run the migrations.
*
@@ -13,24 +12,23 @@ return new class extends Migration
*/
public function up()
{
- Schema::table('documents', function (Blueprint $table) {
+ Schema::table('documents', function (Blueprint $table) {
$table->index(['documentable_id', 'documentable_type', 'deleted_at']);
- });
+ });
- Schema::table('expenses', function (Blueprint $table) {
+ Schema::table('expenses', function (Blueprint $table) {
$table->index(['invoice_id', 'deleted_at']);
- });
+ });
- Schema::table('company_tokens', function (Blueprint $table) {
+ Schema::table('company_tokens', function (Blueprint $table) {
$table->dropIndex('company_tokens_token_index');
$table->index(['token','deleted_at']);
- });
+ });
- Schema::table('invoice_invitations', function (Blueprint $table) {
+ Schema::table('invoice_invitations', function (Blueprint $table) {
$table->dropIndex('invoice_invitations_key_index');
$table->index(['key','deleted_at']);
- });
-
+ });
}
/**
diff --git a/database/migrations/2022_10_27_044909_add_user_sms_verification_code.php b/database/migrations/2022_10_27_044909_add_user_sms_verification_code.php
index b0dcaa823b9d..f16ebe910ff8 100644
--- a/database/migrations/2022_10_27_044909_add_user_sms_verification_code.php
+++ b/database/migrations/2022_10_27_044909_add_user_sms_verification_code.php
@@ -4,8 +4,7 @@ use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
-return new class extends Migration
-{
+return new class extends Migration {
/**
* Run the migrations.
*
@@ -13,7 +12,7 @@ return new class extends Migration
*/
public function up()
{
- Schema::table('users', function (Blueprint $table) {
+ Schema::table('users', function (Blueprint $table) {
$table->string('sms_verification_code', 191)->nullable();
});
}
diff --git a/database/migrations/2022_11_02_063742_add_verified_number_flag_to_users_table.php b/database/migrations/2022_11_02_063742_add_verified_number_flag_to_users_table.php
index 432a13c19744..91f35f7926da 100644
--- a/database/migrations/2022_11_02_063742_add_verified_number_flag_to_users_table.php
+++ b/database/migrations/2022_11_02_063742_add_verified_number_flag_to_users_table.php
@@ -4,8 +4,7 @@ use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
-return new class extends Migration
-{
+return new class extends Migration {
/**
* Run the migrations.
*
diff --git a/database/migrations/2022_11_04_013539_disabled_upstream_bank_integrations_table.php b/database/migrations/2022_11_04_013539_disabled_upstream_bank_integrations_table.php
index 736de042740d..868c9002dee7 100644
--- a/database/migrations/2022_11_04_013539_disabled_upstream_bank_integrations_table.php
+++ b/database/migrations/2022_11_04_013539_disabled_upstream_bank_integrations_table.php
@@ -4,8 +4,7 @@ use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
-return new class extends Migration
-{
+return new class extends Migration {
/**
* Run the migrations.
*
@@ -13,11 +12,9 @@ return new class extends Migration
*/
public function up()
{
-
Schema::table('bank_integrations', function (Blueprint $table) {
$table->boolean('disabled_upstream')->default(false);
});
-
}
/**
diff --git a/database/migrations/2022_11_06_215526_drop_html_backups_column_from_backups_table.php b/database/migrations/2022_11_06_215526_drop_html_backups_column_from_backups_table.php
index 9f35d53dddce..f2e1bfea3feb 100644
--- a/database/migrations/2022_11_06_215526_drop_html_backups_column_from_backups_table.php
+++ b/database/migrations/2022_11_06_215526_drop_html_backups_column_from_backups_table.php
@@ -1,13 +1,10 @@
dropColumn('html_backup');
});
}
@@ -31,8 +25,6 @@ return new class extends Migration
Schema::table('bank_integrations', function (Blueprint $table) {
$table->boolean('auto_sync')->default(false);
});
-
-
}
/**
diff --git a/database/migrations/2022_11_13_034143_bank_transaction_rules_table.php b/database/migrations/2022_11_13_034143_bank_transaction_rules_table.php
index 7609d1a7d3fd..1ea4e59c9ee3 100644
--- a/database/migrations/2022_11_13_034143_bank_transaction_rules_table.php
+++ b/database/migrations/2022_11_13_034143_bank_transaction_rules_table.php
@@ -4,8 +4,7 @@ use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
-return new class extends Migration
-{
+return new class extends Migration {
/**
* Run the migrations.
*
@@ -13,7 +12,6 @@ return new class extends Migration
*/
public function up()
{
-
Schema::create('bank_transaction_rules', function (Blueprint $table) {
$table->id();
$table->unsignedInteger('company_id');
@@ -21,7 +19,7 @@ return new class extends Migration
$table->string('name'); //name of rule
$table->mediumText('rules')->nullable(); //array of rule objects
- $table->boolean('auto_convert')->default(false); //auto convert to match
+ $table->boolean('auto_convert')->default(false); //auto convert to match
$table->boolean('matches_on_all')->default(false); //match on all rules or just one
$table->string('applies_to')->default('CREDIT'); //CREDIT/DEBIT
@@ -36,8 +34,6 @@ return new class extends Migration
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade')->onUpdate('cascade');
$table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade')->onUpdate('cascade');
});
-
-
}
/**
diff --git a/database/migrations/2022_11_16_093535_calmness_design.php b/database/migrations/2022_11_16_093535_calmness_design.php
index 898d96549a87..895bfa3bef94 100644
--- a/database/migrations/2022_11_16_093535_calmness_design.php
+++ b/database/migrations/2022_11_16_093535_calmness_design.php
@@ -1,14 +1,10 @@
boolean('invoice_task_lock')->default(false);
$table->boolean('use_vendor_currency')->default(false);
});
- Schema::table('purchase_orders', function (Blueprint $table)
- {
+ Schema::table('purchase_orders', function (Blueprint $table) {
$table->unsignedInteger('currency_id')->nullable();
});
- Schema::table('bank_transactions', function (Blueprint $table)
- {
+ Schema::table('bank_transactions', function (Blueprint $table) {
$table->bigInteger('bank_transaction_rule_id')->nullable();
});
- Schema::table('subscriptions', function (Blueprint $table)
- {
+ Schema::table('subscriptions', function (Blueprint $table) {
$table->boolean('registration_required')->default(false);
$table->boolean('use_inventory_management')->default(false);
$table->text('optional_product_ids')->nullable();
$table->text('optional_recurring_product_ids')->nullable();
-
});
$currencies = [
@@ -69,8 +62,6 @@ return new class extends Migration
\Illuminate\Support\Facades\Artisan::call('ninja:design-update');
$this->buildCache(true);
-
-
}
/**
diff --git a/database/migrations/2022_11_30_063229_add_payment_id_to_bank_transaction_table.php b/database/migrations/2022_11_30_063229_add_payment_id_to_bank_transaction_table.php
index 08547668ebfa..affa8ec6ff57 100644
--- a/database/migrations/2022_11_30_063229_add_payment_id_to_bank_transaction_table.php
+++ b/database/migrations/2022_11_30_063229_add_payment_id_to_bank_transaction_table.php
@@ -5,9 +5,7 @@ use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
-return new class extends Migration
-{
-
+return new class extends Migration {
use AppSetup;
/**
@@ -24,7 +22,6 @@ return new class extends Migration
\Illuminate\Support\Facades\Artisan::call('ninja:design-update');
$this->buildCache(true);
-
}
/**
@@ -34,6 +31,5 @@ return new class extends Migration
*/
public function down()
{
-
}
};
diff --git a/database/migrations/2022_12_07_024625_add_properties_to_companies_table.php b/database/migrations/2022_12_07_024625_add_properties_to_companies_table.php
index 78336ab3e2a8..3f3abd3eda0a 100644
--- a/database/migrations/2022_12_07_024625_add_properties_to_companies_table.php
+++ b/database/migrations/2022_12_07_024625_add_properties_to_companies_table.php
@@ -4,8 +4,7 @@ use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
-return new class extends Migration
-{
+return new class extends Migration {
/**
* Run the migrations.
*
@@ -26,6 +25,5 @@ return new class extends Migration
*/
public function down()
{
-
}
};
diff --git a/database/migrations/2022_12_20_063038_set_proforma_invoice_type.php b/database/migrations/2022_12_20_063038_set_proforma_invoice_type.php
index 28dae37d58a9..dc28a0db225b 100644
--- a/database/migrations/2022_12_20_063038_set_proforma_invoice_type.php
+++ b/database/migrations/2022_12_20_063038_set_proforma_invoice_type.php
@@ -4,8 +4,7 @@ use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
-return new class extends Migration
-{
+return new class extends Migration {
/**
* Run the migrations.
*
@@ -13,17 +12,13 @@ return new class extends Migration
*/
public function up()
{
-
- Schema::table('companies', function (Blueprint $table)
- {
+ Schema::table('companies', function (Blueprint $table) {
$table->boolean('notify_vendor_when_paid')->default(false);
});
- Schema::table('invoices', function (Blueprint $table)
- {
+ Schema::table('invoices', function (Blueprint $table) {
$table->boolean('is_proforma')->default(false);
});
-
}
/**
diff --git a/database/migrations/2023_01_12_125540_set_auto_bill_on_regular_invoice_setting.php b/database/migrations/2023_01_12_125540_set_auto_bill_on_regular_invoice_setting.php
index fade7d7ad3f4..5bbfc72610dd 100644
--- a/database/migrations/2023_01_12_125540_set_auto_bill_on_regular_invoice_setting.php
+++ b/database/migrations/2023_01_12_125540_set_auto_bill_on_regular_invoice_setting.php
@@ -4,8 +4,7 @@ use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
-return new class extends Migration
-{
+return new class extends Migration {
/**
* Run the migrations.
*
@@ -13,20 +12,15 @@ return new class extends Migration
*/
public function up()
{
-
- Schema::table('accounts', function (Blueprint $table)
- {
+ Schema::table('accounts', function (Blueprint $table) {
$table->boolean('is_trial')->default(false);
});
- Schema::table('companies', function (Blueprint $table)
- {
+ Schema::table('companies', function (Blueprint $table) {
$table->boolean('invoice_task_hours')->default(false);
});
- Schema::table('schedulers', function (Blueprint $table)
- {
-
+ Schema::table('schedulers', function (Blueprint $table) {
$table->dropColumn('repeat_every');
$table->dropColumn('start_from');
$table->dropColumn('scheduled_run');
@@ -34,13 +28,10 @@ return new class extends Migration
$table->dropColumn('action_class');
$table->dropColumn('paused');
$table->dropColumn('company_id');
-
});
- Schema::table('schedulers', function (Blueprint $table)
- {
-
+ Schema::table('schedulers', function (Blueprint $table) {
$table->unsignedInteger('company_id');
$table->boolean('is_paused')->default(false);
$table->unsignedInteger('frequency_id')->nullable();
@@ -54,9 +45,7 @@ return new class extends Migration
$table->unique(['company_id', 'name']);
$table->index(['company_id', 'deleted_at']);
-
});
-
}
/**
diff --git a/database/migrations/2023_01_27_023127_update_design_templates.php b/database/migrations/2023_01_27_023127_update_design_templates.php
index f0f45d4a4bb2..9b6265db822b 100644
--- a/database/migrations/2023_01_27_023127_update_design_templates.php
+++ b/database/migrations/2023_01_27_023127_update_design_templates.php
@@ -1,11 +1,8 @@
boolean('require_custom_value1')->default(false);
$table->boolean('require_custom_value2')->default(false);
$table->boolean('require_custom_value3')->default(false);
$table->boolean('require_custom_value4')->default(false);
-
});
-
}
/**
diff --git a/database/migrations/2023_02_07_114011_add_additional_product_fields.php b/database/migrations/2023_02_07_114011_add_additional_product_fields.php
index 55f3e701666d..038927e3045b 100644
--- a/database/migrations/2023_02_07_114011_add_additional_product_fields.php
+++ b/database/migrations/2023_02_07_114011_add_additional_product_fields.php
@@ -5,8 +5,7 @@ use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
-return new class extends Migration
-{
+return new class extends Migration {
/**
* Run the migrations.
*
@@ -14,26 +13,20 @@ return new class extends Migration
*/
public function up()
{
- Schema::table('products', function (Blueprint $table){
+ Schema::table('products', function (Blueprint $table) {
$table->unsignedInteger("max_quantity")->nullable();
$table->string("product_image", 191)->nullable();
});
Company::query()
->chunk(1000, function ($companies) {
-
- foreach($companies as $c)
- {
-
- $settings = $c->settings;
- $settings->font_size = 16;
- $c->settings = $settings;
- $c->save();
-
- }
-
- });
-
+ foreach ($companies as $c) {
+ $settings = $c->settings;
+ $settings->font_size = 16;
+ $c->settings = $settings;
+ $c->save();
+ }
+ });
}
/**
diff --git a/database/migrations/2023_02_14_064135_create_react_settings_column_company_user_table.php b/database/migrations/2023_02_14_064135_create_react_settings_column_company_user_table.php
index 281b7d8e4c9d..a763630ffbf8 100644
--- a/database/migrations/2023_02_14_064135_create_react_settings_column_company_user_table.php
+++ b/database/migrations/2023_02_14_064135_create_react_settings_column_company_user_table.php
@@ -4,8 +4,7 @@ use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
-return new class extends Migration
-{
+return new class extends Migration {
/**
* Run the migrations.
*
@@ -14,11 +13,9 @@ return new class extends Migration
public function up()
{
Schema::table('company_user', function (Blueprint $table) {
-
$table->mediumText('react_settings')->nullable();
\Illuminate\Support\Facades\Artisan::call('ninja:design-update');
-
});
}
@@ -29,6 +26,5 @@ return new class extends Migration
*/
public function down()
{
-
}
};
diff --git a/database/seeders/LanguageSeeder.php b/database/seeders/LanguageSeeder.php
index fdb6e5f07e06..1291b915014e 100644
--- a/database/seeders/LanguageSeeder.php
+++ b/database/seeders/LanguageSeeder.php
@@ -69,39 +69,29 @@ class LanguageSeeder extends Seeder
}
}
- if(!Language::find(33)) {
-
+ if (!Language::find(33)) {
$serbian = ['id' => 33, 'name' => 'Serbian', 'locale' => 'sr'];
Language::create($serbian);
-
}
- if(!Language::find(34)) {
-
+ if (!Language::find(34)) {
$slovak = ['id' => 34, 'name' => 'Slovak', 'locale' => 'sk'];
Language::create($slovak);
-
}
- if(!Language::find(35)) {
-
+ if (!Language::find(35)) {
$estonia = ['id' => 35, 'name' => 'Estonian', 'locale' => 'et'];
Language::create($estonia);
-
}
- if(!Language::find(36)) {
-
+ if (!Language::find(36)) {
$bulgarian = ['id' => 36, 'name' => 'Bulgarian', 'locale' => 'bg'];
Language::create($bulgarian);
-
}
- if(!Language::find(37)) {
-
+ if (!Language::find(37)) {
$hebrew = ['id' => 37, 'name' => 'Hebrew', 'locale' => 'he'];
Language::create($hebrew);
-
}
}
}
diff --git a/database/seeders/PaymentLibrariesSeeder.php b/database/seeders/PaymentLibrariesSeeder.php
index a62240ed6779..b7420fb8c4ee 100644
--- a/database/seeders/PaymentLibrariesSeeder.php
+++ b/database/seeders/PaymentLibrariesSeeder.php
@@ -6,7 +6,7 @@
*
* @copyright Copyright (c) 2021. Invoice Ninja LLC (https://invoiceninja.com)
*
- * @license https://www.elastic.co/licensing/elastic-license
+ * @license https://www.elastic.co/licensing/elastic-license
*/
namespace Database\Seeders;
diff --git a/database/seeders/RandomDataSeeder.php b/database/seeders/RandomDataSeeder.php
index 0659acb5eee6..50a6e5318d1f 100644
--- a/database/seeders/RandomDataSeeder.php
+++ b/database/seeders/RandomDataSeeder.php
@@ -54,7 +54,6 @@ class RandomDataSeeder extends Seeder
*/
public function run()
{
-
/* Warm up the cache !*/
$cached_tables = config('ninja.cached_tables');
@@ -209,7 +208,6 @@ class RandomDataSeeder extends Seeder
$credit->save();
$credit->service()->createInvitations()->markSent()->save();
-
});
/* Recurring Invoice Factory */
diff --git a/lang/ar/texts.php b/lang/ar/texts.php
index 4b3ae06c598f..2e86a79024ce 100644
--- a/lang/ar/texts.php
+++ b/lang/ar/texts.php
@@ -1,6 +1,6 @@
'الشركة ',
'name' => 'الاسم',
'website' => 'الموقع الإلكتروني',
@@ -4928,7 +4928,7 @@ $LANG = array(
'export_company' => 'Create company backup',
'backup' => 'Backup',
'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.',
- 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
+ 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor',
'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.',
'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.',
@@ -4943,8 +4943,6 @@ $LANG = array(
'matomo_url' => 'Matomo URL',
'matomo_id' => 'Matomo Id',
'action_add_to_invoice' => 'Add To Invoice',
-);
+];
return $LANG;
-
-?>
diff --git a/lang/bg/texts.php b/lang/bg/texts.php
index 8e9622e1e121..31d24cf5083f 100644
--- a/lang/bg/texts.php
+++ b/lang/bg/texts.php
@@ -1,6 +1,6 @@
'Организация',
'name' => 'Име',
'website' => 'Уебсайт',
@@ -4908,7 +4908,7 @@ $LANG = array(
'export_company' => 'Create company backup',
'backup' => 'Backup',
'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.',
- 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
+ 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor',
'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.',
'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.',
@@ -4923,8 +4923,6 @@ $LANG = array(
'matomo_url' => 'Matomo URL',
'matomo_id' => 'Matomo Id',
'action_add_to_invoice' => 'Add To Invoice',
-);
+];
return $LANG;
-
-?>
diff --git a/lang/ca/texts.php b/lang/ca/texts.php
index 9e39dc34fb69..3f06d96fc406 100644
--- a/lang/ca/texts.php
+++ b/lang/ca/texts.php
@@ -1,6 +1,6 @@
'Organització',
'name' => 'Nom',
'website' => 'Lloc web',
@@ -4902,7 +4902,7 @@ $LANG = array(
'export_company' => 'Create company backup',
'backup' => 'Backup',
'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.',
- 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
+ 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor',
'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.',
'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.',
@@ -4917,8 +4917,6 @@ $LANG = array(
'matomo_url' => 'Matomo URL',
'matomo_id' => 'Matomo Id',
'action_add_to_invoice' => 'Add To Invoice',
-);
+];
return $LANG;
-
-?>
diff --git a/lang/cs/texts.php b/lang/cs/texts.php
index 404b630dacf4..446f800cbf99 100644
--- a/lang/cs/texts.php
+++ b/lang/cs/texts.php
@@ -1,6 +1,6 @@
'Organizace',
'name' => 'Název',
'website' => 'Stránky',
@@ -4907,7 +4907,7 @@ $LANG = array(
'export_company' => 'Create company backup',
'backup' => 'Backup',
'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.',
- 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
+ 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor',
'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.',
'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.',
@@ -4922,8 +4922,6 @@ $LANG = array(
'matomo_url' => 'Matomo URL',
'matomo_id' => 'Matomo Id',
'action_add_to_invoice' => 'Add To Invoice',
-);
+];
return $LANG;
-
-?>
diff --git a/lang/da/texts.php b/lang/da/texts.php
index a60ae3cbb627..5c16f1d3781f 100644
--- a/lang/da/texts.php
+++ b/lang/da/texts.php
@@ -1,6 +1,6 @@
'Organisation',
'name' => 'Navn',
'website' => 'Hjemmeside',
@@ -4906,7 +4906,7 @@ $LANG = array(
'export_company' => 'Create company backup',
'backup' => 'Backup',
'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.',
- 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
+ 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor',
'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.',
'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.',
@@ -4921,8 +4921,6 @@ $LANG = array(
'matomo_url' => 'Matomo URL',
'matomo_id' => 'Matomo Id',
'action_add_to_invoice' => 'Add To Invoice',
-);
+];
return $LANG;
-
-?>
diff --git a/lang/de/texts.php b/lang/de/texts.php
index 381e9cea0a71..b7e30c8ae3fa 100644
--- a/lang/de/texts.php
+++ b/lang/de/texts.php
@@ -1,6 +1,6 @@
'Unternehmen',
'name' => 'Name',
'website' => 'Webseite',
@@ -4910,7 +4910,7 @@ https://invoiceninja.github.io/docs/migration/#troubleshooting',
'export_company' => 'Unternehmens Sicherungskopie erstellen',
'backup' => 'Sicherungskopie',
'notification_purchase_order_created_body' => 'Die folgende Bestellung :purchase_order wurde für den Lieferant :vendor in Höhe von :amount erstellt.',
- 'notification_purchase_order_created_subject' => 'Bestellung :purchase_order wurde für :vendor erstellt',
+ 'notification_purchase_order_created_subject' => 'Bestellung :purchase_order wurde für :vendor erstellt',
'notification_purchase_order_sent_subject' => 'Bestellung :purchase_order wurde an :vendor gesendet',
'notification_purchase_order_sent' => 'Der folgende Lieferant :vendor hat eine Bestellung :purchase_order über :amount erhalten.',
'subscription_blocked' => 'Dieses Produkt ist ein eingeschränkter Artikel, bitte kontaktieren Sie den Lieferant für weitere Informationen.',
@@ -4925,8 +4925,6 @@ https://invoiceninja.github.io/docs/migration/#troubleshooting',
'matomo_url' => 'Matomo URL',
'matomo_id' => 'Matomo ID',
'action_add_to_invoice' => 'Zur Rechnung hinzufügen',
-);
+];
return $LANG;
-
-?>
diff --git a/lang/el/texts.php b/lang/el/texts.php
index 1bfb24ce4651..7571fbe703e9 100644
--- a/lang/el/texts.php
+++ b/lang/el/texts.php
@@ -1,6 +1,6 @@
'Οργανισμός',
'name' => 'Επωνυμία',
'website' => 'Ιστοσελίδα',
@@ -4907,7 +4907,7 @@ email που είναι συνδεδεμένη με το λογαριασμό σ
'export_company' => 'Create company backup',
'backup' => 'Backup',
'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.',
- 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
+ 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor',
'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.',
'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.',
@@ -4922,8 +4922,6 @@ email που είναι συνδεδεμένη με το λογαριασμό σ
'matomo_url' => 'Matomo URL',
'matomo_id' => 'Matomo Id',
'action_add_to_invoice' => 'Add To Invoice',
-);
+];
return $LANG;
-
-?>
diff --git a/lang/en/texts.php b/lang/en/texts.php
index dd851787bb5b..7c3a28af4e1b 100644
--- a/lang/en/texts.php
+++ b/lang/en/texts.php
@@ -1,6 +1,6 @@
'Organization',
'name' => 'Name',
'website' => 'Website',
@@ -4908,7 +4908,7 @@ $LANG = array(
'export_company' => 'Create company backup',
'backup' => 'Backup',
'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.',
- 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
+ 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor',
'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.',
'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.',
@@ -4953,9 +4953,7 @@ $LANG = array(
'markup' => 'Markup',
'unlock_pro' => 'Unlock Pro',
'preferences' => 'Preferences'
-);
+];
return $LANG;
-
-?>
diff --git a/lang/en_GB/texts.php b/lang/en_GB/texts.php
index 1fd6dfc5ab52..b80c6e368524 100644
--- a/lang/en_GB/texts.php
+++ b/lang/en_GB/texts.php
@@ -1,6 +1,6 @@
'Organisation',
'name' => 'Name',
'website' => 'Website',
@@ -4908,7 +4908,7 @@ $LANG = array(
'export_company' => 'Create company backup',
'backup' => 'Backup',
'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.',
- 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
+ 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor',
'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.',
'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.',
@@ -4923,8 +4923,6 @@ $LANG = array(
'matomo_url' => 'Matomo URL',
'matomo_id' => 'Matomo Id',
'action_add_to_invoice' => 'Add To Invoice',
-);
+];
return $LANG;
-
-?>
diff --git a/lang/es/texts.php b/lang/es/texts.php
index a18ee8e23f15..0e0f21b7528e 100644
--- a/lang/es/texts.php
+++ b/lang/es/texts.php
@@ -1,6 +1,6 @@
'Empresa',
'name' => 'Nombre',
'website' => 'Sitio Web',
@@ -4905,7 +4905,7 @@ $LANG = array(
'export_company' => 'Create company backup',
'backup' => 'Backup',
'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.',
- 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
+ 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor',
'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.',
'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.',
@@ -4920,8 +4920,6 @@ $LANG = array(
'matomo_url' => 'Matomo URL',
'matomo_id' => 'Matomo Id',
'action_add_to_invoice' => 'Add To Invoice',
-);
+];
return $LANG;
-
-?>
diff --git a/lang/es_ES/texts.php b/lang/es_ES/texts.php
index b959d47b5cdc..8c7291c928a4 100644
--- a/lang/es_ES/texts.php
+++ b/lang/es_ES/texts.php
@@ -1,6 +1,6 @@
'Organización',
'name' => 'Nombre',
'website' => 'Página Web',
@@ -4897,7 +4897,7 @@ Una vez que tenga los montos, vuelva a esta página de métodos de pago y haga c
'export_company' => 'Create company backup',
'backup' => 'Backup',
'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.',
- 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
+ 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor',
'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.',
'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.',
@@ -4912,8 +4912,6 @@ Una vez que tenga los montos, vuelva a esta página de métodos de pago y haga c
'matomo_url' => 'Matomo URL',
'matomo_id' => 'Matomo Id',
'action_add_to_invoice' => 'Add To Invoice',
-);
+];
return $LANG;
-
-?>
diff --git a/lang/et/texts.php b/lang/et/texts.php
index 5dd80f4aaf79..10cf428ab5ac 100644
--- a/lang/et/texts.php
+++ b/lang/et/texts.php
@@ -1,6 +1,6 @@
'Organisatsioon',
'name' => 'Nimi',
'website' => 'Kodulehekülg',
@@ -4904,7 +4904,7 @@ $LANG = array(
'export_company' => 'Create company backup',
'backup' => 'Backup',
'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.',
- 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
+ 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor',
'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.',
'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.',
@@ -4919,8 +4919,6 @@ $LANG = array(
'matomo_url' => 'Matomo URL',
'matomo_id' => 'Matomo Id',
'action_add_to_invoice' => 'Add To Invoice',
-);
+];
return $LANG;
-
-?>
diff --git a/lang/fa/texts.php b/lang/fa/texts.php
index 84cc31cb375f..4fee58be66bf 100644
--- a/lang/fa/texts.php
+++ b/lang/fa/texts.php
@@ -1,6 +1,6 @@
'شرکت',
'name' => 'نام',
'website' => 'وب سایت',
@@ -4907,7 +4907,7 @@ $LANG = array(
'export_company' => 'Create company backup',
'backup' => 'Backup',
'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.',
- 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
+ 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor',
'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.',
'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.',
@@ -4922,8 +4922,6 @@ $LANG = array(
'matomo_url' => 'Matomo URL',
'matomo_id' => 'Matomo Id',
'action_add_to_invoice' => 'Add To Invoice',
-);
+];
return $LANG;
-
-?>
diff --git a/lang/fi/texts.php b/lang/fi/texts.php
index e67bedc21ea6..054e25d770f7 100644
--- a/lang/fi/texts.php
+++ b/lang/fi/texts.php
@@ -1,6 +1,6 @@
'Yritys',
'name' => 'Nimi',
'website' => 'Kotisivu',
@@ -4907,7 +4907,7 @@ $LANG = array(
'export_company' => 'Create company backup',
'backup' => 'Backup',
'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.',
- 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
+ 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor',
'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.',
'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.',
@@ -4922,8 +4922,6 @@ $LANG = array(
'matomo_url' => 'Matomo URL',
'matomo_id' => 'Matomo Id',
'action_add_to_invoice' => 'Add To Invoice',
-);
+];
return $LANG;
-
-?>
diff --git a/lang/fr/texts.php b/lang/fr/texts.php
index 878c9bd0ba1e..725d4ce3be54 100644
--- a/lang/fr/texts.php
+++ b/lang/fr/texts.php
@@ -1,6 +1,6 @@
'Entreprise',
'name' => 'Nom',
'website' => 'Site Web',
@@ -4901,7 +4901,7 @@ Lorsque les montant apparaîtront sur votre relevé, veuillez revenir sur cette
'export_company' => 'Create company backup',
'backup' => 'Backup',
'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.',
- 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
+ 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor',
'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.',
'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.',
@@ -4916,8 +4916,6 @@ Lorsque les montant apparaîtront sur votre relevé, veuillez revenir sur cette
'matomo_url' => 'Matomo URL',
'matomo_id' => 'Matomo Id',
'action_add_to_invoice' => 'Add To Invoice',
-);
+];
return $LANG;
-
-?>
diff --git a/lang/fr_CA/texts.php b/lang/fr_CA/texts.php
index 804f48a5789c..e245a41271a9 100644
--- a/lang/fr_CA/texts.php
+++ b/lang/fr_CA/texts.php
@@ -1,6 +1,6 @@
'Entreprise',
'name' => 'Nom',
'website' => 'Site web',
@@ -4899,7 +4899,7 @@ Lorsque les montant apparaîtront sur votre relevé, veuillez revenir sur cette
'export_company' => 'Create company backup',
'backup' => 'Backup',
'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.',
- 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
+ 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor',
'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.',
'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.',
@@ -4914,8 +4914,6 @@ Lorsque les montant apparaîtront sur votre relevé, veuillez revenir sur cette
'matomo_url' => 'Matomo URL',
'matomo_id' => 'Matomo Id',
'action_add_to_invoice' => 'Add To Invoice',
-);
+];
return $LANG;
-
-?>
diff --git a/lang/he/texts.php b/lang/he/texts.php
index 6123bb15ed35..02b0f4cfe7c4 100644
--- a/lang/he/texts.php
+++ b/lang/he/texts.php
@@ -1,6 +1,6 @@
'ארגון ',
'name' => 'שם',
'website' => 'אתר אינטרנט',
@@ -4900,7 +4900,7 @@ $LANG = array(
'export_company' => 'Create company backup',
'backup' => 'Backup',
'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.',
- 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
+ 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor',
'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.',
'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.',
@@ -4915,8 +4915,6 @@ $LANG = array(
'matomo_url' => 'Matomo URL',
'matomo_id' => 'Matomo Id',
'action_add_to_invoice' => 'Add To Invoice',
-);
+];
return $LANG;
-
-?>
diff --git a/lang/hr/texts.php b/lang/hr/texts.php
index 94925e687748..d4663611e631 100644
--- a/lang/hr/texts.php
+++ b/lang/hr/texts.php
@@ -1,6 +1,6 @@
'Organizacija',
'name' => 'Ime',
'website' => 'Web',
@@ -4908,7 +4908,7 @@ Nevažeći kontakt email',
'export_company' => 'Create company backup',
'backup' => 'Backup',
'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.',
- 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
+ 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor',
'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.',
'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.',
@@ -4923,8 +4923,6 @@ Nevažeći kontakt email',
'matomo_url' => 'Matomo URL',
'matomo_id' => 'Matomo Id',
'action_add_to_invoice' => 'Add To Invoice',
-);
+];
return $LANG;
-
-?>
diff --git a/lang/it/texts.php b/lang/it/texts.php
index d81634c2da4a..7a1e91f8a7f1 100644
--- a/lang/it/texts.php
+++ b/lang/it/texts.php
@@ -1,6 +1,6 @@
'Organizzazione',
'name' => 'Nome',
'website' => 'Sito web',
@@ -4910,7 +4910,7 @@ $LANG = array(
'export_company' => 'Create company backup',
'backup' => 'Backup',
'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.',
- 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
+ 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor',
'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.',
'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.',
@@ -4925,8 +4925,6 @@ $LANG = array(
'matomo_url' => 'Matomo URL',
'matomo_id' => 'Matomo Id',
'action_add_to_invoice' => 'Add To Invoice',
-);
+];
return $LANG;
-
-?>
diff --git a/lang/ja/texts.php b/lang/ja/texts.php
index 355d911f93dd..0a0bc3b1a8bf 100644
--- a/lang/ja/texts.php
+++ b/lang/ja/texts.php
@@ -1,6 +1,6 @@
'組織',
'name' => '名前',
'website' => 'WEBサイト',
@@ -4907,7 +4907,7 @@ $LANG = array(
'export_company' => 'Create company backup',
'backup' => 'Backup',
'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.',
- 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
+ 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor',
'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.',
'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.',
@@ -4922,8 +4922,6 @@ $LANG = array(
'matomo_url' => 'Matomo URL',
'matomo_id' => 'Matomo Id',
'action_add_to_invoice' => 'Add To Invoice',
-);
+];
return $LANG;
-
-?>
diff --git a/lang/lt/texts.php b/lang/lt/texts.php
index 9d105ef6a0ae..b423f3b5dc93 100644
--- a/lang/lt/texts.php
+++ b/lang/lt/texts.php
@@ -1,6 +1,6 @@
'Įmonė',
'name' => 'Pavadinimas',
'website' => 'Internetinis puslapis',
@@ -4907,7 +4907,7 @@ $LANG = array(
'export_company' => 'Create company backup',
'backup' => 'Backup',
'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.',
- 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
+ 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor',
'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.',
'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.',
@@ -4922,8 +4922,6 @@ $LANG = array(
'matomo_url' => 'Matomo URL',
'matomo_id' => 'Matomo Id',
'action_add_to_invoice' => 'Add To Invoice',
-);
+];
return $LANG;
-
-?>
diff --git a/lang/lv_LV/texts.php b/lang/lv_LV/texts.php
index 9d41588662a0..05a407bbc9f8 100644
--- a/lang/lv_LV/texts.php
+++ b/lang/lv_LV/texts.php
@@ -1,6 +1,6 @@
'Uzņēmums',
'name' => 'Nosaukums',
'website' => 'Mājas lapa',
@@ -4907,7 +4907,7 @@ $LANG = array(
'export_company' => 'Create company backup',
'backup' => 'Backup',
'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.',
- 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
+ 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor',
'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.',
'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.',
@@ -4922,8 +4922,6 @@ $LANG = array(
'matomo_url' => 'Matomo URL',
'matomo_id' => 'Matomo Id',
'action_add_to_invoice' => 'Add To Invoice',
-);
+];
return $LANG;
-
-?>
diff --git a/lang/mk_MK/texts.php b/lang/mk_MK/texts.php
index badd60d36290..57403832dbe3 100644
--- a/lang/mk_MK/texts.php
+++ b/lang/mk_MK/texts.php
@@ -1,6 +1,6 @@
'Организација',
'name' => 'Име',
'website' => 'Веб Страна',
@@ -4908,7 +4908,7 @@ $LANG = array(
'export_company' => 'Create company backup',
'backup' => 'Backup',
'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.',
- 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
+ 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor',
'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.',
'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.',
@@ -4923,8 +4923,6 @@ $LANG = array(
'matomo_url' => 'Matomo URL',
'matomo_id' => 'Matomo Id',
'action_add_to_invoice' => 'Add To Invoice',
-);
+];
return $LANG;
-
-?>
diff --git a/lang/nb_NO/texts.php b/lang/nb_NO/texts.php
index 269677f60fb3..df957da11864 100644
--- a/lang/nb_NO/texts.php
+++ b/lang/nb_NO/texts.php
@@ -1,6 +1,6 @@
'Organisasjon',
'name' => 'Navn',
'website' => 'Nettside',
@@ -4907,7 +4907,7 @@ $LANG = array(
'export_company' => 'Create company backup',
'backup' => 'Backup',
'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.',
- 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
+ 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor',
'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.',
'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.',
@@ -4922,8 +4922,6 @@ $LANG = array(
'matomo_url' => 'Matomo URL',
'matomo_id' => 'Matomo Id',
'action_add_to_invoice' => 'Add To Invoice',
-);
+];
return $LANG;
-
-?>
diff --git a/lang/nl/texts.php b/lang/nl/texts.php
index e29db171503e..be0baa4481e7 100644
--- a/lang/nl/texts.php
+++ b/lang/nl/texts.php
@@ -1,6 +1,6 @@
'Organisatie',
'name' => 'Naam',
'website' => 'Website',
@@ -4901,7 +4901,7 @@ Email: :email
',
'export_company' => 'Create company backup',
'backup' => 'Backup',
'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.',
- 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
+ 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor',
'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.',
'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.',
@@ -4916,8 +4916,6 @@ Email: :email
',
'matomo_url' => 'Matomo URL',
'matomo_id' => 'Matomo Id',
'action_add_to_invoice' => 'Add To Invoice',
-);
+];
return $LANG;
-
-?>
diff --git a/lang/pl/texts.php b/lang/pl/texts.php
index c8f67fa6af42..7ab9092c514e 100644
--- a/lang/pl/texts.php
+++ b/lang/pl/texts.php
@@ -1,6 +1,6 @@
'Organizacja',
'name' => 'Nazwa',
'website' => 'Strona internetowa',
@@ -4904,7 +4904,7 @@ Gdy przelewy zostaną zaksięgowane na Twoim koncie, wróć do tej strony i klik
'export_company' => 'Create company backup',
'backup' => 'Backup',
'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.',
- 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
+ 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor',
'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.',
'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.',
@@ -4919,8 +4919,6 @@ Gdy przelewy zostaną zaksięgowane na Twoim koncie, wróć do tej strony i klik
'matomo_url' => 'Matomo URL',
'matomo_id' => 'Matomo Id',
'action_add_to_invoice' => 'Add To Invoice',
-);
+];
return $LANG;
-
-?>
diff --git a/lang/pt_BR/texts.php b/lang/pt_BR/texts.php
index 2a29da257d31..f811c6d2e50f 100644
--- a/lang/pt_BR/texts.php
+++ b/lang/pt_BR/texts.php
@@ -1,6 +1,6 @@
'Empresa',
'name' => 'Nome',
'website' => 'Website',
@@ -4901,7 +4901,7 @@ Quando tiver as quantias, volte a esta página de formas de pagamento e clique "
'export_company' => 'Create company backup',
'backup' => 'Backup',
'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.',
- 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
+ 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor',
'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.',
'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.',
@@ -4916,8 +4916,6 @@ Quando tiver as quantias, volte a esta página de formas de pagamento e clique "
'matomo_url' => 'Matomo URL',
'matomo_id' => 'Matomo Id',
'action_add_to_invoice' => 'Add To Invoice',
-);
+];
return $LANG;
-
-?>
diff --git a/lang/pt_PT/texts.php b/lang/pt_PT/texts.php
index 51cedad607cd..04b9ee53db8e 100644
--- a/lang/pt_PT/texts.php
+++ b/lang/pt_PT/texts.php
@@ -1,6 +1,6 @@
'Organização',
'name' => 'Nome',
'website' => 'Site',
@@ -4904,7 +4904,7 @@ O envio de E-mails foi suspenso. Será retomado às 23:00 UTC.',
'export_company' => 'Create company backup',
'backup' => 'Backup',
'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.',
- 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
+ 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor',
'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.',
'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.',
@@ -4919,8 +4919,6 @@ O envio de E-mails foi suspenso. Será retomado às 23:00 UTC.',
'matomo_url' => 'Matomo URL',
'matomo_id' => 'Matomo Id',
'action_add_to_invoice' => 'Add To Invoice',
-);
+];
return $LANG;
-
-?>
diff --git a/lang/ro/texts.php b/lang/ro/texts.php
index ba7f1abd0f33..13da5b986dea 100644
--- a/lang/ro/texts.php
+++ b/lang/ro/texts.php
@@ -1,6 +1,6 @@
'Organizație',
'name' => 'Nume',
'website' => 'Site web',
@@ -4911,7 +4911,7 @@ Odată ce sumele au ajuns la dumneavoastră, reveniți la pagina cu metode de pl
'export_company' => 'Create company backup',
'backup' => 'Backup',
'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.',
- 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
+ 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor',
'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.',
'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.',
@@ -4926,8 +4926,6 @@ Odată ce sumele au ajuns la dumneavoastră, reveniți la pagina cu metode de pl
'matomo_url' => 'Matomo URL',
'matomo_id' => 'Matomo Id',
'action_add_to_invoice' => 'Add To Invoice',
-);
+];
return $LANG;
-
-?>
diff --git a/lang/ru_RU/texts.php b/lang/ru_RU/texts.php
index 6ef760e6c3be..ac6debf474c2 100644
--- a/lang/ru_RU/texts.php
+++ b/lang/ru_RU/texts.php
@@ -1,6 +1,6 @@
'Организация',
'name' => 'Название',
'website' => 'Веб-сайт',
@@ -4908,7 +4908,7 @@ $LANG = array(
'export_company' => 'Create company backup',
'backup' => 'Backup',
'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.',
- 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
+ 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor',
'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.',
'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.',
@@ -4923,8 +4923,6 @@ $LANG = array(
'matomo_url' => 'Matomo URL',
'matomo_id' => 'Matomo Id',
'action_add_to_invoice' => 'Add To Invoice',
-);
+];
return $LANG;
-
-?>
diff --git a/lang/sk/texts.php b/lang/sk/texts.php
index 7851b7ede3f5..a2cc7a2f484b 100644
--- a/lang/sk/texts.php
+++ b/lang/sk/texts.php
@@ -1,6 +1,6 @@
'Organizácia',
'name' => 'Meno',
'website' => 'Web',
@@ -4904,7 +4904,7 @@ Nemôžete nájsť faktúru? Potrebujete poradiť? Radi Vám pomôžeme
'export_company' => 'Create company backup',
'backup' => 'Backup',
'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.',
- 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
+ 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor',
'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.',
'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.',
@@ -4919,8 +4919,6 @@ Nemôžete nájsť faktúru? Potrebujete poradiť? Radi Vám pomôžeme
'matomo_url' => 'Matomo URL',
'matomo_id' => 'Matomo Id',
'action_add_to_invoice' => 'Add To Invoice',
-);
+];
return $LANG;
-
-?>
diff --git a/lang/sl/texts.php b/lang/sl/texts.php
index ca8f29c41e2b..4fbe1f212289 100644
--- a/lang/sl/texts.php
+++ b/lang/sl/texts.php
@@ -1,6 +1,6 @@
'Organizacija',
'name' => 'Ime',
'website' => 'Spletna stran',
@@ -4907,7 +4907,7 @@ Ko imate zneske, se vrnite na to stran plačilnega sredstva in kliknite na "Comp
'export_company' => 'Create company backup',
'backup' => 'Backup',
'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.',
- 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
+ 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor',
'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.',
'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.',
@@ -4922,8 +4922,6 @@ Ko imate zneske, se vrnite na to stran plačilnega sredstva in kliknite na "Comp
'matomo_url' => 'Matomo URL',
'matomo_id' => 'Matomo Id',
'action_add_to_invoice' => 'Add To Invoice',
-);
+];
return $LANG;
-
-?>
diff --git a/lang/sq/texts.php b/lang/sq/texts.php
index f49b00457bd9..16281bfa0e96 100644
--- a/lang/sq/texts.php
+++ b/lang/sq/texts.php
@@ -1,6 +1,6 @@
'Organizata',
'name' => 'Emri',
'website' => 'Website',
@@ -4905,7 +4905,7 @@ Pasi të keni pranuar shumat, kthehuni në faqen e metodave të pagesës dhe kli
'export_company' => 'Create company backup',
'backup' => 'Backup',
'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.',
- 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
+ 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor',
'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.',
'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.',
@@ -4920,8 +4920,6 @@ Pasi të keni pranuar shumat, kthehuni në faqen e metodave të pagesës dhe kli
'matomo_url' => 'Matomo URL',
'matomo_id' => 'Matomo Id',
'action_add_to_invoice' => 'Add To Invoice',
-);
+];
return $LANG;
-
-?>
diff --git a/lang/sr/texts.php b/lang/sr/texts.php
index f0eb40e2673f..fb06a089b0a9 100644
--- a/lang/sr/texts.php
+++ b/lang/sr/texts.php
@@ -1,6 +1,6 @@
'Organizacija',
'name' => 'Ime',
'website' => 'Sajt',
@@ -4907,7 +4907,7 @@ Kada budete imali iznose, vratite se na ovu stranicu sa načinima plaćanja i k
'export_company' => 'Create company backup',
'backup' => 'Backup',
'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.',
- 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
+ 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor',
'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.',
'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.',
@@ -4922,8 +4922,6 @@ Kada budete imali iznose, vratite se na ovu stranicu sa načinima plaćanja i k
'matomo_url' => 'Matomo URL',
'matomo_id' => 'Matomo Id',
'action_add_to_invoice' => 'Add To Invoice',
-);
+];
return $LANG;
-
-?>
diff --git a/lang/sv/texts.php b/lang/sv/texts.php
index e12083139bc9..67d8904f8ce4 100644
--- a/lang/sv/texts.php
+++ b/lang/sv/texts.php
@@ -1,6 +1,6 @@
'Organisation',
'name' => 'Namn',
'website' => 'Hemsida',
@@ -4914,7 +4914,7 @@ Den här funktionen kräver att en produkt skapas och en betalningsgateway är k
'export_company' => 'Create company backup',
'backup' => 'Backup',
'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.',
- 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
+ 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor',
'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.',
'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.',
@@ -4929,8 +4929,6 @@ Den här funktionen kräver att en produkt skapas och en betalningsgateway är k
'matomo_url' => 'Matomo URL',
'matomo_id' => 'Matomo Id',
'action_add_to_invoice' => 'Add To Invoice',
-);
+];
return $LANG;
-
-?>
diff --git a/lang/th/texts.php b/lang/th/texts.php
index 27a7a7242b3c..d99ca1899cda 100644
--- a/lang/th/texts.php
+++ b/lang/th/texts.php
@@ -1,6 +1,6 @@
'องค์กร',
'name' => 'ชื่อ',
'website' => 'เว็บไซต์',
@@ -4908,7 +4908,7 @@ $LANG = array(
'export_company' => 'Create company backup',
'backup' => 'Backup',
'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.',
- 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
+ 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor',
'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.',
'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.',
@@ -4923,8 +4923,6 @@ $LANG = array(
'matomo_url' => 'Matomo URL',
'matomo_id' => 'Matomo Id',
'action_add_to_invoice' => 'Add To Invoice',
-);
+];
return $LANG;
-
-?>
diff --git a/lang/tr_TR/texts.php b/lang/tr_TR/texts.php
index 70774aab0f52..e21b3b289a05 100644
--- a/lang/tr_TR/texts.php
+++ b/lang/tr_TR/texts.php
@@ -1,6 +1,6 @@
'Şirket',
'name' => 'Ünvan',
'website' => 'Web adresi',
@@ -4906,7 +4906,7 @@ adresine gönderildi. Müthiş tüm özelliklerin kilidini açmak için lütfen
'export_company' => 'Create company backup',
'backup' => 'Backup',
'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.',
- 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
+ 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor',
'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.',
'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.',
@@ -4921,8 +4921,6 @@ adresine gönderildi. Müthiş tüm özelliklerin kilidini açmak için lütfen
'matomo_url' => 'Matomo URL',
'matomo_id' => 'Matomo Id',
'action_add_to_invoice' => 'Add To Invoice',
-);
+];
return $LANG;
-
-?>
diff --git a/lang/zh_TW/texts.php b/lang/zh_TW/texts.php
index 75522b696149..cc073088e541 100644
--- a/lang/zh_TW/texts.php
+++ b/lang/zh_TW/texts.php
@@ -1,6 +1,6 @@
'組織',
'name' => '姓名',
'website' => '網站',
@@ -4904,7 +4904,7 @@ $LANG = array(
'export_company' => 'Create company backup',
'backup' => 'Backup',
'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.',
- 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
+ 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor',
'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor',
'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.',
'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.',
@@ -4919,8 +4919,6 @@ $LANG = array(
'matomo_url' => 'Matomo URL',
'matomo_id' => 'Matomo Id',
'action_add_to_invoice' => 'Add To Invoice',
-);
+];
return $LANG;
-
-?>
diff --git a/preload.php b/preload.php
index 6bf7ece52e44..f7a8f68a76c7 100644
--- a/preload.php
+++ b/preload.php
@@ -133,4 +133,4 @@ class Preloader
\Illuminate\Http\UploadedFile::class,
\Illuminate\Support\Carbon::class,
)
- ->load();
\ No newline at end of file
+ ->load();
diff --git a/routes/api.php b/routes/api.php
index b3c52da44482..7b2809a7a472 100644
--- a/routes/api.php
+++ b/routes/api.php
@@ -14,10 +14,10 @@ use App\Http\Controllers\AccountController;
use App\Http\Controllers\ActivityController;
use App\Http\Controllers\Auth\ForgotPasswordController;
use App\Http\Controllers\Auth\LoginController;
+use App\Http\Controllers\Bank\YodleeController;
use App\Http\Controllers\BankIntegrationController;
use App\Http\Controllers\BankTransactionController;
use App\Http\Controllers\BankTransactionRuleController;
-use App\Http\Controllers\Bank\YodleeController;
use App\Http\Controllers\BaseController;
use App\Http\Controllers\ChartController;
use App\Http\Controllers\ClientController;
@@ -350,7 +350,6 @@ Route::group(['middleware' => ['throttle:300,1', 'api_db', 'token_auth', 'locale
Route::post('subscriptions/bulk', [SubscriptionController::class, 'bulk'])->name('subscriptions.bulk');
Route::get('statics', StaticController::class);
// Route::post('apple_pay/upload_file','ApplyPayController::class, 'upload');
-
});
Route::post('api/v1/sms_reset', [TwilioController::class, 'generate2faResetCode'])->name('sms_reset.generate')->middleware('throttle:10,1');
@@ -376,4 +375,4 @@ Route::post('api/v1/yodlee/data_updates', [YodleeController::class, 'dataUpdates
Route::post('api/v1/yodlee/refresh_updates', [YodleeController::class, 'refreshUpdatesWebhook'])->middleware('throttle:100,1');
Route::post('api/v1/yodlee/balance', [YodleeController::class, 'balanceWebhook'])->middleware('throttle:100,1');
-Route::fallback([BaseController::class, 'notFound']);
\ No newline at end of file
+Route::fallback([BaseController::class, 'notFound']);
diff --git a/routes/client.php b/routes/client.php
index c02a23cb26a3..b77efaf61c7b 100644
--- a/routes/client.php
+++ b/routes/client.php
@@ -5,7 +5,6 @@ use App\Http\Controllers\Auth\ContactLoginController;
use App\Http\Controllers\Auth\ContactRegisterController;
use App\Http\Controllers\Auth\ContactResetPasswordController;
use App\Http\Controllers\BaseController;
-use App\Http\Controllers\ClientPortal\DocumentController;
use App\Http\Controllers\ClientPortal\PaymentMethodController;
use App\Http\Controllers\ClientPortal\SubscriptionController;
use App\Http\Controllers\ClientPortal\TaskController;
@@ -45,7 +44,6 @@ Route::get('client/ninja/{contact_key}/{company_key}', [App\Http\Controllers\Cli
Route::post('client/ninja/trial_confirmation', [App\Http\Controllers\ClientPortal\NinjaPlanController::class, 'trial_confirmation'])->name('client.trial.response')->middleware(['domain_db']);
Route::group(['middleware' => ['auth:contact', 'locale', 'domain_db','check_client_existence'], 'prefix' => 'client', 'as' => 'client.'], function () {
-
Route::get('dashboard', [App\Http\Controllers\ClientPortal\DashboardController::class, 'index'])->name('dashboard'); // name = (dashboard. index / create / show / update / destroy / edit
Route::get('plan', [App\Http\Controllers\ClientPortal\NinjaPlanController::class, 'plan'])->name('plan'); // name = (dashboard. index / create / show / update / destroy / edit
@@ -109,7 +107,6 @@ Route::group(['middleware' => ['auth:contact', 'locale', 'domain_db','check_clie
Route::post('upload', App\Http\Controllers\ClientPortal\UploadController::class)->name('upload.store');
Route::get('logout', [ContactLoginController::class, 'logout'])->name('logout');
-
});
Route::post('payments/process/response', [App\Http\Controllers\ClientPortal\PaymentController::class, 'response'])->name('client.payments.response')->middleware(['locale', 'domain_db', 'verify_hash']);
@@ -133,9 +130,8 @@ Route::group(['middleware' => ['invite_db'], 'prefix' => 'client', 'as' => 'clie
Route::get('pay/{invitation_key}', [App\Http\Controllers\ClientPortal\InvitationController::class, 'payInvoice'])->name('pay.invoice');
Route::get('unsubscribe/{entity}/{invitation_key}', [App\Http\Controllers\ClientPortal\InvitationController::class, 'unsubscribe'])->name('unsubscribe');
-
});
Route::get('phantom/{entity}/{invitation_key}', [Phantom::class, 'displayInvitation'])->middleware(['invite_db', 'phantom_secret'])->name('phantom_view');
-Route::fallback([BaseController::class, 'notFoundClient']);
\ No newline at end of file
+Route::fallback([BaseController::class, 'notFoundClient']);
diff --git a/routes/web.php b/routes/web.php
index 26ddc312bec6..2a47d1bf4cde 100644
--- a/routes/web.php
+++ b/routes/web.php
@@ -18,7 +18,7 @@ use Illuminate\Support\Facades\Route;
//Auth::routes(['password.reset' => false]);
Route::get('/', [BaseController::class, 'flutterRoute'])->middleware('guest');
- // Route::get('self-update', [SelfUpdateController::class, 'update'])->middleware('guest');
+// Route::get('self-update', [SelfUpdateController::class, 'update'])->middleware('guest');
Route::get('setup', [SetupController::class, 'index'])->middleware('guest');
Route::post('setup', [SetupController::class, 'doSetup'])->middleware('guest');
@@ -58,4 +58,4 @@ Route::get('yodlee/onboard/{token}', [YodleeController::class, 'auth'])->name('y
Route::get('checkout/3ds_redirect/{company_key}/{company_gateway_id}/{hash}', [Checkout3dsController::class, 'index'])->middleware('domain_db')->name('checkout.3ds_redirect');
Route::get('mollie/3ds_redirect/{company_key}/{company_gateway_id}/{hash}', [Mollie3dsController::class, 'index'])->middleware('domain_db')->name('mollie.3ds_redirect');
Route::get('gocardless/ibp_redirect/{company_key}/{company_gateway_id}/{hash}', [GoCardlessController::class, 'ibpRedirect'])->middleware('domain_db')->name('gocardless.ibp_redirect');
-Route::get('.well-known/apple-developer-merchantid-domain-association', [ApplePayDomainController::class, 'showAppleMerchantId']);
\ No newline at end of file
+Route::get('.well-known/apple-developer-merchantid-domain-association', [ApplePayDomainController::class, 'showAppleMerchantId']);
diff --git a/tests/Browser/ClientPortal/Gateways/Braintree/ACHTest.php b/tests/Browser/ClientPortal/Gateways/Braintree/ACHTest.php
index e884e63ed64c..580eb4cf95eb 100644
--- a/tests/Browser/ClientPortal/Gateways/Braintree/ACHTest.php
+++ b/tests/Browser/ClientPortal/Gateways/Braintree/ACHTest.php
@@ -6,7 +6,6 @@ use App\DataMapper\FeesAndLimits;
use App\Models\Company;
use App\Models\CompanyGateway;
use App\Models\GatewayType;
-use Illuminate\Foundation\Testing\DatabaseMigrations;
use Laravel\Dusk\Browser;
use Tests\Browser\Pages\ClientPortal\Login;
use Tests\DuskTestCase;
diff --git a/tests/Browser/ClientPortal/Gateways/Braintree/CreditCardTest.php b/tests/Browser/ClientPortal/Gateways/Braintree/CreditCardTest.php
index ef125ab77981..9dc3fdb5a72c 100644
--- a/tests/Browser/ClientPortal/Gateways/Braintree/CreditCardTest.php
+++ b/tests/Browser/ClientPortal/Gateways/Braintree/CreditCardTest.php
@@ -16,7 +16,6 @@ use App\DataMapper\FeesAndLimits;
use App\Models\Company;
use App\Models\CompanyGateway;
use App\Models\GatewayType;
-use App\Models\Invoice;
use Laravel\Dusk\Browser;
use Tests\Browser\Pages\ClientPortal\Login;
use Tests\DuskTestCase;
diff --git a/tests/Browser/ClientPortal/Gateways/Stripe/AlipayTest.php b/tests/Browser/ClientPortal/Gateways/Stripe/AlipayTest.php
index 68f7435ce425..b58545eb3a7d 100644
--- a/tests/Browser/ClientPortal/Gateways/Stripe/AlipayTest.php
+++ b/tests/Browser/ClientPortal/Gateways/Stripe/AlipayTest.php
@@ -16,7 +16,6 @@ use App\DataMapper\FeesAndLimits;
use App\Models\Client;
use App\Models\CompanyGateway;
use App\Models\GatewayType;
-use Illuminate\Foundation\Testing\DatabaseMigrations;
use Laravel\Dusk\Browser;
use Tests\Browser\Pages\ClientPortal\Login;
use Tests\DuskTestCase;
diff --git a/tests/Browser/ClientPortal/LoginTest.php b/tests/Browser/ClientPortal/LoginTest.php
index 407e2f3c2999..e8934b6b6574 100644
--- a/tests/Browser/ClientPortal/LoginTest.php
+++ b/tests/Browser/ClientPortal/LoginTest.php
@@ -12,7 +12,6 @@
namespace Tests\Browser\ClientPortal;
-use Illuminate\Foundation\Testing\DatabaseMigrations;
use Laravel\Dusk\Browser;
use Tests\DuskTestCase;
diff --git a/tests/Browser/ClientPortal/QuotesTest.php b/tests/Browser/ClientPortal/QuotesTest.php
index b05c8992f506..ce4b024fe8fb 100644
--- a/tests/Browser/ClientPortal/QuotesTest.php
+++ b/tests/Browser/ClientPortal/QuotesTest.php
@@ -12,7 +12,6 @@
namespace Tests\Browser\ClientPortal;
-use App\Models\Quote;
use Laravel\Dusk\Browser;
use Tests\Browser\Pages\ClientPortal\Login;
use Tests\DuskTestCase;
diff --git a/tests/DuskTestCase.php b/tests/DuskTestCase.php
index 7521085d9880..590eaa3eb96b 100644
--- a/tests/DuskTestCase.php
+++ b/tests/DuskTestCase.php
@@ -44,7 +44,8 @@ abstract class DuskTestCase extends BaseTestCase
return RemoteWebDriver::create(
$_ENV['DUSK_DRIVER_URL'] ?? 'http://localhost:9515',
DesiredCapabilities::chrome()->setCapability(
- ChromeOptions::CAPABILITY, $options
+ ChromeOptions::CAPABILITY,
+ $options
)
);
}
diff --git a/tests/Feature/Account/AccountEmailQuotaTest.php b/tests/Feature/Account/AccountEmailQuotaTest.php
index 408a33754c95..0ddd3142a3c5 100644
--- a/tests/Feature/Account/AccountEmailQuotaTest.php
+++ b/tests/Feature/Account/AccountEmailQuotaTest.php
@@ -18,13 +18,10 @@ use App\Models\Account;
use App\Models\Company;
use App\Utils\Ninja;
use Illuminate\Support\Facades\Cache;
-use Livewire\Livewire;
-use Tests\MockAccountData;
use Tests\TestCase;
class AccountEmailQuotaTest extends TestCase
{
-
protected function setUp(): void
{
parent::setUp();
@@ -33,7 +30,6 @@ class AccountEmailQuotaTest extends TestCase
public function testIfQuotaBreached()
{
-
config([
'ninja.production' => true
]);
@@ -92,12 +88,10 @@ class AccountEmailQuotaTest extends TestCase
$this->assertTrue($account->emailQuotaExceeded());
Cache::forget('123ifyouknowwhatimean');
-
}
public function testQuotaValidRule()
{
-
$account = Account::factory()->create([
'hosted_client_count' => 1000,
'hosted_company_count' => 1000,
@@ -115,7 +109,6 @@ class AccountEmailQuotaTest extends TestCase
$this->assertFalse($account->emailQuotaExceeded());
Cache::forget('123ifyouknowwhatimean');
-
}
public function testEmailSentCount()
@@ -140,7 +133,5 @@ class AccountEmailQuotaTest extends TestCase
$this->assertEquals(3000, $count);
Cache::forget('123ifyouknowwhatimean');
-
}
-
}
diff --git a/tests/Feature/ActivityApiTest.php b/tests/Feature/ActivityApiTest.php
index 115bed1732fc..271b54d2ad0c 100644
--- a/tests/Feature/ActivityApiTest.php
+++ b/tests/Feature/ActivityApiTest.php
@@ -55,5 +55,4 @@ class ActivityApiTest extends TestCase
$response->assertStatus(200);
}
-
}
diff --git a/tests/Feature/ApplePayDomainMerchantUrlTest.php b/tests/Feature/ApplePayDomainMerchantUrlTest.php
index 8082bd3f131a..173d007bda2e 100644
--- a/tests/Feature/ApplePayDomainMerchantUrlTest.php
+++ b/tests/Feature/ApplePayDomainMerchantUrlTest.php
@@ -40,7 +40,7 @@ class ApplePayDomainMerchantUrlTest extends TestCase
public function testMerchantFieldGet()
{
// if (! config('ninja.testvars.stripe')) {
- $this->markTestSkipped('Skip test no company gateways installed');
+ $this->markTestSkipped('Skip test no company gateways installed');
// }
$config = new \stdClass;
diff --git a/tests/Feature/Bank/BankTransactionRuleTest.php b/tests/Feature/Bank/BankTransactionRuleTest.php
index f6a1051d968c..7c014d5ba206 100644
--- a/tests/Feature/Bank/BankTransactionRuleTest.php
+++ b/tests/Feature/Bank/BankTransactionRuleTest.php
@@ -12,13 +12,9 @@
namespace Tests\Feature\Bank;
-use App\Factory\BankIntegrationFactory;
-use App\Factory\BankTransactionFactory;
use App\Models\BankIntegration;
use App\Models\BankTransaction;
use App\Models\BankTransactionRule;
-use App\Models\Invoice;
-use App\Services\Bank\ProcessBankRules;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Validation\ValidationException;
use Tests\MockAccountData;
@@ -44,15 +40,12 @@ class BankTransactionRuleTest extends TestCase
public function testMatchingWithStripos()
{
-
-
$bt_value = strtolower(str_replace(" ", "", 'hello soldier'));
$rule_value = strtolower(str_replace(" ", "", 'solider'));
$rule_length = iconv_strlen($rule_value);
- $this->assertFalse(stripos($rule_value, $bt_value) !== false);
+ $this->assertFalse(stripos($rule_value, $bt_value) !== false);
$this->assertFalse(stripos($bt_value, $rule_value) !== false);
-
}
public function testBankRuleBulkActions()
@@ -89,12 +82,10 @@ class BankTransactionRuleTest extends TestCase
'X-API-TOKEN' => $this->token,
])->post('/api/v1/bank_transaction_rules/bulk', $data)
->assertStatus(200);
-
}
public function testValidationContainsRule()
{
-
$bi = BankIntegration::factory()->create([
'company_id' => $this->company->id,
'user_id' => $this->user->id,
@@ -126,7 +117,7 @@ class BankTransactionRuleTest extends TestCase
'value' => 'hello',
]
]
- ]);
+ ]);
$bt = $bt->refresh();
@@ -146,7 +137,6 @@ class BankTransactionRuleTest extends TestCase
public function testUpdateValidationRules()
{
-
$br = BankTransactionRule::factory()->create([
'company_id' => $this->company->id,
'user_id' => $this->user->id,
@@ -166,15 +156,15 @@ class BankTransactionRuleTest extends TestCase
$data = [
- "applies_to" => "DEBIT",
- "archived_at" => 0,
- "auto_convert" => False,
- "category_id" => $this->expense_category->hashed_id,
- "is_deleted" => False,
- "isChanged" => True,
- "matches_on_all" => True,
- "name" => "TEST 22",
- "updated_at" => 1669060432,
+ "applies_to" => "DEBIT",
+ "archived_at" => 0,
+ "auto_convert" => false,
+ "category_id" => $this->expense_category->hashed_id,
+ "is_deleted" => false,
+ "isChanged" => true,
+ "matches_on_all" => true,
+ "name" => "TEST 22",
+ "updated_at" => 1669060432,
"vendor_id" => $this->vendor->hashed_id
];
@@ -186,23 +176,20 @@ class BankTransactionRuleTest extends TestCase
'X-API-SECRET' => config('ninja.api_secret'),
'X-API-TOKEN' => $this->token,
])->putJson('/api/v1/bank_transaction_rules/'. $br->hashed_id. '?include=expense_category', $data);
-
} catch (ValidationException $e) {
$message = json_decode($e->validator->getMessageBag(), 1);
nlog($message);
}
- if($response){
+ if ($response) {
$arr = $response->json();
-nlog($arr);
- $response->assertStatus(200);
+ nlog($arr);
+ $response->assertStatus(200);
}
-
}
public function testMatchingBankTransactionExpenseAmountLessThanEqualTo()
{
-
$bi = BankIntegration::factory()->create([
'company_id' => $this->company->id,
'user_id' => $this->user->id,
@@ -250,7 +237,6 @@ nlog($arr);
public function testMatchingBankTransactionExpenseAmountLessThan()
{
-
$br = BankTransactionRule::factory()->create([
'company_id' => $this->company->id,
'user_id' => $this->user->id,
@@ -293,7 +279,6 @@ nlog($arr);
public function testMatchingBankTransactionExpenseAmountGreaterThan()
{
-
$br = BankTransactionRule::factory()->create([
'company_id' => $this->company->id,
'user_id' => $this->user->id,
@@ -337,7 +322,6 @@ nlog($arr);
public function testMatchingBankTransactionExpenseAmountMiss()
{
-
$br = BankTransactionRule::factory()->create([
'company_id' => $this->company->id,
'user_id' => $this->user->id,
@@ -380,7 +364,6 @@ nlog($arr);
public function testMatchingBankTransactionExpenseAmount()
{
-
$br = BankTransactionRule::factory()->create([
'company_id' => $this->company->id,
'user_id' => $this->user->id,
@@ -424,7 +407,6 @@ nlog($arr);
public function testMatchingBankTransactionExpenseIsEmpty()
{
-
$br = BankTransactionRule::factory()->create([
'company_id' => $this->company->id,
'user_id' => $this->user->id,
@@ -468,7 +450,6 @@ nlog($arr);
public function testMatchingBankTransactionExpenseIsEmptyMiss()
{
-
$bi = BankIntegration::factory()->create([
'company_id' => $this->company->id,
'user_id' => $this->user->id,
@@ -515,7 +496,6 @@ nlog($arr);
public function testMatchingBankTransactionExpenseStartsWithMiss()
{
-
$br = BankTransactionRule::factory()->create([
'company_id' => $this->company->id,
'user_id' => $this->user->id,
@@ -560,7 +540,6 @@ nlog($arr);
public function testMatchingBankTransactionExpenseStartsWith()
{
-
$br = BankTransactionRule::factory()->create([
'company_id' => $this->company->id,
'user_id' => $this->user->id,
@@ -603,52 +582,50 @@ nlog($arr);
public function testMatchingBankTransactionExpenseContainsMiss()
- {
+ {
+ $br = BankTransactionRule::factory()->create([
+ 'company_id' => $this->company->id,
+ 'user_id' => $this->user->id,
+ 'matches_on_all' => false,
+ 'auto_convert' => true,
+ 'applies_to' => 'DEBIT',
+ 'client_id' => $this->client->id,
+ 'vendor_id' => $this->vendor->id,
+ 'rules' => [
+ [
+ 'search_key' => 'description',
+ 'operator' => 'contains',
+ 'value' => 'asdddfd',
+ ]
+ ]
+ ]);
- $br = BankTransactionRule::factory()->create([
- 'company_id' => $this->company->id,
- 'user_id' => $this->user->id,
- 'matches_on_all' => false,
- 'auto_convert' => true,
- 'applies_to' => 'DEBIT',
- 'client_id' => $this->client->id,
- 'vendor_id' => $this->vendor->id,
- 'rules' => [
- [
- 'search_key' => 'description',
- 'operator' => 'contains',
- 'value' => 'asdddfd',
- ]
- ]
- ]);
+ $bi = BankIntegration::factory()->create([
+ 'company_id' => $this->company->id,
+ 'user_id' => $this->user->id,
+ 'account_id' => $this->account->id,
+ ]);
- $bi = BankIntegration::factory()->create([
- 'company_id' => $this->company->id,
- 'user_id' => $this->user->id,
- 'account_id' => $this->account->id,
- ]);
-
- $bt = BankTransaction::factory()->create([
- 'bank_integration_id' => $bi->id,
- 'company_id' => $this->company->id,
- 'user_id' => $this->user->id,
- 'description' => 'Something asd bizarre',
- 'base_type' => 'DEBIT',
- 'amount' => 100
- ]);
+ $bt = BankTransaction::factory()->create([
+ 'bank_integration_id' => $bi->id,
+ 'company_id' => $this->company->id,
+ 'user_id' => $this->user->id,
+ 'description' => 'Something asd bizarre',
+ 'base_type' => 'DEBIT',
+ 'amount' => 100
+ ]);
- $bt->service()->processRules();
+ $bt->service()->processRules();
- $bt = $bt->fresh();
+ $bt = $bt->fresh();
- $this->assertNull($bt->expense_id);
- }
+ $this->assertNull($bt->expense_id);
+ }
public function testMatchingBankTransactionExpenseContains()
{
-
$br = BankTransactionRule::factory()->create([
'company_id' => $this->company->id,
'user_id' => $this->user->id,
@@ -691,7 +668,6 @@ nlog($arr);
public function testMatchingBankTransactionExpenseMiss()
{
-
$br = BankTransactionRule::factory()->create([
'company_id' => $this->company->id,
'user_id' => $this->user->id,
@@ -733,7 +709,6 @@ nlog($arr);
public function testMatchingBankTransactionExpense()
{
-
$br = BankTransactionRule::factory()->create([
'company_id' => $this->company->id,
'user_id' => $this->user->id,
@@ -776,7 +751,6 @@ nlog($arr);
public function testMatchingBankTransactionInvoice()
{
-
$this->invoice->number = "MUHMUH";
$this->invoice->save();
@@ -819,7 +793,4 @@ nlog($arr);
$this->assertEquals(BankTransaction::STATUS_MATCHED, $bt->status_id);
}
-
-
-
-}
\ No newline at end of file
+}
diff --git a/tests/Feature/Bank/BankTransactionTest.php b/tests/Feature/Bank/BankTransactionTest.php
index 9be72919ffc8..a2c6157b28b2 100644
--- a/tests/Feature/Bank/BankTransactionTest.php
+++ b/tests/Feature/Bank/BankTransactionTest.php
@@ -24,7 +24,6 @@ use Tests\TestCase;
class BankTransactionTest extends TestCase
{
-
use DatabaseTransactions;
use MockAccountData;
@@ -74,13 +73,10 @@ class BankTransactionTest extends TestCase
'X-API-TOKEN' => $this->token,
])->post('/api/v1/bank_transactions/bulk', $data)
->assertStatus(200);
-
-
}
public function testLinkExpenseToTransaction()
{
-
$data = [];
$bi = BankIntegrationFactory::create($this->company->id, $this->user->id, $this->account->id);
@@ -119,12 +115,10 @@ class BankTransactionTest extends TestCase
$this->assertEquals($bt->refresh()->expense_id, $this->expense->id);
$this->assertEquals($this->vendor->id, $bt->vendor_id);
$this->assertEquals(BankTransaction::STATUS_CONVERTED, $bt->status_id);
-
}
public function testLinkingManuallyPaidInvoices()
{
-
$invoice = InvoiceFactory::create($this->company->id, $this->user->id);
$invoice->client_id = $this->client->id;
$invoice->status_id = Invoice::STATUS_SENT;
@@ -180,13 +174,11 @@ class BankTransactionTest extends TestCase
$this->assertEquals($bt->refresh()->payment_id, $p->id);
$this->assertEquals(BankTransaction::STATUS_CONVERTED, $bt->status_id);
$this->assertEquals($invoice->hashed_id, $bt->invoice_ids);
-
}
public function testLinkPaymentToTransaction()
{
-
$data = [];
$bi = BankIntegrationFactory::create($this->company->id, $this->user->id, $this->account->id);
@@ -221,7 +213,6 @@ class BankTransactionTest extends TestCase
$this->assertEquals($this->payment->refresh()->transaction_id, $bt->id);
$this->assertEquals($bt->refresh()->payment_id, $this->payment->id);
$this->assertEquals(BankTransaction::STATUS_CONVERTED, $bt->status_id);
-
}
@@ -244,10 +235,9 @@ class BankTransactionTest extends TestCase
public function testMatchBankTransactionValidationShouldPass()
{
-
- if (config('ninja.testvars.travis') !== false) {
- $this->markTestSkipped('Skip test for Github Actions');
- }
+ if (config('ninja.testvars.travis') !== false) {
+ $this->markTestSkipped('Skip test for Github Actions');
+ }
$data = [];
@@ -278,5 +268,4 @@ class BankTransactionTest extends TestCase
$response->assertStatus(200);
}
-
-}
\ No newline at end of file
+}
diff --git a/tests/Feature/Bank/YodleeApiTest.php b/tests/Feature/Bank/YodleeApiTest.php
index e586c71519e3..2cbd504c48bc 100644
--- a/tests/Feature/Bank/YodleeApiTest.php
+++ b/tests/Feature/Bank/YodleeApiTest.php
@@ -38,15 +38,13 @@ class YodleeApiTest extends TestCase
parent::setUp();
// if(!config('ninja.yodlee.client_id'))
- $this->markTestSkipped('Skip test no Yodlee API credentials found');
+ $this->markTestSkipped('Skip test no Yodlee API credentials found');
$this->makeTestData();
-
}
public function testExpenseGenerationFromBankFeed()
{
-
$bi = BankIntegrationFactory::create($this->company->id, $this->user->id, $this->account->id);
$bi->save();
@@ -73,7 +71,6 @@ class YodleeApiTest extends TestCase
$this->assertNotNull($expense);
$this->assertEquals(10, (int)$expense->amount);
-
}
public function testIncomeMatchingAndPaymentGeneration()
@@ -148,7 +145,7 @@ class YodleeApiTest extends TestCase
$transactions = $yodlee->getTransactionCategories();
- $this->assertTrue(property_exists($transactions,'transactionCategory'));
+ $this->assertTrue(property_exists($transactions, 'transactionCategory'));
$t = collect($transactions->transactionCategory);
@@ -157,7 +154,6 @@ class YodleeApiTest extends TestCase
$this->assertNotNull($x);
$this->assertEquals('Automotive Expenses', $x->highLevelCategoryName);
-
}
// public function testFunctionalMatching()
@@ -165,7 +161,7 @@ class YodleeApiTest extends TestCase
// $yodlee = new Yodlee('sbMem62e1e69547bfb1');
-// $accounts = $yodlee->getAccounts();
+// $accounts = $yodlee->getAccounts();
// foreach($accounts as $account)
// {
@@ -216,7 +212,6 @@ class YodleeApiTest extends TestCase
public function testDataMatching()
{
-
$transaction = collect([
(object)[
'description' => 'tinkertonkton'
@@ -256,19 +251,14 @@ class YodleeApiTest extends TestCase
$invoice = $transaction->first(function ($value, $key) {
-
return str_contains($value->description, 'tinker');
-
});
$this->assertNotNull($invoice);
-
-
}
public function testYodleeInstance()
{
-
$yodlee = new Yodlee();
$this->assertNotNull($yodlee);
@@ -278,7 +268,6 @@ class YodleeApiTest extends TestCase
public function testAccessTokenGeneration()
{
-
$yodlee = new Yodlee('sbMem62e1e69547bfb1');
$access_token = $yodlee->getAccessToken();
@@ -463,13 +452,11 @@ class YodleeApiTest extends TestCase
public function testGetCategories()
{
-
$yodlee = new Yodlee('sbMem62e1e69547bfb2');
$transactions = $yodlee->getTransactionCategories();
$this->assertIsArray($transactions->transactionCategory);
-
}
@@ -497,7 +484,7 @@ class YodleeApiTest extends TestCase
[includeInNetWorth] => 1
[providerId] => 18769
[providerName] => Dag Site Captcha
- [isManual] =>
+ [isManual] =>
[currentBalance] => stdClass Object
(
[currency] => USD
@@ -541,7 +528,7 @@ class YodleeApiTest extends TestCase
[includeInNetWorth] => 1
[providerId] => 18769
[providerName] => Dag Site Captcha
- [isManual] =>
+ [isManual] =>
[availableBalance] => stdClass Object
(
[currency] => USD
@@ -576,7 +563,6 @@ class YodleeApiTest extends TestCase
*/
public function testGetAccounts()
{
-
$yodlee = new Yodlee('sbMem62e1e69547bfb1');
$accounts = $yodlee->getAccounts();
@@ -612,7 +598,7 @@ class YodleeApiTest extends TestCase
[original] => CHEROKEE NATION TAX TA TAHLEQUAH OK
)
- [isManual] =>
+ [isManual] =>
[sourceType] => AGGREGATED
[date] => 2022-08-03
[transactionDate] => 2022-08-03
@@ -628,23 +614,20 @@ class YodleeApiTest extends TestCase
[checkNumber] => 998
)
-
+
*/
public function testGetTransactions()
{
-
$yodlee = new Yodlee('sbMem62e1e69547bfb1');
$transactions = $yodlee->getTransactions(['categoryId' => 2, 'fromDate' => '2000-01-01']);
$this->assertIsArray($transactions);
-
}
public function testGetTransactionsWithParams()
{
-
$yodlee = new Yodlee('sbMem62e1e69547bfb1');
$data = [
@@ -654,10 +637,8 @@ class YodleeApiTest extends TestCase
'fromDate' => '2000-10-10', /// YYYY-MM-DD
];
- $accounts = $yodlee->getTransactions($data);
+ $accounts = $yodlee->getTransactions($data);
$this->assertIsArray($accounts);
-
}
-
}
diff --git a/tests/Feature/Bank/YodleeBankTransactionTest.php b/tests/Feature/Bank/YodleeBankTransactionTest.php
index dbd56ebffcb9..fb658ed9bb60 100644
--- a/tests/Feature/Bank/YodleeBankTransactionTest.php
+++ b/tests/Feature/Bank/YodleeBankTransactionTest.php
@@ -20,7 +20,6 @@ use Tests\TestCase;
class YodleeBankTransactionTest extends TestCase
{
-
use DatabaseTransactions;
use MockAccountData;
@@ -28,8 +27,9 @@ class YodleeBankTransactionTest extends TestCase
{
parent::setUp();
- if(!config('ninja.yodlee.client_id'))
+ if (!config('ninja.yodlee.client_id')) {
$this->markTestSkipped('Skip test no Yodlee API credentials found');
+ }
$this->makeTestData();
@@ -40,7 +40,6 @@ class YodleeBankTransactionTest extends TestCase
public function testDataMatching1()
{
-
$this->invoice->number = "super-funk-1234";
$this->invoice->save();
@@ -56,32 +55,25 @@ class YodleeBankTransactionTest extends TestCase
BankTransaction::where('company_id', $this->company->id)
->where('status_id', BankTransaction::STATUS_UNMATCHED)
->cursor()
- ->each(function ($bt) use($invoices){
-
- $invoice = $invoices->first(function ($value, $key) use ($bt){
-
- return str_contains($value->number, $bt->description);
-
- });
-
- if($invoice)
- {
- $bt->invoice_ids = $invoice->hashed_id;
- $bt->status_id = BankTransaction::STATUS_MATCHED;
- $bt->save();
- }
+ ->each(function ($bt) use ($invoices) {
+ $invoice = $invoices->first(function ($value, $key) use ($bt) {
+ return str_contains($value->number, $bt->description);
+ });
+ if ($invoice) {
+ $bt->invoice_ids = $invoice->hashed_id;
+ $bt->status_id = BankTransaction::STATUS_MATCHED;
+ $bt->save();
+ }
});
$this->assertTrue(BankTransaction::where('invoice_ids', $this->invoice->hashed_id)->exists());
-
}
public function testDataMatching2()
{
-
$this->invoice->number = "super-funk-1234";
$this->invoice->save();
@@ -97,28 +89,19 @@ class YodleeBankTransactionTest extends TestCase
BankTransaction::where('company_id', $this->company->id)
->where('status_id', BankTransaction::STATUS_UNMATCHED)
->cursor()
- ->each(function ($bt) use($invoices){
-
- $invoice = $invoices->first(function ($value, $key) use ($bt){
-
- return str_contains($value->number, $bt->description);
-
- });
-
- if($invoice)
- {
- $bt->invoice_ids = $invoice->hashed_id;
- $bt->status_id = BankTransaction::STATUS_MATCHED;
- $bt->save();
- }
+ ->each(function ($bt) use ($invoices) {
+ $invoice = $invoices->first(function ($value, $key) use ($bt) {
+ return str_contains($value->number, $bt->description);
+ });
+ if ($invoice) {
+ $bt->invoice_ids = $invoice->hashed_id;
+ $bt->status_id = BankTransaction::STATUS_MATCHED;
+ $bt->save();
+ }
});
$this->assertTrue(BankTransaction::where('invoice_ids', $this->invoice->hashed_id)->exists());
-
}
-
-
-
-}
\ No newline at end of file
+}
diff --git a/tests/Feature/BankIntegrationApiTest.php b/tests/Feature/BankIntegrationApiTest.php
index 13c317ffa74d..fc69c8f8f2f1 100644
--- a/tests/Feature/BankIntegrationApiTest.php
+++ b/tests/Feature/BankIntegrationApiTest.php
@@ -15,7 +15,6 @@ use App\Utils\Traits\MakesHash;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\Session;
-use Illuminate\Validation\ValidationException;
use Tests\MockAccountData;
use Tests\TestCase;
diff --git a/tests/Feature/BankTransactionRuleApiTest.php b/tests/Feature/BankTransactionRuleApiTest.php
index ec38d470c9fc..59edbda2e15b 100644
--- a/tests/Feature/BankTransactionRuleApiTest.php
+++ b/tests/Feature/BankTransactionRuleApiTest.php
@@ -15,7 +15,6 @@ use App\Utils\Traits\MakesHash;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\Session;
-use Illuminate\Validation\ValidationException;
use Tests\MockAccountData;
use Tests\TestCase;
@@ -51,7 +50,7 @@ $rules = [
'applies_to' => 'bail|sometimes|bool',
];
-if(isset($this->category_id))
+if(isset($this->category_id))
$rules['category_id'] = 'bail|sometimes|exists:expense_categories,id,'.auth()->user()->company()->id.',is_deleted,0';
if(isset($this->vendor_id))
@@ -66,8 +65,8 @@ if(isset($this->client_id))
'name' => 'The First Rule',
'rules' => [
[
- "operator" => "contains",
- "search_key" => "description",
+ "operator" => "contains",
+ "search_key" => "description",
"value" => "mobile"
],
],
@@ -105,7 +104,6 @@ if(isset($this->client_id))
public function testBankRulePost()
{
-
$data = [
'name' => 'The First Rule',
'rules' => [],
@@ -124,12 +122,10 @@ if(isset($this->client_id))
$response->assertStatus(200);
$this->assertEquals('The First Rule', $arr['data']['name']);
-
}
public function testBankRulePut()
{
-
$data = [
'name' => 'The First Rule',
'rules' => [],
@@ -167,7 +163,6 @@ if(isset($this->client_id))
$response->assertStatus(200);
$this->assertEquals('A New Name For The First Rule', $arr['data']['name']);
-
}
public function testBankTransactionRuleGet()
diff --git a/tests/Feature/BaseApiTest.php b/tests/Feature/BaseApiTest.php
index 3f3c219ab3e1..75d4ae7f24b4 100644
--- a/tests/Feature/BaseApiTest.php
+++ b/tests/Feature/BaseApiTest.php
@@ -22,7 +22,6 @@ use App\Models\BankTransaction;
use App\Models\BankTransactionRule;
use App\Models\Client;
use App\Models\ClientContact;
-use App\Models\ClientGatewayToken;
use App\Models\Company;
use App\Models\CompanyGateway;
use App\Models\CompanyToken;
@@ -49,7 +48,6 @@ use App\Models\TaxRate;
use App\Models\User;
use App\Models\Vendor;
use App\Models\VendorContact;
-use App\Models\Webhook;
use Illuminate\Routing\Middleware\ThrottleRequests;
use Illuminate\Support\Str;
use Illuminate\Testing\Fluent\AssertableJson;
@@ -382,7 +380,6 @@ class BaseApiTest extends TestCase
$cgt = ClientGatewayTokenFactory::create($company->id);
$cgt->save();
-
}
// public function testGeneratingClassName()
@@ -400,41 +397,38 @@ class BaseApiTest extends TestCase
*/
public function testOwnerRoutes()
{
-
$response = $this->withHeaders([
'X-API-SECRET' => config('ninja.api_secret'),
'X-API-TOKEN' => $this->owner_token,
])->get('/api/v1/users/');
- $response->assertStatus(200)
- ->assertJson(fn (AssertableJson $json) => $json->has('data',2)->etc());
+ $response->assertStatus(200)
+ ->assertJson(fn (AssertableJson $json) => $json->has('data', 2)->etc());
/*does not test the number of records however*/
- collect($this->list_routes)->filter(function ($route){
+ collect($this->list_routes)->filter(function ($route) {
return !in_array($route, ['users','designs','payment_terms']);
- })->each(function($route){
+ })->each(function ($route) {
// nlog($route);
$response = $this->withHeaders([
'X-API-SECRET' => config('ninja.api_secret'),
'X-API-TOKEN' => $this->owner_token,
])->get("/api/v1/{$route}/")
- ->assertJson(fn (AssertableJson $json) =>
+ ->assertJson(
+ fn (AssertableJson $json) =>
$json->has('meta')
- ->has('data',1)
- );
+ ->has('data', 1)
+ );
});
-
}
public function testOwnerAccessCompany()
{
-
$response = $this->withHeaders([
'X-API-SECRET' => config('ninja.api_secret'),
'X-API-TOKEN' => $this->low_token,
])->get('/api/v1/companies/'.$this->company->hashed_id)
->assertStatus(403);
-
}
@@ -445,42 +439,40 @@ class BaseApiTest extends TestCase
$this->owner_cu->is_admin = true;
$this->owner_cu->is_locked = false;
$this->owner_cu->permissions = '[]';
- $this->owner_cu->save();
+ $this->owner_cu->save();
$response = $this->withHeaders([
'X-API-SECRET' => config('ninja.api_secret'),
'X-API-TOKEN' => $this->owner_token,
])->get('/api/v1/users/');
- $response->assertStatus(200)
- ->assertJson(fn (AssertableJson $json) => $json->has('data',2)->etc());
+ $response->assertStatus(200)
+ ->assertJson(fn (AssertableJson $json) => $json->has('data', 2)->etc());
- collect($this->list_routes)->filter(function ($route){
+ collect($this->list_routes)->filter(function ($route) {
return !in_array($route, ['users','designs','payment_terms']);
- })->each(function($route){
+ })->each(function ($route) {
// nlog($route);
$response = $this->withHeaders([
'X-API-SECRET' => config('ninja.api_secret'),
'X-API-TOKEN' => $this->owner_token,
])->get("/api/v1/{$route}/")
->assertStatus(200)
- ->assertJson(fn (AssertableJson $json) =>
+ ->assertJson(
+ fn (AssertableJson $json) =>
$json->has('meta')
- ->has('data',1)
- );
+ ->has('data', 1)
+ );
});
-
}
public function testAdminAccessCompany()
{
-
- $response = $this->withHeaders([
- 'X-API-SECRET' => config('ninja.api_secret'),
- 'X-API-TOKEN' => $this->owner_token,
- ])->get('/api/v1/companies/'.$this->company->hashed_id)
- ->assertStatus(200);
-
+ $response = $this->withHeaders([
+ 'X-API-SECRET' => config('ninja.api_secret'),
+ 'X-API-TOKEN' => $this->owner_token,
+ ])->get('/api/v1/companies/'.$this->company->hashed_id)
+ ->assertStatus(200);
}
public function testAdminLockedRoutes()
@@ -490,7 +482,7 @@ class BaseApiTest extends TestCase
$this->owner_cu->is_admin = true;
$this->owner_cu->is_locked = true;
$this->owner_cu->permissions = '[]';
- $this->owner_cu->save();
+ $this->owner_cu->save();
$response = $this->withHeaders([
'X-API-SECRET' => config('ninja.api_secret'),
@@ -498,9 +490,9 @@ class BaseApiTest extends TestCase
])->get('/api/v1/users/')
->assertStatus(403);
- collect($this->list_routes)->filter(function ($route){
+ collect($this->list_routes)->filter(function ($route) {
return !in_array($route, ['users','designs','payment_terms']);
- })->each(function($route){
+ })->each(function ($route) {
// nlog($route);
$response = $this->withHeaders([
'X-API-SECRET' => config('ninja.api_secret'),
@@ -508,25 +500,22 @@ class BaseApiTest extends TestCase
])->get("/api/v1/{$route}/")
->assertStatus(403);
});
-
}
public function testAdminLockedCompany()
{
-
$this->owner_cu = CompanyUser::where('user_id', $this->owner_cu->user_id)->where('company_id', $this->owner_cu->company_id)->first();
$this->owner_cu->is_owner = false;
$this->owner_cu->is_admin = true;
$this->owner_cu->is_locked = true;
$this->owner_cu->permissions = '[]';
- $this->owner_cu->save();
-
- $response = $this->withHeaders([
- 'X-API-SECRET' => config('ninja.api_secret'),
- 'X-API-TOKEN' => $this->owner_token,
- ])->get('/api/v1/companies/'.$this->company->hashed_id)
- ->assertStatus(403);
+ $this->owner_cu->save();
+ $response = $this->withHeaders([
+ 'X-API-SECRET' => config('ninja.api_secret'),
+ 'X-API-TOKEN' => $this->owner_token,
+ ])->get('/api/v1/companies/'.$this->company->hashed_id)
+ ->assertStatus(403);
}
/**
@@ -534,27 +523,26 @@ class BaseApiTest extends TestCase
*/
public function testRestrictedUserRoute()
{
-
$response = $this->withHeaders([
'X-API-SECRET' => config('ninja.api_secret'),
'X-API-TOKEN' => $this->token,
])->get('/api/v1/tasks/')
->assertStatus(200)
- ->assertJson(fn (AssertableJson $json) => $json->has('data',1)->etc());
+ ->assertJson(fn (AssertableJson $json) => $json->has('data', 1)->etc());
$response = $this->withHeaders([
'X-API-SECRET' => config('ninja.api_secret'),
'X-API-TOKEN' => $this->token,
])->get('/api/v1/group_settings/')
->assertStatus(200)
- ->assertJson(fn (AssertableJson $json) => $json->has('data',2)->etc());
+ ->assertJson(fn (AssertableJson $json) => $json->has('data', 2)->etc());
$response = $this->withHeaders([
'X-API-SECRET' => config('ninja.api_secret'),
'X-API-TOKEN' => $this->token,
])->get('/api/v1/designs/')
->assertStatus(200)
- ->assertJson(fn (AssertableJson $json) => $json->has('data',11)->etc());
+ ->assertJson(fn (AssertableJson $json) => $json->has('data', 11)->etc());
$response = $this->withHeaders([
@@ -562,35 +550,33 @@ class BaseApiTest extends TestCase
'X-API-TOKEN' => $this->low_token,
])->get('/api/v1/users/');
- $response->assertStatus(200)
- ->assertJson(fn (AssertableJson $json) => $json->has('data',1)->etc());
+ $response->assertStatus(200)
+ ->assertJson(fn (AssertableJson $json) => $json->has('data', 1)->etc());
- collect($this->list_routes)->filter(function ($route){
+ collect($this->list_routes)->filter(function ($route) {
return !in_array($route, ['tasks', 'users', 'group_settings','designs','client_gateway_tokens']);
- })->each(function($route){
+ })->each(function ($route) {
$response = $this->withHeaders([
'X-API-SECRET' => config('ninja.api_secret'),
'X-API-TOKEN' => $this->low_token,
])->get("/api/v1/{$route}/")
- ->assertJson(fn (AssertableJson $json) =>
+ ->assertJson(
+ fn (AssertableJson $json) =>
$json->has('meta')
- ->has('data',0)
- );
-
+ ->has('data', 0)
+ );
});
- $response = $this->withHeaders([
- 'X-API-SECRET' => config('ninja.api_secret'),
- 'X-API-TOKEN' => $this->low_token,
- ])->get('/api/v1/companies/'.$this->company->hashed_id)
- ->assertStatus(403);
+ $response = $this->withHeaders([
+ 'X-API-SECRET' => config('ninja.api_secret'),
+ 'X-API-TOKEN' => $this->low_token,
+ ])->get('/api/v1/companies/'.$this->company->hashed_id)
+ ->assertStatus(403);
$response = $this->withHeaders([
'X-API-SECRET' => config('ninja.api_secret'),
'X-API-TOKEN' => $this->low_token,
])->get('/api/v1/client_gateway_tokens/')
->assertStatus(403);
-
}
-
}
diff --git a/tests/Feature/Client/ClientMergeTest.php b/tests/Feature/Client/ClientMergeTest.php
index dc6f1806c43c..ef2c4ae62fd9 100644
--- a/tests/Feature/Client/ClientMergeTest.php
+++ b/tests/Feature/Client/ClientMergeTest.php
@@ -12,19 +12,14 @@
namespace Tests\Feature\Client;
-use App\DataMapper\ClientSettings;
-use App\DataMapper\CompanySettings;
-use App\Http\Livewire\CreditsTable;
use App\Models\Account;
use App\Models\Client;
use App\Models\ClientContact;
use App\Models\Company;
-use App\Models\Credit;
use App\Models\User;
use App\Utils\Traits\AppSetup;
use Faker\Factory;
use Illuminate\Foundation\Testing\DatabaseTransactions;
-use Livewire\Livewire;
use Tests\TestCase;
class ClientMergeTest extends TestCase
diff --git a/tests/Feature/ClientApiTest.php b/tests/Feature/ClientApiTest.php
index 734aa4cef8f0..75bed1b223eb 100644
--- a/tests/Feature/ClientApiTest.php
+++ b/tests/Feature/ClientApiTest.php
@@ -55,13 +55,11 @@ class ClientApiTest extends TestCase
$this->faker = \Faker\Factory::create();
Model::reguard();
-
}
public function testCrossCompanyBulkActionsFail()
{
-
$account = Account::factory()->create([
'hosted_client_count' => 1000,
'hosted_company_count' => 1000,
@@ -122,7 +120,6 @@ class ClientApiTest extends TestCase
$v = $this->app['validator']->make($data, $rules);
$this->assertFalse($v->passes());
-
}
@@ -156,20 +153,17 @@ class ClientApiTest extends TestCase
$data = [
'action' => 'archive',
- 'ids' =>
+ 'ids' =>
$this->client->hashed_id
];
$v = $this->app['validator']->make($data, $rules);
$this->assertFalse($v->passes());
-
-
}
public function testClientStatement()
{
-
$response = null;
$data = [
@@ -195,12 +189,10 @@ class ClientApiTest extends TestCase
$this->assertTrue($response->headers->get('content-type') == 'application/pdf');
$response->assertStatus(200);
-
}
public function testClientStatementEmail()
{
-
$response = null;
$data = [
@@ -228,7 +220,6 @@ class ClientApiTest extends TestCase
$response->assertStatus(200);
-
}
@@ -267,7 +258,7 @@ class ClientApiTest extends TestCase
'currency_id' => '3',
],
'client_hash' => 'xx',
- 'contacts' =>
+ 'contacts' =>
[
[
'first_name' => '',
@@ -280,8 +271,8 @@ class ClientApiTest extends TestCase
'custom_value4' => '',
]
],
- 'country_id' => NULL,
- 'shipping_country_id' => NULL,
+ 'country_id' => null,
+ 'shipping_country_id' => null,
'user_id' => $this->user->id,
];
@@ -298,12 +289,10 @@ class ClientApiTest extends TestCase
$c->refresh();
$this->assertEquals("3", $c->settings->currency_id);
-
}
public function testClientSettingsSave()
{
-
$std = new \stdClass;
$std->entity = 'App\\Models\\Client';
$std->currency_id = 3;
@@ -313,13 +302,11 @@ class ClientApiTest extends TestCase
$this->saveSettings($std, $this->client);
$this->assertTrue(true);
-
}
public function testClientSettingsSave2()
{
-
$std = new \stdClass;
$std->entity = 'App\\Models\\Client';
$std->industry_id = '';
@@ -331,16 +318,14 @@ class ClientApiTest extends TestCase
$this->saveSettings($std, $this->client);
$this->assertTrue(true);
-
}
public function testClientStoreValidation()
{
+ auth()->login($this->user, false);
+ auth()->user()->setCompany($this->company);
- auth()->login($this->user, false);
- auth()->user()->setCompany($this->company);
-
- $data = array (
+ $data = [
'company_id' => $this->company->id,
'name' => 'Christian xx',
'phone' => '',
@@ -366,16 +351,16 @@ class ClientApiTest extends TestCase
'balance' => '0',
'paid_to_date' => '0',
'credit_balance' => 0,
- 'settings' =>
- (object) array(
+ 'settings' =>
+ (object) [
'entity' => 'App\\Models\\Client',
'currency_id' => '3',
- ),
+ ],
'client_hash' => 'xx',
- 'contacts' =>
- array (
- 0 =>
- array (
+ 'contacts' =>
+ [
+ 0 =>
+ [
'first_name' => '',
'last_name' => '',
'email' => '',
@@ -384,12 +369,12 @@ class ClientApiTest extends TestCase
'custom_value2' => '',
'custom_value3' => '',
'custom_value4' => '',
- ),
- ),
- 'country_id' => NULL,
- 'shipping_country_id' => NULL,
+ ],
+ ],
+ 'country_id' => null,
+ 'shipping_country_id' => null,
'user_id' => $this->user->id,
- );
+ ];
$request_name = StoreClientRequest::class;
@@ -409,17 +394,13 @@ class ClientApiTest extends TestCase
$_syn_request_class->setValidator($validator);
$this->assertFalse($validator->fails());
-
-
}
public function testClientImportDataStructure()
{
-
-
- $data = array (
+ $data = [
'company_id' => $this->company->id,
'name' => 'Christian xx',
'phone' => '',
@@ -445,16 +426,16 @@ class ClientApiTest extends TestCase
'balance' => '0',
'paid_to_date' => '0',
'credit_balance' => 0,
- 'settings' =>
- (object) array(
+ 'settings' =>
+ (object) [
'entity' => 'App\\Models\\Client',
'currency_id' => '3',
- ),
+ ],
'client_hash' => 'xx',
- 'contacts' =>
- array (
- 0 =>
- array (
+ 'contacts' =>
+ [
+ 0 =>
+ [
'first_name' => '',
'last_name' => '',
'email' => '',
@@ -463,12 +444,12 @@ class ClientApiTest extends TestCase
'custom_value2' => '',
'custom_value3' => '',
'custom_value4' => '',
- ),
- ),
- 'country_id' => NULL,
- 'shipping_country_id' => NULL,
+ ],
+ ],
+ 'country_id' => null,
+ 'shipping_country_id' => null,
'user_id' => $this->user->id,
- );
+ ];
$crepo = new ClientRepository(new ClientContactRepository());
@@ -481,7 +462,6 @@ class ClientApiTest extends TestCase
public function testClientCsvImport()
{
-
$settings = ClientSettings::defaults();
$settings->currency_id = "840";
@@ -521,8 +501,6 @@ class ClientApiTest extends TestCase
$c = $crepo->save($data, ClientFactory::create($this->company->id, $this->user->id));
$c->saveQuietly();
-
-
}
@@ -815,7 +793,7 @@ class ClientApiTest extends TestCase
$response = false;
- try{
+ try {
$response = $this->withHeaders([
'X-API-TOKEN' => $this->token,
])->post('/api/v1/clients/bulk?action=archive', $data);
@@ -824,7 +802,7 @@ class ClientApiTest extends TestCase
nlog($message);
}
- if($response){
+ if ($response) {
$arr = $response->json();
$this->assertNotNull($arr['data'][0]['archived_at']);
}
@@ -976,6 +954,4 @@ class ClientApiTest extends TestCase
$x = Number::formatValueNoTrailingZeroes(1.50000005, $currency);
$this->assertEquals(1.50000005, $x);
}
-
-
}
diff --git a/tests/Feature/ClientDeletedInvoiceCreationTest.php b/tests/Feature/ClientDeletedInvoiceCreationTest.php
index 4d8f0ef6fa45..20a562514fd0 100644
--- a/tests/Feature/ClientDeletedInvoiceCreationTest.php
+++ b/tests/Feature/ClientDeletedInvoiceCreationTest.php
@@ -11,8 +11,6 @@
namespace Tests\Feature;
-use App\Models\Client;
-use App\Models\ClientContact;
use App\Models\Invoice;
use App\Utils\Traits\MakesHash;
use Illuminate\Database\Eloquent\Model;
diff --git a/tests/Feature/ClientGatewayTokenApiTest.php b/tests/Feature/ClientGatewayTokenApiTest.php
index 196424e7272b..9a7849de06f6 100644
--- a/tests/Feature/ClientGatewayTokenApiTest.php
+++ b/tests/Feature/ClientGatewayTokenApiTest.php
@@ -16,7 +16,6 @@ use App\Models\GatewayType;
use App\Utils\Traits\MakesHash;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Testing\DatabaseTransactions;
-use Illuminate\Support\Facades\Session;
use Tests\MockAccountData;
use Tests\TestCase;
diff --git a/tests/Feature/ClientModelTest.php b/tests/Feature/ClientModelTest.php
index 246e7b27f23e..464f26e4b6bc 100644
--- a/tests/Feature/ClientModelTest.php
+++ b/tests/Feature/ClientModelTest.php
@@ -13,7 +13,6 @@ namespace Tests\Feature;
use App\Models\CompanyGateway;
use Illuminate\Foundation\Testing\DatabaseTransactions;
-use Illuminate\Support\Facades\URL;
use Tests\MockAccountData;
use Tests\TestCase;
diff --git a/tests/Feature/ClientPortal/InvoicesTest.php b/tests/Feature/ClientPortal/InvoicesTest.php
index aa606e1f05d0..11cb71a7b4f9 100644
--- a/tests/Feature/ClientPortal/InvoicesTest.php
+++ b/tests/Feature/ClientPortal/InvoicesTest.php
@@ -12,7 +12,6 @@
namespace Tests\Feature\ClientPortal;
-use App\DataMapper\ClientSettings;
use App\Http\Livewire\InvoicesTable;
use App\Models\Account;
use App\Models\Client;
diff --git a/tests/Feature/ClientTest.php b/tests/Feature/ClientTest.php
index e321b29c6a75..17927bb747fb 100644
--- a/tests/Feature/ClientTest.php
+++ b/tests/Feature/ClientTest.php
@@ -67,13 +67,12 @@ class ClientTest extends TestCase
{
$line_items = [];
- for($x=0; $x<$number; $x++)
- {
+ for ($x=0; $x<$number; $x++) {
$item = InvoiceItemFactory::create();
$item->quantity = 1;
$item->cost = 10;
- $line_items[] = $item;
+ $line_items[] = $item;
}
return $line_items;
diff --git a/tests/Feature/CompanyGatewayApiTest.php b/tests/Feature/CompanyGatewayApiTest.php
index f9764081885e..9af80c664c5f 100644
--- a/tests/Feature/CompanyGatewayApiTest.php
+++ b/tests/Feature/CompanyGatewayApiTest.php
@@ -85,7 +85,6 @@ class CompanyGatewayApiTest extends TestCase
'X-API-TOKEN' => $this->token,
])->post('/api/v1/company_gateways/bulk', $data)
->assertStatus(200);
-
}
@@ -556,6 +555,6 @@ class CompanyGatewayApiTest extends TestCase
$company_gateway = CompanyGateway::find($id);
- $this->assertEquals(1.2, round($company_gateway->calcGatewayFee(10, GatewayType::CREDIT_CARD, true),1));
+ $this->assertEquals(1.2, round($company_gateway->calcGatewayFee(10, GatewayType::CREDIT_CARD, true), 1));
}
}
diff --git a/tests/Feature/CompanyGatewayResolutionTest.php b/tests/Feature/CompanyGatewayResolutionTest.php
index ef294c2b26fc..df01d5614ace 100644
--- a/tests/Feature/CompanyGatewayResolutionTest.php
+++ b/tests/Feature/CompanyGatewayResolutionTest.php
@@ -233,6 +233,6 @@ class CompanyGatewayResolutionTest extends TestCase
$this->cg->save();
$fee = $this->cg->calcGatewayFee(89, GatewayType::CREDIT_CARD, false);
- $this->assertEquals(1.89, round($fee,2));
+ $this->assertEquals(1.89, round($fee, 2));
}
}
diff --git a/tests/Feature/CompanyGatewayTest.php b/tests/Feature/CompanyGatewayTest.php
index ff1ce14afa0a..97118f1f92d3 100644
--- a/tests/Feature/CompanyGatewayTest.php
+++ b/tests/Feature/CompanyGatewayTest.php
@@ -158,7 +158,6 @@ class CompanyGatewayTest extends TestCase
public function testGatewayFeesAreClearedAppropriately()
{
-
$data = [];
$data[1]['min_limit'] = -1;
$data[1]['max_limit'] = -1;
@@ -205,7 +204,6 @@ class CompanyGatewayTest extends TestCase
public function testMarkPaidAdjustsGatewayFeeAppropriately()
{
-
$data = [];
$data[1]['min_limit'] = -1;
$data[1]['max_limit'] = -1;
@@ -248,8 +246,6 @@ class CompanyGatewayTest extends TestCase
$i = Invoice::withTrashed()->find($this->invoice->id);
$this->assertEquals($wiped_balance, $i->amount);
-
-
}
diff --git a/tests/Feature/CompanySettingsTest.php b/tests/Feature/CompanySettingsTest.php
index 9a546d046117..9e65294280ad 100644
--- a/tests/Feature/CompanySettingsTest.php
+++ b/tests/Feature/CompanySettingsTest.php
@@ -6,7 +6,7 @@
*
* @copyright Copyright (c) 2021. Invoice Ninja LLC (https://invoiceninja.com)
*
- * @license https://www.elastic.co/licensing/elastic-license
+ * @license https://www.elastic.co/licensing/elastic-license
*/
namespace Tests\Feature;
@@ -81,10 +81,10 @@ class CompanySettingsTest extends TestCase
$response = false;
try {
- $response = $this->withHeaders([
- 'X-API-SECRET' => config('ninja.api_secret'),
- 'X-API-Token' => $this->token,
- ])->putJson('/api/v1/companies/'.$this->encodePrimaryKey($this->company->id), $this->company->toArray());
+ $response = $this->withHeaders([
+ 'X-API-SECRET' => config('ninja.api_secret'),
+ 'X-API-Token' => $this->token,
+ ])->putJson('/api/v1/companies/'.$this->encodePrimaryKey($this->company->id), $this->company->toArray());
} catch (ValidationException $e) {
$message = json_decode($e->validator->getMessageBag(), 1);
nlog($message);
diff --git a/tests/Feature/CompanyTest.php b/tests/Feature/CompanyTest.php
index 418321dc16bc..a8eb0c8e894c 100644
--- a/tests/Feature/CompanyTest.php
+++ b/tests/Feature/CompanyTest.php
@@ -49,7 +49,6 @@ class CompanyTest extends TestCase
public function testUpdateCompanyPropertyInvoiceTaskHours()
{
-
$company_update = [
'invoice_task_hours' => true
];
@@ -61,9 +60,9 @@ class CompanyTest extends TestCase
->assertStatus(200);
- $arr = $response->json();
+ $arr = $response->json();
- $this->assertTrue($arr['data']['invoice_task_hours']);
+ $this->assertTrue($arr['data']['invoice_task_hours']);
$company_update = [
@@ -77,10 +76,9 @@ class CompanyTest extends TestCase
->assertStatus(200);
- $arr = $response->json();
-
- $this->assertFalse($arr['data']['invoice_task_hours']);
+ $arr = $response->json();
+ $this->assertFalse($arr['data']['invoice_task_hours']);
}
public function testCompanyList()
diff --git a/tests/Feature/CreditTest.php b/tests/Feature/CreditTest.php
index d3118c1f089d..0e830189e813 100644
--- a/tests/Feature/CreditTest.php
+++ b/tests/Feature/CreditTest.php
@@ -53,13 +53,11 @@ class CreditTest extends TestCase
$response->assertStatus(200);
$this->assertTrue($response->headers->get('content-type') == 'application/pdf');
-
}
public function testBulkActions()
{
-
$data = [
'action' => 'archive',
'ids' => [$this->credit->hashed_id]
@@ -92,7 +90,6 @@ class CreditTest extends TestCase
'X-API-TOKEN' => $this->token,
])->post('/api/v1/credits/bulk', $data)
->assertStatus(200);
-
}
diff --git a/tests/Feature/DeleteInvoiceTest.php b/tests/Feature/DeleteInvoiceTest.php
index 8dcf2daf4764..7828aa827dd7 100644
--- a/tests/Feature/DeleteInvoiceTest.php
+++ b/tests/Feature/DeleteInvoiceTest.php
@@ -184,7 +184,6 @@ class DeleteInvoiceTest extends TestCase
$this->assertEquals(6000, $payment->amount);
$this->assertFalse($payment->is_deleted);
$this->assertNull($payment->deleted_at);
-
}
public function testInvoiceDeletionAfterCancellation()
diff --git a/tests/Feature/DesignApiTest.php b/tests/Feature/DesignApiTest.php
index 723596e639b2..dec0cc00bed7 100644
--- a/tests/Feature/DesignApiTest.php
+++ b/tests/Feature/DesignApiTest.php
@@ -46,7 +46,6 @@ class DesignApiTest extends TestCase
public function testDesignPost()
{
-
$design = [
'body' => 'body',
'includes' => 'includes',
diff --git a/tests/Feature/Email/EmailServiceTest.php b/tests/Feature/Email/EmailServiceTest.php
index 66b10b118a15..3f14e6e518df 100644
--- a/tests/Feature/Email/EmailServiceTest.php
+++ b/tests/Feature/Email/EmailServiceTest.php
@@ -15,11 +15,10 @@ use App\Services\Email\EmailObject;
use App\Services\Email\EmailService;
use App\Utils\Traits\GeneratesCounter;
use App\Utils\Traits\MakesHash;
-use Illuminate\Routing\Middleware\ThrottleRequests;
-use Tests\MockAccountData;
-use Tests\TestCase;
use Illuminate\Mail\Mailables\Address;
use Illuminate\Support\Facades\Cache;
+use Tests\MockAccountData;
+use Tests\TestCase;
/**
* @test
@@ -39,8 +38,9 @@ class EmailServiceTest extends TestCase
{
parent::setUp();
- if(!class_exists(\Modules\Admin\Jobs\Account\EmailFilter::class))
+ if (!class_exists(\Modules\Admin\Jobs\Account\EmailFilter::class)) {
$this->markTestSkipped('Skipped :: test not needed in this environment');
+ }
$this->makeTestData();
@@ -59,7 +59,6 @@ class EmailServiceTest extends TestCase
];
$this->email_service = new EmailService($this->email_object, $this->company);
-
}
public function testScanEmailsAttemptedFromVerifiedAccounts()
@@ -76,21 +75,17 @@ class EmailServiceTest extends TestCase
$this->assertFalse($this->email_service->preFlightChecksFail());
- collect($email_filter->getSpamKeywords())->each(function ($spam_subject){
-
+ collect($email_filter->getSpamKeywords())->each(function ($spam_subject) {
$this->email_object->subject = $spam_subject;
$this->assertTrue($this->email_service->preFlightChecksFail());
-
});
-
}
public function scanEmailsAttemptedFromUnverifiedAccounts()
{
-
config(['ninja.environment' => 'hosted']);
Cache::put($this->account->key, 1);
@@ -99,7 +94,6 @@ class EmailServiceTest extends TestCase
$this->account->save();
$this->assertTrue($this->email_service->preFlightChecksFail());
-
}
@@ -113,45 +107,39 @@ class EmailServiceTest extends TestCase
$this->account->save();
$this->assertFalse($this->email_service->preFlightChecksFail());
-
}
public function testClientMailersAreUnCapped()
{
-
config(['ninja.environment' => 'hosted']);
Cache::put($this->account->key, 1000000);
collect([
- 'gmail',
- 'office365',
- 'client_postmark',
+ 'gmail',
+ 'office365',
+ 'client_postmark',
'client_mailgun'])
- ->each(function ($mailer){
-
+ ->each(function ($mailer) {
$this->email_object->settings->email_sending_method = $mailer;
$this->assertFalse($this->email_service->preFlightChecksFail());
-
});
$this->email_object->settings->email_sending_method = 'postmark';
$this->assertTrue($this->email_service->preFlightChecksFail());
-
}
public function testFlaggedInvalidEmailsPrevented()
{
-
config(['ninja.environment' => 'hosted']);
Cache::put($this->account->key, 1);
- $this->email_object->to = [new Address("user@example.com", "Cool Name")];
+ $this->email_object->to = [new Address("user@example.com", "Cool Name")];
- $this->assertTrue($this->email_service->preFlightChecksFail());
+ $this->assertTrue($this->email_service->preFlightChecksFail());
collect([
@@ -159,21 +147,15 @@ class EmailServiceTest extends TestCase
'',
'bademail',
'domain.com',
- ])->each(function ($email){
-
-
+ ])->each(function ($email) {
$this->email_object->to = [new Address($email, "Cool Name")];
$this->assertTrue($this->email_service->preFlightChecksFail());
-
});
-
-
}
public function testFlaggedAccountsPrevented()
{
-
Cache::put($this->account->key, 1);
config(['ninja.environment' => 'hosted']);
@@ -182,31 +164,23 @@ class EmailServiceTest extends TestCase
$this->account->save();
$this->assertTrue($this->email_service->preFlightChecksFail());
-
}
public function testPreFlightChecksHosted()
{
-
Cache::put($this->account->key, 1);
config(['ninja.environment' => 'hosted']);
$this->assertFalse($this->email_service->preFlightChecksFail());
-
}
public function testPreFlightChecksSelfHost()
{
-
Cache::put($this->account->key, 1);
config(['ninja.environment' => 'selfhost']);
$this->assertFalse($this->email_service->preFlightChecksFail());
-
}
-
-
-
}
diff --git a/tests/Feature/EntityPaidToDateTest.php b/tests/Feature/EntityPaidToDateTest.php
index e39f3b3891d1..3212ff63d7a6 100644
--- a/tests/Feature/EntityPaidToDateTest.php
+++ b/tests/Feature/EntityPaidToDateTest.php
@@ -11,25 +11,15 @@
namespace Tests\Feature;
-use App\DataMapper\ClientSettings;
-use App\Factory\ClientFactory;
-use App\Factory\CreditFactory;
-use App\Factory\InvoiceFactory;
use App\Factory\InvoiceItemFactory;
-use App\Factory\PaymentFactory;
-use App\Helpers\Invoice\InvoiceSum;
use App\Models\Client;
-use App\Models\ClientContact;
-use App\Models\Credit;
use App\Models\Invoice;
-use App\Models\Payment;
use App\Utils\Traits\MakesHash;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\WithoutEvents;
use Illuminate\Routing\Middleware\ThrottleRequests;
use Illuminate\Support\Facades\Session;
-use Illuminate\Validation\ValidationException;
use Tests\MockAccountData;
use Tests\TestCase;
diff --git a/tests/Feature/ExpenseApiTest.php b/tests/Feature/ExpenseApiTest.php
index a2d3c56a4abe..23877f7c0d99 100644
--- a/tests/Feature/ExpenseApiTest.php
+++ b/tests/Feature/ExpenseApiTest.php
@@ -43,14 +43,12 @@ class ExpenseApiTest extends TestCase
public function testExpenseGetClientStatus()
{
-
$response = $this->withHeaders([
'X-API-SECRET' => config('ninja.api_secret'),
'X-API-TOKEN' => $this->token,
])->get('/api/v1/expenses?client_status=paid');
$response->assertStatus(200);
-
}
public function testExpensePost()
diff --git a/tests/Feature/Export/ClientCsvTest.php b/tests/Feature/Export/ClientCsvTest.php
index bc59900ae5ff..eba4d1bcd6da 100644
--- a/tests/Feature/Export/ClientCsvTest.php
+++ b/tests/Feature/Export/ClientCsvTest.php
@@ -11,11 +11,8 @@
namespace Tests\Feature\Export;
-use App\Models\Invoice;
use App\Utils\Traits\MakesHash;
use Illuminate\Routing\Middleware\ThrottleRequests;
-use Illuminate\Support\Facades\Storage;
-use League\Csv\Writer;
use Tests\MockAccountData;
use Tests\TestCase;
diff --git a/tests/Feature/Export/ExportCompanyTest.php b/tests/Feature/Export/ExportCompanyTest.php
index 307d45f917b8..88696330ff63 100644
--- a/tests/Feature/Export/ExportCompanyTest.php
+++ b/tests/Feature/Export/ExportCompanyTest.php
@@ -12,11 +12,8 @@
namespace Tests\Feature\Export;
use App\Jobs\Company\CompanyExport;
-use App\Models\Invoice;
use App\Utils\Traits\MakesHash;
use Illuminate\Routing\Middleware\ThrottleRequests;
-use Illuminate\Support\Facades\Storage;
-use League\Csv\Writer;
use Tests\MockAccountData;
use Tests\TestCase;
diff --git a/tests/Feature/Export/ProductSalesReportTest.php b/tests/Feature/Export/ProductSalesReportTest.php
index ff285653a60d..8684533f7a35 100644
--- a/tests/Feature/Export/ProductSalesReportTest.php
+++ b/tests/Feature/Export/ProductSalesReportTest.php
@@ -11,28 +11,17 @@
namespace Tests\Feature\Export;
-use App\DataMapper\ClientSettings;
use App\DataMapper\CompanySettings;
use App\Export\CSV\ProductSalesExport;
-use App\Factory\ExpenseCategoryFactory;
-use App\Factory\ExpenseFactory;
-use App\Factory\InvoiceFactory;
use App\Factory\InvoiceItemFactory;
use App\Models\Account;
use App\Models\Client;
-use App\Models\ClientContact;
use App\Models\Company;
use App\Models\Expense;
-use App\Models\ExpenseCategory;
use App\Models\Invoice;
use App\Models\User;
-use App\Services\Report\ProfitLoss;
use App\Utils\Traits\MakesHash;
-use Database\Factories\ClientContactFactory;
use Illuminate\Routing\Middleware\ThrottleRequests;
-use Illuminate\Support\Facades\Storage;
-use League\Csv\Writer;
-use Tests\MockAccountData;
use Tests\TestCase;
/**
@@ -126,7 +115,6 @@ class ProductSalesReportTest extends TestCase
'company_id' => $this->company->id,
'is_deleted' => 0,
]);
-
}
public function testProductSalesInstance()
@@ -140,7 +128,7 @@ class ProductSalesReportTest extends TestCase
$this->account->delete();
}
- public function testSimpleReport()
+ public function testSimpleReport()
{
$this->buildData();
@@ -213,5 +201,4 @@ class ProductSalesReportTest extends TestCase
return $line_items;
}
-
-}
\ No newline at end of file
+}
diff --git a/tests/Feature/Export/ProfitAndLossReportTest.php b/tests/Feature/Export/ProfitAndLossReportTest.php
index d052b9f091e5..52ba1b37342d 100644
--- a/tests/Feature/Export/ProfitAndLossReportTest.php
+++ b/tests/Feature/Export/ProfitAndLossReportTest.php
@@ -15,22 +15,16 @@ use App\DataMapper\ClientSettings;
use App\DataMapper\CompanySettings;
use App\Factory\ExpenseCategoryFactory;
use App\Factory\ExpenseFactory;
-use App\Factory\InvoiceFactory;
use App\Models\Account;
use App\Models\Client;
use App\Models\ClientContact;
use App\Models\Company;
use App\Models\Expense;
-use App\Models\ExpenseCategory;
use App\Models\Invoice;
use App\Models\User;
use App\Services\Report\ProfitLoss;
use App\Utils\Traits\MakesHash;
-use Database\Factories\ClientContactFactory;
use Illuminate\Routing\Middleware\ThrottleRequests;
-use Illuminate\Support\Facades\Storage;
-use League\Csv\Writer;
-use Tests\MockAccountData;
use Tests\TestCase;
/**
diff --git a/tests/Feature/GoCardlessInstantBankPaymentTest.php b/tests/Feature/GoCardlessInstantBankPaymentTest.php
index db7fe3b2e74e..96383eaaec6e 100644
--- a/tests/Feature/GoCardlessInstantBankPaymentTest.php
+++ b/tests/Feature/GoCardlessInstantBankPaymentTest.php
@@ -33,11 +33,11 @@ class GoCardlessInstantBankPaymentTest extends TestCase
use MakesHash;
private array $mock = [
- 'events' =>
+ 'events' =>
[
[
'id' => 'EV032JF',
- 'links' =>
+ 'links' =>
[
'customer' => 'CU001ZDX',
'billing_request' => 'BRQ0005',
@@ -45,7 +45,7 @@ class GoCardlessInstantBankPaymentTest extends TestCase
'customer_bank_account' => 'BA001V2111PK6J',
],
'action' => 'payer_details_confirmed',
- 'details' =>
+ 'details' =>
[
'cause' => 'billing_request_payer_details_confirmed',
'origin' => 'api',
@@ -57,7 +57,7 @@ class GoCardlessInstantBankPaymentTest extends TestCase
],
[
'id' => 'EV032JF67TF2',
- 'links' =>
+ 'links' =>
[
'customer' => 'CU001DXYDR3',
'billing_request' => 'BRQ005YJ7GHF',
@@ -65,7 +65,7 @@ class GoCardlessInstantBankPaymentTest extends TestCase
'mandate_request_mandate' => 'MD01W5RP7GA',
],
'action' => 'fulfilled',
- 'details' =>
+ 'details' =>
[
'cause' => 'billing_request_fulfilled',
'origin' => 'api',
@@ -77,18 +77,18 @@ class GoCardlessInstantBankPaymentTest extends TestCase
],
[
'id' => 'EV032JF67S0M8',
- 'links' =>
+ 'links' =>
[
'mandate' => 'MD001W5RP7GA1W',
],
'action' => 'created',
- 'details' =>
+ 'details' =>
[
'cause' => 'mandate_created',
'origin' => 'api',
'description' => 'Mandate created via the API.',
],
- 'metadata' =>
+ 'metadata' =>
[],
'created_at' => '2022-11-06T08:50:34.667Z',
'resource_type' => 'mandates',
@@ -110,42 +110,35 @@ class GoCardlessInstantBankPaymentTest extends TestCase
public function testWebhookProcessingWithGoCardless()
{
+ $this->assertIsArray($this->mock);
- $this->assertIsArray($this->mock);
-
- foreach($this->mock['events'] as $event)
- {
-
- if($event['action'] == 'fulfilled' && array_key_exists('billing_request', $event['links'])) {
-
- $this->assertEquals('CU001DXYDR3', $event['links']['customer']);
- $this->assertEquals('BRQ005YJ7GHF', $event['links']['billing_request']);
- $this->assertEquals('BA00V2111PK', $event['links']['customer_bank_account']);
-
+ foreach ($this->mock['events'] as $event) {
+ if ($event['action'] == 'fulfilled' && array_key_exists('billing_request', $event['links'])) {
+ $this->assertEquals('CU001DXYDR3', $event['links']['customer']);
+ $this->assertEquals('BRQ005YJ7GHF', $event['links']['billing_request']);
+ $this->assertEquals('BA00V2111PK', $event['links']['customer_bank_account']);
}
+ }
- }
-
- // mock the invoice and the payment hash
-
+ // mock the invoice and the payment hash
}
public function testInvoiceDelayedNotificationPayment()
{
-
- $gocardlesspayment = new \stdClass;
- $links = new \stdClass;
- $links->mandate = "my_mandate";
- $gocardlesspayment->links = $links;
- $gocardlesspayment->id = "gocardless_payment_id";
+ $gocardlesspayment = new \stdClass;
+ $links = new \stdClass;
+ $links->mandate = "my_mandate";
+ $gocardlesspayment->links = $links;
+ $gocardlesspayment->id = "gocardless_payment_id";
$invoice = Invoice::factory()->create(
- [
- 'user_id' => $this->user->id,
- 'company_id' => $this->company->id,
- 'client_id' => $this->client->id
- ]);
+ [
+ 'user_id' => $this->user->id,
+ 'company_id' => $this->company->id,
+ 'client_id' => $this->client->id
+ ]
+ );
$invoice->status_id = Invoice::STATUS_SENT;
$invoice->calc()->getInvoice()->save();
@@ -171,7 +164,7 @@ class GoCardlessInstantBankPaymentTest extends TestCase
$this->assertIsArray($data_object->invoices);
$this->assertIsObject(end($data_object->invoices));
- $this->assertEquals(1, count($data_object->invoices));
+ $this->assertEquals(1, count($data_object->invoices));
$test_invoice_object = end($data_object->invoices);
@@ -191,65 +184,52 @@ class GoCardlessInstantBankPaymentTest extends TestCase
$cg->fees_and_limits = '';
$cg->save();
- foreach($this->mock['events'] as $event)
- {
+ foreach ($this->mock['events'] as $event) {
+ if ($event['action'] == 'fulfilled' && array_key_exists('billing_request', $event['links'])) {
+ $hash = PaymentHash::whereJsonContains('data->billing_request', $event['links']['billing_request'])->first();
- if($event['action'] == 'fulfilled' && array_key_exists('billing_request', $event['links'])) {
+ $this->assertNotNull($hash);
+ $this->assertEquals('1234567890abc', $hash->hash);
- $hash = PaymentHash::whereJsonContains('data->billing_request', $event['links']['billing_request'])->first();
+ $invoices = Invoice::whereIn('id', $this->transformKeys(array_column($hash->invoices(), 'invoice_id')))->withTrashed()->get();
- $this->assertNotNull($hash);
- $this->assertEquals('1234567890abc', $hash->hash);
+ $this->assertNotNull($invoices);
+ $this->assertEquals(1, $invoices->count());
- $invoices = Invoice::whereIn('id', $this->transformKeys(array_column($hash->invoices(), 'invoice_id')))->withTrashed()->get();
+ // remove all paid invoices
+ $invoices->filter(function ($invoice) {
+ return $invoice->isPayable();
+ });
- $this->assertNotNull($invoices);
- $this->assertEquals(1, $invoices->count());
-
- // remove all paid invoices
- $invoices->filter(function ($invoice){
- return $invoice->isPayable();
- });
-
- $this->assertEquals(1, $invoices->count());
+ $this->assertEquals(1, $invoices->count());
- $data = [
- 'payment_method' => $gocardlesspayment->links->mandate,
- 'payment_type' => PaymentType::INSTANT_BANK_PAY,
- 'amount' => $hash->data->amount_with_fee,
- 'transaction_reference' => $gocardlesspayment->id,
- 'gateway_type_id' => GatewayType::INSTANT_BANK_PAY,
- ];
+ $data = [
+ 'payment_method' => $gocardlesspayment->links->mandate,
+ 'payment_type' => PaymentType::INSTANT_BANK_PAY,
+ 'amount' => $hash->data->amount_with_fee,
+ 'transaction_reference' => $gocardlesspayment->id,
+ 'gateway_type_id' => GatewayType::INSTANT_BANK_PAY,
+ ];
- $this->assertEquals('my_mandate', $data['payment_method']);
- $this->assertEquals('gocardless_payment_id', $data['transaction_reference']);
- $this->assertEquals($invoice->balance, $data['amount']);
+ $this->assertEquals('my_mandate', $data['payment_method']);
+ $this->assertEquals('gocardless_payment_id', $data['transaction_reference']);
+ $this->assertEquals($invoice->balance, $data['amount']);
- $gocardless_driver = $cg->driver($this->client);
- $gocardless_driver->setPaymentHash($hash);
+ $gocardless_driver = $cg->driver($this->client);
+ $gocardless_driver->setPaymentHash($hash);
- $payment = $gocardless_driver->createPayment($data, Payment::STATUS_COMPLETED);
+ $payment = $gocardless_driver->createPayment($data, Payment::STATUS_COMPLETED);
- $this->assertInstanceOf(Payment::class, $payment);
-
- $this->assertEquals(round($invoice->amount,2), round($payment->amount,2));
- $this->assertEquals(Payment::STATUS_COMPLETED, $payment->status_id);
- $this->assertEquals(1, $payment->invoices()->count());
- $this->assertEquals($invoice->number, $payment->invoices()->first()->number);
- $this->assertEquals(Invoice::STATUS_PAID, $payment->invoices()->first()->status_id);
-
-
-
- }
-
- }
+ $this->assertInstanceOf(Payment::class, $payment);
+ $this->assertEquals(round($invoice->amount, 2), round($payment->amount, 2));
+ $this->assertEquals(Payment::STATUS_COMPLETED, $payment->status_id);
+ $this->assertEquals(1, $payment->invoices()->count());
+ $this->assertEquals($invoice->number, $payment->invoices()->first()->number);
+ $this->assertEquals(Invoice::STATUS_PAID, $payment->invoices()->first()->status_id);
+ }
+ }
}
-
-
}
-
-
-
diff --git a/tests/Feature/Import/CSV/BaseTransformerTest.php b/tests/Feature/Import/CSV/BaseTransformerTest.php
index 812d9b543e46..06f8451fa2bb 100644
--- a/tests/Feature/Import/CSV/BaseTransformerTest.php
+++ b/tests/Feature/Import/CSV/BaseTransformerTest.php
@@ -14,18 +14,12 @@ namespace Tests\Feature\Import\CSV;
use App\Import\Transformer\BaseTransformer;
use App\Models\Client;
use App\Models\ClientContact;
-use App\Models\Expense;
use App\Models\Invoice;
-use App\Models\Payment;
use App\Models\Product;
use App\Models\TaxRate;
use App\Models\Vendor;
use App\Utils\Traits\MakesHash;
use Illuminate\Routing\Middleware\ThrottleRequests;
-use Illuminate\Support\Facades\Cache;
-use Illuminate\Support\Str;
-use League\Csv\Reader;
-use League\Csv\Statement;
use Tests\MockAccountData;
use Tests\TestCase;
diff --git a/tests/Feature/Import/CSV/CsvImportTest.php b/tests/Feature/Import/CSV/CsvImportTest.php
index af78d814a6db..9f8583fbdf3b 100644
--- a/tests/Feature/Import/CSV/CsvImportTest.php
+++ b/tests/Feature/Import/CSV/CsvImportTest.php
@@ -14,20 +14,13 @@ namespace Tests\Feature\Import\CSV;
use App\Import\Providers\Csv;
use App\Import\Transformer\BaseTransformer;
use App\Models\Client;
-use App\Models\ClientContact;
-use App\Models\Expense;
use App\Models\Invoice;
-use App\Models\Payment;
-use App\Models\Product;
-use App\Models\TaxRate;
use App\Models\Vendor;
use App\Utils\Traits\MakesHash;
use App\Utils\TruthSource;
use Illuminate\Routing\Middleware\ThrottleRequests;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;
-use League\Csv\Reader;
-use League\Csv\Statement;
use Tests\MockAccountData;
use Tests\TestCase;
@@ -53,7 +46,6 @@ class CsvImportTest extends TestCase
$this->withoutExceptionHandling();
auth()->login($this->user);
-
}
public function testExpenseCsvImport()
@@ -324,6 +316,6 @@ class CsvImportTest extends TestCase
$this->assertTrue($invoice->payments()->exists());
$this->assertEquals(1, $invoice->payments()->count());
- $this->assertEquals(51.03, round($invoice->payments()->sum('payments.amount'),2));
+ $this->assertEquals(51.03, round($invoice->payments()->sum('payments.amount'), 2));
}
}
diff --git a/tests/Feature/Import/Freshbooks/FreshbooksTest.php b/tests/Feature/Import/Freshbooks/FreshbooksTest.php
index a6062b1b3454..8b8e2e7b4971 100644
--- a/tests/Feature/Import/Freshbooks/FreshbooksTest.php
+++ b/tests/Feature/Import/Freshbooks/FreshbooksTest.php
@@ -11,14 +11,10 @@
namespace Tests\Feature\Import\Freshbooks;
-use App\Import\Providers\BaseImport;
use App\Import\Providers\Freshbooks;
-use App\Import\Providers\Zoho;
use App\Import\Transformer\BaseTransformer;
use App\Models\Client;
use App\Models\Invoice;
-use App\Models\Product;
-use App\Models\Vendor;
use App\Utils\Traits\MakesHash;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Routing\Middleware\ThrottleRequests;
diff --git a/tests/Feature/Import/ImportCompanyTest.php b/tests/Feature/Import/ImportCompanyTest.php
index 7860cd063ca9..593f742794b1 100644
--- a/tests/Feature/Import/ImportCompanyTest.php
+++ b/tests/Feature/Import/ImportCompanyTest.php
@@ -46,16 +46,10 @@ use App\Models\TaskStatus;
use App\Models\TaxRate;
use App\Models\User;
use App\Models\Vendor;
-use App\Models\VendorContact;
use App\Utils\Traits\MakesHash;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Routing\Middleware\ThrottleRequests;
use Illuminate\Support\Facades\Artisan;
-use Illuminate\Support\Facades\Cache;
-use Illuminate\Support\Str;
-use League\Csv\Reader;
-use League\Csv\Statement;
-use Tests\MockAccountData;
use Tests\TestCase;
/**
@@ -199,9 +193,9 @@ class ImportCompanyTest extends TestCase
unset($cu_array['id']);
$new_cu = CompanyUser::firstOrNew(
- ['user_id' => $user_id, 'company_id' => $this->company->id],
- $cu_array,
- );
+ ['user_id' => $user_id, 'company_id' => $this->company->id],
+ $cu_array,
+ );
$new_cu->account_id = $this->account->id;
$new_cu->save(['timestamps' => false]);
@@ -229,9 +223,9 @@ class ImportCompanyTest extends TestCase
unset($ct_array['id']);
$new_ct = CompanyToken::firstOrNew(
- ['user_id' => $user_id, 'company_id' => $this->company->id],
- $ct_array,
- );
+ ['user_id' => $user_id, 'company_id' => $this->company->id],
+ $ct_array,
+ );
$new_ct->account_id = $this->account->id;
$new_ct->save(['timestamps' => false]);
@@ -258,9 +252,9 @@ class ImportCompanyTest extends TestCase
unset($obj_array['id']);
$new_obj = PaymentTerm::firstOrNew(
- ['num_days' => $obj->num_days, 'company_id' => $this->company->id],
- $obj_array,
- );
+ ['num_days' => $obj->num_days, 'company_id' => $this->company->id],
+ $obj_array,
+ );
$new_obj->save(['timestamps' => false]);
}
@@ -286,9 +280,9 @@ class ImportCompanyTest extends TestCase
unset($obj_array['tax_rate_id']);
$new_obj = TaxRate::firstOrNew(
- ['name' => $obj->name, 'company_id' => $this->company->id, 'rate' => $obj->rate],
- $obj_array,
- );
+ ['name' => $obj->name, 'company_id' => $this->company->id, 'rate' => $obj->rate],
+ $obj_array,
+ );
$new_obj->save(['timestamps' => false]);
}
@@ -313,9 +307,9 @@ class ImportCompanyTest extends TestCase
unset($obj_array['id']);
$new_obj = ExpenseCategory::firstOrNew(
- ['name' => $obj->name, 'company_id' => $this->company->id],
- $obj_array,
- );
+ ['name' => $obj->name, 'company_id' => $this->company->id],
+ $obj_array,
+ );
$new_obj->save(['timestamps' => false]);
}
@@ -340,9 +334,9 @@ class ImportCompanyTest extends TestCase
unset($obj_array['id']);
$new_obj = TaskStatus::firstOrNew(
- ['name' => $obj->name, 'company_id' => $this->company->id],
- $obj_array,
- );
+ ['name' => $obj->name, 'company_id' => $this->company->id],
+ $obj_array,
+ );
$new_obj->save(['timestamps' => false]);
}
@@ -372,9 +366,9 @@ class ImportCompanyTest extends TestCase
unset($obj_array['documents']);
$new_obj = Client::firstOrNew(
- ['number' => $obj->number, 'company_id' => $this->company->id],
- $obj_array,
- );
+ ['number' => $obj->number, 'company_id' => $this->company->id],
+ $obj_array,
+ );
$new_obj->save(['timestamps' => false]);
@@ -408,9 +402,9 @@ class ImportCompanyTest extends TestCase
$obj_array['client_id'] = $client_id;
$new_obj = ClientContact::firstOrNew(
- ['email' => $obj->email, 'company_id' => $this->company->id],
- $obj_array,
- );
+ ['email' => $obj->email, 'company_id' => $this->company->id],
+ $obj_array,
+ );
$new_obj->save(['timestamps' => false]);
@@ -426,11 +420,13 @@ class ImportCompanyTest extends TestCase
/* Generic */
$this->assertEquals(1, count($this->backup_json_object->vendors));
- $this->genericImport(Vendor::class,
+ $this->genericImport(
+ Vendor::class,
['user_id', 'assigned_user_id', 'company_id', 'id', 'hashed_id'],
[['users' => 'user_id'], ['users' =>'assigned_user_id']],
'vendors',
- 'number');
+ 'number'
+ );
$this->assertEquals(1, Vendor::count());
@@ -438,11 +434,13 @@ class ImportCompanyTest extends TestCase
$this->assertEquals(1, count($this->backup_json_object->projects));
//$class, $unset, $transforms, $object_property, $match_key
- $this->genericImport(Project::class,
+ $this->genericImport(
+ Project::class,
['user_id', 'assigned_user_id', 'company_id', 'id', 'hashed_id', 'client_id'],
[['users' => 'user_id'], ['users' =>'assigned_user_id'], ['clients' => 'client_id']],
'projects',
- 'number');
+ 'number'
+ );
$this->assertEquals(1, Project::count());
@@ -452,7 +450,8 @@ class ImportCompanyTest extends TestCase
$this->assertEquals(1, count($this->backup_json_object->products));
- $this->genericNewClassImport(Product::class,
+ $this->genericNewClassImport(
+ Product::class,
['user_id', 'company_id', 'hashed_id', 'id'],
[['users' => 'user_id'], ['users' =>'assigned_user_id'], ['vendors' => 'vendor_id'], ['projects' => 'project_id']],
'products'
@@ -463,7 +462,8 @@ class ImportCompanyTest extends TestCase
$this->assertEquals(1, count($this->backup_json_object->company_gateways));
- $this->genericNewClassImport(CompanyGateway::class,
+ $this->genericNewClassImport(
+ CompanyGateway::class,
['user_id', 'company_id', 'hashed_id', 'id'],
[['users' => 'user_id']],
'company_gateways'
@@ -475,29 +475,35 @@ class ImportCompanyTest extends TestCase
//client gateway tokens
- $this->genericNewClassImport(ClientGatewayToken::class,
+ $this->genericNewClassImport(
+ ClientGatewayToken::class,
['company_id', 'id', 'hashed_id', 'client_id'],
[['clients' => 'client_id']],
- 'client_gateway_tokens');
+ 'client_gateway_tokens'
+ );
//client gateway tokens
//Group Settings
- $this->genericImport(GroupSetting::class,
+ $this->genericImport(
+ GroupSetting::class,
['user_id', 'company_id', 'id', 'hashed_id'],
[['users' => 'user_id']],
'group_settings',
- 'name');
+ 'name'
+ );
//Group Settings
//Subscriptions
$this->assertEquals(1, count($this->backup_json_object->subscriptions));
- $this->genericImport(Subscription::class,
+ $this->genericImport(
+ Subscription::class,
['user_id', 'assigned_user_id', 'company_id', 'id', 'hashed_id'],
[['group_settings' => 'group_id'], ['users' => 'user_id'], ['users' => 'assigned_user_id']],
'subscriptions',
- 'name');
+ 'name'
+ );
$this->assertEquals(1, Subscription::count());
@@ -507,7 +513,8 @@ class ImportCompanyTest extends TestCase
$this->assertEquals(2, count($this->backup_json_object->recurring_invoices));
- $this->genericImport(RecurringInvoice::class,
+ $this->genericImport(
+ RecurringInvoice::class,
['user_id', 'assigned_user_id', 'company_id', 'id', 'hashed_id', 'client_id', 'subscription_id', 'project_id', 'vendor_id', 'status'],
[
['subscriptions' => 'subscription_id'],
@@ -519,7 +526,8 @@ class ImportCompanyTest extends TestCase
['clients' => 'client_id'],
],
'recurring_invoices',
- 'number');
+ 'number'
+ );
$this->assertEquals(2, RecurringInvoice::count());
@@ -529,7 +537,8 @@ class ImportCompanyTest extends TestCase
$this->assertEquals(2, count($this->backup_json_object->recurring_invoice_invitations));
- $this->genericImport(RecurringInvoiceInvitation::class,
+ $this->genericImport(
+ RecurringInvoiceInvitation::class,
['user_id', 'client_contact_id', 'company_id', 'id', 'hashed_id', 'recurring_invoice_id'],
[
['users' => 'user_id'],
@@ -537,7 +546,8 @@ class ImportCompanyTest extends TestCase
['client_contacts' => 'client_contact_id'],
],
'recurring_invoice_invitations',
- 'key');
+ 'key'
+ );
$this->assertEquals(2, RecurringInvoiceInvitation::count());
@@ -547,7 +557,8 @@ class ImportCompanyTest extends TestCase
$this->assertEquals(2, count($this->backup_json_object->invoices));
- $this->genericImport(Invoice::class,
+ $this->genericImport(
+ Invoice::class,
['user_id', 'client_id', 'company_id', 'id', 'hashed_id', 'recurring_id', 'status'],
[
['users' => 'user_id'],
@@ -559,7 +570,8 @@ class ImportCompanyTest extends TestCase
['vendors' => 'vendor_id'],
],
'invoices',
- 'number');
+ 'number'
+ );
$this->assertEquals(2, Invoice::count());
@@ -569,7 +581,8 @@ class ImportCompanyTest extends TestCase
$this->assertEquals(2, count($this->backup_json_object->invoice_invitations));
- $this->genericImport(InvoiceInvitation::class,
+ $this->genericImport(
+ InvoiceInvitation::class,
['user_id', 'client_contact_id', 'company_id', 'id', 'hashed_id', 'invoice_id'],
[
['users' => 'user_id'],
@@ -577,7 +590,8 @@ class ImportCompanyTest extends TestCase
['client_contacts' => 'client_contact_id'],
],
'invoice_invitations',
- 'key');
+ 'key'
+ );
$this->assertEquals(2, InvoiceInvitation::count());
@@ -586,7 +600,8 @@ class ImportCompanyTest extends TestCase
// Quotes
$this->assertEquals(2, count($this->backup_json_object->quotes));
- $this->genericImport(Quote::class,
+ $this->genericImport(
+ Quote::class,
['user_id', 'client_id', 'company_id', 'id', 'hashed_id', 'recurring_id', 'status'],
[
['users' => 'user_id'],
@@ -598,7 +613,8 @@ class ImportCompanyTest extends TestCase
['vendors' => 'vendor_id'],
],
'quotes',
- 'number');
+ 'number'
+ );
$this->assertEquals(2, Quote::count());
@@ -608,7 +624,8 @@ class ImportCompanyTest extends TestCase
$this->assertEquals(2, count($this->backup_json_object->quote_invitations));
- $this->genericImport(QuoteInvitation::class,
+ $this->genericImport(
+ QuoteInvitation::class,
['user_id', 'client_contact_id', 'company_id', 'id', 'hashed_id', 'quote_id'],
[
['users' => 'user_id'],
@@ -616,7 +633,8 @@ class ImportCompanyTest extends TestCase
['client_contacts' => 'client_contact_id'],
],
'quote_invitations',
- 'key');
+ 'key'
+ );
$this->assertEquals(2, QuoteInvitation::count());
@@ -625,7 +643,8 @@ class ImportCompanyTest extends TestCase
// Credits
$this->assertEquals(2, count($this->backup_json_object->credits));
- $this->genericImport(Credit::class,
+ $this->genericImport(
+ Credit::class,
['user_id', 'client_id', 'company_id', 'id', 'hashed_id', 'recurring_id', 'status'],
[
['users' => 'user_id'],
@@ -637,7 +656,8 @@ class ImportCompanyTest extends TestCase
['vendors' => 'vendor_id'],
],
'credits',
- 'number');
+ 'number'
+ );
$this->assertEquals(2, Credit::count());
@@ -647,7 +667,8 @@ class ImportCompanyTest extends TestCase
$this->assertEquals(2, count($this->backup_json_object->credit_invitations));
- $this->genericImport(CreditInvitation::class,
+ $this->genericImport(
+ CreditInvitation::class,
['user_id', 'client_contact_id', 'company_id', 'id', 'hashed_id', 'credit_id'],
[
['users' => 'user_id'],
@@ -655,7 +676,8 @@ class ImportCompanyTest extends TestCase
['client_contacts' => 'client_contact_id'],
],
'credit_invitations',
- 'key');
+ 'key'
+ );
$this->assertEquals(2, CreditInvitation::count());
@@ -665,7 +687,8 @@ class ImportCompanyTest extends TestCase
$this->assertEquals(2, count($this->backup_json_object->expenses));
- $this->genericImport(Expense::class,
+ $this->genericImport(
+ Expense::class,
['assigned_user_id', 'user_id', 'client_id', 'company_id', 'id', 'hashed_id', 'project_id', 'vendor_id'],
[
['users' => 'user_id'],
@@ -675,7 +698,8 @@ class ImportCompanyTest extends TestCase
['vendors' => 'vendor_id'],
],
'expenses',
- 'number');
+ 'number'
+ );
$this->assertEquals(2, Expense::count());
@@ -685,7 +709,8 @@ class ImportCompanyTest extends TestCase
$this->assertEquals(3, count($this->backup_json_object->tasks));
- $this->genericImport(Task::class,
+ $this->genericImport(
+ Task::class,
['assigned_user_id', 'user_id', 'client_id', 'company_id', 'id', 'hashed_id', 'invoice_id', 'project_id'],
[
['users' => 'user_id'],
@@ -695,7 +720,8 @@ class ImportCompanyTest extends TestCase
['invoices' => 'invoice_id'],
],
'tasks',
- 'number');
+ 'number'
+ );
$this->assertEquals(3, Task::count());
@@ -705,7 +731,8 @@ class ImportCompanyTest extends TestCase
$this->assertEquals(2, count($this->backup_json_object->payments));
- $this->genericImport(Payment::class,
+ $this->genericImport(
+ Payment::class,
['assigned_user_id', 'user_id', 'client_id', 'company_id', 'id', 'hashed_id', 'client_contact_id', 'invitation_id', 'vendor_id', 'paymentables'],
[
['users' => 'user_id'],
@@ -717,7 +744,8 @@ class ImportCompanyTest extends TestCase
['company_gateways' => 'company_gateway_id'],
],
'payments',
- 'number');
+ 'number'
+ );
$this->assertEquals(2, Payment::count());
@@ -743,7 +771,8 @@ class ImportCompanyTest extends TestCase
$this->backup_json_object->activities = $activities;
- $this->genericNewClassImport(Activity::class,
+ $this->genericNewClassImport(
+ Activity::class,
[
'user_id',
'company_id',
@@ -780,7 +809,8 @@ class ImportCompanyTest extends TestCase
['recurring_invoices' => 'recurring_invoice_id'],
['invitations' => 'invitation_id'],
],
- 'activities');
+ 'activities'
+ );
$this->assertEquals(25, Activity::count());
@@ -790,13 +820,15 @@ class ImportCompanyTest extends TestCase
$this->assertEquals(25, count($this->backup_json_object->backups));
- $this->genericImportWithoutCompany(Backup::class,
+ $this->genericImportWithoutCompany(
+ Backup::class,
['activity_id', 'hashed_id', 'html_backup'],
[
['activities' => 'activity_id'],
],
'backups',
- 'created_at');
+ 'created_at'
+ );
$this->assertEquals(25, Backup::count());
@@ -805,7 +837,8 @@ class ImportCompanyTest extends TestCase
// Company Ledger
$this->assertEquals(3, count($this->backup_json_object->company_ledger));
- $this->genericImport(CompanyLedger::class,
+ $this->genericImport(
+ CompanyLedger::class,
['company_id', 'user_id', 'client_id', 'activity_id', 'id', 'account_id'],
[
['users' => 'user_id'],
@@ -813,7 +846,8 @@ class ImportCompanyTest extends TestCase
['activities' => 'activity_id'],
],
'company_ledger',
- 'created_at');
+ 'created_at'
+ );
$this->assertEquals(3, CompanyLedger::count());
@@ -821,13 +855,15 @@ class ImportCompanyTest extends TestCase
// Designs
- $this->genericImport(Design::class,
+ $this->genericImport(
+ Design::class,
['company_id', 'user_id'],
[
['users' => 'user_id'],
],
'designs',
- 'name');
+ 'name'
+ );
// Designs
@@ -1028,9 +1064,9 @@ class ImportCompanyTest extends TestCase
}
$new_obj = $class::firstOrNew(
- [$match_key => $obj->{$match_key}],
- $obj_array,
- );
+ [$match_key => $obj->{$match_key}],
+ $obj_array,
+ );
$new_obj->save(['timestamps' => false]);
@@ -1068,9 +1104,9 @@ class ImportCompanyTest extends TestCase
}
$new_obj = $class::firstOrNew(
- [$match_key => $obj->{$match_key}, 'company_id' => $this->company->id],
- $obj_array,
- );
+ [$match_key => $obj->{$match_key}, 'company_id' => $this->company->id],
+ $obj_array,
+ );
$new_obj->save(['timestamps' => false]);
diff --git a/tests/Feature/Import/Invoice2Go/Invoice2GoTest.php b/tests/Feature/Import/Invoice2Go/Invoice2GoTest.php
index 9cf62be12b67..d88313f0cf93 100644
--- a/tests/Feature/Import/Invoice2Go/Invoice2GoTest.php
+++ b/tests/Feature/Import/Invoice2Go/Invoice2GoTest.php
@@ -11,15 +11,10 @@
namespace Tests\Feature\Import\Invoice2Go;
-use App\Import\Providers\BaseImport;
-use App\Import\Providers\Freshbooks;
use App\Import\Providers\Invoice2Go;
-use App\Import\Providers\Zoho;
use App\Import\Transformer\BaseTransformer;
use App\Models\Client;
use App\Models\Invoice;
-use App\Models\Product;
-use App\Models\Vendor;
use App\Utils\Traits\MakesHash;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Routing\Middleware\ThrottleRequests;
diff --git a/tests/Feature/Import/Invoicely/InvoicelyTest.php b/tests/Feature/Import/Invoicely/InvoicelyTest.php
index 8d4896516817..3358702adb6c 100644
--- a/tests/Feature/Import/Invoicely/InvoicelyTest.php
+++ b/tests/Feature/Import/Invoicely/InvoicelyTest.php
@@ -11,14 +11,10 @@
namespace Tests\Feature\Import\Invoicely;
-use App\Import\Providers\BaseImport;
use App\Import\Providers\Invoicely;
-use App\Import\Providers\Zoho;
use App\Import\Transformer\BaseTransformer;
use App\Models\Client;
use App\Models\Invoice;
-use App\Models\Product;
-use App\Models\Vendor;
use App\Utils\Traits\MakesHash;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Routing\Middleware\ThrottleRequests;
diff --git a/tests/Feature/Import/Wave/WaveTest.php b/tests/Feature/Import/Wave/WaveTest.php
index de984b5b9558..f8f3edf47fc7 100644
--- a/tests/Feature/Import/Wave/WaveTest.php
+++ b/tests/Feature/Import/Wave/WaveTest.php
@@ -11,7 +11,6 @@
namespace Tests\Feature\Import\Wave;
-use App\Import\Providers\BaseImport;
use App\Import\Providers\Wave;
use App\Import\Transformer\BaseTransformer;
use App\Models\Client;
diff --git a/tests/Feature/Import/Zoho/ZohoTest.php b/tests/Feature/Import/Zoho/ZohoTest.php
index 550abde66002..0ab065f392fd 100644
--- a/tests/Feature/Import/Zoho/ZohoTest.php
+++ b/tests/Feature/Import/Zoho/ZohoTest.php
@@ -11,13 +11,10 @@
namespace Tests\Feature\Import\Zoho;
-use App\Import\Providers\BaseImport;
use App\Import\Providers\Zoho;
use App\Import\Transformer\BaseTransformer;
use App\Models\Client;
use App\Models\Invoice;
-use App\Models\Product;
-use App\Models\Vendor;
use App\Utils\Traits\MakesHash;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Routing\Middleware\ThrottleRequests;
diff --git a/tests/Feature/Inventory/InventoryManagementTest.php b/tests/Feature/Inventory/InventoryManagementTest.php
index 79e847f5cbb9..ee6556ccd354 100644
--- a/tests/Feature/Inventory/InventoryManagementTest.php
+++ b/tests/Feature/Inventory/InventoryManagementTest.php
@@ -39,7 +39,7 @@ class InventoryManagementTest extends TestCase
);
if (config('ninja.testvars.travis') !== false) {
- $this->markTestSkipped('Skip test for Travis');
+ $this->markTestSkipped('Skip test for Travis');
}
}
@@ -90,7 +90,7 @@ class InventoryManagementTest extends TestCase
$data = $response->json();
- $invoice = Invoice::find($this->decodePrimaryKey($data['data']['id']));
+ $invoice = Invoice::find($this->decodePrimaryKey($data['data']['id']));
$invoice->service()->markDeleted()->save();
$invoice->is_deleted = true;
@@ -98,13 +98,10 @@ class InventoryManagementTest extends TestCase
$this->assertEquals(100, $product->fresh()->in_stock_quantity);
- $invoice = Invoice::withTrashed()->find($this->decodePrimaryKey($data['data']['id']));
+ $invoice = Invoice::withTrashed()->find($this->decodePrimaryKey($data['data']['id']));
$invoice->service()->handleRestore()->save();
$this->assertEquals(90, $product->fresh()->in_stock_quantity);
-
-
-
}
}
diff --git a/tests/Feature/InvitationTest.php b/tests/Feature/InvitationTest.php
index 02610d5e5418..597f90cee7d8 100644
--- a/tests/Feature/InvitationTest.php
+++ b/tests/Feature/InvitationTest.php
@@ -21,10 +21,8 @@ use App\Models\Company;
use App\Models\Invoice;
use App\Models\User;
use App\Utils\Traits\MakesHash;
-use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\RefreshDatabase;
-use Illuminate\Support\Facades\Session;
use Tests\TestCase;
/**
@@ -42,7 +40,6 @@ class InvitationTest extends TestCase
parent::setUp();
$this->faker = \Faker\Factory::create();
-
}
public function testInvoiceCreationAfterInvoiceMarkedSent()
diff --git a/tests/Feature/InvoiceTest.php b/tests/Feature/InvoiceTest.php
index f41f7f34af5c..60f5db3ae254 100644
--- a/tests/Feature/InvoiceTest.php
+++ b/tests/Feature/InvoiceTest.php
@@ -49,21 +49,19 @@ class InvoiceTest extends TestCase
public function testInvoiceGetPaidInvoices()
{
-
$response = $this->withHeaders([
'X-API-SECRET' => config('ninja.api_secret'),
'X-API-TOKEN' => $this->token,
- ])->get('/api/v1/invoices?client_status=paid',)
+ ])->get('/api/v1/invoices?client_status=paid', )
->assertStatus(200);
}
public function testInvoiceArchiveAction()
{
-
$response = $this->withHeaders([
'X-API-SECRET' => config('ninja.api_secret'),
'X-API-TOKEN' => $this->token,
- ])->get('/api/v1/invoices/'.$this->invoice->hashed_id.'/archive',)
+ ])->get('/api/v1/invoices/'.$this->invoice->hashed_id.'/archive', )
->assertStatus(200);
}
@@ -312,6 +310,4 @@ class InvoiceTest extends TestCase
])->post('/api/v1/invoices/', $data)
->assertStatus(200);
}
-
-
}
diff --git a/tests/Feature/LiveDesignTest.php b/tests/Feature/LiveDesignTest.php
index 51d6fbfdf3ba..3bf5b0cf8957 100644
--- a/tests/Feature/LiveDesignTest.php
+++ b/tests/Feature/LiveDesignTest.php
@@ -38,17 +38,16 @@ class LiveDesignTest extends TestCase
if (config('ninja.testvars.travis') !== false) {
$this->markTestSkipped('Skip test for Travis');
}
-
}
public function testDesignRoute200()
{
- $data = [
- 'entity' => 'invoice',
- 'entity_id' => $this->invoice->hashed_id,
- 'settings_type' => 'company',
- 'settings' => (array)$this->company->settings,
- ];
+ $data = [
+ 'entity' => 'invoice',
+ 'entity_id' => $this->invoice->hashed_id,
+ 'settings_type' => 'company',
+ 'settings' => (array)$this->company->settings,
+ ];
$response = $this->withHeaders([
'X-API-SECRET' => config('ninja.api_secret'),
@@ -57,6 +56,4 @@ class LiveDesignTest extends TestCase
$response->assertStatus(200);
}
-
-
}
diff --git a/tests/Feature/LoadTest.php b/tests/Feature/LoadTest.php
index 38b5c15fa6f2..d884c17824f6 100644
--- a/tests/Feature/LoadTest.php
+++ b/tests/Feature/LoadTest.php
@@ -20,7 +20,6 @@ use App\Models\Client;
use App\Models\ClientContact;
use App\Models\Company;
use App\Models\CompanyToken;
-use App\Models\Country;
use App\Models\Credit;
use App\Models\Document;
use App\Models\Expense;
@@ -34,10 +33,7 @@ use App\Models\VendorContact;
use App\Repositories\InvoiceRepository;
use App\Utils\Traits\GeneratesCounter;
use App\Utils\Traits\MakesHash;
-use Illuminate\Foundation\Testing\DatabaseTransactions;
-use Illuminate\Routing\Middleware\ThrottleRequests;
use Illuminate\Support\Str;
-use Tests\MockAccountData;
use Tests\TestCase;
/**
diff --git a/tests/Feature/MultiPaymentDeleteTest.php b/tests/Feature/MultiPaymentDeleteTest.php
index ee42d5fb4bcb..62df515c697e 100644
--- a/tests/Feature/MultiPaymentDeleteTest.php
+++ b/tests/Feature/MultiPaymentDeleteTest.php
@@ -11,7 +11,6 @@
namespace Tests\Feature;
-use App\Factory\CompanyTokenFactory;
use App\Factory\CompanyUserFactory;
use App\Factory\InvoiceFactory;
use App\Factory\InvoiceItemFactory;
@@ -25,7 +24,6 @@ use App\Models\Payment;
use App\Models\User;
use App\Utils\Traits\MakesHash;
use Illuminate\Foundation\Testing\DatabaseTransactions;
-use Illuminate\Validation\ValidationException;
use Tests\TestCase;
/**
diff --git a/tests/Feature/Notify/NotificationTest.php b/tests/Feature/Notify/NotificationTest.php
index 0afee0a28c1a..50818f9299b0 100644
--- a/tests/Feature/Notify/NotificationTest.php
+++ b/tests/Feature/Notify/NotificationTest.php
@@ -11,7 +11,6 @@
namespace Tests\Feature\Notify;
-
use App\DataMapper\CompanySettings;
use App\Models\CompanyToken;
use App\Models\CompanyUser;
@@ -51,7 +50,7 @@ class NotificationTest extends TestCase
$u = User::factory()->create([
'account_id' => $this->account->id,
'email' => $this->faker->safeEmail(),
- 'confirmation_code' => uniqid("st",true),
+ 'confirmation_code' => uniqid("st", true),
]);
$company_token = new CompanyToken;
@@ -81,7 +80,7 @@ class NotificationTest extends TestCase
$i = Invoice::factory()->create([
'user_id' => $u->id,
'company_id' => $this->company->id,
- 'number' => uniqid("st",true),
+ 'number' => uniqid("st", true),
'client_id' => $this->client->id,
]);
@@ -99,7 +98,6 @@ class NotificationTest extends TestCase
$methods = $this->findUserNotificationTypes($invitation, $company_user, 'invoice', ['all_notifications', 'invoice_viewed', 'invoice_viewed_all']);
$this->assertCount(0, $methods);
-
}
@@ -110,7 +108,7 @@ class NotificationTest extends TestCase
$this->user->company_users()->where('company_id', $this->company->id)->update(['notifications' => (array)$notifications]);
- $this->assertTrue(property_exists($this->cu->notifications,'email'));
+ $this->assertTrue(property_exists($this->cu->notifications, 'email'));
$p = Product::factory()->create([
'user_id' => $this->user->id,
@@ -125,7 +123,6 @@ class NotificationTest extends TestCase
$notification_users = $this->filterUsersByPermissions($this->company->company_users, $p, ['inventory_user','invalid notification']);
$this->assertCount(0, $notification_users->toArray());
-
}
public function testAllNotificationsFires()
@@ -142,7 +139,6 @@ class NotificationTest extends TestCase
$notification_users = $this->filterUsersByPermissions($this->company->company_users, $p, ['inventory_all']);
$this->assertCount(1, $notification_users->toArray());
-
}
public function testAllNotificationsFiresForUser()
@@ -159,7 +155,6 @@ class NotificationTest extends TestCase
$notification_users = $this->filterUsersByPermissions($this->company->company_users, $p, ['all_user_notifications']);
$this->assertCount(1, $notification_users->toArray());
-
}
public function testAllNotificationsDoesNotFiresForUser()
@@ -167,7 +162,7 @@ class NotificationTest extends TestCase
$u = User::factory()->create([
'account_id' => $this->account->id,
'email' => $this->faker->safeEmail(),
- 'confirmation_code' => uniqid("st",true),
+ 'confirmation_code' => uniqid("st", true),
]);
$company_token = new CompanyToken;
@@ -237,8 +232,5 @@ class NotificationTest extends TestCase
$this->assertCount(1, $methods);
$this->assertTrue($this->checkNotificationExists($cu, $p, ['inventory_all', 'inventory_user']));
-
}
-
-
}
diff --git a/tests/Feature/PaymentTest.php b/tests/Feature/PaymentTest.php
index 0f95a9d33e65..aa963d7d46b3 100644
--- a/tests/Feature/PaymentTest.php
+++ b/tests/Feature/PaymentTest.php
@@ -64,14 +64,11 @@ class PaymentTest extends TestCase
public function testGetPaymentMatchList()
{
-
$response = $this->withHeaders([
'X-API-SECRET' => config('ninja.api_secret'),
'X-API-TOKEN' => $this->token,
])->get('/api/v1/payments?match_transactions=true')
->assertStatus(200);
-
-
}
public function testStorePaymentIdempotencyKeyIllegalLength()
@@ -114,12 +111,9 @@ class PaymentTest extends TestCase
])->post('/api/v1/payments/', $data);
} catch (ValidationException $e) {
// $message = json_decode($e->validator->getMessageBag(), 1);
-
-
}
$this->assertFalse($response);
-
}
diff --git a/tests/Feature/Payments/CreditPaymentTest.php b/tests/Feature/Payments/CreditPaymentTest.php
index bc031be4a235..2e25dfebe1d3 100644
--- a/tests/Feature/Payments/CreditPaymentTest.php
+++ b/tests/Feature/Payments/CreditPaymentTest.php
@@ -11,15 +11,9 @@
namespace Tests\Feature\Payments;
-use App\DataMapper\ClientSettings;
-use App\Factory\ClientFactory;
-use App\Factory\CreditFactory;
use App\Factory\InvoiceFactory;
-use App\Factory\InvoiceItemFactory;
-use App\Factory\PaymentFactory;
use App\Helpers\Invoice\InvoiceSum;
use App\Models\Client;
-use App\Models\ClientContact;
use App\Models\Credit;
use App\Models\Invoice;
use App\Models\Payment;
@@ -30,7 +24,6 @@ use Illuminate\Foundation\Testing\WithoutEvents;
use Illuminate\Routing\Middleware\ThrottleRequests;
use Illuminate\Support\Facades\Session;
use Illuminate\Validation\ValidationException;
-use Tests\MockAccountData;
use Tests\MockUnitData;
use Tests\TestCase;
diff --git a/tests/Feature/Payments/StorePaymentValidationTest.php b/tests/Feature/Payments/StorePaymentValidationTest.php
index 1dce4cbd6b5e..72613a0680db 100644
--- a/tests/Feature/Payments/StorePaymentValidationTest.php
+++ b/tests/Feature/Payments/StorePaymentValidationTest.php
@@ -11,18 +11,6 @@
namespace Tests\Feature\Payments;
-use App\DataMapper\ClientSettings;
-use App\Factory\ClientFactory;
-use App\Factory\CreditFactory;
-use App\Factory\InvoiceFactory;
-use App\Factory\InvoiceItemFactory;
-use App\Factory\PaymentFactory;
-use App\Helpers\Invoice\InvoiceSum;
-use App\Models\Client;
-use App\Models\ClientContact;
-use App\Models\Credit;
-use App\Models\Invoice;
-use App\Models\Payment;
use App\Utils\Traits\MakesHash;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Testing\DatabaseTransactions;
@@ -31,7 +19,6 @@ use Illuminate\Routing\Middleware\ThrottleRequests;
use Illuminate\Support\Facades\Session;
use Illuminate\Validation\ValidationException;
use Tests\MockAccountData;
-use Tests\MockUnitData;
use Tests\TestCase;
/**
@@ -217,6 +204,5 @@ class StorePaymentValidationTest extends TestCase
}
$response->assertStatus(302);
-
}
}
diff --git a/tests/Feature/Payments/UnappliedPaymentDeleteTest.php b/tests/Feature/Payments/UnappliedPaymentDeleteTest.php
index c79591a163c2..1803279c9951 100644
--- a/tests/Feature/Payments/UnappliedPaymentDeleteTest.php
+++ b/tests/Feature/Payments/UnappliedPaymentDeleteTest.php
@@ -20,7 +20,6 @@ use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\WithoutEvents;
use Illuminate\Routing\Middleware\ThrottleRequests;
use Illuminate\Validation\ValidationException;
-use Tests\MockAccountData;
use Tests\MockUnitData;
use Tests\TestCase;
diff --git a/tests/Feature/Payments/UnappliedPaymentRefundTest.php b/tests/Feature/Payments/UnappliedPaymentRefundTest.php
index f2b16336bdef..04f4cb63bc13 100644
--- a/tests/Feature/Payments/UnappliedPaymentRefundTest.php
+++ b/tests/Feature/Payments/UnappliedPaymentRefundTest.php
@@ -17,7 +17,6 @@ use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\WithoutEvents;
use Illuminate\Routing\Middleware\ThrottleRequests;
use Illuminate\Validation\ValidationException;
-use Tests\MockAccountData;
use Tests\MockUnitData;
use Tests\TestCase;
diff --git a/tests/Feature/PurchaseOrderTest.php b/tests/Feature/PurchaseOrderTest.php
index 323732774d8a..b3fc1be63519 100644
--- a/tests/Feature/PurchaseOrderTest.php
+++ b/tests/Feature/PurchaseOrderTest.php
@@ -11,7 +11,6 @@
namespace Tests\Feature;
-use App\Models\Client;
use App\Models\PurchaseOrder;
use App\Utils\Traits\MakesHash;
use Illuminate\Database\Eloquent\Model;
@@ -133,7 +132,6 @@ class PurchaseOrderTest extends TestCase
'X-API-TOKEN' => $this->token,
])->post("/api/v1/purchase_orders/bulk", $data)
->assertStatus(302);
-
}
public function testPurchaseOrderDownloadPDF()
@@ -147,7 +145,6 @@ class PurchaseOrderTest extends TestCase
$response->assertStatus(200);
$this->assertTrue($response->headers->get('content-type') == 'application/pdf');
-
}
diff --git a/tests/Feature/QuoteTest.php b/tests/Feature/QuoteTest.php
index 1550e8ec8206..c324f05f8c30 100644
--- a/tests/Feature/QuoteTest.php
+++ b/tests/Feature/QuoteTest.php
@@ -11,7 +11,6 @@
namespace Tests\Feature;
-use App\Models\Client;
use App\Models\ClientContact;
use App\Models\Project;
use App\Models\Quote;
@@ -61,7 +60,6 @@ class QuoteTest extends TestCase
$response->assertStatus(200);
$this->assertTrue($response->headers->get('content-type') == 'application/pdf');
-
}
public function testQuoteListApproved()
@@ -80,7 +78,7 @@ class QuoteTest extends TestCase
$response = $this->withHeaders([
'X-API-SECRET' => config('ninja.api_secret'),
'X-API-TOKEN' => $this->token,
- ])->post('/api/v1/quotes/bulk',['action' => 'convert_to_project', 'ids' => [$this->quote->hashed_id]]);
+ ])->post('/api/v1/quotes/bulk', ['action' => 'convert_to_project', 'ids' => [$this->quote->hashed_id]]);
$response->assertStatus(200);
@@ -183,5 +181,4 @@ class QuoteTest extends TestCase
$response->assertStatus(200);
}
-
}
diff --git a/tests/Feature/RecurringInvoiceTest.php b/tests/Feature/RecurringInvoiceTest.php
index be9c0e002bb2..f772c5aa714e 100644
--- a/tests/Feature/RecurringInvoiceTest.php
+++ b/tests/Feature/RecurringInvoiceTest.php
@@ -60,7 +60,6 @@ class RecurringInvoiceTest extends TestCase
'X-API-TOKEN' => $this->token,
])->get('/api/v1/recurring_invoices?client_status=active')
->assertStatus(200);
-
}
diff --git a/tests/Feature/RecurringInvoicesCronTest.php b/tests/Feature/RecurringInvoicesCronTest.php
index fe3c45ad0d0f..5a62db9a5dd7 100644
--- a/tests/Feature/RecurringInvoicesCronTest.php
+++ b/tests/Feature/RecurringInvoicesCronTest.php
@@ -39,7 +39,6 @@ class RecurringInvoicesCronTest extends TestCase
public function testCountCorrectNumberOfRecurringInvoicesDue()
{
-
//spin up 5 valid and 1 invalid recurring invoices
$recurring_invoices = RecurringInvoice::where('next_send_date', '<=', Carbon::now()->addMinutes(30))->get();
diff --git a/tests/Feature/RecurringQuoteTest.php b/tests/Feature/RecurringQuoteTest.php
index 3051f0466100..d795b5cf035a 100644
--- a/tests/Feature/RecurringQuoteTest.php
+++ b/tests/Feature/RecurringQuoteTest.php
@@ -49,7 +49,6 @@ class RecurringQuoteTest extends TestCase
public function testRecurringQuoteListFilter()
{
-
$response = $this->withHeaders([
'X-API-SECRET' => config('ninja.api_secret'),
'X-API-TOKEN' => $this->token,
@@ -74,7 +73,7 @@ class RecurringQuoteTest extends TestCase
{
RecurringQuote::factory()->create(['user_id' => $this->user->id, 'company_id' => $this->company->id, 'client_id' => $this->client->id]);
- $RecurringQuote = RecurringQuote::query()->where('user_id', $this->user->id)->orderBy('id','DESC')->first();
+ $RecurringQuote = RecurringQuote::query()->where('user_id', $this->user->id)->orderBy('id', 'DESC')->first();
$RecurringQuote->save();
$response = $this->withHeaders([
diff --git a/tests/Feature/ReminderTest.php b/tests/Feature/ReminderTest.php
index 2e9a30fe10f5..85d5428f334d 100644
--- a/tests/Feature/ReminderTest.php
+++ b/tests/Feature/ReminderTest.php
@@ -51,7 +51,6 @@ class ReminderTest extends TestCase
public function testForClientTimezoneEdges()
{
-
$this->invoice->next_send_date = null;
$this->invoice->date = now()->format('Y-m-d');
$this->invoice->due_date = Carbon::now()->addDays(5)->format('Y-m-d');
@@ -128,7 +127,6 @@ class ReminderTest extends TestCase
$this->assertTrue($next_send_date->eq($calculatedReminderDate));
nlog($next_send_date->format('Y-m-d h:i:s'));
-
}
public function testReminderQueryCatchesDate()
@@ -272,6 +270,4 @@ class ReminderTest extends TestCase
$this->assertNotNull($this->invoice->next_send_date);
}
-
-
}
diff --git a/tests/Feature/Scheduler/SchedulerTest.php b/tests/Feature/Scheduler/SchedulerTest.php
index ebaebbe7a88c..d2ec6eee0931 100644
--- a/tests/Feature/Scheduler/SchedulerTest.php
+++ b/tests/Feature/Scheduler/SchedulerTest.php
@@ -51,23 +51,21 @@ class SchedulerTest extends TestCase
$this->withoutMiddleware(
ThrottleRequests::class
);
-
}
public function testClientCountResolution()
{
-
$c = Client::factory()->create([
'company_id' => $this->company->id,
'user_id' => $this->user->id,
- 'number' => rand(1000,100000),
+ 'number' => rand(1000, 100000),
'name' => 'A fancy client'
]);
$c2 = Client::factory()->create([
'company_id' => $this->company->id,
'user_id' => $this->user->id,
- 'number' => rand(1000,100000),
+ 'number' => rand(1000, 100000),
'name' => 'A fancy client'
]);
@@ -82,7 +80,7 @@ class SchedulerTest extends TestCase
'show_aging_table' => true,
'status' => 'paid',
'clients' => [
- $c2->hashed_id,
+ $c2->hashed_id,
$c->hashed_id
],
],
@@ -90,12 +88,11 @@ class SchedulerTest extends TestCase
$response = false;
- try{
+ try {
$response = $this->withHeaders([
'X-API-SECRET' => config('ninja.api_secret'),
'X-API-TOKEN' => $this->token,
])->postJson('/api/v1/task_schedulers', $data);
-
} catch (ValidationException $e) {
$message = json_decode($e->validator->getMessageBag(), 1);
nlog($message);
@@ -117,23 +114,21 @@ class SchedulerTest extends TestCase
->cursor();
$this->assertCount(2, $q);
-
}
public function testClientsValidationInScheduledTask()
{
-
$c = Client::factory()->create([
'company_id' => $this->company->id,
'user_id' => $this->user->id,
- 'number' => rand(1000,100000),
+ 'number' => rand(1000, 100000),
'name' => 'A fancy client'
]);
$c2 = Client::factory()->create([
'company_id' => $this->company->id,
'user_id' => $this->user->id,
- 'number' => rand(1000,100000),
+ 'number' => rand(1000, 100000),
'name' => 'A fancy client'
]);
@@ -148,7 +143,7 @@ class SchedulerTest extends TestCase
'show_aging_table' => true,
'status' => 'paid',
'clients' => [
- $c2->hashed_id,
+ $c2->hashed_id,
$c->hashed_id
],
],
@@ -156,12 +151,11 @@ class SchedulerTest extends TestCase
$response = false;
- try{
+ try {
$response = $this->withHeaders([
'X-API-SECRET' => config('ninja.api_secret'),
'X-API-TOKEN' => $this->token,
])->postJson('/api/v1/task_schedulers', $data);
-
} catch (ValidationException $e) {
$message = json_decode($e->validator->getMessageBag(), 1);
nlog($message);
@@ -181,7 +175,7 @@ class SchedulerTest extends TestCase
'show_aging_table' => true,
'status' => 'paid',
'clients' => [
- $c2->hashed_id,
+ $c2->hashed_id,
],
],
];
@@ -205,7 +199,7 @@ class SchedulerTest extends TestCase
'show_aging_table' => true,
'status' => 'paid',
'clients' => [
- 'xx33434',
+ 'xx33434',
],
],
];
@@ -216,14 +210,11 @@ class SchedulerTest extends TestCase
])->postJson('/api/v1/task_schedulers', $data);
$response->assertStatus(422);
-
-
}
public function testCalculateNextRun()
{
-
$scheduler = SchedulerFactory::create($this->company->id, $this->user->id);
$data = [
@@ -247,13 +238,12 @@ class SchedulerTest extends TestCase
$reflectionMethod = new \ReflectionMethod(SchedulerService::class, 'calculateNextRun');
$reflectionMethod->setAccessible(true);
- $method = $reflectionMethod->invoke(new SchedulerService($scheduler));
+ $method = $reflectionMethod->invoke(new SchedulerService($scheduler));
$scheduler->fresh();
$offset = $this->company->timezone_offset();
$this->assertEquals(now()->startOfDay()->addMonthNoOverflow()->addSeconds($offset)->format('Y-m-d'), $scheduler->next_run->format('Y-m-d'));
-
}
public function testCalculateStartAndEndDates()
@@ -283,19 +273,17 @@ class SchedulerTest extends TestCase
$reflectionMethod = new \ReflectionMethod(SchedulerService::class, 'calculateStartAndEndDates');
$reflectionMethod->setAccessible(true);
- $method = $reflectionMethod->invoke(new SchedulerService($scheduler));
+ $method = $reflectionMethod->invoke(new SchedulerService($scheduler));
$this->assertIsArray($method);
$this->assertEquals('previous_month', $scheduler->parameters['date_range']);
$this->assertEqualsCanonicalizing(['2022-12-01','2022-12-31'], $method);
-
}
public function testCalculateStatementProperties()
{
-
$scheduler = SchedulerFactory::create($this->company->id, $this->user->id);
$data = [
@@ -329,12 +317,10 @@ class SchedulerTest extends TestCase
$this->assertIsArray($method);
$this->assertEquals('paid', $method['status']);
-
}
public function testGetThisMonthRange()
{
-
$this->travelTo(Carbon::parse('2023-01-14'));
$this->assertEqualsCanonicalizing(['2023-01-01','2023-01-31'], $this->getDateRange('this_month'));
@@ -346,7 +332,6 @@ class SchedulerTest extends TestCase
$this->assertEqualsCanonicalizing(['2022-01-01','2022-12-31'], $this->getDateRange('previous_year'));
$this->travelBack();
-
}
private function getDateRange($range)
@@ -384,12 +369,10 @@ class SchedulerTest extends TestCase
])->postJson('/api/v1/task_schedulers', $data);
$response->assertStatus(200);
-
}
public function testDeleteSchedule()
{
-
$data = [
'ids' => [$this->scheduler->hashed_id],
];
@@ -410,12 +393,10 @@ class SchedulerTest extends TestCase
'X-API-TOKEN' => $this->token,
])->postJson('/api/v1/task_schedulers/bulk?action=restore', $data)
->assertStatus(200);
-
- }
+ }
public function testRestoreSchedule()
{
-
$data = [
'ids' => [$this->scheduler->hashed_id],
];
@@ -436,12 +417,10 @@ class SchedulerTest extends TestCase
'X-API-TOKEN' => $this->token,
])->postJson('/api/v1/task_schedulers/bulk?action=restore', $data)
->assertStatus(200);
-
- }
+ }
public function testArchiveSchedule()
{
-
$data = [
'ids' => [$this->scheduler->hashed_id],
];
@@ -451,12 +430,10 @@ class SchedulerTest extends TestCase
'X-API-TOKEN' => $this->token,
])->postJson('/api/v1/task_schedulers/bulk?action=archive', $data)
->assertStatus(200);
-
}
public function testSchedulerPost()
{
-
$data = [
'name' => 'A different Name',
'frequency_id' => 5,
@@ -471,11 +448,10 @@ class SchedulerTest extends TestCase
])->postJson('/api/v1/task_schedulers', $data);
$response->assertStatus(200);
- }
+ }
public function testSchedulerPut()
{
-
$data = [
'name' => 'A different Name',
'frequency_id' => 5,
@@ -490,7 +466,7 @@ class SchedulerTest extends TestCase
])->putJson('/api/v1/task_schedulers/'.$this->scheduler->hashed_id, $data);
$response->assertStatus(200);
- }
+ }
public function testSchedulerGet()
{
diff --git a/tests/Feature/SubscriptionApiTest.php b/tests/Feature/SubscriptionApiTest.php
index 46cf797c20e1..61f72e0d6451 100644
--- a/tests/Feature/SubscriptionApiTest.php
+++ b/tests/Feature/SubscriptionApiTest.php
@@ -12,13 +12,10 @@
namespace Tests\Feature;
use App\Models\Product;
-use App\Models\RecurringInvoice;
use App\Models\Subscription;
use App\Utils\Traits\MakesHash;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Testing\DatabaseTransactions;
-use Illuminate\Foundation\Testing\RefreshDatabase;
-use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
@@ -52,13 +49,11 @@ class SubscriptionApiTest extends TestCase
public function testSubscriptionFilter()
{
-
$response = $this->withHeaders([
'X-API-SECRET' => config('ninja.api_secret'),
'X-API-TOKEN' => $this->token,
])->get('/api/v1/subscriptions?filter=xx')
->assertStatus(200);
-
}
public function testSubscriptionsGet()
diff --git a/tests/Feature/SystemLogApiTest.php b/tests/Feature/SystemLogApiTest.php
index 56985c502a7a..53d57b21073c 100644
--- a/tests/Feature/SystemLogApiTest.php
+++ b/tests/Feature/SystemLogApiTest.php
@@ -37,13 +37,12 @@ class SystemLogApiTest extends TestCase
public function testFilters()
{
-
$response = $this->withHeaders([
'X-API-SECRET' => config('ninja.api_secret'),
'X-API-TOKEN' => $this->token,
])->get('/api/v1/system_logs?type_id=3')
- ->assertStatus(200);;
-
+ ->assertStatus(200);
+ ;
}
public function testSystemLogRoutes()
diff --git a/tests/Feature/TaskApiTest.php b/tests/Feature/TaskApiTest.php
index b5f77674024a..24a5de247f58 100644
--- a/tests/Feature/TaskApiTest.php
+++ b/tests/Feature/TaskApiTest.php
@@ -45,8 +45,9 @@ class TaskApiTest extends TestCase
private function checkTimeLog(array $log): bool
{
- if(count($log) == 0)
+ if (count($log) == 0) {
return true;
+ }
/*Get first value of all arrays*/
$result = array_column($log, 0);
@@ -57,57 +58,58 @@ class TaskApiTest extends TestCase
$new_array = [];
/*Rebuild the array in order*/
- foreach($result as $key => $value)
+ foreach ($result as $key => $value) {
$new_array[] = $log[$key];
+ }
/*Iterate through the array and perform checks*/
- foreach($new_array as $key => $array)
- {
+ foreach ($new_array as $key => $array) {
/*Flag which helps us know if there is a NEXT timelog*/
$next = false;
/* If there are more than 1 time log in the array, ensure the last timestamp is not zero*/
- if(count($new_array) >1 && $array[1] == 0)
+ if (count($new_array) >1 && $array[1] == 0) {
return false;
+ }
- /* Check if the start time is greater than the end time */
- /* Ignore the last value for now, we'll do a separate check for this */
- if($array[0] > $array[1] && $array[1] != 0)
+ /* Check if the start time is greater than the end time */
+ /* Ignore the last value for now, we'll do a separate check for this */
+ if ($array[0] > $array[1] && $array[1] != 0) {
return false;
+ }
/* Find the next time log value - if it exists */
- if(array_key_exists($key+1, $new_array))
+ if (array_key_exists($key+1, $new_array)) {
$next = $new_array[$key+1];
+ }
/* check the next time log and ensure the start time is GREATER than the end time of the previous record */
- if($next && $next[0] < $array[1])
+ if ($next && $next[0] < $array[1]) {
return false;
+ }
/* Get the last row of the timelog*/
$last_row = end($new_array);
/*If the last value is NOT zero, ensure start time is not GREATER than the endtime */
- if($last_row[1] != 0 && $last_row[0] > $last_row[1])
+ if ($last_row[1] != 0 && $last_row[0] > $last_row[1]) {
return false;
+ }
return true;
}
-
}
public function testTimeLogChecker1()
{
-
$log = [
[50,0]
];
$this->assertTrue($this->checkTimeLog($log));
-
}
public function testTimeLogChecker2()
{
-
$log = [
[4,5],
[5,1]
@@ -115,13 +117,11 @@ class TaskApiTest extends TestCase
$this->assertFalse($this->checkTimeLog($log));
-
}
public function testTimeLogChecker3()
{
-
$log = [
[4,5],
[3,50]
@@ -129,13 +129,11 @@ class TaskApiTest extends TestCase
$this->assertFalse($this->checkTimeLog($log));
-
}
public function testTimeLogChecker4()
{
-
$log = [
[4,5],
[3,0]
@@ -143,12 +141,10 @@ class TaskApiTest extends TestCase
$this->assertFalse($this->checkTimeLog($log));
-
}
public function testTimeLogChecker5()
{
-
$log = [
[4,5],
[3,1]
@@ -156,12 +152,10 @@ class TaskApiTest extends TestCase
$this->assertFalse($this->checkTimeLog($log));
-
}
public function testTimeLogChecker6()
{
-
$log = [
[4,5],
[1,3],
@@ -169,12 +163,10 @@ class TaskApiTest extends TestCase
$this->assertTrue($this->checkTimeLog($log));
-
}
public function testTimeLogChecker7()
{
-
$log = [
[1,3],
[4,5]
@@ -182,58 +174,49 @@ class TaskApiTest extends TestCase
$this->assertTrue($this->checkTimeLog($log));
-
}
public function testTimeLogChecker8()
{
-
$log = [
[1,3],
[50,0]
];
$this->assertTrue($this->checkTimeLog($log));
-
}
public function testTimeLogChecker9()
{
-
$log = [
[4,5,'bb'],
[50,0,'aa'],
];
$this->assertTrue($this->checkTimeLog($log));
-
}
public function testTimeLogChecker10()
{
-
$log = [
[4,5,'5'],
[50,0,'3'],
];
$this->assertTrue($this->checkTimeLog($log));
-
}
public function testTimeLogChecker11()
{
-
$log = [
[1,2,'a'],
[3,4,'d'],
];
$this->assertTrue($this->checkTimeLog($log));
-
}
@@ -244,7 +227,6 @@ class TaskApiTest extends TestCase
'X-API-TOKEN' => $this->token,
])->get('/api/v1/tasks?client_status=invoiced')
->assertStatus(200);
-
}
public function testTaskLockingGate()
@@ -296,7 +278,6 @@ class TaskApiTest extends TestCase
$arr = $response->json();
$response->assertStatus(401);
-
}
@@ -345,7 +326,6 @@ class TaskApiTest extends TestCase
} catch (ValidationException $e) {
$response->assertStatus(302);
}
-
}
public function testTimeLogValidation1()
@@ -361,7 +341,6 @@ class TaskApiTest extends TestCase
$arr = $response->json();
$response->assertStatus(200);
-
}
@@ -379,8 +358,6 @@ class TaskApiTest extends TestCase
$arr = $response->json();
$response->assertStatus(200);
-
-
}
public function testTimeLogValidation3()
@@ -399,7 +376,6 @@ class TaskApiTest extends TestCase
} catch (ValidationException $e) {
$response->assertStatus(302);
}
-
}
public function testTimeLogValidation4()
@@ -415,8 +391,6 @@ class TaskApiTest extends TestCase
$arr = $response->json();
$response->assertStatus(200);
-
-
}
@@ -513,15 +487,14 @@ class TaskApiTest extends TestCase
];
try {
- $response = $this->withHeaders([
- 'X-API-SECRET' => config('ninja.api_secret'),
- 'X-API-TOKEN' => $this->token,
- ])->post('/api/v1/tasks', $data);
+ $response = $this->withHeaders([
+ 'X-API-SECRET' => config('ninja.api_secret'),
+ 'X-API-TOKEN' => $this->token,
+ ])->post('/api/v1/tasks', $data);
$arr = $response->json();
} catch (ValidationException $e) {
$response->assertStatus(302);
}
-
}
public function testTaskPostWithActionStart()
diff --git a/tests/Feature/UpdatePaymentTest.php b/tests/Feature/UpdatePaymentTest.php
index cc53702ed6fa..911b6d68a24b 100644
--- a/tests/Feature/UpdatePaymentTest.php
+++ b/tests/Feature/UpdatePaymentTest.php
@@ -11,20 +11,12 @@
namespace Tests\Feature;
-use App\DataMapper\ClientSettings;
-use App\Factory\ClientFactory;
-use App\Factory\CreditFactory;
use App\Factory\InvoiceFactory;
-use App\Factory\InvoiceItemFactory;
-use App\Factory\PaymentFactory;
use App\Helpers\Invoice\InvoiceSum;
use App\Models\Client;
-use App\Models\ClientContact;
-use App\Models\Credit;
use App\Models\Invoice;
use App\Models\Payment;
use App\Utils\Traits\MakesHash;
-use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\WithoutEvents;
use Illuminate\Routing\Middleware\ThrottleRequests;
@@ -62,7 +54,6 @@ class UpdatePaymentTest extends TestCase
public function testUpdatePaymentClientPaidToDate()
{
-
//Create new client
$client = Client::factory()->create([
'user_id' => $this->user->id,
diff --git a/tests/Feature/UserTest.php b/tests/Feature/UserTest.php
index 39d4dafefc1b..8d6dd7fdc045 100644
--- a/tests/Feature/UserTest.php
+++ b/tests/Feature/UserTest.php
@@ -12,7 +12,6 @@
namespace Tests\Feature;
use App\Factory\CompanyUserFactory;
-use App\Factory\UserFactory;
use App\Http\Middleware\PasswordProtection;
use App\Models\Company;
use App\Models\CompanyToken;
@@ -55,12 +54,10 @@ class UserTest extends TestCase
ThrottleRequests::class,
PasswordProtection::class
);
-
}
public function testUserFiltersWith()
{
-
$response = $this->withHeaders([
'X-API-SECRET' => config('ninja.api_secret'),
'X-API-TOKEN' => $this->token,
@@ -68,7 +65,6 @@ class UserTest extends TestCase
])->get('/api/v1/users?with='.$this->user->hashed_id);
$response->assertStatus(200);
-
}
public function testUserList()
@@ -105,7 +101,6 @@ class UserTest extends TestCase
])->post('/api/v1/users?include=company_user', $data);
$response->assertStatus(200);
-
}
public function testValidationRulesPhoneIsBlankString()
@@ -155,7 +150,6 @@ class UserTest extends TestCase
'X-API-TOKEN' => $this->token,
'X-API-PASSWORD' => 'ALongAndBriliantPassword',
])->putJson('/api/v1/users/'.$user->hashed_id.'?include=company_user', $data);
-
}
public function testUserStore()
diff --git a/tests/Feature/WebhookAPITest.php b/tests/Feature/WebhookAPITest.php
index 0d1708a2f34a..a2ed5c54f3a3 100644
--- a/tests/Feature/WebhookAPITest.php
+++ b/tests/Feature/WebhookAPITest.php
@@ -11,14 +11,10 @@
namespace Tests\Feature;
-use App\Jobs\Util\WebhookHandler;
-use App\Repositories\ClientContactRepository;
-use App\Repositories\ClientRepository;
use App\Utils\Traits\MakesHash;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Routing\Middleware\ThrottleRequests;
-use Illuminate\Support\Facades\Queue;
use Tests\MockAccountData;
use Tests\TestCase;
@@ -71,7 +67,6 @@ class WebhookAPITest extends TestCase
public function testWebhookPostRoute()
{
-
$data = [
'target_url' => 'http://hook.com',
'event_id' => 1,
diff --git a/tests/Integration/CheckRemindersTest.php b/tests/Integration/CheckRemindersTest.php
index ab6478a1fdc1..9911349f05bd 100644
--- a/tests/Integration/CheckRemindersTest.php
+++ b/tests/Integration/CheckRemindersTest.php
@@ -12,7 +12,6 @@
namespace Tests\Integration;
use App\Models\Invoice;
-use App\Utils\Traits\MakesReminders;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Carbon;
use Tests\MockAccountData;
diff --git a/tests/Integration/CompanyLedgerTest.php b/tests/Integration/CompanyLedgerTest.php
index f07f36b62e00..8a4927886015 100644
--- a/tests/Integration/CompanyLedgerTest.php
+++ b/tests/Integration/CompanyLedgerTest.php
@@ -23,11 +23,8 @@ use App\Models\Payment;
use App\Models\User;
use App\Utils\Traits\MakesHash;
use Illuminate\Foundation\Testing\DatabaseTransactions;
-use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Hash;
-use Illuminate\Support\Facades\Schema;
use Illuminate\Validation\ValidationException;
-use Tests\MockAccountData;
use Tests\TestCase;
/** @test*/
diff --git a/tests/Integration/DownloadHistoricalInvoiceTest.php b/tests/Integration/DownloadHistoricalInvoiceTest.php
index 5bd475668f29..acce97b9afa4 100644
--- a/tests/Integration/DownloadHistoricalInvoiceTest.php
+++ b/tests/Integration/DownloadHistoricalInvoiceTest.php
@@ -57,6 +57,4 @@ class DownloadHistoricalInvoiceTest extends TestCase
$this->assertNotNull($this->invoice->activities);
}
-
-
}
diff --git a/tests/Integration/EventTest.php b/tests/Integration/EventTest.php
index ccf565521fd5..8d2323c6e61d 100644
--- a/tests/Integration/EventTest.php
+++ b/tests/Integration/EventTest.php
@@ -6,7 +6,7 @@
*
* @copyright Copyright (c) 2021. Invoice Ninja LLC (https://invoiceninja.com)
*
- * @license https://www.elastic.co/licensing/elastic-license
+ * @license https://www.elastic.co/licensing/elastic-license
*/
namespace Tests\Integration;
@@ -31,15 +31,15 @@ use App\Events\Invoice\InvoiceWasDeleted;
use App\Events\Invoice\InvoiceWasRestored;
use App\Events\Invoice\InvoiceWasUpdated;
use App\Events\Payment\PaymentWasArchived;
-use App\Events\PurchaseOrder\PurchaseOrderWasCreated;
-use App\Events\PurchaseOrder\PurchaseOrderWasUpdated;
-use App\Events\PurchaseOrder\PurchaseOrderWasArchived;
-use App\Events\PurchaseOrder\PurchaseOrderWasRestored;
-use App\Events\PurchaseOrder\PurchaseOrderWasDeleted;
use App\Events\Payment\PaymentWasCreated;
use App\Events\Payment\PaymentWasDeleted;
use App\Events\Payment\PaymentWasRestored;
use App\Events\Payment\PaymentWasUpdated;
+use App\Events\PurchaseOrder\PurchaseOrderWasArchived;
+use App\Events\PurchaseOrder\PurchaseOrderWasCreated;
+use App\Events\PurchaseOrder\PurchaseOrderWasDeleted;
+use App\Events\PurchaseOrder\PurchaseOrderWasRestored;
+use App\Events\PurchaseOrder\PurchaseOrderWasUpdated;
use App\Events\Quote\QuoteWasApproved;
use App\Events\Quote\QuoteWasArchived;
use App\Events\Quote\QuoteWasCreated;
@@ -167,7 +167,6 @@ class EventTest extends TestCase
public function testVendorEvents()
{
-
$this->expectsEvents([
VendorWasCreated::class,
VendorWasUpdated::class,
@@ -227,7 +226,6 @@ class EventTest extends TestCase
public function testTaskEvents()
{
-
/* Test fire new invoice */
$data = [
'client_id' => $this->client->hashed_id,
@@ -288,7 +286,6 @@ class EventTest extends TestCase
public function testCreditEvents()
{
-
/* Test fire new invoice */
$data = [
'client_id' => $this->client->hashed_id,
@@ -349,7 +346,6 @@ class EventTest extends TestCase
public function testQuoteEvents()
{
-
/* Test fire new invoice */
$data = [
'client_id' => $this->client->hashed_id,
@@ -812,75 +808,72 @@ class EventTest extends TestCase
public function PurchaseOrderEvents()
- {
+{
+ /* Test fire new invoice */
+ $data = [
+ 'client_id' => $this->vendor->hashed_id,
+ 'number' => 'dude',
+ ];
- /* Test fire new invoice */
- $data = [
- 'client_id' => $this->vendor->hashed_id,
- 'number' => 'dude',
- ];
+ $this->expectsEvents([
+ PurchaseOrderWasCreated::class,
+ PurchaseOrderWasUpdated::class,
+ PurchaseOrderWasArchived::class,
+ PurchaseOrderWasRestored::class,
+ PurchaseOrderWasDeleted::class,
+ ]);
- $this->expectsEvents([
- PurchaseOrderWasCreated::class,
- PurchaseOrderWasUpdated::class,
- PurchaseOrderWasArchived::class,
- PurchaseOrderWasRestored::class,
- PurchaseOrderWasDeleted::class,
- ]);
-
- $response = $this->withHeaders([
- 'X-API-SECRET' => config('ninja.api_secret'),
- 'X-API-TOKEN' => $this->token,
- ])->postJson('/api/v1/purchase_orders/', $data)
- ->assertStatus(200);
+ $response = $this->withHeaders([
+ 'X-API-SECRET' => config('ninja.api_secret'),
+ 'X-API-TOKEN' => $this->token,
+ ])->postJson('/api/v1/purchase_orders/', $data)
+ ->assertStatus(200);
- $arr = $response->json();
+ $arr = $response->json();
- $data = [
- 'client_id' => $this->vendor->hashed_id,
- 'number' => 'dude2',
- ];
+ $data = [
+ 'client_id' => $this->vendor->hashed_id,
+ 'number' => 'dude2',
+ ];
- $response = $this->withHeaders([
- 'X-API-SECRET' => config('ninja.api_secret'),
- 'X-API-TOKEN' => $this->token,
- ])->putJson('/api/v1/purchase_orders/' . $arr['data']['id'], $data)
- ->assertStatus(200);
+ $response = $this->withHeaders([
+ 'X-API-SECRET' => config('ninja.api_secret'),
+ 'X-API-TOKEN' => $this->token,
+ ])->putJson('/api/v1/purchase_orders/' . $arr['data']['id'], $data)
+ ->assertStatus(200);
- $data = [
- 'ids' => [$arr['data']['id']],
- ];
+ $data = [
+ 'ids' => [$arr['data']['id']],
+ ];
- $quote = PurchaseOrder::find($this->decodePrimaryKey($arr['data']['id']));
- $quote->status_id = PurchaseOrder::STATUS_SENT;
- $quote->save();
+ $quote = PurchaseOrder::find($this->decodePrimaryKey($arr['data']['id']));
+ $quote->status_id = PurchaseOrder::STATUS_SENT;
+ $quote->save();
- $response = $this->withHeaders([
- 'X-API-SECRET' => config('ninja.api_secret'),
- 'X-API-TOKEN' => $this->token,
- ])->postJson('/api/v1/purchase_orders/bulk?action=archive', $data)
- ->assertStatus(200);
+ $response = $this->withHeaders([
+ 'X-API-SECRET' => config('ninja.api_secret'),
+ 'X-API-TOKEN' => $this->token,
+ ])->postJson('/api/v1/purchase_orders/bulk?action=archive', $data)
+ ->assertStatus(200);
- $response = $this->withHeaders([
- 'X-API-SECRET' => config('ninja.api_secret'),
- 'X-API-TOKEN' => $this->token,
- ])->postJson('/api/v1/purchase_orders/bulk?action=restore', $data)
- ->assertStatus(200);
-
- $response = $this->withHeaders([
- 'X-API-SECRET' => config('ninja.api_secret'),
- 'X-API-TOKEN' => $this->token,
- ])->postJson('/api/v1/purchase_orders/bulk?action=approve', $data)
- ->assertStatus(200);
-
- $response = $this->withHeaders([
- 'X-API-SECRET' => config('ninja.api_secret'),
- 'X-API-TOKEN' => $this->token,
- ])->postJson('/api/v1/purchase_orders/bulk?action=delete', $data)
- ->assertStatus(200);
- }
+ $response = $this->withHeaders([
+ 'X-API-SECRET' => config('ninja.api_secret'),
+ 'X-API-TOKEN' => $this->token,
+ ])->postJson('/api/v1/purchase_orders/bulk?action=restore', $data)
+ ->assertStatus(200);
+ $response = $this->withHeaders([
+ 'X-API-SECRET' => config('ninja.api_secret'),
+ 'X-API-TOKEN' => $this->token,
+ ])->postJson('/api/v1/purchase_orders/bulk?action=approve', $data)
+ ->assertStatus(200);
+ $response = $this->withHeaders([
+ 'X-API-SECRET' => config('ninja.api_secret'),
+ 'X-API-TOKEN' => $this->token,
+ ])->postJson('/api/v1/purchase_orders/bulk?action=delete', $data)
+ ->assertStatus(200);
+}
}
diff --git a/tests/Integration/MultiDBUserTest.php b/tests/Integration/MultiDBUserTest.php
index b61c0662e6f6..354cae6ded51 100644
--- a/tests/Integration/MultiDBUserTest.php
+++ b/tests/Integration/MultiDBUserTest.php
@@ -180,8 +180,7 @@ class MultiDBUserTest extends TestCase
public function test_cross_db_user_linking_fails_appropriately()
{
-
- //$this->withoutExceptionHandling();
+ //$this->withoutExceptionHandling();
$data = [
'first_name' => 'hey',
diff --git a/tests/Integration/PostmarkWebhookTest.php b/tests/Integration/PostmarkWebhookTest.php
index 2ad08ff60fb2..f57191cedabc 100644
--- a/tests/Integration/PostmarkWebhookTest.php
+++ b/tests/Integration/PostmarkWebhookTest.php
@@ -12,7 +12,6 @@
namespace Tests\Integration;
use App\Jobs\PostMark\ProcessPostmarkWebhook;
-use App\Models\Invoice;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Tests\MockAccountData;
use Tests\TestCase;
diff --git a/tests/MockAccountData.php b/tests/MockAccountData.php
index 8c3160c95b96..b1caf098c759 100644
--- a/tests/MockAccountData.php
+++ b/tests/MockAccountData.php
@@ -41,7 +41,6 @@ use App\Models\InvoiceInvitation;
use App\Models\Payment;
use App\Models\Product;
use App\Models\Project;
-use App\Models\PurchaseOrder;
use App\Models\PurchaseOrderInvitation;
use App\Models\Quote;
use App\Models\QuoteInvitation;
@@ -64,7 +63,6 @@ use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Storage;
-use Illuminate\Support\Str;
/**
* Class MockAccountData.
@@ -196,7 +194,6 @@ trait MockAccountData
$this->artisan('db:seed --force');
foreach ($cached_tables as $name => $class) {
-
// check that the table exists in case the migration is pending
if (! Schema::hasTable((new $class())->getTable())) {
continue;
@@ -828,7 +825,6 @@ trait MockAccountData
]);
$this->scheduler->save();
-
}
/**
diff --git a/tests/Unit/AutoBillInvoiceTest.php b/tests/Unit/AutoBillInvoiceTest.php
index aa8ef0281e66..c4a2f5a761b0 100644
--- a/tests/Unit/AutoBillInvoiceTest.php
+++ b/tests/Unit/AutoBillInvoiceTest.php
@@ -11,7 +11,6 @@
namespace Tests\Unit;
-use App\Models\Invoice;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Tests\MockAccountData;
use Tests\TestCase;
@@ -47,5 +46,4 @@ class AutoBillInvoiceTest extends TestCase
$this->assertEquals($this->client->fresh()->paid_to_date, 10);
$this->assertEquals($this->client->fresh()->credit_balance, 0);
}
-
}
diff --git a/tests/Unit/CentConversionTest.php b/tests/Unit/CentConversionTest.php
index ec166fd680d6..026cbc97a5f9 100644
--- a/tests/Unit/CentConversionTest.php
+++ b/tests/Unit/CentConversionTest.php
@@ -11,7 +11,6 @@
namespace Tests\Unit;
-use App\DataMapper\ClientSettings;
use Tests\TestCase;
/**
diff --git a/tests/Unit/Chart/ChartCurrencyTest.php b/tests/Unit/Chart/ChartCurrencyTest.php
index 2f30dfd57964..888d5c35f0a1 100644
--- a/tests/Unit/Chart/ChartCurrencyTest.php
+++ b/tests/Unit/Chart/ChartCurrencyTest.php
@@ -15,7 +15,6 @@ use App\DataMapper\ClientSettings;
use App\Models\Client;
use App\Models\Invoice;
use App\Services\Chart\ChartService;
-use App\Utils\Ninja;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Tests\MockAccountData;
use Tests\TestCase;
diff --git a/tests/Unit/ClientSettingsTest.php b/tests/Unit/ClientSettingsTest.php
index befc88b2d62b..01e707a70506 100644
--- a/tests/Unit/ClientSettingsTest.php
+++ b/tests/Unit/ClientSettingsTest.php
@@ -31,7 +31,6 @@ class ClientSettingsTest extends TestCase
$this->makeTestData();
$this->faker = \Faker\Factory::create();
-
}
public function testClientBaseline()
@@ -101,7 +100,6 @@ class ClientSettingsTest extends TestCase
public function testClientIllegalCurrency()
{
-
$data = [
'name' => $this->faker->firstName(),
'id_number' => 'Cooliox2',
diff --git a/tests/Unit/CollectionMergingTest.php b/tests/Unit/CollectionMergingTest.php
index a4afd8993f8e..016c5922b7aa 100644
--- a/tests/Unit/CollectionMergingTest.php
+++ b/tests/Unit/CollectionMergingTest.php
@@ -13,8 +13,6 @@ namespace Tests\Unit;
use App\Factory\ClientContactFactory;
use App\Factory\InvoiceItemFactory;
-use App\Utils\Traits\UserSessionAttributes;
-use Illuminate\Support\Facades\Session;
use Tests\TestCase;
/**
diff --git a/tests/Unit/CompanyDocumentsTest.php b/tests/Unit/CompanyDocumentsTest.php
index 49ef1058bc59..0675197caccf 100644
--- a/tests/Unit/CompanyDocumentsTest.php
+++ b/tests/Unit/CompanyDocumentsTest.php
@@ -50,7 +50,8 @@ class CompanyDocumentsTest extends TestCase
UploadFile::IMAGE,
$this->user,
$this->company,
- $this->invoice))->handle();
+ $this->invoice
+ ))->handle();
$this->assertNotNull($document);
diff --git a/tests/Unit/CompareCollectionTest.php b/tests/Unit/CompareCollectionTest.php
index d51f55b606b4..718a92258e48 100644
--- a/tests/Unit/CompareCollectionTest.php
+++ b/tests/Unit/CompareCollectionTest.php
@@ -53,19 +53,15 @@ class CompareCollectionTest extends TestCase
$invoices = explode(",", $invoice_ids);
- if(count($invoices) >= 1)
- {
-
- foreach($invoices as $invoice){
-
- if(is_string($invoice) && strlen($invoice) > 1)
+ if (count($invoices) >= 1) {
+ foreach ($invoices as $invoice) {
+ if (is_string($invoice) && strlen($invoice) > 1) {
$collection->push($this->decodePrimaryKey($invoice));
+ }
}
-
}
$this->assertEquals(0, $collection->count());
-
}
public function testCompareResultOfComparison()
diff --git a/tests/Unit/CreditBalanceTest.php b/tests/Unit/CreditBalanceTest.php
index 322ce031a311..68122c2739d0 100644
--- a/tests/Unit/CreditBalanceTest.php
+++ b/tests/Unit/CreditBalanceTest.php
@@ -11,12 +11,7 @@
namespace Tests\Unit;
-use App\Models\Account;
-use App\Models\Client;
-use App\Models\Company;
use App\Models\Credit;
-use App\Models\CreditInvitation;
-use App\Models\User;
use App\Utils\Traits\AppSetup;
use Tests\MockUnitData;
use Tests\TestCase;
@@ -86,7 +81,7 @@ class CreditBalanceTest extends TestCase
$credit->push();
- //delete invoice
+ //delete invoice
$data = [
'ids' => [$credit->hashed_id],
];
@@ -101,7 +96,7 @@ class CreditBalanceTest extends TestCase
$this->assertEquals(0, $client->credit_balance);
- //restore invoice
+ //restore invoice
$response = $this->withHeaders([
'X-API-SECRET' => config('ninja.api_secret'),
'X-API-TOKEN' => $this->token,
diff --git a/tests/Unit/DatesTest.php b/tests/Unit/DatesTest.php
index 5045414bc450..0fbaf15987d1 100644
--- a/tests/Unit/DatesTest.php
+++ b/tests/Unit/DatesTest.php
@@ -11,7 +11,6 @@
namespace Tests\Unit;
-use App\Helpers\Invoice\InvoiceSum;
use Carbon\Carbon;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Tests\MockAccountData;
diff --git a/tests/Unit/EntityTranslationTest.php b/tests/Unit/EntityTranslationTest.php
index 4922b0e48d10..02942cea3456 100644
--- a/tests/Unit/EntityTranslationTest.php
+++ b/tests/Unit/EntityTranslationTest.php
@@ -175,7 +175,5 @@ class EntityTranslationTest extends TestCase
$this->assertEquals(str_replace(" ", "_", ctrans('texts.invoice')) . "_xxx", $invoice->numberFormatter());
$this->assertEquals(str_replace(" ", "_", ctrans('texts.quote')) . "_xxx", $quote->numberFormatter());
$this->assertEquals(str_replace(" ", "_", ctrans('texts.purchase_order')) . "_xxx", $po->numberFormatter());
-
-
}
}
diff --git a/tests/Unit/GeneratesConvertedQuoteCounterTest.php b/tests/Unit/GeneratesConvertedQuoteCounterTest.php
index 76470d1aa72c..488fa5aaad19 100644
--- a/tests/Unit/GeneratesConvertedQuoteCounterTest.php
+++ b/tests/Unit/GeneratesConvertedQuoteCounterTest.php
@@ -11,26 +11,18 @@
namespace Tests\Unit;
-use App\DataMapper\ClientSettings;
-use App\Factory\ClientFactory;
-use App\Factory\QuoteFactory;
-use App\Factory\VendorFactory;
use App\Models\Account;
use App\Models\Client;
use App\Models\ClientContact;
use App\Models\Company;
-use App\Models\Credit;
use App\Models\Invoice;
use App\Models\Quote;
-use App\Models\RecurringInvoice;
-use App\Models\Timezone;
use App\Models\User;
use App\Utils\Traits\GeneratesConvertedQuoteCounter;
use App\Utils\Traits\MakesHash;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\Session;
-use Tests\MockAccountData;
use Tests\TestCase;
/**
diff --git a/tests/Unit/GeneratesCounterTest.php b/tests/Unit/GeneratesCounterTest.php
index 5d6f68c4776f..87f002bd2756 100644
--- a/tests/Unit/GeneratesCounterTest.php
+++ b/tests/Unit/GeneratesCounterTest.php
@@ -13,7 +13,6 @@ namespace Tests\Unit;
use App\DataMapper\ClientSettings;
use App\Factory\ClientFactory;
-use App\Factory\QuoteFactory;
use App\Factory\VendorFactory;
use App\Models\Client;
use App\Models\Company;
diff --git a/tests/Unit/InvitationTest.php b/tests/Unit/InvitationTest.php
index 08a84ee35ef0..8ed282052e20 100644
--- a/tests/Unit/InvitationTest.php
+++ b/tests/Unit/InvitationTest.php
@@ -12,7 +12,6 @@
namespace Tests\Unit;
use App\Factory\InvoiceInvitationFactory;
-use App\Models\CompanyToken;
use App\Utils\Traits\MakesHash;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Routing\Middleware\ThrottleRequests;
diff --git a/tests/Unit/InvoiceStatusTest.php b/tests/Unit/InvoiceStatusTest.php
index 90d9000492fa..4f2e5835aa34 100644
--- a/tests/Unit/InvoiceStatusTest.php
+++ b/tests/Unit/InvoiceStatusTest.php
@@ -11,8 +11,6 @@
namespace Tests\Unit;
-use App\Factory\InvoiceItemFactory;
-use App\Helpers\Invoice\InvoiceSum;
use App\Models\Invoice;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Tests\MockAccountData;
diff --git a/tests/Unit/InvoiceTest.php b/tests/Unit/InvoiceTest.php
index 0ed0ebb67085..a289f8f01356 100644
--- a/tests/Unit/InvoiceTest.php
+++ b/tests/Unit/InvoiceTest.php
@@ -80,7 +80,6 @@ class InvoiceTest extends TestCase
// $this->invoice->save();
$this->assertEquals($invoice_calc->getTotalTaxes(), 15.96);
-
}
private function buildLineItems()
diff --git a/tests/Unit/LateFeeTest.php b/tests/Unit/LateFeeTest.php
index 28ef22a50d4e..66acfdbe742a 100644
--- a/tests/Unit/LateFeeTest.php
+++ b/tests/Unit/LateFeeTest.php
@@ -34,7 +34,6 @@ class LateFeeTest extends TestCase
public function testLateFeeBalances()
{
-
$this->assertEquals(10, $this->client->balance);
$this->assertEquals(10, $this->invoice->balance);
@@ -42,12 +41,10 @@ class LateFeeTest extends TestCase
$this->assertEquals(15, $this->client->fresh()->balance);
$this->assertEquals(15, $this->invoice->fresh()->balance);
-
}
private function setLateFee($invoice, $amount, $percent) :Invoice
{
-
$temp_invoice_balance = $invoice->balance;
if ($amount <= 0 && $percent <= 0) {
@@ -82,5 +79,4 @@ class LateFeeTest extends TestCase
return $invoice;
}
-
}
diff --git a/tests/Unit/NumberTest.php b/tests/Unit/NumberTest.php
index f76e15685bec..8cd7f0ccaff4 100644
--- a/tests/Unit/NumberTest.php
+++ b/tests/Unit/NumberTest.php
@@ -11,7 +11,6 @@
namespace Tests\Unit;
-use App\Models\Currency;
use App\Utils\Number;
use Tests\TestCase;
@@ -21,7 +20,6 @@ use Tests\TestCase;
*/
class NumberTest extends TestCase
{
-
public function testFloatPrecision()
{
$value = 1.1;
@@ -97,5 +95,4 @@ class NumberTest extends TestCase
$this->assertEquals(7.99, $converted_amount);
}
-
}
diff --git a/tests/Unit/PermissionsTest.php b/tests/Unit/PermissionsTest.php
index 6638967a23ab..bf0386c2a301 100644
--- a/tests/Unit/PermissionsTest.php
+++ b/tests/Unit/PermissionsTest.php
@@ -20,8 +20,6 @@ use App\Models\CompanyUser;
use App\Models\Invoice;
use App\Models\RecurringInvoice;
use App\Models\User;
-use Illuminate\Foundation\Testing\DatabaseTransactions;
-use Tests\MockAccountData;
use Tests\TestCase;
/**
@@ -29,7 +27,6 @@ use Tests\TestCase;
*/
class PermissionsTest extends TestCase
{
-
public User $user;
public CompanyUser $cu;
@@ -76,12 +73,10 @@ class PermissionsTest extends TestCase
$company_token->token = $this->token;
$company_token->is_system = true;
$company_token->save();
-
}
public function testIntersectPermissions()
{
-
$low_cu = CompanyUser::where(['company_id' => $this->company->id, 'user_id' => $this->user->id])->first();
$low_cu->permissions = '["view_client"]';
$low_cu->save();
@@ -110,12 +105,10 @@ class PermissionsTest extends TestCase
$this->assertFalse($this->user->hasIntersectPermissions(["createbank_transaction"]));
$this->assertTrue($this->user->hasIntersectPermissions(["create_bank_transaction"]));
$this->assertTrue($this->user->hasIntersectPermissions(['create_bank_transaction','edit_bank_transaction','view_bank_transaction']));
-
}
public function testViewClientPermission()
{
-
$low_cu = CompanyUser::where(['company_id' => $this->company->id, 'user_id' => $this->user->id])->first();
$low_cu->permissions = '["view_client"]';
$low_cu->save();
@@ -168,7 +161,6 @@ class PermissionsTest extends TestCase
$low_cu->save();
$this->assertTrue($this->user->hasPermission('view_recurring_invoice'));
-
}
public function testPermissionResolution()
@@ -216,44 +208,36 @@ class PermissionsTest extends TestCase
$this->assertEquals('invoice', \Illuminate\Support\Str::snake(class_basename(Invoice::class)));
$this->assertEquals('recurring_invoice', \Illuminate\Support\Str::snake(class_basename(RecurringInvoice::class)));
-
}
public function testExactPermissions()
{
-
$this->assertTrue($this->user->hasExactPermission("view_client"));
$this->assertFalse($this->user->hasExactPermission("view_all"));
-
}
public function testMissingPermissions()
{
-
$low_cu = CompanyUser::where(['company_id' => $this->company->id, 'user_id' => $this->user->id])->first();
$low_cu->permissions = '[""]';
$low_cu->save();
$this->assertFalse($this->user->hasExactPermission("view_client"));
$this->assertFalse($this->user->hasExactPermission("view_all"));
-
}
public function testViewAllValidPermissions()
{
-
$low_cu = CompanyUser::where(['company_id' => $this->company->id, 'user_id' => $this->user->id])->first();
$low_cu->permissions = '["view_all"]';
$low_cu->save();
$this->assertTrue($this->user->hasExactPermission("view_client"));
$this->assertTrue($this->user->hasExactPermission("view_all"));
-
}
public function testReturnTypesOfStripos()
{
-
$this->assertEquals(0, stripos("view_client", ''));
$all_permission = '[]';
@@ -268,11 +252,11 @@ class PermissionsTest extends TestCase
$all_permission = "";//problems are empty strings
$this->assertTrue(empty($all_permission));
- $this->assertFalse( stripos($all_permission, "view_client") !== false);
- $this->assertFalse( is_int(stripos($all_permission, "view_client")));
+ $this->assertFalse(stripos($all_permission, "view_client") !== false);
+ $this->assertFalse(is_int(stripos($all_permission, "view_client")));
$all_permission = 'view';//will always pass currently
- $this->assertFalse( stripos($all_permission, "view_client") !== false);
+ $this->assertFalse(stripos($all_permission, "view_client") !== false);
$this->assertFalse(is_int(stripos($all_permission, "view_client")));
$all_permission = "view_client";
@@ -280,11 +264,5 @@ class PermissionsTest extends TestCase
$this->assertTrue(is_int(stripos($all_permission, "view_client")) !== false);
$this->assertTrue(is_int(stripos($all_permission, "view_client")));
-
-
}
-
-
-
}
-
diff --git a/tests/Unit/RangeDetectionTest.php b/tests/Unit/RangeDetectionTest.php
index afb9e9c211d9..9aed0da124be 100644
--- a/tests/Unit/RangeDetectionTest.php
+++ b/tests/Unit/RangeDetectionTest.php
@@ -11,7 +11,6 @@
namespace Tests\Unit;
-use Illuminate\Foundation\Testing\DatabaseTransactions;
use Tests\TestCase;
/**
diff --git a/tests/Unit/RecurringDateTest.php b/tests/Unit/RecurringDateTest.php
index e8224badb29d..4321031b290f 100644
--- a/tests/Unit/RecurringDateTest.php
+++ b/tests/Unit/RecurringDateTest.php
@@ -11,7 +11,6 @@
namespace Tests\Unit;
-use App\Models\Invoice;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Carbon;
use Tests\MockAccountData;
@@ -42,5 +41,4 @@ class RecurringDateTest extends TestCase
$this->assertequals($trial_ends->format('Y-m-d'), '2021-12-03');
}
-
}
diff --git a/tests/Unit/RecurringExpenseCloneTest.php b/tests/Unit/RecurringExpenseCloneTest.php
index 6fc877068ad5..9a20f5c8968c 100644
--- a/tests/Unit/RecurringExpenseCloneTest.php
+++ b/tests/Unit/RecurringExpenseCloneTest.php
@@ -16,9 +16,7 @@ use App\Factory\RecurringExpenseToExpenseFactory;
use App\Models\Account;
use App\Models\Client;
use App\Models\Company;
-use App\Models\RecurringExpense;
use App\Models\User;
-use App\Utils\Ninja;
use Tests\TestCase;
/**
diff --git a/tests/Unit/RedisVsDatabaseTest.php b/tests/Unit/RedisVsDatabaseTest.php
index d53a479d268d..e2b0af1b7015 100644
--- a/tests/Unit/RedisVsDatabaseTest.php
+++ b/tests/Unit/RedisVsDatabaseTest.php
@@ -12,10 +12,7 @@
namespace Tests\Unit;
use App\Models\Currency;
-use App\Models\Invoice;
-use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\Cache;
-use Tests\MockAccountData;
use Tests\TestCase;
/**
diff --git a/tests/Unit/RefundUnitTest.php b/tests/Unit/RefundUnitTest.php
index c2a375543124..067eeca9ae77 100644
--- a/tests/Unit/RefundUnitTest.php
+++ b/tests/Unit/RefundUnitTest.php
@@ -13,7 +13,6 @@ namespace Tests\Unit;
use App\Helpers\Invoice\ProRata;
use App\Models\RecurringInvoice;
-use App\Utils\Ninja;
use Illuminate\Support\Carbon;
use Tests\TestCase;
diff --git a/tests/Unit/RelationExistsTest.php b/tests/Unit/RelationExistsTest.php
index 047dc5ec8ce0..dc4ad73189b5 100644
--- a/tests/Unit/RelationExistsTest.php
+++ b/tests/Unit/RelationExistsTest.php
@@ -11,7 +11,6 @@
namespace Tests\Unit;
-use App\Factory\CloneQuoteToInvoiceFactory;
use App\Models\Client;
use App\Models\Credit;
use App\Models\Expense;
diff --git a/tests/Unit/S3CleanupTest.php b/tests/Unit/S3CleanupTest.php
index c49ed358a184..ba90d1fe89b8 100644
--- a/tests/Unit/S3CleanupTest.php
+++ b/tests/Unit/S3CleanupTest.php
@@ -11,7 +11,6 @@
namespace Tests\Unit;
-use App\DataMapper\ClientSettings;
use Tests\TestCase;
/**
diff --git a/tests/Unit/SettingsSaverTest.php b/tests/Unit/SettingsSaverTest.php
index 051bb415ebf5..888972358b55 100644
--- a/tests/Unit/SettingsSaverTest.php
+++ b/tests/Unit/SettingsSaverTest.php
@@ -11,7 +11,6 @@
namespace Tests\Unit;
-use App\DataMapper\CompanySettings;
use App\Utils\Traits\SettingsSaver;
use Tests\TestCase;
diff --git a/tests/Unit/SubscriptionsCalcTest.php b/tests/Unit/SubscriptionsCalcTest.php
index a944507c3a32..2e8684743c9e 100644
--- a/tests/Unit/SubscriptionsCalcTest.php
+++ b/tests/Unit/SubscriptionsCalcTest.php
@@ -105,7 +105,6 @@ class SubscriptionsCalcTest extends TestCase
public function testProrataDiscountRatioPercentage()
{
-
$subscription = Subscription::factory()->create([
'company_id' => $this->company->id,
'user_id' => $this->user->id,
@@ -157,12 +156,10 @@ class SubscriptionsCalcTest extends TestCase
$ratio = $subscription->service()->calculateDiscountRatio($invoice);
$this->assertEquals(.1, $ratio);
-
}
public function testProrataDiscountRatioAmount()
{
-
$subscription = Subscription::factory()->create([
'company_id' => $this->company->id,
'user_id' => $this->user->id,
@@ -214,9 +211,5 @@ class SubscriptionsCalcTest extends TestCase
$ratio = $subscription->service()->calculateDiscountRatio($invoice);
$this->assertEquals(.2, $ratio);
-
}
-
-
-
}
diff --git a/tests/Unit/ValidationRules/BlacklistValidationTest.php b/tests/Unit/ValidationRules/BlacklistValidationTest.php
index 68a1ba915b15..1a6b54a41435 100644
--- a/tests/Unit/ValidationRules/BlacklistValidationTest.php
+++ b/tests/Unit/ValidationRules/BlacklistValidationTest.php
@@ -12,9 +12,6 @@
namespace Tests\Unit\ValidationRules;
use App\Http\ValidationRules\Account\BlackListRule;
-use App\Models\Invoice;
-use Illuminate\Foundation\Testing\DatabaseTransactions;
-use Tests\MockAccountData;
use Tests\TestCase;
/**
diff --git a/tests/Unit/ValidationRules/EmailBlacklistValidationTest.php b/tests/Unit/ValidationRules/EmailBlacklistValidationTest.php
index 57504cc7c107..16aff0d75c31 100644
--- a/tests/Unit/ValidationRules/EmailBlacklistValidationTest.php
+++ b/tests/Unit/ValidationRules/EmailBlacklistValidationTest.php
@@ -11,11 +11,7 @@
namespace Tests\Unit\ValidationRules;
-use App\Http\ValidationRules\Account\BlackListRule;
use App\Http\ValidationRules\Account\EmailBlackListRule;
-use App\Models\Invoice;
-use Illuminate\Foundation\Testing\DatabaseTransactions;
-use Tests\MockAccountData;
use Tests\TestCase;
/**
diff --git a/tests/Unit/ValidationRules/UniqueInvoiceNumberValidationTest.php b/tests/Unit/ValidationRules/UniqueInvoiceNumberValidationTest.php
index 79782df52c6a..923b092a4c19 100644
--- a/tests/Unit/ValidationRules/UniqueInvoiceNumberValidationTest.php
+++ b/tests/Unit/ValidationRules/UniqueInvoiceNumberValidationTest.php
@@ -12,10 +12,8 @@
namespace Tests\Unit\ValidationRules;
use App\Http\Requests\Invoice\StoreInvoiceRequest;
-use App\Http\ValidationRules\Account\BlackListRule;
use App\Models\Invoice;
use App\Utils\Traits\MakesHash;
-use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\Validator;
use Tests\MockAccountData;
use Tests\TestCase;
diff --git a/tests/Unit/ZeroDecimalTest.php b/tests/Unit/ZeroDecimalTest.php
index 4efc7864a74f..7327c95214e1 100644
--- a/tests/Unit/ZeroDecimalTest.php
+++ b/tests/Unit/ZeroDecimalTest.php
@@ -11,13 +11,6 @@
namespace Tests\Unit;
-use App\Jobs\Util\UploadFile;
-use App\Models\Document;
-use Illuminate\Foundation\Testing\DatabaseTransactions;
-use Illuminate\Http\UploadedFile;
-use Illuminate\Routing\Middleware\ThrottleRequests;
-use Illuminate\Support\Facades\Storage;
-use Tests\MockAccountData;
use Tests\TestCase;
class ZeroDecimalTest extends TestCase