php-cs-fixer

This commit is contained in:
David Bomba 2023-02-16 12:36:09 +11:00
parent a25daa8144
commit 4babfbb651
965 changed files with 5565 additions and 9452 deletions

19
.php_cs
View File

@ -1,19 +0,0 @@
<?php
$finder = Symfony\Component\Finder\Finder::create()
->notPath('vendor')
->notPath('bootstrap')
->notPath('storage')
->notPath('node_modules')
->in(__DIR__)
->name('*.php')
->notName('*.blade.php');
return PhpCsFixer\Config::create()
->setRules([
'@PSR2' => true,
'array_syntax' => ['syntax' => 'short'],
'ordered_imports' => ['sortAlgorithm' => 'alpha'],
'no_unused_imports' => true,
])
->setFinder($finder);

View File

@ -14,11 +14,9 @@ namespace App\Console\Commands;
use App\Libraries\MultiDB; use App\Libraries\MultiDB;
use App\Models\Backup; use App\Models\Backup;
use App\Models\Company; use App\Models\Company;
use App\Models\Design;
use App\Models\Document; use App\Models\Document;
use Illuminate\Console\Command; use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Storage;
use stdClass;
class BackupUpdate extends Command class BackupUpdate extends Command
{ {
@ -60,7 +58,6 @@ class BackupUpdate extends Command
if (! config('ninja.db.multi_db_enabled')) { if (! config('ninja.db.multi_db_enabled')) {
$this->handleOnDb(); $this->handleOnDb();
} else { } else {
//multiDB environment, need to //multiDB environment, need to
foreach (MultiDB::$dbs as $db) { foreach (MultiDB::$dbs as $db) {
MultiDB::setDB($db); MultiDB::setDB($db);
@ -78,50 +75,43 @@ class BackupUpdate extends Command
//logos //logos
Company::cursor() Company::cursor()
->each(function ($company){ ->each(function ($company) {
$company_logo = $company->present()->logo();
$company_logo = $company->present()->logo(); if ($company_logo == 'https://invoicing.co/images/new_logo.png') {
return;
}
if($company_logo == 'https://invoicing.co/images/new_logo.png') $logo = @file_get_contents($company_logo);
return;
$logo = @file_get_contents($company_logo); if ($logo) {
$path = str_replace("https://objects.invoicing.co/", "", $company->present()->logo());
if($logo){ $path = str_replace("https://v5-at-backup.us-southeast-1.linodeobjects.com/", "", $path);
$path = str_replace("https://objects.invoicing.co/", "", $company->present()->logo());
$path = str_replace("https://v5-at-backup.us-southeast-1.linodeobjects.com/", "", $path);
Storage::disk($this->option('disk'))->put($path, $logo);
}
Storage::disk($this->option('disk'))->put($path, $logo);
}
}); });
//documents //documents
Document::cursor() Document::cursor()
->each(function ($document){ ->each(function ($document) {
$doc_bin = $document->getFile(); $doc_bin = $document->getFile();
if($doc_bin) if ($doc_bin) {
Storage::disk($this->option('disk'))->put($document->url, $doc_bin); Storage::disk($this->option('disk'))->put($document->url, $doc_bin);
}
}); });
//backups //backups
Backup::cursor() Backup::cursor()
->each(function ($backup){ ->each(function ($backup) {
$backup_bin = Storage::disk('s3')->get($backup->filename);
$backup_bin = Storage::disk('s3')->get($backup->filename); if ($backup_bin) {
if($backup_bin)
Storage::disk($this->option('disk'))->put($backup->filename, $backup_bin); Storage::disk($this->option('disk'))->put($backup->filename, $backup_bin);
}
}); });
} }
} }

View File

@ -28,9 +28,7 @@ use App\Models\CreditInvitation;
use App\Models\Invoice; use App\Models\Invoice;
use App\Models\InvoiceInvitation; use App\Models\InvoiceInvitation;
use App\Models\Payment; use App\Models\Payment;
use App\Models\Paymentable;
use App\Models\PurchaseOrder; use App\Models\PurchaseOrder;
use App\Models\PurchaseOrderInvitation;
use App\Models\Quote; use App\Models\Quote;
use App\Models\QuoteInvitation; use App\Models\QuoteInvitation;
use App\Models\RecurringInvoiceInvitation; use App\Models\RecurringInvoiceInvitation;
@ -102,7 +100,7 @@ class CheckData extends Command
public function handle() public function handle()
{ {
$time_start = microtime(true); $time_start = microtime(true);
$database_connection = $this->option('database') ? $this->option('database') : 'Connected to Default DB'; $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 ";
@ -113,8 +111,8 @@ class CheckData extends Command
config(['database.default' => $database]); config(['database.default' => $database]);
} }
$this->checkInvoiceBalances(); $this->checkInvoiceBalances();
$this->checkClientBalanceEdgeCases(); $this->checkClientBalanceEdgeCases();
$this->checkPaidToDatesNew(); $this->checkPaidToDatesNew();
$this->checkContacts(); $this->checkContacts();
$this->checkVendorContacts(); $this->checkVendorContacts();
@ -128,7 +126,7 @@ class CheckData extends Command
$this->checkCompanyTokens(); $this->checkCompanyTokens();
$this->checkUserState(); $this->checkUserState();
if(Ninja::isHosted()){ if (Ninja::isHosted()) {
$this->checkAccountStatuses(); $this->checkAccountStatuses();
$this->checkNinjaPortalUrls(); $this->checkNinjaPortalUrls();
} }
@ -162,44 +160,35 @@ class CheckData extends Command
private function checkCompanyTokens() private function checkCompanyTokens()
{ {
CompanyUser::doesnthave('token')->cursor()->each(function ($cu) {
CompanyUser::doesnthave('token')->cursor()->each(function ($cu){ if ($cu->user) {
if($cu->user){
$this->logMessage("Creating missing company token for user # {$cu->user->id} for company id # {$cu->company->id}"); $this->logMessage("Creating missing company token for user # {$cu->user->id} for company id # {$cu->company->id}");
(new CreateCompanyToken($cu->company, $cu->user, 'System'))->handle(); (new CreateCompanyToken($cu->company, $cu->user, 'System'))->handle();
} } else {
else {
$this->logMessage("Dangling User ID # {$cu->id}"); $this->logMessage("Dangling User ID # {$cu->id}");
} }
}); });
} }
private function checkOauthSanity() private function checkOauthSanity()
{ {
User::where('oauth_provider_id', '1')->cursor()->each(function ($user){ User::where('oauth_provider_id', '1')->cursor()->each(function ($user) {
$this->logMessage("Invalid provider ID for user id# {$user->id}"); $this->logMessage("Invalid provider ID for user id# {$user->id}");
}); });
} }
private function checkDuplicateRecurringInvoices() private function checkDuplicateRecurringInvoices()
{ {
if (Ninja::isHosted()) {
if(Ninja::isHosted())
{
$c = Client::on('db-ninja-01')->where('company_id', config('ninja.ninja_default_company_id')) $c = Client::on('db-ninja-01')->where('company_id', config('ninja.ninja_default_company_id'))
->with('recurring_invoices') ->with('recurring_invoices')
->cursor() ->cursor()
->each(function ($client){ ->each(function ($client) {
if($client->recurring_invoices()->where('is_deleted', 0)->where('deleted_at', null)->count() > 1) if ($client->recurring_invoices()->where('is_deleted', 0)->where('deleted_at', null)->count() > 1) {
$this->logMessage("Duplicate Recurring Invoice => {$client->custom_value1}"); $this->logMessage("Duplicate Recurring Invoice => {$client->custom_value1}");
}
}); });
} }
} }
@ -302,7 +291,6 @@ class CheckData extends Command
$new_contact->save(); $new_contact->save();
} }
} }
} }
private function checkVendorContacts() private function checkVendorContacts()
@ -350,7 +338,6 @@ class CheckData extends Command
} }
if ($this->option('fix') == 'true') { if ($this->option('fix') == 'true') {
$vendors = Vendor::withTrashed()->doesntHave('contacts')->get(); $vendors = Vendor::withTrashed()->doesntHave('contacts')->get();
foreach ($vendors as $vendor) { foreach ($vendors as $vendor) {
@ -363,7 +350,6 @@ class CheckData extends Command
$new_contact->save(); $new_contact->save();
} }
} }
} }
@ -418,27 +404,22 @@ class CheckData extends Command
User::withTrashed() User::withTrashed()
->where('deleted_at', '0000-00-00 00:00:00.000000') ->where('deleted_at', '0000-00-00 00:00:00.000000')
->cursor() ->cursor()
->each(function ($user){ ->each(function ($user) {
$user->restore(); $user->restore();
}); });
} }
private function checkEntityInvitations() private function checkEntityInvitations()
{ {
RecurringInvoiceInvitation::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]);
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]);
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]);
CreditInvitation::where('deleted_at',"0000-00-00 00:00:00.000000")->withTrashed()->update(['deleted_at' => null]);
collect([Invoice::class, Quote::class, Credit::class, PurchaseOrder::class])->each(function ($entity){ collect([Invoice::class, Quote::class, Credit::class, PurchaseOrder::class])->each(function ($entity) {
if ($entity::doesntHave('invitations')->count() > 0) {
if($entity::doesntHave('invitations')->count() > 0)
{
$entity::doesntHave('invitations')->cursor()->each(function ($entity) { $entity::doesntHave('invitations')->cursor()->each(function ($entity) {
$client_vendor_key = 'client_id'; $client_vendor_key = 'client_id';
$contact_id = 'client_contact_id'; $contact_id = 'client_contact_id';
$contact_class = ClientContact::class; $contact_class = ClientContact::class;
@ -446,55 +427,47 @@ class CheckData extends Command
$entity_key = \Illuminate\Support\Str::of(class_basename($entity))->snake()->append('_id')->value; $entity_key = \Illuminate\Support\Str::of(class_basename($entity))->snake()->append('_id')->value;
$entity_obj = get_class($entity).'Invitation'; $entity_obj = get_class($entity).'Invitation';
if($entity instanceof PurchaseOrder){ if ($entity instanceof PurchaseOrder) {
$client_vendor_key = 'vendor_id'; $client_vendor_key = 'vendor_id';
$contact_id = 'vendor_contact_id'; $contact_id = 'vendor_contact_id';
$contact_class = VendorContact::class; $contact_class = VendorContact::class;
} }
$invitation = false; $invitation = false;
//check contact exists! //check contact exists!
if($contact_class::where('company_id', $entity->company_id)->where($client_vendor_key,$entity->{$client_vendor_key})->exists()) if ($contact_class::where('company_id', $entity->company_id)->where($client_vendor_key, $entity->{$client_vendor_key})->exists()) {
{ $contact = $contact_class::where('company_id', $entity->company_id)->where($client_vendor_key, $entity->{$client_vendor_key})->first();
$contact = $contact_class::where('company_id', $entity->company_id)->where($client_vendor_key,$entity->{$client_vendor_key})->first(); //double check if an archived invite exists
if ($contact && $entity_obj::withTrashed()->where($entity_key, $entity->id)->where($contact_id, $contact->id)->count() != 0) {
//double check if an archived invite exists $i = $entity_obj::withTrashed()->where($entity_key, $entity->id)->where($contact_id, $contact->id)->first();
if($contact && $entity_obj::withTrashed()->where($entity_key, $entity->id)->where($contact_id, $contact->id)->count() != 0) { $i->restore();
$i = $entity_obj::withTrashed()->where($entity_key, $entity->id)->where($contact_id, $contact->id)->first(); $this->logMessage("Found a valid contact and invitation restoring for {$entity_key} - {$entity->id}");
$i->restore(); } else {
$this->logMessage("Found a valid contact and invitation restoring for {$entity_key} - {$entity->id}"); $invitation = new $entity_obj();
} $invitation->company_id = $entity->company_id;
else { $invitation->user_id = $entity->user_id;
$invitation = new $entity_obj(); $invitation->{$entity_key} = $entity->id;
$invitation->company_id = $entity->company_id; $invitation->{$contact_id} = $contact->id;
$invitation->user_id = $entity->user_id; $invitation->key = Str::random(config('ninja.key_length'));
$invitation->{$entity_key} = $entity->id; $this->logMessage("Add invitation for {$entity_key} - {$entity->id}");
$invitation->{$contact_id} = $contact->id;
$invitation->key = Str::random(config('ninja.key_length'));
$this->logMessage("Add invitation for {$entity_key} - {$entity->id}");
}
} }
else } else {
$this->logMessage("No contact present, so cannot add invitation for {$entity_key} - {$entity->id}"); $this->logMessage("No contact present, so cannot add invitation for {$entity_key} - {$entity->id}");
try{
if($invitation)
$invitation->save();
} }
catch(\Exception $e){
try {
if ($invitation) {
$invitation->save();
}
} catch(\Exception $e) {
$this->logMessage($e->getMessage()); $this->logMessage($e->getMessage());
$invitation = null; $invitation = null;
} }
}); });
} }
}); });
} }
private function fixInvitations($entities, $entity) private function fixInvitations($entities, $entity)
@ -503,8 +476,7 @@ class CheckData extends Command
$entity_obj = 'App\Models\\'.ucfirst(Str::camel($entity)).'Invitation'; $entity_obj = 'App\Models\\'.ucfirst(Str::camel($entity)).'Invitation';
foreach($entities as $entity) foreach ($entities as $entity) {
{
$invitation = new $entity_obj(); $invitation = new $entity_obj();
$invitation->company_id = $entity->company_id; $invitation->company_id = $entity->company_id;
$invitation->user_id = $entity->user_id; $invitation->user_id = $entity->user_id;
@ -512,20 +484,17 @@ class CheckData extends Command
$invitation->client_contact_id = ClientContact::whereClientId($entity->client_id)->first()->id; $invitation->client_contact_id = ClientContact::whereClientId($entity->client_id)->first()->id;
$invitation->key = Str::random(config('ninja.key_length')); $invitation->key = Str::random(config('ninja.key_length'));
try{ try {
$invitation->save(); $invitation->save();
} } catch(\Exception $e) {
catch(\Exception $e){
$invitation = null; $invitation = null;
} }
} }
} }
private function clientPaidToDateQuery() private function clientPaidToDateQuery()
{ {
$results = \DB::select( \DB::raw(" $results = \DB::select(\DB::raw("
SELECT SELECT
clients.id as client_id, clients.id as client_id,
clients.paid_to_date as client_paid_to_date, clients.paid_to_date as client_paid_to_date,
@ -540,14 +509,14 @@ class CheckData extends Command
GROUP BY clients.id GROUP BY clients.id
HAVING payments_applied != client_paid_to_date HAVING payments_applied != client_paid_to_date
ORDER BY clients.id; ORDER BY clients.id;
") ); "));
return $results; return $results;
} }
private function clientCreditPaymentables($client) private function clientCreditPaymentables($client)
{ {
$results = \DB::select( \DB::raw(" $results = \DB::select(\DB::raw("
SELECT SELECT
SUM(paymentables.amount - paymentables.refunded) as credit_payment SUM(paymentables.amount - paymentables.refunded) as credit_payment
FROM payments FROM payments
@ -559,7 +528,7 @@ class CheckData extends Command
AND paymentables.amount > 0 AND paymentables.amount > 0
AND payments.is_deleted = 0 AND payments.is_deleted = 0
AND payments.client_id = ?; AND payments.client_id = ?;
"), [App\Models\Credit::class, $client->id] ); "), [App\Models\Credit::class, $client->id]);
return $results; return $results;
} }
@ -570,8 +539,7 @@ class CheckData extends Command
$this->wrong_paid_to_dates = 0; $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); $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'); $credits_from_reversal = Credit::withTrashed()->where('client_id', $client->id)->where('is_deleted', 0)->whereNotNull('invoice_id')->sum('amount');
@ -580,26 +548,22 @@ class CheckData extends Command
$total_paid_to_date = $_client->payments_applied + $credits_used_for_payments[0]->credit_payment - $credits_from_reversal; $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->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->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; $this->isValid = false;
if($this->option('paid_to_date')){ if ($this->option('paid_to_date')) {
$this->logMessage("# {$client->id} " . $client->present()->name().' - '.$client->number." Fixing {$client->paid_to_date} to {$total_paid_to_date}"); $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->paid_to_date = $total_paid_to_date;
$client->save(); $client->save();
} }
} }
} }
$this->logMessage("{$this->wrong_paid_to_dates} clients with incorrect paid to dates"); $this->logMessage("{$this->wrong_paid_to_dates} clients with incorrect paid to dates");
} }
private function checkPaidToDates() private function checkPaidToDates()
@ -608,12 +572,12 @@ class CheckData extends Command
$credit_total_applied = 0; $credit_total_applied = 0;
$clients = DB::table('clients') $clients = DB::table('clients')
->leftJoin('payments', function($join) { ->leftJoin('payments', function ($join) {
$join->on('payments.client_id', '=', 'clients.id') $join->on('payments.client_id', '=', 'clients.id')
->where('payments.is_deleted', 0) ->where('payments.is_deleted', 0)
->whereIn('payments.status_id', [Payment::STATUS_COMPLETED, Payment:: STATUS_PENDING, Payment::STATUS_PARTIALLY_REFUNDED, Payment::STATUS_REFUNDED]); ->whereIn('payments.status_id', [Payment::STATUS_COMPLETED, Payment::STATUS_PENDING, Payment::STATUS_PARTIALLY_REFUNDED, Payment::STATUS_REFUNDED]);
}) })
->where('clients.is_deleted',0) ->where('clients.is_deleted', 0)
->where('clients.updated_at', '>', now()->subDays(2)) ->where('clients.updated_at', '>', now()->subDays(2))
->groupBy('clients.id') ->groupBy('clients.id')
->havingRaw('clients.paid_to_date != sum(coalesce(payments.amount - payments.refunded, 0))') ->havingRaw('clients.paid_to_date != sum(coalesce(payments.amount - payments.refunded, 0))')
@ -621,32 +585,28 @@ class CheckData extends Command
/* Due to accounting differences we need to perform a second loop here to ensure there actually is an issue */ /* 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) { $clients->each(function ($client_record) use ($credit_total_applied) {
$client = Client::withTrashed()->find($client_record->id); $client = Client::withTrashed()->find($client_record->id);
$total_invoice_payments = 0; $total_invoice_payments = 0;
foreach ($client->invoices()->where('is_deleted', false)->where('status_id', '>', 1)->get() as $invoice) { foreach ($client->invoices()->where('is_deleted', false)->where('status_id', '>', 1)->get() as $invoice) {
$total_invoice_payments += $invoice->payments() $total_invoice_payments += $invoice->payments()
->where('is_deleted', false)->whereIn('status_id', [Payment::STATUS_COMPLETED, Payment:: STATUS_PENDING, Payment::STATUS_PARTIALLY_REFUNDED, Payment::STATUS_REFUNDED]) ->where('is_deleted', false)->whereIn('status_id', [Payment::STATUS_COMPLETED, Payment::STATUS_PENDING, Payment::STATUS_PARTIALLY_REFUNDED, Payment::STATUS_REFUNDED])
->selectRaw('sum(paymentables.amount - paymentables.refunded) as p') ->selectRaw('sum(paymentables.amount - paymentables.refunded) as p')
->pluck('p') ->pluck('p')
->first(); ->first();
} }
//commented IN 27/06/2021 - sums ALL client payments AND the unapplied amounts to match the client paid to date //commented IN 27/06/2021 - sums ALL client payments AND the unapplied amounts to match the client paid to date
$p = Payment::where('client_id', $client->id) $p = Payment::where('client_id', $client->id)
->where('is_deleted', 0) ->where('is_deleted', 0)
->whereIn('status_id', [Payment::STATUS_COMPLETED, Payment:: STATUS_PENDING, Payment::STATUS_PARTIALLY_REFUNDED, Payment::STATUS_REFUNDED]) ->whereIn('status_id', [Payment::STATUS_COMPLETED, Payment::STATUS_PENDING, Payment::STATUS_PARTIALLY_REFUNDED, Payment::STATUS_REFUNDED])
->sum(DB::Raw('amount - applied')); ->sum(DB::Raw('amount - applied'));
$total_invoice_payments += $p; $total_invoice_payments += $p;
// 10/02/21 // 10/02/21
foreach ($client->payments as $payment) { foreach ($client->payments as $payment) {
$credit_total_applied += $payment->paymentables() $credit_total_applied += $payment->paymentables()
->where('paymentable_type', App\Models\Credit::class) ->where('paymentable_type', App\Models\Credit::class)
->selectRaw('sum(paymentables.amount - paymentables.refunded) as p') ->selectRaw('sum(paymentables.amount - paymentables.refunded) as p')
@ -656,7 +616,7 @@ class CheckData extends Command
if ($credit_total_applied < 0) { if ($credit_total_applied < 0) {
$total_invoice_payments += $credit_total_applied; $total_invoice_payments += $credit_total_applied;
} }
if (round($total_invoice_payments, 2) != round($client->paid_to_date, 2)) { if (round($total_invoice_payments, 2) != round($client->paid_to_date, 2)) {
$this->wrong_paid_to_dates++; $this->wrong_paid_to_dates++;
@ -665,7 +625,7 @@ class CheckData extends Command
$this->isValid = false; $this->isValid = false;
if($this->option('paid_to_date')){ if ($this->option('paid_to_date')) {
$this->logMessage("# {$client->id} " . $client->present()->name().' - '.$client->number." Fixing {$client->paid_to_date} to {$total_invoice_payments}"); $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->paid_to_date = $total_invoice_payments;
$client->save(); $client->save();
@ -681,11 +641,9 @@ class CheckData extends Command
$this->wrong_balances = 0; $this->wrong_balances = 0;
Client::cursor()->where('is_deleted', 0)->where('clients.updated_at', '>', now()->subDays(2))->each(function ($client) { 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) { $client->invoices->where('is_deleted', false)->whereIn('status_id', '!=', Invoice::STATUS_DRAFT)->each(function ($invoice) use ($client) {
$total_paid = $invoice->payments() $total_paid = $invoice->payments()
->where('is_deleted', false)->whereIn('status_id', [Payment::STATUS_COMPLETED, Payment:: STATUS_PENDING, Payment::STATUS_PARTIALLY_REFUNDED, Payment::STATUS_REFUNDED]) ->where('is_deleted', false)->whereIn('status_id', [Payment::STATUS_COMPLETED, Payment::STATUS_PENDING, Payment::STATUS_PARTIALLY_REFUNDED, Payment::STATUS_REFUNDED])
->selectRaw('sum(paymentables.amount - paymentables.refunded) as p') ->selectRaw('sum(paymentables.amount - paymentables.refunded) as p')
->pluck('p') ->pluck('p')
->first(); ->first();
@ -702,7 +660,6 @@ class CheckData extends Command
$this->isValid = false; $this->isValid = false;
} }
}); });
}); });
$this->logMessage("{$this->wrong_balances} clients with incorrect invoice balances"); $this->logMessage("{$this->wrong_balances} clients with incorrect invoice balances");
@ -710,7 +667,7 @@ class CheckData extends Command
private function clientBalanceQuery() private function clientBalanceQuery()
{ {
$results = \DB::select( \DB::raw(" $results = \DB::select(\DB::raw("
SELECT SELECT
SUM(invoices.balance) as invoice_balance, SUM(invoices.balance) as invoice_balance,
clients.id as client_id, clients.id as client_id,
@ -724,7 +681,7 @@ class CheckData extends Command
GROUP BY clients.id GROUP BY clients.id
HAVING invoice_balance != clients.balance HAVING invoice_balance != clients.balance
ORDER BY clients.id; ORDER BY clients.id;
") ); "));
return $results; return $results;
} }
@ -736,8 +693,7 @@ class CheckData extends Command
$clients = $this->clientBalanceQuery(); $clients = $this->clientBalanceQuery();
foreach($clients as $client) foreach ($clients as $client) {
{
$client = (array)$client; $client = (array)$client;
if ((string) $client['invoice_balance'] != (string) $client['client_balance']) { if ((string) $client['invoice_balance'] != (string) $client['client_balance']) {
@ -747,18 +703,14 @@ class CheckData extends Command
$this->logMessage($client_object->present()->name().' - '.$client_object->id." - calculated client balances do not match Invoice Balances = ". $client['invoice_balance'] ." - Client Balance = ".rtrim($client['client_balance'], '0')); $this->logMessage($client_object->present()->name().' - '.$client_object->id." - calculated client balances do not match Invoice Balances = ". $client['invoice_balance'] ." - Client Balance = ".rtrim($client['client_balance'], '0'));
if($this->option('client_balance')){ if ($this->option('client_balance')) {
$this->logMessage("# {$client_object->id} " . $client_object->present()->name().' - '.$client_object->number." Fixing {$client_object->balance} to " . $client['invoice_balance']); $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->balance = $client['invoice_balance'];
$client_object->save(); $client_object->save();
} }
$this->isValid = false; $this->isValid = false;
} }
} }
$this->logMessage("{$this->wrong_paid_to_dates} clients with incorrect client balances"); $this->logMessage("{$this->wrong_paid_to_dates} clients with incorrect client balances");
@ -767,58 +719,46 @@ class CheckData extends Command
private function checkClientBalanceEdgeCases() private function checkClientBalanceEdgeCases()
{ {
Client::query() Client::query()
->where('is_deleted',false) ->where('is_deleted', false)
->where('balance', '!=', 0) ->where('balance', '!=', 0)
->cursor() ->cursor()
->each(function ($client){ ->each(function ($client) {
$count = Invoice::withTrashed()
->where('client_id', $client->id)
->where('is_deleted', false)
->whereIn('status_id', [2,3])
->count();
$count = Invoice::withTrashed() if ($count == 0) {
->where('client_id', $client->id) //factor in over payments to the client balance
->where('is_deleted',false) $over_payment = Payment::where('client_id', $client->id)
->whereIn('status_id', [2,3]) ->where('is_deleted', 0)
->count(); ->whereIn('status_id', [1,4])
->selectRaw('sum(amount - applied) as p')
->pluck('p')
->first();
if($count == 0){ $over_payment = $over_payment*-1;
//factor in over payments to the client balance
$over_payment = Payment::where('client_id', $client->id)
->where('is_deleted', 0)
->whereIn('status_id', [1,4])
->selectRaw('sum(amount - applied) as p')
->pluck('p')
->first();
$over_payment = $over_payment*-1; if (floatval($over_payment) == floatval($client->balance)) {
} else {
if(floatval($over_payment) == floatval($client->balance)){ $this->logMessage("# {$client->id} # {$client->name} {$client->balance} is invalid should be {$over_payment}");
}
}
else {
$this->logMessage("# {$client->id} # {$client->name} {$client->balance} is invalid should be {$over_payment}");
}
if($this->option('client_balance') && (floatval($over_payment) != floatval($client->balance) )){ if ($this->option('client_balance') && (floatval($over_payment) != floatval($client->balance))) {
$this->logMessage("# {$client->id} " . $client->present()->name().' - '.$client->number." Fixing {$client->balance} to 0");
$this->logMessage("# {$client->id} " . $client->present()->name().' - '.$client->number." Fixing {$client->balance} to 0");
$client->balance = $over_payment;
$client->save();
}
}
$client->balance = $over_payment;
$client->save();
}
}
}); });
} }
private function invoiceBalanceQuery() private function invoiceBalanceQuery()
{ {
$results = \DB::select( \DB::raw(" $results = \DB::select(\DB::raw("
SELECT SELECT
clients.id, clients.id,
clients.balance, clients.balance,
@ -832,7 +772,7 @@ class CheckData extends Command
GROUP BY clients.id GROUP BY clients.id
HAVING(invoices_balance != clients.balance) HAVING(invoices_balance != clients.balance)
ORDER BY clients.id; ORDER BY clients.id;
") ); "));
return $results; return $results;
} }
@ -844,8 +784,7 @@ class CheckData extends Command
$_clients = $this->invoiceBalanceQuery(); $_clients = $this->invoiceBalanceQuery();
foreach($_clients as $_client) foreach ($_clients as $_client) {
{
$client = Client::withTrashed()->find($_client->id); $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');
@ -860,27 +799,22 @@ class CheckData extends Command
$this->isValid = false; $this->isValid = false;
if($this->option('client_balance')){ if ($this->option('client_balance')) {
$this->logMessage("# {$client->id} " . $client->present()->name().' - '.$client->number." Fixing {$client->balance} to {$invoice_balance}"); $this->logMessage("# {$client->id} " . $client->present()->name().' - '.$client->number." Fixing {$client->balance} to {$invoice_balance}");
$client->balance = $invoice_balance; $client->balance = $invoice_balance;
$client->save(); $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->adjustment = $invoice_balance;
$ledger->balance = $invoice_balance; $ledger->balance = $invoice_balance;
$ledger->notes = 'Ledger Adjustment'; $ledger->notes = 'Ledger Adjustment';
$ledger->save(); $ledger->save();
} }
} }
} }
$this->logMessage("{$this->wrong_balances} clients with incorrect balances"); $this->logMessage("{$this->wrong_balances} clients with incorrect balances");
} }
private function checkLedgerBalances() private function checkLedgerBalances()
@ -899,8 +833,7 @@ class CheckData extends Command
$this->isValid = false; $this->isValid = false;
if($this->option('ledger_balance')){ if ($this->option('ledger_balance')) {
$this->logMessage("# {$client->id} " . $client->present()->name().' - '.$client->number." Fixing {$client->balance} to {$invoice_balance}"); $this->logMessage("# {$client->id} " . $client->present()->name().' - '.$client->number." Fixing {$client->balance} to {$invoice_balance}");
$client->balance = $invoice_balance; $client->balance = $invoice_balance;
$client->save(); $client->save();
@ -910,7 +843,6 @@ class CheckData extends Command
$ledger->notes = 'Ledger Adjustment'; $ledger->notes = 'Ledger Adjustment';
$ledger->save(); $ledger->save();
} }
} }
} }
@ -1002,31 +934,27 @@ class CheckData extends Command
public function checkAccountStatuses() 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(); $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') $payment = Payment::on('db-ninja-01')
->where('company_id', config('ninja.ninja_default_company_id')) ->where('company_id', config('ninja.ninja_default_company_id'))
->where('client_id', $client->id) ->where('client_id', $client->id)
->where('date', '>=', now()->subDays(2)) ->where('date', '>=', now()->subDays(2))
->exists(); ->exists();
if($payment) if ($payment) {
$this->logMessage("I found a payment for {$account->key}"); $this->logMessage("I found a payment for {$account->key}");
}
} }
}); });
} }
public function checkClientSettings() public function checkClientSettings()
{ {
if ($this->option('fix') == 'true') { if ($this->option('fix') == 'true') {
// Client::query()->whereNull('settings->currency_id')->cursor()->each(function ($client){ // Client::query()->whereNull('settings->currency_id')->cursor()->each(function ($client){
// if(is_array($client->settings) && count($client->settings) == 0) // if(is_array($client->settings) && count($client->settings) == 0)
@ -1047,36 +975,25 @@ class CheckData extends Command
// }); // });
Client::query()->whereNull('country_id')->cursor()->each(function ($client){ Client::query()->whereNull('country_id')->cursor()->each(function ($client) {
$client->country_id = $client->company->settings->country_id; $client->country_id = $client->company->settings->country_id;
$client->save(); $client->save();
$this->logMessage("Fixing country for # {$client->id}"); $this->logMessage("Fixing country for # {$client->id}");
}); });
} }
} }
public function checkVendorSettings() public function checkVendorSettings()
{ {
if ($this->option('fix') == 'true') {
if ($this->option('fix') == 'true') Vendor::query()->whereNull('currency_id')->orWhere('currency_id', '')->cursor()->each(function ($vendor) {
{
Vendor::query()->whereNull('currency_id')->orWhere('currency_id', '')->cursor()->each(function ($vendor){
$vendor->currency_id = $vendor->company->settings->currency_id; $vendor->currency_id = $vendor->company->settings->currency_id;
$vendor->save(); $vendor->save();
$this->logMessage("Fixing vendor currency for # {$vendor->id}"); $this->logMessage("Fixing vendor currency for # {$vendor->id}");
}); });
} }
} }
@ -1085,14 +1002,12 @@ class CheckData extends Command
{ {
$this->wrong_paid_status = 0; $this->wrong_paid_status = 0;
foreach(Invoice::with(['payments'])->where('is_deleted',0)->where('balance', '>', 0)->whereHas('payments')->where('status_id', 4)->cursor() as $invoice) foreach (Invoice::with(['payments'])->where('is_deleted', 0)->where('balance', '>', 0)->whereHas('payments')->where('status_id', 4)->cursor() as $invoice) {
{
$this->wrong_paid_status++; $this->wrong_paid_status++;
$this->logMessage("# {$invoice->id} " . ' - '.$invoice->number." - Marked as paid, but balance = {$invoice->balance}"); $this->logMessage("# {$invoice->id} " . ' - '.$invoice->number." - Marked as paid, but balance = {$invoice->balance}");
if($this->option('balance_status')){ if ($this->option('balance_status')) {
$val = $invoice->balance; $val = $invoice->balance;
$invoice->balance = 0; $invoice->balance = 0;
@ -1101,8 +1016,7 @@ class CheckData extends Command
$p = $invoice->payments->first(); $p = $invoice->payments->first();
if($p && (int)$p->amount == 0) if ($p && (int)$p->amount == 0) {
{
$p->amount = $val; $p->amount = $val;
$p->applied = $val; $p->applied = $val;
$p->save(); $p->save();
@ -1114,62 +1028,48 @@ class CheckData extends Command
$this->logMessage("Fixing {$invoice->id} settings payment to {$val}"); $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");
} }
public function checkNinjaPortalUrls() public function checkNinjaPortalUrls()
{ {
$wrong_count = CompanyUser::where('is_owner', 1)->where('ninja_portal_url', '')->count();
$wrong_count = CompanyUser::where('is_owner',1)->where('ninja_portal_url', '')->count();
$this->logMessage("Missing ninja portal Urls = {$wrong_count}"); $this->logMessage("Missing ninja portal Urls = {$wrong_count}");
if(!$this->option('portal_url')) if (!$this->option('portal_url')) {
return; return;
}
CompanyUser::where('is_owner',1)->where('ninja_portal_url', '')->cursor()->each(function ($cu){ CompanyUser::where('is_owner', 1)->where('ninja_portal_url', '')->cursor()->each(function ($cu) {
$cc = ClientContact::on('db-ninja-01')->where('company_id', config('ninja.ninja_default_company_id'))->where('email', $cu->user->email)->first();
$cc = ClientContact::on('db-ninja-01')->where('company_id', config('ninja.ninja_default_company_id'))->where('email', $cu->user->email)->first(); if ($cc) {
if($cc){
$ninja_portal_url = "https://invoiceninja.invoicing.co/client/ninja/{$cc->contact_key}/{$cu->account->key}"; $ninja_portal_url = "https://invoiceninja.invoicing.co/client/ninja/{$cc->contact_key}/{$cu->account->key}";
$cu->ninja_portal_url = $ninja_portal_url; $cu->ninja_portal_url = $ninja_portal_url;
$cu->save(); $cu->save();
$this->logMessage("Fixing - {$ninja_portal_url}"); $this->logMessage("Fixing - {$ninja_portal_url}");
} } else {
else{
$c = Client::on('db-ninja-01')->where("company_id", config('ninja.ninja_default_company_id'))->where('custom_value2', $cu->account->key)->first(); $c = Client::on('db-ninja-01')->where("company_id", config('ninja.ninja_default_company_id'))->where('custom_value2', $cu->account->key)->first();
if($c) if ($c) {
{ $cc = $c->contacts()->first();
$cc = $c->contacts()->first();
if($cc) if ($cc) {
{
$ninja_portal_url = "https://invoiceninja.invoicing.co/client/ninja/{$cc->contact_key}/{$cu->account->key}"; $ninja_portal_url = "https://invoiceninja.invoicing.co/client/ninja/{$cc->contact_key}/{$cu->account->key}";
$cu->ninja_portal_url = $ninja_portal_url; $cu->ninja_portal_url = $ninja_portal_url;
$cu->save(); $cu->save();
$this->logMessage("Fixing - {$ninja_portal_url}"); $this->logMessage("Fixing - {$ninja_portal_url}");
}
} }
}
} }
}); });
} }
} }

View File

@ -11,8 +11,6 @@
namespace App\Console\Commands; namespace App\Console\Commands;
use App;
use App\Factory\ClientContactFactory;
use App\Models\Account; use App\Models\Account;
use App\Models\Activity; use App\Models\Activity;
use App\Models\Backup; use App\Models\Backup;
@ -24,7 +22,6 @@ use App\Models\CompanyGateway;
use App\Models\CompanyLedger; use App\Models\CompanyLedger;
use App\Models\CompanyToken; use App\Models\CompanyToken;
use App\Models\CompanyUser; use App\Models\CompanyUser;
use App\Models\Contact;
use App\Models\Credit; use App\Models\Credit;
use App\Models\CreditInvitation; use App\Models\CreditInvitation;
use App\Models\Design; use App\Models\Design;
@ -53,13 +50,7 @@ use App\Models\User;
use App\Models\Vendor; use App\Models\Vendor;
use App\Models\VendorContact; use App\Models\VendorContact;
use App\Models\Webhook; use App\Models\Webhook;
use App\Utils\Ninja;
use DB;
use Exception;
use Illuminate\Console\Command; use Illuminate\Console\Command;
use Illuminate\Support\Str;
use Mail;
use Symfony\Component\Console\Input\InputOption;
/** /**
* Class CheckDb. * Class CheckDb.

View File

@ -13,40 +13,19 @@ namespace App\Console\Commands;
use App\DataMapper\ClientRegistrationFields; use App\DataMapper\ClientRegistrationFields;
use App\DataMapper\CompanySettings; use App\DataMapper\CompanySettings;
use App\DataMapper\FeesAndLimits;
use App\Events\Invoice\InvoiceWasCreated;
use App\Factory\InvoiceFactory;
use App\Factory\InvoiceItemFactory;
use App\Helpers\Invoice\InvoiceSum;
use App\Jobs\Company\CreateCompanyPaymentTerms; use App\Jobs\Company\CreateCompanyPaymentTerms;
use App\Jobs\Company\CreateCompanyTaskStatuses; use App\Jobs\Company\CreateCompanyTaskStatuses;
use App\Jobs\Util\VersionCheck; use App\Jobs\Util\VersionCheck;
use App\Models\Account; use App\Models\Account;
use App\Models\Client;
use App\Models\ClientContact;
use App\Models\Company; use App\Models\Company;
use App\Models\CompanyGateway;
use App\Models\CompanyToken; use App\Models\CompanyToken;
use App\Models\Country;
use App\Models\Credit;
use App\Models\Expense;
use App\Models\Product;
use App\Models\Project;
use App\Models\Quote;
use App\Models\Task;
use App\Models\User; use App\Models\User;
use App\Models\Vendor;
use App\Models\VendorContact;
use App\Repositories\InvoiceRepository; use App\Repositories\InvoiceRepository;
use App\Utils\Ninja;
use App\Utils\Traits\GeneratesCounter; use App\Utils\Traits\GeneratesCounter;
use App\Utils\Traits\MakesHash; use App\Utils\Traits\MakesHash;
use Carbon\Carbon;
use Faker\Factory;
use Illuminate\Console\Command; use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str; use Illuminate\Support\Str;
class CreateAccount extends Command class CreateAccount extends Command
@ -140,7 +119,6 @@ class CreateAccount extends Command
(new VersionCheck())->handle(); (new VersionCheck())->handle();
$this->warmCache(); $this->warmCache();
} }
private function warmCache() private function warmCache()
@ -162,7 +140,6 @@ class CreateAccount extends Command
if ($tableData->count()) { if ($tableData->count()) {
Cache::forever($name, $tableData); Cache::forever($name, $tableData);
} }
} }
} }
} }

View File

@ -50,13 +50,11 @@ use App\Utils\Ninja;
use App\Utils\Traits\GeneratesCounter; use App\Utils\Traits\GeneratesCounter;
use App\Utils\Traits\MakesHash; use App\Utils\Traits\MakesHash;
use Carbon\Carbon; use Carbon\Carbon;
use Database\Factories\BankTransactionRuleFactory;
use Faker\Factory; use Faker\Factory;
use Illuminate\Console\Command; use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Schema; use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
use stdClass; use stdClass;
class CreateSingleAccount extends Command class CreateSingleAccount extends Command
@ -80,9 +78,9 @@ class CreateSingleAccount extends Command
*/ */
public function handle() public function handle()
{ {
if (Ninja::isHosted() || config('ninja.is_docker') || !$this->confirm('Are you sure you want to inject dummy data?')) {
if (Ninja::isHosted() || config('ninja.is_docker') || !$this->confirm('Are you sure you want to inject dummy data?'))
return; return;
}
$this->invoice_repo = new InvoiceRepository(); $this->invoice_repo = new InvoiceRepository();
@ -103,8 +101,7 @@ class CreateSingleAccount extends Command
{ {
$this->info('Creating Small Account and Company'); $this->info('Creating Small Account and Company');
if($user = User::where('email','small@example.com')->first()) if ($user = User::where('email', 'small@example.com')->first()) {
{
$user->account->delete(); $user->account->delete();
} }
@ -201,7 +198,7 @@ class CreateSingleAccount extends Command
$btr = BankTransactionRule::factory()->create([ $btr = BankTransactionRule::factory()->create([
'user_id' => $user->id, 'user_id' => $user->id,
'company_id' => $company->id, 'company_id' => $company->id,
'applies_to' => (bool)rand(0,1) ? 'CREDIT' : 'DEBIT', 'applies_to' => (bool)rand(0, 1) ? 'CREDIT' : 'DEBIT',
]); ]);
$client = Client::factory()->create([ $client = Client::factory()->create([
@ -359,7 +356,6 @@ class CreateSingleAccount extends Command
private function createClient($company, $user) private function createClient($company, $user)
{ {
// dispatch(function () use ($company, $user) { // dispatch(function () use ($company, $user) {
// }); // });
@ -630,30 +626,29 @@ class CreateSingleAccount extends Command
$cached_tables = config('ninja.cached_tables'); $cached_tables = config('ninja.cached_tables');
foreach ($cached_tables as $name => $class) { foreach ($cached_tables as $name => $class) {
// check that the table exists in case the migration is pending // check that the table exists in case the migration is pending
if (! Schema::hasTable((new $class())->getTable())) { if (! Schema::hasTable((new $class())->getTable())) {
continue; continue;
} }
if ($name == 'payment_terms') { if ($name == 'payment_terms') {
$orderBy = 'num_days'; $orderBy = 'num_days';
} elseif ($name == 'fonts') { } elseif ($name == 'fonts') {
$orderBy = 'sort_order'; $orderBy = 'sort_order';
} elseif (in_array($name, ['currencies', 'industries', 'languages', 'countries', 'banks'])) { } elseif (in_array($name, ['currencies', 'industries', 'languages', 'countries', 'banks'])) {
$orderBy = 'name'; $orderBy = 'name';
} else { } else {
$orderBy = 'id'; $orderBy = 'id';
} }
$tableData = $class::orderBy($orderBy)->get(); $tableData = $class::orderBy($orderBy)->get();
if ($tableData->count()) { if ($tableData->count()) {
Cache::forever($name, $tableData); Cache::forever($name, $tableData);
} }
} }
} }
private function createGateways($company, $user) private function createGateways($company, $user)
{ {
if (config('ninja.testvars.stripe') && ($this->gateway == 'all' || $this->gateway == 'stripe')) { if (config('ninja.testvars.stripe') && ($this->gateway == 'all' || $this->gateway == 'stripe')) {
$cg = new CompanyGateway; $cg = new CompanyGateway;
$cg->company_id = $company->id; $cg->company_id = $company->id;
$cg->user_id = $user->id; $cg->user_id = $user->id;
@ -672,8 +667,6 @@ class CreateSingleAccount extends Command
$cg->fees_and_limits = $fees_and_limits; $cg->fees_and_limits = $fees_and_limits;
$cg->save(); $cg->save();
} }
if (config('ninja.testvars.paypal') && ($this->gateway == 'all' || $this->gateway == 'paypal')) { if (config('ninja.testvars.paypal') && ($this->gateway == 'all' || $this->gateway == 'paypal')) {

View File

@ -380,7 +380,6 @@ class CreateTestData extends Command
private function createClient($company, $user) private function createClient($company, $user)
{ {
// dispatch(function () use ($company, $user) { // dispatch(function () use ($company, $user) {
// }); // });

View File

@ -257,7 +257,6 @@ class DemoMode extends Command
private function createClient($company, $user, $assigned_user_id = null) private function createClient($company, $user, $assigned_user_id = null)
{ {
// dispatch(function () use ($company, $user) { // dispatch(function () use ($company, $user) {
// }); // });

View File

@ -56,7 +56,6 @@ class DesignUpdate extends Command
if (! config('ninja.db.multi_db_enabled')) { if (! config('ninja.db.multi_db_enabled')) {
$this->handleOnDb(); $this->handleOnDb();
} else { } else {
//multiDB environment, need to //multiDB environment, need to
foreach (MultiDB::$dbs as $db) { foreach (MultiDB::$dbs as $db) {
MultiDB::setDB($db); MultiDB::setDB($db);

View File

@ -11,27 +11,19 @@
namespace App\Console\Commands; namespace App\Console\Commands;
use App\DataMapper\CompanySettings;
use App\Exceptions\MigrationValidatorFailed; use App\Exceptions\MigrationValidatorFailed;
use App\Exceptions\NonExistingMigrationFile; use App\Exceptions\NonExistingMigrationFile;
use App\Exceptions\ProcessingMigrationArchiveFailed; use App\Exceptions\ProcessingMigrationArchiveFailed;
use App\Exceptions\ResourceDependencyMissing; use App\Exceptions\ResourceDependencyMissing;
use App\Exceptions\ResourceNotAvailableForMigration; use App\Exceptions\ResourceNotAvailableForMigration;
use App\Jobs\Util\Import; use App\Jobs\Util\Import;
use App\Jobs\Util\StartMigration;
use App\Libraries\MultiDB; use App\Libraries\MultiDB;
use App\Mail\MigrationFailed; use App\Mail\MigrationFailed;
use App\Models\Account;
use App\Models\Company;
use App\Models\CompanyToken;
use App\Models\User; use App\Models\User;
use App\Utils\Traits\AppSetup; use App\Utils\Traits\AppSetup;
use App\Utils\Traits\MakesHash; use App\Utils\Traits\MakesHash;
use DirectoryIterator; use DirectoryIterator;
use Faker\Factory;
use Faker\Generator;
use Illuminate\Console\Command; use Illuminate\Console\Command;
use Illuminate\Support\Str;
use ZipArchive; use ZipArchive;
class HostedMigrations extends Command class HostedMigrations extends Command

View File

@ -11,9 +11,7 @@
namespace App\Console\Commands; namespace App\Console\Commands;
use App\Models\ClientContact;
use App\Models\Company; use App\Models\Company;
use App\Models\User;
use App\Utils\Ninja; use App\Utils\Ninja;
use Illuminate\Console\Command; use Illuminate\Console\Command;

View File

@ -11,8 +11,6 @@
namespace App\Console\Commands; namespace App\Console\Commands;
use App\Models\Company;
use App\Models\User;
use App\Utils\CurlUtils; use App\Utils\CurlUtils;
use Illuminate\Console\Command; use Illuminate\Console\Command;

View File

@ -63,9 +63,7 @@ class OpenApiYaml extends Command
$this->info($directory); $this->info($directory);
foreach ($directory as $file) { foreach ($directory as $file) {
$this->info($file);
$this->info($file);
} }
Storage::disk('base')->delete('/openapi/api-docs.yaml'); Storage::disk('base')->delete('/openapi/api-docs.yaml');
@ -76,14 +74,9 @@ class OpenApiYaml extends Command
$directory = new DirectoryIterator($path . '/paths/'); $directory = new DirectoryIterator($path . '/paths/');
foreach ($directory as $file) { foreach ($directory as $file) {
if ($file->isFile() && ! $file->isDot()) {
if ($file->isFile() && ! $file->isDot())
{
Storage::disk('base')->append('/openapi/api-docs.yaml', file_get_contents("{$path}/paths/{$file->getFilename()}")); Storage::disk('base')->append('/openapi/api-docs.yaml', file_get_contents("{$path}/paths/{$file->getFilename()}"));
} }
} }
@ -96,20 +89,12 @@ class OpenApiYaml extends Command
$directory = new DirectoryIterator($path . '/components/schemas/'); $directory = new DirectoryIterator($path . '/components/schemas/');
foreach ($directory as $file) { foreach ($directory as $file) {
if ($file->isFile() && ! $file->isDot()) {
if ($file->isFile() && ! $file->isDot())
{
Storage::disk('base')->append('/openapi/api-docs.yaml', file_get_contents("{$path}/components/schemas/{$file->getFilename()}")); Storage::disk('base')->append('/openapi/api-docs.yaml', file_get_contents("{$path}/components/schemas/{$file->getFilename()}"));
} }
} }
// Storage::disk('base')->append('/openapi/api-docs.yaml', file_get_contents($path.'/components/schemas/account.yaml')); // Storage::disk('base')->append('/openapi/api-docs.yaml', file_get_contents($path.'/components/schemas/account.yaml'));
Storage::disk('base')->append('/openapi/api-docs.yaml', file_get_contents($path.'/misc/misc.yaml')); Storage::disk('base')->append('/openapi/api-docs.yaml', file_get_contents($path.'/misc/misc.yaml'));
} }
} }

View File

@ -12,7 +12,6 @@
namespace App\Console\Commands; namespace App\Console\Commands;
use App\Jobs\Util\VersionCheck; use App\Jobs\Util\VersionCheck;
use App\Utils\Ninja;
use App\Utils\Traits\AppSetup; use App\Utils\Traits\AppSetup;
use Illuminate\Console\Command; use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan; use Illuminate\Support\Facades\Artisan;

View File

@ -11,12 +11,7 @@
namespace App\Console\Commands; namespace App\Console\Commands;
use App\Libraries\MultiDB;
use App\Models\Backup;
use App\Models\Design;
use Illuminate\Console\Command; use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;
use stdClass;
class ReactBuilder extends Command class ReactBuilder extends Command
{ {

View File

@ -14,7 +14,6 @@ namespace App\Console\Commands;
use App\DataMapper\InvoiceItem; use App\DataMapper\InvoiceItem;
use App\Events\Invoice\InvoiceWasEmailed; use App\Events\Invoice\InvoiceWasEmailed;
use App\Jobs\Entity\EmailEntity; use App\Jobs\Entity\EmailEntity;
use App\Jobs\Ninja\SendReminders;
use App\Jobs\Util\WebhookHandler; use App\Jobs\Util\WebhookHandler;
use App\Libraries\MultiDB; use App\Libraries\MultiDB;
use App\Models\Invoice; use App\Models\Invoice;
@ -97,7 +96,6 @@ class SendRemindersCron extends Command
$invoice->save(); $invoice->save();
} }
}); });
} }
private function calcLateFee($invoice, $template) :Invoice private function calcLateFee($invoice, $template) :Invoice

View File

@ -13,22 +13,14 @@ namespace App\Console\Commands;
use App\DataMapper\CompanySettings; use App\DataMapper\CompanySettings;
use App\DataMapper\DefaultSettings; use App\DataMapper\DefaultSettings;
use App\Factory\ClientFactory;
use App\Factory\InvoiceFactory;
use App\Factory\InvoiceInvitationFactory;
use App\Jobs\Invoice\CreateEntityPdf;
use App\Jobs\Mail\NinjaMailerJob; use App\Jobs\Mail\NinjaMailerJob;
use App\Jobs\Mail\NinjaMailerObject; use App\Jobs\Mail\NinjaMailerObject;
use App\Mail\Migration\MaxCompanies; use App\Mail\Migration\MaxCompanies;
use App\Mail\TemplateEmail;
use App\Models\Account; use App\Models\Account;
use App\Models\Client;
use App\Models\ClientContact;
use App\Models\Company; use App\Models\Company;
use App\Models\User; use App\Models\User;
use Faker\Factory; use Faker\Factory;
use Illuminate\Console\Command; use Illuminate\Console\Command;
use Illuminate\Support\Facades\Mail;
class SendTestEmails extends Command class SendTestEmails extends Command
{ {

View File

@ -11,14 +11,10 @@
namespace App\Console\Commands; namespace App\Console\Commands;
use App\Libraries\MultiDB;
use App\Models\Backup;
use App\Models\Design;
use Illuminate\Console\Command; use Illuminate\Console\Command;
use Illuminate\Support\Arr; use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Lang; use Illuminate\Support\Facades\Lang;
use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Storage;
use stdClass;
class TranslationsExport extends Command class TranslationsExport extends Command
{ {
@ -98,42 +94,35 @@ class TranslationsExport extends Command
{ {
$type =$this->option('type') ?? 'export'; $type =$this->option('type') ?? 'export';
if($type == 'import') if ($type == 'import') {
$this->import(); $this->import();
}
if($type == 'export') if ($type == 'export') {
$this->export(); $this->export();
}
} }
private function import() private function import()
{ {
//loop and //loop and
foreach($this->langs as $lang) foreach ($this->langs as $lang) {
{
$import_file = "textsphp_{$lang}.php"; $import_file = "textsphp_{$lang}.php";
$dir = $this->option('path') ?? storage_path('lang_import/'); $dir = $this->option('path') ?? storage_path('lang_import/');
$path = $dir.$import_file; $path = $dir.$import_file;
if(file_exists($path)){ if (file_exists($path)) {
$this->logMessage($path); $this->logMessage($path);
$trans = file_get_contents($path); $trans = file_get_contents($path);
file_put_contents(lang_path("/{$lang}/texts.php"), $trans); file_put_contents(lang_path("/{$lang}/texts.php"), $trans);
} else {
}
else{
$this->logMessage("Could not open file"); $this->logMessage("Could not open file");
$this->logMessage($path); $this->logMessage($path);
} }
} }
} }
@ -147,7 +136,7 @@ class TranslationsExport extends Command
$translations = Lang::getLoader()->load($lang, 'texts'); $translations = Lang::getLoader()->load($lang, 'texts');
Storage::disk('local')->put("lang/{$lang}/{$lang}.json", json_encode(Arr::dot($translations), JSON_UNESCAPED_UNICODE)); Storage::disk('local')->put("lang/{$lang}/{$lang}.json", json_encode(Arr::dot($translations), JSON_UNESCAPED_UNICODE));
} }
} }
private function logMessage($str) private function logMessage($str)
@ -156,5 +145,4 @@ class TranslationsExport extends Command
$this->info($str); $this->info($str);
$this->log .= $str."\n"; $this->log .= $str."\n";
} }
} }

View File

@ -11,17 +11,11 @@
namespace App\Console\Commands; namespace App\Console\Commands;
use App\Http\ValidationRules\ValidClientGroupSettingsRule;
use App\Libraries\MultiDB; use App\Libraries\MultiDB;
use App\Models\Backup;
use App\Models\Client; use App\Models\Client;
use App\Models\Company; use App\Models\Company;
use App\Models\Design;
use App\Utils\Traits\ClientGroupSettingsSaver; use App\Utils\Traits\ClientGroupSettingsSaver;
use Illuminate\Console\Command; use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use stdClass;
class TypeCheck extends Command class TypeCheck extends Command
{ {

View File

@ -15,14 +15,13 @@ use App\Jobs\Cron\AutoBillCron;
use App\Jobs\Cron\RecurringExpensesCron; use App\Jobs\Cron\RecurringExpensesCron;
use App\Jobs\Cron\RecurringInvoicesCron; use App\Jobs\Cron\RecurringInvoicesCron;
use App\Jobs\Cron\SubscriptionCron; use App\Jobs\Cron\SubscriptionCron;
use App\Jobs\Ledger\LedgerBalanceUpdate; use App\Jobs\Invoice\InvoiceCheckLateWebhook;
use App\Jobs\Ninja\AdjustEmailQuota; use App\Jobs\Ninja\AdjustEmailQuota;
use App\Jobs\Ninja\BankTransactionSync; use App\Jobs\Ninja\BankTransactionSync;
use App\Jobs\Ninja\CompanySizeCheck; use App\Jobs\Ninja\CompanySizeCheck;
use App\Jobs\Ninja\QueueSize; use App\Jobs\Ninja\QueueSize;
use App\Jobs\Ninja\SystemMaintenance; use App\Jobs\Ninja\SystemMaintenance;
use App\Jobs\Ninja\TaskScheduler; use App\Jobs\Ninja\TaskScheduler;
use App\Jobs\Invoice\InvoiceCheckLateWebhook;
use App\Jobs\Quote\QuoteCheckExpired; use App\Jobs\Quote\QuoteCheckExpired;
use App\Jobs\Subscription\CleanStaleInvoiceOrder; use App\Jobs\Subscription\CleanStaleInvoiceOrder;
use App\Jobs\Util\DiskCleanup; use App\Jobs\Util\DiskCleanup;
@ -96,16 +95,13 @@ class Kernel extends ConsoleKernel
if (Ninja::isSelfHost()) { if (Ninja::isSelfHost()) {
$schedule->call(function () { $schedule->call(function () {
Account::whereNotNull('id')->update(['is_scheduler_running' => true]); Account::whereNotNull('id')->update(['is_scheduler_running' => true]);
})->everyFiveMinutes(); })->everyFiveMinutes();
} }
/* Run hosted specific jobs */ /* Run hosted specific jobs */
if (Ninja::isHosted()) { if (Ninja::isHosted()) {
$schedule->job(new AdjustEmailQuota)->dailyAt('23:30')->withoutOverlapping(); $schedule->job(new AdjustEmailQuota)->dailyAt('23:30')->withoutOverlapping();
/* Pulls in bank transactions from third party services */ /* Pulls in bank transactions from third party services */
@ -119,15 +115,12 @@ class Kernel extends ConsoleKernel
$schedule->command('ninja:check-data --database=db-ninja-02')->dailyAt('02:20')->withoutOverlapping()->name('check-data-db-2-job')->onOneServer(); $schedule->command('ninja:check-data --database=db-ninja-02')->dailyAt('02:20')->withoutOverlapping()->name('check-data-db-2-job')->onOneServer();
$schedule->command('ninja:s3-cleanup')->dailyAt('23:15')->withoutOverlapping()->name('s3-cleanup-job')->onOneServer(); $schedule->command('ninja:s3-cleanup')->dailyAt('23:15')->withoutOverlapping()->name('s3-cleanup-job')->onOneServer();
} }
if (config('queue.default') == 'database' && Ninja::isSelfHost() && config('ninja.internal_queue_enabled') && ! config('ninja.is_docker')) { 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:work database --stop-when-empty --memory=256')->everyMinute()->withoutOverlapping();
$schedule->command('queue:restart')->everyFiveMinutes()->withoutOverlapping(); $schedule->command('queue:restart')->everyFiveMinutes()->withoutOverlapping();
} }
} }

View File

@ -57,5 +57,4 @@ class BaseSettings
return $value; return $value;
} }
} }
} }

