diff --git a/app/Console/Commands/BackupUpdate.php b/app/Console/Commands/BackupUpdate.php
index 33f8b3d6abe8..fcd1e6fa04d5 100644
--- a/app/Console/Commands/BackupUpdate.php
+++ b/app/Console/Commands/BackupUpdate.php
@@ -66,39 +66,25 @@ class BackupUpdate extends Command
$this->handleOnDb();
}
- MultiDB::setDB($current_db);
-
+ MultiDB::setDB($current_db);
}
-
-
}
private function handleOnDb()
{
set_time_limit(0);
-
- Backup::whereHas('activity')->whereRaw('html_backup IS NOT NULL')->cursor()->each( function ($backup) {
-
- if(strlen($backup->html_backup) > 1 && $backup->activity->invoice->exists()){
-
- $client = $backup->activity->invoice->client;
- $backup->storeRemotely($backup->html_backup, $client);
-
- }else if(strlen($backup->html_backup) > 1 && $backup->activity->quote->exists()){
-
- $client = $backup->activity->quote->client;
- $backup->storeRemotely($backup->html_backup, $client);
-
- }else if(strlen($backup->html_backup) > 1 && $backup->activity->credit->exists()){
-
- $client = $backup->activity->credit->client;
- $backup->storeRemotely($backup->html_backup, $client);
-
- }
-
-
+ Backup::whereHas('activity')->whereRaw('html_backup IS NOT NULL')->cursor()->each(function ($backup) {
+ if (strlen($backup->html_backup) > 1 && $backup->activity->invoice->exists()) {
+ $client = $backup->activity->invoice->client;
+ $backup->storeRemotely($backup->html_backup, $client);
+ } elseif (strlen($backup->html_backup) > 1 && $backup->activity->quote->exists()) {
+ $client = $backup->activity->quote->client;
+ $backup->storeRemotely($backup->html_backup, $client);
+ } elseif (strlen($backup->html_backup) > 1 && $backup->activity->credit->exists()) {
+ $client = $backup->activity->credit->client;
+ $backup->storeRemotely($backup->html_backup, $client);
+ }
});
-
}
}
diff --git a/app/Console/Commands/CheckData.php b/app/Console/Commands/CheckData.php
index 835038859f3b..961c0d6b4693 100644
--- a/app/Console/Commands/CheckData.php
+++ b/app/Console/Commands/CheckData.php
@@ -91,21 +91,20 @@ class CheckData extends Command
protected $wrong_paid_status = 0;
-
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 ";
+ $fix_status = $this->option('fix') ? 'Fixing Issues' : 'Just checking issues ';
- $this->logMessage(date('Y-m-d h:i:s').' Running CheckData... on ' . $database_connection . " Fix Status = {$fix_status}");
+ $this->logMessage(date('Y-m-d h:i:s').' Running CheckData... on '.$database_connection." Fix Status = {$fix_status}");
if ($database = $this->option('database')) {
config(['database.default' => $database]);
}
- $this->checkInvoiceBalances();
+ $this->checkInvoiceBalances();
$this->checkPaidToDatesNew();
$this->checkContacts();
@@ -114,15 +113,16 @@ class CheckData extends Command
$this->checkCompanyData();
$this->checkBalanceVsPaidStatus();
- if(Ninja::isHosted())
+ if (Ninja::isHosted()) {
$this->checkAccountStatuses();
+ }
if (! $this->option('client_id')) {
$this->checkOAuth();
}
$this->logMessage('Done: '.strtoupper($this->isValid ? Account::RESULT_SUCCESS : Account::RESULT_FAILURE));
- $this->logMessage('Total execution time in seconds: ' . (microtime(true) - $time_start));
+ $this->logMessage('Total execution time in seconds: '.(microtime(true) - $time_start));
$errorEmail = config('ninja.error_email');
@@ -235,7 +235,7 @@ class CheckData extends Command
if ($this->option('fix') == 'true') {
foreach ($clients as $client) {
$this->logMessage("Fixing missing contacts #{$client->id}");
-
+
$new_contact = ClientContactFactory::create($client->company_id, $client->user_id);
$new_contact->client_id = $client->id;
$new_contact->contact_key = Str::random(40);
@@ -243,7 +243,6 @@ class CheckData extends Command
$new_contact->save();
}
}
-
}
private function checkVendorContacts()
@@ -291,12 +290,11 @@ class CheckData extends Command
}
if ($this->option('fix') == 'true') {
-
$vendors = Vendor::withTrashed()->doesntHave('contacts')->get();
foreach ($vendors as $vendor) {
$this->logMessage("Fixing missing vendor contacts #{$vendor->id}");
-
+
$new_contact = VendorContactFactory::create($vendor->company_id, $vendor->user_id);
$new_contact->vendor_id = $vendor->id;
$new_contact->contact_key = Str::random(40);
@@ -304,10 +302,8 @@ class CheckData extends Command
$new_contact->save();
}
}
-
}
-
private function checkFailedJobs()
{
if (config('ninja.testvars.travis')) {
@@ -356,36 +352,32 @@ class CheckData extends Command
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]);
$entities = ['invoice', 'quote', 'credit', 'recurring_invoice'];
- foreach($entities as $entity)
- {
+ foreach ($entities as $entity) {
$table = "{$entity}s";
$invitation_table = "{$entity}_invitations";
- $entities = DB::table($table)
- ->leftJoin($invitation_table, function ($join) use($invitation_table, $table, $entity){
+ $entities = DB::table($table)
+ ->leftJoin($invitation_table, function ($join) use ($invitation_table, $table, $entity) {
$join->on("{$invitation_table}.{$entity}_id", '=', "{$table}.id");
- // ->whereNull("{$invitation_table}.deleted_at");
+ // ->whereNull("{$invitation_table}.deleted_at");
})
->groupBy("{$table}.id", "{$table}.user_id", "{$table}.company_id", "{$table}.client_id")
->havingRaw("count({$invitation_table}.id) = 0")
->get(["{$table}.id", "{$table}.user_id", "{$table}.company_id", "{$table}.client_id"]);
+ $this->logMessage($entities->count()." {$table} without any invitations");
- $this->logMessage($entities->count()." {$table} without any invitations");
-
- if ($this->option('fix') == 'true')
- $this->fixInvitations($entities, $entity);
-
+ if ($this->option('fix') == 'true') {
+ $this->fixInvitations($entities, $entity);
+ }
}
-
}
private function fixInvitations($entities, $entity)
@@ -394,8 +386,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;
@@ -403,20 +394,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,
@@ -431,14 +419,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
@@ -450,8 +438,8 @@ 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;
}
@@ -460,9 +448,8 @@ class CheckData extends Command
$clients_to_check = $this->clientPaidToDateQuery();
$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');
@@ -471,26 +458,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')){
- $this->logMessage("# {$client->id} " . $client->present()->name.' - '.$client->number." Fixing {$client->paid_to_date} to {$total_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()
@@ -499,12 +482,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]);
})
- ->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))')
@@ -512,19 +495,16 @@ 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])
->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
@@ -537,7 +517,6 @@ class CheckData extends Command
// 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')
@@ -547,7 +526,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++;
@@ -556,8 +535,8 @@ class CheckData extends Command
$this->isValid = false;
- if($this->option('paid_to_date')){
- $this->logMessage("# {$client->id} " . $client->present()->name.' - '.$client->number." Fixing {$client->paid_to_date} to {$total_invoice_payments}");
+ 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();
}
@@ -572,9 +551,7 @@ 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])
->selectRaw('sum(paymentables.amount - paymentables.refunded) as p')
@@ -585,7 +562,7 @@ class CheckData extends Command
$calculated_paid_amount = $invoice->amount - $invoice->balance - $total_credit;
- if ((string)$total_paid != (string)($invoice->amount - $invoice->balance - $total_credit)) {
+ if ((string) $total_paid != (string) ($invoice->amount - $invoice->balance - $total_credit)) {
$this->wrong_balances++;
$this->logMessage($client->present()->name.' - '.$client->id." - Total Paid = {$total_paid} != Calculated Total = {$calculated_paid_amount}");
@@ -593,7 +570,6 @@ class CheckData extends Command
$this->isValid = false;
}
});
-
});
$this->logMessage("{$this->wrong_balances} clients with incorrect invoice balances");
@@ -601,7 +577,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,
@@ -615,8 +591,8 @@ class CheckData extends Command
GROUP BY clients.id
HAVING invoice_balance != clients.balance
ORDER BY clients.id;
- ") );
-
+ '));
+
return $results;
}
@@ -627,29 +603,24 @@ class CheckData extends Command
$clients = $this->clientBalanceQuery();
- foreach($clients as $client)
- {
- $client = (array)$client;
-
+ foreach ($clients as $client) {
+ $client = (array) $client;
+
if ((string) $client['invoice_balance'] != (string) $client['client_balance']) {
$this->wrong_paid_to_dates++;
$client_object = Client::withTrashed()->find($client['client_id']);
- $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')){
-
- $this->logMessage("# {$client_object->id} " . $client_object->present()->name.' - '.$client_object->number." Fixing {$client_object->balance} to " . $client['invoice_balance']);
+ $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')) {
+ $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");
@@ -657,7 +628,7 @@ class CheckData extends Command
private function invoiceBalanceQuery()
{
- $results = \DB::select( \DB::raw("
+ $results = \DB::select(\DB::raw('
SELECT
clients.id,
clients.balance,
@@ -671,8 +642,8 @@ class CheckData extends Command
GROUP BY clients.id
HAVING(invoices_balance != clients.balance)
ORDER BY clients.id;
- ") );
-
+ '));
+
return $results;
}
@@ -683,11 +654,10 @@ 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');
+ $invoice_balance = $client->invoices()->where('is_deleted', false)->whereIn('status_id', [2, 3])->sum('balance');
$ledger = CompanyLedger::where('client_id', $client->id)->orderBy('id', 'DESC')->first();
@@ -695,31 +665,26 @@ class CheckData extends Command
$this->wrong_balances++;
$ledger_balance = $ledger ? $ledger->balance : 0;
- $this->logMessage("# {$client->id} " . $client->present()->name.' - '.$client->number." - Balance Failure - Invoice Balances = {$invoice_balance} Client Balance = {$client->balance} Ledger Balance = {$ledger_balance}");
+ $this->logMessage("# {$client->id} ".$client->present()->name.' - '.$client->number." - Balance Failure - Invoice Balances = {$invoice_balance} Client Balance = {$client->balance} Ledger Balance = {$ledger_balance}");
$this->isValid = false;
- if($this->option('client_balance')){
-
- $this->logMessage("# {$client->id} " . $client->present()->name.' - '.$client->number." Fixing {$client->balance} to {$invoice_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()
@@ -728,19 +693,17 @@ class CheckData extends Command
$this->wrong_paid_to_dates = 0;
foreach (Client::where('is_deleted', 0)->where('clients.updated_at', '>', now()->subDays(2))->cursor() as $client) {
- $invoice_balance = $client->invoices()->where('is_deleted', false)->whereIn('status_id', [2,3])->sum('balance');
+ $invoice_balance = $client->invoices()->where('is_deleted', false)->whereIn('status_id', [2, 3])->sum('balance');
$ledger = CompanyLedger::where('client_id', $client->id)->orderBy('id', 'DESC')->first();
if ($ledger && number_format($ledger->balance, 4) != number_format($client->balance, 4)) {
$this->wrong_balances++;
- $this->logMessage("# {$client->id} " . $client->present()->name.' - '.$client->number." - Balance Failure - Client Balance = {$client->balance} Ledger Balance = {$ledger->balance}");
+ $this->logMessage("# {$client->id} ".$client->present()->name.' - '.$client->number." - Balance Failure - Client Balance = {$client->balance} Ledger Balance = {$ledger->balance}");
$this->isValid = false;
-
- if($this->option('ledger_balance')){
-
- $this->logMessage("# {$client->id} " . $client->present()->name.' - '.$client->number." Fixing {$client->balance} to {$invoice_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();
@@ -749,7 +712,6 @@ class CheckData extends Command
$ledger->notes = 'Ledger Adjustment';
$ledger->save();
}
-
}
}
@@ -841,22 +803,20 @@ 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)
- $this->logMessage("I found a payment for {$account->key}");
+ if ($payment) {
+ $this->logMessage("I found a payment for {$account->key}");
+ }
}
-
});
}
@@ -864,24 +824,21 @@ class CheckData extends Command
{
$this->wrong_paid_status = 0;
- foreach(Invoice::with(['payments'])->whereHas('payments')->where('status_id', 4)->where('balance', '>', 0)->where('is_deleted',0)->cursor() as $invoice)
- {
+ foreach (Invoice::with(['payments'])->whereHas('payments')->where('status_id', 4)->where('balance', '>', 0)->where('is_deleted', 0)->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')){
+ $this->logMessage("# {$invoice->id} ".' - '.$invoice->number." - Marked as paid, but balance = {$invoice->balance}");
+ if ($this->option('balance_status')) {
$val = $invoice->balance;
$invoice->balance = 0;
- $invoice->paid_to_date=$val;
+ $invoice->paid_to_date = $val;
$invoice->save();
$p = $invoice->payments->first();
- if($p && (int)$p->amount == 0)
- {
+ if ($p && (int) $p->amount == 0) {
$p->amount = $val;
$p->applied = $val;
$p->save();
@@ -891,14 +848,10 @@ class CheckData extends Command
$pivot->save();
}
-
$this->logMessage("Fixing {$invoice->id} settings payment to {$val}");
-
}
-
}
- $this->logMessage($this->wrong_paid_status." wrong invoices with bad balance state");
-
+ $this->logMessage($this->wrong_paid_status.' wrong invoices with bad balance state');
}
-}
\ No newline at end of file
+}
diff --git a/app/Console/Commands/CheckDb.php b/app/Console/Commands/CheckDb.php
index b626e193c646..5f8fd0a1a0f9 100644
--- a/app/Console/Commands/CheckDb.php
+++ b/app/Console/Commands/CheckDb.php
@@ -36,8 +36,8 @@ use App\Models\GroupSetting;
use App\Models\Invoice;
use App\Models\InvoiceInvitation;
use App\Models\Payment;
-use App\Models\PaymentHash;
use App\Models\Paymentable;
+use App\Models\PaymentHash;
use App\Models\Product;
use App\Models\Project;
use App\Models\Quote;
@@ -61,13 +61,11 @@ use Illuminate\Support\Str;
use Mail;
use Symfony\Component\Console\Input\InputOption;
-
/**
* Class CheckDb.
*/
class CheckDb extends Command
{
-
protected $signature = 'ninja:check-db';
protected $description = 'Check MultiDB';
@@ -118,33 +116,30 @@ class CheckDb extends Command
public function handle()
{
+ $this->LogMessage('Checking - V5_DB1');
- $this->LogMessage("Checking - V5_DB1");
-
- foreach($this->entities as $entity) {
-
+ foreach ($this->entities as $entity) {
$count_db_1 = $entity::on('db-ninja-01')->count();
$count_db_2 = $entity::on('db-ninja-02a')->count();
$diff = $count_db_1 - $count_db_2;
- if($diff != 0)
+ if ($diff != 0) {
$this->logMessage("{$entity} DB1: {$count_db_1} - DB2: {$count_db_2} - diff = {$diff}");
-
+ }
}
- $this->LogMessage("Checking - V5_DB2");
-
- foreach($this->entities as $entity) {
+ $this->LogMessage('Checking - V5_DB2');
+ foreach ($this->entities as $entity) {
$count_db_1 = $entity::on('db-ninja-02')->count();
$count_db_2 = $entity::on('db-ninja-01a')->count();
$diff = $count_db_1 - $count_db_2;
- if($diff != 0)
+ if ($diff != 0) {
$this->logMessage("{$entity} DB1: {$count_db_1} - DB2: {$count_db_2} - diff = {$diff}");
-
+ }
}
}
@@ -154,5 +149,4 @@ class CheckDb extends Command
$this->info($str);
$this->log .= $str."\n";
}
-
}
diff --git a/app/Console/Commands/CreateAccount.php b/app/Console/Commands/CreateAccount.php
index 0def06c5d5bd..460dbe72d36b 100644
--- a/app/Console/Commands/CreateAccount.php
+++ b/app/Console/Commands/CreateAccount.php
@@ -51,10 +51,12 @@ use Illuminate\Support\Str;
class CreateAccount extends Command
{
use MakesHash, GeneratesCounter;
+
/**
* @var string
*/
protected $description = 'Create Single Account';
+
/**
* @var string
*/
@@ -82,12 +84,10 @@ class CreateAccount extends Command
$this->warmCache();
$this->createAccount();
-
}
private function createAccount()
{
-
$account = Account::factory()->create();
$company = Company::factory()->create([
'account_id' => $account->id,
@@ -134,7 +134,6 @@ class CreateAccount extends Command
CreateCompanyPaymentTerms::dispatchNow($company, $user);
CreateCompanyTaskStatuses::dispatchNow($company, $user);
VersionCheck::dispatchNow();
-
}
private function warmCache()
@@ -164,5 +163,4 @@ class CreateAccount extends Command
}
}
}
-
}
diff --git a/app/Console/Commands/CreateSingleAccount.php b/app/Console/Commands/CreateSingleAccount.php
index b51415233ce8..5708bf934e83 100644
--- a/app/Console/Commands/CreateSingleAccount.php
+++ b/app/Console/Commands/CreateSingleAccount.php
@@ -57,9 +57,9 @@ use stdClass;
class CreateSingleAccount extends Command
{
use MakesHash, GeneratesCounter;
-
+
protected $description = 'Create Single Sample Account';
-
+
protected $signature = 'ninja:create-single-account {gateway=all} {--database=db-ninja-01}';
protected $invoice_repo;
@@ -75,12 +75,13 @@ class CreateSingleAccount extends Command
*/
public function handle()
{
+ if (config('ninja.is_docker')) {
+ return;
+ }
- if(config('ninja.is_docker'))
- return;
-
- if (!$this->confirm('Are you sure you want to inject dummy data?'))
+ if (! $this->confirm('Are you sure you want to inject dummy data?')) {
return;
+ }
$this->invoice_repo = new InvoiceRepository();
@@ -105,10 +106,10 @@ class CreateSingleAccount extends Command
$company = Company::factory()->create([
'account_id' => $account->id,
'slack_webhook_url' => config('ninja.notification.slack'),
- 'default_password_timeout' => 30*60000,
+ 'default_password_timeout' => 30 * 60000,
'portal_mode' => 'domain',
'portal_domain' => 'http://ninja.test:8000',
- 'track_inventory' => true
+ 'track_inventory' => true,
]);
$settings = $company->settings;
@@ -153,33 +154,31 @@ class CreateSingleAccount extends Command
]);
Product::factory()->count(1)->create([
- 'user_id' => $user->id,
- 'company_id' => $company->id,
- ]);
-
+ 'user_id' => $user->id,
+ 'company_id' => $company->id,
+ ]);
TaxRate::factory()->create([
'user_id' => $user->id,
'company_id' => $company->id,
'name' => 'GST',
- 'rate' => 10
+ 'rate' => 10,
]);
TaxRate::factory()->create([
'user_id' => $user->id,
'company_id' => $company->id,
'name' => 'VAT',
- 'rate' => 17.5
+ 'rate' => 17.5,
]);
TaxRate::factory()->create([
'user_id' => $user->id,
'company_id' => $company->id,
'name' => 'CA Sales Tax',
- 'rate' => 5
+ 'rate' => 5,
]);
-
$this->info('Creating '.$this->count.' clients');
for ($x = 0; $x < $this->count; $x++) {
@@ -227,18 +226,18 @@ class CreateSingleAccount extends Command
$client = $company->clients->random();
- $this->info('creating task for client #' . $client->id);
+ $this->info('creating task for client #'.$client->id);
$this->createTask($client);
$client = $company->clients->random();
- $this->info('creating project for client #' . $client->id);
+ $this->info('creating project for client #'.$client->id);
$this->createProject($client);
- $this->info('creating credit for client #' . $client->id);
+ $this->info('creating credit for client #'.$client->id);
$this->createCredit($client);
- $this->info('creating recurring invoice for client # ' . $client->id);
+ $this->info('creating recurring invoice for client # '.$client->id);
$this->createRecurringInvoice($client);
}
@@ -250,7 +249,7 @@ class CreateSingleAccount extends Command
private function createSubsData($company, $user)
{
$gs = GroupSettingFactory::create($company->id, $user->id);
- $gs->name = "plans";
+ $gs->name = 'plans';
$gs->save();
$p1 = Product::factory()->create([
@@ -290,7 +289,7 @@ class CreateSingleAccount extends Command
];
$sub = SubscriptionFactory::create($company->id, $user->id);
- $sub->name = "Pro Plan";
+ $sub->name = 'Pro Plan';
$sub->group_id = $gs->id;
$sub->recurring_product_ids = "{$p1->hashed_id}";
$sub->webhook_configuration = $webhook_config;
@@ -299,7 +298,7 @@ class CreateSingleAccount extends Command
$sub->save();
$sub = SubscriptionFactory::create($company->id, $user->id);
- $sub->name = "Enterprise Plan";
+ $sub->name = 'Enterprise Plan';
$sub->group_id = $gs->id;
$sub->recurring_product_ids = "{$p2->hashed_id}";
$sub->webhook_configuration = $webhook_config;
@@ -308,7 +307,7 @@ class CreateSingleAccount extends Command
$sub->save();
$sub = SubscriptionFactory::create($company->id, $user->id);
- $sub->name = "Free Plan";
+ $sub->name = 'Free Plan';
$sub->group_id = $gs->id;
$sub->recurring_product_ids = "{$p3->hashed_id}";
$sub->webhook_configuration = $webhook_config;
@@ -324,28 +323,28 @@ class CreateSingleAccount extends Command
// });
$client = Client::factory()->create([
- 'user_id' => $user->id,
- 'company_id' => $company->id,
- ]);
+ 'user_id' => $user->id,
+ 'company_id' => $company->id,
+ ]);
ClientContact::factory()->create([
- 'user_id' => $user->id,
- 'client_id' => $client->id,
- 'company_id' => $company->id,
- 'is_primary' => 1,
- 'email' => 'user@example.com'
- ]);
+ 'user_id' => $user->id,
+ 'client_id' => $client->id,
+ 'company_id' => $company->id,
+ 'is_primary' => 1,
+ 'email' => 'user@example.com',
+ ]);
ClientContact::factory()->count(rand(1, 2))->create([
- 'user_id' => $user->id,
- 'client_id' => $client->id,
- 'company_id' => $company->id,
- ]);
+ 'user_id' => $user->id,
+ 'client_id' => $client->id,
+ 'company_id' => $company->id,
+ ]);
$client->number = $this->getNextClientNumber($client);
$settings = $client->settings;
- $settings->currency_id = "1";
+ $settings->currency_id = '1';
// $settings->use_credits_payment = "always";
$client->settings = $settings;
@@ -359,48 +358,48 @@ class CreateSingleAccount extends Command
private function createExpense($client)
{
Expense::factory()->count(rand(1, 2))->create([
- 'user_id' => $client->user->id,
- 'client_id' => $client->id,
- 'company_id' => $client->company->id,
- ]);
+ 'user_id' => $client->user->id,
+ 'client_id' => $client->id,
+ 'company_id' => $client->company->id,
+ ]);
}
private function createVendor($client)
{
$vendor = Vendor::factory()->create([
- 'user_id' => $client->user->id,
- 'company_id' => $client->company->id,
- ]);
+ 'user_id' => $client->user->id,
+ 'company_id' => $client->company->id,
+ ]);
VendorContact::factory()->create([
- 'user_id' => $client->user->id,
- 'vendor_id' => $vendor->id,
- 'company_id' => $client->company->id,
- 'is_primary' => 1,
- ]);
+ 'user_id' => $client->user->id,
+ 'vendor_id' => $vendor->id,
+ 'company_id' => $client->company->id,
+ 'is_primary' => 1,
+ ]);
VendorContact::factory()->count(rand(1, 2))->create([
- 'user_id' => $client->user->id,
- 'vendor_id' => $vendor->id,
- 'company_id' => $client->company->id,
- 'is_primary' => 0,
- ]);
+ 'user_id' => $client->user->id,
+ 'vendor_id' => $vendor->id,
+ 'company_id' => $client->company->id,
+ 'is_primary' => 0,
+ ]);
}
private function createTask($client)
{
$vendor = Task::factory()->create([
- 'user_id' => $client->user->id,
- 'company_id' => $client->company->id,
- ]);
+ 'user_id' => $client->user->id,
+ 'company_id' => $client->company->id,
+ ]);
}
private function createProject($client)
{
$vendor = Project::factory()->create([
- 'user_id' => $client->user->id,
- 'company_id' => $client->company->id,
- ]);
+ 'user_id' => $client->user->id,
+ 'company_id' => $client->company->id,
+ ]);
}
private function createInvoice($client)
@@ -517,7 +516,6 @@ class CreateSingleAccount extends Command
$quote->service()->createInvitations();
}
-
private function buildCreditItem()
{
$line_items = [];
@@ -538,11 +536,9 @@ class CreateSingleAccount extends Command
$line_items[] = $item;
-
return $line_items;
}
-
private function buildLineItems($count = 1)
{
$line_items = [];
@@ -614,7 +610,6 @@ class CreateSingleAccount extends Command
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;
@@ -633,8 +628,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')) {
@@ -742,7 +735,6 @@ class CreateSingleAccount extends Command
$cg->save();
}
-
if (config('ninja.testvars.paytrace.decrypted') && ($this->gateway == 'all' || $this->gateway == 'paytrace')) {
$cg = new CompanyGateway;
$cg->company_id = $company->id;
@@ -756,7 +748,6 @@ class CreateSingleAccount extends Command
$cg->save();
-
$gateway_types = $cg->driver()->gatewayTypes();
$fees_and_limits = new stdClass;
diff --git a/app/Console/Commands/CreateTestData.php b/app/Console/Commands/CreateTestData.php
index ecd6ab2018f3..390717175a15 100644
--- a/app/Console/Commands/CreateTestData.php
+++ b/app/Console/Commands/CreateTestData.php
@@ -48,10 +48,12 @@ use Illuminate\Support\Str;
class CreateTestData extends Command
{
use MakesHash, GeneratesCounter;
+
/**
* @var string
*/
protected $description = 'Create Test Data';
+
/**
* @var string
*/
@@ -66,14 +68,16 @@ class CreateTestData extends Command
*/
public function handle()
{
- if(config('ninja.is_docker'))
+ if (config('ninja.is_docker')) {
return;
+ }
- if (!$this->confirm('Are you sure you want to inject dummy data?'))
- return;
+ if (! $this->confirm('Are you sure you want to inject dummy data?')) {
+ return;
+ }
$this->invoice_repo = new InvoiceRepository();
-
+
$this->info(date('r').' Running CreateTestData...');
$this->count = $this->argument('count');
@@ -125,14 +129,14 @@ class CreateTestData extends Command
'is_admin' => 1,
'is_locked' => 0,
'notifications' => CompanySettings::notificationDefaults(),
- // 'permissions' => '',
+ // 'permissions' => '',
'settings' => null,
]);
Product::factory()->count(50)->create([
- 'user_id' => $user->id,
- 'company_id' => $company->id,
- ]);
+ 'user_id' => $user->id,
+ 'company_id' => $company->id,
+ ]);
$this->info('Creating '.$this->count.' clients');
@@ -219,15 +223,14 @@ class CreateTestData extends Command
'is_admin' => 1,
'is_locked' => 0,
'notifications' => CompanySettings::notificationDefaults(),
- // 'permissions' => '',
+ // 'permissions' => '',
'settings' => null,
]);
Product::factory()->count(50)->create([
- 'user_id' => $user->id,
- 'company_id' => $company->id,
- ]);
-
+ 'user_id' => $user->id,
+ 'company_id' => $company->id,
+ ]);
$this->count = $this->count * 10;
@@ -317,14 +320,14 @@ class CreateTestData extends Command
'is_admin' => 1,
'is_locked' => 0,
'notifications' => CompanySettings::notificationDefaults(),
- // 'permissions' => '',
+ // 'permissions' => '',
'settings' => null,
]);
Product::factory()->count(15000)->create([
- 'user_id' => $user->id,
- 'company_id' => $company->id,
- ]);
+ 'user_id' => $user->id,
+ 'company_id' => $company->id,
+ ]);
$this->count = $this->count * 10;
@@ -382,30 +385,29 @@ class CreateTestData extends Command
// });
$client = Client::factory()->create([
- 'user_id' => $user->id,
- 'company_id' => $company->id,
- ]);
-
+ 'user_id' => $user->id,
+ 'company_id' => $company->id,
+ ]);
Document::factory()->count(50)->create([
- 'user_id' => $user->id,
- 'company_id' => $company->id,
- 'documentable_type' => Client::class,
- 'documentable_id' => $client->id
- ]);
+ 'user_id' => $user->id,
+ 'company_id' => $company->id,
+ 'documentable_type' => Client::class,
+ 'documentable_id' => $client->id,
+ ]);
ClientContact::factory()->create([
- 'user_id' => $user->id,
- 'client_id' => $client->id,
- 'company_id' => $company->id,
- 'is_primary' => 1,
- ]);
+ 'user_id' => $user->id,
+ 'client_id' => $client->id,
+ 'company_id' => $company->id,
+ 'is_primary' => 1,
+ ]);
ClientContact::factory()->count(rand(1, 5))->create([
- 'user_id' => $user->id,
- 'client_id' => $client->id,
- 'company_id' => $company->id,
- ]);
+ 'user_id' => $user->id,
+ 'client_id' => $client->id,
+ 'company_id' => $company->id,
+ ]);
$client->number = $this->getNextClientNumber($client);
@@ -422,70 +424,69 @@ class CreateTestData extends Command
private function createExpense($client)
{
Expense::factory()->count(rand(1, 5))->create([
- 'user_id' => $client->user->id,
- 'client_id' => $client->id,
- 'company_id' => $client->company->id,
- ]);
+ 'user_id' => $client->user->id,
+ 'client_id' => $client->id,
+ 'company_id' => $client->company->id,
+ ]);
}
private function createVendor($client)
{
$vendor = Vendor::factory()->create([
- 'user_id' => $client->user->id,
- 'company_id' => $client->company->id,
- ]);
+ 'user_id' => $client->user->id,
+ 'company_id' => $client->company->id,
+ ]);
Document::factory()->count(50)->create([
- 'user_id' => $client->user->id,
- 'company_id' => $client->company_id,
- 'documentable_type' => Vendor::class,
- 'documentable_id' => $vendor->id
- ]);
+ 'user_id' => $client->user->id,
+ 'company_id' => $client->company_id,
+ 'documentable_type' => Vendor::class,
+ 'documentable_id' => $vendor->id,
+ ]);
VendorContact::factory()->create([
- 'user_id' => $client->user->id,
- 'vendor_id' => $vendor->id,
- 'company_id' => $client->company->id,
- 'is_primary' => 1,
- ]);
+ 'user_id' => $client->user->id,
+ 'vendor_id' => $vendor->id,
+ 'company_id' => $client->company->id,
+ 'is_primary' => 1,
+ ]);
VendorContact::factory()->count(rand(1, 5))->create([
- 'user_id' => $client->user->id,
- 'vendor_id' => $vendor->id,
- 'company_id' => $client->company->id,
- 'is_primary' => 0,
- ]);
+ 'user_id' => $client->user->id,
+ 'vendor_id' => $vendor->id,
+ 'company_id' => $client->company->id,
+ 'is_primary' => 0,
+ ]);
}
private function createTask($client)
{
$vendor = Task::factory()->create([
- 'user_id' => $client->user->id,
- 'company_id' => $client->company->id,
- ]);
-
+ 'user_id' => $client->user->id,
+ 'company_id' => $client->company->id,
+ ]);
Document::factory()->count(5)->create([
- 'user_id' => $client->user->id,
- 'company_id' => $client->company_id,
- 'documentable_type' => Task::class,
- 'documentable_id' => $vendor->id
- ]);
+ 'user_id' => $client->user->id,
+ 'company_id' => $client->company_id,
+ 'documentable_type' => Task::class,
+ 'documentable_id' => $vendor->id,
+ ]);
}
private function createProject($client)
{
$vendor = Project::factory()->create([
- 'user_id' => $client->user->id,
- 'company_id' => $client->company->id,
- ]);
+ 'user_id' => $client->user->id,
+ 'company_id' => $client->company->id,
+ ]);
- Document::factory()->count(5)->create([
- 'user_id' => $client->user->id,
- 'company_id' => $client->company_id,
- 'documentable_type' => Project::class,
- 'documentable_id' => $vendor->id
- ]);
+ Document::factory()->count(5)->create([
+ 'user_id' => $client->user->id,
+ 'company_id' => $client->company_id,
+ 'documentable_type' => Project::class,
+ 'documentable_id' => $vendor->id,
+ ]);
}
private function createInvoice($client)
@@ -537,16 +538,15 @@ class CreateTestData extends Command
$invoice = $invoice->service()->markPaid()->save();
}
- Document::factory()->count(5)->create([
- 'user_id' => $invoice->user->id,
- 'company_id' => $invoice->company_id,
- 'documentable_type' => Invoice::class,
- 'documentable_id' => $invoice->id
- ]);
+ Document::factory()->count(5)->create([
+ 'user_id' => $invoice->user->id,
+ 'company_id' => $invoice->company_id,
+ 'documentable_type' => Invoice::class,
+ 'documentable_id' => $invoice->id,
+ ]);
RecurringInvoice::factory()->create(['user_id' => $invoice->user->id, 'company_id' => $invoice->company->id, 'client_id' => $invoice->client_id]);
-
event(new InvoiceWasCreated($invoice, $invoice->company, Ninja::eventVars()));
}
diff --git a/app/Console/Commands/DemoMode.php b/app/Console/Commands/DemoMode.php
index bbb24e2a89db..d2cc795c0d3e 100644
--- a/app/Console/Commands/DemoMode.php
+++ b/app/Console/Commands/DemoMode.php
@@ -73,8 +73,9 @@ class DemoMode extends Command
{
set_time_limit(0);
- if(config('ninja.is_docker'))
+ if (config('ninja.is_docker')) {
return;
+ }
$this->invoice_repo = new InvoiceRepository();
@@ -182,7 +183,7 @@ class DemoMode extends Command
'is_admin' => 1,
'is_locked' => 0,
'notifications' => CompanySettings::notificationDefaults(),
- // 'permissions' => '',
+ // 'permissions' => '',
'settings' => null,
]);
@@ -217,9 +218,9 @@ class DemoMode extends Command
}
Product::factory()->count(50)->create([
- 'user_id' => $user->id,
- 'company_id' => $company->id,
- ]);
+ 'user_id' => $user->id,
+ 'company_id' => $company->id,
+ ]);
$this->info('Creating '.$this->count.' clients');
@@ -265,22 +266,22 @@ class DemoMode extends Command
// });
$client = Client::factory()->create([
- 'user_id' => $user->id,
- 'company_id' => $company->id,
- ]);
+ 'user_id' => $user->id,
+ 'company_id' => $company->id,
+ ]);
ClientContact::factory()->create([
- 'user_id' => $user->id,
- 'client_id' => $client->id,
- 'company_id' => $company->id,
- 'is_primary' => 1,
- ]);
+ 'user_id' => $user->id,
+ 'client_id' => $client->id,
+ 'company_id' => $company->id,
+ 'is_primary' => 1,
+ ]);
ClientContact::factory()->count(rand(1, 5))->create([
- 'user_id' => $user->id,
- 'client_id' => $client->id,
- 'company_id' => $company->id,
- ]);
+ 'user_id' => $user->id,
+ 'client_id' => $client->id,
+ 'company_id' => $company->id,
+ ]);
$client->number = $this->getNextClientNumber($client);
@@ -299,41 +300,37 @@ class DemoMode extends Command
private function createExpense($client)
{
Expense::factory()->count(rand(1, 5))->create([
- 'user_id' => $client->user_id,
- 'client_id' => $client->id,
- 'company_id' => $client->company_id,
- ]);
-
- Expense::all()->each(function ($expense){
+ 'user_id' => $client->user_id,
+ 'client_id' => $client->id,
+ 'company_id' => $client->company_id,
+ ]);
+ Expense::all()->each(function ($expense) {
$expense->number = $this->getNextExpenseNumber($expense);
$expense->save();
-
});
-
}
private function createVendor($client, $assigned_user_id = null)
{
$vendor = Vendor::factory()->create([
- 'user_id' => $client->user_id,
- 'company_id' => $client->company_id,
- ]);
+ 'user_id' => $client->user_id,
+ 'company_id' => $client->company_id,
+ ]);
VendorContact::factory()->create([
- 'user_id' => $client->user->id,
- 'vendor_id' => $vendor->id,
- 'company_id' => $client->company_id,
- 'is_primary' => 1,
- ]);
+ 'user_id' => $client->user->id,
+ 'vendor_id' => $vendor->id,
+ 'company_id' => $client->company_id,
+ 'is_primary' => 1,
+ ]);
VendorContact::factory()->count(rand(1, 5))->create([
- 'user_id' => $client->user->id,
- 'vendor_id' => $vendor->id,
- 'company_id' => $client->company_id,
- 'is_primary' => 0,
- ]);
-
+ 'user_id' => $client->user->id,
+ 'vendor_id' => $vendor->id,
+ 'company_id' => $client->company_id,
+ 'is_primary' => 0,
+ ]);
$vendor->number = $this->getNextVendorNumber($vendor);
$vendor->save();
@@ -342,25 +339,24 @@ class DemoMode extends Command
private function createTask($client, $assigned_user_id = null)
{
$task = Task::factory()->create([
- 'user_id' => $client->user->id,
- 'company_id' => $client->company_id,
- 'client_id' => $client->id
- ]);
+ 'user_id' => $client->user->id,
+ 'company_id' => $client->company_id,
+ 'client_id' => $client->id,
+ ]);
$task->status_id = TaskStatus::all()->random()->id;
$task->number = $this->getNextTaskNumber($task);
$task->save();
-
}
private function createProject($client, $assigned_user_id = null)
{
$project = Project::factory()->create([
- 'user_id' => $client->user->id,
- 'company_id' => $client->company_id,
- 'client_id' => $client->id,
- ]);
+ 'user_id' => $client->user->id,
+ 'company_id' => $client->company_id,
+ 'client_id' => $client->id,
+ ]);
$project->number = $this->getNextProjectNumber($project);
$project->save();
diff --git a/app/Console/Commands/DesignUpdate.php b/app/Console/Commands/DesignUpdate.php
index cada484be4bb..caccb3bd7c42 100644
--- a/app/Console/Commands/DesignUpdate.php
+++ b/app/Console/Commands/DesignUpdate.php
@@ -64,11 +64,8 @@ class DesignUpdate extends Command
$this->handleOnDb($db);
}
- MultiDB::setDB($current_db);
-
+ MultiDB::setDB($current_db);
}
-
-
}
private function handleOnDb()
diff --git a/app/Console/Commands/HostedMigrations.php b/app/Console/Commands/HostedMigrations.php
index e8540a9c4431..0e303129a7ec 100644
--- a/app/Console/Commands/HostedMigrations.php
+++ b/app/Console/Commands/HostedMigrations.php
@@ -71,26 +71,27 @@ class HostedMigrations extends Command
public function handle()
{
$this->buildCache();
-
- if(!MultiDB::userFindAndSetDb($this->option('email'))){
- $this->info("Could not find a user with that email address");
+
+ if (! MultiDB::userFindAndSetDb($this->option('email'))) {
+ $this->info('Could not find a user with that email address');
+
return;
}
$user = User::where('email', $this->option('email'))->first();
- if(!$user){
- $this->info("There was a problem getting the user, did you set the right DB?");
+ if (! $user) {
+ $this->info('There was a problem getting the user, did you set the right DB?');
+
return;
}
$path = public_path('storage/migrations/import');
-
+
$directory = new DirectoryIterator($path);
foreach ($directory as $file) {
if ($file->getExtension() === 'zip') {
-
$company = $user->companies()->first();
$this->info('Started processing: '.$file->getBasename().' at '.now());
@@ -104,14 +105,13 @@ class HostedMigrations extends Command
}
$filename = pathinfo($file->getRealPath(), PATHINFO_FILENAME);
-
+
$zip->extractTo(public_path("storage/migrations/{$filename}"));
$zip->close();
$import_file = public_path("storage/migrations/$filename/migration.json");
Import::dispatch($import_file, $user->companies()->first(), $user);
-
} catch (NonExistingMigrationFile | ProcessingMigrationArchiveFailed | ResourceNotAvailableForMigration | MigrationValidatorFailed | ResourceDependencyMissing $e) {
\Mail::to($this->user)->send(new MigrationFailed($e, $e->getMessage()));
@@ -122,5 +122,4 @@ class HostedMigrations extends Command
}
}
}
-
}
diff --git a/app/Console/Commands/HostedUsers.php b/app/Console/Commands/HostedUsers.php
index 621102382e2f..7fc670ce1249 100644
--- a/app/Console/Commands/HostedUsers.php
+++ b/app/Console/Commands/HostedUsers.php
@@ -41,21 +41,16 @@ class HostedUsers extends Command
*/
public function handle()
{
-
- Company::on('db-ninja-01')->each(function ($company){
-
- if(Ninja::isHosted())
+ Company::on('db-ninja-01')->each(function ($company) {
+ if (Ninja::isHosted()) {
\Modules\Admin\Jobs\Account\NinjaUser::dispatchNow([], $company);
-
+ }
});
- Company::on('db-ninja-02')->each(function ($company){
-
- if(Ninja::isHosted())
+ Company::on('db-ninja-02')->each(function ($company) {
+ if (Ninja::isHosted()) {
\Modules\Admin\Jobs\Account\NinjaUser::dispatchNow([], $company);
-
+ }
});
-
}
-
}
diff --git a/app/Console/Commands/ImportMigrations.php b/app/Console/Commands/ImportMigrations.php
index dcd184a2f1a9..594d447469cf 100644
--- a/app/Console/Commands/ImportMigrations.php
+++ b/app/Console/Commands/ImportMigrations.php
@@ -77,9 +77,9 @@ class ImportMigrations extends Command
public function handle()
{
$this->buildCache();
-
+
$path = $this->option('path') ?? public_path('storage/migrations/import');
-
+
$directory = new DirectoryIterator($path);
foreach ($directory as $file) {
@@ -98,7 +98,7 @@ class ImportMigrations extends Command
}
$filename = pathinfo($file->getRealPath(), PATHINFO_FILENAME);
-
+
$zip->extractTo(public_path("storage/migrations/{$filename}"));
$zip->close();
@@ -124,7 +124,7 @@ class ImportMigrations extends Command
$user = User::factory()->create([
'account_id' => $account->id,
- 'email' => Str::random(10) . "@example.com",
+ 'email' => Str::random(10).'@example.com',
'confirmation_code' => $this->createDbHash($company->db),
]);
@@ -137,7 +137,7 @@ class ImportMigrations extends Command
'name' => 'First token',
'token' => Str::random(64),
]);
-
+
$user->companies()->attach($company->id, [
'account_id' => $account->id,
'is_owner' => 1,
diff --git a/app/Console/Commands/MobileLocalization.php b/app/Console/Commands/MobileLocalization.php
index 7ae72f6cd1bc..0277fb75adce 100644
--- a/app/Console/Commands/MobileLocalization.php
+++ b/app/Console/Commands/MobileLocalization.php
@@ -23,7 +23,6 @@ class MobileLocalization extends Command
*/
protected $description = 'Generate mobile localization resources';
-
/**
* Create a new command instance.
*
@@ -83,9 +82,9 @@ class MobileLocalization extends Command
$text = $resources->$key;
}
- $text = str_replace(array('', ''), '', $text);
- $text = str_replace(array('', ''), '', $text);
- $text = str_replace(array('', ''), '', $text);
+ $text = str_replace(['', ''], '', $text);
+ $text = str_replace(['', ''], '', $text);
+ $text = str_replace(['', ''], '', $text);
echo "'$key': '$text',\n";
}
@@ -103,11 +102,11 @@ class MobileLocalization extends Command
$end = strpos($data, '},', $start);
$data = substr($data, $start, $end - $start - 5);
- $data = str_replace("\n", "", $data);
- $data = str_replace("\"", "\'", $data);
- $data = str_replace("'", "\"", $data);
+ $data = str_replace("\n", '', $data);
+ $data = str_replace('"', "\'", $data);
+ $data = str_replace("'", '"', $data);
- return json_decode('{' . rtrim($data, ',') . '}');
+ return json_decode('{'.rtrim($data, ',').'}');
}
protected function getOptions()
@@ -116,5 +115,4 @@ class MobileLocalization extends Command
['type', null, InputOption::VALUE_OPTIONAL, 'Type', null],
];
}
-
}
diff --git a/app/Console/Commands/ParallelCheckData.php b/app/Console/Commands/ParallelCheckData.php
index 1879202cb432..c79161632835 100644
--- a/app/Console/Commands/ParallelCheckData.php
+++ b/app/Console/Commands/ParallelCheckData.php
@@ -52,15 +52,10 @@ class ParallelCheckData extends Command
public function handle()
{
-
- $hash = Str::random(32);
-
- Company::cursor()->each(function ($company) use ($hash){
-
- CheckCompanyData::dispatch($company, $hash)->onQueue('checkdata');
-
- });
+ $hash = Str::random(32);
+ Company::cursor()->each(function ($company) use ($hash) {
+ CheckCompanyData::dispatch($company, $hash)->onQueue('checkdata');
+ });
}
-
-}
\ No newline at end of file
+}
diff --git a/app/Console/Commands/PostUpdate.php b/app/Console/Commands/PostUpdate.php
index 5eeadb84ac88..007a9bed6211 100644
--- a/app/Console/Commands/PostUpdate.php
+++ b/app/Console/Commands/PostUpdate.php
@@ -50,24 +50,22 @@ class PostUpdate extends Command
info("I wasn't able to migrate the data.");
}
- info("finished migrating");
+ info('finished migrating');
$output = [];
// exec('vendor/bin/composer install --no-dev -o', $output);
- info(print_r($output,1));
- info("finished running composer install ");
+ info(print_r($output, 1));
+ info('finished running composer install ');
try {
-
Artisan::call('optimize');
-
} catch (\Exception $e) {
info("I wasn't able to optimize.");
}
- info("optimized");
+ info('optimized');
try {
Artisan::call('view:clear');
@@ -75,7 +73,7 @@ class PostUpdate extends Command
info("I wasn't able to clear the views.");
}
- info("view cleared");
+ info('view cleared');
try {
Artisan::call('queue:restart');
@@ -83,11 +81,10 @@ class PostUpdate extends Command
info("I wasn't able to restart the queue.");
}
- info("queue restarted");
+ info('queue restarted');
VersionCheck::dispatch();
- info("Sent for version check");
-
+ info('Sent for version check');
}
}
diff --git a/app/Console/Commands/ReactBuilder.php b/app/Console/Commands/ReactBuilder.php
index 4081e76846e6..15a2f6520f46 100644
--- a/app/Console/Commands/ReactBuilder.php
+++ b/app/Console/Commands/ReactBuilder.php
@@ -56,33 +56,19 @@ class ReactBuilder extends Command
$directoryIterator = new \RecursiveDirectoryIterator(public_path('react'), \RecursiveDirectoryIterator::SKIP_DOTS);
foreach (new \RecursiveIteratorIterator($directoryIterator) as $file) {
-
- if(str_contains($file->getFileName(), '.js')) {
-
- if(str_contains($file->getFileName(), 'index.')){
-
- $includes .= ''."\n";
-
- }
- else{
-
- $includes .= ''."\n";
+ if (str_contains($file->getFileName(), '.js')) {
+ if (str_contains($file->getFileName(), 'index.')) {
+ $includes .= ''."\n";
+ } else {
+ $includes .= ''."\n";
+ }
}
- }
-
-
- if(str_contains($file->getFileName(), '.css')) {
-
- $includes .= ''."\n";
-
- }
-
+ if (str_contains($file->getFileName(), '.css')) {
+ $includes .= ''."\n";
+ }
}
file_put_contents(resource_path('views/react/head.blade.php'), $includes);
-
}
-
-
}
diff --git a/app/Console/Commands/S3Cleanup.php b/app/Console/Commands/S3Cleanup.php
index 9b29ee692a63..12b998dd5697 100644
--- a/app/Console/Commands/S3Cleanup.php
+++ b/app/Console/Commands/S3Cleanup.php
@@ -42,10 +42,10 @@ class S3Cleanup extends Command
*/
public function handle()
{
-
- if(!Ninja::isHosted())
+ if (! Ninja::isHosted()) {
return;
-
+ }
+
$c1 = Company::on('db-ninja-01')->pluck('company_key');
$c2 = Company::on('db-ninja-02')->pluck('company_key');
@@ -53,23 +53,20 @@ class S3Cleanup extends Command
$directories = Storage::disk(config('filesystems.default'))->directories();
- $this->LogMessage("Disk Cleanup");
+ $this->LogMessage('Disk Cleanup');
- foreach($directories as $dir)
- {
- if(!in_array($dir, $merged))
- {
- $this->logMessage("Deleting $dir");
+ foreach ($directories as $dir) {
+ if (! in_array($dir, $merged)) {
+ $this->logMessage("Deleting $dir");
- /* Ensure we are not deleting the root folder */
- if(strlen($dir) > 1)
- Storage::disk(config('filesystems.default'))->deleteDirectory($dir);
-
+ /* Ensure we are not deleting the root folder */
+ if (strlen($dir) > 1) {
+ Storage::disk(config('filesystems.default'))->deleteDirectory($dir);
}
- }
-
- $this->logMessage("exiting");
+ }
+ }
+ $this->logMessage('exiting');
}
private function logMessage($str)
diff --git a/app/Console/Commands/SendRemindersCron.php b/app/Console/Commands/SendRemindersCron.php
index cd16da8ecae2..cdbdad6b37ab 100644
--- a/app/Console/Commands/SendRemindersCron.php
+++ b/app/Console/Commands/SendRemindersCron.php
@@ -29,6 +29,7 @@ use Illuminate\Support\Facades\App;
class SendRemindersCron extends Command
{
use MakesReminders, MakesDates;
+
/**
* The name and signature of the console command.
*
@@ -60,56 +61,49 @@ class SendRemindersCron extends Command
*/
public function handle()
{
-
Invoice::where('next_send_date', '<=', now()->toDateTimeString())
->whereNull('deleted_at')
->where('is_deleted', 0)
->whereIn('status_id', [Invoice::STATUS_SENT, Invoice::STATUS_PARTIAL])
->where('balance', '>', 0)
->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);
+ $query->where('is_disabled', 0);
})
->with('invitations')->cursor()->each(function ($invoice) {
+ if ($invoice->isPayable()) {
+ $reminder_template = $invoice->calculateTemplate('invoice');
+ $invoice->service()->touchReminder($reminder_template)->save();
+ $invoice = $this->calcLateFee($invoice, $reminder_template);
- if ($invoice->isPayable()) {
- $reminder_template = $invoice->calculateTemplate('invoice');
- $invoice->service()->touchReminder($reminder_template)->save();
- $invoice = $this->calcLateFee($invoice, $reminder_template);
+ //check if this reminder needs to be emailed
+ if (in_array($reminder_template, ['reminder1', 'reminder2', 'reminder3']) && $invoice->client->getSetting('enable_'.$reminder_template)) {
+ $invoice->invitations->each(function ($invitation) use ($invoice, $reminder_template) {
+ EmailEntity::dispatch($invitation, $invitation->company, $reminder_template);
+ nlog("Firing reminder email for invoice {$invoice->number}");
+ });
- //check if this reminder needs to be emailed
- if(in_array($reminder_template, ['reminder1','reminder2','reminder3']) && $invoice->client->getSetting("enable_".$reminder_template))
- {
- $invoice->invitations->each(function ($invitation) use ($invoice, $reminder_template) {
- EmailEntity::dispatch($invitation, $invitation->company, $reminder_template);
- nlog("Firing reminder email for invoice {$invoice->number}");
- });
+ 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();
- }
-
- });
-
-
- // SendReminders::dispatchNow();
+ // SendReminders::dispatchNow();
// $this->webHookOverdueInvoices();
// $this->webHookExpiredQuotes();
}
-
- private function calcLateFee($invoice, $template) :Invoice
+ private function calcLateFee($invoice, $template) :Invoice
{
$late_fee_amount = 0;
$late_fee_percent = 0;
@@ -151,7 +145,6 @@ class SendRemindersCron extends Command
*/
private function setLateFee($invoice, $amount, $percent) :Invoice
{
-
App::forgetInstance('translator');
$t = app('translator');
$t->replace(Ninja::transformTranslations($invoice->client->getMergedSettings()));
@@ -187,49 +180,20 @@ class SendRemindersCron extends Command
$invoice->calc()->getInvoice()->save();
$invoice->fresh();
$invoice->service()->deletePdf();
-
+
/* Refresh the client here to ensure the balance is fresh */
$client = $invoice->client;
$client = $client->fresh();
- nlog("adjusting client balance and invoice balance by ". ($invoice->balance - $temp_invoice_balance));
+ nlog('adjusting client balance and invoice balance by '.($invoice->balance - $temp_invoice_balance));
$client->service()->updateBalance($invoice->balance - $temp_invoice_balance)->save();
$invoice->ledger()->updateInvoiceBalance($invoice->balance - $temp_invoice_balance, "Late Fee Adjustment for invoice {$invoice->number}");
return $invoice;
}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
private function webHookOverdueInvoices()
{
-
-
if (! config('ninja.db.multi_db_enabled')) {
$this->executeWebhooks();
} else {
@@ -240,12 +204,10 @@ class SendRemindersCron extends Command
$this->executeWebhooks();
}
}
-
}
private function webHookExpiredQuotes()
{
-
}
private function executeWebhooks()
@@ -255,21 +217,18 @@ class SendRemindersCron extends Command
->where('balance', '>', 0)
->whereDate('due_date', '<=', now()->subDays(1)->startOfDay())
->cursor();
-
+
$invoices->each(function ($invoice) {
WebhookHandler::dispatch(Webhook::EVENT_LATE_INVOICE, $invoice, $invoice->company);
-
});
$quotes = Quote::where('is_deleted', 0)
->where('status_id', Quote::STATUS_SENT)
->whereDate('due_date', '<=', now()->subDays(1)->startOfDay())
->cursor();
-
+
$quotes->each(function ($quote) {
WebhookHandler::dispatch(Webhook::EVENT_EXPIRED_QUOTE, $quote, $quote->company);
});
}
-
-
}
diff --git a/app/Console/Commands/SubdomainFill.php b/app/Console/Commands/SubdomainFill.php
index ad5471d7866c..aa099a57a51e 100644
--- a/app/Console/Commands/SubdomainFill.php
+++ b/app/Console/Commands/SubdomainFill.php
@@ -40,25 +40,17 @@ class SubdomainFill extends Command
*/
public function handle()
{
-
$c1 = Company::on('db-ninja-01')->whereNull('subdomain')->orWhere('subdomain', '')->get();
$c2 = Company::on('db-ninja-02')->whereNull('subdomain')->orWhere('subdomain', '')->get();
-
- $c1->each(function ($company){
-
+ $c1->each(function ($company) {
$company->subdomain = MultiDB::randomSubdomainGenerator();
$company->save();
-
});
- $c2->each(function ($company){
-
+ $c2->each(function ($company) {
$company->subdomain = MultiDB::randomSubdomainGenerator();
$company->save();
-
});
-
}
-
}
diff --git a/app/Console/Commands/TranslationsExport.php b/app/Console/Commands/TranslationsExport.php
index bfc7ffe3f370..5fcf588b0ff5 100644
--- a/app/Console/Commands/TranslationsExport.php
+++ b/app/Console/Commands/TranslationsExport.php
@@ -69,8 +69,9 @@ class TranslationsExport extends Command
'sv',
'th',
'tr_TR',
- 'zh_TW'
+ 'zh_TW',
];
+
/**
* Create a new command instance.
*
@@ -88,19 +89,14 @@ class TranslationsExport extends Command
*/
public function handle()
{
-
Storage::makeDirectory(storage_path('lang'));
- foreach($this->langs as $lang)
- {
+ foreach ($this->langs as $lang) {
Storage::makeDirectory(storage_path("lang/{$lang}"));
- $translations = Lang::getLoader()->load($lang,'texts');
+ $translations = Lang::getLoader()->load($lang, 'texts');
Storage::put(storage_path("lang/{$lang}/{$lang}.json"), json_encode(Arr::dot($translations), JSON_UNESCAPED_UNICODE));
-
}
-
}
-
}
diff --git a/app/Console/Commands/TypeCheck.php b/app/Console/Commands/TypeCheck.php
index 0c7c3b97ed29..3ec6a339c34d 100644
--- a/app/Console/Commands/TypeCheck.php
+++ b/app/Console/Commands/TypeCheck.php
@@ -43,7 +43,6 @@ class TypeCheck extends Command
protected $log = '';
-
/**
* Create a new command instance.
*
@@ -65,91 +64,74 @@ class TypeCheck extends Command
$current_db = config('database.default');
- if($this->option('all'))
- {
+ if ($this->option('all')) {
if (! config('ninja.db.multi_db_enabled')) {
- $this->checkAll();
+ $this->checkAll();
} else {
-
- foreach (MultiDB::$dbs as $db)
- {
+ foreach (MultiDB::$dbs as $db) {
MultiDB::setDB($db);
$this->checkAll();
}
MultiDB::setDB($current_db);
-
}
-
}
- if($this->option('client_id'))
- {
+ if ($this->option('client_id')) {
$client = MultiDB::findAndSetDbByClientId($this->option('client_id'));
- if($client)
+ if ($client) {
$this->checkClient($client);
- else
+ } else {
$this->logMessage(date('Y-m-d h:i:s').' Could not find this client');
-
+ }
}
- if($this->option('company_id'))
- {
+ if ($this->option('company_id')) {
$company = MultiDB::findAndSetDbByCompanyId($this->option('company_id'));
-
- if($company)
+ if ($company) {
$this->checkCompany($company);
- else
+ } else {
$this->logMessage(date('Y-m-d h:i:s').' Could not find this company');
+ }
}
-
}
-
private function checkClient($client)
{
- $this->logMessage(date('Y-m-d h:i:s').' Checking Client => ' . $client->present()->name(). " " . $client->id);
-
-
- $entity_settings = $this->checkSettingType($client->settings);
- $entity_settings->md5 = md5(time());
- $client->settings = $entity_settings;
- $client->save();
+ $this->logMessage(date('Y-m-d h:i:s').' Checking Client => '.$client->present()->name().' '.$client->id);
+ $entity_settings = $this->checkSettingType($client->settings);
+ $entity_settings->md5 = md5(time());
+ $client->settings = $entity_settings;
+ $client->save();
}
private function checkCompany($company)
{
- $this->logMessage(date('Y-m-d h:i:s').' Checking Company => ' . $company->present()->name(). " " . $company->id);
-
- $company->saveSettings((array)$company->settings, $company);
+ $this->logMessage(date('Y-m-d h:i:s').' Checking Company => '.$company->present()->name().' '.$company->id);
+ $company->saveSettings((array) $company->settings, $company);
}
private function checkAll()
{
-
$this->logMessage(date('Y-m-d h:i:s').' Checking all clients and companies.');
- Client::withTrashed()->cursor()->each( function ($client) {
+ Client::withTrashed()->cursor()->each(function ($client) {
$this->logMessage("Checking client {$client->id}");
$entity_settings = $this->checkSettingType($client->settings);
$entity_settings->md5 = md5(time());
$client->settings = $entity_settings;
$client->save();
-
});
- Company::cursor()->each( function ($company) {
+ Company::cursor()->each(function ($company) {
$this->logMessage("Checking company {$company->id}");
$company->saveSettings($company->settings, $company);
-
});
-
-
}
private function logMessage($str)
@@ -159,4 +141,3 @@ class TypeCheck extends Command
$this->log .= $str."\n";
}
}
-
diff --git a/app/Console/Kernel.php b/app/Console/Kernel.php
index e6ebbdc808c3..a0a586050149 100644
--- a/app/Console/Kernel.php
+++ b/app/Console/Kernel.php
@@ -51,7 +51,6 @@ class Kernel extends ConsoleKernel
*/
protected function schedule(Schedule $schedule)
{
-
$schedule->job(new VersionCheck)->daily();
$schedule->job(new DiskCleanup)->daily()->withoutOverlapping();
@@ -78,17 +77,14 @@ class Kernel extends ConsoleKernel
$schedule->job(new SystemMaintenance)->weekly()->withoutOverlapping();
- if(Ninja::isSelfHost())
- {
+ 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();
$schedule->job(new SendFailedEmails)->daily()->withoutOverlapping();
@@ -98,17 +94,13 @@ class Kernel extends ConsoleKernel
$schedule->command('ninja:check-data --database=db-ninja-02')->dailyAt('02:05')->withoutOverlapping();
$schedule->command('ninja:s3-cleanup')->dailyAt('23:15')->withoutOverlapping();
-
}
- if (config('queue.default') == 'database' && Ninja::isSelfHost() && config('ninja.internal_queue_enabled') && !config('ninja.is_docker')) {
-
+ 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();
-
}
-
}
/**
@@ -118,7 +110,7 @@ class Kernel extends ConsoleKernel
*/
protected function commands()
{
- $this->load(__DIR__ . '/Commands');
+ $this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
diff --git a/app/DataMapper/Analytics/AccountPlatform.php b/app/DataMapper/Analytics/AccountPlatform.php
index 40f0e2abf9f2..2e696ab50172 100644
--- a/app/DataMapper/Analytics/AccountPlatform.php
+++ b/app/DataMapper/Analytics/AccountPlatform.php
@@ -53,7 +53,8 @@ class AccountPlatform extends GenericMixedMetric
public $string_metric7 = 'ip_address';
- public function __construct($string_metric5, $string_metric6, $string_metric7) {
+ public function __construct($string_metric5, $string_metric6, $string_metric7)
+ {
$this->string_metric5 = $string_metric5;
$this->string_metric6 = $string_metric6;
$this->string_metric7 = $string_metric7;
diff --git a/app/DataMapper/Analytics/DbQuery.php b/app/DataMapper/Analytics/DbQuery.php
index 52ffbe646444..05d8b232b75e 100644
--- a/app/DataMapper/Analytics/DbQuery.php
+++ b/app/DataMapper/Analytics/DbQuery.php
@@ -52,6 +52,7 @@ class DbQuery extends GenericMixedMetric
public $string_metric6 = 'url';
public $string_metric7 = 'ip_address';
+
/**
* The counter
* set to 1.
@@ -62,7 +63,8 @@ class DbQuery extends GenericMixedMetric
public $double_metric2 = 1;
- public function __construct($string_metric5, $string_metric6, $int_metric1, $double_metric2, $string_metric7) {
+ public function __construct($string_metric5, $string_metric6, $int_metric1, $double_metric2, $string_metric7)
+ {
$this->int_metric1 = $int_metric1;
$this->string_metric5 = $string_metric5;
$this->string_metric6 = $string_metric6;
diff --git a/app/DataMapper/Analytics/EmailFailure.php b/app/DataMapper/Analytics/EmailFailure.php
index 077e0a15be9b..43cfc97fae32 100644
--- a/app/DataMapper/Analytics/EmailFailure.php
+++ b/app/DataMapper/Analytics/EmailFailure.php
@@ -71,7 +71,8 @@ class EmailFailure extends GenericMixedMetric
*/
public $string_metric7 = '';
- public function __construct($string_metric7) {
+ public function __construct($string_metric7)
+ {
$this->string_metric7 = $string_metric7;
}
}
diff --git a/app/DataMapper/Analytics/EmailSuccess.php b/app/DataMapper/Analytics/EmailSuccess.php
index 1d2160cb58e8..9f566eaa752a 100644
--- a/app/DataMapper/Analytics/EmailSuccess.php
+++ b/app/DataMapper/Analytics/EmailSuccess.php
@@ -15,7 +15,6 @@ use Turbo124\Beacon\ExampleMetric\GenericMixedMetric;
class EmailSuccess extends GenericMixedMetric
{
-
/**
* The type of Sample.
*
@@ -72,8 +71,8 @@ class EmailSuccess extends GenericMixedMetric
*/
public $string_metric7 = '';
- public function __construct($string_metric7) {
+ public function __construct($string_metric7)
+ {
$this->string_metric7 = $string_metric7;
}
-
}
diff --git a/app/DataMapper/Analytics/Mail/EmailBounce.php b/app/DataMapper/Analytics/Mail/EmailBounce.php
index 010a77ab3413..90a115a2ad53 100644
--- a/app/DataMapper/Analytics/Mail/EmailBounce.php
+++ b/app/DataMapper/Analytics/Mail/EmailBounce.php
@@ -71,7 +71,8 @@ class EmailBounce extends GenericMixedMetric
*/
public $int_metric1 = 1;
- public function __construct($string_metric5,$string_metric6,$string_metric7) {
+ public function __construct($string_metric5, $string_metric6, $string_metric7)
+ {
$this->string_metric5 = $string_metric5;
$this->string_metric6 = $string_metric6;
$this->string_metric7 = $string_metric7;
diff --git a/app/DataMapper/Analytics/Mail/EmailSpam.php b/app/DataMapper/Analytics/Mail/EmailSpam.php
index 1e63b6ba4b69..9d658d1243d9 100644
--- a/app/DataMapper/Analytics/Mail/EmailSpam.php
+++ b/app/DataMapper/Analytics/Mail/EmailSpam.php
@@ -71,7 +71,8 @@ class EmailSpam extends GenericMixedMetric
*/
public $int_metric1 = 1;
- public function __construct($string_metric5,$string_metric6,$string_metric7) {
+ public function __construct($string_metric5, $string_metric6, $string_metric7)
+ {
$this->string_metric5 = $string_metric5;
$this->string_metric6 = $string_metric6;
$this->string_metric7 = $string_metric7;
diff --git a/app/DataMapper/Analytics/QueueSize.php b/app/DataMapper/Analytics/QueueSize.php
index 3266f38645e2..0a356785f7a3 100644
--- a/app/DataMapper/Analytics/QueueSize.php
+++ b/app/DataMapper/Analytics/QueueSize.php
@@ -15,7 +15,6 @@ use Turbo124\Beacon\ExampleMetric\GenericMixedMetric;
class QueueSize extends GenericMixedMetric
{
-
/**
* The type of Sample.
*
@@ -72,8 +71,8 @@ class QueueSize extends GenericMixedMetric
*/
public $string_metric7 = '';
- public function __construct($int_metric1) {
+ public function __construct($int_metric1)
+ {
$this->int_metric1 = $int_metric1;
}
-
}
diff --git a/app/DataMapper/Billing/SubscriptionContextMapper.php b/app/DataMapper/Billing/SubscriptionContextMapper.php
index e45c6d1587e1..c86738a9162b 100644
--- a/app/DataMapper/Billing/SubscriptionContextMapper.php
+++ b/app/DataMapper/Billing/SubscriptionContextMapper.php
@@ -12,7 +12,6 @@
namespace App\DataMapper\Billing;
-
class SubscriptionContextMapper
{
/**
diff --git a/app/DataMapper/Billing/WebhookConfiguration.php b/app/DataMapper/Billing/WebhookConfiguration.php
index 1e0edd246417..08560d5ce1a1 100644
--- a/app/DataMapper/Billing/WebhookConfiguration.php
+++ b/app/DataMapper/Billing/WebhookConfiguration.php
@@ -12,7 +12,6 @@
namespace App\DataMapper\Billing;
-
class WebhookConfiguration
{
/**
@@ -33,11 +32,11 @@ class WebhookConfiguration
/**
* @var string
*/
- public $post_purchase_body = '';
+ public $post_purchase_body = '';
/**
* @var string
- */
+ */
public $post_purchase_rest_method = 'POST';
/**
diff --git a/app/DataMapper/ClientRegistrationFields.php b/app/DataMapper/ClientRegistrationFields.php
index a70871163f76..5e6397267dfe 100644
--- a/app/DataMapper/ClientRegistrationFields.php
+++ b/app/DataMapper/ClientRegistrationFields.php
@@ -13,89 +13,88 @@ namespace App\DataMapper;
class ClientRegistrationFields
{
-
public static function generate()
{
- $data =
+ $data =
[
[
'key' => 'first_name',
- 'required' => true
+ 'required' => true,
],
[
'key' => 'last_name',
- 'required' => true
+ 'required' => true,
],
[
'key' => 'email',
- 'required' => true
+ 'required' => true,
],
[
'key' => 'phone',
- 'required' => false
+ 'required' => false,
],
[
'key' => 'password',
- 'required' => true
- ],
+ 'required' => true,
+ ],
[
'key' => 'name',
- 'required' => false
+ 'required' => false,
],
[
'key' => 'website',
- 'required' => false
+ 'required' => false,
],
[
'key' => 'address1',
- 'required' => false
+ 'required' => false,
],
[
'key' => 'address2',
- 'required' => false
+ 'required' => false,
],
[
'key' => 'city',
- 'required' => false
+ 'required' => false,
],
[
'key' => 'state',
- 'required' => false
+ 'required' => false,
],
[
'key' => 'postal_code',
- 'required' => false
- ],
+ 'required' => false,
+ ],
[
'key' => 'country_id',
- 'required' => false
- ],
+ 'required' => false,
+ ],
[
'key' => 'custom_value1',
- 'required' => false
- ],
+ 'required' => false,
+ ],
[
'key' => 'custom_value2',
- 'required' => false
+ 'required' => false,
],
[
'key' => 'custom_value3',
- 'required' => false
- ],
+ 'required' => false,
+ ],
[
'key' => 'custom_value4',
- 'required' => false
- ],
+ 'required' => false,
+ ],
[
'key' => 'public_notes',
- 'required' => false
- ],
+ 'required' => false,
+ ],
[
'key' => 'vat_number',
- 'required' => false
- ],
+ 'required' => false,
+ ],
];
return $data;
}
-}
\ No newline at end of file
+}
diff --git a/app/DataMapper/ClientSettings.php b/app/DataMapper/ClientSettings.php
index 334b1c5936bd..2f10f03b655f 100644
--- a/app/DataMapper/ClientSettings.php
+++ b/app/DataMapper/ClientSettings.php
@@ -30,6 +30,7 @@ class ClientSettings extends BaseSettings
* Settings which which are unique to client settings.
*/
public $industry_id;
+
public $size_id;
public static $casts = [
diff --git a/app/DataMapper/CompanySettings.php b/app/DataMapper/CompanySettings.php
index 3ee028fe98f7..ddb3384daea1 100644
--- a/app/DataMapper/CompanySettings.php
+++ b/app/DataMapper/CompanySettings.php
@@ -28,20 +28,29 @@ class CompanySettings extends BaseSettings
public $lock_invoices = 'off'; //off,when_sent,when_paid //@implemented
public $enable_client_portal_tasks = false; //@ben to implement
+
public $show_all_tasks_client_portal = 'invoiced'; // all, uninvoiced, invoiced
+
public $enable_client_portal_password = false; //@implemented
+
public $enable_client_portal = true; //@implemented
+
public $enable_client_portal_dashboard = false; // @TODO There currently is no dashboard so this is pending
+
public $signature_on_pdf = false; //@implemented
+
public $document_email_attachment = false; //@TODO I assume this is 3rd party attachments on the entity to be included
public $portal_design_id = '1'; //?@deprecated
public $timezone_id = ''; //@implemented
+
public $date_format_id = ''; //@implemented
+
public $military_time = false; // @TODOImplemented in Tasks only?
public $language_id = ''; //@implemented
+
public $show_currency_code = false; //@implemented
public $company_gateway_ids = ''; //@implemented
@@ -49,243 +58,379 @@ class CompanySettings extends BaseSettings
public $currency_id = '1'; //@implemented
public $custom_value1 = ''; //@implemented
+
public $custom_value2 = ''; //@implemented
+
public $custom_value3 = ''; //@implemented
+
public $custom_value4 = ''; //@implemented
public $default_task_rate = 0; // @TODO Where do we inject this?
public $payment_terms = ''; //@implemented
+
public $send_reminders = true; //@TODO
public $custom_message_dashboard = ''; // @TODO There currently is no dashboard so this is pending
+
public $custom_message_unpaid_invoice = '';
+
public $custom_message_paid_invoice = '';
+
public $custom_message_unapproved_quote = '';
+
public $auto_archive_quote = false; //@implemented
+
public $auto_convert_quote = true; //@implemented
+
public $auto_email_invoice = true; //@only used for Recurring Invoices, if set to false, we never send?
public $entity_send_time = 6;
public $inclusive_taxes = false; //@implemented
+
public $quote_footer = ''; //@implmented
public $translations;
public $counter_number_applied = 'when_saved'; // when_saved , when_sent //@implemented
+
public $quote_number_applied = 'when_saved'; // when_saved , when_sent //@implemented
/* Counters */
public $invoice_number_pattern = ''; //@implemented
+
public $invoice_number_counter = 1; //@implemented
public $recurring_invoice_number_pattern = ''; //@implemented
+
public $recurring_invoice_number_counter = 1; //@implemented
public $quote_number_pattern = ''; //@implemented
+
public $quote_number_counter = 1; //@implemented
public $client_number_pattern = ''; //@implemented
+
public $client_number_counter = 1; //@implemented
public $credit_number_pattern = ''; //@implemented
+
public $credit_number_counter = 1; //@implemented
public $task_number_pattern = ''; //@implemented
+
public $task_number_counter = 1; //@implemented
public $expense_number_pattern = ''; //@implemented
+
public $expense_number_counter = 1; //@implemented
public $recurring_expense_number_pattern = '';
+
public $recurring_expense_number_counter = 1;
public $recurring_quote_number_pattern = '';
+
public $recurring_quote_number_counter = 1;
public $vendor_number_pattern = ''; //@implemented
+
public $vendor_number_counter = 1; //@implemented
public $ticket_number_pattern = ''; //@implemented
+
public $ticket_number_counter = 1; //@implemented
public $payment_number_pattern = ''; //@implemented
+
public $payment_number_counter = 1; //@implemented
public $project_number_pattern = ''; //@implemented
+
public $project_number_counter = 1; //@implemented
public $purchase_order_number_pattern = ''; //@implemented
+
public $purchase_order_number_counter = 1; //@implemented
public $shared_invoice_quote_counter = false; //@implemented
+
public $shared_invoice_credit_counter = false; //@implemented
+
public $recurring_number_prefix = ''; //@implemented
+
public $reset_counter_frequency_id = '0'; //@implemented
+
public $reset_counter_date = ''; //@implemented
+
public $counter_padding = 4; //@implemented
public $auto_bill = 'off'; //off,always,optin,optout //@implemented
+
public $auto_bill_date = 'on_due_date'; // on_due_date , on_send_date //@implemented
public $invoice_terms = ''; //@implemented
+
public $quote_terms = ''; //@implemented
+
public $invoice_taxes = 0; // ? used in AP only?
public $invoice_design_id = 'Wpmbk5ezJn'; //@implemented
+
public $quote_design_id = 'Wpmbk5ezJn'; //@implemented
+
public $credit_design_id = 'Wpmbk5ezJn'; //@implemented
public $purchase_order_design_id = 'Wpmbk5ezJn';
+
public $purchase_order_footer = ''; //@implemented
+
public $purchase_order_terms = ''; //@implemented
+
public $purchase_order_public_notes = ''; //@implemented
+
public $require_purchase_order_signature = false; //@TODO ben to confirm
-
+
public $invoice_footer = ''; //@implemented
+
public $credit_footer = ''; //@implemented
+
public $credit_terms = ''; //@implemented
+
public $invoice_labels = ''; //@TODO used in AP only?
+
public $tax_name1 = ''; //@TODO where do we use this?
+
public $tax_rate1 = 0; //@TODO where do we use this?
+
public $tax_name2 = ''; //@TODO where do we use this?
+
public $tax_rate2 = 0; //@TODO where do we use this?
+
public $tax_name3 = ''; //@TODO where do we use this?
+
public $tax_rate3 = 0; //@TODO where do we use this?
+
public $payment_type_id = '0'; //@TODO where do we use this?
public $valid_until = ''; //@implemented
public $show_accept_invoice_terms = false; //@TODO ben to confirm
+
public $show_accept_quote_terms = false; //@TODO ben to confirm
+
public $require_invoice_signature = false; //@TODO ben to confirm
+
public $require_quote_signature = false; //@TODO ben to confirm
//email settings
public $email_sending_method = 'default'; //enum 'default','gmail','office365' //@implemented
+
public $gmail_sending_user_id = '0'; //@implemented
public $reply_to_email = ''; //@implemented
+
public $reply_to_name = ''; //@implemented
+
public $bcc_email = ''; //@TODO
+
public $pdf_email_attachment = false; //@implemented
+
public $ubl_email_attachment = false; //@implemented
public $email_style = 'light'; //plain, light, dark, custom //@implemented
+
public $email_style_custom = ''; //the template itself //@implemented
+
public $email_subject_invoice = ''; //@implemented
+
public $email_subject_quote = ''; //@implemented
+
public $email_subject_credit = ''; //@implemented
+
public $email_subject_payment = ''; //@implemented
+
public $email_subject_payment_partial = ''; //@implemented
+
public $email_subject_statement = ''; //@implemented
+
public $email_subject_purchase_order = ''; //@implemented
+
public $email_template_purchase_order = ''; //@implemented
+
public $email_template_invoice = ''; //@implemented
+
public $email_template_credit = ''; //@implemented
+
public $email_template_quote = ''; //@implemented
+
public $email_template_payment = ''; //@implemented
+
public $email_template_payment_partial = ''; //@implemented
+
public $email_template_statement = ''; //@implemented
+
public $email_subject_reminder1 = ''; //@implemented
+
public $email_subject_reminder2 = ''; //@implemented
+
public $email_subject_reminder3 = ''; //@implemented
+
public $email_subject_reminder_endless = ''; //@implemented
+
public $email_template_reminder1 = ''; //@implemented
+
public $email_template_reminder2 = ''; //@implemented
+
public $email_template_reminder3 = ''; //@implemented
+
public $email_template_reminder_endless = ''; //@implemented
+
public $email_signature = ''; //@implemented
+
public $enable_email_markup = true; //@TODO -
public $email_subject_custom1 = ''; //@TODO
+
public $email_subject_custom2 = ''; //@TODO
+
public $email_subject_custom3 = ''; //@TODO
public $email_template_custom1 = ''; //@TODO
+
public $email_template_custom2 = ''; //@TODO
+
public $email_template_custom3 = ''; //@TODO
public $enable_reminder1 = false; //@implmemented
+
public $enable_reminder2 = false; //@implmemented
+
public $enable_reminder3 = false; //@implmemented
+
public $enable_reminder_endless = false; //@implmemented
- public $num_days_reminder1 = 0;//@implmemented
- public $num_days_reminder2 = 0;//@implmemented
- public $num_days_reminder3 = 0;//@implmemented
+ public $num_days_reminder1 = 0; //@implmemented
+
+ public $num_days_reminder2 = 0; //@implmemented
+
+ public $num_days_reminder3 = 0; //@implmemented
public $schedule_reminder1 = ''; // (enum: after_invoice_date, before_due_date, after_due_date) implmemented
+
public $schedule_reminder2 = ''; // (enum: after_invoice_date, before_due_date, after_due_date) implmemented
+
public $schedule_reminder3 = ''; // (enum: after_invoice_date, before_due_date, after_due_date) implmemented
public $reminder_send_time = 0; //number of seconds from UTC +0 to send reminders @TODO
public $late_fee_amount1 = 0; //@implemented
+
public $late_fee_amount2 = 0; //@implemented
+
public $late_fee_amount3 = 0; //@implemented
public $late_fee_percent1 = 0; //@implemented
+
public $late_fee_percent2 = 0; //@implemented
+
public $late_fee_percent3 = 0; //@implemented
public $endless_reminder_frequency_id = '0'; //@implemented
+
public $late_fee_endless_amount = 0; //@implemented
+
public $late_fee_endless_percent = 0; //@implemented
public $client_online_payment_notification = true; //@todo implement in notifications check this bool prior to sending payment notification to client
+
public $client_manual_payment_notification = true; //@todo implement in notifications check this bool prior to sending manual payment notification to client
/* Company Meta data that we can use to build sub companies*/
public $name = ''; //@implemented
+
public $company_logo = ''; //@implemented
+
public $website = ''; //@implemented
+
public $address1 = ''; //@implemented
+
public $address2 = ''; //@implemented
+
public $city = ''; //@implemented
+
public $state = ''; //@implemented
+
public $postal_code = ''; //@implemented
+
public $phone = ''; //@implemented
+
public $email = ''; //@implemented
+
public $country_id; //@implemented
+
public $vat_number = ''; //@implemented
+
public $id_number = ''; //@implemented
public $page_size = 'A4'; //Letter, Legal, Tabloid, Ledger, A0, A1, A2, A3, A4, A5, A6
+
public $page_layout = 'portrait';
+
public $font_size = 7; //@implemented
+
public $primary_font = 'Roboto';
+
public $secondary_font = 'Roboto';
+
public $primary_color = '#298AAB';
+
public $secondary_color = '#7081e0';
public $page_numbering = false;
+
public $page_numbering_alignment = 'C'; //C,R,L
public $hide_paid_to_date = false; //@TODO where?
+
public $embed_documents = false; //@TODO where?
+
public $all_pages_header = false; //@deprecated 31-05-2021
+
public $all_pages_footer = false; //@deprecated 31-05-2021
+
public $pdf_variables = ''; //@implemented
public $portal_custom_head = ''; //@TODO @BEN
+
public $portal_custom_css = ''; //@TODO @BEN
+
public $portal_custom_footer = ''; //@TODO @BEN
+
public $portal_custom_js = ''; //@TODO @BEN
public $client_can_register = false; //@deorecated 04/06/2021
+
public $client_portal_terms = ''; //@TODO @BEN
+
public $client_portal_privacy_policy = ''; //@TODO @BEN
+
public $client_portal_enable_uploads = false; //@implemented
+
public $client_portal_allow_under_payment = false; //@implemented
+
public $client_portal_under_payment_minimum = 0; //@implemented
+
public $client_portal_allow_over_payment = false; //@implemented
public $use_credits_payment = 'off'; //always, option, off //@implemented
+
public $hide_empty_columns_on_pdf = false;
+
public $email_from_name = '';
+
public $auto_archive_invoice_cancelled = false;
public static $casts = [
diff --git a/app/DataMapper/DefaultSettings.php b/app/DataMapper/DefaultSettings.php
index e2b4d45b9d52..2c0ebef43bcf 100644
--- a/app/DataMapper/DefaultSettings.php
+++ b/app/DataMapper/DefaultSettings.php
@@ -26,12 +26,11 @@ class DefaultSettings extends BaseSettings
/**
* @return stdClass
- *
*/
public static function userSettings() : stdClass
{
return (object) [
- // class_basename(User::class) => self::userSettingsObject(),
+ // class_basename(User::class) => self::userSettingsObject(),
];
}
@@ -41,7 +40,7 @@ class DefaultSettings extends BaseSettings
private static function userSettingsObject() : stdClass
{
return (object) [
- // 'per_page' => self::$per_page,
+ // 'per_page' => self::$per_page,
];
}
}
diff --git a/app/DataMapper/EmailTemplateDefaults.php b/app/DataMapper/EmailTemplateDefaults.php
index 5cdc7b915c23..3ce6ab53ac96 100644
--- a/app/DataMapper/EmailTemplateDefaults.php
+++ b/app/DataMapper/EmailTemplateDefaults.php
@@ -162,11 +162,9 @@ class EmailTemplateDefaults
public static function emailPurchaseOrderTemplate()
{
-
$purchase_order_message = '
$vendor
'.self::transformText('purchase_order_message').'
$view_button
';
return $purchase_order_message;
-
}
public static function emailPaymentTemplate()
@@ -249,6 +247,6 @@ class EmailTemplateDefaults
{
//preformat the string, removing trailing colons.
- return str_replace(':', '$', rtrim( ctrans('texts.'.$string), ":"));
+ return str_replace(':', '$', rtrim(ctrans('texts.'.$string), ':'));
}
}
diff --git a/app/DataMapper/FreeCompanySettings.php b/app/DataMapper/FreeCompanySettings.php
index fceab936b176..cecea6bf606d 100644
--- a/app/DataMapper/FreeCompanySettings.php
+++ b/app/DataMapper/FreeCompanySettings.php
@@ -20,67 +20,123 @@ use stdClass;
class FreeCompanySettings extends BaseSettings
{
use MakesHash;
+
/*Group settings based on functionality*/
public $credit_design_id = 'VolejRejNm';
+
public $client_number_pattern = '';
+
public $client_number_counter = 1;
+
public $credit_number_pattern = '';
+
public $credit_number_counter = 1;
+
public $currency_id = '1';
+
public $custom_value1 = '';
+
public $custom_value2 = '';
+
public $custom_value3 = '';
+
public $custom_value4 = '';
+
public $date_format_id = '';
+
// public $enabled_item_tax_rates = 0;
public $expense_number_pattern = '';
+
public $expense_number_counter = 1;
+
public $inclusive_taxes = false;
+
public $invoice_design_id = 'VolejRejNm';
+
public $invoice_number_pattern = '';
+
public $invoice_number_counter = 1;
+
public $invoice_taxes = 0;
+
public $language_id = '';
+
public $military_time = false;
+
public $payment_number_pattern = '';
+
public $payment_number_counter = 1;
+
public $payment_terms = '';
+
public $payment_type_id = '0';
+
public $portal_design_id = '1';
+
public $quote_design_id = 'VolejRejNm';
+
public $quote_number_pattern = '';
+
public $quote_number_counter = 1;
+
public $timezone_id = '';
+
public $show_currency_code = false;
+
public $company_gateway_ids = '';
+
public $task_number_pattern = '';
+
public $task_number_counter = 1;
+
public $tax_name1 = '';
+
public $tax_rate1 = 0;
+
public $tax_name2 = '';
+
public $tax_rate2 = 0;
+
public $tax_name3 = '';
+
public $tax_rate3 = 0;
+
public $ticket_number_pattern = '';
+
public $ticket_number_counter = 1;
+
public $translations;
+
public $vendor_number_pattern = '';
+
public $vendor_number_counter = 1;
/* Company Meta data that we can use to build sub companies*/
public $address1 = '';
+
public $address2 = '';
+
public $city = '';
+
public $company_logo = '';
+
public $country_id;
+
public $email = '';
+
public $id_number = '';
+
public $name = '';
+
public $phone = '';
+
public $postal_code = '';
+
public $state = '';
+
public $vat_number = '';
+
public $website = '';
public static $casts = [
diff --git a/app/DataMapper/Transactions/BaseTransaction.php b/app/DataMapper/Transactions/BaseTransaction.php
index 88c49b8cdb3c..7546ebbae740 100644
--- a/app/DataMapper/Transactions/BaseTransaction.php
+++ b/app/DataMapper/Transactions/BaseTransaction.php
@@ -22,8 +22,7 @@ use App\Models\TransactionEvent;
*/
class BaseTransaction implements TransactionInterface
{
-
- public $event_id = TransactionEvent::INVOICE_MARK_PAID;
+ public $event_id = TransactionEvent::INVOICE_MARK_PAID;
public array $model = [
'client_id',
@@ -56,7 +55,7 @@ class BaseTransaction implements TransactionInterface
{
// $invoice = $data['invoice'];
// $payment = $data['payment'];
- // $client = $data['client'];
+ // $client = $data['client'];
// $credit = $data['credit'];
// $payment_request = $data['payment']['payment_request'];
// $metadata = $data['metadata'];
@@ -95,6 +94,5 @@ class BaseTransaction implements TransactionInterface
// 'credit_status' => $credit?->status_id,
// 'timestamp' => time(),
// ];
-
}
}
diff --git a/app/DataMapper/Transactions/ClientStatusTransaction.php b/app/DataMapper/Transactions/ClientStatusTransaction.php
index 0670c3f0fd89..0c28e4a8dc16 100644
--- a/app/DataMapper/Transactions/ClientStatusTransaction.php
+++ b/app/DataMapper/Transactions/ClientStatusTransaction.php
@@ -22,7 +22,5 @@ use App\Models\TransactionEvent;
*/
class ClientStatusTransaction extends BaseTransaction implements TransactionInterface
{
-
- public $event_id = TransactionEvent::CLIENT_STATUS;
-
+ public $event_id = TransactionEvent::CLIENT_STATUS;
}
diff --git a/app/DataMapper/Transactions/GatewayPaymentMadeTransaction.php b/app/DataMapper/Transactions/GatewayPaymentMadeTransaction.php
index 26af2acd3b65..f41d91b7a8b8 100644
--- a/app/DataMapper/Transactions/GatewayPaymentMadeTransaction.php
+++ b/app/DataMapper/Transactions/GatewayPaymentMadeTransaction.php
@@ -22,7 +22,5 @@ use App\Models\TransactionEvent;
*/
class GatewayPaymentMadeTransaction extends BaseTransaction implements TransactionInterface
{
-
- public $event_id = TransactionEvent::GATEWAY_PAYMENT_MADE;
-
+ public $event_id = TransactionEvent::GATEWAY_PAYMENT_MADE;
}
diff --git a/app/DataMapper/Transactions/InvoiceCancelledTransaction.php b/app/DataMapper/Transactions/InvoiceCancelledTransaction.php
index 1e7438513285..9dcd28b09b03 100644
--- a/app/DataMapper/Transactions/InvoiceCancelledTransaction.php
+++ b/app/DataMapper/Transactions/InvoiceCancelledTransaction.php
@@ -22,7 +22,5 @@ use App\Models\TransactionEvent;
*/
class InvoiceCancelledTransaction extends BaseTransaction implements TransactionInterface
{
-
- public $event_id = TransactionEvent::INVOICE_CANCELLED;
-
+ public $event_id = TransactionEvent::INVOICE_CANCELLED;
}
diff --git a/app/DataMapper/Transactions/InvoiceDeletedTransaction.php b/app/DataMapper/Transactions/InvoiceDeletedTransaction.php
index 7a1d6c89ae35..a7ef833ad764 100644
--- a/app/DataMapper/Transactions/InvoiceDeletedTransaction.php
+++ b/app/DataMapper/Transactions/InvoiceDeletedTransaction.php
@@ -22,7 +22,5 @@ use App\Models\TransactionEvent;
*/
class InvoiceDeletedTransaction extends BaseTransaction implements TransactionInterface
{
-
- public $event_id = TransactionEvent::INVOICE_DELETED;
-
+ public $event_id = TransactionEvent::INVOICE_DELETED;
}
diff --git a/app/DataMapper/Transactions/InvoiceFeeAppliedTransaction.php b/app/DataMapper/Transactions/InvoiceFeeAppliedTransaction.php
index fdc9b4f67f7d..ab3a41fe9e3f 100644
--- a/app/DataMapper/Transactions/InvoiceFeeAppliedTransaction.php
+++ b/app/DataMapper/Transactions/InvoiceFeeAppliedTransaction.php
@@ -22,7 +22,5 @@ use App\Models\TransactionEvent;
*/
class InvoiceFeeAppliedTransaction extends BaseTransaction implements TransactionInterface
{
-
- public $event_id = TransactionEvent::INVOICE_FEE_APPLIED;
-
+ public $event_id = TransactionEvent::INVOICE_FEE_APPLIED;
}
diff --git a/app/DataMapper/Transactions/InvoicePaymentTransaction.php b/app/DataMapper/Transactions/InvoicePaymentTransaction.php
index af1c86f1d2cc..43c39d365288 100644
--- a/app/DataMapper/Transactions/InvoicePaymentTransaction.php
+++ b/app/DataMapper/Transactions/InvoicePaymentTransaction.php
@@ -22,7 +22,5 @@ use App\Models\TransactionEvent;
*/
class InvoicePaymentTransaction extends BaseTransaction implements TransactionInterface
{
-
- public $event_id = TransactionEvent::INVOICE_PAYMENT_APPLIED;
-
+ public $event_id = TransactionEvent::INVOICE_PAYMENT_APPLIED;
}
diff --git a/app/DataMapper/Transactions/InvoiceReversalTransaction.php b/app/DataMapper/Transactions/InvoiceReversalTransaction.php
index 4577b99434d8..afe2fb6dbf0c 100644
--- a/app/DataMapper/Transactions/InvoiceReversalTransaction.php
+++ b/app/DataMapper/Transactions/InvoiceReversalTransaction.php
@@ -22,7 +22,5 @@ use App\Models\TransactionEvent;
*/
class InvoiceReversalTransaction extends BaseTransaction implements TransactionInterface
{
-
- public $event_id = TransactionEvent::INVOICE_REVERSED;
-
+ public $event_id = TransactionEvent::INVOICE_REVERSED;
}
diff --git a/app/DataMapper/Transactions/InvoiceUpdatedTransaction.php b/app/DataMapper/Transactions/InvoiceUpdatedTransaction.php
index 675df7c230c7..fb0343aa9d15 100644
--- a/app/DataMapper/Transactions/InvoiceUpdatedTransaction.php
+++ b/app/DataMapper/Transactions/InvoiceUpdatedTransaction.php
@@ -22,7 +22,5 @@ use App\Models\TransactionEvent;
*/
class InvoiceUpdatedTransaction extends BaseTransaction implements TransactionInterface
{
-
- public $event_id = TransactionEvent::INVOICE_UPDATED;
-
+ public $event_id = TransactionEvent::INVOICE_UPDATED;
}
diff --git a/app/DataMapper/Transactions/MarkPaidTransaction.php b/app/DataMapper/Transactions/MarkPaidTransaction.php
index b1a5c2f6425f..78506c0c1503 100644
--- a/app/DataMapper/Transactions/MarkPaidTransaction.php
+++ b/app/DataMapper/Transactions/MarkPaidTransaction.php
@@ -22,7 +22,5 @@ use App\Models\TransactionEvent;
*/
class MarkPaidTransaction extends BaseTransaction implements TransactionInterface
{
-
- public $event_id = TransactionEvent::INVOICE_MARK_PAID;
-
+ public $event_id = TransactionEvent::INVOICE_MARK_PAID;
}
diff --git a/app/DataMapper/Transactions/PaymentAppliedTransaction.php b/app/DataMapper/Transactions/PaymentAppliedTransaction.php
index c00e3a828d1a..b0f9a32172d0 100644
--- a/app/DataMapper/Transactions/PaymentAppliedTransaction.php
+++ b/app/DataMapper/Transactions/PaymentAppliedTransaction.php
@@ -22,7 +22,5 @@ use App\Models\TransactionEvent;
*/
class PaymentAppliedTransaction extends BaseTransaction implements TransactionInterface
{
-
- public $event_id = TransactionEvent::PAYMENT_APPLIED;
-
+ public $event_id = TransactionEvent::PAYMENT_APPLIED;
}
diff --git a/app/DataMapper/Transactions/PaymentDeletedTransaction.php b/app/DataMapper/Transactions/PaymentDeletedTransaction.php
index f1d6e51cd8dc..e9cca01cce16 100644
--- a/app/DataMapper/Transactions/PaymentDeletedTransaction.php
+++ b/app/DataMapper/Transactions/PaymentDeletedTransaction.php
@@ -22,7 +22,5 @@ use App\Models\TransactionEvent;
*/
class PaymentDeletedTransaction extends BaseTransaction implements TransactionInterface
{
-
- public $event_id = TransactionEvent::PAYMENT_DELETED;
-
+ public $event_id = TransactionEvent::PAYMENT_DELETED;
}
diff --git a/app/DataMapper/Transactions/PaymentFailedTransaction.php b/app/DataMapper/Transactions/PaymentFailedTransaction.php
index a215c08815ac..d46bd83b16ff 100644
--- a/app/DataMapper/Transactions/PaymentFailedTransaction.php
+++ b/app/DataMapper/Transactions/PaymentFailedTransaction.php
@@ -22,7 +22,5 @@ use App\Models\TransactionEvent;
*/
class PaymentFailedTransaction extends BaseTransaction implements TransactionInterface
{
-
- public $event_id = TransactionEvent::PAYMENT_FAILED;
-
+ public $event_id = TransactionEvent::PAYMENT_FAILED;
}
diff --git a/app/DataMapper/Transactions/PaymentMadeTransaction.php b/app/DataMapper/Transactions/PaymentMadeTransaction.php
index a96b923eb746..427f59edc16a 100644
--- a/app/DataMapper/Transactions/PaymentMadeTransaction.php
+++ b/app/DataMapper/Transactions/PaymentMadeTransaction.php
@@ -22,7 +22,5 @@ use App\Models\TransactionEvent;
*/
class PaymentMadeTransaction extends BaseTransaction implements TransactionInterface
{
-
- public $event_id = TransactionEvent::PAYMENT_MADE;
-
+ public $event_id = TransactionEvent::PAYMENT_MADE;
}
diff --git a/app/DataMapper/Transactions/PaymentRefundedTransaction.php b/app/DataMapper/Transactions/PaymentRefundedTransaction.php
index a7c696d8e3b8..f2b2b92ad587 100644
--- a/app/DataMapper/Transactions/PaymentRefundedTransaction.php
+++ b/app/DataMapper/Transactions/PaymentRefundedTransaction.php
@@ -22,7 +22,5 @@ use App\Models\TransactionEvent;
*/
class PaymentRefundedTransaction extends BaseTransaction implements TransactionInterface
{
-
- public $event_id = TransactionEvent::PAYMENT_REFUND;
-
+ public $event_id = TransactionEvent::PAYMENT_REFUND;
}
diff --git a/app/Events/Client/ClientWasRestored.php b/app/Events/Client/ClientWasRestored.php
index 4a1fc529736b..41cf7fd04e50 100644
--- a/app/Events/Client/ClientWasRestored.php
+++ b/app/Events/Client/ClientWasRestored.php
@@ -28,7 +28,7 @@ class ClientWasRestored
public $client;
public $fromDeleted;
-
+
public $company;
public $event_vars;
diff --git a/app/Events/Credit/CreditWasEmailed.php b/app/Events/Credit/CreditWasEmailed.php
index fc567516c6b0..3c17c71da343 100644
--- a/app/Events/Credit/CreditWasEmailed.php
+++ b/app/Events/Credit/CreditWasEmailed.php
@@ -28,6 +28,7 @@ class CreditWasEmailed
public $event_vars;
public $template;
+
/**
* Create a new event instance.
*
diff --git a/app/Events/Credit/CreditWasMarkedSent.php b/app/Events/Credit/CreditWasMarkedSent.php
index 48f0ca791a48..60ce1a4e84cf 100644
--- a/app/Events/Credit/CreditWasMarkedSent.php
+++ b/app/Events/Credit/CreditWasMarkedSent.php
@@ -21,6 +21,7 @@ use Illuminate\Queue\SerializesModels;
class CreditWasMarkedSent
{
use SerializesModels;
+
/**
* @var Credit
*/
diff --git a/app/Events/Credit/CreditWasRestored.php b/app/Events/Credit/CreditWasRestored.php
index 1f515ac41625..cb564bc006ca 100644
--- a/app/Events/Credit/CreditWasRestored.php
+++ b/app/Events/Credit/CreditWasRestored.php
@@ -32,6 +32,7 @@ class CreditWasRestored
public $event_vars;
public $fromDeleted;
+
/**
* Create a new event instance.
*
diff --git a/app/Events/Design/DesignWasRestored.php b/app/Events/Design/DesignWasRestored.php
index bca0757aa152..42525602fa86 100644
--- a/app/Events/Design/DesignWasRestored.php
+++ b/app/Events/Design/DesignWasRestored.php
@@ -32,6 +32,7 @@ class DesignWasRestored
public $event_vars;
public $fromDeleted;
+
/**
* Create a new event instance.
*
diff --git a/app/Events/Document/DocumentWasRestored.php b/app/Events/Document/DocumentWasRestored.php
index 4941db97cfe1..3fc9580e7828 100644
--- a/app/Events/Document/DocumentWasRestored.php
+++ b/app/Events/Document/DocumentWasRestored.php
@@ -32,6 +32,7 @@ class DocumentWasRestored
public $event_vars;
public $fromDeleted;
+
/**
* Create a new event instance.
*
diff --git a/app/Events/Expense/ExpenseWasRestored.php b/app/Events/Expense/ExpenseWasRestored.php
index 2c74bf5e6d86..5341329823c1 100644
--- a/app/Events/Expense/ExpenseWasRestored.php
+++ b/app/Events/Expense/ExpenseWasRestored.php
@@ -32,6 +32,7 @@ class ExpenseWasRestored
public $event_vars;
public $fromDeleted;
+
/**
* Create a new event instance.
*
diff --git a/app/Events/Invoice/InvoiceWasRestored.php b/app/Events/Invoice/InvoiceWasRestored.php
index d848d4cb0e59..489e47b1a173 100644
--- a/app/Events/Invoice/InvoiceWasRestored.php
+++ b/app/Events/Invoice/InvoiceWasRestored.php
@@ -32,7 +32,7 @@ class InvoiceWasRestored
public $company;
public $event_vars;
-
+
/**
* Create a new event instance.
*
diff --git a/app/Events/Payment/PaymentWasRestored.php b/app/Events/Payment/PaymentWasRestored.php
index 390e3e193c92..378e3a956613 100644
--- a/app/Events/Payment/PaymentWasRestored.php
+++ b/app/Events/Payment/PaymentWasRestored.php
@@ -26,8 +26,11 @@ class PaymentWasRestored
* @var Payment
*/
public $payment;
+
public $fromDeleted;
+
public $company;
+
public $event_vars;
/**
diff --git a/app/Events/Product/ProductWasRestored.php b/app/Events/Product/ProductWasRestored.php
index 9949bf21b396..16432c6ce8b3 100644
--- a/app/Events/Product/ProductWasRestored.php
+++ b/app/Events/Product/ProductWasRestored.php
@@ -32,6 +32,7 @@ class ProductWasRestored
public $event_vars;
public $fromDeleted;
+
/**
* Create a new event instance.
*
diff --git a/app/Events/PurchaseOrder/PurchaseOrderWasAccepted.php b/app/Events/PurchaseOrder/PurchaseOrderWasAccepted.php
index ed2147b5fdb1..d903911cfda9 100644
--- a/app/Events/PurchaseOrder/PurchaseOrderWasAccepted.php
+++ b/app/Events/PurchaseOrder/PurchaseOrderWasAccepted.php
@@ -34,6 +34,7 @@ class PurchaseOrderWasAccepted
public $event_vars;
public $contact;
+
/**
* Create a new event instance.
*
diff --git a/app/Events/PurchaseOrder/PurchaseOrderWasRestored.php b/app/Events/PurchaseOrder/PurchaseOrderWasRestored.php
index c957c52a75b9..c0a40f7838a4 100644
--- a/app/Events/PurchaseOrder/PurchaseOrderWasRestored.php
+++ b/app/Events/PurchaseOrder/PurchaseOrderWasRestored.php
@@ -32,6 +32,7 @@ class PurchaseOrderWasRestored
public $event_vars;
public $fromDeleted;
+
/**
* Create a new event instance.
*
diff --git a/app/Events/Quote/QuoteWasEmailed.php b/app/Events/Quote/QuoteWasEmailed.php
index 02f6ea7c376b..5cd9ad36a19e 100644
--- a/app/Events/Quote/QuoteWasEmailed.php
+++ b/app/Events/Quote/QuoteWasEmailed.php
@@ -30,6 +30,7 @@ class QuoteWasEmailed
public $event_vars;
public $template;
+
/**
* Create a new event instance.
*
diff --git a/app/Events/Quote/QuoteWasRestored.php b/app/Events/Quote/QuoteWasRestored.php
index 162cec73d7d3..4f4f550e4e8f 100644
--- a/app/Events/Quote/QuoteWasRestored.php
+++ b/app/Events/Quote/QuoteWasRestored.php
@@ -29,6 +29,7 @@ class QuoteWasRestored
public $event_vars;
public $fromDeleted;
+
/**
* Create a new event instance.
*
diff --git a/app/Events/RecurringExpense/RecurringExpenseWasRestored.php b/app/Events/RecurringExpense/RecurringExpenseWasRestored.php
index 7134e211800c..903c041c49eb 100644
--- a/app/Events/RecurringExpense/RecurringExpenseWasRestored.php
+++ b/app/Events/RecurringExpense/RecurringExpenseWasRestored.php
@@ -32,6 +32,7 @@ class RecurringExpenseWasRestored
public $event_vars;
public $fromDeleted;
+
/**
* Create a new event instance.
*
diff --git a/app/Events/RecurringInvoice/RecurringInvoiceWasRestored.php b/app/Events/RecurringInvoice/RecurringInvoiceWasRestored.php
index e6441eae6143..4e31892c1f1c 100644
--- a/app/Events/RecurringInvoice/RecurringInvoiceWasRestored.php
+++ b/app/Events/RecurringInvoice/RecurringInvoiceWasRestored.php
@@ -32,7 +32,7 @@ class RecurringInvoiceWasRestored
public $company;
public $event_vars;
-
+
/**
* Create a new event instance.
*
diff --git a/app/Events/RecurringQuote/RecurringQuoteWasRestored.php b/app/Events/RecurringQuote/RecurringQuoteWasRestored.php
index 400bf11aa858..d84bc692e562 100644
--- a/app/Events/RecurringQuote/RecurringQuoteWasRestored.php
+++ b/app/Events/RecurringQuote/RecurringQuoteWasRestored.php
@@ -32,7 +32,7 @@ class RecurringQuoteWasRestored
public $company;
public $event_vars;
-
+
/**
* Create a new event instance.
*
diff --git a/app/Events/Subscription/SubscriptionWasCreated.php b/app/Events/Subscription/SubscriptionWasCreated.php
index 67d061f6738d..1da537bbbf1f 100644
--- a/app/Events/Subscription/SubscriptionWasCreated.php
+++ b/app/Events/Subscription/SubscriptionWasCreated.php
@@ -2,8 +2,8 @@
namespace App\Events\Subscription;
-use App\Models\Subscription;
use App\Models\Company;
+use App\Models\Subscription;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
diff --git a/app/Events/Subscription/SubscriptionWasRestored.php b/app/Events/Subscription/SubscriptionWasRestored.php
index d205a5c2f702..54029013febb 100644
--- a/app/Events/Subscription/SubscriptionWasRestored.php
+++ b/app/Events/Subscription/SubscriptionWasRestored.php
@@ -32,6 +32,7 @@ class SubscriptionWasRestored
public $event_vars;
public $fromDeleted;
+
/**
* Create a new event instance.
*
diff --git a/app/Events/Task/TaskWasRestored.php b/app/Events/Task/TaskWasRestored.php
index a6c68e5d2367..54f9b087e197 100644
--- a/app/Events/Task/TaskWasRestored.php
+++ b/app/Events/Task/TaskWasRestored.php
@@ -32,6 +32,7 @@ class TaskWasRestored
public $event_vars;
public $fromDeleted;
+
/**
* Create a new event instance.
*
diff --git a/app/Events/Vendor/VendorWasRestored.php b/app/Events/Vendor/VendorWasRestored.php
index 00f44cd8ae84..9d402240b504 100644
--- a/app/Events/Vendor/VendorWasRestored.php
+++ b/app/Events/Vendor/VendorWasRestored.php
@@ -32,6 +32,7 @@ class VendorWasRestored
public $event_vars;
public $fromDeleted;
+
/**
* Create a new event instance.
*
diff --git a/app/Exceptions/Handler.php b/app/Exceptions/Handler.php
index f9bc844a31da..7b5b4533a3ad 100644
--- a/app/Exceptions/Handler.php
+++ b/app/Exceptions/Handler.php
@@ -77,37 +77,33 @@ class Handler extends ExceptionHandler
{
if (! Schema::hasTable('accounts')) {
info('account table not found');
+
return;
}
- if(Ninja::isHosted() && !($exception instanceof ValidationException)){
-
+ if (Ninja::isHosted() && ! ($exception instanceof ValidationException)) {
app('sentry')->configureScope(function (Scope $scope): void {
-
$name = 'hosted@invoiceninja.com';
- if(auth()->guard('contact') && auth()->guard('contact')->user()){
- $name = "Contact = ".auth()->guard('contact')->user()->email;
+ if (auth()->guard('contact') && auth()->guard('contact')->user()) {
+ $name = 'Contact = '.auth()->guard('contact')->user()->email;
$key = auth()->guard('contact')->user()->company->account->key;
- }
- elseif (auth()->guard('user') && auth()->guard('user')->user()){
- $name = "Admin = ".auth()->guard('user')->user()->email;
+ } elseif (auth()->guard('user') && auth()->guard('user')->user()) {
+ $name = 'Admin = '.auth()->guard('user')->user()->email;
$key = auth()->user()->account->key;
- }
- else
+ } else {
$key = 'Anonymous';
-
- $scope->setUser([
- 'id' => $key,
- 'email' => 'hosted@invoiceninja.com',
- 'name' => $name,
- ]);
+ }
+
+ $scope->setUser([
+ 'id' => $key,
+ 'email' => 'hosted@invoiceninja.com',
+ 'name' => $name,
+ ]);
});
- app('sentry')->captureException($exception);
-
- }
- elseif (app()->bound('sentry') && $this->shouldReport($exception)) {
+ app('sentry')->captureException($exception);
+ } elseif (app()->bound('sentry') && $this->shouldReport($exception)) {
app('sentry')->configureScope(function (Scope $scope): void {
if (auth()->guard('contact') && auth()->guard('contact')->user() && auth()->guard('contact')->user()->company->account->report_errors) {
$scope->setUser([
@@ -130,28 +126,33 @@ class Handler extends ExceptionHandler
}
parent::report($exception);
-
}
private function validException($exception)
{
- if (strpos($exception->getMessage(), 'file_put_contents') !== false)
+ if (strpos($exception->getMessage(), 'file_put_contents') !== false) {
return false;
+ }
- if (strpos($exception->getMessage(), 'Permission denied') !== false)
- return false;
-
- if (strpos($exception->getMessage(), 'flock') !== false)
+ if (strpos($exception->getMessage(), 'Permission denied') !== false) {
return false;
+ }
- if (strpos($exception->getMessage(), 'expects parameter 1 to be resource') !== false)
+ if (strpos($exception->getMessage(), 'flock') !== false) {
return false;
+ }
- if (strpos($exception->getMessage(), 'fwrite()') !== false)
+ if (strpos($exception->getMessage(), 'expects parameter 1 to be resource') !== false) {
return false;
-
- if(strpos($exception->getMessage(), 'LockableFile') !== false)
+ }
+
+ if (strpos($exception->getMessage(), 'fwrite()') !== false) {
return false;
+ }
+
+ if (strpos($exception->getMessage(), 'LockableFile') !== false) {
+ return false;
+ }
return true;
}
@@ -168,11 +169,11 @@ class Handler extends ExceptionHandler
{
if ($exception instanceof ModelNotFoundException && $request->expectsJson()) {
return response()->json(['message'=>$exception->getMessage()], 400);
- }elseif($exception instanceof InternalPDFFailure && $request->expectsJson()){
+ } elseif ($exception instanceof InternalPDFFailure && $request->expectsJson()) {
return response()->json(['message' => $exception->getMessage()], 500);
- }elseif($exception instanceof PhantomPDFFailure && $request->expectsJson()){
+ } elseif ($exception instanceof PhantomPDFFailure && $request->expectsJson()) {
return response()->json(['message' => $exception->getMessage()], 500);
- }elseif($exception instanceof FilePermissionsFailure) {
+ } elseif ($exception instanceof FilePermissionsFailure) {
return response()->json(['message' => $exception->getMessage()], 500);
} elseif ($exception instanceof ThrottleRequestsException && $request->expectsJson()) {
return response()->json(['message'=>'Too many requests'], 429);
@@ -202,7 +203,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);
}
diff --git a/app/Exceptions/PaymentFailed.php b/app/Exceptions/PaymentFailed.php
index 7c0f2cb67711..13bf2e10d21b 100644
--- a/app/Exceptions/PaymentFailed.php
+++ b/app/Exceptions/PaymentFailed.php
@@ -13,7 +13,7 @@ class PaymentFailed extends Exception
public function render($request)
{
- if (auth()->user() || ($request->has('cko-session-id') && $request->query('cko-session-id') )) {
+ if (auth()->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 94a6fe455e01..d2be5cadc8b2 100644
--- a/app/Exceptions/PaymentRefundFailed.php
+++ b/app/Exceptions/PaymentRefundFailed.php
@@ -30,12 +30,12 @@ class PaymentRefundFailed extends Exception
// $msg = 'Unable to refund the transaction';
$msg = ctrans('texts.warning_local_refund');
- if($this->getMessage() && strlen($this->getMessage()) >=1 )
+ if ($this->getMessage() && strlen($this->getMessage()) >= 1) {
$msg = $this->getMessage();
+ }
return response()->json([
- 'message' => $msg,
- ], 401);
-
+ 'message' => $msg,
+ ], 401);
}
}
diff --git a/app/Exceptions/SystemError.php b/app/Exceptions/SystemError.php
index f15cf8cf1333..03b0aaabe0c7 100644
--- a/app/Exceptions/SystemError.php
+++ b/app/Exceptions/SystemError.php
@@ -13,12 +13,9 @@ class SystemError extends Exception
public function render($request)
{
-
return view('errors.guest', [
'message' => $this->getMessage(),
'code' => $this->getCode(),
]);
-
-
}
}
diff --git a/app/Export/CSV/BaseExport.php b/app/Export/CSV/BaseExport.php
index 250bba51d10c..4d0271b767d3 100644
--- a/app/Export/CSV/BaseExport.php
+++ b/app/Export/CSV/BaseExport.php
@@ -15,28 +15,22 @@ use Illuminate\Support\Carbon;
class BaseExport
{
-
protected function addDateRange($query)
{
-
$date_range = $this->input['date_range'];
- if(array_key_exists('date_key', $this->input) && strlen($this->input['date_key']) > 1)
+ if (array_key_exists('date_key', $this->input) && strlen($this->input['date_key']) > 1) {
$this->date_key = $this->input['date_key'];
-
- try{
-
- $custom_start_date = Carbon::parse($this->input['start_date']);
- $custom_end_date = Carbon::parse($this->input['end_date']);
-
}
- catch(\Exception $e){
+ try {
+ $custom_start_date = Carbon::parse($this->input['start_date']);
+ $custom_end_date = Carbon::parse($this->input['end_date']);
+ } catch (\Exception $e) {
$custom_start_date = now()->startOfYear();
$custom_end_date = now();
-
}
-
+
switch ($date_range) {
case 'all':
@@ -61,26 +55,23 @@ class BaseExport
return $query->whereBetween($this->date_key, [now()->startOfYear(), now()])->orderBy($this->date_key, 'ASC');
}
-
}
protected function buildHeader() :array
{
-
$header = [];
- foreach($this->input['report_keys'] as $value){
+ foreach ($this->input['report_keys'] as $value) {
+ $key = array_search($value, $this->entity_keys);
- $key = array_search ($value, $this->entity_keys);
-
- $key = str_replace("item.", "", $key);
- $key = str_replace("invoice.", "", $key);
- $key = str_replace("client.", "", $key);
- $key = str_replace("contact.", "", $key);
+ $key = str_replace('item.', '', $key);
+ $key = str_replace('invoice.', '', $key);
+ $key = str_replace('client.', '', $key);
+ $key = str_replace('contact.', '', $key);
$header[] = ctrans("texts.{$key}");
}
return $header;
}
-}
\ No newline at end of file
+}
diff --git a/app/Export/CSV/ClientExport.php b/app/Export/CSV/ClientExport.php
index b4d4df64e67e..5ba69ed72622 100644
--- a/app/Export/CSV/ClientExport.php
+++ b/app/Export/CSV/ClientExport.php
@@ -17,9 +17,9 @@ 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;
-use Illuminate\Support\Carbon;
class ClientExport extends BaseExport
{
@@ -95,7 +95,6 @@ class ClientExport extends BaseExport
public function run()
{
-
MultiDB::setDb($this->company->db);
App::forgetInstance('translator');
App::setLocale($this->company->locale());
@@ -105,8 +104,9 @@ class ClientExport 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());
@@ -114,69 +114,65 @@ class ClientExport extends BaseExport
$query = Client::query()->with('contacts')
->withTrashed()
->where('company_id', $this->company->id)
- ->where('is_deleted',0);
-
+ ->where('is_deleted', 0);
+
$query = $this->addDateRange($query);
$query->cursor()
- ->each(function ($client){
- $this->csv->insertOne($this->buildRow($client));
- });
-
-
- return $this->csv->toString();
+ ->each(function ($client) {
+ $this->csv->insertOne($this->buildRow($client));
+ });
+ return $this->csv->toString();
}
private function buildRow(Client $client) :array
{
-
$transformed_contact = false;
$transformed_client = $this->client_transformer->transform($client);
- if($contact = $client->contacts()->first())
+ if ($contact = $client->contacts()->first()) {
$transformed_contact = $this->contact_transformer->transform($contact);
+ }
$entity = [];
- foreach(array_values($this->input['report_keys']) as $key){
+ foreach (array_values($this->input['report_keys']) as $key) {
+ $parts = explode('.', $key);
- $parts = explode(".",$key);
-
$keyval = array_search($key, $this->entity_keys);
- if($parts[0] == 'client' && array_key_exists($parts[1], $transformed_client)) {
+ if ($parts[0] == 'client' && array_key_exists($parts[1], $transformed_client)) {
$entity[$keyval] = $transformed_client[$parts[1]];
- }
- elseif($parts[0] == 'contact' && array_key_exists($parts[1], $transformed_contact)) {
+ } elseif ($parts[0] == 'contact' && array_key_exists($parts[1], $transformed_contact)) {
$entity[$keyval] = $transformed_contact[$parts[1]];
+ } else {
+ $entity[$keyval] = '';
}
- else
- $entity[$keyval] = "";
-
}
return $this->decorateAdvancedFields($client, $entity);
-
}
private function decorateAdvancedFields(Client $client, array $entity) :array
{
+ if (in_array('client.country_id', $this->input['report_keys'])) {
+ $entity['country'] = $client->country ? ctrans("texts.country_{$client->country->name}") : '';
+ }
- if(in_array('client.country_id', $this->input['report_keys']))
- $entity['country'] = $client->country ? ctrans("texts.country_{$client->country->name}") : "";
+ if (in_array('client.shipping_country_id', $this->input['report_keys'])) {
+ $entity['shipping_country'] = $client->shipping_country ? ctrans("texts.country_{$client->shipping_country->name}") : '';
+ }
- if(in_array('client.shipping_country_id', $this->input['report_keys']))
- $entity['shipping_country'] = $client->shipping_country ? ctrans("texts.country_{$client->shipping_country->name}") : "";
-
- if(in_array('client.currency', $this->input['report_keys']))
+ if (in_array('client.currency', $this->input['report_keys'])) {
$entity['currency'] = $client->currency() ? $client->currency()->code : $client->company->currency()->code;
+ }
- if(in_array('client.industry_id', $this->input['report_keys']))
- $entity['industry_id'] = $client->industry ? ctrans("texts.industry_{$client->industry->name}") : "";
+ if (in_array('client.industry_id', $this->input['report_keys'])) {
+ $entity['industry_id'] = $client->industry ? ctrans("texts.industry_{$client->industry->name}") : '';
+ }
return $entity;
}
-
}
diff --git a/app/Export/CSV/ContactExport.php b/app/Export/CSV/ContactExport.php
index 1c938b187f46..a96974cba829 100644
--- a/app/Export/CSV/ContactExport.php
+++ b/app/Export/CSV/ContactExport.php
@@ -91,7 +91,6 @@ class ContactExport extends BaseExport
public function run()
{
-
MultiDB::setDb($this->company->db);
App::forgetInstance('translator');
App::setLocale($this->company->locale());
@@ -101,8 +100,9 @@ class ContactExport 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());
@@ -112,19 +112,15 @@ class ContactExport extends BaseExport
$query = $this->addDateRange($query);
- $query->cursor()->each(function ($contact){
-
- $this->csv->insertOne($this->buildRow($contact));
-
+ $query->cursor()->each(function ($contact) {
+ $this->csv->insertOne($this->buildRow($contact));
});
- return $this->csv->toString();
-
+ return $this->csv->toString();
}
private function buildRow(ClientContact $contact) :array
{
-
$transformed_contact = false;
$transformed_client = $this->client_transformer->transform($contact->client);
@@ -132,41 +128,40 @@ class ContactExport extends BaseExport
$entity = [];
- foreach(array_values($this->input['report_keys']) as $key){
-
- $parts = explode(".",$key);
+ foreach (array_values($this->input['report_keys']) as $key) {
+ $parts = explode('.', $key);
$keyval = array_search($key, $this->entity_keys);
- if($parts[0] == 'client' && array_key_exists($parts[1], $transformed_client)) {
+ if ($parts[0] == 'client' && array_key_exists($parts[1], $transformed_client)) {
$entity[$keyval] = $transformed_client[$parts[1]];
- }
- elseif($parts[0] == 'contact' && array_key_exists($parts[1], $transformed_contact)) {
+ } elseif ($parts[0] == 'contact' && array_key_exists($parts[1], $transformed_contact)) {
$entity[$keyval] = $transformed_contact[$parts[1]];
+ } else {
+ $entity[$keyval] = '';
}
- else
- $entity[$keyval] = "";
}
return $this->decorateAdvancedFields($contact->client, $entity);
-
}
private function decorateAdvancedFields(Client $client, array $entity) :array
{
+ if (in_array('client.country_id', $this->input['report_keys'])) {
+ $entity['country'] = $client->country ? ctrans("texts.country_{$client->country->name}") : '';
+ }
- if(in_array('client.country_id', $this->input['report_keys']))
- $entity['country'] = $client->country ? ctrans("texts.country_{$client->country->name}") : "";
+ if (in_array('client.shipping_country_id', $this->input['report_keys'])) {
+ $entity['shipping_country'] = $client->shipping_country ? ctrans("texts.country_{$client->shipping_country->name}") : '';
+ }
- if(in_array('client.shipping_country_id', $this->input['report_keys']))
- $entity['shipping_country'] = $client->shipping_country ? ctrans("texts.country_{$client->shipping_country->name}") : "";
-
- if(in_array('client.currency', $this->input['report_keys']))
+ if (in_array('client.currency', $this->input['report_keys'])) {
$entity['currency'] = $client->currency() ? $client->currency()->code : $client->company->currency()->code;
+ }
- if(in_array('client.industry_id', $this->input['report_keys']))
- $entity['industry_id'] = $client->industry ? ctrans("texts.industry_{$client->industry->name}") : "";
+ if (in_array('client.industry_id', $this->input['report_keys'])) {
+ $entity['industry_id'] = $client->industry ? ctrans("texts.industry_{$client->industry->name}") : '';
+ }
return $entity;
}
-
}
diff --git a/app/Export/CSV/CreditExport.php b/app/Export/CSV/CreditExport.php
index e28711bfe111..8a552a991300 100644
--- a/app/Export/CSV/CreditExport.php
+++ b/app/Export/CSV/CreditExport.php
@@ -65,7 +65,7 @@ class CreditExport extends BaseExport
'tax_rate3' => 'tax_rate3',
'terms' => 'terms',
'total_taxes' => 'total_taxes',
- 'currency' => 'currency'
+ 'currency' => 'currency',
];
private array $decorate_keys = [
@@ -84,7 +84,6 @@ class CreditExport extends BaseExport
public function run()
{
-
MultiDB::setDb($this->company->db);
App::forgetInstance('translator');
App::setLocale($this->company->locale());
@@ -94,71 +93,69 @@ class CreditExport 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());
$query = Credit::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 ($credit){
-
- $this->csv->insertOne($this->buildRow($credit));
-
- });
-
- return $this->csv->toString();
+ ->each(function ($credit) {
+ $this->csv->insertOne($this->buildRow($credit));
+ });
+ return $this->csv->toString();
}
private function buildRow(Credit $credit) :array
{
-
$transformed_credit = $this->credit_transformer->transform($credit);
$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_credit))
+ if (array_key_exists($key, $transformed_credit)) {
$entity[$keyval] = $transformed_credit[$key];
- else
+ } else {
$entity[$keyval] = '';
-
+ }
}
return $this->decorateAdvancedFields($credit, $entity);
-
}
private function decorateAdvancedFields(Credit $credit, array $entity) :array
{
+ if (in_array('country_id', $this->input['report_keys'])) {
+ $entity['country'] = $credit->client->country ? ctrans("texts.country_{$credit->client->country->name}") : '';
+ }
- if(in_array('country_id', $this->input['report_keys']))
- $entity['country'] = $credit->client->country ? ctrans("texts.country_{$credit->client->country->name}") : "";
+ if (in_array('currency_id', $this->input['report_keys'])) {
+ $entity['currency_id'] = $credit->client->currency() ? $credit->client->currency()->code : $invoice->company->currency()->code;
+ }
- if(in_array('currency_id', $this->input['report_keys']))
- $entity['currency_id'] = $credit->client->currency() ? $credit->client->currency()->code : $invoice->company->currency()->code;;
+ if (in_array('invoice_id', $this->input['report_keys'])) {
+ $entity['invoice'] = $credit->invoice ? $credit->invoice->number : '';
+ }
- if(in_array('invoice_id', $this->input['report_keys']))
- $entity['invoice'] = $credit->invoice ? $credit->invoice->number : "";
-
- if(in_array('client_id', $this->input['report_keys']))
+ if (in_array('client_id', $this->input['report_keys'])) {
$entity['client'] = $credit->client->present()->name();
+ }
- if(in_array('status_id',$this->input['report_keys']))
+ if (in_array('status_id', $this->input['report_keys'])) {
$entity['status'] = $credit->stringStatus($credit->status_id);
+ }
return $entity;
}
-
}
diff --git a/app/Export/CSV/DocumentExport.php b/app/Export/CSV/DocumentExport.php
index b70a854af7bd..dae5f6509c74 100644
--- a/app/Export/CSV/DocumentExport.php
+++ b/app/Export/CSV/DocumentExport.php
@@ -52,7 +52,6 @@ class DocumentExport extends BaseExport
public function run()
{
-
MultiDB::setDb($this->company->db);
App::forgetInstance('translator');
App::setLocale($this->company->locale());
@@ -62,8 +61,9 @@ class DocumentExport 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());
@@ -73,47 +73,41 @@ class DocumentExport extends BaseExport
$query = $this->addDateRange($query);
$query->cursor()
- ->each(function ($entity){
-
- $this->csv->insertOne($this->buildRow($entity));
-
- });
-
- return $this->csv->toString();
+ ->each(function ($entity) {
+ $this->csv->insertOne($this->buildRow($entity));
+ });
+ return $this->csv->toString();
}
private function buildRow(Document $document) :array
{
-
$transformed_entity = $this->entity_transformer->transform($document);
$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_entity))
+ if (array_key_exists($key, $transformed_entity)) {
$entity[$keyval] = $transformed_entity[$key];
- else
- $entity[$keyval] = '';
+ } else {
+ $entity[$keyval] = '';
+ }
}
return $this->decorateAdvancedFields($document, $entity);
-
}
private function decorateAdvancedFields(Document $document, array $entity) :array
{
-
- if(in_array('record_type', $this->input['report_keys']))
+ if (in_array('record_type', $this->input['report_keys'])) {
$entity['record_type'] = class_basename($document->documentable);
+ }
// if(in_array('record_name', $this->input['report_keys']))
// $entity['record_name'] = $document->hashed_id;
return $entity;
}
-
}
diff --git a/app/Export/CSV/ExpenseExport.php b/app/Export/CSV/ExpenseExport.php
index d4ccaaa23674..dced738d742c 100644
--- a/app/Export/CSV/ExpenseExport.php
+++ b/app/Export/CSV/ExpenseExport.php
@@ -82,7 +82,6 @@ class ExpenseExport extends BaseExport
public function run()
{
-
MultiDB::setDb($this->company->db);
App::forgetInstance('translator');
App::setLocale($this->company->locale());
@@ -92,8 +91,9 @@ class ExpenseExport 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());
@@ -102,69 +102,67 @@ class ExpenseExport extends BaseExport
->with('client')
->withTrashed()
->where('company_id', $this->company->id)
- ->where('is_deleted',0);
+ ->where('is_deleted', 0);
$query = $this->addDateRange($query);
$query->cursor()
- ->each(function ($expense){
-
- $this->csv->insertOne($this->buildRow($expense));
-
- });
-
-
- return $this->csv->toString();
+ ->each(function ($expense) {
+ $this->csv->insertOne($this->buildRow($expense));
+ });
+ return $this->csv->toString();
}
private function buildRow(Expense $expense) :array
{
-
$transformed_expense = $this->expense_transformer->transform($expense);
$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_expense))
+ if (array_key_exists($key, $transformed_expense)) {
$entity[$keyval] = $transformed_expense[$key];
- else
+ } else {
$entity[$keyval] = '';
-
+ }
}
return $this->decorateAdvancedFields($expense, $entity);
-
}
private function decorateAdvancedFields(Expense $expense, array $entity) :array
{
- if(in_array('currency_id', $this->input['report_keys']))
- $entity['currency'] = $expense->currency ? $expense->currency->code : "";
+ if (in_array('currency_id', $this->input['report_keys'])) {
+ $entity['currency'] = $expense->currency ? $expense->currency->code : '';
+ }
- if(in_array('client_id', $this->input['report_keys']))
- $entity['client'] = $expense->client ? $expense->client->present()->name() : "";
+ if (in_array('client_id', $this->input['report_keys'])) {
+ $entity['client'] = $expense->client ? $expense->client->present()->name() : '';
+ }
- if(in_array('invoice_id', $this->input['report_keys']))
- $entity['invoice'] = $expense->invoice ? $expense->invoice->number : "";
+ if (in_array('invoice_id', $this->input['report_keys'])) {
+ $entity['invoice'] = $expense->invoice ? $expense->invoice->number : '';
+ }
- if(in_array('category_id', $this->input['report_keys']))
- $entity['category'] = $expense->category ? $expense->category->name : "";
+ if (in_array('category_id', $this->input['report_keys'])) {
+ $entity['category'] = $expense->category ? $expense->category->name : '';
+ }
- if(in_array('vendor_id', $this->input['report_keys']))
- $entity['vendor'] = $expense->vendor ? $expense->vendor->name : "";
+ if (in_array('vendor_id', $this->input['report_keys'])) {
+ $entity['vendor'] = $expense->vendor ? $expense->vendor->name : '';
+ }
- if(in_array('payment_type_id', $this->input['report_keys']))
- $entity['payment_type'] = $expense->payment_type ? $expense->payment_type->name : "";
-
- if(in_array('project_id', $this->input['report_keys']))
- $entity['project'] = $expense->project ? $expense->project->name : "";
+ if (in_array('payment_type_id', $this->input['report_keys'])) {
+ $entity['payment_type'] = $expense->payment_type ? $expense->payment_type->name : '';
+ }
+ if (in_array('project_id', $this->input['report_keys'])) {
+ $entity['project'] = $expense->project ? $expense->project->name : '';
+ }
return $entity;
}
-
}
diff --git a/app/Export/CSV/InvoiceExport.php b/app/Export/CSV/InvoiceExport.php
index 76ecf16a18c4..be13d99c3a9f 100644
--- a/app/Export/CSV/InvoiceExport.php
+++ b/app/Export/CSV/InvoiceExport.php
@@ -63,7 +63,7 @@ class InvoiceExport extends BaseExport
'tax_rate3' => 'tax_rate3',
'terms' => 'terms',
'total_taxes' => 'total_taxes',
- 'currency_id' => 'currency_id'
+ 'currency_id' => 'currency_id',
];
private array $decorate_keys = [
@@ -84,7 +84,6 @@ class InvoiceExport extends BaseExport
public function run()
{
-
MultiDB::setDb($this->company->db);
App::forgetInstance('translator');
App::setLocale($this->company->locale());
@@ -94,9 +93,10 @@ class InvoiceExport 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());
@@ -104,57 +104,55 @@ class InvoiceExport extends BaseExport
->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){
-
- $this->csv->insertOne($this->buildRow($invoice));
-
- });
-
- return $this->csv->toString();
+ ->each(function ($invoice) {
+ $this->csv->insertOne($this->buildRow($invoice));
+ });
+ return $this->csv->toString();
}
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('country_id', $this->input['report_keys']))
- $entity['country'] = $invoice->client->country ? ctrans("texts.country_{$invoice->client->country->name}") : "";
+ if (in_array('country_id', $this->input['report_keys'])) {
+ $entity['country'] = $invoice->client->country ? ctrans("texts.country_{$invoice->client->country->name}") : '';
+ }
- if(in_array('currency_id', $this->input['report_keys']))
+ if (in_array('currency_id', $this->input['report_keys'])) {
$entity['currency_id'] = $invoice->client->currency() ? $invoice->client->currency()->code : $invoice->company->currency()->code;
+ }
- if(in_array('client_id', $this->input['report_keys']))
+ if (in_array('client_id', $this->input['report_keys'])) {
$entity['client'] = $invoice->client->present()->name();
+ }
- if(in_array('status_id',$this->input['report_keys']))
+ if (in_array('status_id', $this->input['report_keys'])) {
$entity['status'] = $invoice->stringStatus($invoice->status_id);
+ }
return $entity;
}
-
}
diff --git a/app/Export/CSV/InvoiceItemExport.php b/app/Export/CSV/InvoiceItemExport.php
index fdaceae88cc2..e7edd540bf3d 100644
--- a/app/Export/CSV/InvoiceItemExport.php
+++ b/app/Export/CSV/InvoiceItemExport.php
@@ -99,7 +99,6 @@ class InvoiceItemExport extends BaseExport
public function run()
{
-
MultiDB::setDb($this->company->db);
App::forgetInstance('translator');
App::setLocale($this->company->locale());
@@ -109,27 +108,25 @@ 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());
$query = Invoice::query()
->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)
@@ -138,76 +135,68 @@ 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.")){
-
- $key = str_replace("item.", "", $key);
+ foreach (array_values($this->input['report_keys']) as $key) {
+ if (str_contains($key, 'item.')) {
+ $key = str_replace('item.', '', $key);
$item_array[$key] = $item->{$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
- $entity[$keyval] = "";
-
+ } 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
- $entity[$keyval] = "";
-
+ } 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']))
+ if (in_array('client_id', $this->input['report_keys'])) {
$entity['client'] = $invoice->client->present()->name();
+ }
- if(in_array('status_id', $this->input['report_keys']))
+ if (in_array('status_id', $this->input['report_keys'])) {
$entity['status'] = $invoice->stringStatus($invoice->status_id);
+ }
return $entity;
}
-
}
diff --git a/app/Export/CSV/PaymentExport.php b/app/Export/CSV/PaymentExport.php
index 0b5b4f309772..ccd49d84e109 100644
--- a/app/Export/CSV/PaymentExport.php
+++ b/app/Export/CSV/PaymentExport.php
@@ -73,7 +73,6 @@ class PaymentExport extends BaseExport
public function run()
{
-
MultiDB::setDb($this->company->db);
App::forgetInstance('translator');
App::setLocale($this->company->locale());
@@ -83,8 +82,9 @@ class PaymentExport 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());
@@ -94,66 +94,66 @@ class PaymentExport extends BaseExport
$query = $this->addDateRange($query);
$query->cursor()
- ->each(function ($entity){
-
- $this->csv->insertOne($this->buildRow($entity));
-
- });
-
- return $this->csv->toString();
+ ->each(function ($entity) {
+ $this->csv->insertOne($this->buildRow($entity));
+ });
+ return $this->csv->toString();
}
private function buildRow(Payment $payment) :array
{
-
$transformed_entity = $this->entity_transformer->transform($payment);
$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_entity))
+ if (array_key_exists($key, $transformed_entity)) {
$entity[$keyval] = $transformed_entity[$key];
- else
+ } else {
$entity[$keyval] = '';
-
+ }
}
return $this->decorateAdvancedFields($payment, $entity);
-
}
private function decorateAdvancedFields(Payment $payment, array $entity) :array
{
-
- if(in_array('status_id', $this->input['report_keys']))
+ if (in_array('status_id', $this->input['report_keys'])) {
$entity['status'] = $payment->stringStatus($payment->status_id);
+ }
- if(in_array('vendor_id', $this->input['report_keys']))
+ if (in_array('vendor_id', $this->input['report_keys'])) {
$entity['vendor'] = $payment->vendor()->exists() ? $payment->vendor->name : '';
+ }
- if(in_array('project_id', $this->input['report_keys']))
+ if (in_array('project_id', $this->input['report_keys'])) {
$entity['project'] = $payment->project()->exists() ? $payment->project->name : '';
+ }
- if(in_array('currency_id', $this->input['report_keys']))
+ if (in_array('currency_id', $this->input['report_keys'])) {
$entity['currency'] = $payment->currency()->exists() ? $payment->currency->code : '';
+ }
- if(in_array('exchange_currency_id', $this->input['report_keys']))
+ if (in_array('exchange_currency_id', $this->input['report_keys'])) {
$entity['exchange_currency'] = $payment->exchange_currency()->exists() ? $payment->exchange_currency->code : '';
+ }
- if(in_array('client_id', $this->input['report_keys']))
+ if (in_array('client_id', $this->input['report_keys'])) {
$entity['client'] = $payment->client->present()->name();
+ }
- if(in_array('type_id', $this->input['report_keys']))
+ if (in_array('type_id', $this->input['report_keys'])) {
$entity['type'] = $payment->translatedType();
+ }
- if(in_array('gateway_type_id', $this->input['report_keys']))
- $entity['gateway'] = $payment->gateway_type ? $payment->gateway_type->name : "Unknown Type";
+ if (in_array('gateway_type_id', $this->input['report_keys'])) {
+ $entity['gateway'] = $payment->gateway_type ? $payment->gateway_type->name : 'Unknown Type';
+ }
return $entity;
}
-
}
diff --git a/app/Export/CSV/ProductExport.php b/app/Export/CSV/ProductExport.php
index 9523f8ad050a..ff96841951d0 100644
--- a/app/Export/CSV/ProductExport.php
+++ b/app/Export/CSV/ProductExport.php
@@ -66,7 +66,6 @@ class ProductExport extends BaseExport
public function run()
{
-
MultiDB::setDb($this->company->db);
App::forgetInstance('translator');
App::setLocale($this->company->locale());
@@ -76,8 +75,9 @@ class ProductExport 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());
@@ -87,49 +87,42 @@ class ProductExport extends BaseExport
$query = $this->addDateRange($query);
$query->cursor()
- ->each(function ($entity){
-
- $this->csv->insertOne($this->buildRow($entity));
-
- });
-
- return $this->csv->toString();
+ ->each(function ($entity) {
+ $this->csv->insertOne($this->buildRow($entity));
+ });
+ return $this->csv->toString();
}
private function buildRow(Product $product) :array
{
-
$transformed_entity = $this->entity_transformer->transform($product);
$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_entity))
+ if (array_key_exists($key, $transformed_entity)) {
$entity[$keyval] = $transformed_entity[$key];
- else
+ } else {
$entity[$keyval] = '';
-
-
+ }
}
return $this->decorateAdvancedFields($product, $entity);
-
}
private function decorateAdvancedFields(Product $product, array $entity) :array
{
-
- if(in_array('vendor_id', $this->input['report_keys']))
+ if (in_array('vendor_id', $this->input['report_keys'])) {
$entity['vendor'] = $product->vendor()->exists() ? $product->vendor->name : '';
+ }
- if(array_key_exists('project_id', $this->input['report_keys']))
+ if (array_key_exists('project_id', $this->input['report_keys'])) {
$entity['project'] = $product->project()->exists() ? $product->project->name : '';
+ }
return $entity;
}
-
}
diff --git a/app/Export/CSV/QuoteExport.php b/app/Export/CSV/QuoteExport.php
index fe1dff206eb6..a48f4c4ef4a8 100644
--- a/app/Export/CSV/QuoteExport.php
+++ b/app/Export/CSV/QuoteExport.php
@@ -70,7 +70,7 @@ class QuoteExport extends BaseExport
private array $decorate_keys = [
'client',
'currency',
- 'invoice'
+ 'invoice',
];
public function __construct(Company $company, array $input)
@@ -82,7 +82,6 @@ class QuoteExport extends BaseExport
public function run()
{
-
MultiDB::setDb($this->company->db);
App::forgetInstance('translator');
App::setLocale($this->company->locale());
@@ -92,8 +91,9 @@ class QuoteExport 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());
@@ -101,58 +101,55 @@ class QuoteExport extends BaseExport
$query = Quote::query()
->with('client')
->where('company_id', $this->company->id)
- ->where('is_deleted',0);
+ ->where('is_deleted', 0);
$query = $this->addDateRange($query);
$query->cursor()
- ->each(function ($quote){
-
- $this->csv->insertOne($this->buildRow($quote));
-
- });
-
-
- return $this->csv->toString();
+ ->each(function ($quote) {
+ $this->csv->insertOne($this->buildRow($quote));
+ });
+ return $this->csv->toString();
}
private function buildRow(Quote $quote) :array
{
-
$transformed_quote = $this->quote_transformer->transform($quote);
$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_quote))
+ if (array_key_exists($key, $transformed_quote)) {
$entity[$keyval] = $transformed_quote[$key];
- else
+ } else {
$entity[$keyval] = '';
+ }
}
return $this->decorateAdvancedFields($quote, $entity);
-
}
private function decorateAdvancedFields(Quote $quote, array $entity) :array
{
- if(in_array('currency_id', $this->input['report_keys']))
+ if (in_array('currency_id', $this->input['report_keys'])) {
$entity['currency'] = $quote->client->currency()->code;
+ }
- if(in_array('client_id', $this->input['report_keys']))
+ if (in_array('client_id', $this->input['report_keys'])) {
$entity['client'] = $quote->client->present()->name();
+ }
- if(in_array('status_id',$this->input['report_keys']))
+ if (in_array('status_id', $this->input['report_keys'])) {
$entity['status'] = $quote->stringStatus($quote->status_id);
+ }
- if(in_array('invoice_id', $this->input['report_keys']))
- $entity['invoice'] = $quote->invoice ? $quote->invoice->number : "";
+ if (in_array('invoice_id', $this->input['report_keys'])) {
+ $entity['invoice'] = $quote->invoice ? $quote->invoice->number : '';
+ }
return $entity;
}
-
}
diff --git a/app/Export/CSV/QuoteItemExport.php b/app/Export/CSV/QuoteItemExport.php
index ad1ded90ca73..e89d56311601 100644
--- a/app/Export/CSV/QuoteItemExport.php
+++ b/app/Export/CSV/QuoteItemExport.php
@@ -85,7 +85,6 @@ class QuoteItemExport extends BaseExport
'custom_value4' => 'item.custom_value4',
];
-
private array $decorate_keys = [
'client',
'currency',
@@ -100,7 +99,6 @@ class QuoteItemExport extends BaseExport
public function run()
{
-
MultiDB::setDb($this->company->db);
App::forgetInstance('translator');
App::setLocale($this->company->locale());
@@ -110,28 +108,25 @@ class QuoteItemExport 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());
$query = Quote::query()
->with('client')->where('company_id', $this->company->id)
- ->where('is_deleted',0);
+ ->where('is_deleted', 0);
$query = $this->addDateRange($query);
$query->cursor()
- ->each(function ($quote){
-
+ ->each(function ($quote) {
$this->iterateItems($quote);
+ });
- });
-
- return $this->csv->toString();
-
+ return $this->csv->toString();
}
private function iterateItems(Quote $quote)
@@ -140,76 +135,68 @@ class QuoteItemExport extends BaseExport
$transformed_items = [];
- foreach($quote->line_items as $item)
- {
+ foreach ($quote->line_items as $item) {
$item_array = [];
- foreach(array_values($this->input['report_keys']) as $key){
-
- if(str_contains($key, "item.")){
-
- $key = str_replace("item.", "", $key);
+ foreach (array_values($this->input['report_keys']) as $key) {
+ if (str_contains($key, 'item.')) {
+ $key = str_replace('item.', '', $key);
$item_array[$key] = $item->{$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
- $entity[$keyval] = "";
+ } else {
+ $entity[$keyval] = '';
+ }
}
-
$transformed_items = array_merge($transformed_quote, $item_array);
$entity = $this->decorateAdvancedFields($quote, $transformed_items);
- $this->csv->insertOne($entity);
-
+ $this->csv->insertOne($entity);
}
-
}
private function buildRow(Quote $quote) :array
{
-
$transformed_quote = $this->quote_transformer->transform($quote);
$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_quote))
+ if (array_key_exists($key, $transformed_quote)) {
$entity[$keyval] = $transformed_quote[$key];
- else
- $entity[$keyval] = "";
-
+ } else {
+ $entity[$keyval] = '';
+ }
}
return $this->decorateAdvancedFields($quote, $entity);
-
}
private function decorateAdvancedFields(Quote $quote, array $entity) :array
{
- if(in_array('currency_id', $this->input['report_keys']))
+ if (in_array('currency_id', $this->input['report_keys'])) {
$entity['currency'] = $quote->client->currency() ? $quote->client->currency()->code : $quote->company->currency()->code;
+ }
- if(in_array('client_id', $this->input['report_keys']))
+ if (in_array('client_id', $this->input['report_keys'])) {
$entity['client'] = $quote->client->present()->name();
+ }
- if(in_array('status_id', $this->input['report_keys']))
+ if (in_array('status_id', $this->input['report_keys'])) {
$entity['status'] = $quote->stringStatus($quote->status_id);
+ }
return $entity;
}
-
}
diff --git a/app/Export/CSV/RecurringInvoiceExport.php b/app/Export/CSV/RecurringInvoiceExport.php
index 47232ebcfa12..30accbd22511 100644
--- a/app/Export/CSV/RecurringInvoiceExport.php
+++ b/app/Export/CSV/RecurringInvoiceExport.php
@@ -74,7 +74,7 @@ class RecurringInvoiceExport extends BaseExport
'currency',
'status',
'vendor',
- 'project'
+ 'project',
];
public function __construct(Company $company, array $input)
@@ -86,7 +86,6 @@ class RecurringInvoiceExport extends BaseExport
public function run()
{
-
MultiDB::setDb($this->company->db);
App::forgetInstance('translator');
App::setLocale($this->company->locale());
@@ -96,8 +95,9 @@ class RecurringInvoiceExport 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());
@@ -105,64 +105,63 @@ class RecurringInvoiceExport extends BaseExport
$query = RecurringInvoice::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){
-
- $this->csv->insertOne($this->buildRow($invoice));
-
- });
-
- return $this->csv->toString();
+ ->each(function ($invoice) {
+ $this->csv->insertOne($this->buildRow($invoice));
+ });
+ return $this->csv->toString();
}
private function buildRow(RecurringInvoice $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(RecurringInvoice $invoice, array $entity) :array
{
- if(in_array('country_id', $this->input['report_keys']))
- $entity['country'] = $invoice->client->country ? ctrans("texts.country_{$invoice->client->country->name}") : "";
+ if (in_array('country_id', $this->input['report_keys'])) {
+ $entity['country'] = $invoice->client->country ? ctrans("texts.country_{$invoice->client->country->name}") : '';
+ }
- 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']))
+ if (in_array('client_id', $this->input['report_keys'])) {
$entity['client'] = $invoice->client->present()->name();
+ }
- if(in_array('status_id',$this->input['report_keys']))
+ if (in_array('status_id', $this->input['report_keys'])) {
$entity['status'] = $invoice->stringStatus($invoice->status_id);
+ }
- if(in_array('project_id',$this->input['report_keys']))
- $entity['project'] = $invoice->project ? $invoice->project->name : "";
+ if (in_array('project_id', $this->input['report_keys'])) {
+ $entity['project'] = $invoice->project ? $invoice->project->name : '';
+ }
- if(in_array('vendor_id',$this->input['report_keys']))
- $entity['vendor'] = $invoice->vendor ? $invoice->vendor->name : "";
+ if (in_array('vendor_id', $this->input['report_keys'])) {
+ $entity['vendor'] = $invoice->vendor ? $invoice->vendor->name : '';
+ }
return $entity;
}
-
}
diff --git a/app/Export/CSV/TaskExport.php b/app/Export/CSV/TaskExport.php
index f700c8c83063..7ee9007f520c 100644
--- a/app/Export/CSV/TaskExport.php
+++ b/app/Export/CSV/TaskExport.php
@@ -71,7 +71,6 @@ class TaskExport extends BaseExport
public function run()
{
-
MultiDB::setDb($this->company->db);
App::forgetInstance('translator');
App::setLocale($this->company->locale());
@@ -79,15 +78,15 @@ class TaskExport extends BaseExport
$t->replace(Ninja::transformTranslations($this->company->settings));
$this->date_format = DateFormat::find($this->company->settings->date_format_id)->format;
-
+
//load the CSV document from a string
$this->csv = Writer::createFromString();
-
+
ksort($this->entity_keys);
- 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());
@@ -97,59 +96,50 @@ class TaskExport extends BaseExport
$query = $this->addDateRange($query);
$query->cursor()
- ->each(function ($entity){
-
- $this->buildRow($entity);
-
- });
-
- return $this->csv->toString();
+ ->each(function ($entity) {
+ $this->buildRow($entity);
+ });
+ return $this->csv->toString();
}
- private function buildRow(Task $task)
+ private function buildRow(Task $task)
{
-
$entity = [];
$transformed_entity = $this->entity_transformer->transform($task);
- if(is_null($task->time_log) || (is_array(json_decode($task->time_log,1)) && count(json_decode($task->time_log,1)) == 0)){
-
- foreach(array_values($this->input['report_keys']) as $key){
-
+ if (is_null($task->time_log) || (is_array(json_decode($task->time_log, 1)) && count(json_decode($task->time_log, 1)) == 0)) {
+ foreach (array_values($this->input['report_keys']) as $key) {
$keyval = array_search($key, $this->entity_keys);
- if(array_key_exists($key, $transformed_entity))
+ if (array_key_exists($key, $transformed_entity)) {
$entity[$keyval] = $transformed_entity[$key];
- else
- $entity[$keyval] = '';
+ } else {
+ $entity[$keyval] = '';
+ }
}
- $entity['start_date'] = "";
- $entity['end_date'] = "";
- $entity['duration'] = "";
+ $entity['start_date'] = '';
+ $entity['end_date'] = '';
+ $entity['duration'] = '';
$entity = $this->decorateAdvancedFields($task, $entity);
ksort($entity);
$this->csv->insertOne($entity);
-
- }
- elseif(is_array(json_decode($task->time_log,1)) && count(json_decode($task->time_log,1)) > 0) {
-
- foreach(array_values($this->input['report_keys']) as $key){
-
+ } elseif (is_array(json_decode($task->time_log, 1)) && count(json_decode($task->time_log, 1)) > 0) {
+ foreach (array_values($this->input['report_keys']) as $key) {
$keyval = array_search($key, $this->entity_keys);
- if(array_key_exists($key, $transformed_entity))
+ if (array_key_exists($key, $transformed_entity)) {
$entity[$keyval] = $transformed_entity[$key];
- else
- $entity[$keyval] = '';
+ } else {
+ $entity[$keyval] = '';
+ }
}
$this->iterateLogs($task, $entity);
}
-
}
private function iterateLogs(Task $task, array $entity)
@@ -157,48 +147,51 @@ class TaskExport extends BaseExport
$timezone = Timezone::find($task->company->settings->timezone_id);
$timezone_name = 'US/Eastern';
- if($timezone)
+ if ($timezone) {
$timezone_name = $timezone->name;
+ }
- $logs = json_decode($task->time_log,1);
-
- $date_format_default = "Y-m-d";
+ $logs = json_decode($task->time_log, 1);
+
+ $date_format_default = 'Y-m-d';
$date_format = DateFormat::find($task->company->settings->date_format_id);
- if($date_format)
+ if ($date_format) {
$date_format_default = $date_format->format;
+ }
- foreach($logs as $key => $item)
- {
-
- if(in_array("start_date", $this->input['report_keys'])){
+ foreach ($logs as $key => $item) {
+ if (in_array('start_date', $this->input['report_keys'])) {
$entity['start_date'] = Carbon::createFromTimeStamp($item[0])->setTimezone($timezone_name)->format($date_format_default);
}
- if(in_array("end_date", $this->input['report_keys']) && $item[1] > 0){
+ if (in_array('end_date', $this->input['report_keys']) && $item[1] > 0) {
$entity['end_date'] = Carbon::createFromTimeStamp($item[1])->setTimezone($timezone_name)->format($date_format_default);
}
- if(in_array("end_date", $this->input['report_keys']) && $item[1] == 0){
+ if (in_array('end_date', $this->input['report_keys']) && $item[1] == 0) {
$entity['end_date'] = ctrans('texts.is_running');
}
- if(in_array("duration", $this->input['report_keys'])){
+ if (in_array('duration', $this->input['report_keys'])) {
$entity['duration'] = $task->calcDuration();
}
- if(!array_key_exists('duration', $entity))
- $entity['duration'] = "";
+ if (! array_key_exists('duration', $entity)) {
+ $entity['duration'] = '';
+ }
- if(!array_key_exists('start_date', $entity))
- $entity['start_date'] = "";
+ if (! array_key_exists('start_date', $entity)) {
+ $entity['start_date'] = '';
+ }
- if(!array_key_exists('end_date', $entity))
- $entity['end_date'] = "";
+ if (! array_key_exists('end_date', $entity)) {
+ $entity['end_date'] = '';
+ }
$entity = $this->decorateAdvancedFields($task, $entity);
-
+
ksort($entity);
$this->csv->insertOne($entity);
@@ -206,25 +199,26 @@ class TaskExport extends BaseExport
unset($entity['end_date']);
unset($entity['duration']);
}
-
}
private function decorateAdvancedFields(Task $task, array $entity) :array
{
-
- if(in_array('status_id', $this->input['report_keys']))
+ if (in_array('status_id', $this->input['report_keys'])) {
$entity['status'] = $task->status()->exists() ? $task->status->name : '';
+ }
- if(in_array('project_id', $this->input['report_keys']))
+ if (in_array('project_id', $this->input['report_keys'])) {
$entity['project'] = $task->project()->exists() ? $task->project->name : '';
+ }
- if(in_array('client_id', $this->input['report_keys']))
- $entity['client'] = $task->client ? $task->client->present()->name() : "";
+ if (in_array('client_id', $this->input['report_keys'])) {
+ $entity['client'] = $task->client ? $task->client->present()->name() : '';
+ }
- if(in_array('invoice_id', $this->input['report_keys']))
- $entity['invoice'] = $task->invoice ? $task->invoice->number : "";
+ if (in_array('invoice_id', $this->input['report_keys'])) {
+ $entity['invoice'] = $task->invoice ? $task->invoice->number : '';
+ }
return $entity;
}
-
}
diff --git a/app/Factory/ClientGatewayTokenFactory.php b/app/Factory/ClientGatewayTokenFactory.php
index fa46b327b020..0b3196ef4b73 100644
--- a/app/Factory/ClientGatewayTokenFactory.php
+++ b/app/Factory/ClientGatewayTokenFactory.php
@@ -25,7 +25,7 @@ class ClientGatewayTokenFactory
$client_gateway_token->is_deleted = false;
$client_gateway_token->token = '';
$client_gateway_token->routing_number = '';
-
+
return $client_gateway_token;
}
}
diff --git a/app/Factory/CloneQuoteToInvoiceFactory.php b/app/Factory/CloneQuoteToInvoiceFactory.php
index 03d057987a99..9cb03ff22c83 100644
--- a/app/Factory/CloneQuoteToInvoiceFactory.php
+++ b/app/Factory/CloneQuoteToInvoiceFactory.php
@@ -28,11 +28,12 @@ class CloneQuoteToInvoiceFactory
unset($quote_array['invoice_id']);
unset($quote_array['id']);
unset($quote_array['invitations']);
-
+
//preserve terms if they exist on Quotes
//if(array_key_exists('terms', $quote_array) && strlen($quote_array['terms']) < 2)
- if(!$quote->company->use_quote_terms_on_conversion)
+ if (! $quote->company->use_quote_terms_on_conversion) {
unset($quote_array['terms']);
+ }
// unset($quote_array['public_notes']);
unset($quote_array['footer']);
diff --git a/app/Factory/CompanyFactory.php b/app/Factory/CompanyFactory.php
index d78508f9ffd0..89ad41118f03 100644
--- a/app/Factory/CompanyFactory.php
+++ b/app/Factory/CompanyFactory.php
@@ -37,12 +37,13 @@ class CompanyFactory
//$company->custom_fields = (object) ['invoice1' => '1', 'invoice2' => '2', 'client1'=>'3'];
$company->custom_fields = (object) [];
$company->client_registration_fields = ClientRegistrationFields::generate();
-
- if(Ninja::isHosted())
+
+ if (Ninja::isHosted()) {
$company->subdomain = MultiDB::randomSubdomainGenerator();
- else
+ } else {
$company->subdomain = '';
-
+ }
+
$company->enabled_modules = config('ninja.enabled_modules'); //32767;//8191; //4095
$company->default_password_timeout = 1800000;
$company->markdown_email_enabled = false;
diff --git a/app/Factory/CompanyGatewayFactory.php b/app/Factory/CompanyGatewayFactory.php
index d3030484d300..8f4743072cbe 100644
--- a/app/Factory/CompanyGatewayFactory.php
+++ b/app/Factory/CompanyGatewayFactory.php
@@ -24,7 +24,7 @@ class CompanyGatewayFactory
$company_gateway->require_billing_address = false;
$company_gateway->require_shipping_address = false;
$company_gateway->config = encrypt(json_encode(new \stdClass));
-
+
return $company_gateway;
}
}
diff --git a/app/Factory/ExpenseCategoryFactory.php b/app/Factory/ExpenseCategoryFactory.php
index 88a702ca5fcf..f39da086d2a8 100644
--- a/app/Factory/ExpenseCategoryFactory.php
+++ b/app/Factory/ExpenseCategoryFactory.php
@@ -23,7 +23,7 @@ class ExpenseCategoryFactory
$expense->name = '';
$expense->is_deleted = false;
$expense->color = '';
-
+
return $expense;
}
}
diff --git a/app/Factory/ExpenseFactory.php b/app/Factory/ExpenseFactory.php
index 997412ef1b5f..0ca0e0e1ba18 100644
--- a/app/Factory/ExpenseFactory.php
+++ b/app/Factory/ExpenseFactory.php
@@ -42,7 +42,7 @@ class ExpenseFactory
$expense->tax_amount1 = 0;
$expense->tax_amount2 = 0;
$expense->tax_amount3 = 0;
-
+
return $expense;
}
}
diff --git a/app/Factory/GroupSettingFactory.php b/app/Factory/GroupSettingFactory.php
index 88c1c6f615cb..acea47af60f9 100644
--- a/app/Factory/GroupSettingFactory.php
+++ b/app/Factory/GroupSettingFactory.php
@@ -18,8 +18,8 @@ class GroupSettingFactory
{
public static function create(int $company_id, int $user_id) :GroupSetting
{
- $settings = new \stdClass;
- $settings->entity = Client::class;
+ $settings = new \stdClass;
+ $settings->entity = Client::class;
$gs = new GroupSetting;
$gs->name = '';
diff --git a/app/Factory/InvoiceFactory.php b/app/Factory/InvoiceFactory.php
index 934fffb1583e..d400fd91da67 100644
--- a/app/Factory/InvoiceFactory.php
+++ b/app/Factory/InvoiceFactory.php
@@ -49,7 +49,7 @@ class InvoiceFactory
$invoice->user_id = $user_id;
$invoice->company_id = $company_id;
$invoice->recurring_id = null;
-
+
return $invoice;
}
}
diff --git a/app/Factory/InvoiceItemFactory.php b/app/Factory/InvoiceItemFactory.php
index 713035dce9e6..d88674f19adc 100644
--- a/app/Factory/InvoiceItemFactory.php
+++ b/app/Factory/InvoiceItemFactory.php
@@ -40,7 +40,7 @@ class InvoiceItemFactory
$item->custom_value2 = '';
$item->custom_value3 = '';
$item->custom_value4 = '';
- $item->type_id = "1";
+ $item->type_id = '1';
return $item;
}
@@ -71,7 +71,7 @@ class InvoiceItemFactory
// $item->custom_value4 = $faker->realText(10);
$item->tax_name1 = 'GST';
$item->tax_rate1 = 10.00;
- $item->type_id = "1";
+ $item->type_id = '1';
$data[] = $item;
}
@@ -105,7 +105,7 @@ class InvoiceItemFactory
// $item->custom_value4 = $faker->realText(10);
$item->tax_name1 = '';
$item->tax_rate1 = 0;
- $item->type_id = "1";
+ $item->type_id = '1';
$data[] = $item;
}
diff --git a/app/Factory/ProjectFactory.php b/app/Factory/ProjectFactory.php
index 77f9c7b8c81e..68cb9b04a88e 100644
--- a/app/Factory/ProjectFactory.php
+++ b/app/Factory/ProjectFactory.php
@@ -31,7 +31,7 @@ class ProjectFactory
$project->custom_value3 = '';
$project->custom_value4 = '';
$project->is_deleted = 0;
-
+
return $project;
}
}
diff --git a/app/Factory/PurchaseOrderInvitationFactory.php b/app/Factory/PurchaseOrderInvitationFactory.php
index ee3987ea7e39..8d354d244c8e 100644
--- a/app/Factory/PurchaseOrderInvitationFactory.php
+++ b/app/Factory/PurchaseOrderInvitationFactory.php
@@ -1,6 +1,5 @@
custom_value4 = '';
$recurring_expense->uses_inclusive_taxes = true;
$recurring_expense->calculate_tax_by_amount = true;
-
+
return $recurring_expense;
}
}
diff --git a/app/Factory/RecurringExpenseToExpenseFactory.php b/app/Factory/RecurringExpenseToExpenseFactory.php
index 503a167a2cf3..1f44a75d5a77 100644
--- a/app/Factory/RecurringExpenseToExpenseFactory.php
+++ b/app/Factory/RecurringExpenseToExpenseFactory.php
@@ -65,27 +65,25 @@ class RecurringExpenseToExpenseFactory
$expense->tax_amount3 = $recurring_expense->tax_amount3 ?: 0;
$expense->uses_inclusive_taxes = $recurring_expense->uses_inclusive_taxes;
$expense->calculate_tax_by_amount = $recurring_expense->calculate_tax_by_amount;
-
+
return $expense;
}
public static function transformObject(?string $value, $recurring_expense): ?string
{
- if(!$value)
+ if (! $value) {
return '';
-
- if($recurring_expense->client){
-
+ }
+
+ if ($recurring_expense->client) {
$locale = $recurring_expense->client->locale();
$date_format = $recurring_expense->client->date_format();
-
- }
- else {
+ } else {
$locale = $recurring_expense->company->locale();
$date_formats = Cache::get('date_formats');
- $date_format = $date_formats->filter(function ($item) use($recurring_expense){
+ $date_format = $date_formats->filter(function ($item) use ($recurring_expense) {
return $item->id == $recurring_expense->company->settings->date_format_id;
})->first()->format;
}
@@ -96,7 +94,7 @@ class RecurringExpenseToExpenseFactory
'literal' => [
':MONTH' => Carbon::createFromDate(now()->year, now()->month)->translatedFormat('F'),
':YEAR' => now()->year,
- ':QUARTER' => 'Q' . now()->quarter,
+ ':QUARTER' => 'Q'.now()->quarter,
':WEEK_BEFORE' => \sprintf(
'%s %s %s',
Carbon::now()->subDays(7)->translatedFormat($date_format),
@@ -110,9 +108,9 @@ class RecurringExpenseToExpenseFactory
Carbon::now()->addDays(14)->translatedFormat($date_format)
),
':WEEK' => \sprintf(
- '%s %s %s',
- Carbon::now()->translatedFormat($date_format),
- ctrans('texts.to'),
+ '%s %s %s',
+ Carbon::now()->translatedFormat($date_format),
+ ctrans('texts.to'),
Carbon::now()->addDays(7)->translatedFormat($date_format)
),
],
@@ -122,7 +120,7 @@ class RecurringExpenseToExpenseFactory
':QUARTER' => now()->quarter,
],
'ranges' => [
- 'MONTHYEAR' => Carbon::createFromDate(now()->year, now()->month),
+ 'MONTHYEAR' => Carbon::createFromDate(now()->year, now()->month),
],
'ranges_raw' => [
'MONTH' => now()->month,
@@ -136,7 +134,7 @@ class RecurringExpenseToExpenseFactory
$matches = array_shift($ranges);
foreach ($matches as $match) {
- if (!Str::contains($match, '|')) {
+ if (! Str::contains($match, '|')) {
continue;
}
@@ -147,7 +145,7 @@ class RecurringExpenseToExpenseFactory
$right = substr($parts[1], 0, -1); // MONTH+2
// If left side is not part of replacements, skip.
- if (!array_key_exists($left, $replacements['ranges'])) {
+ if (! array_key_exists($left, $replacements['ranges'])) {
continue;
}
@@ -155,7 +153,7 @@ class RecurringExpenseToExpenseFactory
$_right = '';
// If right side doesn't have any calculations, replace with raw ranges keyword.
- if (!Str::contains($right, ['-', '+', '/', '*'])) {
+ if (! Str::contains($right, ['-', '+', '/', '*'])) {
$_right = Carbon::createFromDate(now()->year, now()->month)->translatedFormat('F Y');
}
@@ -178,7 +176,6 @@ class RecurringExpenseToExpenseFactory
}
}
-
// Second case with more common calculations.
preg_match_all('/:([^:\s]+)/', $value, $common);
@@ -193,7 +190,7 @@ class RecurringExpenseToExpenseFactory
continue;
}
- if (!Str::contains($match, ['-', '+', '/', '*'])) {
+ if (! Str::contains($match, ['-', '+', '/', '*'])) {
$value = preg_replace(
sprintf('/%s/', $matches->keys()->first()), $replacements['literal'][$matches->keys()->first()], $value, 1
);
@@ -208,26 +205,26 @@ class RecurringExpenseToExpenseFactory
$raw = strtr($matches->keys()->first(), $replacements['raw']); // :MONTH => 1
- $number = $res = preg_replace("/[^0-9]/", '', $_value[1]); // :MONTH+1. || :MONTH+2! => 1 || 2
+ $number = $res = preg_replace('/[^0-9]/', '', $_value[1]); // :MONTH+1. || :MONTH+2! => 1 || 2
$target = "/{$matches->keys()->first()}\\{$_operation}{$number}/"; // /:$KEYWORD\\$OPERATION$VALUE => /:MONTH\\+1
- $output = (int) $raw + (int)$_value[1];
+ $output = (int) $raw + (int) $_value[1];
if ($operation == '+') {
- $output = (int) $raw + (int)$_value[1]; // 1 (:MONTH) + 4
+ $output = (int) $raw + (int) $_value[1]; // 1 (:MONTH) + 4
}
if ($_operation == '-') {
- $output = (int)$raw - (int)$_value[1]; // 1 (:MONTH) - 4
+ $output = (int) $raw - (int) $_value[1]; // 1 (:MONTH) - 4
}
- if ($_operation == '/' && (int)$_value[1] != 0) {
- $output = (int)$raw / (int)$_value[1]; // 1 (:MONTH) / 4
+ if ($_operation == '/' && (int) $_value[1] != 0) {
+ $output = (int) $raw / (int) $_value[1]; // 1 (:MONTH) / 4
}
if ($_operation == '*') {
- $output = (int)$raw * (int)$_value[1]; // 1 (:MONTH) * 4
+ $output = (int) $raw * (int) $_value[1]; // 1 (:MONTH) * 4
}
if ($matches->keys()->first() == ':MONTH') {
@@ -242,5 +239,4 @@ class RecurringExpenseToExpenseFactory
return $value;
}
-
}
diff --git a/app/Factory/RecurringInvoiceToInvoiceFactory.php b/app/Factory/RecurringInvoiceToInvoiceFactory.php
index a4b428d230ea..a1101972dd6b 100644
--- a/app/Factory/RecurringInvoiceToInvoiceFactory.php
+++ b/app/Factory/RecurringInvoiceToInvoiceFactory.php
@@ -67,24 +67,21 @@ class RecurringInvoiceToInvoiceFactory
$invoice->auto_bill_enabled = $recurring_invoice->auto_bill_enabled;
$invoice->paid_to_date = 0;
$invoice->design_id = $recurring_invoice->design_id;
-
+
return $invoice;
}
private static function transformItems($recurring_invoice, $client)
{
-
$line_items = $recurring_invoice->line_items;
- foreach($line_items as $key => $item){
-
- if(property_exists($line_items[$key], 'notes'))
+ foreach ($line_items as $key => $item) {
+ if (property_exists($line_items[$key], 'notes')) {
$line_items[$key]->notes = Helpers::processReservedKeywords($item->notes, $client);
-
+ }
}
return $line_items;
-
}
private static function tranformObject($object, $client)
diff --git a/app/Factory/RecurringQuoteToQuoteFactory.php b/app/Factory/RecurringQuoteToQuoteFactory.php
index b23e2567b93e..f5e0f765db44 100644
--- a/app/Factory/RecurringQuoteToQuoteFactory.php
+++ b/app/Factory/RecurringQuoteToQuoteFactory.php
@@ -54,7 +54,7 @@ class RecurringQuoteToQuoteFactory
$quote->auto_bill_enabled = $recurring_quote->auto_bill_enabled;
$quote->paid_to_date = 0;
$quote->design_id = $recurring_quote->design_id;
-
+
return $quote;
}
}
diff --git a/app/Factory/TaskStatusFactory.php b/app/Factory/TaskStatusFactory.php
index a59d2e9247ff..4f98d76e14f0 100644
--- a/app/Factory/TaskStatusFactory.php
+++ b/app/Factory/TaskStatusFactory.php
@@ -23,7 +23,7 @@ class TaskStatusFactory
$task_status->name = '';
$task_status->color = '';
$task_status->status_order = 9999;
-
+
return $task_status;
}
}
diff --git a/app/Factory/UserFactory.php b/app/Factory/UserFactory.php
index baba2fff2588..9ea2ce21c7b1 100644
--- a/app/Factory/UserFactory.php
+++ b/app/Factory/UserFactory.php
@@ -28,7 +28,7 @@ class UserFactory
$user->failed_logins = 0;
$user->signature = '';
$user->theme_id = 0;
-
+
return $user;
}
}
diff --git a/app/Factory/WebhookFactory.php b/app/Factory/WebhookFactory.php
index a9e8ce04d0f8..4d61c00f3d8e 100644
--- a/app/Factory/WebhookFactory.php
+++ b/app/Factory/WebhookFactory.php
@@ -25,7 +25,7 @@ class WebhookFactory
$webhook->format = 'JSON';
$webhook->rest_method = 'post';
$webhook->headers = [];
-
+
return $webhook;
}
}
diff --git a/app/Filters/ClientFilters.php b/app/Filters/ClientFilters.php
index a373038667ec..d7b63d7d74a5 100644
--- a/app/Filters/ClientFilters.php
+++ b/app/Filters/ClientFilters.php
@@ -22,7 +22,6 @@ use Illuminate\Support\Facades\Gate;
*/
class ClientFilters extends QueryFilters
{
-
/**
* Filter by name.
*
@@ -57,8 +56,9 @@ class ClientFilters extends QueryFilters
{
$parts = explode(':', $balance);
- if(!is_array($parts))
+ if (! is_array($parts)) {
return $this->builder;
+ }
return $this->builder->whereBetween('balance', [$parts[0], $parts[1]]);
}
@@ -70,7 +70,6 @@ class ClientFilters extends QueryFilters
$this->builder->whereHas('contacts', function ($query) use ($email) {
$query->where('email', $email);
});
-
}
public function client_id(string $client_id = '') :Builder
@@ -80,7 +79,6 @@ class ClientFilters extends QueryFilters
}
return $this->builder->where('id', $this->decodePrimaryKey($client_id));
-
}
public function id_number(string $id_number = ''):Builder
@@ -109,10 +107,10 @@ class ClientFilters extends QueryFilters
return $this->builder->where(function ($query) use ($filter) {
$query->where('clients.name', 'like', '%'.$filter.'%')
->orWhere('clients.id_number', 'like', '%'.$filter.'%')
- ->orWhereHas('contacts', function ($query) use($filter){
- $query->where('first_name', 'like', '%'.$filter.'%');
- $query->orWhere('last_name', 'like', '%'.$filter.'%');
- $query->orWhere('email', 'like', '%'.$filter.'%');
+ ->orWhereHas('contacts', function ($query) use ($filter) {
+ $query->where('first_name', 'like', '%'.$filter.'%');
+ $query->orWhere('last_name', 'like', '%'.$filter.'%');
+ $query->orWhere('email', 'like', '%'.$filter.'%');
})
->orWhere('clients.custom_value1', 'like', '%'.$filter.'%')
->orWhere('clients.custom_value2', 'like', '%'.$filter.'%')
diff --git a/app/Filters/CompanyGatewayFilters.php b/app/Filters/CompanyGatewayFilters.php
index 7bff1b2a3144..ef2d6594da87 100644
--- a/app/Filters/CompanyGatewayFilters.php
+++ b/app/Filters/CompanyGatewayFilters.php
@@ -35,7 +35,6 @@ class CompanyGatewayFilters extends QueryFilters
return $this->builder->where(function ($query) use ($filter) {
$query->where('company_gateways.label', 'like', '%'.$filter.'%');
});
-
}
/**
diff --git a/app/Filters/DocumentFilters.php b/app/Filters/DocumentFilters.php
index 195d6a18ffed..fade4950705a 100644
--- a/app/Filters/DocumentFilters.php
+++ b/app/Filters/DocumentFilters.php
@@ -19,7 +19,6 @@ use Illuminate\Database\Eloquent\Builder;
*/
class DocumentFilters extends QueryFilters
{
-
/**
* Filter based on search text.
*
@@ -39,9 +38,7 @@ class DocumentFilters extends QueryFilters
/* If client ID passed to this entity, simply return */
public function client_id(string $client_id = '') :Builder
{
-
return $this->builder;
-
}
/**
diff --git a/app/Filters/ExpenseFilters.php b/app/Filters/ExpenseFilters.php
index c0c3ef362185..174acff790af 100644
--- a/app/Filters/ExpenseFilters.php
+++ b/app/Filters/ExpenseFilters.php
@@ -93,8 +93,9 @@ class ExpenseFilters extends QueryFilters
{
$sort_col = explode('|', $sort);
- if(is_array($sort_col) && in_array($sort_col[1], ['asc', 'desc']) && in_array($sort_col[0], ['public_notes', 'date', 'id_number', 'custom_value1', 'custom_value2', 'custom_value3', 'custom_value4']))
+ if (is_array($sort_col) && in_array($sort_col[1], ['asc', 'desc']) && in_array($sort_col[0], ['public_notes', 'date', 'id_number', 'custom_value1', 'custom_value2', 'custom_value3', 'custom_value4'])) {
return $this->builder->orderBy($sort_col[0], $sort_col[1]);
+ }
return $this->builder;
}
diff --git a/app/Filters/InvoiceFilters.php b/app/Filters/InvoiceFilters.php
index b10fbc1fd02d..00fd9075576c 100644
--- a/app/Filters/InvoiceFilters.php
+++ b/app/Filters/InvoiceFilters.php
@@ -23,6 +23,7 @@ use Illuminate\Support\Carbon;
class InvoiceFilters extends QueryFilters
{
use MakesHash;
+
/**
* Filter based on client status.
*
@@ -98,7 +99,6 @@ class InvoiceFilters extends QueryFilters
});
}
-
/**
* Filters the list based on the status
* archived, active, deleted - legacy from V1.
@@ -153,7 +153,7 @@ class InvoiceFilters extends QueryFilters
$this->builder->whereIn('status_id', [Invoice::STATUS_SENT, Invoice::STATUS_PARTIAL])
->where('is_deleted', 0)
->where(function ($query) {
- $query->where('due_date', '<', now())
+ $query->where('due_date', '<', now())
->orWhere('partial_due_date', '<', now());
})
->orderBy('due_date', 'ASC');
@@ -182,8 +182,9 @@ class InvoiceFilters extends QueryFilters
$sort_col = explode('|', $sort);
//catch invalid explode array count
- if(count($sort_col) == 1)
+ if (count($sort_col) == 1) {
return $this->builder;
+ }
return $this->builder->orderBy($sort_col[0], $sort_col[1]);
}
diff --git a/app/Filters/PaymentFilters.php b/app/Filters/PaymentFilters.php
index 8667583c59a8..823cb9fcf741 100644
--- a/app/Filters/PaymentFilters.php
+++ b/app/Filters/PaymentFilters.php
@@ -94,7 +94,6 @@ class PaymentFilters extends QueryFilters
return $this->builder->orderBy($sort_col[0], $sort_col[1]);
}
-
public function number(string $number) : Builder
{
return $this->builder->where('number', $number);
diff --git a/app/Filters/ProjectFilters.php b/app/Filters/ProjectFilters.php
index 8c17b6c3a836..f6202c25ee60 100644
--- a/app/Filters/ProjectFilters.php
+++ b/app/Filters/ProjectFilters.php
@@ -141,6 +141,5 @@ class ProjectFilters extends QueryFilters
//return $this->builder->whereCompanyId(auth()->user()->company()->id);
// return $this->builder->whereCompanyId(auth()->user()->company()->id)->orWhere('company_id', null);
return $this->builder->company();
-
}
}
diff --git a/app/Filters/PurchaseOrderFilters.php b/app/Filters/PurchaseOrderFilters.php
index 38be4155d694..3aa91958ef36 100644
--- a/app/Filters/PurchaseOrderFilters.php
+++ b/app/Filters/PurchaseOrderFilters.php
@@ -11,8 +11,6 @@
namespace App\Filters;
-
-
use App\Models\PurchaseOrder;
use App\Models\User;
use Illuminate\Database\Eloquent\Builder;
@@ -157,7 +155,6 @@ class PurchaseOrderFilters extends QueryFilters
*
* We need to ensure we are using the correct company ID
* as we could be hitting this from either the client or company auth guard
- *
*/
public function entityFilter()
{
diff --git a/app/Filters/QueryFilters.php b/app/Filters/QueryFilters.php
index d16619ce85a0..370ae558e09e 100644
--- a/app/Filters/QueryFilters.php
+++ b/app/Filters/QueryFilters.php
@@ -22,7 +22,7 @@ use Illuminate\Http\Request;
abstract class QueryFilters
{
use MakesHash;
-
+
/**
* active status.
*/
@@ -168,7 +168,7 @@ abstract class QueryFilters
public function created_at($value)
{
- $created_at = $value ? (int)$value : 0;
+ $created_at = $value ? (int) $value : 0;
$created_at = date('Y-m-d H:i:s', $value);
@@ -177,11 +177,11 @@ abstract class QueryFilters
public function is_deleted($value)
{
- if($value == 'true')
+ if ($value == 'true') {
return $this->builder->where('is_deleted', $value)->withTrashed();
+ }
return $this->builder->where('is_deleted', $value);
-
}
public function client_id(string $client_id = '') :Builder
@@ -191,20 +191,14 @@ abstract class QueryFilters
}
return $this->builder->where('client_id', $this->decodePrimaryKey($client_id));
-
}
public function filter_deleted_clients($value)
{
-
- if($value == 'true'){
-
+ if ($value == 'true') {
return $this->builder->whereHas('client', function (Builder $query) {
-
- $query->where('is_deleted', 0);
-
+ $query->where('is_deleted', 0);
});
-
}
return $this->builder;
@@ -212,11 +206,8 @@ abstract class QueryFilters
public function with_trashed($value)
{
-
- if($value == 'false'){
-
+ if ($value == 'false') {
return $this->builder->where('is_deleted', 0);
-
}
// if($value == 'true'){
@@ -226,6 +217,5 @@ abstract class QueryFilters
// }
return $this->builder;
-
}
}
diff --git a/app/Filters/TaskStatusFilters.php b/app/Filters/TaskStatusFilters.php
index d77f353be677..67886d83aad4 100644
--- a/app/Filters/TaskStatusFilters.php
+++ b/app/Filters/TaskStatusFilters.php
@@ -35,7 +35,6 @@ class TaskStatusFilters extends QueryFilters
return $this->builder->where(function ($query) use ($filter) {
$query->where('task_statuses.name', 'like', '%'.$filter.'%');
});
-
}
/**
diff --git a/app/Filters/TaxRateFilters.php b/app/Filters/TaxRateFilters.php
index 31d21084f726..ab8bdbfc79b9 100644
--- a/app/Filters/TaxRateFilters.php
+++ b/app/Filters/TaxRateFilters.php
@@ -35,7 +35,6 @@ class TaxRateFilters extends QueryFilters
return $this->builder->where(function ($query) use ($filter) {
$query->where('tax_rates.name', 'like', '%'.$filter.'%');
});
-
}
/**
diff --git a/app/Filters/VendorFilters.php b/app/Filters/VendorFilters.php
index 2e8daa253969..dd2c7e885824 100644
--- a/app/Filters/VendorFilters.php
+++ b/app/Filters/VendorFilters.php
@@ -38,7 +38,7 @@ class VendorFilters extends QueryFilters
return $this->builder->where(function ($query) use ($filter) {
$query->where('vendors.name', 'like', '%'.$filter.'%')
->orWhere('vendors.id_number', 'like', '%'.$filter.'%')
- ->orWhereHas('contacts', function ($query) use($filter){
+ ->orWhereHas('contacts', function ($query) use ($filter) {
$query->where('vendor_contacts.first_name', 'like', '%'.$filter.'%');
$query->orWhere('vendor_contacts.last_name', 'like', '%'.$filter.'%');
$query->orWhere('vendor_contacts.email', 'like', '%'.$filter.'%');
diff --git a/app/Helpers/Document/WithTypeHelpers.php b/app/Helpers/Document/WithTypeHelpers.php
index 45984e12d6d1..eb43316f68c8 100644
--- a/app/Helpers/Document/WithTypeHelpers.php
+++ b/app/Helpers/Document/WithTypeHelpers.php
@@ -16,8 +16,8 @@ trait WithTypeHelpers
{
/**
* Returns boolean based on checks for image.
- *
- * @return bool
+ *
+ * @return bool
*/
public function isImage(): bool
{
diff --git a/app/Helpers/Generic.php b/app/Helpers/Generic.php
index 87cbb4a3c803..0faa97726569 100644
--- a/app/Helpers/Generic.php
+++ b/app/Helpers/Generic.php
@@ -22,28 +22,25 @@ use App\Utils\Ninja;
*/
function nlog($output, $context = []): void
{
-
- if (!config('ninja.expanded_logging'))
+ if (! config('ninja.expanded_logging')) {
return;
+ }
- if (gettype($output) == 'object') {
- $output = print_r($output, 1);
+ if (gettype($output) == 'object') {
+ $output = print_r($output, 1);
+ }
+
+ $trace = debug_backtrace();
+ //nlog( debug_backtrace()[1]['function']);
+ // \Illuminate\Support\Facades\Log::channel('invoiceninja')->info(print_r($trace[1]['class'],1), []);
+ if (Ninja::isHosted()) {
+ try {
+ info($output);
+ } catch (\Exception $e) {
}
-
- $trace = debug_backtrace();
- //nlog( debug_backtrace()[1]['function']);
- // \Illuminate\Support\Facades\Log::channel('invoiceninja')->info(print_r($trace[1]['class'],1), []);
- if(Ninja::isHosted()) {
- try{
- info($output);
- }
- catch(\Exception $e){
-
- }
- }
- else
- \Illuminate\Support\Facades\Log::channel('invoiceninja')->info($output, $context);
-
+ } else {
+ \Illuminate\Support\Facades\Log::channel('invoiceninja')->info($output, $context);
+ }
}
// if (!function_exists('ray')) {
@@ -52,4 +49,3 @@ function nlog($output, $context = []): void
// return true;
// }
// }
-
diff --git a/app/Helpers/Invoice/CustomValuer.php b/app/Helpers/Invoice/CustomValuer.php
index b4df53a725ee..378e418ceb3f 100644
--- a/app/Helpers/Invoice/CustomValuer.php
+++ b/app/Helpers/Invoice/CustomValuer.php
@@ -27,7 +27,6 @@ trait CustomValuer
public function valuerTax($custom_value, $has_custom_invoice_taxes)
{
-
if (isset($custom_value) && is_numeric($custom_value) && $has_custom_invoice_taxes) {
return round($custom_value * ($this->invoice->tax_rate1 / 100), 2) + round($custom_value * ($this->invoice->tax_rate2 / 100), 2) + round($custom_value * ($this->invoice->tax_rate3 / 100), 2);
}
diff --git a/app/Helpers/Invoice/InvoiceItemSum.php b/app/Helpers/Invoice/InvoiceItemSum.php
index ba6e378a9ea2..8e3b702d7f6f 100644
--- a/app/Helpers/Invoice/InvoiceItemSum.php
+++ b/app/Helpers/Invoice/InvoiceItemSum.php
@@ -52,10 +52,11 @@ class InvoiceItemSum
$this->invoice = $invoice;
- if($this->invoice->client)
+ if ($this->invoice->client) {
$this->currency = $this->invoice->client->currency();
- else
+ } else {
$this->currency = $this->invoice->vendor->currency();
+ }
$this->line_items = [];
}
@@ -98,7 +99,7 @@ class InvoiceItemSum
}
private function sumLineItem()
- {
+ {
$this->setLineTotal($this->item->cost * $this->item->quantity);
return $this;
@@ -134,23 +135,26 @@ class InvoiceItemSum
$item_tax += $item_tax_rate1_total;
- // if($item_tax_rate1_total != 0)
- if (strlen($this->item->tax_name1) > 1)
- $this->groupTax($this->item->tax_name1, $this->item->tax_rate1, $item_tax_rate1_total);
-
+ // if($item_tax_rate1_total != 0)
+ if (strlen($this->item->tax_name1) > 1) {
+ $this->groupTax($this->item->tax_name1, $this->item->tax_rate1, $item_tax_rate1_total);
+ }
+
$item_tax_rate2_total = $this->calcAmountLineTax($this->item->tax_rate2, $amount);
$item_tax += $item_tax_rate2_total;
- if (strlen($this->item->tax_name2) > 1)
+ if (strlen($this->item->tax_name2) > 1) {
$this->groupTax($this->item->tax_name2, $this->item->tax_rate2, $item_tax_rate2_total);
-
+ }
+
$item_tax_rate3_total = $this->calcAmountLineTax($this->item->tax_rate3, $amount);
$item_tax += $item_tax_rate3_total;
- if (strlen($this->item->tax_name3) > 1)
+ if (strlen($this->item->tax_name3) > 1) {
$this->groupTax($this->item->tax_name3, $this->item->tax_rate3, $item_tax_rate3_total);
+ }
$this->setTotalTaxes($this->formatValue($item_tax, $this->currency->precision));
@@ -280,7 +284,6 @@ class InvoiceItemSum
if ($item_tax_rate3_total != 0) {
$this->groupTax($this->item->tax_name3, $this->item->tax_rate3, $item_tax_rate3_total);
}
-
}
$this->setTotalTaxes($item_tax);
diff --git a/app/Helpers/Invoice/InvoiceItemSumInclusive.php b/app/Helpers/Invoice/InvoiceItemSumInclusive.php
index 0b5628229353..213600d3501f 100644
--- a/app/Helpers/Invoice/InvoiceItemSumInclusive.php
+++ b/app/Helpers/Invoice/InvoiceItemSumInclusive.php
@@ -46,10 +46,11 @@ class InvoiceItemSumInclusive
$this->invoice = $invoice;
- if($this->invoice->client)
+ if ($this->invoice->client) {
$this->currency = $this->invoice->client->currency();
- else
+ } else {
$this->currency = $this->invoice->vendor->currency();
+ }
$this->line_items = [];
}
@@ -122,24 +123,26 @@ class InvoiceItemSumInclusive
$item_tax += $this->formatValue($item_tax_rate1_total, $this->currency->precision);
- // if($item_tax_rate1_total != 0)
- if (strlen($this->item->tax_name1) > 1)
- $this->groupTax($this->item->tax_name1, $this->item->tax_rate1, $item_tax_rate1_total);
+ // if($item_tax_rate1_total != 0)
+ if (strlen($this->item->tax_name1) > 1) {
+ $this->groupTax($this->item->tax_name1, $this->item->tax_rate1, $item_tax_rate1_total);
+ }
$item_tax_rate2_total = $this->calcInclusiveLineTax($this->item->tax_rate2, $amount);
$item_tax += $this->formatValue($item_tax_rate2_total, $this->currency->precision);
- if (strlen($this->item->tax_name2) > 1)
+ if (strlen($this->item->tax_name2) > 1) {
$this->groupTax($this->item->tax_name2, $this->item->tax_rate2, $item_tax_rate2_total);
-
+ }
+
$item_tax_rate3_total = $this->calcInclusiveLineTax($this->item->tax_rate3, $amount);
$item_tax += $this->formatValue($item_tax_rate3_total, $this->currency->precision);
- if (strlen($this->item->tax_name3) > 1)
+ if (strlen($this->item->tax_name3) > 1) {
$this->groupTax($this->item->tax_name3, $this->item->tax_rate3, $item_tax_rate3_total);
-
+ }
$this->setTotalTaxes($this->formatValue($item_tax, $this->currency->precision));
@@ -239,12 +242,12 @@ class InvoiceItemSumInclusive
$item_tax = 0;
foreach ($this->line_items as $this->item) {
-
- if($this->sub_total == 0)
+ if ($this->sub_total == 0) {
$amount = $this->item->line_total;
- else
+ } else {
$amount = $this->item->line_total - ($this->item->line_total * ($this->invoice->discount / $this->sub_total));
-
+ }
+
$item_tax_rate1_total = $this->calcInclusiveLineTax($this->item->tax_rate1, $amount);
$item_tax += $item_tax_rate1_total;
diff --git a/app/Helpers/Invoice/InvoiceSum.php b/app/Helpers/Invoice/InvoiceSum.php
index 3436610548f0..f0df4a66c9ec 100644
--- a/app/Helpers/Invoice/InvoiceSum.php
+++ b/app/Helpers/Invoice/InvoiceSum.php
@@ -55,10 +55,11 @@ class InvoiceSum
{
$this->invoice = $invoice;
- if($this->invoice->client)
+ if ($this->invoice->client) {
$this->precision = $this->invoice->client->currency()->precision;
- else
+ } else {
$this->precision = $this->invoice->vendor->currency()->precision;
+ }
$this->tax_map = new Collection;
}
@@ -85,7 +86,7 @@ class InvoiceSum
$this->total = $this->invoice_items->getSubTotal();
$this->setSubTotal($this->invoice_items->getSubTotal());
$this->setGrossSubTotal($this->invoice_items->getGrossSubTotal());
-
+
return $this;
}
@@ -120,7 +121,6 @@ class InvoiceSum
private function calculateInvoiceTaxes()
{
-
if (strlen($this->invoice->tax_name1) > 1) {
$tax = $this->taxer($this->total, $this->invoice->tax_rate1);
$tax += $this->getSurchargeTaxTotalForKey($this->invoice->tax_name1, $this->invoice->tax_rate1);
@@ -144,7 +144,7 @@ class InvoiceSum
$this->total_taxes += $tax;
$this->total_tax_map[] = ['name' => $this->invoice->tax_name3.' '.floatval($this->invoice->tax_rate3).'%', 'total' => $tax];
}
-
+
return $this;
}
@@ -200,6 +200,7 @@ class InvoiceSum
public function getTempEntity()
{
$this->setCalculatedAttributes();
+
return $this->invoice;
}
@@ -349,37 +350,29 @@ class InvoiceSum
private function getSurchargeTaxTotalForKey($key, $rate)
{
-
$tax_component = 0;
- if($this->invoice->custom_surcharge_tax1)
- {
+ if ($this->invoice->custom_surcharge_tax1) {
$tax_component += round($this->invoice->custom_surcharge1 * ($rate / 100), 2);
}
- if($this->invoice->custom_surcharge_tax2)
- {
+ if ($this->invoice->custom_surcharge_tax2) {
$tax_component += round($this->invoice->custom_surcharge2 * ($rate / 100), 2);
}
- if($this->invoice->custom_surcharge_tax3)
- {
+ if ($this->invoice->custom_surcharge_tax3) {
$tax_component += round($this->invoice->custom_surcharge3 * ($rate / 100), 2);
}
- if($this->invoice->custom_surcharge_tax4)
- {
+ if ($this->invoice->custom_surcharge_tax4) {
$tax_component += round($this->invoice->custom_surcharge4 * ($rate / 100), 2);
}
-
+
return $tax_component;
-
}
-
-
public function getTaxMap()
- {
+ {
return $this->tax_map;
}
diff --git a/app/Helpers/Invoice/InvoiceSumInclusive.php b/app/Helpers/Invoice/InvoiceSumInclusive.php
index 5e09187303cc..ad38f2754691 100644
--- a/app/Helpers/Invoice/InvoiceSumInclusive.php
+++ b/app/Helpers/Invoice/InvoiceSumInclusive.php
@@ -42,6 +42,7 @@ class InvoiceSumInclusive
private $sub_total;
private $precision;
+
/**
* Constructs the object with Invoice and Settings object.
*
@@ -51,10 +52,11 @@ class InvoiceSumInclusive
{
$this->invoice = $invoice;
- if($this->invoice->client)
+ if ($this->invoice->client) {
$this->precision = $this->invoice->client->currency()->precision;
- else
+ } else {
$this->precision = $this->invoice->vendor->currency()->precision;
+ }
$this->tax_map = new Collection;
}
@@ -170,7 +172,6 @@ class InvoiceSumInclusive
private function calculateTotals()
{
-
return $this;
}
@@ -188,6 +189,7 @@ class InvoiceSumInclusive
public function getTempEntity()
{
$this->setCalculatedAttributes();
+
return $this->invoice;
}
@@ -243,7 +245,7 @@ class InvoiceSumInclusive
$this->invoice->balance = $this->formatValue($this->getTotal(), $this->precision);
}
}
-
+
/* Set new calculated total */
$this->invoice->amount = $this->formatValue($this->getTotal(), $this->precision);
diff --git a/app/Helpers/Invoice/ProRata.php b/app/Helpers/Invoice/ProRata.php
index 50b3fa108613..d79ae48d7d64 100644
--- a/app/Helpers/Invoice/ProRata.php
+++ b/app/Helpers/Invoice/ProRata.php
@@ -20,62 +20,62 @@ use Illuminate\Support\Carbon;
class ProRata
{
-
-
/**
* Returns the amount to refund based on
* the time interval and the frequency duration
- *
- * @param float $amount
- * @param Carbon $from_date
- * @param Carbon $to_date
- * @param int $frequency
- * @return float
+ *
+ * @param float $amount
+ * @param Carbon $from_date
+ * @param Carbon $to_date
+ * @param int $frequency
+ * @return float
*/
public function refund(float $amount, Carbon $from_date, Carbon $to_date, int $frequency) :float
{
$days = $from_date->copy()->diffInDays($to_date);
$days_in_frequency = $this->getDaysInFrequency($frequency);
- return round( (($days/$days_in_frequency) * $amount),2);
+ return round((($days / $days_in_frequency) * $amount), 2);
}
/**
* Returns the amount to charge based on
* the time interval and the frequency duration
- *
- * @param float $amount
- * @param Carbon $from_date
- * @param Carbon $to_date
- * @param int $frequency
- * @return float
+ *
+ * @param float $amount
+ * @param Carbon $from_date
+ * @param Carbon $to_date
+ * @param int $frequency
+ * @return float
*/
public function charge(float $amount, Carbon $from_date, Carbon $to_date, int $frequency) :float
{
$days = $from_date->copy()->diffInDays($to_date);
$days_in_frequency = $this->getDaysInFrequency($frequency);
- return round( (($days/$days_in_frequency) * $amount),2);
+ return round((($days / $days_in_frequency) * $amount), 2);
}
/**
* Prepares the line items of an invoice
* to be pro rata refunded.
- *
- * @param Invoice $invoice
- * @param bool $is_credit
- * @return array
- * @throws Exception
+ *
+ * @param Invoice $invoice
+ * @param bool $is_credit
+ * @return array
+ * @throws Exception
*/
public function refundItems(Invoice $invoice, $is_credit = false) :array
{
- if(!$invoice)
+ if (! $invoice) {
return [];
+ }
$recurring_invoice = RecurringInvoice::find($invoice->recurring_id)->first();
- if(!$recurring_invoice)
+ if (! $recurring_invoice) {
throw new \Exception("Invoice isn't attached to a recurring invoice");
+ }
/* depending on whether we are creating an invoice or a credit*/
$multiplier = $is_credit ? 1 : -1;
@@ -84,29 +84,22 @@ class ProRata
$line_items = [];
- foreach($invoice->line_items as $item)
- {
-
- if($item->product_key != ctrans('texts.refund'))
- {
+ foreach ($invoice->line_items as $item) {
+ if ($item->product_key != ctrans('texts.refund')) {
$item->quantity = 1;
- $item->cost = $this->refund($item->cost*$multiplier, $start_date, now(), $recurring_invoice->frequency_id);
+ $item->cost = $this->refund($item->cost * $multiplier, $start_date, now(), $recurring_invoice->frequency_id);
$item->product_key = ctrans('texts.refund');
- $item->notes = ctrans('texts.refund') . ": ". $item->notes;
+ $item->notes = ctrans('texts.refund').': '.$item->notes;
$line_items[] = $item;
-
}
}
return $line_items;
-
}
-
private function getDaysInFrequency($frequency)
{
-
switch ($frequency) {
case RecurringInvoice::FREQUENCY_DAILY:
return 1;
@@ -135,7 +128,5 @@ class ProRata
default:
return 0;
}
-
}
-
-}
\ No newline at end of file
+}
diff --git a/app/Helpers/Mail/GmailTransport.php b/app/Helpers/Mail/GmailTransport.php
index 711c15e22d6e..d77688f5bd39 100644
--- a/app/Helpers/Mail/GmailTransport.php
+++ b/app/Helpers/Mail/GmailTransport.php
@@ -48,7 +48,7 @@ class GmailTransport extends Transport
/*We should nest the token in the message and then discard it as needed*/
$token = $message->getHeaders()->get('GmailToken')->getValue();
-
+
$message->getHeaders()->remove('GmailToken');
$this->beforeSendPerformed($message);
@@ -61,34 +61,25 @@ class GmailTransport extends Transport
$this->gmail->cc($message->getCc());
- if(is_array($message->getBcc()))
+ if (is_array($message->getBcc())) {
$this->gmail->bcc(array_keys($message->getBcc()));
+ }
- foreach ($message->getChildren() as $child)
- {
-
- if($child->getContentType() != 'text/plain')
- {
-
- $this->gmail->attach(TempFile::filePath($child->getBody(), $child->getHeaders()->get('Content-Type')->getParameter('name') ));
-
+ foreach ($message->getChildren() as $child) {
+ if ($child->getContentType() != 'text/plain') {
+ $this->gmail->attach(TempFile::filePath($child->getBody(), $child->getHeaders()->get('Content-Type')->getParameter('name')));
}
-
- }
+ }
/**
* Google is very strict with their
* sending limits, if we hit 429s, sleep and
* retry again later.
*/
- try{
-
+ try {
$this->gmail->send();
-
- }
- catch(\Google\Service\Exception $e)
- {
- nlog("gmail exception");
+ } catch (\Google\Service\Exception $e) {
+ nlog('gmail exception');
nlog($e->getErrors());
sleep(5);
diff --git a/app/Helpers/Mail/GmailTransportManager.php b/app/Helpers/Mail/GmailTransportManager.php
index b6f574427f50..2633f4dd641c 100644
--- a/app/Helpers/Mail/GmailTransportManager.php
+++ b/app/Helpers/Mail/GmailTransportManager.php
@@ -8,6 +8,7 @@
*
* @license https://www.elastic.co/licensing/elastic-license
*/
+
namespace App\Helpers\Mail;
use App\CustomMailDriver\CustomTransport;
@@ -16,7 +17,6 @@ use Dacastro4\LaravelGmail\Services\Message\Mail;
use Illuminate\Mail\MailManager;
use Illuminate\Support\Facades\Config;
-
class GmailTransportManager extends MailManager
{
protected function createGmailTransport()
@@ -28,4 +28,4 @@ class GmailTransportManager extends MailManager
{
return new Office365MailTransport();
}
-}
\ No newline at end of file
+}
diff --git a/app/Helpers/Mail/Office365MailTransport.php b/app/Helpers/Mail/Office365MailTransport.php
index b7fa2546f67a..afa76bbb9002 100644
--- a/app/Helpers/Mail/Office365MailTransport.php
+++ b/app/Helpers/Mail/Office365MailTransport.php
@@ -13,20 +13,18 @@ namespace App\Helpers\Mail;
use Illuminate\Mail\Transport\Transport;
use Illuminate\Support\Str;
-use Swift_Mime_SimpleMessage;
use Microsoft\Graph\Graph;
use Microsoft\Graph\Model\UploadSession;
+use Swift_Mime_SimpleMessage;
class Office365MailTransport extends Transport
{
-
public function __construct()
{
}
public function send(Swift_Mime_SimpleMessage $message, &$failedRecipients = null)
{
-
$this->beforeSendPerformed($message);
$graph = new Graph();
@@ -42,7 +40,7 @@ class Office365MailTransport extends Transport
if ($messageBodySizeMb >= 4) {
unset($messageBody);
- $graphMessage = $graph->createRequest("POST", "/users/" . key($message->getFrom()) . "/messages")
+ $graphMessage = $graph->createRequest('POST', '/users/'.key($message->getFrom()).'/messages')
->attachBody($this->getBody($message))
->setReturnType(\Microsoft\Graph\Model\Message::class)
->execute();
@@ -58,31 +56,31 @@ class Office365MailTransport extends Transport
'AttachmentItem' => [
'attachmentType' => 'file',
'name' => $fileName,
- 'size' => strlen($content)
- ]
+ 'size' => strlen($content),
+ ],
];
if ($size <= 3) { //ErrorAttachmentSizeShouldNotBeLessThanMinimumSize if attachment <= 3mb, then we need to add this
$attachmentBody = [
- "@odata.type" => "#microsoft.graph.fileAttachment",
- "name" => $attachment->getHeaders()->get('Content-Type')->getParameter('name'),
- "contentType" => $attachment->getBodyContentType(),
- "contentBytes" => base64_encode($attachment->getBody()),
- 'contentId' => $id
+ '@odata.type' => '#microsoft.graph.fileAttachment',
+ 'name' => $attachment->getHeaders()->get('Content-Type')->getParameter('name'),
+ 'contentType' => $attachment->getBodyContentType(),
+ 'contentBytes' => base64_encode($attachment->getBody()),
+ 'contentId' => $id,
];
- $addAttachment = $graph->createRequest("POST", "/users/" . key($message->getFrom()) . "/messages/" . $graphMessage->getId() . "/attachments")
+ $addAttachment = $graph->createRequest('POST', '/users/'.key($message->getFrom()).'/messages/'.$graphMessage->getId().'/attachments')
->attachBody($attachmentBody)
->setReturnType(UploadSession::class)
->execute();
} else {
//upload the files in chunks of 4mb....
- $uploadSession = $graph->createRequest("POST", "/users/" . key($message->getFrom()) . "/messages/" . $graphMessage->getId() . "/attachments/createUploadSession")
+ $uploadSession = $graph->createRequest('POST', '/users/'.key($message->getFrom()).'/messages/'.$graphMessage->getId().'/attachments/createUploadSession')
->attachBody($attachmentMessage)
->setReturnType(UploadSession::class)
->execute();
- $fragSize = 1024 * 1024 * 4; //4mb at once...
+ $fragSize = 1024 * 1024 * 4; //4mb at once...
$numFragments = ceil($fileSize / $fragSize);
$contentChunked = str_split($content, $fragSize);
$bytesRemaining = $fileSize;
@@ -97,19 +95,19 @@ class Office365MailTransport extends Transport
$end = $fileSize - 1;
}
$data = $contentChunked[$i];
- $content_range = "bytes " . $start . "-" . $end . "/" . $fileSize;
+ $content_range = 'bytes '.$start.'-'.$end.'/'.$fileSize;
$headers = [
- "Content-Length" => $numBytes,
- "Content-Range" => $content_range
+ 'Content-Length' => $numBytes,
+ 'Content-Range' => $content_range,
];
$client = new \GuzzleHttp\Client();
$tmp = $client->put($uploadSession->getUploadUrl(), [
'headers' => $headers,
'body' => $data,
'allow_redirects' => false,
- 'timeout' => 1000
+ 'timeout' => 1000,
]);
- $result = $tmp->getBody() . '';
+ $result = $tmp->getBody().'';
$result = json_decode($result); //if body == empty, then the file was successfully uploaded
$bytesRemaining = $bytesRemaining - $chunkSize;
$i++;
@@ -119,19 +117,16 @@ class Office365MailTransport extends Transport
}
//definetly send the message
- $graph->createRequest("POST", "/users/" . key($message->getFrom()) . "/messages/" . $graphMessage->getId() . "/send")->execute();
+ $graph->createRequest('POST', '/users/'.key($message->getFrom()).'/messages/'.$graphMessage->getId().'/send')->execute();
} else {
-
try {
- $graphMessage = $graph->createRequest("POST", "/users/" . key($message->getFrom()) . "/sendmail")
+ $graphMessage = $graph->createRequest('POST', '/users/'.key($message->getFrom()).'/sendmail')
->attachBody($messageBody)
->setReturnType(\Microsoft\Graph\Model\Message::class)
->execute();
- }
- catch(\Exception $e){
-
+ } catch (\Exception $e) {
sleep(5);
- $graphMessage = $graph->createRequest("POST", "/users/" . key($message->getFrom()) . "/sendmail")
+ $graphMessage = $graph->createRequest('POST', '/users/'.key($message->getFrom()).'/sendmail')
->attachBody($messageBody)
->setReturnType(\Microsoft\Graph\Model\Message::class)
->execute();
@@ -150,15 +145,14 @@ class Office365MailTransport extends Transport
* @param bool $withAttachments
* @return array
*/
-
protected function getBody(Swift_Mime_SimpleMessage $message, $withAttachments = false)
{
$messageData = [
'from' => [
'emailAddress' => [
'address' => key($message->getFrom()),
- 'name' => current($message->getFrom())
- ]
+ 'name' => current($message->getFrom()),
+ ],
],
'toRecipients' => $this->getTo($message),
'ccRecipients' => $this->getCc($message),
@@ -166,9 +160,9 @@ class Office365MailTransport extends Transport
'replyTo' => $this->getReplyTo($message),
'subject' => $message->getSubject(),
'body' => [
- 'contentType' => $message->getBodyContentType() == "text/html" ? 'html' : 'text',
- 'content' => $message->getBody()
- ]
+ 'contentType' => $message->getBodyContentType() == 'text/html' ? 'html' : 'text',
+ 'content' => $message->getBody(),
+ ],
];
if ($withAttachments) {
@@ -178,11 +172,11 @@ class Office365MailTransport extends Transport
foreach ($message->getChildren() as $attachment) {
if ($attachment instanceof \Swift_Mime_SimpleMimeEntity && $attachment->getContentType() != 'text/plain') {
$attachments[] = [
- "@odata.type" => "#microsoft.graph.fileAttachment",
- "name" => $attachment->getHeaders()->get('Content-Type')->getParameter('name'),
- "contentType" => $attachment->getBodyContentType(),
- "contentBytes" => base64_encode($attachment->getBody()),
- 'contentId' => $attachment->getId()
+ '@odata.type' => '#microsoft.graph.fileAttachment',
+ 'name' => $attachment->getHeaders()->get('Content-Type')->getParameter('name'),
+ 'contentType' => $attachment->getBodyContentType(),
+ 'contentBytes' => base64_encode($attachment->getBody()),
+ 'contentId' => $attachment->getId(),
];
}
}
@@ -206,12 +200,12 @@ class Office365MailTransport extends Transport
return $display ? [
'emailAddress' => [
'address' => $address,
- 'name' => $display
- ]
+ 'name' => $display,
+ ],
] : [
'emailAddress' => [
- 'address' => $address
- ]
+ 'address' => $address,
+ ],
];
})->values()->toArray();
}
@@ -228,12 +222,12 @@ class Office365MailTransport extends Transport
return $display ? [
'emailAddress' => [
'address' => $address,
- 'name' => $display
- ]
+ 'name' => $display,
+ ],
] : [
'emailAddress' => [
- 'address' => $address
- ]
+ 'address' => $address,
+ ],
];
})->values()->toArray();
}
@@ -250,12 +244,12 @@ class Office365MailTransport extends Transport
return $display ? [
'emailAddress' => [
'address' => $address,
- 'name' => $display
- ]
+ 'name' => $display,
+ ],
] : [
'emailAddress' => [
- 'address' => $address
- ]
+ 'address' => $address,
+ ],
];
})->values()->toArray();
}
@@ -272,12 +266,12 @@ class Office365MailTransport extends Transport
return $display ? [
'emailAddress' => [
'address' => $address,
- 'name' => $display
- ]
+ 'name' => $display,
+ ],
] : [
'emailAddress' => [
- 'address' => $address
- ]
+ 'address' => $address,
+ ],
];
})->values()->toArray();
}
@@ -297,5 +291,4 @@ class Office365MailTransport extends Transport
(array) $message->getReplyTo()
);
}
-
-}
\ No newline at end of file
+}
diff --git a/app/Helpers/Mail/Office365TransportManager.php b/app/Helpers/Mail/Office365TransportManager.php
index 3c88383820e4..0e6547300673 100644
--- a/app/Helpers/Mail/Office365TransportManager.php
+++ b/app/Helpers/Mail/Office365TransportManager.php
@@ -20,4 +20,4 @@ class Office365TransportManager extends MailManager
{
return new Office365MailTransport();
}
-}
\ No newline at end of file
+}
diff --git a/app/Helpers/Subscription/SubscriptionCalculator.php b/app/Helpers/Subscription/SubscriptionCalculator.php
index 8cb9d903eed2..4fc5aca2fea2 100644
--- a/app/Helpers/Subscription/SubscriptionCalculator.php
+++ b/app/Helpers/Subscription/SubscriptionCalculator.php
@@ -20,9 +20,8 @@ use Illuminate\Support\Carbon;
/**
* SubscriptionCalculator.
*/
-class SubscriptionCalculator
+class SubscriptionCalculator
{
-
public Subscription $target_subscription;
public Invoice $invoice;
@@ -37,20 +36,18 @@ class SubscriptionCalculator
* Tests if the user is currently up
* to date with their payments for
* a given recurring invoice
- *
+ *
* @return bool
*/
public function isPaidUp() :bool
{
-
$outstanding_invoices_exist = Invoice::whereIn('status_id', [Invoice::STATUS_SENT, Invoice::STATUS_PARTIAL])
->where('subscription_id', $this->invoice->subscription_id)
->where('client_id', $this->invoice->client_id)
->where('balance', '>', 0)
->exists();
- return ! $outstanding_invoices_exist;
-
+ return ! $outstanding_invoices_exist;
}
public function calcUpgradePlan()
@@ -63,21 +60,21 @@ class SubscriptionCalculator
//are they paid up to date.
//yes - calculate refund
- if($this->isPaidUp())
+ if ($this->isPaidUp()) {
$refund_invoice = $this->getRefundInvoice();
+ }
- if($refund_invoice)
- {
+ if ($refund_invoice) {
$subscription = Subscription::find($this->invoice->subscription_id);
$pro_rata = new ProRata;
- $to_date = $subscription->service()->getNextDateForFrequency(Carbon::parse($refund_invoice->date), $subscription->frequency_id);
+ $to_date = $subscription->service()->getNextDateForFrequency(Carbon::parse($refund_invoice->date), $subscription->frequency_id);
$refund_amount = $pro_rata->refund($refund_invoice->amount, now(), $to_date, $subscription->frequency_id);
$charge_amount = $pro_rata->charge($this->target_subscription->price, now(), $to_date, $this->target_subscription->frequency_id);
-
- return ($charge_amount - $refund_amount);
+
+ return $charge_amount - $refund_amount;
}
//no - return full freight charge.
@@ -86,7 +83,6 @@ class SubscriptionCalculator
public function executeUpgradePlan()
{
-
}
private function getRefundInvoice()
@@ -96,7 +92,5 @@ class SubscriptionCalculator
->where('is_deleted', 0)
->orderBy('id', 'desc')
->first();
-
}
-
-}
\ No newline at end of file
+}
diff --git a/app/Http/Controllers/AccountController.php b/app/Http/Controllers/AccountController.php
index 67d2ffca77a2..7f512abf4a49 100644
--- a/app/Http/Controllers/AccountController.php
+++ b/app/Http/Controllers/AccountController.php
@@ -151,22 +151,21 @@ class AccountController extends BaseController
$ct = CompanyUser::whereUserId(auth()->user()->id);
- $truth = app()->make(TruthSource::class);
- $truth->setCompanyUser($ct->first());
- $truth->setUser(auth()->user());
- $truth->setCompany($ct->first()->company);
-
+ $truth = app()->make(TruthSource::class);
+ $truth->setCompanyUser($ct->first());
+ $truth->setUser(auth()->user());
+ $truth->setCompany($ct->first()->company);
return $this->listResponse($ct);
}
public function update(UpdateAccountRequest $request, Account $account)
{
-
$fi = new \FilesystemIterator(public_path('react'), \FilesystemIterator::SKIP_DOTS);
- if(iterator_count($fi) < 30)
+ if (iterator_count($fi) < 30) {
return response()->json(['message' => 'React App Not Installed, Please install the React app before attempting to switch.'], 400);
+ }
$account->fill($request->all());
$account->save();
diff --git a/app/Http/Controllers/ActivityController.php b/app/Http/Controllers/ActivityController.php
index e216355c9d14..e64f3df8bec5 100644
--- a/app/Http/Controllers/ActivityController.php
+++ b/app/Http/Controllers/ActivityController.php
@@ -23,8 +23,8 @@ use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Storage;
-use Symfony\Component\HttpFoundation\StreamedResponse;
use stdClass;
+use Symfony\Component\HttpFoundation\StreamedResponse;
class ActivityController extends BaseController
{
@@ -91,28 +91,25 @@ class ActivityController extends BaseController
$activities = Activity::orderBy('created_at', 'DESC')->company()
->take($default_activities);
- if($request->has('react')){
-
+ if ($request->has('react')) {
$system = ctrans('texts.system');
- $data = $activities->cursor()->map(function ($activity) use($system){
-
- $arr=
+ $data = $activities->cursor()->map(function ($activity) use ($system) {
+ $arr =
[
- 'client' => $activity->client ? $activity->client : '',
- 'contact' => $activity->contact ? $activity->contact : '',
- 'quote' => $activity->quote ? $activity->quote : '',
- 'user' => $activity->user ? $activity->user : '',
- 'expense' => $activity->expense ? $activity->expense : '',
- 'invoice' => $activity->invoice ? $activity->invoice : '',
- 'recurring_invoice' => $activity->recurring_invoice ? $activity->recurring_invoice : '',
- 'payment' => $activity->payment ? $activity->payment : '',
- 'credit' => $activity->credit ? $activity->credit : '',
- 'task' => $activity->task ? $activity->task : '',
+ 'client' => $activity->client ? $activity->client : '',
+ 'contact' => $activity->contact ? $activity->contact : '',
+ 'quote' => $activity->quote ? $activity->quote : '',
+ 'user' => $activity->user ? $activity->user : '',
+ 'expense' => $activity->expense ? $activity->expense : '',
+ 'invoice' => $activity->invoice ? $activity->invoice : '',
+ 'recurring_invoice' => $activity->recurring_invoice ? $activity->recurring_invoice : '',
+ 'payment' => $activity->payment ? $activity->payment : '',
+ 'credit' => $activity->credit ? $activity->credit : '',
+ 'task' => $activity->task ? $activity->task : '',
];
return array_merge($arr, $activity->toArray());
-
});
return response()->json(['data' => $data->toArray()], 200);
@@ -168,25 +165,23 @@ class ActivityController extends BaseController
$backup = $activity->backup;
$html_backup = '';
- /* Refactor 20-10-2021
+ /* Refactor 20-10-2021
*
* We have moved the backups out of the database and into object storage.
- * In order to handle edge cases, we still check for the database backup
+ * In order to handle edge cases, we still check for the database backup
* in case the file no longer exists
*/
- if($backup && $backup->filename && Storage::disk(config('filesystems.default'))->exists($backup->filename)){ //disk
+ if ($backup && $backup->filename && Storage::disk(config('filesystems.default'))->exists($backup->filename)) { //disk
- if(Ninja::isHosted())
+ if (Ninja::isHosted()) {
$html_backup = file_get_contents(Storage::disk(config('filesystems.default'))->url($backup->filename));
- else
+ } else {
$html_backup = file_get_contents(Storage::disk(config('filesystems.default'))->path($backup->filename));
-
- }
- elseif($backup && $backup->html_backup){ //db
+ }
+ } elseif ($backup && $backup->html_backup) { //db
$html_backup = $backup->html_backup;
- }
- elseif (! $backup || ! $backup->html_backup) { //failed
+ } elseif (! $backup || ! $backup->html_backup) { //failed
return response()->json(['message'=> ctrans('texts.no_backup_exists'), 'errors' => new stdClass], 404);
}
@@ -195,32 +190,25 @@ class ActivityController extends BaseController
$numbered_pdf = $this->pageNumbering($pdf, $activity->company);
- if($numbered_pdf)
- $pdf = $numbered_pdf;
-
-
- }
- elseif(config('ninja.invoiceninja_hosted_pdf_generation') || config('ninja.pdf_generator') == 'hosted_ninja'){
+ if ($numbered_pdf) {
+ $pdf = $numbered_pdf;
+ }
+ } elseif (config('ninja.invoiceninja_hosted_pdf_generation') || config('ninja.pdf_generator') == 'hosted_ninja') {
$pdf = (new NinjaPdf())->build($html_backup);
- $numbered_pdf = $this->pageNumbering($pdf, $activity->company);
+ $numbered_pdf = $this->pageNumbering($pdf, $activity->company);
- if($numbered_pdf)
- $pdf = $numbered_pdf;
-
-
-
- }
- else {
+ if ($numbered_pdf) {
+ $pdf = $numbered_pdf;
+ }
+ } else {
$pdf = $this->makePdf(null, null, $html_backup);
- $numbered_pdf = $this->pageNumbering($pdf, $activity->company);
-
- if($numbered_pdf)
- $pdf = $numbered_pdf;
-
-
+ $numbered_pdf = $this->pageNumbering($pdf, $activity->company);
+ if ($numbered_pdf) {
+ $pdf = $numbered_pdf;
+ }
}
if (isset($activity->invoice_id)) {
diff --git a/app/Http/Controllers/Auth/ContactForgotPasswordController.php b/app/Http/Controllers/Auth/ContactForgotPasswordController.php
index 84d4139b33ca..e26fbfc672c8 100644
--- a/app/Http/Controllers/Auth/ContactForgotPasswordController.php
+++ b/app/Http/Controllers/Auth/ContactForgotPasswordController.php
@@ -58,26 +58,24 @@ class ContactForgotPasswordController extends Controller
*/
public function showLinkRequestForm(Request $request)
{
-
$account = false;
-
- if(Ninja::isHosted() && $request->session()->has('company_key'))
- {
+
+ if (Ninja::isHosted() && $request->session()->has('company_key')) {
MultiDB::findAndSetDbByCompanyKey($request->session()->get('company_key'));
$company = Company::where('company_key', $request->session()->get('company_key'))->first();
$account = $company->account;
}
- if(!$account){
+ if (! $account) {
$account = Account::first();
$company = $account->companies->first();
}
-
+
return $this->render('auth.passwords.request', [
'title' => 'Client Password Reset',
'passwordEmailRoute' => 'client.password.email',
'account' => $account,
- 'company' => $company
+ 'company' => $company,
]);
}
@@ -93,44 +91,41 @@ class ContactForgotPasswordController extends Controller
public function sendResetLinkEmail(ContactPasswordResetRequest $request)
{
- if(Ninja::isHosted() && $request->has('company_key'))
+ if (Ninja::isHosted() && $request->has('company_key')) {
MultiDB::findAndSetDbByCompanyKey($request->input('company_key'));
-
+ }
+
$this->validateEmail($request);
- if(Ninja::isHosted() && $company = Company::where('company_key', $request->input('company_key'))->first())
- {
+ if (Ninja::isHosted() && $company = Company::where('company_key', $request->input('company_key'))->first()) {
$contact = ClientContact::where(['email' => $request->input('email'), 'company_id' => $company->id])
->whereHas('client', function ($query) {
- $query->where('is_deleted',0);
- })->first();
- }
- else {
-
+ $query->where('is_deleted', 0);
+ })->first();
+ } else {
$contact = ClientContact::where(['email' => $request->input('email')])
->whereHas('client', function ($query) {
- $query->where('is_deleted',0);
- })->first();
+ $query->where('is_deleted', 0);
+ })->first();
}
$response = false;
- if($contact){
+ if ($contact) {
/* Update all instances of the client */
$token = Str::random(60);
ClientContact::where('email', $contact->email)->update(['token' => $token]);
$contact->sendPasswordResetNotification($token);
$response = Password::RESET_LINK_SENT;
-
- }
- else
+ } else {
return $this->sendResetLinkFailedResponse($request, Password::INVALID_USER);
+ }
if ($request->ajax()) {
-
- if($response == Password::RESET_THROTTLED)
+ if ($response == Password::RESET_THROTTLED) {
return response()->json(['message' => ctrans('passwords.throttled'), 'status' => false], 429);
+ }
return $response == Password::RESET_LINK_SENT
? response()->json(['message' => 'Reset link sent to your email.', 'status' => true], 201)
@@ -141,5 +136,4 @@ class ContactForgotPasswordController extends Controller
? $this->sendResetLinkResponse($request, $response)
: $this->sendResetLinkFailedResponse($request, $response);
}
-
}
diff --git a/app/Http/Controllers/Auth/ContactLoginController.php b/app/Http/Controllers/Auth/ContactLoginController.php
index e3118cb0fb73..7e18829e4cc5 100644
--- a/app/Http/Controllers/Auth/ContactLoginController.php
+++ b/app/Http/Controllers/Auth/ContactLoginController.php
@@ -39,52 +39,46 @@ class ContactLoginController extends Controller
public function showLoginForm(Request $request)
{
-
$company = false;
$account = false;
- if($request->session()->has('company_key')){
+ if ($request->session()->has('company_key')) {
MultiDB::findAndSetDbByCompanyKey($request->session()->get('company_key'));
$company = Company::where('company_key', $request->input('company_key'))->first();
}
- if($company){
+ if ($company) {
$account = $company->account;
- }
- elseif (!$company && strpos($request->getHost(), 'invoicing.co') !== false) {
+ } elseif (! $company && strpos($request->getHost(), 'invoicing.co') !== false) {
$subdomain = explode('.', $request->getHost())[0];
MultiDB::findAndSetDbByDomain(['subdomain' => $subdomain]);
$company = Company::where('subdomain', $subdomain)->first();
-
- } elseif(Ninja::isHosted()){
-
+ } elseif (Ninja::isHosted()) {
MultiDB::findAndSetDbByDomain(['portal_domain' => $request->getSchemeAndHttpHost()]);
$company = Company::where('portal_domain', $request->getSchemeAndHttpHost())->first();
-
- }
- elseif (Ninja::isSelfHost()) {
+ } elseif (Ninja::isSelfHost()) {
$account = Account::first();
$company = $account->default_company;
} else {
$company = null;
}
- if(!$account){
+ if (! $account) {
$account_id = $request->get('account_id');
$account = Account::find($account_id);
}
return $this->render('auth.login', ['account' => $account, 'company' => $company]);
-
}
public function login(Request $request)
{
Auth::shouldUse('contact');
- if(Ninja::isHosted() && $request->has('company_key'))
+ if (Ninja::isHosted() && $request->has('company_key')) {
MultiDB::findAndSetDbByCompanyKey($request->input('company_key'));
+ }
$this->validateLogin($request);
// If the class is using the ThrottlesLogins trait, we can automatically throttle
@@ -97,21 +91,20 @@ class ContactLoginController extends Controller
return $this->sendLockoutResponse($request);
}
- if(Ninja::isHosted() && $request->has('password') && $company = Company::where('company_key', $request->input('company_key'))->first()){
-
+ if (Ninja::isHosted() && $request->has('password') && $company = Company::where('company_key', $request->input('company_key'))->first()) {
$contact = ClientContact::where(['email' => $request->input('email'), 'company_id' => $company->id])
->whereHas('client', function ($query) {
- $query->where('is_deleted',0);
- })->first();
+ $query->where('is_deleted', 0);
+ })->first();
- if(!$contact)
+ if (! $contact) {
return $this->sendFailedLoginResponse($request);
+ }
- if(Hash::check($request->input('password'), $contact->password))
+ if (Hash::check($request->input('password'), $contact->password)) {
return $this->authenticated($request, $contact);
-
- }
- elseif ($this->attemptLogin($request)) {
+ }
+ } elseif ($this->attemptLogin($request)) {
return $this->sendLoginResponse($request);
}
// If the login attempt was unsuccessful we will increment the number of attempts
@@ -164,19 +157,18 @@ class ContactLoginController extends Controller
private function setRedirectPath()
{
-
- if(auth()->guard('contact')->user()->company->enabled_modules & PortalComposer::MODULE_INVOICES)
+ if (auth()->guard('contact')->user()->company->enabled_modules & PortalComposer::MODULE_INVOICES) {
$this->redirectTo = '/client/invoices';
- elseif(auth()->guard('contact')->user()->company->enabled_modules & PortalComposer::MODULE_RECURRING_INVOICES)
+ } elseif (auth()->guard('contact')->user()->company->enabled_modules & PortalComposer::MODULE_RECURRING_INVOICES) {
$this->redirectTo = '/client/recurring_invoices';
- elseif(auth()->guard('contact')->user()->company->enabled_modules & PortalComposer::MODULE_QUOTES)
+ } elseif (auth()->guard('contact')->user()->company->enabled_modules & PortalComposer::MODULE_QUOTES) {
$this->redirectTo = '/client/quotes';
- elseif(auth()->guard('contact')->user()->company->enabled_modules & PortalComposer::MODULE_CREDITS)
+ } elseif (auth()->guard('contact')->user()->company->enabled_modules & PortalComposer::MODULE_CREDITS) {
$this->redirectTo = '/client/credits';
- elseif(auth()->guard('contact')->user()->company->enabled_modules & PortalComposer::MODULE_TASKS)
+ } elseif (auth()->guard('contact')->user()->company->enabled_modules & PortalComposer::MODULE_TASKS) {
$this->redirectTo = '/client/tasks';
- elseif(auth()->guard('contact')->user()->company->enabled_modules & PortalComposer::MODULE_EXPENSES)
+ } elseif (auth()->guard('contact')->user()->company->enabled_modules & PortalComposer::MODULE_EXPENSES) {
$this->redirectTo = '/client/expenses';
-
+ }
}
}
diff --git a/app/Http/Controllers/Auth/ContactRegisterController.php b/app/Http/Controllers/Auth/ContactRegisterController.php
index 6d34694ce2c7..4bb551017a7d 100644
--- a/app/Http/Controllers/Auth/ContactRegisterController.php
+++ b/app/Http/Controllers/Auth/ContactRegisterController.php
@@ -19,9 +19,9 @@ use App\Models\Client;
use App\Models\Company;
use App\Utils\Ninja;
use App\Utils\Traits\GeneratesCounter;
+use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
-use Illuminate\Support\Facades\App;
class ContactRegisterController extends Controller
{
@@ -34,11 +34,11 @@ class ContactRegisterController extends Controller
public function showRegisterForm(string $company_key = '')
{
-
- if(strlen($company_key) > 2)
+ if (strlen($company_key) > 2) {
$key = $company_key;
- else
+ } else {
$key = request()->session()->has('company_key') ? request()->session()->get('company_key') : $company_key;
+ }
$company = Company::where('company_key', $key)->firstOrFail();
@@ -63,7 +63,6 @@ class ContactRegisterController extends Controller
private function getClient(array $data)
{
-
$client = ClientFactory::create($data['company']->id, $data['company']->owner()->id);
$client->fill($data);
@@ -71,10 +70,8 @@ class ContactRegisterController extends Controller
$client->number = $this->getNextClientNumber($client);
$client->save();
- if(!array_key_exists('country_id', $data) && strlen($client->company->settings->country_id) > 1){
-
+ if (! array_key_exists('country_id', $data) && strlen($client->company->settings->country_id) > 1) {
$client->update(['country_id' => $client->company->settings->country_id]);
-
}
return $client;
@@ -88,8 +85,9 @@ class ContactRegisterController extends Controller
$client_contact->client_id = $client->id;
$client_contact->is_primary = true;
- if(array_key_exists('password', $data))
+ if (array_key_exists('password', $data)) {
$client_contact->password = Hash::make($data['password']);
+ }
$client_contact->save();
diff --git a/app/Http/Controllers/Auth/ContactResetPasswordController.php b/app/Http/Controllers/Auth/ContactResetPasswordController.php
index 44ab7909ab20..2b060d0bb5b8 100644
--- a/app/Http/Controllers/Auth/ContactResetPasswordController.php
+++ b/app/Http/Controllers/Auth/ContactResetPasswordController.php
@@ -69,63 +69,56 @@ class ContactResetPasswordController extends Controller
*/
public function showResetForm(Request $request, $token = null)
{
-
- if($request->session()->has('company_key')){
+ if ($request->session()->has('company_key')) {
MultiDB::findAndSetDbByCompanyKey($request->session()->get('company_key'));
$company = Company::where('company_key', $request->session()->get('company_key'))->first();
$db = $company->db;
$account = $company->account;
- }
- else {
-
+ } else {
$account_key = $request->session()->has('account_key') ? $request->session()->get('account_key') : false;
- if($account_key){
-
+ if ($account_key) {
MultiDB::findAndSetDbByAccountKey($account_key);
$account = Account::where('key', $account_key)->first();
$db = $account->companies->first()->db;
$company = $account->companies->first();
- }
- else{
-
+ } else {
$account = Account::first();
$db = $account->companies->first()->db;
$company = $account->companies->first();
}
-
}
-
return $this->render('auth.passwords.reset')->with(
['token' => $token, 'email' => $request->email, 'account' => $account, 'db' => $db, 'company' => $company]
);
-
}
public function reset(Request $request)
{
- if($request->session()->has('company_key'))
+ if ($request->session()->has('company_key')) {
MultiDB::findAndSetDbByCompanyKey($request->session()->get('company_key'));
-
+ }
+
$request->validate($this->rules(), $this->validationErrorMessages());
- $user = ClientContact::where($request->only(['email','token']))->first();
+ $user = ClientContact::where($request->only(['email', 'token']))->first();
- if(!$user)
+ if (! $user) {
return $this->sendResetFailedResponse($request, PASSWORD::INVALID_USER);
+ }
$hashed_password = Hash::make($request->input('password'));
ClientContact::where('email', $user->email)->update([
'password' => $hashed_password,
- 'remember_token' => Str::random(60)
+ 'remember_token' => Str::random(60),
]);
event(new PasswordReset($user));
auth()->login($user, true);
-
+
$response = Password::PASSWORD_RESET;
// Added this because it collides the session between
diff --git a/app/Http/Controllers/Auth/ForgotPasswordController.php b/app/Http/Controllers/Auth/ForgotPasswordController.php
index ba041fc661f3..c8ce54988eb3 100644
--- a/app/Http/Controllers/Auth/ForgotPasswordController.php
+++ b/app/Http/Controllers/Auth/ForgotPasswordController.php
@@ -60,12 +60,12 @@ class ForgotPasswordController extends Controller
// need to show to the user. Finally, we'll send out a proper response.
$response = $this->broker()->sendResetLink(
$this->credentials($request)
- );
+ );
if ($request->ajax()) {
-
- if($response == Password::RESET_THROTTLED)
+ if ($response == Password::RESET_THROTTLED) {
return response()->json(['message' => ctrans('passwords.throttled'), 'status' => false], 429);
+ }
return $response == Password::RESET_LINK_SENT
? response()->json(['message' => 'Reset link sent to your email.', 'status' => true], 201)
@@ -79,16 +79,15 @@ class ForgotPasswordController extends Controller
public function showLinkRequestForm(Request $request)
{
- if($request->has('company_key')){
+ if ($request->has('company_key')) {
MultiDB::findAndSetDbByCompanyKey($request->input('company_key'));
$company = Company::where('company_key', $request->input('company_key'))->first();
$account = $company->account;
- }
- else{
+ } else {
$account_id = $request->get('account_id');
$account = Account::find($account_id);
}
-
+
return $this->render('auth.passwords.request', ['root' => 'themes', 'account' => $account]);
}
}
diff --git a/app/Http/Controllers/Auth/LoginController.php b/app/Http/Controllers/Auth/LoginController.php
index c3124824b39a..7626056d13eb 100644
--- a/app/Http/Controllers/Auth/LoginController.php
+++ b/app/Http/Controllers/Auth/LoginController.php
@@ -32,8 +32,8 @@ use App\Models\SystemLog;
use App\Models\User;
use App\Transformers\CompanyUserTransformer;
use App\Utils\Ninja;
-use App\Utils\Traits\UserSessionAttributes;
use App\Utils\Traits\User\LoginCache;
+use App\Utils\Traits\UserSessionAttributes;
use App\Utils\TruthSource;
use Google_Client;
use Illuminate\Database\Eloquent\Builder;
@@ -43,24 +43,24 @@ 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 Microsoft\Graph\Model;
class LoginController extends BaseController
{
/**
- * @OA\Tag(
- * name="login",
- * description="Authentication",
- * @OA\ExternalDocumentation(
- * description="Find out more",
- * url="http://docs.invoiceninja.com"
- * )
- * )
- */
-
+ * @OA\Tag(
+ * name="login",
+ * description="Authentication",
+ * @OA\ExternalDocumentation(
+ * description="Find out more",
+ * url="http://docs.invoiceninja.com"
+ * )
+ * )
+ */
use AuthenticatesUsers;
+
use UserSessionAttributes;
use LoginCache;
@@ -176,7 +176,6 @@ class LoginController extends BaseController
}
if ($this->attemptLogin($request)) {
-
LightLogs::create(new LoginSuccess())
->increment()
->queue();
@@ -184,29 +183,24 @@ class LoginController extends BaseController
$user = $this->guard()->user();
//2FA
- if($user->google_2fa_secret && $request->has('one_time_password'))
- {
+ if ($user->google_2fa_secret && $request->has('one_time_password')) {
$google2fa = new Google2FA();
- if(strlen($request->input('one_time_password')) == 0 || !$google2fa->verifyKey(decrypt($user->google_2fa_secret), $request->input('one_time_password')))
- {
+ if (strlen($request->input('one_time_password')) == 0 || ! $google2fa->verifyKey(decrypt($user->google_2fa_secret), $request->input('one_time_password'))) {
return response()
->json(['message' => ctrans('texts.invalid_one_time_password')], 401)
->header('X-App-Version', config('ninja.app_version'))
->header('X-Api-Version', config('ninja.minimum_client_version'));
}
-
- }
- elseif($user->google_2fa_secret && !$request->has('one_time_password')) {
-
- return response()
+ } elseif ($user->google_2fa_secret && ! $request->has('one_time_password')) {
+ return response()
->json(['message' => ctrans('texts.invalid_one_time_password')], 401)
->header('X-App-Version', config('ninja.app_version'))
->header('X-Api-Version', config('ninja.minimum_client_version'));
}
/* If for some reason we lose state on the default company ie. a company is deleted - always make sure we can default to a company*/
- if(!$user->account->default_company){
+ if (! $user->account->default_company) {
$account = $user->account;
$account->default_company_id = $user->companies->first()->id;
$account->save();
@@ -215,20 +209,19 @@ class LoginController extends BaseController
$cu = $this->hydrateCompanyUser();
- if($cu->count() == 0)
+ if ($cu->count() == 0) {
return response()->json(['message' => 'User found, but not attached to any companies, please see your administrator'], 400);
+ }
/*On the hosted platform, only owners can login for free/pro accounts*/
- if (Ninja::isHosted() && !$cu->first()->is_owner && !$user->account->isEnterpriseClient())
+ if (Ninja::isHosted() && ! $cu->first()->is_owner && ! $user->account->isEnterpriseClient()) {
return response()->json(['message' => 'Pro / Free accounts only the owner can log in. Please upgrade'], 403);
+ }
event(new UserLoggedIn($user, $user->account->default_company, Ninja::eventVars($user->id)));
return $this->timeConstrainedResponse($cu);
-
-
} else {
-
LightLogs::create(new LoginFailure())
->increment()
->queue();
@@ -239,7 +232,6 @@ class LoginController extends BaseController
->json(['message' => ctrans('texts.invalid_credentials')], 401)
->header('X-App-Version', config('ninja.app_version'))
->header('X-Api-Version', config('ninja.minimum_client_version'));
-
}
}
@@ -286,29 +278,32 @@ class LoginController extends BaseController
{
$truth = app()->make(TruthSource::class);
- if ($truth->getCompanyToken())
+ if ($truth->getCompanyToken()) {
$company_token = $truth->getCompanyToken();
- else
+ } else {
$company_token = CompanyToken::where('token', $request->header('X-API-TOKEN'))->first();
+ }
$cu = CompanyUser::query()
->where('user_id', $company_token->user_id);
- if ($cu->count() == 0)
+ if ($cu->count() == 0) {
return response()->json(['message' => 'User found, but not attached to any companies, please see your administrator'], 400);
+ }
$cu->first()->account->companies->each(function ($company) use ($cu, $request) {
-
if ($company->tokens()->where('is_system', true)->count() == 0) {
CreateCompanyToken::dispatchNow($company, $cu->first()->user, $request->server('HTTP_USER_AGENT'));
}
});
- if ($request->has('current_company') && $request->input('current_company') == 'true')
- $cu->where("company_id", $company_token->company_id);
+ if ($request->has('current_company') && $request->input('current_company') == 'true') {
+ $cu->where('company_id', $company_token->company_id);
+ }
- if (Ninja::isHosted() && !$cu->first()->is_owner && !$cu->first()->user->account->isEnterpriseClient())
+ if (Ninja::isHosted() && ! $cu->first()->is_owner && ! $cu->first()->user->account->isEnterpriseClient()) {
return response()->json(['message' => 'Pro / Free accounts only the owner can log in. Please upgrade'], 403);
+ }
return $this->refreshResponse($cu);
}
@@ -327,7 +322,6 @@ class LoginController extends BaseController
*/
public function oauthApiLogin()
{
-
$message = 'Provider not supported';
if (request()->input('provider') == 'google') {
return $this->handleGoogleOauth();
@@ -363,14 +357,13 @@ class LoginController extends BaseController
if ($user) {
return $this->loginOrCreateFromSocialite($user, $provider);
}
+
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 loginOrCreateFromSocialite($user, $provider)
{
$query = [
@@ -378,27 +371,29 @@ class LoginController extends BaseController
'oauth_provider_id' => $provider,
];
if ($existing_user = MultiDB::hasUser($query)) {
-
- if (!$existing_user->account)
+ if (! $existing_user->account) {
return response()->json(['message' => 'User exists, but not attached to any companies! Orphaned user!'], 400);
+ }
Auth::login($existing_user, true);
$cu = $this->hydrateCompanyUser();
- if ($cu->count() == 0)
+ if ($cu->count() == 0) {
return response()->json(['message' => 'User found, but not attached to any companies, please see your administrator'], 400);
+ }
- if (Ninja::isHosted() && !$cu->first()->is_owner && !$existing_user->account->isEnterpriseClient())
+ if (Ninja::isHosted() && ! $cu->first()->is_owner && ! $existing_user->account->isEnterpriseClient()) {
return response()->json(['message' => 'Pro / Free accounts only the owner can log in. Please upgrade'], 403);
+ }
return $this->timeConstrainedResponse($cu);
-
}
//If this is a result user/email combo - lets add their OAuth details details
if ($existing_login_user = MultiDB::hasUser(['email' => $user->email])) {
- if (!$existing_login_user->account)
+ if (! $existing_login_user->account) {
return response()->json(['message' => 'User exists, but not attached to any companies! Orphaned user!'], 400);
+ }
Auth::login($existing_login_user, true);
@@ -409,11 +404,13 @@ class LoginController extends BaseController
$cu = $this->hydrateCompanyUser();
- if ($cu->count() == 0)
+ if ($cu->count() == 0) {
return response()->json(['message' => 'User found, but not attached to any companies, please see your administrator'], 400);
+ }
- if (Ninja::isHosted() && !$cu->first()->is_owner && !$existing_login_user->account->isEnterpriseClient())
+ if (Ninja::isHosted() && ! $cu->first()->is_owner && ! $existing_login_user->account->isEnterpriseClient()) {
return response()->json(['message' => 'Pro / Free accounts only the owner can log in. Please upgrade'], 403);
+ }
return $this->timeConstrainedResponse($cu);
}
@@ -438,27 +435,28 @@ class LoginController extends BaseController
$cu = $this->hydrateCompanyUser();
- if ($cu->count() == 0)
+ if ($cu->count() == 0) {
return response()->json(['message' => 'User found, but not attached to any companies, please see your administrator'], 400);
+ }
- if (Ninja::isHosted() && !$cu->first()->is_owner && !auth()->user()->account->isEnterpriseClient())
+ if (Ninja::isHosted() && ! $cu->first()->is_owner && ! auth()->user()->account->isEnterpriseClient()) {
return response()->json(['message' => 'Pro / Free accounts only the owner can log in. Please upgrade'], 403);
+ }
return $this->timeConstrainedResponse($cu);
}
-
private function hydrateCompanyUser(): Builder
{
-
$cu = CompanyUser::query()->where('user_id', auth()->user()->id);
- if($cu->count() == 0)
+ if ($cu->count() == 0) {
return $cu;
+ }
- if (CompanyUser::query()->where('user_id', auth()->user()->id)->where('company_id', auth()->user()->account->default_company_id)->exists())
+ if (CompanyUser::query()->where('user_id', auth()->user()->id)->where('company_id', auth()->user()->account->default_company_id)->exists()) {
$set_company = auth()->user()->account->default_company;
- else {
+ } else {
$set_company = $cu->first()->company;
}
@@ -471,45 +469,39 @@ class LoginController extends BaseController
$truth->setUser(auth()->user());
$truth->setCompany($set_company);
- if($cu->count() == 0)
+ if ($cu->count() == 0) {
return $cu;
+ }
if (auth()->user()->company_users()->count() != auth()->user()->tokens()->distinct('company_id')->count()) {
-
auth()->user()->companies->each(function ($company) {
-
- if (!CompanyToken::where('user_id', auth()->user()->id)->where('company_id', $company->id)->exists()) {
-
- CreateCompanyToken::dispatchNow($company, auth()->user(), "Google_O_Auth");
-
+ if (! CompanyToken::where('user_id', auth()->user()->id)->where('company_id', $company->id)->exists()) {
+ CreateCompanyToken::dispatchNow($company, auth()->user(), 'Google_O_Auth');
}
-
- });
-
+ });
}
$truth->setCompanyToken(CompanyToken::where('user_id', auth()->user()->id)->where('company_id', $set_company->id)->first());
return $cu;
-
}
private function handleMicrosoftOauth()
{
- if(request()->has('accessToken'))
+ if (request()->has('accessToken')) {
$accessToken = request()->input('accessToken');
- else
+ } else {
return response()->json(['message' => 'Invalid response from oauth server'], 400);
+ }
$graph = new \Microsoft\Graph\Graph();
$graph->setAccessToken($accessToken);
- $user = $graph->createRequest("GET", "/me")
+ $user = $graph->createRequest('GET', '/me')
->setReturnType(Model\User::class)
->execute();
- if($user){
-
+ if ($user) {
$account = request()->input('account');
$email = $user->getMail() ?: $user->getUserPrincipalName();
@@ -519,18 +511,18 @@ class LoginController extends BaseController
];
if ($existing_user = MultiDB::hasUser($query)) {
-
- if(!$existing_user->account)
+ if (! $existing_user->account) {
return response()->json(['message' => 'User exists, but not attached to any companies! Orphaned user!'], 400);
+ }
return $this->existingOauthUser($existing_user);
}
//If this is a result user/email combo - lets add their OAuth details details
- if($existing_login_user = MultiDB::hasUser(['email' => $email]))
- {
- if(!$existing_login_user->account)
+ if ($existing_login_user = MultiDB::hasUser(['email' => $email])) {
+ if (! $existing_login_user->account) {
return response()->json(['message' => 'User exists, but not attached to any companies! Orphaned user!'], 400);
+ }
Auth::login($existing_login_user, true);
@@ -540,7 +532,7 @@ class LoginController extends BaseController
// Signup!
$new_account = [
'first_name' => $user->getGivenName() ?: '',
- 'last_name' => $user->getSurname() ?: '' ,
+ 'last_name' => $user->getSurname() ?: '',
'password' => '',
'email' => $email,
'oauth_user_id' => $user->getId(),
@@ -548,9 +540,7 @@ class LoginController extends BaseController
];
return $this->createNewAccount($new_account);
-
}
-
}
private function existingOauthUser($existing_user)
@@ -559,33 +549,35 @@ class LoginController extends BaseController
$cu = $this->hydrateCompanyUser();
- if($cu->count() == 0)
+ if ($cu->count() == 0) {
return response()->json(['message' => 'User found, but not attached to any companies, please see your administrator'], 400);
+ }
- if(Ninja::isHosted() && !$cu->first()->is_owner && !$existing_user->account->isEnterpriseClient())
+ if (Ninja::isHosted() && ! $cu->first()->is_owner && ! $existing_user->account->isEnterpriseClient()) {
return response()->json(['message' => 'Pro / Free accounts only the owner can log in. Please upgrade'], 403);
+ }
return $this->timeConstrainedResponse($cu);
}
private function existingLoginUser($oauth_user_id, $provider)
{
-
auth()->user()->update([
'oauth_user_id' => $oauth_user_id,
'oauth_provider_id'=> $provider,
- ]);
+ ]);
$cu = $this->hydrateCompanyUser();
- if($cu->count() == 0)
+ if ($cu->count() == 0) {
return response()->json(['message' => 'User found, but not attached to any companies, please see your administrator'], 400);
+ }
- if(Ninja::isHosted() && !$cu->first()->is_owner && !auth()->user()->account->isEnterpriseClient())
+ if (Ninja::isHosted() && ! $cu->first()->is_owner && ! auth()->user()->account->isEnterpriseClient()) {
return response()->json(['message' => 'Pro / Free accounts only the owner can log in. Please upgrade'], 403);
+ }
return $this->timeConstrainedResponse($cu);
-
}
private function handleGoogleOauth()
@@ -597,40 +589,38 @@ class LoginController extends BaseController
$user = $google->getTokenResponse(request()->input('id_token'));
if (is_array($user)) {
-
$query = [
'oauth_user_id' => $google->harvestSubField($user),
'oauth_provider_id'=> 'google',
];
if ($existing_user = MultiDB::hasUser($query)) {
-
- if(!$existing_user->account)
+ if (! $existing_user->account) {
return response()->json(['message' => 'User exists, but not attached to any companies! Orphaned user!'], 400);
+ }
return $this->existingOauthUser($existing_user);
}
//If this is a result user/email combo - lets add their OAuth details details
- if($existing_login_user = MultiDB::hasUser(['email' => $google->harvestEmail($user)]))
- {
- if(!$existing_login_user->account)
+ if ($existing_login_user = MultiDB::hasUser(['email' => $google->harvestEmail($user)])) {
+ if (! $existing_login_user->account) {
return response()->json(['message' => 'User exists, but not attached to any companies! Orphaned user!'], 400);
+ }
Auth::login($existing_login_user, true);
return $this->existingLoginUser($google->harvestSubField($user), 'google');
}
-
}
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)
+ if ($existing_login_user = MultiDB::hasUser(['email' => $google->harvestEmail($user)])) {
+ if (! $existing_login_user->account) {
return response()->json(['message' => 'User exists, but not attached to any companies! Orphaned user!'], 400);
+ }
Auth::login($existing_login_user, true);
@@ -660,13 +650,13 @@ class LoginController extends BaseController
private function createNewAccount($new_account)
{
-
MultiDB::setDefaultDatabase();
$account = CreateAccount::dispatchNow($new_account, request()->getClientIp());
- if(!$account instanceOf Account)
+ if (! $account instanceof Account) {
return $account;
+ }
Auth::login($account->default_company->owner(), true);
auth()->user()->email_verified_at = now();
@@ -674,40 +664,39 @@ class LoginController extends BaseController
$cu = $this->hydrateCompanyUser();
- if($cu->count() == 0)
+ if ($cu->count() == 0) {
return response()->json(['message' => 'User found, but not attached to any companies, please see your administrator'], 400);
+ }
- if(Ninja::isHosted() && !$cu->first()->is_owner && !auth()->user()->account->isEnterpriseClient())
+ if (Ninja::isHosted() && ! $cu->first()->is_owner && ! auth()->user()->account->isEnterpriseClient()) {
return response()->json(['message' => 'Pro / Free accounts only the owner can log in. Please upgrade'], 403);
+ }
return $this->timeConstrainedResponse($cu);
-
}
public function redirectToProvider(string $provider)
{
-
$scopes = [];
$parameters = [];
- if($provider == 'google'){
-
- $scopes = ['https://www.googleapis.com/auth/gmail.send','email','profile','openid'];
- $parameters = ['access_type' => 'offline', "prompt" => "consent select_account", 'redirect_uri' => config('ninja.app_url')."/auth/google"];
+ if ($provider == 'google') {
+ $scopes = ['https://www.googleapis.com/auth/gmail.send', 'email', 'profile', 'openid'];
+ $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.ReadWrite', 'Mail.Send', 'offline_access', 'profile', 'User.Read openid'];
- $parameters = ['response_type' => 'code', 'redirect_uri' => config('ninja.app_url')."/auth/microsoft"];
+ $parameters = ['response_type' => 'code', 'redirect_uri' => config('ninja.app_url').'/auth/microsoft'];
}
if (request()->has('code')) {
return $this->handleProviderCallback($provider);
} else {
-
- if(!in_array($provider, ['google','microsoft']))
+ if (! in_array($provider, ['google', 'microsoft'])) {
return abort(400, 'Invalid provider');
+ }
return Socialite::driver($provider)->with($parameters)->scopes($scopes)->redirect();
}
@@ -715,27 +704,23 @@ class LoginController extends BaseController
public function handleProviderCallback(string $provider)
{
-
- if($provider == 'microsoft')
+ if ($provider == 'microsoft') {
return $this->handleMicrosoftProviderCallback();
+ }
$socialite_user = Socialite::driver($provider)->user();
$oauth_user_token = '';
- if($socialite_user->refreshToken){
-
- $client = new Google_Client();
- $client->setClientId(config('ninja.auth.google.client_id'));
- $client->setClientSecret(config('ninja.auth.google.client_secret'));
- $client->fetchAccessTokenWithRefreshToken($socialite_user->refreshToken);
- $oauth_user_token = $client->getAccessToken();
-
- }
-
- if($user = OAuth::handleAuth($socialite_user, $provider))
- {
+ if ($socialite_user->refreshToken) {
+ $client = new Google_Client();
+ $client->setClientId(config('ninja.auth.google.client_id'));
+ $client->setClientSecret(config('ninja.auth.google.client_secret'));
+ $client->fetchAccessTokenWithRefreshToken($socialite_user->refreshToken);
+ $oauth_user_token = $client->getAccessToken();
+ }
+ if ($user = OAuth::handleAuth($socialite_user, $provider)) {
nlog('found user and updating their user record');
$name = OAuth::splitName($socialite_user->getName());
@@ -746,14 +731,12 @@ class LoginController extends BaseController
'oauth_user_id' => $socialite_user->getId(),
'oauth_provider_id' => $provider,
'oauth_user_token' => $oauth_user_token,
- 'oauth_user_refresh_token' => $socialite_user->refreshToken
+ 'oauth_user_refresh_token' => $socialite_user->refreshToken,
];
$user->update($update_user);
-
- }
- else {
- nlog("user not found for oauth");
+ } else {
+ nlog('user not found for oauth');
}
return redirect('/#/');
@@ -761,18 +744,15 @@ class LoginController extends BaseController
public function handleMicrosoftProviderCallback($provider = 'microsoft')
{
-
$socialite_user = Socialite::driver($provider)->user();
nlog($socialite_user);
- nlog("refresh token " . $socialite_user->accessTokenResponseBody['refresh_token']);
- nlog("access token " . $socialite_user->accessTokenResponseBody['access_token']);
+ nlog('refresh token '.$socialite_user->accessTokenResponseBody['refresh_token']);
+ nlog('access token '.$socialite_user->accessTokenResponseBody['access_token']);
$oauth_user_token = $socialite_user->accessTokenResponseBody['access_token'];
- 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());
@@ -783,18 +763,14 @@ class LoginController extends BaseController
'oauth_user_id' => $socialite_user->getId(),
'oauth_provider_id' => $provider,
'oauth_user_token' => $oauth_user_token,
- 'oauth_user_refresh_token' => $socialite_user->accessTokenResponseBody['refresh_token']
+ 'oauth_user_refresh_token' => $socialite_user->accessTokenResponseBody['refresh_token'],
];
$user->update($update_user);
-
- }
- else {
- nlog("user not found for oauth");
+ } else {
+ nlog('user not found for oauth');
}
return redirect('/#/');
-
}
-
}
diff --git a/app/Http/Controllers/Auth/ResetPasswordController.php b/app/Http/Controllers/Auth/ResetPasswordController.php
index 43b20fb795de..63b850d38c13 100644
--- a/app/Http/Controllers/Auth/ResetPasswordController.php
+++ b/app/Http/Controllers/Auth/ResetPasswordController.php
@@ -57,19 +57,18 @@ class ResetPasswordController extends Controller
public function showResetForm(Request $request, $token = null)
{
$company = false;
-
- if(Ninja::isHosted()){
+ if (Ninja::isHosted()) {
MultiDB::findAndSetDbByCompanyKey($request->session()->get('company_key'));
$company = Company::where('company_key', $request->session()->get('company_key'))->first();
-
}
- if($company)
+ if ($company) {
$account = $company->account;
- else
+ } else {
$account = Account::first();
-
+ }
+
return $this->render('auth.passwords.reset', ['root' => 'themes', 'token' => $token, 'account' => $account]);
}
diff --git a/app/Http/Controllers/Auth/VendorContactLoginController.php b/app/Http/Controllers/Auth/VendorContactLoginController.php
index 59fb20004e8f..212a2b2630be 100644
--- a/app/Http/Controllers/Auth/VendorContactLoginController.php
+++ b/app/Http/Controllers/Auth/VendorContactLoginController.php
@@ -40,7 +40,7 @@ class VendorContactLoginController extends Controller
public function catch()
{
$data = [
-
+
];
return $this->render('purchase_orders.catch');
@@ -53,6 +53,4 @@ class VendorContactLoginController extends Controller
return redirect('/vendors');
}
-
-
}
diff --git a/app/Http/Controllers/BaseController.php b/app/Http/Controllers/BaseController.php
index 9332df3876f6..116983609549 100644
--- a/app/Http/Controllers/BaseController.php
+++ b/app/Http/Controllers/BaseController.php
@@ -36,6 +36,7 @@ use League\Fractal\Serializer\JsonApiSerializer;
class BaseController extends Controller
{
use AppSetup;
+
/**
* Passed from the parent when we need to force
* includes internally rather than externally via
@@ -59,68 +60,68 @@ class BaseController extends Controller
protected $manager;
private $first_load = [
- 'account',
- 'user.company_user',
- 'token.company_user',
- 'company.activities',
- 'company.designs.company',
- 'company.task_statuses',
- 'company.expense_categories',
- 'company.documents',
- 'company.users.company_user',
- 'company.clients.contacts.company',
- 'company.clients.gateway_tokens',
- 'company.clients.documents',
- 'company.company_gateways.gateway',
- 'company.credits.invitations.contact',
- 'company.credits.invitations.company',
- 'company.credits.documents',
- 'company.expenses.documents',
- 'company.groups.documents',
- 'company.invoices.invitations.contact',
- 'company.invoices.invitations.company',
- 'company.invoices.documents',
- 'company.products',
- 'company.products.documents',
- 'company.payments.paymentables',
- 'company.payments.documents',
- 'company.purchase_orders.documents',
- 'company.payment_terms.company',
- 'company.projects.documents',
- 'company.recurring_expenses',
- 'company.recurring_invoices',
- 'company.recurring_invoices.invitations.contact',
- 'company.recurring_invoices.invitations.company',
- 'company.recurring_invoices.documents',
- 'company.quotes.invitations.contact',
- 'company.quotes.invitations.company',
- 'company.quotes.documents',
- 'company.tasks.documents',
- 'company.subscriptions',
- 'company.tax_rates',
- 'company.tokens_hashed',
- 'company.vendors.contacts.company',
- 'company.vendors.documents',
- 'company.webhooks',
- 'company.system_logs',
- ];
+ 'account',
+ 'user.company_user',
+ 'token.company_user',
+ 'company.activities',
+ 'company.designs.company',
+ 'company.task_statuses',
+ 'company.expense_categories',
+ 'company.documents',
+ 'company.users.company_user',
+ 'company.clients.contacts.company',
+ 'company.clients.gateway_tokens',
+ 'company.clients.documents',
+ 'company.company_gateways.gateway',
+ 'company.credits.invitations.contact',
+ 'company.credits.invitations.company',
+ 'company.credits.documents',
+ 'company.expenses.documents',
+ 'company.groups.documents',
+ 'company.invoices.invitations.contact',
+ 'company.invoices.invitations.company',
+ 'company.invoices.documents',
+ 'company.products',
+ 'company.products.documents',
+ 'company.payments.paymentables',
+ 'company.payments.documents',
+ 'company.purchase_orders.documents',
+ 'company.payment_terms.company',
+ 'company.projects.documents',
+ 'company.recurring_expenses',
+ 'company.recurring_invoices',
+ 'company.recurring_invoices.invitations.contact',
+ 'company.recurring_invoices.invitations.company',
+ 'company.recurring_invoices.documents',
+ 'company.quotes.invitations.contact',
+ 'company.quotes.invitations.company',
+ 'company.quotes.documents',
+ 'company.tasks.documents',
+ 'company.subscriptions',
+ 'company.tax_rates',
+ 'company.tokens_hashed',
+ 'company.vendors.contacts.company',
+ 'company.vendors.documents',
+ 'company.webhooks',
+ 'company.system_logs',
+ ];
private $mini_load = [
- 'account',
- 'user.company_user',
- 'token',
- 'company.activities',
- 'company.tax_rates',
- 'company.documents',
- 'company.company_gateways.gateway',
- 'company.users.company_user',
- 'company.task_statuses',
- 'company.payment_terms',
- 'company.groups',
- 'company.designs.company',
- 'company.expense_categories',
- 'company.subscriptions',
- ];
+ 'account',
+ 'user.company_user',
+ 'token',
+ 'company.activities',
+ 'company.tax_rates',
+ 'company.documents',
+ 'company.company_gateways.gateway',
+ 'company.users.company_user',
+ 'company.task_statuses',
+ 'company.payment_terms',
+ 'company.groups',
+ 'company.designs.company',
+ 'company.expense_categories',
+ 'company.subscriptions',
+ ];
public function __construct()
{
@@ -215,159 +216,160 @@ class BaseController extends Controller
$transformer = new $this->entity_transformer($this->serializer);
$updated_at = request()->has('updated_at') ? request()->input('updated_at') : 0;
- if ($user->getCompany()->is_large && $updated_at == 0){
- $updated_at = time();
+ if ($user->getCompany()->is_large && $updated_at == 0) {
+ $updated_at = time();
}
$updated_at = date('Y-m-d H:i:s', $updated_at);
$query->with(
[
- 'company' => function ($query) use ($updated_at, $user) {
- $query->whereNotNull('updated_at')->with('documents','users');
- },
- 'company.clients' => function ($query) use ($updated_at, $user) {
- $query->where('clients.updated_at', '>=', $updated_at)->with('contacts.company', 'gateway_tokens', 'documents');
+ 'company' => function ($query) use ($updated_at, $user) {
+ $query->whereNotNull('updated_at')->with('documents', 'users');
+ },
+ 'company.clients' => function ($query) use ($updated_at, $user) {
+ $query->where('clients.updated_at', '>=', $updated_at)->with('contacts.company', 'gateway_tokens', 'documents');
- if(!$user->hasPermission('view_client'))
- $query->where('clients.user_id', $user->id)->orWhere('clients.assigned_user_id', $user->id);
+ if (! $user->hasPermission('view_client')) {
+ $query->where('clients.user_id', $user->id)->orWhere('clients.assigned_user_id', $user->id);
+ }
+ },
+ 'company.company_gateways' => function ($query) use ($user) {
+ $query->whereNotNull('updated_at')->with('gateway');
- },
- 'company.company_gateways' => function ($query) use ($user) {
- $query->whereNotNull('updated_at')->with('gateway');
+ if (! $user->isAdmin()) {
+ $query->where('company_gateways.user_id', $user->id);
+ }
+ },
+ 'company.credits'=> function ($query) use ($updated_at, $user) {
+ $query->where('updated_at', '>=', $updated_at)->with('invitations', 'documents');
- if(!$user->isAdmin())
- $query->where('company_gateways.user_id', $user->id);
+ if (! $user->hasPermission('view_credit')) {
+ $query->where('credits.user_id', $user->id)->orWhere('credits.assigned_user_id', $user->id);
+ }
+ },
+ 'company.designs'=> function ($query) use ($updated_at, $user) {
+ $query->where('updated_at', '>=', $updated_at)->with('company');
- },
- 'company.credits'=> function ($query) use ($updated_at, $user) {
- $query->where('updated_at', '>=', $updated_at)->with('invitations', 'documents');
+ if (! $user->isAdmin()) {
+ $query->where('designs.user_id', $user->id);
+ }
+ },
+ 'company.documents'=> function ($query) use ($updated_at, $user) {
+ $query->where('updated_at', '>=', $updated_at);
+ },
+ 'company.expenses'=> function ($query) use ($updated_at, $user) {
+ $query->where('updated_at', '>=', $updated_at)->with('documents');
- if(!$user->hasPermission('view_credit'))
- $query->where('credits.user_id', $user->id)->orWhere('credits.assigned_user_id', $user->id);
-
- },
- 'company.designs'=> function ($query) use ($updated_at, $user) {
- $query->where('updated_at', '>=', $updated_at)->with('company');
-
- if(!$user->isAdmin())
- $query->where('designs.user_id', $user->id);
- },
- 'company.documents'=> function ($query) use ($updated_at, $user) {
- $query->where('updated_at', '>=', $updated_at);
- },
- 'company.expenses'=> function ($query) use ($updated_at, $user) {
- $query->where('updated_at', '>=', $updated_at)->with('documents');
-
- if(!$user->hasPermission('view_expense'))
- $query->where('expenses.user_id', $user->id)->orWhere('expenses.assigned_user_id', $user->id);
- },
- 'company.groups' => function ($query) use ($updated_at, $user) {
- $query->whereNotNull('updated_at')->with('documents');
+ if (! $user->hasPermission('view_expense')) {
+ $query->where('expenses.user_id', $user->id)->orWhere('expenses.assigned_user_id', $user->id);
+ }
+ },
+ 'company.groups' => function ($query) use ($updated_at, $user) {
+ $query->whereNotNull('updated_at')->with('documents');
// if(!$user->isAdmin())
- // $query->where('group_settings.user_id', $user->id);
- },
- 'company.invoices'=> function ($query) use ($updated_at, $user) {
- $query->where('updated_at', '>=', $updated_at)->with('invitations', 'documents');
+ // $query->where('group_settings.user_id', $user->id);
+ },
+ 'company.invoices'=> function ($query) use ($updated_at, $user) {
+ $query->where('updated_at', '>=', $updated_at)->with('invitations', 'documents');
- if(!$user->hasPermission('view_invoice'))
- $query->where('invoices.user_id', $user->id)->orWhere('invoices.assigned_user_id', $user->id);
+ if (! $user->hasPermission('view_invoice')) {
+ $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');
- },
- 'company.payments'=> function ($query) use ($updated_at, $user) {
- $query->where('updated_at', '>=', $updated_at)->with('paymentables', 'documents');
+ if (! $user->hasPermission('view_payment')) {
+ $query->where('payments.user_id', $user->id)->orWhere('payments.assigned_user_id', $user->id);
+ }
+ },
+ 'company.payment_terms'=> function ($query) use ($updated_at, $user) {
+ $query->whereNotNull('updated_at');
- if(!$user->hasPermission('view_payment'))
- $query->where('payments.user_id', $user->id)->orWhere('payments.assigned_user_id', $user->id);
+ if (! $user->isAdmin()) {
+ $query->where('payment_terms.user_id', $user->id);
+ }
+ },
+ 'company.products' => function ($query) use ($updated_at, $user) {
+ $query->where('updated_at', '>=', $updated_at)->with('documents');
- },
- 'company.payment_terms'=> function ($query) use ($updated_at, $user) {
- $query->whereNotNull('updated_at');
+ if (! $user->hasPermission('view_product')) {
+ $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->isAdmin())
- $query->where('payment_terms.user_id', $user->id);
+ if (! $user->hasPermission('view_project')) {
+ $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');
- },
- 'company.products' => function ($query) use ($updated_at, $user) {
- $query->where('updated_at', '>=', $updated_at)->with('documents');
+ if (! $user->hasPermission('view_purchase_order')) {
+ $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_product'))
- $query->where('products.user_id', $user->id)->orWhere('products.assigned_user_id', $user->id);
+ if (! $user->hasPermission('view_quote')) {
+ $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');
- },
- 'company.projects'=> function ($query) use ($updated_at, $user) {
- $query->where('updated_at', '>=', $updated_at)->with('documents');
+ if (! $user->hasPermission('view_recurring_invoice')) {
+ $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_project'))
- $query->where('projects.user_id', $user->id)->orWhere('projects.assigned_user_id', $user->id);
+ if (! $user->hasPermission('view_recurring_expense')) {
+ $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');
- },
- 'company.purchase_orders'=> function ($query) use ($updated_at, $user) {
- $query->where('updated_at', '>=', $updated_at)->with('documents');
+ if (! $user->hasPermission('view_task')) {
+ $query->where('tasks.user_id', $user->id)->orWhere('tasks.assigned_user_id', $user->id);
+ }
+ },
+ 'company.tax_rates'=> function ($query) use ($updated_at, $user) {
+ $query->whereNotNull('updated_at');
+ },
+ 'company.vendors'=> function ($query) use ($updated_at, $user) {
+ $query->where('updated_at', '>=', $updated_at)->with('contacts', 'documents');
- if(!$user->hasPermission('view_purchase_order'))
- $query->where('purchase_orders.user_id', $user->id)->orWhere('purchase_orders.assigned_user_id', $user->id);
+ if (! $user->hasPermission('view_vendor')) {
+ $query->where('vendors.user_id', $user->id)->orWhere('vendors.assigned_user_id', $user->id);
+ }
+ },
+ 'company.expense_categories'=> function ($query) use ($updated_at, $user) {
+ $query->whereNotNull('updated_at');
+ },
+ 'company.task_statuses'=> function ($query) use ($updated_at, $user) {
+ $query->whereNotNull('updated_at');
+ },
+ 'company.activities'=> function ($query) use ($user) {
+ if (! $user->isAdmin()) {
+ $query->where('activities.user_id', $user->id);
+ }
+ },
+ 'company.subscriptions'=> function ($query) use ($updated_at, $user) {
+ $query->whereNotNull('updated_at');
- },
- 'company.quotes'=> function ($query) use ($updated_at, $user) {
- $query->where('updated_at', '>=', $updated_at)->with('invitations', 'documents');
-
- if(!$user->hasPermission('view_quote'))
- $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->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->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->where('tasks.user_id', $user->id)->orWhere('tasks.assigned_user_id', $user->id);
-
- },
- 'company.tax_rates'=> function ($query) use ($updated_at, $user) {
- $query->whereNotNull('updated_at');
- },
- 'company.vendors'=> function ($query) use ($updated_at, $user) {
- $query->where('updated_at', '>=', $updated_at)->with('contacts', 'documents');
-
- if(!$user->hasPermission('view_vendor'))
- $query->where('vendors.user_id', $user->id)->orWhere('vendors.assigned_user_id', $user->id);
-
- },
- 'company.expense_categories'=> function ($query) use ($updated_at, $user) {
- $query->whereNotNull('updated_at');
- },
- 'company.task_statuses'=> function ($query) use ($updated_at, $user) {
- $query->whereNotNull('updated_at');
- },
- 'company.activities'=> function ($query) use($user) {
-
- if(!$user->isAdmin())
- $query->where('activities.user_id', $user->id);
-
- },
- 'company.subscriptions'=> function ($query) use($updated_at, $user) {
- $query->whereNotNull('updated_at');
-
- if(!$user->isAdmin())
- $query->where('subscriptions.user_id', $user->id);
-
- }
- ]
+ if (! $user->isAdmin()) {
+ $query->where('subscriptions.user_id', $user->id);
+ }
+ },
+ ]
);
if ($query instanceof Builder) {
@@ -386,8 +388,7 @@ class BaseController extends Controller
protected function miniLoadResponse($query)
{
- $user = auth()->user();
-
+ $user = auth()->user();
$this->serializer = request()->input('serializer') ?: EntityTransformer::API_SERIALIZER_ARRAY;
@@ -404,35 +405,30 @@ class BaseController extends Controller
$query->with(
[
- 'company' => function ($query) use ($created_at, $user) {
- $query->whereNotNull('created_at')->with('documents','users');
- },
- 'company.designs'=> function ($query) use ($created_at, $user) {
- $query->where('created_at', '>=', $created_at)->with('company');
-
- },
- 'company.documents'=> function ($query) use ($created_at, $user) {
- $query->where('created_at', '>=', $created_at);
- },
- 'company.groups'=> function ($query) use ($created_at, $user) {
- $query->where('created_at', '>=', $created_at)->with('documents');
-
- },
- 'company.payment_terms'=> function ($query) use ($created_at, $user) {
- $query->where('created_at', '>=', $created_at);
-
- },
- 'company.tax_rates'=> function ($query) use ($created_at, $user) {
- $query->whereNotNull('created_at');
-
- },
- 'company.activities'=> function ($query) use($user) {
-
- if(!$user->isAdmin())
- $query->where('activities.user_id', $user->id);
-
- }
- ]
+ 'company' => function ($query) use ($created_at, $user) {
+ $query->whereNotNull('created_at')->with('documents', 'users');
+ },
+ 'company.designs'=> function ($query) use ($created_at, $user) {
+ $query->where('created_at', '>=', $created_at)->with('company');
+ },
+ 'company.documents'=> function ($query) use ($created_at, $user) {
+ $query->where('created_at', '>=', $created_at);
+ },
+ 'company.groups'=> function ($query) use ($created_at, $user) {
+ $query->where('created_at', '>=', $created_at)->with('documents');
+ },
+ 'company.payment_terms'=> function ($query) use ($created_at, $user) {
+ $query->where('created_at', '>=', $created_at);
+ },
+ 'company.tax_rates'=> function ($query) use ($created_at, $user) {
+ $query->whereNotNull('created_at');
+ },
+ 'company.activities'=> function ($query) use ($user) {
+ if (! $user->isAdmin()) {
+ $query->where('activities.user_id', $user->id);
+ }
+ },
+ ]
);
if ($query instanceof Builder) {
@@ -447,21 +443,19 @@ class BaseController extends Controller
}
return $this->response($this->manager->createData($resource)->toArray());
-
-
}
protected function timeConstrainedResponse($query)
{
-
$user = auth()->user();
- if ($user->getCompany()->is_large){
- $this->manager->parseIncludes($this->mini_load);
- return $this->miniLoadResponse($query);
+ if ($user->getCompany()->is_large) {
+ $this->manager->parseIncludes($this->mini_load);
+
+ return $this->miniLoadResponse($query);
+ } else {
+ $this->manager->parseIncludes($this->first_load);
}
- else
- $this->manager->parseIncludes($this->first_load);
$this->serializer = request()->input('serializer') ?: EntityTransformer::API_SERIALIZER_ARRAY;
@@ -478,153 +472,147 @@ class BaseController extends Controller
$query->with(
[
- 'company' => function ($query) use ($created_at, $user) {
- $query->whereNotNull('created_at')->with('documents','users');
- },
- 'company.clients' => function ($query) use ($created_at, $user) {
- $query->where('clients.created_at', '>=', $created_at)->with('contacts.company', 'gateway_tokens', 'documents');
+ 'company' => function ($query) use ($created_at, $user) {
+ $query->whereNotNull('created_at')->with('documents', 'users');
+ },
+ 'company.clients' => function ($query) use ($created_at, $user) {
+ $query->where('clients.created_at', '>=', $created_at)->with('contacts.company', 'gateway_tokens', 'documents');
- if(!$user->hasPermission('view_client'))
- $query->where('clients.user_id', $user->id)->orWhere('clients.assigned_user_id', $user->id);
+ if (! $user->hasPermission('view_client')) {
+ $query->where('clients.user_id', $user->id)->orWhere('clients.assigned_user_id', $user->id);
+ }
+ },
+ 'company.company_gateways' => function ($query) use ($user) {
+ $query->whereNotNull('created_at')->with('gateway');
- },
- 'company.company_gateways' => function ($query) use ($user) {
- $query->whereNotNull('created_at')->with('gateway');
+ if (! $user->isAdmin()) {
+ $query->where('company_gateways.user_id', $user->id);
+ }
+ },
+ 'company.credits'=> function ($query) use ($created_at, $user) {
+ $query->where('created_at', '>=', $created_at)->with('invitations', 'documents');
- if(!$user->isAdmin())
- $query->where('company_gateways.user_id', $user->id);
+ if (! $user->hasPermission('view_credit')) {
+ $query->where('credits.user_id', $user->id)->orWhere('credits.assigned_user_id', $user->id);
+ }
+ },
+ 'company.documents'=> function ($query) use ($created_at, $user) {
+ $query->where('created_at', '>=', $created_at);
+ },
+ 'company.expenses'=> function ($query) use ($created_at, $user) {
+ $query->where('created_at', '>=', $created_at)->with('documents');
- },
- 'company.credits'=> function ($query) use ($created_at, $user) {
- $query->where('created_at', '>=', $created_at)->with('invitations', 'documents');
+ if (! $user->hasPermission('view_expense')) {
+ $query->where('expenses.user_id', $user->id)->orWhere('expenses.assigned_user_id', $user->id);
+ }
+ },
+ 'company.groups' => function ($query) use ($created_at, $user) {
+ $query->where('created_at', '>=', $created_at)->with('documents');
+ },
+ 'company.invoices'=> function ($query) use ($created_at, $user) {
+ $query->where('created_at', '>=', $created_at)->with('invitations', 'documents');
- if(!$user->hasPermission('view_credit'))
- $query->where('credits.user_id', $user->id)->orWhere('credits.assigned_user_id', $user->id);
+ if (! $user->hasPermission('view_invoice')) {
+ $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');
- },
- 'company.documents'=> function ($query) use ($created_at, $user) {
- $query->where('created_at', '>=', $created_at);
- },
- 'company.expenses'=> function ($query) use ($created_at, $user) {
- $query->where('created_at', '>=', $created_at)->with('documents');
+ if (! $user->hasPermission('view_payment')) {
+ $query->where('payments.user_id', $user->id)->orWhere('payments.assigned_user_id', $user->id);
+ }
+ },
+ 'company.payment_terms'=> function ($query) use ($created_at, $user) {
+ $query->where('created_at', '>=', $created_at);
+ },
+ 'company.products' => function ($query) use ($created_at, $user) {
+ $query->where('created_at', '>=', $created_at)->with('documents');
- if(!$user->hasPermission('view_expense'))
- $query->where('expenses.user_id', $user->id)->orWhere('expenses.assigned_user_id', $user->id);
- },
- 'company.groups' => function ($query) use ($created_at, $user) {
- $query->where('created_at', '>=', $created_at)->with('documents');
- },
- 'company.invoices'=> function ($query) use ($created_at, $user) {
- $query->where('created_at', '>=', $created_at)->with('invitations', 'documents');
+ if (! $user->hasPermission('view_product')) {
+ $query->where('products.user_id', $user->id)->orWhere('products.assigned_user_id', $user->id);
+ }
+ },
+ 'company.projects'=> function ($query) use ($created_at, $user) {
+ $query->where('created_at', '>=', $created_at)->with('documents');
- if(!$user->hasPermission('view_invoice'))
- $query->where('invoices.user_id', $user->id)->orWhere('invoices.assigned_user_id', $user->id);
+ if (! $user->hasPermission('view_project')) {
+ $query->where('projects.user_id', $user->id)->orWhere('projects.assigned_user_id', $user->id);
+ }
+ },
+ 'company.purchase_orders'=> function ($query) use ($created_at, $user) {
+ $query->where('created_at', '>=', $created_at)->with('documents');
- },
- 'company.payments'=> function ($query) use ($created_at, $user) {
- $query->where('created_at', '>=', $created_at)->with('paymentables', 'documents');
+ if (! $user->hasPermission('view_purchase_order')) {
+ $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_payment'))
- $query->where('payments.user_id', $user->id)->orWhere('payments.assigned_user_id', $user->id);
+ if (! $user->hasPermission('view_quote')) {
+ $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');
- },
- 'company.payment_terms'=> function ($query) use ($created_at, $user) {
- $query->where('created_at', '>=', $created_at);
+ if (! $user->hasPermission('view_recurring_invoice')) {
+ $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->where('tasks.user_id', $user->id)->orWhere('tasks.assigned_user_id', $user->id);
+ }
+ },
+ 'company.tax_rates' => function ($query) use ($created_at, $user) {
+ $query->where('created_at', '>=', $created_at);
+ },
+ 'company.vendors'=> function ($query) use ($created_at, $user) {
+ $query->where('created_at', '>=', $created_at)->with('contacts', 'documents');
- },
- 'company.products' => function ($query) use ($created_at, $user) {
- $query->where('created_at', '>=', $created_at)->with('documents');
+ if (! $user->hasPermission('view_vendor')) {
+ $query->where('vendors.user_id', $user->id)->orWhere('vendors.assigned_user_id', $user->id);
+ }
+ },
+ 'company.expense_categories'=> function ($query) use ($created_at, $user) {
+ $query->whereNotNull('created_at');
+ },
+ 'company.task_statuses'=> function ($query) use ($created_at, $user) {
+ $query->where('created_at', '>=', $created_at);
+ },
+ 'company.activities'=> function ($query) use ($user) {
+ if (! $user->isAdmin()) {
+ $query->where('activities.user_id', $user->id);
+ }
+ },
+ 'company.webhooks'=> function ($query) use ($user) {
+ if (! $user->isAdmin()) {
+ $query->where('webhooks.user_id', $user->id);
+ }
+ },
+ 'company.tokens'=> function ($query) use ($user) {
+ $query->where('company_tokens.user_id', $user->id);
+ },
+ 'company.system_logs',
+ 'company.subscriptions'=> function ($query) use ($created_at, $user) {
+ $query->where('created_at', '>=', $created_at);
- if(!$user->hasPermission('view_product'))
- $query->where('products.user_id', $user->id)->orWhere('products.assigned_user_id', $user->id);
+ if (! $user->isAdmin()) {
+ $query->where('subscriptions.user_id', $user->id);
+ }
+ },
+ 'company.recurring_expenses'=> function ($query) use ($created_at, $user) {
+ $query->where('created_at', '>=', $created_at)->with('documents');
- },
- 'company.projects'=> function ($query) use ($created_at, $user) {
- $query->where('created_at', '>=', $created_at)->with('documents');
-
- if(!$user->hasPermission('view_project'))
- $query->where('projects.user_id', $user->id)->orWhere('projects.assigned_user_id', $user->id);
-
- },
- 'company.purchase_orders'=> function ($query) use ($created_at, $user) {
- $query->where('created_at', '>=', $created_at)->with('documents');
-
- if(!$user->hasPermission('view_purchase_order'))
- $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->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->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->where('tasks.user_id', $user->id)->orWhere('tasks.assigned_user_id', $user->id);
-
- },
- 'company.tax_rates' => function ($query) use ($created_at, $user) {
- $query->where('created_at', '>=', $created_at);
-
- },
- 'company.vendors'=> function ($query) use ($created_at, $user) {
- $query->where('created_at', '>=', $created_at)->with('contacts', 'documents');
-
- if(!$user->hasPermission('view_vendor'))
- $query->where('vendors.user_id', $user->id)->orWhere('vendors.assigned_user_id', $user->id);
-
- },
- 'company.expense_categories'=> function ($query) use ($created_at, $user) {
- $query->whereNotNull('created_at');
-
- },
- 'company.task_statuses'=> function ($query) use ($created_at, $user) {
- $query->where('created_at', '>=', $created_at);
-
- },
- 'company.activities'=> function ($query) use($user) {
-
- if(!$user->isAdmin())
- $query->where('activities.user_id', $user->id);
-
- },
- 'company.webhooks'=> function ($query) use($user) {
-
- if(!$user->isAdmin())
- $query->where('webhooks.user_id', $user->id);
-
- },
- 'company.tokens'=> function ($query) use($user) {
- $query->where('company_tokens.user_id', $user->id);
- },
- 'company.system_logs',
- 'company.subscriptions'=> function ($query) use($created_at, $user) {
- $query->where('created_at', '>=', $created_at);
-
- if(!$user->isAdmin())
- $query->where('subscriptions.user_id', $user->id);
-
- },
- 'company.recurring_expenses'=> function ($query) use ($created_at, $user) {
- $query->where('created_at', '>=', $created_at)->with('documents');
-
- if(!$user->hasPermission('view_recurring_expense'))
- $query->where('recurring_expenses.user_id', $user->id)->orWhere('recurring_expenses.assigned_user_id', $user->id);
-
- },
- ]
+ if (! $user->hasPermission('view_recurring_expense')) {
+ $query->where('recurring_expenses.user_id', $user->id)->orWhere('recurring_expenses.assigned_user_id', $user->id);
+ }
+ },
+ ]
);
if ($query instanceof Builder) {
@@ -639,13 +627,10 @@ class BaseController extends Controller
}
return $this->response($this->manager->createData($resource)->toArray());
-
-
}
protected function listResponse($query)
{
-
$this->buildManager();
$transformer = new $this->entity_transformer(request()->input('serializer'));
@@ -736,9 +721,9 @@ class BaseController extends Controller
public static function getApiHeaders($count = 0)
{
return [
- 'Content-Type' => 'application/json',
- 'X-Api-Version' => config('ninja.minimum_client_version'),
- 'X-App-Version' => config('ninja.app_version'),
+ 'Content-Type' => 'application/json',
+ 'X-Api-Version' => config('ninja.minimum_client_version'),
+ 'X-App-Version' => config('ninja.app_version'),
];
}
@@ -778,8 +763,9 @@ class BaseController extends Controller
}
/* Clean up URLs and remove query parameters from the URL*/
- if(request()->has('login') && request()->input('login') == 'true')
- return redirect('/')->with(['login' => "true"]);
+ if (request()->has('login') && request()->input('login') == 'true') {
+ return redirect('/')->with(['login' => 'true']);
+ }
$data = [];
@@ -789,10 +775,11 @@ class BaseController extends Controller
//pass referral code to front end
$data['rc'] = request()->has('rc') ? request()->input('rc') : '';
$data['build'] = request()->has('build') ? request()->input('build') : '';
- $data['login'] = request()->has('login') ? request()->input('login') : "false";
-
- if(request()->session()->has('login'))
- $data['login'] = "true";
+ $data['login'] = request()->has('login') ? request()->input('login') : 'false';
+
+ if (request()->session()->has('login')) {
+ $data['login'] = 'true';
+ }
$data['user_agent'] = request()->server('HTTP_USER_AGENT');
@@ -800,11 +787,11 @@ class BaseController extends Controller
$this->buildCache();
- if(Ninja::isSelfHost() && $account->set_react_as_default_ap)
+ if (Ninja::isSelfHost() && $account->set_react_as_default_ap) {
return response()->view('react.index', $data)->header('X-Frame-Options', 'SAMEORIGIN', false);
- else
+ } else {
return response()->view('index.index', $data)->header('X-Frame-Options', 'SAMEORIGIN', false);
-
+ }
}
return redirect('/setup');
@@ -814,10 +801,9 @@ class BaseController extends Controller
{
$build = '';
- if(request()->has('build')) {
+ if (request()->has('build')) {
$build = request()->input('build');
- }
- elseif(Ninja::isHosted()){
+ } elseif (Ninja::isHosted()) {
return 'main.dart.js';
}
@@ -829,29 +815,28 @@ class BaseController extends Controller
case 'last':
return 'main.last.dart.js';
case 'next':
- return 'main.next.dart.js';
+ return 'main.next.dart.js';
case 'profile':
- return 'main.profile.dart.js';
- case 'html':
- return 'main.html.dart.js';
+ return 'main.profile.dart.js';
+ case 'html':
+ return 'main.html.dart.js';
default:
return 'main.foss.dart.js';
}
-
}
public function checkFeature($feature)
{
+ if (auth()->user()->account->hasFeature($feature)) {
+ return true;
+ }
- if(auth()->user()->account->hasFeature($feature))
- return true;
-
- return false;
+ return false;
}
public function featureFailure()
{
- return response()->json(['message' => 'Upgrade to a paid plan for this feature.'], 403);
+ return response()->json(['message' => 'Upgrade to a paid plan for this feature.'], 403);
}
}
diff --git a/app/Http/Controllers/ChartController.php b/app/Http/Controllers/ChartController.php
index 2e39aa4fd736..8dac67dafdf4 100644
--- a/app/Http/Controllers/ChartController.php
+++ b/app/Http/Controllers/ChartController.php
@@ -18,7 +18,6 @@ use Illuminate\Http\Response;
class ChartController extends BaseController
{
-
public function __construct()
{
parent::__construct();
@@ -81,5 +80,4 @@ class ChartController extends BaseController
return response()->json($cs->chart_summary($request->input('start_date'), $request->input('end_date')), 200);
}
-
}
diff --git a/app/Http/Controllers/ClientController.php b/app/Http/Controllers/ClientController.php
index bb41cd22451e..565db70058bf 100644
--- a/app/Http/Controllers/ClientController.php
+++ b/app/Http/Controllers/ClientController.php
@@ -38,6 +38,7 @@ use App\Utils\Traits\Uploadable;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Storage;
+
/**
* Class ClientController.
* @covers App\Http\Controllers\ClientController
@@ -277,7 +278,6 @@ class ClientController extends BaseController
*/
public function update(UpdateClientRequest $request, Client $client)
{
-
if ($request->entityIsDeleted($client)) {
return $request->disallowUpdate();
}
@@ -383,10 +383,8 @@ class ClientController extends BaseController
$client->load('contacts', 'primary_contact');
/* Set the client country to the company if none is set */
- if(!$client->country_id && strlen($client->company->settings->country_id) > 1){
-
+ if (! $client->country_id && strlen($client->company->settings->country_id) > 1) {
$client->update(['country_id' => $client->company->settings->country_id]);
-
}
$this->uploadLogo($request->file('company_logo'), $client->company, $client);
@@ -448,11 +446,9 @@ class ClientController extends BaseController
*/
public function destroy(DestroyClientRequest $request, Client $client)
{
+ $this->client_repo->delete($client);
- $this->client_repo->delete($client);
-
- return $this->itemResponse($client->fresh());
-
+ return $this->itemResponse($client->fresh());
}
/**
@@ -513,8 +509,9 @@ class ClientController extends BaseController
$ids = request()->input('ids');
$clients = Client::withTrashed()->whereIn('id', $this->transformKeys($ids))->cursor();
- if(!in_array($action, ['restore','archive','delete']))
+ if (! in_array($action, ['restore', 'archive', 'delete'])) {
return response()->json(['message' => 'That action is not available.'], 400);
+ }
$clients->each(function ($client, $key) use ($action) {
if (auth()->user()->can('edit', $client)) {
@@ -578,15 +575,15 @@ class ClientController extends BaseController
*/
public function upload(UploadClientRequest $request, Client $client)
{
-
- 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'), $client);
+ }
return $this->itemResponse($client->fresh());
-
}
/**
@@ -642,10 +639,8 @@ class ClientController extends BaseController
public function purge(PurgeClientRequest $request, Client $client)
{
//delete all documents
- $client->documents->each(function ($document){
-
+ $client->documents->each(function ($document) {
Storage::disk(config('filesystems.default'))->delete($document->url);
-
});
//force delete the client
@@ -655,5 +650,4 @@ class ClientController extends BaseController
//todo add an event here using the client name as reference for purge event
}
-
}
diff --git a/app/Http/Controllers/ClientGatewayTokenController.php b/app/Http/Controllers/ClientGatewayTokenController.php
index 83242b744691..44912c5647a4 100644
--- a/app/Http/Controllers/ClientGatewayTokenController.php
+++ b/app/Http/Controllers/ClientGatewayTokenController.php
@@ -273,7 +273,6 @@ class ClientGatewayTokenController extends BaseController
*/
public function update(UpdateClientGatewayTokenRequest $request, ClientGatewayToken $client_gateway_token)
{
-
$client_gateway_token = $this->client_gateway_token_repo->save($request->all(), $client_gateway_token);
return $this->itemResponse($client_gateway_token->fresh());
@@ -427,11 +426,8 @@ class ClientGatewayTokenController extends BaseController
*/
public function destroy(DestroyClientGatewayTokenRequest $request, ClientGatewayToken $client_gateway_token)
{
+ $this->client_gateway_token_repo->delete($client_gateway_token);
- $this->client_gateway_token_repo->delete($client_gateway_token);
-
- return $this->itemResponse($client_gateway_token->fresh());
-
+ return $this->itemResponse($client_gateway_token->fresh());
}
-
}
diff --git a/app/Http/Controllers/ClientPortal/ApplePayDomainController.php b/app/Http/Controllers/ClientPortal/ApplePayDomainController.php
index 2565c7f57942..199f500016e4 100644
--- a/app/Http/Controllers/ClientPortal/ApplePayDomainController.php
+++ b/app/Http/Controllers/ClientPortal/ApplePayDomainController.php
@@ -21,7 +21,6 @@ use Illuminate\Support\Facades\Storage;
class ApplePayDomainController extends Controller
{
-
private array $stripe_keys = ['d14dd26a47cecc30fdd65700bfb67b34', 'd14dd26a37cecc30fdd65700bfb55b23'];
public function showAppleMerchantId(Request $request)
@@ -29,20 +28,15 @@ class ApplePayDomainController extends Controller
/* Self Host */
- if(Ninja::isSelfHost()){
-
+ if (Ninja::isSelfHost()) {
$cgs = CompanyGateway::whereIn('gateway_key', $this->stripe_keys)
->where('is_deleted', false)
->get();
- foreach($cgs as $cg)
- {
-
- if($cg->getConfigField('appleDomainVerification')){
- return response($cg->getConfigField('appleDomainVerification'),200);
-
+ foreach ($cgs as $cg) {
+ if ($cg->getConfigField('appleDomainVerification')) {
+ return response($cg->getConfigField('appleDomainVerification'), 200);
}
-
}
return response('', 400);
@@ -52,52 +46,44 @@ class ApplePayDomainController extends Controller
$domain_name = $request->getHost();
- if (strpos($domain_name, 'invoicing.co') !== false)
- {
+ if (strpos($domain_name, 'invoicing.co') !== false) {
$subdomain = explode('.', $domain_name)[0];
-
+
$query = [
'subdomain' => $subdomain,
'portal_mode' => 'subdomain',
];
- if($company = MultiDB::findAndSetDbByDomain($query)){
- return $this->resolveAppleMerchantId($company);
+ if ($company = MultiDB::findAndSetDbByDomain($query)) {
+ return $this->resolveAppleMerchantId($company);
}
}
- $query = [
+ $query = [
'portal_domain' => $request->getSchemeAndHttpHost(),
'portal_mode' => 'domain',
];
- if($company = MultiDB::findAndSetDbByDomain($query)){
+ if ($company = MultiDB::findAndSetDbByDomain($query)) {
return $this->resolveAppleMerchantId($company);
}
return response('', 400);
-
}
private function resolveAppleMerchantId($company)
{
-
$cgs = $company->company_gateways()
->whereIn('gateway_key', $this->stripe_keys)
->where('is_deleted', false)
->get();
- foreach($cgs as $cg)
- {
-
- if($cg->getConfigField('appleDomainVerification')){
- return response($cg->getConfigField('appleDomainVerification'),200);
+ foreach ($cgs as $cg) {
+ if ($cg->getConfigField('appleDomainVerification')) {
+ return response($cg->getConfigField('appleDomainVerification'), 200);
}
-
}
return response('', 400);
-
}
-
}
diff --git a/app/Http/Controllers/ClientPortal/ContactHashLoginController.php b/app/Http/Controllers/ClientPortal/ContactHashLoginController.php
index 4bff4678c92b..1b97219077f0 100644
--- a/app/Http/Controllers/ClientPortal/ContactHashLoginController.php
+++ b/app/Http/Controllers/ClientPortal/ContactHashLoginController.php
@@ -18,7 +18,6 @@ use Auth;
class ContactHashLoginController extends Controller
{
-
/**
* Logs a user into the client portal using their contact_key
* @param string $contact_key The contact key
@@ -26,23 +25,20 @@ class ContactHashLoginController extends Controller
*/
public function login(string $contact_key)
{
- if(request()->has('subscription') && request()->subscription == 'true') {
-
+ if (request()->has('subscription') && request()->subscription == 'true') {
$recurring_invoice = RecurringInvoice::where('client_id', auth()->guard('contact')->client->id)
->whereNotNull('subscription_id')
->whereNull('deleted_at')
->first();
return redirect()->route('client.recurring_invoice.show', $recurring_invoice->hashed_id);
-
}
- return redirect($this->setRedirectPath());
+ return redirect($this->setRedirectPath());
}
public function magicLink(string $magic_link)
{
-
return redirect($this->setRedirectPath());
}
@@ -53,20 +49,18 @@ class ContactHashLoginController extends Controller
private function setRedirectPath()
{
-
- if(auth()->guard('contact')->user()->company->enabled_modules & PortalComposer::MODULE_INVOICES)
+ if (auth()->guard('contact')->user()->company->enabled_modules & PortalComposer::MODULE_INVOICES) {
return '/client/invoices';
- elseif(auth()->guard('contact')->user()->company->enabled_modules & PortalComposer::MODULE_RECURRING_INVOICES)
+ } elseif (auth()->guard('contact')->user()->company->enabled_modules & PortalComposer::MODULE_RECURRING_INVOICES) {
return '/client/recurring_invoices';
- elseif(auth()->guard('contact')->user()->company->enabled_modules & PortalComposer::MODULE_QUOTES)
+ } elseif (auth()->guard('contact')->user()->company->enabled_modules & PortalComposer::MODULE_QUOTES) {
return '/client/quotes';
- elseif(auth()->guard('contact')->user()->company->enabled_modules & PortalComposer::MODULE_CREDITS)
+ } elseif (auth()->guard('contact')->user()->company->enabled_modules & PortalComposer::MODULE_CREDITS) {
return '/client/credits';
- elseif(auth()->guard('contact')->user()->company->enabled_modules & PortalComposer::MODULE_TASKS)
+ } elseif (auth()->guard('contact')->user()->company->enabled_modules & PortalComposer::MODULE_TASKS) {
return '/client/tasks';
- elseif(auth()->guard('contact')->user()->company->enabled_modules & PortalComposer::MODULE_EXPENSES)
+ } elseif (auth()->guard('contact')->user()->company->enabled_modules & PortalComposer::MODULE_EXPENSES) {
return '/client/expenses';
-
+ }
}
-
}
diff --git a/app/Http/Controllers/ClientPortal/CreditController.php b/app/Http/Controllers/ClientPortal/CreditController.php
index 9bf792ef76a2..9b6ee3fefed8 100644
--- a/app/Http/Controllers/ClientPortal/CreditController.php
+++ b/app/Http/Controllers/ClientPortal/CreditController.php
@@ -34,17 +34,15 @@ class CreditController extends Controller
$data = [
'credit' => $credit,
- 'key' => $invitation ? $invitation->key : false
+ 'key' => $invitation ? $invitation->key : false,
];
- if ($invitation && auth()->guard('contact') && ! request()->has('silent') && ! $invitation->viewed_date) {
+ if ($invitation && auth()->guard('contact') && ! request()->has('silent') && ! $invitation->viewed_date) {
+ $invitation->markViewed();
- $invitation->markViewed();
-
- event(new InvitationWasViewed($credit, $invitation, $credit->company, Ninja::eventVars()));
- event(new CreditWasViewed($invitation, $invitation->company, Ninja::eventVars()));
-
- }
+ event(new InvitationWasViewed($credit, $invitation, $credit->company, Ninja::eventVars()));
+ event(new CreditWasViewed($invitation, $invitation->company, Ninja::eventVars()));
+ }
if ($request->query('mode') === 'fullscreen') {
return render('credits.show-fullscreen', $data);
diff --git a/app/Http/Controllers/ClientPortal/DashboardController.php b/app/Http/Controllers/ClientPortal/DashboardController.php
index 3e58d53166cc..fbf159ecd461 100644
--- a/app/Http/Controllers/ClientPortal/DashboardController.php
+++ b/app/Http/Controllers/ClientPortal/DashboardController.php
@@ -22,7 +22,7 @@ class DashboardController extends Controller
*/
public function index()
{
- return redirect()->route('client.invoices.index');
+ return redirect()->route('client.invoices.index');
//return $this->render('dashboard.index');
}
}
diff --git a/app/Http/Controllers/ClientPortal/DocumentController.php b/app/Http/Controllers/ClientPortal/DocumentController.php
index 60a087a29d4c..835c1bb640c1 100644
--- a/app/Http/Controllers/ClientPortal/DocumentController.php
+++ b/app/Http/Controllers/ClientPortal/DocumentController.php
@@ -60,8 +60,9 @@ class DocumentController extends Controller
$headers = [];
- if(request()->input('inline') == 'true')
+ if (request()->input('inline') == 'true') {
$headers = array_merge($headers, ['Content-Disposition' => 'inline']);
+ }
return Storage::disk($document->disk)->download($document->url, $document->name, $headers);
}
@@ -74,29 +75,22 @@ class DocumentController extends Controller
$zipFile = new \PhpZip\ZipFile();
- try{
-
+ try {
foreach ($documents as $document) {
$zipFile->addFile(TempFile::path($document->filePath()), $document->name);
}
- $filename = now() . '-documents.zip';
- $filepath = sys_get_temp_dir() . '/' . $filename;
+ $filename = now().'-documents.zip';
+ $filepath = sys_get_temp_dir().'/'.$filename;
- $zipFile->saveAsFile($filepath) // save the archive to a file
+ $zipFile->saveAsFile($filepath) // save the archive to a file
->close(); // close archive
-
- return response()->download($filepath, $filename)->deleteFileAfterSend(true);
- }
- catch(\PhpZip\Exception\ZipException $e){
+ return response()->download($filepath, $filename)->deleteFileAfterSend(true);
+ } catch (\PhpZip\Exception\ZipException $e) {
// handle exception
- }
- finally{
+ } finally {
$zipFile->close();
}
-
}
-
-
}
diff --git a/app/Http/Controllers/ClientPortal/EntityViewController.php b/app/Http/Controllers/ClientPortal/EntityViewController.php
index f521f21fa736..fb73c3ce4a07 100644
--- a/app/Http/Controllers/ClientPortal/EntityViewController.php
+++ b/app/Http/Controllers/ClientPortal/EntityViewController.php
@@ -45,7 +45,6 @@ class EntityViewController extends Controller
$key = $entity_type.'_id';
-
$invitation = $invitation_entity::where('key', $invitation_key)
->with('contact.client')
->firstOrFail();
@@ -139,7 +138,7 @@ class EntityViewController extends Controller
$invitation = $entity_obj::where('key', $request->invitation_key)
->whereHas($request->entity_type, function ($query) {
- $query->where('is_deleted',0);
+ $query->where('is_deleted', 0);
})
->with('contact.client')
->first();
@@ -154,15 +153,16 @@ class EntityViewController extends Controller
if (! $invitation->viewed_date) {
$invitation->markViewed();
- if(!session()->get('is_silent'))
+ if (! session()->get('is_silent')) {
event(new InvitationWasViewed($invitation->{$request->entity_type}, $invitation, $invitation->{$request->entity_type}->company, Ninja::eventVars()));
+ }
- if(!session()->get('is_silent'))
+ if (! session()->get('is_silent')) {
$this->fireEntityViewedEvent($invitation, $request->entity_type);
+ }
}
-
+
return redirect()->route('client.'.$request->entity_type.'.show', [$request->entity_type => $this->encodePrimaryKey($invitation->{$key})]);
-
}
private function fireEntityViewedEvent($invitation, $entity_string)
@@ -182,5 +182,4 @@ class EntityViewController extends Controller
break;
}
}
-
}
diff --git a/app/Http/Controllers/ClientPortal/InvitationController.php b/app/Http/Controllers/ClientPortal/InvitationController.php
index 490a60f31a34..4011c1d44a02 100644
--- a/app/Http/Controllers/ClientPortal/InvitationController.php
+++ b/app/Http/Controllers/ClientPortal/InvitationController.php
@@ -70,9 +70,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';
@@ -83,69 +83,68 @@ class InvitationController extends Controller
$invitation = $entity_obj::withTrashed()
->where('key', $invitation_key)
->whereHas($entity, function ($query) {
- $query->where('is_deleted',0);
+ $query->where('is_deleted', 0);
})
->with('contact.client')
->first();
- if(!$invitation)
- return abort(404,'The resource is no longer available.');
+ if (! $invitation) {
+ return abort(404, 'The resource is no longer available.');
+ }
/* 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');
+ return redirect()->route('client.login');
} else {
- nlog("else - default - login contact");
+ nlog('else - default - login contact');
request()->session()->invalidate();
auth()->guard('contact')->loginUsingId($client_contact->id, true);
}
-
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)
@@ -168,20 +167,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';
@@ -192,8 +191,9 @@ class InvitationController extends Controller
->with('contact.client')
->firstOrFail();
- if(!$invitation)
- return response()->json(["message" => "no record found"], 400);
+ if (! $invitation) {
+ return response()->json(['message' => 'no record found'], 400);
+ }
$file_name = $invitation->{$entity}->numberFormatter().'.pdf';
@@ -201,13 +201,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)
@@ -219,13 +219,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)
@@ -239,23 +239,22 @@ class InvitationController extends Controller
$invoice = $invitation->invoice;
- if($invoice->partial > 0)
- $amount = round($invoice->partial, (int)$invoice->client->currency()->precision);
- else
- $amount = round($invoice->balance, (int)$invoice->client->currency()->precision);
+ if ($invoice->partial > 0) {
+ $amount = round($invoice->partial, (int) $invoice->client->currency()->precision);
+ } 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'],
'payable_invoices' => [
['invoice_id' => $invitation->invoice->hashed_id, 'amount' => $amount],
],
- 'signature' => false
+ 'signature' => false,
];
$request->replace($data);
@@ -265,38 +264,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");
+ 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 f3a49b20ead1..b5f42beb0783 100644
--- a/app/Http/Controllers/ClientPortal/InvoiceController.php
+++ b/app/Http/Controllers/ClientPortal/InvoiceController.php
@@ -26,9 +26,9 @@ use App\Utils\Traits\MakesHash;
use Illuminate\Contracts\Container\BindingResolutionException;
use Illuminate\Contracts\View\Factory;
use Illuminate\Http\RedirectResponse;
+use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\View\View;
-use Illuminate\Http\Request;
class InvoiceController extends Controller
{
@@ -41,7 +41,6 @@ class InvoiceController extends Controller
*/
public function index(ShowInvoicesRequest $request)
{
-
return $this->render('invoices.index');
}
@@ -61,23 +60,22 @@ class InvoiceController extends Controller
$invitation = $invoice->invitations()->where('client_contact_id', auth()->guard('contact')->user()->id)->first();
- if ($invitation && auth()->guard('contact') && !session()->get('is_silent') && ! $invitation->viewed_date) {
+ if ($invitation && auth()->guard('contact') && ! session()->get('is_silent') && ! $invitation->viewed_date) {
+ $invitation->markViewed();
- $invitation->markViewed();
-
- event(new InvitationWasViewed($invoice, $invitation, $invoice->company, Ninja::eventVars()));
- event(new InvoiceWasViewed($invitation, $invitation->company, Ninja::eventVars()));
-
- }
+ event(new InvitationWasViewed($invoice, $invitation, $invoice->company, Ninja::eventVars()));
+ event(new InvoiceWasViewed($invitation, $invitation->company, Ninja::eventVars()));
+ }
$data = [
'invoice' => $invoice,
- 'key' => $invitation ? $invitation->key : false
+ 'key' => $invitation ? $invitation->key : false,
];
if ($request->query('mode') === 'fullscreen') {
return render('invoices.show-fullscreen', $data);
}
+
return $this->render('invoices.show', $data);
}
@@ -87,7 +85,6 @@ class InvoiceController extends Controller
* @param ProcessInvoicesInBulkRequest $request
* @return mixed
*/
-
public function catch_bulk()
{
return $this->render('invoices.index');
@@ -110,14 +107,14 @@ class InvoiceController extends Controller
public function downloadInvoices($ids)
{
-
$data['invoices'] = Invoice::whereIn('id', $ids)
->whereClientId(auth()->guard('contact')->user()->client->id)
->withTrashed()
->get();
- if(count($data['invoices']) == 0)
+ if (count($data['invoices']) == 0) {
return back()->with(['message' => ctrans('texts.no_items_selected')]);
+ }
return $this->render('invoices.download', $data);
}
@@ -125,11 +122,13 @@ class InvoiceController extends Controller
public function download(Request $request)
{
$transformed_ids = $this->transformKeys($request->invoices);
+
return $this->downloadInvoicePDF((array) $transformed_ids);
}
+
/**
- * @param array $ids
- * @return Factory|View|RedirectResponse
+ * @param array $ids
+ * @return Factory|View|RedirectResponse
*/
private function makePayment(array $ids)
{
@@ -151,21 +150,19 @@ class InvoiceController extends Controller
//iterate and sum the payable amounts either partial or balance
$total = 0;
- foreach($invoices as $invoice)
- {
-
- if($invoice->partial > 0)
+ foreach ($invoices as $invoice) {
+ if ($invoice->partial > 0) {
$total += $invoice->partial;
- else
+ } else {
$total += $invoice->balance;
-
+ }
}
//format data
$invoices->map(function ($invoice) {
$invoice->service()->removeUnpaidGatewayFees();
$invoice->balance = $invoice->balance > 0 ? Number::formatValue($invoice->balance, $invoice->client->currency()) : 0;
- $invoice->partial = $invoice->partial > 0 ? Number::formatValue($invoice->partial, $invoice->client->currency()) : 0;
+ $invoice->partial = $invoice->partial > 0 ? Number::formatValue($invoice->partial, $invoice->client->currency()) : 0;
return $invoice;
});
@@ -212,46 +209,39 @@ class InvoiceController extends Controller
if ($invoices->count() == 1) {
$invoice = $invoices->first();
- $file = $invoice->service()->getInvoicePdf(auth()->guard('contact')->user());
+ $file = $invoice->service()->getInvoicePdf(auth()->guard('contact')->user());
- // return response()->download(file_get_contents(public_path($file)));
+ // return response()->download(file_get_contents(public_path($file)));
- 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']);
}
return $this->buildZip($invoices);
-
}
-
private function buildZip($invoices)
{
// create new archive
$zipFile = new \PhpZip\ZipFile();
- try{
-
+ try {
foreach ($invoices as $invoice) {
- #add it to the zip
+ //add it to the zip
$zipFile->addFromString(basename($invoice->pdf_file_path()), file_get_contents($invoice->pdf_file_path(null, 'url', true)));
-
}
$filename = date('Y-m-d').'_'.str_replace(' ', '_', trans('texts.invoices')).'.zip';
- $filepath = sys_get_temp_dir() . '/' . $filename;
+ $filepath = sys_get_temp_dir().'/'.$filename;
- $zipFile->saveAsFile($filepath) // save the archive to a file
+ $zipFile->saveAsFile($filepath) // save the archive to a file
->close(); // close archive
-
- return response()->download($filepath, $filename)->deleteFileAfterSend(true);
- }
- catch(\PhpZip\Exception\ZipException $e){
+ return response()->download($filepath, $filename)->deleteFileAfterSend(true);
+ } catch (\PhpZip\Exception\ZipException $e) {
// handle exception
- }
- finally{
+ } finally {
$zipFile->close();
}
}
diff --git a/app/Http/Controllers/ClientPortal/NinjaPlanController.php b/app/Http/Controllers/ClientPortal/NinjaPlanController.php
index b76e09ede7ec..cb271cbd7567 100644
--- a/app/Http/Controllers/ClientPortal/NinjaPlanController.php
+++ b/app/Http/Controllers/ClientPortal/NinjaPlanController.php
@@ -41,35 +41,29 @@ class NinjaPlanController extends Controller
public function index(string $contact_key, string $account_or_company_key)
{
-
MultiDB::findAndSetDbByCompanyKey($account_or_company_key);
$company = Company::where('company_key', $account_or_company_key)->first();
- if(!$company){
+ if (! $company) {
MultiDB::findAndSetDbByAccountKey($account_or_company_key);
$account = Account::where('key', $account_or_company_key)->first();
- }
- else
+ } else {
$account = $company->account;
+ }
- if (MultiDB::findAndSetDbByContactKey($contact_key) && $client_contact = ClientContact::where('contact_key', $contact_key)->first())
- {
-
- nlog("Ninja Plan Controller - Found and set Client Contact");
-
- Auth::guard('contact')->loginUsingId($client_contact->id,true);
+ if (MultiDB::findAndSetDbByContactKey($contact_key) && $client_contact = ClientContact::where('contact_key', $contact_key)->first()) {
+ nlog('Ninja Plan Controller - Found and set Client Contact');
+
+ Auth::guard('contact')->loginUsingId($client_contact->id, true);
return $this->plan();
-
}
return redirect()->route('client.catchall');
-
}
public function trial()
{
-
$gateway = CompanyGateway::on('db-ninja-01')->find(config('ninja.ninja_default_company_gateway_id'));
$data['gateway'] = $gateway;
@@ -79,22 +73,19 @@ class NinjaPlanController extends Controller
$customer = $gateway_driver->findOrCreateCustomer();
$setupIntent = \Stripe\SetupIntent::create([
- 'payment_method_types' => ['card'],
- 'usage' => 'off_session',
- 'customer' => $customer->id
+ 'payment_method_types' => ['card'],
+ 'usage' => 'off_session',
+ 'customer' => $customer->id,
]);
$data['intent'] = $setupIntent;
- $data['client'] = Auth::guard('contact')->user()->client;
+ $data['client'] = Auth::guard('contact')->user()->client;
return $this->render('plan.trial', $data);
-
-
}
public function trial_confirmation(Request $request)
{
-
$client = auth()->guard('contact')->user()->client;
$client->fill($request->all());
$client->save();
@@ -125,7 +116,7 @@ class NinjaPlanController extends Controller
$gateway_driver->storeGatewayToken($data, ['gateway_customer_reference' => $customer->id]);
//set free trial
- if(auth()->guard('contact')->user()->client->custom_value2){
+ if (auth()->guard('contact')->user()->client->custom_value2) {
MultiDB::findAndSetDbByAccountKey(auth()->guard('contact')->user()->client->custom_value2);
$account = Account::where('key', auth()->guard('contact')->user()->client->custom_value2)->first();
// $account->trial_started = now();
@@ -138,7 +129,7 @@ class NinjaPlanController extends Controller
}
MultiDB::setDB('db-ninja-01');
-
+
//create recurring invoice
$subscription_repo = new SubscriptionRepository();
$subscription = Subscription::find(6);
@@ -151,7 +142,7 @@ class NinjaPlanController extends Controller
$recurring_invoice->date = now()->addDays(14);
$recurring_invoice->remaining_cycles = -1;
$recurring_invoice->auto_bill = $client->getSetting('auto_bill');
- $recurring_invoice->auto_bill_enabled = $this->setAutoBillFlag($recurring_invoice->auto_bill);
+ $recurring_invoice->auto_bill_enabled = $this->setAutoBillFlag($recurring_invoice->auto_bill);
$recurring_invoice->due_date_days = 'terms';
$recurring_invoice->next_send_date = now()->addDays(14)->format('Y-m-d');
$recurring_invoice->next_send_date_client = now()->addDays(14)->format('Y-m-d');
@@ -166,10 +157,8 @@ class NinjaPlanController extends Controller
->queue();
return $this->render('plan.trial_confirmed', $data);
-
}
-
private function setAutoBillFlag($auto_bill)
{
if ($auto_bill == 'always' || $auto_bill == 'optout') {
@@ -177,7 +166,6 @@ class NinjaPlanController extends Controller
}
return false;
-
}
public function plan()
@@ -186,18 +174,17 @@ class NinjaPlanController extends Controller
//harvest the current plan
$data = [];
$data['late_invoice'] = false;
-
- if(MultiDB::findAndSetDbByAccountKey(Auth::guard('contact')->user()->client->custom_value2))
- {
+
+ if (MultiDB::findAndSetDbByAccountKey(Auth::guard('contact')->user()->client->custom_value2)) {
$account = Account::where('key', Auth::guard('contact')->user()->client->custom_value2)->first();
- if($account)
- {
+ if ($account) {
//offer the option to have a free trial
- if(!$account->trial_started && !$account->plan)
+ if (! $account->trial_started && ! $account->plan) {
return $this->trial();
+ }
- if(Carbon::parse($account->plan_expires)->lt(now())){
+ if (Carbon::parse($account->plan_expires)->lt(now())) {
//expired get the most recent invoice for payment
$late_invoice = Invoice::on('db-ninja-01')
@@ -211,12 +198,11 @@ class NinjaPlanController extends Controller
//account status means user cannot perform upgrades until they pay their account.
// $data['late_invoice'] = $late_invoice;
- //14-01-2022 remove late invoices from blocking upgrades
- $data['late_invoice'] = false;
-
+ //14-01-2022 remove late invoices from blocking upgrades
+ $data['late_invoice'] = false;
}
- $recurring_invoice = RecurringInvoice::on('db-ninja-01')
+ $recurring_invoice = RecurringInvoice::on('db-ninja-01')
->where('client_id', auth()->guard('contact')->user()->client->id)
->where('company_id', Auth::guard('contact')->user()->company->id)
->whereNotNull('subscription_id')
@@ -241,27 +227,22 @@ class NinjaPlanController extends Controller
$current_subscription_id = $recurring_invoice ? $this->encodePrimaryKey($recurring_invoice->subscription_id) : false;
//remove existing subscription
- if($current_subscription_id){
-
- $monthly_plans = $monthly_plans->filter(function ($plan) use($current_subscription_id){
- return (string)$plan->hashed_id != (string)$current_subscription_id;
- });
-
+ if ($current_subscription_id) {
+ $monthly_plans = $monthly_plans->filter(function ($plan) use ($current_subscription_id) {
+ return (string) $plan->hashed_id != (string) $current_subscription_id;
+ });
}
$data['account'] = $account;
- $data['client'] = Auth::guard('contact')->user()->client;
+ $data['client'] = Auth::guard('contact')->user()->client;
$data['plans'] = $monthly_plans;
$data['current_subscription_id'] = $current_subscription_id;
$data['current_recurring_id'] = $recurring_invoice ? $recurring_invoice->hashed_id : false;
return $this->render('plan.index', $data);
-
}
-
- }
- else
+ } else {
return redirect('/client/dashboard');
-
+ }
}
}
diff --git a/app/Http/Controllers/ClientPortal/PaymentController.php b/app/Http/Controllers/ClientPortal/PaymentController.php
index 1459af1bf596..aa23e084cde0 100644
--- a/app/Http/Controllers/ClientPortal/PaymentController.php
+++ b/app/Http/Controllers/ClientPortal/PaymentController.php
@@ -90,13 +90,12 @@ 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)->first();
$invoice = Invoice::with('client')->find($payment_hash->fee_invoice_id);
$client = $invoice ? $invoice->client : auth()->user()->client;
- return $gateway
+ return $gateway
// ->driver(auth()->user()->client)
->driver($client)
->setPaymentMethod($request->input('payment_method_id'))
@@ -112,8 +111,7 @@ class PaymentController extends Controller
* @return Response The response view
*/
public function credit_response(Request $request)
- {
-
+ {
$payment_hash = PaymentHash::where('hash', $request->input('payment_hash'))->first();
/* Hydrate the $payment */
diff --git a/app/Http/Controllers/ClientPortal/PaymentMethodController.php b/app/Http/Controllers/ClientPortal/PaymentMethodController.php
index 778723809956..4dbf694c3b17 100644
--- a/app/Http/Controllers/ClientPortal/PaymentMethodController.php
+++ b/app/Http/Controllers/ClientPortal/PaymentMethodController.php
@@ -97,7 +97,6 @@ class PaymentMethodController extends Controller
public function verify(ClientGatewayToken $payment_method)
{
-
return $payment_method->gateway
->driver(auth()->user()->client)
->setPaymentMethod(request()->query('method'))
@@ -122,24 +121,18 @@ class PaymentMethodController extends Controller
*/
public function destroy(ClientGatewayToken $payment_method)
{
-
- if($payment_method->gateway()->exists()){
-
+ if ($payment_method->gateway()->exists()) {
$payment_method->gateway
->driver(auth()->user()->client)
->setPaymentMethod(request()->query('method'))
->detach($payment_method);
-
}
try {
-
event(new MethodDeleted($payment_method, auth()->guard('contact')->user()->company, Ninja::eventVars(auth()->guard('contact')->user()->id)));
-
+
$payment_method->delete();
-
} catch (Exception $e) {
-
nlog($e->getMessage());
return back();
diff --git a/app/Http/Controllers/ClientPortal/QuoteController.php b/app/Http/Controllers/ClientPortal/QuoteController.php
index caf2d8c8b4be..d0e40b70b601 100644
--- a/app/Http/Controllers/ClientPortal/QuoteController.php
+++ b/app/Http/Controllers/ClientPortal/QuoteController.php
@@ -25,11 +25,11 @@ 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;
-use Illuminate\Http\Request;
-use Illuminate\Support\Carbon;
class QuoteController extends Controller
{
@@ -53,10 +53,9 @@ class QuoteController extends Controller
* @return Factory|View|BinaryFileResponse
*/
public function show(ShowQuoteRequest $request, Quote $quote)
- {
+ {
/* If the quote is expired, convert the status here */
-
$invitation = $quote->invitations()->where('client_contact_id', auth()->user()->id)->first();
$data = [
@@ -65,12 +64,10 @@ class QuoteController extends Controller
];
if ($invitation && auth()->guard('contact') && ! request()->has('silent') && ! $invitation->viewed_date) {
-
$invitation->markViewed();
event(new InvitationWasViewed($quote, $invitation, $quote->company, Ninja::eventVars()));
event(new QuoteWasViewed($invitation, $invitation->company, Ninja::eventVars()));
-
}
if ($request->query('mode') === 'fullscreen') {
@@ -97,14 +94,14 @@ class QuoteController extends Controller
public function downloadQuotes($ids)
{
-
$data['quotes'] = Quote::whereIn('id', $ids)
->whereClientId(auth()->user()->client->id)
->withTrashed()
->get();
- if(count($data['quotes']) == 0)
+ if (count($data['quotes']) == 0) {
return back()->with(['message' => ctrans('texts.no_items_selected')]);
+ }
return $this->render('quotes.download', $data);
}
@@ -112,7 +109,7 @@ class QuoteController extends Controller
public function download(Request $request)
{
$transformed_ids = $this->transformKeys($request->quotes);
-
+
return $this->downloadQuotePdf((array) $transformed_ids);
}
@@ -130,44 +127,37 @@ class QuoteController extends Controller
}
if ($quotes->count() == 1) {
-
- $file = $quotes->first()->service()->getQuotePdf();
- // return response()->download($file, basename($file), ['Cache-Control:' => 'no-cache'])->deleteFileAfterSend(true);
- return response()->streamDownload(function () use($file) {
- echo Storage::get($file);
- }, basename($file), ['Content-Type' => 'application/pdf']);
+ $file = $quotes->first()->service()->getQuotePdf();
+ // return response()->download($file, basename($file), ['Cache-Control:' => 'no-cache'])->deleteFileAfterSend(true);
+ return response()->streamDownload(function () use ($file) {
+ echo Storage::get($file);
+ }, basename($file), ['Content-Type' => 'application/pdf']);
}
return $this->buildZip($quotes);
-
}
private function buildZip($quotes)
{
// create new archive
$zipFile = new \PhpZip\ZipFile();
- try{
-
+ try {
foreach ($quotes as $quote) {
- #add it to the zip
+ //add it to the zip
$zipFile->addFromString(basename($quote->pdf_file_path()), file_get_contents($quote->pdf_file_path(null, 'url', true)));
-
}
$filename = date('Y-m-d').'_'.str_replace(' ', '_', trans('texts.quotes')).'.zip';
- $filepath = sys_get_temp_dir() . '/' . $filename;
+ $filepath = sys_get_temp_dir().'/'.$filename;
- $zipFile->saveAsFile($filepath) // save the archive to a file
+ $zipFile->saveAsFile($filepath) // save the archive to a file
->close(); // close archive
-
- return response()->download($filepath, $filename)->deleteFileAfterSend(true);
- }
- catch(\PhpZip\Exception\ZipException $e){
+ return response()->download($filepath, $filename)->deleteFileAfterSend(true);
+ } catch (\PhpZip\Exception\ZipException $e) {
// handle exception
- }
- finally{
+ } finally {
$zipFile->close();
}
}
@@ -181,7 +171,7 @@ class QuoteController extends Controller
->withTrashed()
->get();
- if (!$quotes || $quotes->count() == 0) {
+ if (! $quotes || $quotes->count() == 0) {
return redirect()
->route('client.quotes.index')
->with('message', ctrans('texts.quotes_with_status_sent_can_be_approved'));
@@ -192,19 +182,20 @@ class QuoteController extends Controller
$quote->service()->approve(auth()->user())->save();
event(new QuoteWasApproved(auth()->guard('contact')->user(), $quote, $quote->company, Ninja::eventVars()));
- if (request()->has('signature') && !is_null(request()->signature) && !empty(request()->signature)) {
+ if (request()->has('signature') && ! is_null(request()->signature) && ! empty(request()->signature)) {
InjectSignature::dispatch($quote, request()->signature);
}
}
- if(count($ids) == 1){
+ if (count($ids) == 1) {
//forward client to the invoice if it exists
- if($quote->invoice()->exists())
- return redirect()->route('client.invoice.show', $quote->invoice->hashed_id);
-
- return redirect()->route('client.quote.show', $quotes->first()->hashed_id);
- }
+ if ($quote->invoice()->exists()) {
+ return redirect()->route('client.invoice.show', $quote->invoice->hashed_id);
+ }
+
+ return redirect()->route('client.quote.show', $quotes->first()->hashed_id);
+ }
return redirect()
->route('client.quotes.index')
diff --git a/app/Http/Controllers/ClientPortal/RecurringInvoiceController.php b/app/Http/Controllers/ClientPortal/RecurringInvoiceController.php
index 5c4bd6747961..e4fa23a7f03f 100644
--- a/app/Http/Controllers/ClientPortal/RecurringInvoiceController.php
+++ b/app/Http/Controllers/ClientPortal/RecurringInvoiceController.php
@@ -13,8 +13,8 @@ namespace App\Http\Controllers\ClientPortal;
use App\Http\Controllers\Controller;
use App\Http\Requests\ClientPortal\RecurringInvoices\RequestCancellationRequest;
-use App\Http\Requests\ClientPortal\RecurringInvoices\ShowRecurringInvoicesRequest;
use App\Http\Requests\ClientPortal\RecurringInvoices\ShowRecurringInvoiceRequest;
+use App\Http\Requests\ClientPortal\RecurringInvoices\ShowRecurringInvoicesRequest;
use App\Jobs\Mail\NinjaMailer;
use App\Jobs\Mail\NinjaMailerJob;
use App\Jobs\Mail\NinjaMailerObject;
@@ -62,11 +62,10 @@ class RecurringInvoiceController extends Controller
public function requestCancellation(RequestCancellationRequest $request, RecurringInvoice $recurring_invoice)
{
- nlog("outside cancellation");
+ nlog('outside cancellation');
if (optional($recurring_invoice->subscription)->allow_cancellation) {
-
- nlog("inside the cancellation");
+ nlog('inside the cancellation');
$nmo = new NinjaMailerObject;
$nmo->mailable = (new NinjaMailer((new ClientContactRequestCancellationObject($recurring_invoice, auth()->user()))->build()));
@@ -75,24 +74,16 @@ class RecurringInvoiceController extends Controller
// $notifiable_users = $this->filterUsersByPermissions($recurring_invoice->company->company_users, $recurring_invoice, ['recurring_cancellation']);
- $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']);
-
//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);
-
}
-
-
-
});
// $notifiable_users->each(function ($company_user) use($nmo){
diff --git a/app/Http/Controllers/ClientPortal/SubscriptionController.php b/app/Http/Controllers/ClientPortal/SubscriptionController.php
index 0710beccc734..21fa9116c23e 100644
--- a/app/Http/Controllers/ClientPortal/SubscriptionController.php
+++ b/app/Http/Controllers/ClientPortal/SubscriptionController.php
@@ -21,10 +21,7 @@ class SubscriptionController extends Controller
{
public function index()
{
-
- if(Ninja::isHosted()){
-
-
+ if (Ninja::isHosted()) {
$count = RecurringInvoice::query()
->where('client_id', auth()->guard('contact')->user()->client->id)
->where('company_id', auth()->guard('contact')->user()->client->company_id)
@@ -34,12 +31,11 @@ class SubscriptionController extends Controller
->withTrashed()
->count();
- if($count == 0)
- return redirect()->route('client.ninja_contact_login', ['contact_key' => auth()->guard('contact')->user()->contact_key, 'company_key' => auth()->guard('contact')->user()->company->company_key]);
-
+ if ($count == 0) {
+ return redirect()->route('client.ninja_contact_login', ['contact_key' => auth()->guard('contact')->user()->contact_key, 'company_key' => auth()->guard('contact')->user()->company->company_key]);
+ }
}
-
return render('subscriptions.index');
}
}
diff --git a/app/Http/Controllers/ClientPortal/SubscriptionPlanSwitchController.php b/app/Http/Controllers/ClientPortal/SubscriptionPlanSwitchController.php
index 0af33a6954a8..b5b4593a52fa 100644
--- a/app/Http/Controllers/ClientPortal/SubscriptionPlanSwitchController.php
+++ b/app/Http/Controllers/ClientPortal/SubscriptionPlanSwitchController.php
@@ -31,19 +31,17 @@ class SubscriptionPlanSwitchController extends Controller
*/
public function index(ShowPlanSwitchRequest $request, RecurringInvoice $recurring_invoice, Subscription $target)
{
-
$amount = $recurring_invoice->subscription
->service()
->calculateUpgradePrice($recurring_invoice, $target);
/**
- *
* Null value here is a proxy for
* denying the user a change plan option
- *
*/
- if(is_null($amount))
+ if (is_null($amount)) {
render('subscriptions.denied');
-
+ }
+
return render('subscriptions.switch', [
'subscription' => $recurring_invoice->subscription,
'recurring_invoice' => $recurring_invoice,
diff --git a/app/Http/Controllers/ClientPortal/SubscriptionPurchaseController.php b/app/Http/Controllers/ClientPortal/SubscriptionPurchaseController.php
index cb8d272aa29b..09825123d32a 100644
--- a/app/Http/Controllers/ClientPortal/SubscriptionPurchaseController.php
+++ b/app/Http/Controllers/ClientPortal/SubscriptionPurchaseController.php
@@ -25,7 +25,7 @@ class SubscriptionPurchaseController extends Controller
public function index(Subscription $subscription, Request $request)
{
/* Make sure the contact is logged into the correct company for this subscription */
- if(auth()->guard('contact')->user() && auth()->guard('contact')->user()->company_id != $subscription->company_id){
+ if (auth()->guard('contact')->user() && auth()->guard('contact')->user()->company_id != $subscription->company_id) {
auth()->guard('contact')->logout();
$request->session()->invalidate();
}
diff --git a/app/Http/Controllers/ClientPortal/SwitchCompanyController.php b/app/Http/Controllers/ClientPortal/SwitchCompanyController.php
index 804720d466be..d0f92ffa459c 100644
--- a/app/Http/Controllers/ClientPortal/SwitchCompanyController.php
+++ b/app/Http/Controllers/ClientPortal/SwitchCompanyController.php
@@ -30,7 +30,7 @@ class SwitchCompanyController extends Controller
auth()->guard('contact')->loginUsingId($client_contact->id, true);
request()->session()->regenerate();
-
+
return redirect('/client/dashboard');
}
}
diff --git a/app/Http/Controllers/ClientPortal/TempRouteController.php b/app/Http/Controllers/ClientPortal/TempRouteController.php
index a35f6defdb8f..db5be7f680ce 100644
--- a/app/Http/Controllers/ClientPortal/TempRouteController.php
+++ b/app/Http/Controllers/ClientPortal/TempRouteController.php
@@ -17,7 +17,6 @@ use Illuminate\Support\Facades\Cache;
class TempRouteController extends Controller
{
-
/**
* Logs a user into the client portal using their contact_key
* @param string $contact_key The contact key
diff --git a/app/Http/Controllers/ClientStatementController.php b/app/Http/Controllers/ClientStatementController.php
index 00d0b4c3acfd..052ddc91a9de 100644
--- a/app/Http/Controllers/ClientStatementController.php
+++ b/app/Http/Controllers/ClientStatementController.php
@@ -77,7 +77,7 @@ class ClientStatementController extends BaseController
* property="show_payments_table",
* description="Flag which determines if the payments table is shown",
* type="boolean",
- * ),
+ * ),
* @OA\Property(
* property="show_aging_table",
* description="Flag which determines if the aging table is shown",
@@ -107,17 +107,16 @@ class ClientStatementController extends BaseController
* ),
* )
*/
-
public function statement(CreateStatementRequest $request)
- {
+ {
$pdf = $request->client()->service()->statement(
$request->only(['start_date', 'end_date', 'show_payments_table', 'show_aging_table', 'status'])
);
-
+
if ($pdf) {
return response()->streamDownload(function () use ($pdf) {
echo $pdf;
- }, ctrans('texts.statement') . '.pdf', ['Content-Type' => 'application/pdf']);
+ }, ctrans('texts.statement').'.pdf', ['Content-Type' => 'application/pdf']);
}
return response()->json(['message' => 'Something went wrong. Please check logs.']);
diff --git a/app/Http/Controllers/CompanyController.php b/app/Http/Controllers/CompanyController.php
index c780d66f3007..0be886c5797b 100644
--- a/app/Http/Controllers/CompanyController.php
+++ b/app/Http/Controllers/CompanyController.php
@@ -71,13 +71,11 @@ class CompanyController extends BaseController
*/
public function __construct(CompanyRepository $company_repo)
{
-
parent::__construct();
$this->company_repo = $company_repo;
$this->middleware('password_protected')->only(['destroy']);
-
}
/**
@@ -232,8 +230,7 @@ class CompanyController extends BaseController
'notifications' => CompanySettings::notificationDefaults(),
]);
- if($company->account->companies()->where('is_large', 1)->exists())
- {
+ if ($company->account->companies()->where('is_large', 1)->exists()) {
$company->account->companies()->update(['is_large' => true]);
}
@@ -419,16 +416,18 @@ class CompanyController extends BaseController
*/
public function update(UpdateCompanyRequest $request, Company $company)
{
- if ($request->hasFile('company_logo') || (is_array($request->input('settings')) && !array_key_exists('company_logo', $request->input('settings'))))
+ if ($request->hasFile('company_logo') || (is_array($request->input('settings')) && ! array_key_exists('company_logo', $request->input('settings')))) {
$this->removeLogo($company);
-
+ }
+
$company = $this->company_repo->save($request->all(), $company);
$company->saveSettings($request->input('settings'), $company);
- if ($request->has('documents'))
+ if ($request->has('documents')) {
$this->saveDocuments($request->input('documents'), $company, false);
-
+ }
+
$this->uploadLogo($request->file('company_logo'), $company, $company);
return $this->itemResponse($company);
@@ -486,16 +485,15 @@ class CompanyController extends BaseController
*/
public function destroy(DestroyCompanyRequest $request, Company $company)
{
-
- if(Ninja::isHosted() && config('ninja.ninja_default_company_id') == $company->id)
+ if (Ninja::isHosted() && config('ninja.ninja_default_company_id') == $company->id) {
return response()->json(['message' => 'Cannot purge this company'], 400);
-
+ }
+
$company_count = $company->account->companies->count();
$account = $company->account;
$account_key = $account->key;
if ($company_count == 1) {
-
$company->company_users->each(function ($company_user) {
$company_user->user->forceDelete();
$company_user->forceDelete();
@@ -503,28 +501,28 @@ class CompanyController extends BaseController
$account->delete();
- if(Ninja::isHosted())
+ if (Ninja::isHosted()) {
\Modules\Admin\Jobs\Account\NinjaDeletedAccount::dispatch($account_key, $request->all());
+ }
LightLogs::create(new AccountDeleted())
->increment()
->queue();
-
} else {
$company_id = $company->id;
- $company->company_users->each(function ($company_user){
+ $company->company_users->each(function ($company_user) {
$company_user->forceDelete();
});
-
- $other_company = $company->account->companies->where('id', '!=', $company->id)->first();
- $nmo = new NinjaMailerObject;
- $nmo->mailable = new CompanyDeleted($company->present()->name, auth()->user(), $company->account, $company->settings);
- $nmo->company = $other_company;
- $nmo->settings = $other_company->settings;
- $nmo->to_user = auth()->user();
- NinjaMailerJob::dispatch($nmo);
+ $other_company = $company->account->companies->where('id', '!=', $company->id)->first();
+
+ $nmo = new NinjaMailerObject;
+ $nmo->mailable = new CompanyDeleted($company->present()->name, auth()->user(), $company->account, $company->settings);
+ $nmo->company = $other_company;
+ $nmo->settings = $other_company->settings;
+ $nmo->to_user = auth()->user();
+ NinjaMailerJob::dispatch($nmo);
$company->delete();
@@ -592,18 +590,18 @@ class CompanyController extends BaseController
*/
public function upload(UploadCompanyRequest $request, Company $company)
{
-
- 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'), $company);
+ }
return $this->itemResponse($company->fresh());
-
}
-/**
+ /**
* Update the specified resource in storage.
*
* @param UploadCompanyRequest $request
@@ -656,13 +654,10 @@ class CompanyController extends BaseController
*/
public function default(DefaultCompanyRequest $request, Company $company)
{
-
$account = $company->account;
$account->default_company_id = $company->id;
- $account->save();
+ $account->save();
return $this->itemResponse($company->fresh());
-
}
-
}
diff --git a/app/Http/Controllers/CompanyGatewayController.php b/app/Http/Controllers/CompanyGatewayController.php
index ec3858b48225..d957238d4179 100644
--- a/app/Http/Controllers/CompanyGatewayController.php
+++ b/app/Http/Controllers/CompanyGatewayController.php
@@ -49,7 +49,6 @@ class CompanyGatewayController extends BaseController
private array $stripe_keys = ['d14dd26a47cecc30fdd65700bfb67b34', 'd14dd26a37cecc30fdd65700bfb55b23'];
-
/**
* CompanyGatewayController constructor.
* @param CompanyRepository $company_repo
@@ -200,8 +199,7 @@ class CompanyGatewayController extends BaseController
$company_gateway->save();
/*Always ensure at least one fees and limits object is set per gateway*/
- if(!isset($company_gateway->fees_and_limits)) {
-
+ if (! isset($company_gateway->fees_and_limits)) {
$gateway_types = $company_gateway->driver(new Client)->gatewayTypes();
$fees_and_limits = new \stdClass;
@@ -213,8 +211,7 @@ class CompanyGatewayController extends BaseController
ApplePayDomain::dispatch($company_gateway, $company_gateway->company->db);
- if(in_array($company_gateway->gateway_key, $this->stripe_keys))
- {
+ if (in_array($company_gateway->gateway_key, $this->stripe_keys)) {
StripeWebhook::dispatch($company_gateway->company->company_key, $company_gateway->id);
}
@@ -448,14 +445,12 @@ class CompanyGatewayController extends BaseController
*/
public function destroy(DestroyCompanyGatewayRequest $request, CompanyGateway $company_gateway)
{
-
$company_gateway->driver(new Client)
->disconnect();
$company_gateway->delete();
return $this->itemResponse($company_gateway->fresh());
-
}
/**
diff --git a/app/Http/Controllers/ConnectedAccountController.php b/app/Http/Controllers/ConnectedAccountController.php
index a520045fdbe3..facaff34311c 100644
--- a/app/Http/Controllers/ConnectedAccountController.php
+++ b/app/Http/Controllers/ConnectedAccountController.php
@@ -30,7 +30,7 @@ class ConnectedAccountController extends BaseController
protected $entity_type = User::class;
protected $entity_transformer = UserTransformer::class;
-
+
public function __construct()
{
parent::__construct();
@@ -96,7 +96,6 @@ class ConnectedAccountController extends BaseController
$user = $google->getTokenResponse(request()->input('id_token'));
if ($user) {
-
$client = new Google_Client();
$client->setClientId(config('ninja.auth.google.client_id'));
$client->setClientSecret(config('ninja.auth.google.client_secret'));
@@ -106,24 +105,24 @@ class ConnectedAccountController extends BaseController
$email = $google->harvestEmail($user);
- 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,
'oauth_user_id' => $google->harvestSubField($user),
'oauth_provider_id' => 'google',
- 'email_verified_at' =>now()
+ 'email_verified_at' =>now(),
];
auth()->user()->update($connected_account);
auth()->user()->email_verified_at = now();
auth()->user()->save();
-
- $this->setLoginCache(auth()->user());
-
- return $this->itemResponse(auth()->user());
+ $this->setLoginCache(auth()->user());
+
+ return $this->itemResponse(auth()->user());
}
return response()
@@ -132,11 +131,8 @@ class ConnectedAccountController extends BaseController
->header('X-Api-Version', config('ninja.minimum_client_version'));
}
-
-
public function handleGmailOauth(Request $request)
{
-
$user = false;
$google = new Google();
@@ -144,7 +140,6 @@ class ConnectedAccountController extends BaseController
$user = $google->getTokenResponse($request->input('id_token'));
if ($user) {
-
$client = new Google_Client();
$client->setClientId(config('ninja.auth.google.client_id'));
$client->setClientSecret(config('ninja.auth.google.client_secret'));
@@ -163,27 +158,26 @@ class ConnectedAccountController extends BaseController
'oauth_user_token' => $token,
'oauth_user_refresh_token' => $refresh_token,
'oauth_provider_id' => 'google',
- 'email_verified_at' =>now()
+ 'email_verified_at' =>now(),
];
- if(auth()->user()->email != $google->harvestEmail($user))
+ if (auth()->user()->email != $google->harvestEmail($user)) {
return response()->json(['message' => 'Primary Email differs to OAuth email. Emails must match.'], 400);
+ }
auth()->user()->update($connected_account);
auth()->user()->email_verified_at = now();
auth()->user()->save();
-
+
$this->activateGmail(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 activateGmail(User $user)
@@ -191,13 +185,12 @@ class ConnectedAccountController extends BaseController
$company = $user->company();
$settings = $company->settings;
- if($settings->email_sending_method == 'default')
- {
+ if ($settings->email_sending_method == 'default') {
$settings->email_sending_method = 'gmail';
- $settings->gmail_sending_user_id = (string)$user->hashed_id;
+ $settings->gmail_sending_user_id = (string) $user->hashed_id;
$company->settings = $settings;
$company->save();
- }
+ }
}
}
diff --git a/app/Http/Controllers/Contact/LoginController.php b/app/Http/Controllers/Contact/LoginController.php
index 97d8444f190d..7452e94799aa 100644
--- a/app/Http/Controllers/Contact/LoginController.php
+++ b/app/Http/Controllers/Contact/LoginController.php
@@ -94,9 +94,9 @@ class LoginController extends BaseController
{
//'https://www.googleapis.com/auth/gmail.send','email','profile','openid'
$scopes = [];
-
- if($provider == 'google'){
- $scopes = ['https://www.googleapis.com/auth/gmail.send','email','profile','openid'];
+
+ if ($provider == 'google') {
+ $scopes = ['https://www.googleapis.com/auth/gmail.send', 'email', 'profile', 'openid'];
}
if (request()->has('code')) {
@@ -235,6 +235,4 @@ class LoginController extends BaseController
return $this->errorResponse(['message' => 'Invalid credentials'], 401);
}
}
-
-
}
diff --git a/app/Http/Controllers/CreditController.php b/app/Http/Controllers/CreditController.php
index 1e868f46c00f..161d90f44cd4 100644
--- a/app/Http/Controllers/CreditController.php
+++ b/app/Http/Controllers/CreditController.php
@@ -48,7 +48,7 @@ class CreditController extends BaseController
{
use MakesHash;
use SavesDocuments;
-
+
protected $entity_type = Credit::class;
protected $entity_transformer = CreditTransformer::class;
@@ -205,7 +205,7 @@ class CreditController extends BaseController
->triggeredActions($request)
->save();
- if($credit->invoice_id){
+ if ($credit->invoice_id) {
$credit = $credit->service()->markSent()->save();
$credit->client->service()->updatePaidToDate(-1 * $credit->balance)->save();
}
@@ -388,7 +388,7 @@ class CreditController extends BaseController
$credit->service()
->triggeredActions($request)
->deletePdf();
-
+
event(new CreditWasUpdated($credit, $credit->company, Ninja::eventVars(auth()->user() ? auth()->user()->id : null)));
return $this->itemResponse($credit);
@@ -520,7 +520,8 @@ class CreditController extends BaseController
if ($action == 'bulk_download' && $credits->count() > 1) {
$credits->each(function ($credit) {
if (auth()->user()->cannot('view', $credit)) {
- nlog("access denied");
+ nlog('access denied');
+
return response()->json(['message' => ctrans('text.access_denied')]);
}
});
@@ -530,7 +531,6 @@ class CreditController extends BaseController
return response()->json(['message' => ctrans('texts.sent_message')], 200);
}
-
$credits->each(function ($credit, $key) use ($action) {
if (auth()->user()->can('edit', $credit)) {
$this->performAction($credit, $action, true);
@@ -551,6 +551,7 @@ class CreditController extends BaseController
switch ($action) {
case 'mark_paid':
$credit->service()->markPaid()->save();
+
return $this->itemResponse($credit);
break;
@@ -569,15 +570,15 @@ class CreditController extends BaseController
return $this->itemResponse($credit);
}
break;
- case 'download':
+ case 'download':
// $file = $credit->pdf_file_path();
$file = $credit->service()->getCreditPdf($credit->invitations->first());
// return response()->download($file, basename($file), ['Cache-Control:' => 'no-cache'])->deleteFileAfterSend(true);
- 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 'archive':
$this->credit_repository->archive($credit);
@@ -607,7 +608,6 @@ class CreditController extends BaseController
EmailEntity::dispatch($invitation, $credit->company, 'credit');
});
-
if (! $bulk) {
return response()->json(['message'=>'email sent'], 200);
}
@@ -626,17 +626,16 @@ class CreditController extends BaseController
$credit = $invitation->credit;
$file = $credit->service()->getCreditPdf($invitation);
-
+
$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 Storage::get($file);
- }, basename($file), $headers);
-
-
+ return response()->streamDownload(function () use ($file) {
+ echo Storage::get($file);
+ }, basename($file), $headers);
}
/**
@@ -692,15 +691,14 @@ class CreditController extends BaseController
*/
public function upload(UploadCreditRequest $request, Credit $credit)
{
-
- 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'), $credit);
+ }
return $this->itemResponse($credit->fresh());
-
}
-
}
diff --git a/app/Http/Controllers/DesignController.php b/app/Http/Controllers/DesignController.php
index dbb22226c761..a7c603f06bb3 100644
--- a/app/Http/Controllers/DesignController.php
+++ b/app/Http/Controllers/DesignController.php
@@ -357,11 +357,11 @@ class DesignController extends BaseController
$design->fill($request->all());
$design->save();
-/*
- This is required as the base template does not know to inject the table elements
-*/
+ /*
+ This is required as the base template does not know to inject the table elements
+ */
- $properties = ['includes','header','body','footer'];
+ $properties = ['includes', 'header', 'body', 'footer'];
$d = $design->design;
@@ -395,18 +395,17 @@ class DesignController extends BaseController