View File

@ -762,7 +762,6 @@ class CompanySettings extends BaseSettings
*/ */
public static function defaults(): stdClass public static function defaults(): stdClass
{ {
$data = (object) get_class_vars(self::class); $data = (object) get_class_vars(self::class);
unset($data->casts); unset($data->casts);

View File

@ -20,7 +20,6 @@ class EmailTemplateDefaults
App::setLocale($locale); App::setLocale($locale);
switch ($template) { switch ($template) {
/* Template */ /* Template */
case 'email_template_invoice': case 'email_template_invoice':
@ -65,7 +64,7 @@ class EmailTemplateDefaults
return self::emailPurchaseOrderTemplate(); return self::emailPurchaseOrderTemplate();
break; break;
/* Subject */ /* Subject */
case 'email_subject_purchase_order': case 'email_subject_purchase_order':
return self::emailPurchaseOrderSubject(); return self::emailPurchaseOrderSubject();
case 'email_subject_invoice': case 'email_subject_invoice':
@ -240,7 +239,6 @@ class EmailTemplateDefaults
public static function emailStatementTemplate() public static function emailStatementTemplate()
{ {
$statement_message = '<p>$client<br><br>'.self::transformText('client_statement_body').'<br></p>'; $statement_message = '<p>$client<br><br>'.self::transformText('client_statement_body').'<br></p>';
return $statement_message; return $statement_message;

View File

@ -11,15 +11,11 @@
namespace App\DataMapper\Schedule; namespace App\DataMapper\Schedule;
use App\Models\Client;
use stdClass;
class ClientStatement class ClientStatement
{ {
/** /**
* Defines the template name * Defines the template name
* *
* @var string * @var string
*/ */
public string $template = 'client_statement'; public string $template = 'client_statement';
@ -28,7 +24,7 @@ class ClientStatement
* An array of clients hashed_ids * An array of clients hashed_ids
* *
* Leave blank if this action should apply to all clients * Leave blank if this action should apply to all clients
* *
* @var array * @var array
*/ */
public array $clients = []; public array $clients = [];
@ -46,7 +42,7 @@ class ClientStatement
/** /**
* The date range the statement should include * The date range the statement should include
* *
* @var string * @var string
*/ */
public string $date_range = 'this_month'; public string $date_range = 'this_month';
@ -54,7 +50,7 @@ class ClientStatement
/** /**
* If a custom range is select for the date range then * If a custom range is select for the date range then
* the start_date should be supplied in Y-m-d format * the start_date should be supplied in Y-m-d format
* *
* @var string * @var string
*/ */
public string $start_date = ''; public string $start_date = '';
@ -62,7 +58,7 @@ class ClientStatement
/** /**
* If a custom range is select for the date range then * If a custom range is select for the date range then
* the end_date should be supplied in Y-m-d format * the end_date should be supplied in Y-m-d format
* *
* @var string * @var string
*/ */
public string $end_date = ''; public string $end_date = '';
@ -87,10 +83,8 @@ class ClientStatement
* String const which defines whether * String const which defines whether
* the invoices to be shown are either * the invoices to be shown are either
* paid or unpaid * paid or unpaid
* *
* @var string * @var string
*/ */
public string $status = 'paid'; // paid | unpaid public string $status = 'paid'; // paid | unpaid
}
}

View File

@ -11,10 +11,6 @@
namespace App\DataMapper\Transactions; namespace App\DataMapper\Transactions;
use App\Models\Client;
use App\Models\Credit;
use App\Models\Invoice;
use App\Models\Payment;
use App\Models\TransactionEvent; use App\Models\TransactionEvent;
/** /**

View File

@ -11,10 +11,6 @@
namespace App\DataMapper\Transactions; namespace App\DataMapper\Transactions;
use App\Models\Client;
use App\Models\Credit;
use App\Models\Invoice;
use App\Models\Payment;
use App\Models\TransactionEvent; use App\Models\TransactionEvent;
/** /**

View File

@ -11,10 +11,6 @@
namespace App\DataMapper\Transactions; namespace App\DataMapper\Transactions;
use App\Models\Client;
use App\Models\Credit;
use App\Models\Invoice;
use App\Models\Payment;
use App\Models\TransactionEvent; use App\Models\TransactionEvent;
/** /**

View File

@ -11,10 +11,6 @@
namespace App\DataMapper\Transactions; namespace App\DataMapper\Transactions;
use App\Models\Client;
use App\Models\Credit;
use App\Models\Invoice;
use App\Models\Payment;
use App\Models\TransactionEvent; use App\Models\TransactionEvent;
/** /**

View File

@ -11,10 +11,6 @@
namespace App\DataMapper\Transactions; namespace App\DataMapper\Transactions;
use App\Models\Client;
use App\Models\Credit;
use App\Models\Invoice;
use App\Models\Payment;
use App\Models\TransactionEvent; use App\Models\TransactionEvent;
/** /**

View File

@ -11,10 +11,6 @@
namespace App\DataMapper\Transactions; namespace App\DataMapper\Transactions;
use App\Models\Client;
use App\Models\Credit;
use App\Models\Invoice;
use App\Models\Payment;
use App\Models\TransactionEvent; use App\Models\TransactionEvent;
/** /**

View File

@ -11,10 +11,6 @@
namespace App\DataMapper\Transactions; namespace App\DataMapper\Transactions;
use App\Models\Client;
use App\Models\Credit;
use App\Models\Invoice;
use App\Models\Payment;
use App\Models\TransactionEvent; use App\Models\TransactionEvent;
/** /**

View File

@ -11,10 +11,6 @@
namespace App\DataMapper\Transactions; namespace App\DataMapper\Transactions;
use App\Models\Client;
use App\Models\Credit;
use App\Models\Invoice;
use App\Models\Payment;
use App\Models\TransactionEvent; use App\Models\TransactionEvent;
/** /**

View File

@ -11,10 +11,6 @@
namespace App\DataMapper\Transactions; namespace App\DataMapper\Transactions;
use App\Models\Client;
use App\Models\Credit;
use App\Models\Invoice;
use App\Models\Payment;
use App\Models\TransactionEvent; use App\Models\TransactionEvent;
/** /**

View File

@ -11,10 +11,6 @@
namespace App\DataMapper\Transactions; namespace App\DataMapper\Transactions;
use App\Models\Client;
use App\Models\Credit;
use App\Models\Invoice;
use App\Models\Payment;
use App\Models\TransactionEvent; use App\Models\TransactionEvent;
/** /**

View File

@ -11,10 +11,6 @@
namespace App\DataMapper\Transactions; namespace App\DataMapper\Transactions;
use App\Models\Client;
use App\Models\Credit;
use App\Models\Invoice;
use App\Models\Payment;
use App\Models\TransactionEvent; use App\Models\TransactionEvent;
/** /**

View File

@ -11,10 +11,6 @@
namespace App\DataMapper\Transactions; namespace App\DataMapper\Transactions;
use App\Models\Client;
use App\Models\Credit;
use App\Models\Invoice;
use App\Models\Payment;
use App\Models\TransactionEvent; use App\Models\TransactionEvent;
/** /**

View File

@ -11,10 +11,6 @@
namespace App\DataMapper\Transactions; namespace App\DataMapper\Transactions;
use App\Models\Client;
use App\Models\Credit;
use App\Models\Invoice;
use App\Models\Payment;
use App\Models\TransactionEvent; use App\Models\TransactionEvent;
/** /**

View File

@ -11,10 +11,6 @@
namespace App\DataMapper\Transactions; namespace App\DataMapper\Transactions;
use App\Models\Client;
use App\Models\Credit;
use App\Models\Invoice;
use App\Models\Payment;
use App\Models\TransactionEvent; use App\Models\TransactionEvent;
/** /**

View File

@ -13,7 +13,6 @@ namespace App\Events\PurchaseOrder;
use App\Models\Company; use App\Models\Company;
use App\Models\PurchaseOrder; use App\Models\PurchaseOrder;
use App\Models\PurchaseOrderInvitation;
use App\Models\VendorContact; use App\Models\VendorContact;
use Illuminate\Queue\SerializesModels; use Illuminate\Queue\SerializesModels;

View File

@ -4,11 +4,8 @@ namespace App\Events\Subscription;
use App\Models\Company; use App\Models\Company;
use App\Models\Subscription; use App\Models\Subscription;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets; use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel; use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels; use Illuminate\Queue\SerializesModels;

View File

@ -11,10 +11,6 @@
namespace App\Exceptions; namespace App\Exceptions;
use App\Exceptions\FilePermissionsFailure;
use App\Exceptions\InternalPDFFailure;
use App\Exceptions\PhantomPDFFailure;
use App\Exceptions\StripeConnectFailure;
use App\Utils\Ninja; use App\Utils\Ninja;
use Illuminate\Auth\Access\AuthorizationException; use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Auth\AuthenticationException; use Illuminate\Auth\AuthenticationException;
@ -29,13 +25,13 @@ use Illuminate\Session\TokenMismatchException;
use Illuminate\Support\Arr; use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Schema; use Illuminate\Support\Facades\Schema;
use Illuminate\Validation\ValidationException; use Illuminate\Validation\ValidationException;
use League\Flysystem\UnableToCreateDirectory;
use PDOException; use PDOException;
use Sentry\Laravel\Integration; use Sentry\Laravel\Integration;
use Sentry\State\Scope; use Sentry\State\Scope;
use Symfony\Component\Console\Exception\CommandNotFoundException; use Symfony\Component\Console\Exception\CommandNotFoundException;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException; use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use League\Flysystem\UnableToCreateDirectory;
use Throwable; use Throwable;
class Handler extends ExceptionHandler class Handler extends ExceptionHandler
@ -127,7 +123,6 @@ class Handler extends ExceptionHandler
if ($this->validException($exception) && $this->sentryShouldReport($exception)) { if ($this->validException($exception) && $this->sentryShouldReport($exception)) {
Integration::captureUnhandledException($exception); Integration::captureUnhandledException($exception);
} }
} elseif (app()->bound('sentry')) { } elseif (app()->bound('sentry')) {
Integration::configureScope(function (Scope $scope): void { Integration::configureScope(function (Scope $scope): void {
if (auth()->guard('contact') && auth()->guard('contact')->user() && auth()->guard('contact')->user()->company->account->report_errors) { if (auth()->guard('contact') && auth()->guard('contact')->user() && auth()->guard('contact')->user()->company->account->report_errors) {
@ -191,10 +186,11 @@ class Handler extends ExceptionHandler
*/ */
protected function sentryShouldReport(Throwable $e) protected function sentryShouldReport(Throwable $e)
{ {
if(Ninja::isHosted()) if (Ninja::isHosted()) {
$dontReport = array_merge($this->hostedDontReport, $this->internalDontReport); $dontReport = array_merge($this->hostedDontReport, $this->internalDontReport);
else } else {
$dontReport = array_merge($this->selfHostDontReport, $this->internalDontReport); $dontReport = array_merge($this->selfHostDontReport, $this->internalDontReport);
}
return is_null(Arr::first($dontReport, fn ($type) => $e instanceof $type)); return is_null(Arr::first($dontReport, fn ($type) => $e instanceof $type));
} }
@ -244,7 +240,7 @@ class Handler extends ExceptionHandler
return response()->json(['message' => $exception->getMessage()], 400); return response()->json(['message' => $exception->getMessage()], 400);
} elseif ($exception instanceof StripeConnectFailure) { } elseif ($exception instanceof StripeConnectFailure) {
return response()->json(['message' => $exception->getMessage()], 400); return response()->json(['message' => $exception->getMessage()], 400);
} }
return parent::render($request, $exception); return parent::render($request, $exception);
} }
@ -258,7 +254,7 @@ class Handler extends ExceptionHandler
$guard = Arr::get($exception->guards(), 0); $guard = Arr::get($exception->guards(), 0);
switch ($guard) { switch ($guard) {
case 'contact': case 'contact':
$login = 'client.login'; $login = 'client.login';
break; break;
case 'user': case 'user':

View File

@ -23,8 +23,7 @@ class PaymentFailed extends Exception
public function render($request) public function render($request)
{ {
if (auth()->guard('contact')->user() || ($request->has('cko-session-id') && $request->query('cko-session-id') )) { if (auth()->guard('contact')->user() || ($request->has('cko-session-id') && $request->query('cko-session-id'))) {
return render('gateways.unsuccessful', [ return render('gateways.unsuccessful', [
'message' => $this->getMessage(), 'message' => $this->getMessage(),
'code' => $this->getCode(), 'code' => $this->getCode(),

View File

@ -36,7 +36,6 @@ class PaymentRefundFailed extends Exception
*/ */
public function render($request) public function render($request)
{ {
// $msg = 'Unable to refund the transaction'; // $msg = 'Unable to refund the transaction';
$msg = ctrans('texts.warning_local_refund'); $msg = ctrans('texts.warning_local_refund');

View File

@ -36,7 +36,6 @@ class YodleeApiException extends Exception
*/ */
public function render($request) public function render($request)
{ {
// $msg = 'Unable to refund the transaction'; // $msg = 'Unable to refund the transaction';
$msg = ctrans('texts.error'); $msg = ctrans('texts.error');

View File

@ -32,7 +32,6 @@ class BaseExport
} }
switch ($date_range) { switch ($date_range) {
case 'all': case 'all':
return $query; return $query;
case 'last7': case 'last7':
@ -53,7 +52,6 @@ class BaseExport
return $query->whereBetween($this->date_key, [$custom_start_date, $custom_end_date])->orderBy($this->date_key, 'ASC'); return $query->whereBetween($this->date_key, [$custom_start_date, $custom_end_date])->orderBy($this->date_key, 'ASC');
default: default:
return $query->whereBetween($this->date_key, [now()->startOfYear(), now()])->orderBy($this->date_key, 'ASC'); return $query->whereBetween($this->date_key, [now()->startOfYear(), now()])->orderBy($this->date_key, 'ASC');
} }
} }

View File

@ -17,7 +17,6 @@ use App\Models\Company;
use App\Transformers\ClientContactTransformer; use App\Transformers\ClientContactTransformer;
use App\Transformers\ClientTransformer; use App\Transformers\ClientTransformer;
use App\Utils\Ninja; use App\Utils\Ninja;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\App; use Illuminate\Support\Facades\App;
use League\Csv\Writer; use League\Csv\Writer;
@ -181,11 +180,13 @@ class ClientExport extends BaseExport
private function calculateStatus($client) private function calculateStatus($client)
{ {
if($client->is_deleted) if ($client->is_deleted) {
return ctrans('texts.deleted'); return ctrans('texts.deleted');
}
if($client->deleted_at) if ($client->deleted_at) {
return ctrans('texts.arcvived'); return ctrans('texts.arcvived');
}
return ctrans('texts.active'); return ctrans('texts.active');
} }

View File

@ -12,7 +12,6 @@
namespace App\Export\CSV; namespace App\Export\CSV;
use App\Libraries\MultiDB; use App\Libraries\MultiDB;
use App\Models\Client;
use App\Models\Company; use App\Models\Company;
use App\Models\Credit; use App\Models\Credit;
use App\Transformers\CreditTransformer; use App\Transformers\CreditTransformer;

View File

@ -12,9 +12,7 @@
namespace App\Export\CSV; namespace App\Export\CSV;
use App\Libraries\MultiDB; use App\Libraries\MultiDB;
use App\Models\Client;
use App\Models\Company; use App\Models\Company;
use App\Models\Credit;
use App\Models\Document; use App\Models\Document;
use App\Transformers\DocumentTransformer; use App\Transformers\DocumentTransformer;
use App\Utils\Ninja; use App\Utils\Ninja;

View File

@ -12,7 +12,6 @@
namespace App\Export\CSV; namespace App\Export\CSV;
use App\Libraries\MultiDB; use App\Libraries\MultiDB;
use App\Models\Client;
use App\Models\Company; use App\Models\Company;
use App\Models\Expense; use App\Models\Expense;
use App\Transformers\ExpenseTransformer; use App\Transformers\ExpenseTransformer;

View File

@ -12,7 +12,6 @@
namespace App\Export\CSV; namespace App\Export\CSV;
use App\Libraries\MultiDB; use App\Libraries\MultiDB;
use App\Models\Client;
use App\Models\Company; use App\Models\Company;
use App\Models\Invoice; use App\Models\Invoice;
use App\Transformers\InvoiceTransformer; use App\Transformers\InvoiceTransformer;

View File

@ -100,7 +100,6 @@ class InvoiceItemExport extends BaseExport
public function run() public function run()
{ {
MultiDB::setDb($this->company->db); MultiDB::setDb($this->company->db);
App::forgetInstance('translator'); App::forgetInstance('translator');
App::setLocale($this->company->locale()); App::setLocale($this->company->locale());
@ -110,8 +109,9 @@ class InvoiceItemExport extends BaseExport
//load the CSV document from a string //load the CSV document from a string
$this->csv = Writer::createFromString(); $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); $this->input['report_keys'] = array_values($this->entity_keys);
}
//insert the header //insert the header
$this->csv->insertOne($this->buildHeader()); $this->csv->insertOne($this->buildHeader());
@ -119,19 +119,16 @@ class InvoiceItemExport extends BaseExport
$query = Invoice::query() $query = Invoice::query()
->withTrashed() ->withTrashed()
->with('client')->where('company_id', $this->company->id) ->with('client')->where('company_id', $this->company->id)
->where('is_deleted',0); ->where('is_deleted', 0);
$query = $this->addDateRange($query); $query = $this->addDateRange($query);
$query->cursor() $query->cursor()
->each(function ($invoice){ ->each(function ($invoice) {
$this->iterateItems($invoice); $this->iterateItems($invoice);
});
}); return $this->csv->toString();
return $this->csv->toString();
} }
private function iterateItems(Invoice $invoice) private function iterateItems(Invoice $invoice)
@ -140,81 +137,71 @@ class InvoiceItemExport extends BaseExport
$transformed_items = []; $transformed_items = [];
foreach($invoice->line_items as $item) foreach ($invoice->line_items as $item) {
{
$item_array = []; $item_array = [];
foreach(array_values($this->input['report_keys']) as $key){ foreach (array_values($this->input['report_keys']) as $key) {
if (str_contains($key, "item.")) {
if(str_contains($key, "item.")){
$key = str_replace("item.", "", $key); $key = str_replace("item.", "", $key);
if(property_exists($item, $key)) if (property_exists($item, $key)) {
$item_array[$key] = $item->{$key}; $item_array[$key] = $item->{$key};
else } else {
$item_array[$key] = ''; $item_array[$key] = '';
}
} }
} }
$entity = []; $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); $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]; $entity[$keyval] = $transformed_items[$key];
else } else {
$entity[$keyval] = ""; $entity[$keyval] = "";
}
} }
$transformed_items = array_merge($transformed_invoice, $item_array); $transformed_items = array_merge($transformed_invoice, $item_array);
$entity = $this->decorateAdvancedFields($invoice, $transformed_items); $entity = $this->decorateAdvancedFields($invoice, $transformed_items);
$this->csv->insertOne($entity); $this->csv->insertOne($entity);
} }
} }
private function buildRow(Invoice $invoice) :array private function buildRow(Invoice $invoice) :array
{ {
$transformed_invoice = $this->invoice_transformer->transform($invoice); $transformed_invoice = $this->invoice_transformer->transform($invoice);
$entity = []; $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); $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]; $entity[$keyval] = $transformed_invoice[$key];
else } else {
$entity[$keyval] = ""; $entity[$keyval] = "";
}
} }
return $this->decorateAdvancedFields($invoice, $entity); return $this->decorateAdvancedFields($invoice, $entity);
} }
private function decorateAdvancedFields(Invoice $invoice, array $entity) :array 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; $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(); $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); $entity['status'] = $invoice->stringStatus($invoice->status_id);
return $entity; return $entity;
} }
} }

View File

@ -12,9 +12,7 @@
namespace App\Export\CSV; namespace App\Export\CSV;
use App\Libraries\MultiDB; use App\Libraries\MultiDB;
use App\Models\Client;
use App\Models\Company; use App\Models\Company;
use App\Models\Credit;
use App\Models\Document; use App\Models\Document;
use App\Models\Payment; use App\Models\Payment;
use App\Transformers\PaymentTransformer; use App\Transformers\PaymentTransformer;

View File

@ -12,9 +12,7 @@
namespace App\Export\CSV; namespace App\Export\CSV;
use App\Libraries\MultiDB; use App\Libraries\MultiDB;
use App\Models\Client;
use App\Models\Company; use App\Models\Company;
use App\Models\Credit;
use App\Models\Document; use App\Models\Document;
use App\Models\Product; use App\Models\Product;
use App\Transformers\ProductTransformer; use App\Transformers\ProductTransformer;

View File

@ -12,17 +12,13 @@
namespace App\Export\CSV; namespace App\Export\CSV;
use App\Libraries\MultiDB; use App\Libraries\MultiDB;
use App\Models\Client;
use App\Models\Company; use App\Models\Company;
use App\Models\Credit;
use App\Models\Document; use App\Models\Document;
use App\Models\Invoice; use App\Models\Invoice;
use App\Models\Product;
use App\Transformers\ProductTransformer;
use App\Utils\Ninja; use App\Utils\Ninja;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\App; use Illuminate\Support\Facades\App;
use League\Csv\Writer; use League\Csv\Writer;
use Illuminate\Support\Carbon;
class ProductSalesExport extends BaseExport class ProductSalesExport extends BaseExport
{ {
@ -98,10 +94,9 @@ class ProductSalesExport extends BaseExport
$query->cursor() $query->cursor()
->each(function ($invoice) { ->each(function ($invoice) {
foreach ($invoice->line_items as $item) {
foreach($invoice->line_items as $item) $this->csv->insertOne($this->buildRow($invoice, $item));
$this->csv->insertOne($this->buildRow($invoice, $item)); }
}); });
return $this->csv->toString(); return $this->csv->toString();

View File

@ -12,7 +12,6 @@
namespace App\Export\CSV; namespace App\Export\CSV;
use App\Libraries\MultiDB; use App\Libraries\MultiDB;
use App\Models\Client;
use App\Models\Company; use App\Models\Company;
use App\Models\Quote; use App\Models\Quote;
use App\Transformers\QuoteTransformer; use App\Transformers\QuoteTransformer;

View File

@ -12,7 +12,6 @@
namespace App\Export\CSV; namespace App\Export\CSV;
use App\Libraries\MultiDB; use App\Libraries\MultiDB;
use App\Models\Client;
use App\Models\Company; use App\Models\Company;
use App\Models\Quote; use App\Models\Quote;
use App\Transformers\QuoteTransformer; use App\Transformers\QuoteTransformer;

View File

@ -12,7 +12,6 @@
namespace App\Export\CSV; namespace App\Export\CSV;
use App\Libraries\MultiDB; use App\Libraries\MultiDB;
use App\Models\Client;
use App\Models\Company; use App\Models\Company;
use App\Models\RecurringInvoice; use App\Models\RecurringInvoice;
use App\Transformers\RecurringInvoiceTransformer; use App\Transformers\RecurringInvoiceTransformer;

View File

@ -12,7 +12,6 @@
namespace App\Export\CSV; namespace App\Export\CSV;
use App\Libraries\MultiDB; use App\Libraries\MultiDB;
use App\Models\Client;
use App\Models\Company; use App\Models\Company;
use App\Models\DateFormat; use App\Models\DateFormat;
use App\Models\Task; use App\Models\Task;

View File

@ -12,7 +12,6 @@
namespace App\Factory; namespace App\Factory;
use App\Models\BankIntegration; use App\Models\BankIntegration;
use Illuminate\Support\Str;
class BankIntegrationFactory class BankIntegrationFactory
{ {

View File

@ -12,7 +12,6 @@
namespace App\Factory; namespace App\Factory;
use App\Models\BankTransaction; use App\Models\BankTransaction;
use Illuminate\Support\Str;
class BankTransactionFactory class BankTransactionFactory
{ {

View File

@ -12,7 +12,6 @@
namespace App\Factory; namespace App\Factory;
use App\Models\BankTransactionRule; use App\Models\BankTransactionRule;
use Illuminate\Support\Str;
class BankTransactionRuleFactory class BankTransactionRuleFactory
{ {

View File

@ -12,7 +12,6 @@
namespace App\Factory; namespace App\Factory;
use App\Models\ClientGatewayToken; use App\Models\ClientGatewayToken;
use Illuminate\Support\Str;
class ClientGatewayTokenFactory class ClientGatewayTokenFactory
{ {

View File

@ -11,7 +11,6 @@
namespace App\Factory; namespace App\Factory;
use App\DataMapper\FeesAndLimits;
use App\Models\CompanyGateway; use App\Models\CompanyGateway;
class CompanyGatewayFactory class CompanyGatewayFactory

View File

@ -13,7 +13,6 @@ namespace App\Factory;
use App\Models\Client; use App\Models\Client;
use App\Models\PurchaseOrder; use App\Models\PurchaseOrder;
use Illuminate\Database\Eloquent\Model;
class PurchaseOrderFactory class PurchaseOrderFactory
{ {

View File

@ -3,7 +3,6 @@
namespace App\Factory; namespace App\Factory;
use App\Models\PurchaseOrderInvitation; use App\Models\PurchaseOrderInvitation;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str; use Illuminate\Support\Str;
class PurchaseOrderInvitationFactory class PurchaseOrderInvitationFactory

View File

@ -13,7 +13,6 @@ namespace App\Factory;
use App\Models\Expense; use App\Models\Expense;
use App\Models\RecurringExpense; use App\Models\RecurringExpense;
use App\Utils\Helpers;
use Illuminate\Support\Carbon; use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str; use Illuminate\Support\Str;
@ -175,7 +174,10 @@ class RecurringExpenseToExpenseFactory
$replacement = sprintf('%s to %s', $_left, $_right); $replacement = sprintf('%s to %s', $_left, $_right);
$value = preg_replace( $value = preg_replace(
sprintf('/%s/', preg_quote($match)), $replacement, $value, 1 sprintf('/%s/', preg_quote($match)),
$replacement,
$value,
1
); );
} }
} }
@ -196,7 +198,10 @@ class RecurringExpenseToExpenseFactory
if (! Str::contains($match, ['-', '+', '/', '*'])) { if (! Str::contains($match, ['-', '+', '/', '*'])) {
$value = preg_replace( $value = preg_replace(
sprintf('/%s/', $matches->keys()->first()), $replacements['literal'][$matches->keys()->first()], $value, 1 sprintf('/%s/', $matches->keys()->first()),
$replacements['literal'][$matches->keys()->first()],
$value,
1
); );
} }
@ -236,7 +241,10 @@ class RecurringExpenseToExpenseFactory
} }
$value = preg_replace( $value = preg_replace(
$target, $output, $value, 1 $target,
$output,
$value,
1
); );
} }
} }

View File

@ -11,7 +11,6 @@
namespace App\Factory; namespace App\Factory;
use App\Models\CompanyUser;
use App\Models\User; use App\Models\User;
class UserFactory class UserFactory

View File

@ -49,7 +49,6 @@ class BankIntegrationFilters extends QueryFilters
return $this->builder->where(function ($query) use ($filter) { return $this->builder->where(function ($query) use ($filter) {
$query->where('bank_account_name', 'like', '%'.$filter.'%'); $query->where('bank_account_name', 'like', '%'.$filter.'%');
}); });
} }
/** /**
@ -68,7 +67,6 @@ class BankIntegrationFilters extends QueryFilters
$filters = explode(',', $filter); $filters = explode(',', $filter);
return $this->builder->where(function ($query) use ($filters) { return $this->builder->where(function ($query) use ($filters) {
if (in_array(parent::STATUS_ACTIVE, $filters)) { if (in_array(parent::STATUS_ACTIVE, $filters)) {
$query->orWhereNull('deleted_at'); $query->orWhereNull('deleted_at');
} }

View File

@ -50,7 +50,6 @@ class BankTransactionFilters extends QueryFilters
return $this->builder->where(function ($query) use ($filter) { return $this->builder->where(function ($query) use ($filter) {
$query->where('bank_transactions.description', 'like', '%'.$filter.'%'); $query->where('bank_transactions.description', 'like', '%'.$filter.'%');
}); });
} }
@ -79,8 +78,7 @@ class BankTransactionFilters extends QueryFilters
return $this->builder; return $this->builder;
} }
$this->builder->where(function ($query) use ($status_parameters){ $this->builder->where(function ($query) use ($status_parameters) {
$status_array = []; $status_array = [];
$debit_or_withdrawal_array = []; $debit_or_withdrawal_array = [];
@ -105,14 +103,13 @@ class BankTransactionFilters extends QueryFilters
$debit_or_withdrawal_array[] = 'DEBIT'; $debit_or_withdrawal_array[] = 'DEBIT';
} }
if(count($status_array) >=1) { if (count($status_array) >=1) {
$query->whereIn('status_id', $status_array); $query->whereIn('status_id', $status_array);
} }
if(count($debit_or_withdrawal_array) >=1) { if (count($debit_or_withdrawal_array) >=1) {
$query->orWhereIn('base_type', $debit_or_withdrawal_array); $query->orWhereIn('base_type', $debit_or_withdrawal_array);
} }
}); });
return $this->builder; return $this->builder;
@ -132,17 +129,21 @@ class BankTransactionFilters extends QueryFilters
return $this->builder; return $this->builder;
} }
if($sort_col[0] == 'deposit') if ($sort_col[0] == 'deposit') {
return $this->builder->where('base_type', 'CREDIT')->orderBy('amount', $sort_col[1]); return $this->builder->where('base_type', 'CREDIT')->orderBy('amount', $sort_col[1]);
}
if($sort_col[0] == 'withdrawal') if ($sort_col[0] == 'withdrawal') {
return $this->builder->where('base_type', 'DEBIT')->orderBy('amount', $sort_col[1]); return $this->builder->where('base_type', 'DEBIT')->orderBy('amount', $sort_col[1]);
}
if($sort_col[0] == 'status') if ($sort_col[0] == 'status') {
$sort_col[0] = 'status_id'; $sort_col[0] = 'status_id';
}
if(in_array($sort_col[0],['invoices','expense'])) if (in_array($sort_col[0], ['invoices','expense'])) {
return $this->builder; return $this->builder;
}
return $this->builder->orderBy($sort_col[0], $sort_col[1]); return $this->builder->orderBy($sort_col[0], $sort_col[1]);
} }

View File

@ -49,7 +49,6 @@ class BankTransactionRuleFilters extends QueryFilters
return $this->builder->where(function ($query) use ($filter) { return $this->builder->where(function ($query) use ($filter) {
$query->where('bank_transaction_rules.name', 'like', '%'.$filter.'%'); $query->where('bank_transaction_rules.name', 'like', '%'.$filter.'%');
}); });
} }
/** /**

View File

@ -147,8 +147,9 @@ class ClientFilters extends QueryFilters
return $this->builder; return $this->builder;
} }
if($sort_col[0] == 'display_name') if ($sort_col[0] == 'display_name') {
$sort_col[0] = 'name'; $sort_col[0] = 'name';
}
return $this->builder->orderBy($sort_col[0], $sort_col[1]); return $this->builder->orderBy($sort_col[0], $sort_col[1]);
} }
@ -165,11 +166,10 @@ class ClientFilters extends QueryFilters
public function filter_details(string $filter = '') public function filter_details(string $filter = '')
{ {
if ($filter == 'true') {
if($filter == 'true')
return $this->builder->select('id', 'name', 'number', 'id_number'); return $this->builder->select('id', 'name', 'number', 'id_number');
}
return $this->builder; return $this->builder;
} }
} }

View File

@ -44,17 +44,21 @@ class CreditFilters extends QueryFilters
$credit_filters = []; $credit_filters = [];
if (in_array('draft', $status_parameters)) if (in_array('draft', $status_parameters)) {
$credit_filters[] = Credit::STATUS_DRAFT; $credit_filters[] = Credit::STATUS_DRAFT;
}
if (in_array('partial', $status_parameters)) if (in_array('partial', $status_parameters)) {
$credit_filters[] = Credit::STATUS_PARTIAL; $credit_filters[] = Credit::STATUS_PARTIAL;
}
if (in_array('applied', $status_parameters)) if (in_array('applied', $status_parameters)) {
$credit_filters[] = Credit::STATUS_APPLIED; $credit_filters[] = Credit::STATUS_APPLIED;
}
if(count($credit_filters) >=1) if (count($credit_filters) >=1) {
$this->builder->whereIn('status_id', $credit_filters); $this->builder->whereIn('status_id', $credit_filters);
}
return $this->builder; return $this->builder;
} }

View File

@ -23,7 +23,7 @@ class DesignFilters extends QueryFilters
* *
* @param string query filter * @param string query filter
* @return Builder * @return Builder
* *
* @deprecated * @deprecated
*/ */
public function filter(string $filter = ''): Builder public function filter(string $filter = ''): Builder
@ -41,7 +41,7 @@ class DesignFilters extends QueryFilters
* Sorts the list based on $sort. * Sorts the list based on $sort.
* *
* @param string sort formatted as column|asc * @param string sort formatted as column|asc
* *
* @return Builder * @return Builder
*/ */
public function sort(string $sort = ''): Builder public function sort(string $sort = ''): Builder
@ -62,6 +62,6 @@ class DesignFilters extends QueryFilters
*/ */
public function entityFilter(): Builder public function entityFilter(): Builder
{ {
return $this->builder->where('company_id', auth()->user()->company()->id)->orWhere('company_id', null)->orderBy('id','asc'); return $this->builder->where('company_id', auth()->user()->company()->id)->orWhere('company_id', null)->orderBy('id', 'asc');
} }
} }

View File

@ -39,10 +39,10 @@ class DocumentFilters extends QueryFilters
* Overriding method as client_id does * Overriding method as client_id does
* not exist on this model, just pass * not exist on this model, just pass
* back the builder * back the builder
* *
* @param string $client_id The client hashed id. * @param string $client_id The client hashed id.
* *
* @return Builder * @return Builder
*/ */
public function client_id(string $client_id = ''): Builder public function client_id(string $client_id = ''): Builder
{ {
@ -69,8 +69,9 @@ class DocumentFilters extends QueryFilters
public function company_documents($value = 'false') public function company_documents($value = 'false')
{ {
if($value == 'true') if ($value == 'true') {
return $this->builder->where('documentable_type', Company::class); return $this->builder->where('documentable_type', Company::class);
}
return $this->builder; return $this->builder;
} }

View File

@ -32,7 +32,6 @@ class ExpenseCategoryFilters extends QueryFilters
} }
return $this->builder->where('name', 'like', '%'.$filter.'%'); return $this->builder->where('name', 'like', '%'.$filter.'%');
} }
/** /**
@ -49,8 +48,9 @@ class ExpenseCategoryFilters extends QueryFilters
return $this->builder; return $this->builder;
} }
if (is_array($sort_col) && in_array($sort_col[1], ['asc', 'desc']) && in_array($sort_col[0], ['name'])) if (is_array($sort_col) && in_array($sort_col[1], ['asc', 'desc']) && in_array($sort_col[0], ['name'])) {
return $this->builder->orderBy($sort_col[0], $sort_col[1]); return $this->builder->orderBy($sort_col[0], $sort_col[1]);
}
return $this->builder; return $this->builder;

View File

@ -65,52 +65,40 @@ class ExpenseFilters extends QueryFilters
return $this->builder; return $this->builder;
} }
$this->builder->where(function ($query) use($status_parameters){ $this->builder->where(function ($query) use ($status_parameters) {
if (in_array('logged', $status_parameters)) { if (in_array('logged', $status_parameters)) {
$query->orWhere(function ($query) {
$query->orWhere(function ($query){
$query->where('amount', '>', 0) $query->where('amount', '>', 0)
->whereNull('invoice_id') ->whereNull('invoice_id')
->whereNull('payment_date') ->whereNull('payment_date')
->where('should_be_invoiced',false); ->where('should_be_invoiced', false);
}); });
} }
if (in_array('pending', $status_parameters)) { if (in_array('pending', $status_parameters)) {
$query->orWhere(function ($query) {
$query->orWhere(function ($query){ $query->where('should_be_invoiced', true)
$query->where('should_be_invoiced',true)
->whereNull('invoice_id'); ->whereNull('invoice_id');
}); });
} }
if (in_array('invoiced', $status_parameters)) { if (in_array('invoiced', $status_parameters)) {
$query->orWhere(function ($query) {
$query->orWhere(function ($query){
$query->whereNotNull('invoice_id'); $query->whereNotNull('invoice_id');
}); });
} }
if (in_array('paid', $status_parameters)) { if (in_array('paid', $status_parameters)) {
$query->orWhere(function ($query) {
$query->orWhere(function ($query){
$query->whereNotNull('payment_date'); $query->whereNotNull('payment_date');
}); });
} }
if (in_array('unpaid', $status_parameters)) { if (in_array('unpaid', $status_parameters)) {
$query->orWhere(function ($query) {
$query->orWhere(function ($query){
$query->whereNull('payment_date'); $query->whereNull('payment_date');
}); });
} }
}); });
// nlog($this->builder->toSql()); // nlog($this->builder->toSql());
@ -123,10 +111,8 @@ class ExpenseFilters extends QueryFilters
*/ */
public function match_transactions($value = '') public function match_transactions($value = '')
{ {
if ($value == 'true') {
if($value == 'true') return $this->builder->where('is_deleted', 0)->whereNull('transaction_id');
{
return $this->builder->where('is_deleted',0)->whereNull('transaction_id');
} }
return $this->builder; return $this->builder;

View File

@ -50,8 +50,7 @@ class InvoiceFilters extends QueryFilters
return $this->builder; return $this->builder;
} }
$this->builder->where(function ($query) use($status_parameters){ $this->builder->where(function ($query) use ($status_parameters) {
$invoice_filters = []; $invoice_filters = [];
if (in_array('paid', $status_parameters)) { if (in_array('paid', $status_parameters)) {
@ -63,7 +62,7 @@ class InvoiceFilters extends QueryFilters
$invoice_filters[] = Invoice::STATUS_PARTIAL; $invoice_filters[] = Invoice::STATUS_PARTIAL;
} }
if(count($invoice_filters) >0){ if (count($invoice_filters) >0) {
$query->whereIn('status_id', $invoice_filters); $query->whereIn('status_id', $invoice_filters);
} }
@ -79,8 +78,9 @@ class InvoiceFilters extends QueryFilters
public function number(string $number = ''): Builder public function number(string $number = ''): Builder
{ {
if(strlen($number) == 0) if (strlen($number) == 0) {
return $this->builder; return $this->builder;
}
return $this->builder->where('number', $number); return $this->builder->where('number', $number);
} }
@ -112,20 +112,19 @@ class InvoiceFilters extends QueryFilters
} }
/** /**
* @return Builder * @return Builder
* @throws RuntimeException * @throws RuntimeException
*/ */
public function without_deleted_clients(): Builder public function without_deleted_clients(): Builder
{ {
return $this->builder->whereHas('client', function ($query) { return $this->builder->whereHas('client', function ($query) {
$query->where('is_deleted',0); $query->where('is_deleted', 0);
}); });
} }
/** /**
* @return Builder * @return Builder
* @throws InvalidArgumentException * @throws InvalidArgumentException
*/ */
public function upcoming(): Builder public function upcoming(): Builder
{ {
@ -138,8 +137,8 @@ class InvoiceFilters extends QueryFilters
} }
/** /**
* @return void * @return void
* @throws InvalidArgumentException * @throws InvalidArgumentException
*/ */
public function overdue(): Builder public function overdue(): Builder
{ {
@ -153,9 +152,9 @@ class InvoiceFilters extends QueryFilters
} }
/** /**
* @param string $client_id * @param string $client_id
* @return Builder * @return Builder
* @throws InvalidArgumentException * @throws InvalidArgumentException
*/ */
public function payable(string $client_id = ''): Builder public function payable(string $client_id = ''): Builder
{ {
@ -198,15 +197,15 @@ class InvoiceFilters extends QueryFilters
{ {
if (auth()->guard('contact')->user()) { if (auth()->guard('contact')->user()) {
return $this->contactViewFilter(); return $this->contactViewFilter();
} else { } else {
return $this->builder->company()->with(['invitations.company'], ['documents.company']); return $this->builder->company()->with(['invitations.company'], ['documents.company']);
} }
} }
/** /**
* @param string $filter * @param string $filter
* @return Builder * @return Builder
* @throws InvalidArgumentException * @throws InvalidArgumentException
*/ */
public function private_notes($filter = '') :Builder public function private_notes($filter = '') :Builder
{ {

View File

@ -46,17 +46,14 @@ class PaymentFilters extends QueryFilters
*/ */
public function match_transactions($value = 'true'): Builder public function match_transactions($value = 'true'): Builder
{ {
if ($value == 'true') {
if($value == 'true'){
return $this->builder return $this->builder
->where('is_deleted',0) ->where('is_deleted', 0)
->where(function ($query){ ->where(function ($query) {
$query->whereNull('transaction_id') $query->whereNull('transaction_id')
->orWhere("transaction_id","") ->orWhere("transaction_id", "")
->company(); ->company();
}); });
} }
return $this->builder; return $this->builder;

View File

@ -61,8 +61,9 @@ class ProjectFilters extends QueryFilters
return $this->builder; return $this->builder;
} }
if(is_array($sort_col)) if (is_array($sort_col)) {
return $this->builder->orderBy($sort_col[0], $sort_col[1]); return $this->builder->orderBy($sort_col[0], $sort_col[1]);
}
} }
/** /**

View File

@ -16,7 +16,6 @@ use Illuminate\Database\Eloquent\Builder;
class PurchaseOrderFilters extends QueryFilters class PurchaseOrderFilters extends QueryFilters
{ {
/** /**
* Filter based on client status. * Filter based on client status.
* *
@ -41,8 +40,7 @@ class PurchaseOrderFilters extends QueryFilters
return $this->builder; return $this->builder;
} }
$this->builder->where(function ($query) use ($status_parameters){ $this->builder->where(function ($query) use ($status_parameters) {
$po_status = []; $po_status = [];
if (in_array('draft', $status_parameters)) { if (in_array('draft', $status_parameters)) {
@ -50,12 +48,11 @@ class PurchaseOrderFilters extends QueryFilters
} }
if (in_array('sent', $status_parameters)) { if (in_array('sent', $status_parameters)) {
$query->orWhere(function ($q){ $query->orWhere(function ($q) {
$q->where('status_id', PurchaseOrder::STATUS_SENT) $q->where('status_id', PurchaseOrder::STATUS_SENT)
->whereNull('due_date') ->whereNull('due_date')
->orWhere('due_date', '>=', now()->toDateString()); ->orWhere('due_date', '>=', now()->toDateString());
}); });
} }
if (in_array('accepted', $status_parameters)) { if (in_array('accepted', $status_parameters)) {
@ -66,7 +63,7 @@ class PurchaseOrderFilters extends QueryFilters
$po_status[] = PurchaseOrder::STATUS_CANCELLED; $po_status[] = PurchaseOrder::STATUS_CANCELLED;
} }
if(count($status_parameters) >=1) { if (count($status_parameters) >=1) {
$query->whereIn('status_id', $status_parameters); $query->whereIn('status_id', $status_parameters);
} }
}); });

View File

@ -55,7 +55,7 @@ abstract class QueryFilters
/** /**
* The "with" filter property column. * The "with" filter property column.
* *
* var string * var string
*/ */
protected $with_property = 'id'; protected $with_property = 'id';
@ -151,7 +151,7 @@ abstract class QueryFilters
if (in_array(self::STATUS_ARCHIVED, $filters)) { if (in_array(self::STATUS_ARCHIVED, $filters)) {
$query->orWhere(function ($query) { $query->orWhere(function ($query) {
$query->whereNotNull('deleted_at')->where('is_deleted',0); $query->whereNotNull('deleted_at')->where('is_deleted', 0);
}); });
} }
@ -188,7 +188,6 @@ abstract class QueryFilters
default: default:
return '='; return '=';
break; break;
} }
} }
@ -208,38 +207,30 @@ abstract class QueryFilters
public function created_at($value = '') public function created_at($value = '')
{ {
if ($value == '') {
if($value == '')
return $this->builder; return $this->builder;
}
try{ try {
if (is_numeric($value)) {
if(is_numeric($value)){
$created_at = Carbon::createFromTimestamp((int)$value); $created_at = Carbon::createFromTimestamp((int)$value);
} } else {
else{
$created_at = Carbon::parse($value); $created_at = Carbon::parse($value);
} }
return $this->builder->where('created_at', '>=', $created_at); return $this->builder->where('created_at', '>=', $created_at);
} catch(\Exception $e) {
}
catch(\Exception $e) {
return $this->builder; return $this->builder;
} }
} }
public function updated_at($value = '') public function updated_at($value = '')
{ {
if ($value == '') {
if ($value == '')
return $this->builder; return $this->builder;
}
try { try {
if (is_numeric($value)) { if (is_numeric($value)) {
$created_at = Carbon::createFromTimestamp((int)$value); $created_at = Carbon::createFromTimestamp((int)$value);
} else { } else {
@ -248,7 +239,6 @@ abstract class QueryFilters
return $this->builder->where('updated_at', '>=', $created_at); return $this->builder->where('updated_at', '>=', $created_at);
} catch (\Exception $e) { } catch (\Exception $e) {
return $this->builder; return $this->builder;
} }
} }

View File

@ -65,14 +65,13 @@ class QuoteFilters extends QueryFilters
return $this->builder; return $this->builder;
} }
$this->builder->where(function ($query) use ($status_parameters){ $this->builder->where(function ($query) use ($status_parameters) {
if (in_array('sent', $status_parameters)) { if (in_array('sent', $status_parameters)) {
$query->orWhere(function ($q){ $query->orWhere(function ($q) {
$q->where('status_id', Quote::STATUS_SENT) $q->where('status_id', Quote::STATUS_SENT)
->whereNull('due_date') ->whereNull('due_date')
->orWhere('due_date', '>=', now()->toDateString()); ->orWhere('due_date', '>=', now()->toDateString());
}); });
} }
$quote_filters = []; $quote_filters = [];
@ -86,26 +85,25 @@ class QuoteFilters extends QueryFilters
$quote_filters[] = Quote::STATUS_APPROVED; $quote_filters[] = Quote::STATUS_APPROVED;
} }
if(count($quote_filters) >0){ if (count($quote_filters) >0) {
$query->orWhereIn('status_id', $quote_filters); $query->orWhereIn('status_id', $quote_filters);
} }
if (in_array('expired', $status_parameters)) { if (in_array('expired', $status_parameters)) {
$query->orWhere(function ($q){ $query->orWhere(function ($q) {
$q->where('status_id', Quote::STATUS_SENT) $q->where('status_id', Quote::STATUS_SENT)
->whereNotNull('due_date') ->whereNotNull('due_date')
->where('due_date', '<=', now()->toDateString()); ->where('due_date', '<=', now()->toDateString());
}); });
} }
if (in_array('upcoming', $status_parameters)) { if (in_array('upcoming', $status_parameters)) {
$query->orWhere(function ($q){ $query->orWhere(function ($q) {
$q->where('status_id', Quote::STATUS_SENT) $q->where('status_id', Quote::STATUS_SENT)
->where('due_date', '>=', now()->toDateString()) ->where('due_date', '>=', now()->toDateString())
->orderBy('due_date', 'DESC'); ->orderBy('due_date', 'DESC');
}); });
} }
}); });
return $this->builder; return $this->builder;
@ -134,8 +132,9 @@ class QuoteFilters extends QueryFilters
return $this->builder; return $this->builder;
} }
if($sort_col[0] == 'valid_until') if ($sort_col[0] == 'valid_until') {
$sort_col[0] = 'due_date'; $sort_col[0] = 'due_date';
}
return $this->builder->orderBy($sort_col[0], $sort_col[1]); return $this->builder->orderBy($sort_col[0], $sort_col[1]);
} }

View File

@ -66,21 +66,24 @@ class RecurringInvoiceFilters extends QueryFilters
$recurring_filters = []; $recurring_filters = [];
if (in_array('active', $status_parameters)) if (in_array('active', $status_parameters)) {
$recurring_filters[] = RecurringInvoice::STATUS_ACTIVE; $recurring_filters[] = RecurringInvoice::STATUS_ACTIVE;
}
if (in_array('paused', $status_parameters)) if (in_array('paused', $status_parameters)) {
$recurring_filters[] = RecurringInvoice::STATUS_PAUSED; $recurring_filters[] = RecurringInvoice::STATUS_PAUSED;
}
if (in_array('completed', $status_parameters)) if (in_array('completed', $status_parameters)) {
$recurring_filters[] = RecurringInvoice::STATUS_COMPLETED; $recurring_filters[] = RecurringInvoice::STATUS_COMPLETED;
}
if(count($recurring_filters) >= 1) if (count($recurring_filters) >= 1) {
return $this->builder->whereIn('status_id', $recurring_filters); return $this->builder->whereIn('status_id', $recurring_filters);
}
return $this->builder; return $this->builder;
} }
public function number(string $number = ''): Builder public function number(string $number = ''): Builder

View File

@ -74,7 +74,6 @@ class TaskFilters extends QueryFilters
public function project_tasks($project): Builder public function project_tasks($project): Builder
{ {
if (strlen($project) == 0) { if (strlen($project) == 0) {
return $this->builder; return $this->builder;
} }

View File

@ -70,17 +70,16 @@ class UserFilters extends QueryFilters
} }
/** /**
* Overrides the base with() function as no company ID * Overrides the base with() function as no company ID
* exists on the user table * exists on the user table
* *
* @param string $value Hashed ID of the user to return back in the dataset * @param string $value Hashed ID of the user to return back in the dataset
* *
* @return Builder * @return Builder
*/ */
public function with(string $value = ''): Builder public function with(string $value = ''): Builder
{ {
if (strlen($value) == 0) {
if(strlen($value) == 0) {
return $this->builder; return $this->builder;
} }
@ -89,5 +88,4 @@ class UserFilters extends QueryFilters
->orderByRaw("{$this->with_property} = ? DESC", [$value]) ->orderByRaw("{$this->with_property} = ? DESC", [$value])
->where('account_id', auth()->user()->account_id); ->where('account_id', auth()->user()->account_id);
} }
} }

View File

@ -13,5 +13,5 @@ namespace App\Helpers\Bank;
interface AccountTransformerInterface interface AccountTransformerInterface
{ {
public function transform($accounts); public function transform($accounts);
} }

View File

@ -13,5 +13,4 @@ namespace App\Helpers\Bank;
interface BankExpenseInterface interface BankExpenseInterface
{ {
} }

View File

@ -12,7 +12,7 @@
namespace App\Helpers\Bank\Yodlee\Transformer; namespace App\Helpers\Bank\Yodlee\Transformer;
use App\Helpers\Bank\AccountTransformerInterface; use App\Helpers\Bank\AccountTransformerInterface;
/** /**
[0] => stdClass Object [0] => stdClass Object
( (
@ -33,7 +33,7 @@ use App\Helpers\Bank\AccountTransformerInterface;
[includeInNetWorth] => 1 [includeInNetWorth] => 1
[providerId] => 18769 [providerId] => 18769
[providerName] => Dag Site Captcha [providerName] => Dag Site Captcha
[isManual] => [isManual] =>
[currentBalance] => stdClass Object [currentBalance] => stdClass Object
( (
[currency] => USD [currency] => USD
@ -64,17 +64,15 @@ use App\Helpers\Bank\AccountTransformerInterface;
class AccountTransformer implements AccountTransformerInterface class AccountTransformer implements AccountTransformerInterface
{ {
public function transform($yodlee_account) public function transform($yodlee_account)
{ {
$data = []; $data = [];
if(!property_exists($yodlee_account, 'account')) if (!property_exists($yodlee_account, 'account')) {
return $data; return $data;
}
foreach($yodlee_account->account as $account) foreach ($yodlee_account->account as $account) {
{
$data[] = $this->transformAccount($account); $data[] = $this->transformAccount($account);
} }
@ -83,7 +81,6 @@ class AccountTransformer implements AccountTransformerInterface
public function transformAccount($account) public function transformAccount($account)
{ {
return [ return [
'id' => $account->id, 'id' => $account->id,
'account_type' => $account->CONTAINER, 'account_type' => $account->CONTAINER,
@ -100,5 +97,3 @@ class AccountTransformer implements AccountTransformerInterface
]; ];
} }
} }

View File

@ -10,7 +10,7 @@
*/ */
namespace App\Helpers\Bank\Yodlee\Transformer; namespace App\Helpers\Bank\Yodlee\Transformer;
/** /**
"date": "string", "date": "string",
"sourceId": "string", "sourceId": "string",
@ -74,7 +74,4 @@ namespace App\Helpers\Bank\Yodlee\Transformer;
class ExpenseTransformer class ExpenseTransformer
{ {
} }

View File

@ -74,7 +74,7 @@ use Illuminate\Support\Facades\Cache;
"holdingDescription": "string", "holdingDescription": "string",
"isin": "string", "isin": "string",
"status": "POSTED" "status": "POSTED"
( (
[CONTAINER] => bank [CONTAINER] => bank
[id] => 103953585 [id] => 103953585
@ -96,7 +96,7 @@ use Illuminate\Support\Facades\Cache;
[original] => CHEROKEE NATION TAX TA TAHLEQUAH OK [original] => CHEROKEE NATION TAX TA TAHLEQUAH OK
) )
[isManual] => [isManual] =>
[sourceType] => AGGREGATED [sourceType] => AGGREGATED
[date] => 2022-08-03 [date] => 2022-08-03
[transactionDate] => 2022-08-03 [transactionDate] => 2022-08-03
@ -119,17 +119,17 @@ class IncomeTransformer implements BankRevenueInterface
public function transform($transaction) public function transform($transaction)
{ {
$data = []; $data = [];
if(!property_exists($transaction, 'transaction')) if (!property_exists($transaction, 'transaction')) {
return $data; return $data;
}
foreach($transaction->transaction as $transaction) foreach ($transaction->transaction as $transaction) {
{
//do not store duplicate / pending transactions //do not store duplicate / pending transactions
if(property_exists($transaction,'status') && $transaction->status == 'PENDING') if (property_exists($transaction, 'status') && $transaction->status == 'PENDING') {
continue; continue;
}
$data[] = $this->transformTransaction($transaction); $data[] = $this->transformTransaction($transaction);
} }
@ -139,7 +139,6 @@ class IncomeTransformer implements BankRevenueInterface
public function transformTransaction($transaction) public function transformTransaction($transaction)
{ {
return [ return [
'transaction_id' => $transaction->id, 'transaction_id' => $transaction->id,
'amount' => $transaction->amount->amount, 'amount' => $transaction->amount->amount,
@ -158,34 +157,29 @@ class IncomeTransformer implements BankRevenueInterface
{ {
//CREDIT / DEBIT //CREDIT / DEBIT
if(property_exists($transaction, 'highLevelCategoryId') && $transaction->highLevelCategoryId == 10000012) if (property_exists($transaction, 'highLevelCategoryId') && $transaction->highLevelCategoryId == 10000012) {
return 'CREDIT'; return 'CREDIT';
}
return 'DEBIT'; return 'DEBIT';
} }
private function convertCurrency(string $code) private function convertCurrency(string $code)
{ {
$currencies = Cache::get('currencies'); $currencies = Cache::get('currencies');
if (! $currencies) { if (! $currencies) {
$this->buildCache(true); $this->buildCache(true);
} }
$currency = $currencies->filter(function ($item) use($code){ $currency = $currencies->filter(function ($item) use ($code) {
return $item->code == $code; return $item->code == $code;
})->first(); })->first();
if($currency) if ($currency) {
return $currency->id; return $currency->id;
}
return 1; return 1;
} }
} }

View File

@ -16,10 +16,9 @@ use App\Helpers\Bank\Yodlee\Transformer\AccountTransformer;
use App\Helpers\Bank\Yodlee\Transformer\IncomeTransformer; use App\Helpers\Bank\Yodlee\Transformer\IncomeTransformer;
use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str; use Illuminate\Support\Str;
class Yodlee class Yodlee
{ {
public bool $test_mode = false; public bool $test_mode = false;
private string $api_endpoint = 'https://production.api.yodlee.com/ysl'; private string $api_endpoint = 'https://production.api.yodlee.com/ysl';
@ -44,7 +43,6 @@ class Yodlee
public function __construct(?string $bank_account_id = null) public function __construct(?string $bank_account_id = null)
{ {
$this->bank_account_id = $bank_account_id; $this->bank_account_id = $bank_account_id;
$this->client_id = config('ninja.yodlee.client_id'); $this->client_id = config('ninja.yodlee.client_id');
@ -56,13 +54,13 @@ class Yodlee
$this->test_mode = config('ninja.yodlee.test_mode'); $this->test_mode = config('ninja.yodlee.test_mode');
config('ninja.yodlee.dev_mode') ? $this->setDevUrl() : null; config('ninja.yodlee.dev_mode') ? $this->setDevUrl() : null;
} }
public function getFastTrackUrl() public function getFastTrackUrl()
{ {
if(config('ninja.yodlee.dev_mode')) if (config('ninja.yodlee.dev_mode')) {
return $this->dev_fast_track_url; return $this->dev_fast_track_url;
}
return $this->test_mode ? $this->test_fast_track_url : $this->production_track_url; return $this->test_mode ? $this->test_fast_track_url : $this->production_track_url;
} }
@ -94,12 +92,13 @@ class Yodlee
*/ */
public function getAccessToken($is_admin = false) public function getAccessToken($is_admin = false)
{ {
if($is_admin) if ($is_admin) {
$user = $this->admin_name; $user = $this->admin_name;
else } else {
$user = $this->bank_account_id ?: $this->admin_name; $user = $this->bank_account_id ?: $this->admin_name;
}
$response = $this->bankFormRequest('/auth/token', 'post', [], ['loginName' => $user]); $response = $this->bankFormRequest('/auth/token', 'post', [], ['loginName' => $user]);
return $response->token->accessToken; return $response->token->accessToken;
} }
@ -107,103 +106,98 @@ class Yodlee
public function createUser($company) public function createUser($company)
{ {
$token = $this->getAccessToken(true); $token = $this->getAccessToken(true);
$user['user'] = [ $user['user'] = [
'loginName' => Str::uuid(), 'loginName' => Str::uuid(),
]; ];
/* /*
{ {
"user": { "user": {
"preferences": { "preferences": {
"dateFormat": "string", "dateFormat": "string",
"timeZone": "string", "timeZone": "string",
"currency": "USD", "currency": "USD",
"locale": "en_US" "locale": "en_US"
}, },
"address": { "address": {
"zip": "string", "zip": "string",
"country": "string", "country": "string",
"address3": "string", "address3": "string",
"address2": "string", "address2": "string",
"city": "string", "city": "string",
"address1": "string", "address1": "string",
"state": "string" "state": "string"
}, },
"loginName": "string", "loginName": "string",
"name": { "name": {
"middle": "string", "middle": "string",
"last": "string", "last": "string",
"fullName": "string", "fullName": "string",
"first": "string" "first": "string"
}, },
"email": "string", "email": "string",
"segmentName": "string" "segmentName": "string"
} }
} }
*/ */
$response = Http::withHeaders($this->getHeaders(["Authorization" => "Bearer {$token}"]))->post($this->getEndpoint(). "/user/register", $user); $response = Http::withHeaders($this->getHeaders(["Authorization" => "Bearer {$token}"]))->post($this->getEndpoint(). "/user/register", $user);
if($response->successful()) if ($response->successful()) {
return $response->object(); return $response->object();
}
if($response->failed()) if ($response->failed()) {
throw new YodleeApiException($response->body()); throw new YodleeApiException($response->body());
}
} }
public function getAccounts($params = []) public function getAccounts($params = [])
{ {
$token = $this->getAccessToken(); $token = $this->getAccessToken();
$response = Http::withHeaders($this->getHeaders(["Authorization" => "Bearer {$token}"]))->get($this->getEndpoint(). "/accounts", $params); $response = Http::withHeaders($this->getHeaders(["Authorization" => "Bearer {$token}"]))->get($this->getEndpoint(). "/accounts", $params);
if($response->successful()){ if ($response->successful()) {
$at = new AccountTransformer(); $at = new AccountTransformer();
return $at->transform($response->object()); return $at->transform($response->object());
} }
if($response->failed()) if ($response->failed()) {
throw new YodleeApiException($response->body()); throw new YodleeApiException($response->body());
}
} }
public function getAccount($account_id) public function getAccount($account_id)
{ {
$token = $this->getAccessToken(); $token = $this->getAccessToken();
$response = Http::withHeaders($this->getHeaders(["Authorization" => "Bearer {$token}"]))->get($this->getEndpoint(). "/accounts/{$account_id}", []); $response = Http::withHeaders($this->getHeaders(["Authorization" => "Bearer {$token}"]))->get($this->getEndpoint(). "/accounts/{$account_id}", []);
if($response->successful()) if ($response->successful()) {
return true; return true;
}
if($response->failed()) if ($response->failed()) {
return false; return false;
}
} }
public function deleteAccount($account_id) public function deleteAccount($account_id)
{ {
$token = $this->getAccessToken(); $token = $this->getAccessToken();
$response = Http::withHeaders($this->getHeaders(["Authorization" => "Bearer {$token}"]))->delete($this->getEndpoint(). "/accounts/{$account_id}", []); $response = Http::withHeaders($this->getHeaders(["Authorization" => "Bearer {$token}"]))->delete($this->getEndpoint(). "/accounts/{$account_id}", []);
if($response->successful()){ if ($response->successful()) {
return true; return true;
} }
if($response->failed()) if ($response->failed()) {
throw new YodleeApiException($response->body()); throw new YodleeApiException($response->body());
}
} }
@ -213,16 +207,15 @@ class Yodlee
$response = Http::withHeaders($this->getHeaders(["Authorization" => "Bearer {$token}"]))->get($this->getEndpoint(). "/transactions", $params); $response = Http::withHeaders($this->getHeaders(["Authorization" => "Bearer {$token}"]))->get($this->getEndpoint(). "/transactions", $params);
if($response->successful()){ if ($response->successful()) {
// return $response->object(); // return $response->object();
$it = new IncomeTransformer(); $it = new IncomeTransformer();
return $it->transform($response->object()); return $it->transform($response->object());
} }
if($response->failed()) if ($response->failed()) {
throw new YodleeApiException($response->body()); throw new YodleeApiException($response->body());
}
} }
public function getTransactionCount($params = []) public function getTransactionCount($params = [])
@ -231,16 +224,14 @@ class Yodlee
$response = Http::withHeaders($this->getHeaders(["Authorization" => "Bearer {$token}"]))->get($this->getEndpoint(). "/transactions/count", $params); $response = Http::withHeaders($this->getHeaders(["Authorization" => "Bearer {$token}"]))->get($this->getEndpoint(). "/transactions/count", $params);
if($response->successful()){ if ($response->successful()) {
return $response->object(); return $response->object();
} }
if($response->failed()) if ($response->failed()) {
throw new YodleeApiException($response->body()); throw new YodleeApiException($response->body());
}
} }
public function getTransactionCategories($params = []) public function getTransactionCategories($params = [])
{ {
@ -248,25 +239,26 @@ class Yodlee
$response = Http::withHeaders($this->getHeaders(["Authorization" => "Bearer {$token}"]))->get($this->getEndpoint(). "/transactions/categories", $params); $response = Http::withHeaders($this->getHeaders(["Authorization" => "Bearer {$token}"]))->get($this->getEndpoint(). "/transactions/categories", $params);
if($response->successful()) if ($response->successful()) {
return $response->object(); return $response->object();
}
if($response->failed()) if ($response->failed()) {
throw new YodleeApiException($response->body()); throw new YodleeApiException($response->body());
}
} }
private function bankFormRequest(string $uri, string $verb, array $data, array $headers) private function bankFormRequest(string $uri, string $verb, array $data, array $headers)
{ {
$response = Http::withHeaders($this->getFormHeaders($headers))->asForm()->{$verb}($this->getEndpoint() . $uri, $this->buildBody()); $response = Http::withHeaders($this->getFormHeaders($headers))->asForm()->{$verb}($this->getEndpoint() . $uri, $this->buildBody());
if($response->successful()) if ($response->successful()) {
return $response->object(); return $response->object();
}
if($response->failed()) if ($response->failed()) {
throw new YodleeApiException($response->body()); throw new YodleeApiException($response->body());
}
} }
private function getHeaders($data = []) private function getHeaders($data = [])
@ -287,12 +279,9 @@ class Yodlee
private function buildBody() private function buildBody()
{ {
return [ return [
'clientId' => $this->client_id, 'clientId' => $this->client_id,
'secret' => $this->client_secret, 'secret' => $this->client_secret,
]; ];
} }
} }

View File

@ -26,7 +26,7 @@ function isActive($page, bool $boolean = false)
$current_page = Route::currentRouteName(); $current_page = Route::currentRouteName();
$action = Route::currentRouteAction(); // string $action = Route::currentRouteAction(); // string
$show = str_replace(['.show','payment_methodss','documentss','subscriptionss','paymentss'],['s.index','payment_methods','documents','subscriptions','payments'], $current_page); $show = str_replace(['.show','payment_methodss','documentss','subscriptionss','paymentss'], ['s.index','payment_methods','documents','subscriptions','payments'], $current_page);
if ($page == $current_page && $boolean) { if ($page == $current_page && $boolean) {
return true; return true;
@ -36,7 +36,7 @@ function isActive($page, bool $boolean = false)
return 'bg-gray-200'; return 'bg-gray-200';
} }
if(($page == $show) && $boolean){ if (($page == $show) && $boolean) {
return true; return true;
} }

View File

@ -15,17 +15,16 @@ use App\Models\Company;
use App\Models\Invoice; use App\Models\Invoice;
use App\Models\RecurringInvoice; use App\Models\RecurringInvoice;
use App\Utils\Ninja; use App\Utils\Ninja;
use BaconQrCode\Renderer\ImageRenderer;
use BaconQrCode\Renderer\Image\SvgImageBackEnd; use BaconQrCode\Renderer\Image\SvgImageBackEnd;
use BaconQrCode\Renderer\ImageRenderer;
use BaconQrCode\Renderer\RendererStyle\RendererStyle; use BaconQrCode\Renderer\RendererStyle\RendererStyle;
use BaconQrCode\Writer; use BaconQrCode\Writer;
/** /**
* EpcQrGenerator. * EpcQrGenerator.
*/ */
class EpcQrGenerator class EpcQrGenerator
{ {
private array $sepa = [ private array $sepa = [
'serviceTag' => 'BCD', 'serviceTag' => 'BCD',
'version' => 2, 'version' => 2,
@ -36,11 +35,12 @@ class EpcQrGenerator
]; ];
public function __construct(protected Company $company, protected Invoice|RecurringInvoice $invoice, protected float $amount){} public function __construct(protected Company $company, protected Invoice|RecurringInvoice $invoice, protected float $amount)
{
}
public function getQrCode() public function getQrCode()
{ {
$renderer = new ImageRenderer( $renderer = new ImageRenderer(
new RendererStyle(200), new RendererStyle(200),
new SvgImageBackEnd() new SvgImageBackEnd()
@ -51,22 +51,18 @@ class EpcQrGenerator
try { try {
$qr = $writer->writeString($this->encodeMessage(), 'utf-8'); $qr = $writer->writeString($this->encodeMessage(), 'utf-8');
} } catch(\Throwable $e) {
catch(\Throwable $e){
return ''; return '';
} } catch(\Exception $e) {
catch(\Exception $e){
return ''; return '';
} }
return "<svg viewBox='0 0 200 200' width='200' height='200' x='0' y='0' xmlns='http://www.w3.org/2000/svg'> return "<svg viewBox='0 0 200 200' width='200' height='200' x='0' y='0' xmlns='http://www.w3.org/2000/svg'>
<rect x='0' y='0' width='100%'' height='100%' />{$qr}</svg>"; <rect x='0' y='0' width='100%'' height='100%' />{$qr}</svg>";
} }
public function encodeMessage() public function encodeMessage()
{ {
return rtrim(implode("\n", [
return rtrim(implode("\n", array(
$this->sepa['serviceTag'], $this->sepa['serviceTag'],
sprintf('%03d', $this->sepa['version']), sprintf('%03d', $this->sepa['version']),
$this->sepa['characterSet'], $this->sepa['characterSet'],
@ -76,25 +72,25 @@ class EpcQrGenerator
isset($this->company?->custom_fields?->company1) ? $this->company->settings->custom_value1 : '', isset($this->company?->custom_fields?->company1) ? $this->company->settings->custom_value1 : '',
$this->formatMoney($this->amount), $this->formatMoney($this->amount),
$this->sepa['purpose'], $this->sepa['purpose'],
substr($this->invoice->number,0,34), substr($this->invoice->number, 0, 34),
'', '',
'' ''
)), "\n"); ]), "\n");
} }
private function validateFields() private function validateFields()
{ {
if (Ninja::isSelfHost() && isset($this->company?->custom_fields?->company2)) {
if(Ninja::isSelfHost() && isset($this->company?->custom_fields?->company2))
nlog('The BIC field is not present and _may_ be a required fields for EPC QR codes'); nlog('The BIC field is not present and _may_ be a required fields for EPC QR codes');
}
if(Ninja::isSelfHost() && isset($this->company?->custom_fields?->company1)) if (Ninja::isSelfHost() && isset($this->company?->custom_fields?->company1)) {
nlog('The IBAN field is required'); nlog('The IBAN field is required');
}
} }
private function formatMoney($value) { private function formatMoney($value)
{
return sprintf('EUR%s', number_format($value, 2, '.', '')); return sprintf('EUR%s', number_format($value, 2, '.', ''));
} }
} }

View File

@ -43,4 +43,4 @@ function nlog($output, $context = []): void
$output = null; $output = null;
$context = null; $context = null;
} }

View File

@ -112,11 +112,9 @@ class InvoiceItemSum
if ($this->invoice->is_amount_discount) { if ($this->invoice->is_amount_discount) {
$this->setLineTotal($this->getLineTotal() - $this->formatValue($this->item->discount, $this->currency->precision)); $this->setLineTotal($this->getLineTotal() - $this->formatValue($this->item->discount, $this->currency->precision));
} else { } else {
$discount = ($this->item->line_total * ($this->item->discount / 100)); $discount = ($this->item->line_total * ($this->item->discount / 100));
$this->setLineTotal($this->formatValue(($this->getLineTotal() - $discount), $this->currency->precision)); $this->setLineTotal($this->formatValue(($this->getLineTotal() - $discount), $this->currency->precision));
} }
$this->item->is_amount_discount = $this->invoice->is_amount_discount; $this->item->is_amount_discount = $this->invoice->is_amount_discount;

View File

@ -12,7 +12,6 @@
namespace App\Helpers\Invoice; namespace App\Helpers\Invoice;
use App\Models\Invoice; use App\Models\Invoice;
use App\Models\TaxRate;
use App\Utils\Traits\NumberFormatter; use App\Utils\Traits\NumberFormatter;
use Illuminate\Support\Collection; use Illuminate\Support\Collection;
@ -101,7 +100,6 @@ class InvoiceSum
private function calculateCustomValues() private function calculateCustomValues()
{ {
$this->total_custom_values += $this->valuer($this->invoice->custom_surcharge1); $this->total_custom_values += $this->valuer($this->invoice->custom_surcharge1);
$this->total_custom_values += $this->valuer($this->invoice->custom_surcharge2); $this->total_custom_values += $this->valuer($this->invoice->custom_surcharge2);
@ -151,7 +149,6 @@ class InvoiceSum
*/ */
private function calculateBalance() private function calculateBalance()
{ {
$this->setCalculatedAttributes(); $this->setCalculatedAttributes();
return $this; return $this;

View File

@ -13,9 +13,7 @@ namespace App\Helpers\Invoice;
use App\Models\Invoice; use App\Models\Invoice;
use App\Models\RecurringInvoice; use App\Models\RecurringInvoice;
use Carbon\Exceptions\InvalidFormatException;
use Exception; use Exception;
use Illuminate\Contracts\Container\BindingResolutionException;
use Illuminate\Support\Carbon; use Illuminate\Support\Carbon;
class ProRata class ProRata

View File

@ -11,9 +11,9 @@
namespace App\Helpers\Mail; namespace App\Helpers\Mail;
use Google\Client;
use Google\Service\Gmail; use Google\Service\Gmail;
use Google\Service\Gmail\Message; use Google\Service\Gmail\Message;
use Google\Client;
use Symfony\Component\Mailer\SentMessage; use Symfony\Component\Mailer\SentMessage;
use Symfony\Component\Mailer\Transport\AbstractTransport; use Symfony\Component\Mailer\Transport\AbstractTransport;
use Symfony\Component\Mime\MessageConverter; use Symfony\Component\Mime\MessageConverter;
@ -23,7 +23,6 @@ use Symfony\Component\Mime\MessageConverter;
*/ */
class GmailTransport extends AbstractTransport class GmailTransport extends AbstractTransport
{ {
public function __construct() public function __construct()
{ {
parent::__construct(); parent::__construct();
@ -50,34 +49,26 @@ class GmailTransport extends AbstractTransport
$bcc_list = ''; $bcc_list = '';
if($bccs) if ($bccs) {
{
$bcc_list = 'Bcc: '; $bcc_list = 'Bcc: ';
foreach($bccs->getAddresses() as $address){ foreach ($bccs->getAddresses() as $address) {
$bcc_list .= $address->getAddress() .','; $bcc_list .= $address->getAddress() .',';
} }
$bcc_list = rtrim($bcc_list, ",") . "\r\n"; $bcc_list = rtrim($bcc_list, ",") . "\r\n";
} }
$body->setRaw($this->base64_encode($bcc_list.$message->toString())); $body->setRaw($this->base64_encode($bcc_list.$message->toString()));
try{ try {
$service->users_messages->send('me', $body, []); $service->users_messages->send('me', $body, []);
} } catch(\Google\Service\Exception $e) {
catch(\Google\Service\Exception $e) {
/* Need to slow down */ /* Need to slow down */
if($e->getCode() == '429') { if ($e->getCode() == '429') {
nlog("429 google - retrying "); nlog("429 google - retrying ");
$service->users_messages->send('me', $body, []); $service->users_messages->send('me', $body, []);
} }
} }
} }
@ -90,5 +81,4 @@ class GmailTransport extends AbstractTransport
{ {
return 'gmail'; return 'gmail';
} }
} }

View File

@ -11,16 +11,13 @@
namespace App\Helpers\Mail; namespace App\Helpers\Mail;
use Illuminate\Support\Str;
use Microsoft\Graph\Graph; use Microsoft\Graph\Graph;
use Microsoft\Graph\Model\UploadSession;
use Symfony\Component\Mailer\SentMessage; use Symfony\Component\Mailer\SentMessage;
use Symfony\Component\Mailer\Transport\AbstractTransport; use Symfony\Component\Mailer\Transport\AbstractTransport;
use Symfony\Component\Mime\MessageConverter; use Symfony\Component\Mime\MessageConverter;
class Office365MailTransport extends AbstractTransport class Office365MailTransport extends AbstractTransport
{ {
public function __construct() public function __construct()
{ {
parent::__construct(); parent::__construct();
@ -28,7 +25,6 @@ class Office365MailTransport extends AbstractTransport
protected function doSend(SentMessage $message): void protected function doSend(SentMessage $message): void
{ {
$symfony_message = MessageConverter::toEmail($message->getOriginalMessage()); $symfony_message = MessageConverter::toEmail($message->getOriginalMessage());
$graph = new Graph(); $graph = new Graph();
@ -41,16 +37,11 @@ class Office365MailTransport extends AbstractTransport
$bcc_list = ''; $bcc_list = '';
if($bccs) if ($bccs) {
{ foreach ($bccs->getAddresses() as $address) {
foreach($bccs->getAddresses() as $address){
$bcc_list .= 'Bcc: "'.$address->getAddress().'" <'.$address->getAddress().'>\r\n'; $bcc_list .= 'Bcc: "'.$address->getAddress().'" <'.$address->getAddress().'>\r\n';
} }
}
}
try { try {
$graphMessage = $graph->createRequest('POST', '/users/'.$symfony_message->getFrom()[0]->getAddress().'/sendmail') $graphMessage = $graph->createRequest('POST', '/users/'.$symfony_message->getFrom()[0]->getAddress().'/sendmail')
@ -66,12 +57,10 @@ class Office365MailTransport extends AbstractTransport
->setReturnType(\Microsoft\Graph\Model\Message::class) ->setReturnType(\Microsoft\Graph\Model\Message::class)
->execute(); ->execute();
} }
} }
public function __toString(): string public function __toString(): string
{ {
return 'office365'; return 'office365';
} }
} }

View File

@ -13,7 +13,6 @@ namespace App\Helpers\Subscription;
use App\Helpers\Invoice\ProRata; use App\Helpers\Invoice\ProRata;
use App\Models\Invoice; use App\Models\Invoice;
use App\Models\RecurringInvoice;
use App\Models\Subscription; use App\Models\Subscription;
use Illuminate\Support\Carbon; use Illuminate\Support\Carbon;

Some files were not shown because too many files have changed in this diff Show More