php cs fixes

This commit is contained in:
David Bomba 2023-10-26 13:57:44 +11:00
parent 96c15c9716
commit 33585c65c4
463 changed files with 3532 additions and 3726 deletions

View File

@ -16,12 +16,12 @@ use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
class EncryptedCast implements CastsAttributes class EncryptedCast implements CastsAttributes
{ {
public function get($model, string $key, $value, array $attributes) public function get($model, string $key, $value, array $attributes)
{ {
return is_string($value) && strlen($value) > 1 ? decrypt($value) : null; return is_string($value) && strlen($value) > 1 ? decrypt($value) : null;
} }
public function set($model, string $key, $value, array $attributes) public function set($model, string $key, $value, array $attributes)
{ {
return [$key => ! is_null($value) ? encrypt($value) : null]; return [$key => ! is_null($value) ? encrypt($value) : null];
} }
} }

View File

@ -11,13 +11,13 @@
namespace App\Console\Commands; namespace App\Console\Commands;
use App\Utils\Ninja; use App\Libraries\MultiDB;
use App\Models\Backup; use App\Models\Backup;
use App\Models\Client; use App\Models\Client;
use App\Models\Company; use App\Models\Company;
use App\Models\Document; use App\Models\Document;
use App\Libraries\MultiDB;
use App\Models\GroupSetting; use App\Models\GroupSetting;
use App\Utils\Ninja;
use Illuminate\Console\Command; use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Storage;
@ -56,8 +56,9 @@ class BackupUpdate extends Command
{ {
//always return state to first DB //always return state to first DB
if(Ninja::isSelfHost()) if(Ninja::isSelfHost()) {
return; return;
}
$current_db = config('database.default'); $current_db = config('database.default');

View File

@ -12,38 +12,37 @@
namespace App\Console\Commands; namespace App\Console\Commands;
use App; use App;
use Exception;
use App\Models\User;
use App\Utils\Ninja;
use App\Models\Quote;
use App\Models\Client;
use App\Models\Credit;
use App\Models\Vendor;
use App\Models\Account;
use App\Models\Company;
use App\Models\Contact;
use App\Models\Invoice;
use App\Models\Payment;
use App\Models\CompanyUser;
use Illuminate\Support\Str;
use App\Models\CompanyToken;
use App\Models\ClientContact;
use App\Models\CompanyLedger;
use App\Models\PurchaseOrder;
use App\Models\VendorContact;
use App\Models\BankTransaction;
use App\Models\QuoteInvitation;
use Illuminate\Console\Command;
use App\Models\CreditInvitation;
use App\Models\RecurringInvoice;
use App\Models\InvoiceInvitation;
use App\DataMapper\ClientSettings; use App\DataMapper\ClientSettings;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use App\Factory\ClientContactFactory; use App\Factory\ClientContactFactory;
use App\Factory\VendorContactFactory; use App\Factory\VendorContactFactory;
use App\Jobs\Company\CreateCompanyToken; use App\Jobs\Company\CreateCompanyToken;
use App\Models\Account;
use App\Models\BankTransaction;
use App\Models\Client;
use App\Models\ClientContact;
use App\Models\Company;
use App\Models\CompanyLedger;
use App\Models\CompanyToken;
use App\Models\CompanyUser;
use App\Models\Contact;
use App\Models\Credit;
use App\Models\CreditInvitation;
use App\Models\Invoice;
use App\Models\InvoiceInvitation;
use App\Models\Payment;
use App\Models\PurchaseOrder;
use App\Models\Quote;
use App\Models\QuoteInvitation;
use App\Models\RecurringInvoice;
use App\Models\RecurringInvoiceInvitation; use App\Models\RecurringInvoiceInvitation;
use App\Models\User;
use App\Models\Vendor;
use App\Models\VendorContact;
use App\Utils\Ninja;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;
use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputOption;
/* /*
@ -185,8 +184,7 @@ class CheckData extends Command
if ($cu->company && $cu->user) { if ($cu->company && $cu->user) {
(new CreateCompanyToken($cu->company, $cu->user, 'System'))->handle(); (new CreateCompanyToken($cu->company, $cu->user, 'System'))->handle();
} } else {
else {
// $cu->forceDelete(); // $cu->forceDelete();
} }
} }
@ -445,7 +443,7 @@ class CheckData extends Command
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]);
InvoiceInvitation::where('sent_date', '0000-00-00 00:00:00')->cursor()->each(function ($ii){ InvoiceInvitation::where('sent_date', '0000-00-00 00:00:00')->cursor()->each(function ($ii) {
$ii->sent_date = null; $ii->sent_date = null;
$ii->saveQuietly(); $ii->saveQuietly();
}); });
@ -619,7 +617,7 @@ class CheckData extends Command
} }
$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 clientBalanceQuery() private function clientBalanceQuery()
{ {
@ -1028,7 +1026,7 @@ class CheckData extends Command
{ {
$this->logMessage("checking bank transactions"); $this->logMessage("checking bank transactions");
BankTransaction::with('payment')->withTrashed()->where('invoice_ids', ',,,,,,,,')->cursor()->each(function ($bt){ BankTransaction::with('payment')->withTrashed()->where('invoice_ids', ',,,,,,,,')->cursor()->each(function ($bt) {
if($bt->payment->exists()) { if($bt->payment->exists()) {
@ -1052,7 +1050,7 @@ class CheckData extends Command
if ($this->option('fix') == 'true') { if ($this->option('fix') == 'true') {
$q->cursor()->each(function ($c){ $q->cursor()->each(function ($c) {
$c->send_email = false; $c->send_email = false;
$c->saveQuietly(); $c->saveQuietly();

View File

@ -20,7 +20,6 @@ use App\Models\Account;
use App\Models\Company; use App\Models\Company;
use App\Models\CompanyToken; use App\Models\CompanyToken;
use App\Models\User; use App\Models\User;
use App\Repositories\InvoiceRepository;
use App\Utils\Traits\GeneratesCounter; use App\Utils\Traits\GeneratesCounter;
use App\Utils\Traits\MakesHash; use App\Utils\Traits\MakesHash;
use Illuminate\Console\Command; use Illuminate\Console\Command;

View File

@ -11,52 +11,52 @@
namespace App\Console\Commands; namespace App\Console\Commands;
use stdClass; use App\DataMapper\ClientRegistrationFields;
use Carbon\Carbon; use App\DataMapper\CompanySettings;
use Faker\Factory; use App\DataMapper\FeesAndLimits;
use App\Models\Task; use App\Events\Invoice\InvoiceWasCreated;
use App\Models\User; use App\Events\RecurringInvoice\RecurringInvoiceWasCreated;
use App\Utils\Ninja; use App\Factory\GroupSettingFactory;
use App\Models\Quote; use App\Factory\InvoiceFactory;
use App\Models\Client; use App\Factory\InvoiceItemFactory;
use App\Models\Credit; use App\Factory\RecurringInvoiceFactory;
use App\Models\Vendor; use App\Factory\SubscriptionFactory;
use App\Helpers\Invoice\InvoiceSum;
use App\Jobs\Company\CreateCompanyTaskStatuses;
use App\Libraries\MultiDB;
use App\Models\Account; use App\Models\Account;
use App\Models\BankIntegration;
use App\Models\BankTransaction;
use App\Models\BankTransactionRule;
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\Country; use App\Models\Country;
use App\Models\Credit;
use App\Models\Expense; use App\Models\Expense;
use App\Models\Invoice; use App\Models\Invoice;
use App\Models\Product; use App\Models\Product;
use App\Models\Project; use App\Models\Project;
use App\Models\TaxRate; use App\Models\Quote;
use App\Libraries\MultiDB;
use App\Models\CompanyToken;
use App\Models\ClientContact;
use App\Models\VendorContact;
use App\Models\CompanyGateway;
use App\Factory\InvoiceFactory;
use App\Models\BankIntegration;
use App\Models\BankTransaction;
use App\Utils\Traits\MakesHash;
use Illuminate\Console\Command;
use App\Models\RecurringInvoice; use App\Models\RecurringInvoice;
use App\DataMapper\FeesAndLimits; use App\Models\Task;
use App\DataMapper\CompanySettings; use App\Models\TaxRate;
use App\Factory\InvoiceItemFactory; use App\Models\User;
use App\Helpers\Invoice\InvoiceSum; use App\Models\Vendor;
use App\Models\BankTransactionRule; use App\Models\VendorContact;
use App\Factory\GroupSettingFactory;
use App\Factory\SubscriptionFactory;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Cache;
use App\Utils\Traits\GeneratesCounter;
use Illuminate\Support\Facades\Schema;
use App\Repositories\InvoiceRepository; use App\Repositories\InvoiceRepository;
use App\Factory\RecurringInvoiceFactory; use App\Utils\Ninja;
use App\Events\Invoice\InvoiceWasCreated; use App\Utils\Traits\GeneratesCounter;
use App\DataMapper\ClientRegistrationFields; use App\Utils\Traits\MakesHash;
use App\Jobs\Company\CreateCompanyTaskStatuses; use Carbon\Carbon;
use App\Events\RecurringInvoice\RecurringInvoiceWasCreated; use Faker\Factory;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Schema;
use stdClass;
class CreateSingleAccount extends Command class CreateSingleAccount extends Command
{ {
@ -460,7 +460,7 @@ class CreateSingleAccount extends Command
$settings = $client->settings; $settings = $client->settings;
$settings->currency_id = "1"; $settings->currency_id = "1";
// $settings->use_credits_payment = "always"; // $settings->use_credits_payment = "always";
$client->settings = $settings; $client->settings = $settings;

View File

@ -496,7 +496,7 @@ class CreateTestData extends Command
$invoice = InvoiceFactory::create($client->company->id, $client->user->id); //stub the company and user_id $invoice = InvoiceFactory::create($client->company->id, $client->user->id); //stub the company and user_id
$invoice->client_id = $client->id; $invoice->client_id = $client->id;
// $invoice->date = $faker->date(); // $invoice->date = $faker->date();
$dateable = Carbon::now()->subDays(rand(0, 90)); $dateable = Carbon::now()->subDays(rand(0, 90));
$invoice->date = $dateable; $invoice->date = $dateable;

View File

@ -18,7 +18,6 @@ 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\Mail\MigrationFailed; use App\Mail\MigrationFailed;
use App\Models\Account; use App\Models\Account;
use App\Models\Company; use App\Models\Company;

View File

@ -52,8 +52,7 @@ class ReactBuilder extends Command
try { try {
$directoryIterator = new \RecursiveDirectoryIterator(public_path('react/v'.config('ninja.app_version').'/'), \RecursiveDirectoryIterator::SKIP_DOTS); $directoryIterator = new \RecursiveDirectoryIterator(public_path('react/v'.config('ninja.app_version').'/'), \RecursiveDirectoryIterator::SKIP_DOTS);
} } catch (\Exception $e) {
catch (\Exception $e) {
$this->error('React files not found'); $this->error('React files not found');
return; return;
} }

View File

@ -174,7 +174,7 @@ class SendRemindersCron extends Command
$invoice->calc()->getInvoice()->save(); $invoice->calc()->getInvoice()->save();
$invoice->fresh(); $invoice->fresh();
// $invoice->service()->deletePdf()->save(); // $invoice->service()->deletePdf()->save();
if ($invoice->client->getSetting('enable_e_invoice')){ if ($invoice->client->getSetting('enable_e_invoice')) {
$invoice->service()->deleteEInvoice()->save(); $invoice->service()->deleteEInvoice()->save();
} }

View File

@ -11,17 +11,10 @@
namespace App\Console\Commands; namespace App\Console\Commands;
use Faker\Factory;
use App\Models\User;
use App\Models\Account;
use App\Models\Company;
use App\Mail\TestMailServer;
use Illuminate\Console\Command;
use App\Jobs\Mail\NinjaMailerJob;
use App\DataMapper\CompanySettings;
use App\DataMapper\DefaultSettings;
use App\Jobs\Mail\NinjaMailerObject; use App\Jobs\Mail\NinjaMailerObject;
use App\Mail\Migration\MaxCompanies; use App\Mail\TestMailServer;
use App\Models\User;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Mail; use Illuminate\Support\Facades\Mail;
class SendTestEmails extends Command class SendTestEmails extends Command

View File

@ -11,29 +11,29 @@
namespace App\Console; namespace App\Console;
use App\Utils\Ninja;
use App\Models\Account;
use App\Jobs\Ninja\QueueSize;
use App\Jobs\Util\DiskCleanup;
use App\Jobs\Util\ReminderJob;
use App\Jobs\Cron\AutoBillCron; use App\Jobs\Cron\AutoBillCron;
use App\Jobs\Util\VersionCheck;
use App\Jobs\Ninja\TaskScheduler;
use App\Jobs\Util\SchedulerCheck;
use App\Jobs\Ninja\CheckACHStatus;
use App\Jobs\Cron\SubscriptionCron;
use App\Jobs\Ninja\AdjustEmailQuota;
use App\Jobs\Ninja\CompanySizeCheck;
use App\Jobs\Ninja\SystemMaintenance;
use App\Jobs\Quote\QuoteCheckExpired;
use App\Jobs\Util\UpdateExchangeRates;
use App\Jobs\Ninja\BankTransactionSync;
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\UpdateCalculatedFields; use App\Jobs\Cron\UpdateCalculatedFields;
use Illuminate\Console\Scheduling\Schedule;
use App\Jobs\Invoice\InvoiceCheckLateWebhook; use App\Jobs\Invoice\InvoiceCheckLateWebhook;
use App\Jobs\Ninja\AdjustEmailQuota;
use App\Jobs\Ninja\BankTransactionSync;
use App\Jobs\Ninja\CheckACHStatus;
use App\Jobs\Ninja\CompanySizeCheck;
use App\Jobs\Ninja\QueueSize;
use App\Jobs\Ninja\SystemMaintenance;
use App\Jobs\Ninja\TaskScheduler;
use App\Jobs\Quote\QuoteCheckExpired;
use App\Jobs\Subscription\CleanStaleInvoiceOrder; use App\Jobs\Subscription\CleanStaleInvoiceOrder;
use App\Jobs\Util\DiskCleanup;
use App\Jobs\Util\ReminderJob;
use App\Jobs\Util\SchedulerCheck;
use App\Jobs\Util\UpdateExchangeRates;
use App\Jobs\Util\VersionCheck;
use App\Models\Account;
use App\Utils\Ninja;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel; use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel class Kernel extends ConsoleKernel

View File

@ -497,11 +497,11 @@ class CompanySettings extends BaseSettings
'payment_receipt_design_id' => 'string', 'payment_receipt_design_id' => 'string',
'payment_refund_design_id' => 'string', 'payment_refund_design_id' => 'string',
'classification' => 'string', 'classification' => 'string',
'enable_e_invoice' => 'bool', 'enable_e_invoice' => 'bool',
'classification' => 'string', 'classification' => 'string',
'default_expense_payment_type_id' => 'string', 'default_expense_payment_type_id' => 'string',
'e_invoice_type' => 'string', 'e_invoice_type' => 'string',
'mailgun_endpoint' => 'string', 'mailgun_endpoint' => 'string',
'client_initiated_payments' => 'bool', 'client_initiated_payments' => 'bool',
'client_initiated_payments_minimum' => 'float', 'client_initiated_payments_minimum' => 'float',
'sync_invoice_quote_columns' => 'bool', 'sync_invoice_quote_columns' => 'bool',

View File

@ -34,4 +34,4 @@ class DefaultSettings extends BaseSettings
]; ];
} }
} }

View File

@ -44,7 +44,7 @@ class FreeCompanySettings extends BaseSettings
public $date_format_id = ''; public $date_format_id = '';
// public $enabled_item_tax_rates = 0; // public $enabled_item_tax_rates = 0;
public $expense_number_pattern = ''; public $expense_number_pattern = '';
public $expense_number_counter = 1; public $expense_number_counter = 1;

View File

@ -10,7 +10,7 @@
*/ */
namespace App\DataMapper\Settings; namespace App\DataMapper\Settings;
class SettingsData class SettingsData
{ {
public bool $auto_archive_invoice = false; // @implemented public bool $auto_archive_invoice = false; // @implemented
@ -469,27 +469,28 @@ class SettingsData
public function cast(mixed $object) public function cast(mixed $object)
{ {
if(is_array($object)) if(is_array($object)) {
$object = (object)$object; $object = (object)$object;
}
if (is_object($object)) { if (is_object($object)) {
foreach ($object as $key => $value) { foreach ($object as $key => $value) {
try{ try {
settype($object->{$key}, gettype($this->{$key})); settype($object->{$key}, gettype($this->{$key}));
} } catch(\Exception | \Error | \Throwable $e) {
catch(\Exception | \Error | \Throwable $e){
if(property_exists($this, $key)) if(property_exists($this, $key)) {
$object->{$key} = $this->{$key}; $object->{$key} = $this->{$key};
else } else {
unset($object->{$key}); unset($object->{$key});
}
} }
// if(!property_exists($this, $key)) { // if(!property_exists($this, $key)) {
// unset($object->{$key}); // unset($object->{$key});
// } // }
// elseif(is_array($object->{$key}) && gettype($this->{$key} != 'array')){ // elseif(is_array($object->{$key}) && gettype($this->{$key} != 'array')){
// $object->{$key} = $this->{$key}; // $object->{$key} = $this->{$key};
// } // }
@ -512,4 +513,4 @@ class SettingsData
{ {
return (array)$this->object; return (array)$this->object;
} }
} }

View File

@ -11,11 +11,11 @@
namespace App\DataMapper\Tax; namespace App\DataMapper\Tax;
use App\DataMapper\Tax\ZipTax\Response;
use App\DataProviders\USStates;
use App\Models\Client; use App\Models\Client;
use App\Models\Invoice; use App\Models\Invoice;
use App\Models\Product; use App\Models\Product;
use App\DataProviders\USStates;
use App\DataMapper\Tax\ZipTax\Response;
class BaseRule implements RuleInterface class BaseRule implements RuleInterface
{ {
@ -66,7 +66,7 @@ class BaseRule implements RuleInterface
'SK', // Slovakia 'SK', // Slovakia
]; ];
public array $region_codes = [ public array $region_codes = [
'AT' => 'EU', // Austria 'AT' => 'EU', // Austria
'BE' => 'EU', // Belgium 'BE' => 'EU', // Belgium
'BG' => 'EU', // Bulgaria 'BG' => 'EU', // Bulgaria
@ -147,8 +147,9 @@ class BaseRule implements RuleInterface
$this->resolveRegions(); $this->resolveRegions();
if(!$this->isTaxableRegion()) if(!$this->isTaxableRegion()) {
return $this; return $this;
}
$this->configTaxData(); $this->configTaxData();
@ -173,26 +174,26 @@ class BaseRule implements RuleInterface
/** Harvest the client_region */ /** Harvest the client_region */
/** If the tax data is already set and the invoice is marked as sent, do not adjust the rates */ /** If the tax data is already set and the invoice is marked as sent, do not adjust the rates */
if($this->invoice->tax_data && $this->invoice->status_id > 1) if($this->invoice->tax_data && $this->invoice->status_id > 1) {
return $this; return $this;
}
/** /**
* Origin - Company Tax Data * Origin - Company Tax Data
* Destination - Client Tax Data * Destination - Client Tax Data
* *
*/ */
$tax_data = false; $tax_data = false;
if($this->seller_region == 'US' && $this->client_region == 'US'){ if($this->seller_region == 'US' && $this->client_region == 'US') {
$company = $this->invoice->company; $company = $this->invoice->company;
/** If no company tax data has been configured, lets do that now. */ /** If no company tax data has been configured, lets do that now. */
/** We should never encounter this scenario */ /** We should never encounter this scenario */
if(!$company->origin_tax_data) if(!$company->origin_tax_data) {
{ $this->should_calc_tax = false;
$this->should_calc_tax = false;
return $this; return $this;
} }
@ -201,8 +202,7 @@ class BaseRule implements RuleInterface
$tax_data = $company->origin_tax_data; $tax_data = $company->origin_tax_data;
} } elseif($this->client->tax_data) {
elseif($this->client->tax_data){
$tax_data = $this->client->tax_data; $tax_data = $this->client->tax_data;
@ -215,8 +215,9 @@ class BaseRule implements RuleInterface
$this->invoice->tax_data = $tax_data; $this->invoice->tax_data = $tax_data;
if(\DB::transactionLevel() == 0) if(\DB::transactionLevel() == 0) {
$this->invoice->saveQuietly(); $this->invoice->saveQuietly();
}
} }
return $this; return $this;
@ -234,7 +235,7 @@ class BaseRule implements RuleInterface
$this->client_region = $this->region_codes[$this->client->country->iso_3166_2]; $this->client_region = $this->region_codes[$this->client->country->iso_3166_2];
match($this->client_region){ match($this->client_region) {
'US' => $this->client_subregion = isset($this->invoice?->client?->tax_data?->geoState) ? $this->invoice->client->tax_data->geoState : $this->getUSState(), 'US' => $this->client_subregion = isset($this->invoice?->client?->tax_data?->geoState) ? $this->invoice->client->tax_data->geoState : $this->getUSState(),
'EU' => $this->client_subregion = $this->client->country->iso_3166_2, 'EU' => $this->client_subregion = $this->client->country->iso_3166_2,
'AU' => $this->client_subregion = 'AU', 'AU' => $this->client_subregion = 'AU',
@ -251,8 +252,9 @@ class BaseRule implements RuleInterface
$states = USStates::$states; $states = USStates::$states;
if(isset($states[$this->client->state])) if(isset($states[$this->client->state])) {
return $this->client->state; return $this->client->state;
}
return USStates::getState(strlen($this->client->postal_code) > 1 ? $this->client->postal_code : $this->client->shipping_postal_code); return USStates::getState(strlen($this->client->postal_code) > 1 ? $this->client->postal_code : $this->client->shipping_postal_code);
@ -263,7 +265,7 @@ class BaseRule implements RuleInterface
public function isTaxableRegion(): bool public function isTaxableRegion(): bool
{ {
return $this->client->company->tax_data->regions->{$this->client_region}->tax_all_subregions || return $this->client->company->tax_data->regions->{$this->client_region}->tax_all_subregions ||
(property_exists($this->client->company->tax_data->regions->{$this->client_region}->subregions, $this->client_subregion) && $this->client->company->tax_data->regions->{$this->client_region}->subregions->{$this->client_subregion}->apply_tax); (property_exists($this->client->company->tax_data->regions->{$this->client_region}->subregions, $this->client_subregion) && $this->client->company->tax_data->regions->{$this->client_region}->subregions->{$this->client_subregion}->apply_tax);
} }
@ -277,8 +279,7 @@ class BaseRule implements RuleInterface
return $this; return $this;
} } elseif($this->client_region == 'AU') { //these are defaults and are only stubbed out for now, for AU we can actually remove these
elseif($this->client_region == 'AU'){ //these are defaults and are only stubbed out for now, for AU we can actually remove these
$this->tax_rate1 = $this->client->company->tax_data->regions->AU->subregions->AU->tax_rate; $this->tax_rate1 = $this->client->company->tax_data->regions->AU->subregions->AU->tax_rate;
$this->tax_name1 = $this->client->company->tax_data->regions->AU->subregions->AU->tax_name; $this->tax_name1 = $this->client->company->tax_data->regions->AU->subregions->AU->tax_name;

View File

@ -11,12 +11,12 @@
namespace App\DataMapper\Tax\DE; namespace App\DataMapper\Tax\DE;
use App\Models\Product;
use App\DataMapper\Tax\BaseRule; use App\DataMapper\Tax\BaseRule;
use App\DataMapper\Tax\RuleInterface; use App\DataMapper\Tax\RuleInterface;
use App\Models\Product;
class Rule extends BaseRule implements RuleInterface class Rule extends BaseRule implements RuleInterface
{ {
/** @var string $seller_region */ /** @var string $seller_region */
public string $seller_region = 'EU'; public string $seller_region = 'EU';
@ -67,7 +67,7 @@ class Rule extends BaseRule implements RuleInterface
return $this->taxExempt($item); return $this->taxExempt($item);
} }
match(intval($item->tax_id)){ match(intval($item->tax_id)) {
Product::PRODUCT_TYPE_EXEMPT => $this->taxExempt($item), Product::PRODUCT_TYPE_EXEMPT => $this->taxExempt($item),
Product::PRODUCT_TYPE_DIGITAL => $this->taxDigital($item), Product::PRODUCT_TYPE_DIGITAL => $this->taxDigital($item),
Product::PRODUCT_TYPE_SERVICE => $this->taxService($item), Product::PRODUCT_TYPE_SERVICE => $this->taxService($item),
@ -220,39 +220,28 @@ class Rule extends BaseRule implements RuleInterface
// nlog("tax exempt"); // nlog("tax exempt");
$this->tax_rate = 0; $this->tax_rate = 0;
$this->reduced_tax_rate = 0; $this->reduced_tax_rate = 0;
} } elseif($this->client_subregion != $this->client->company->tax_data->seller_subregion && in_array($this->client_subregion, $this->eu_country_codes) && $this->client->vat_number && $this->eu_business_tax_exempt) {
elseif($this->client_subregion != $this->client->company->tax_data->seller_subregion && in_array($this->client_subregion, $this->eu_country_codes) && $this->client->vat_number && $this->eu_business_tax_exempt) // elseif($this->client_subregion != $this->client->company->tax_data->seller_subregion && in_array($this->client_subregion, $this->eu_country_codes) && $this->client->has_valid_vat_number && $this->eu_business_tax_exempt)
// elseif($this->client_subregion != $this->client->company->tax_data->seller_subregion && in_array($this->client_subregion, $this->eu_country_codes) && $this->client->has_valid_vat_number && $this->eu_business_tax_exempt)
{
// nlog("euro zone and tax exempt"); // nlog("euro zone and tax exempt");
$this->tax_rate = 0; $this->tax_rate = 0;
$this->reduced_tax_rate = 0; $this->reduced_tax_rate = 0;
} } elseif(!in_array($this->client_subregion, $this->eu_country_codes) && ($this->foreign_consumer_tax_exempt || $this->foreign_business_tax_exempt)) { //foreign + tax exempt
elseif(!in_array($this->client_subregion, $this->eu_country_codes) && ($this->foreign_consumer_tax_exempt || $this->foreign_business_tax_exempt)) //foreign + tax exempt
{
// nlog("foreign and tax exempt"); // nlog("foreign and tax exempt");
$this->tax_rate = 0; $this->tax_rate = 0;
$this->reduced_tax_rate = 0; $this->reduced_tax_rate = 0;
} } elseif(!in_array($this->client_subregion, $this->eu_country_codes)) {
elseif(!in_array($this->client_subregion, $this->eu_country_codes))
{
$this->defaultForeign(); $this->defaultForeign();
} } elseif(in_array($this->client_subregion, $this->eu_country_codes) && !$this->client->vat_number) { //eu country / no valid vat
elseif(in_array($this->client_subregion, $this->eu_country_codes) && !$this->client->vat_number) //eu country / no valid vat if(($this->client->company->tax_data->seller_subregion != $this->client_subregion) && $this->client->company->tax_data->regions->EU->has_sales_above_threshold) {
{
if(($this->client->company->tax_data->seller_subregion != $this->client_subregion) && $this->client->company->tax_data->regions->EU->has_sales_above_threshold)
{
// nlog("eu zone with sales above threshold"); // nlog("eu zone with sales above threshold");
$this->tax_rate = $this->client->company->tax_data->regions->EU->subregions->{$this->client->country->iso_3166_2}->tax_rate; $this->tax_rate = $this->client->company->tax_data->regions->EU->subregions->{$this->client->country->iso_3166_2}->tax_rate;
$this->reduced_tax_rate = $this->client->company->tax_data->regions->EU->subregions->{$this->client->country->iso_3166_2}->reduced_tax_rate; $this->reduced_tax_rate = $this->client->company->tax_data->regions->EU->subregions->{$this->client->country->iso_3166_2}->reduced_tax_rate;
} } else {
else {
// nlog("EU with intra-community supply ie DE to DE"); // nlog("EU with intra-community supply ie DE to DE");
$this->tax_rate = $this->client->company->tax_data->regions->EU->subregions->{$this->client->company->country()->iso_3166_2}->tax_rate; $this->tax_rate = $this->client->company->tax_data->regions->EU->subregions->{$this->client->company->country()->iso_3166_2}->tax_rate;
$this->reduced_tax_rate = $this->client->company->tax_data->regions->EU->subregions->{$this->client->company->country()->iso_3166_2}->reduced_tax_rate; $this->reduced_tax_rate = $this->client->company->tax_data->regions->EU->subregions->{$this->client->company->country()->iso_3166_2}->reduced_tax_rate;
} }
} } else {
else {
// nlog("default tax"); // nlog("default tax");
$this->tax_rate = $this->client->company->tax_data->regions->EU->subregions->{$this->client->company->country()->iso_3166_2}->tax_rate; $this->tax_rate = $this->client->company->tax_data->regions->EU->subregions->{$this->client->company->country()->iso_3166_2}->tax_rate;
$this->reduced_tax_rate = $this->client->company->tax_data->regions->EU->subregions->{$this->client->company->country()->iso_3166_2}->reduced_tax_rate; $this->reduced_tax_rate = $this->client->company->tax_data->regions->EU->subregions->{$this->client->company->country()->iso_3166_2}->reduced_tax_rate;
@ -262,4 +251,4 @@ class Rule extends BaseRule implements RuleInterface
} }
} }

View File

@ -36,4 +36,4 @@ interface RuleInterface
public function override($item); public function override($item);
public function calculateRates(); public function calculateRates();
} }

View File

@ -15,7 +15,7 @@ use App\DataMapper\Tax\ZipTax\Response;
/** /**
* InvoiceTaxData * InvoiceTaxData
* *
* Definition for the invoice tax data structure * Definition for the invoice tax data structure
*/ */
class TaxData class TaxData

View File

@ -11,7 +11,7 @@
namespace App\DataMapper\Tax; namespace App\DataMapper\Tax;
class TaxModel class TaxModel
{ {
/** @var string $seller_subregion */ /** @var string $seller_subregion */
@ -32,10 +32,11 @@ class TaxModel
public function __construct(public ?TaxModel $model = null) public function __construct(public ?TaxModel $model = null)
{ {
if(!$this->model) if(!$this->model) {
$this->regions = $this->init(); $this->regions = $this->init();
else } else {
$this->regions = $model; $this->regions = $model;
}
} }
@ -79,7 +80,7 @@ class TaxModel
* *
* @return self * @return self
*/ */
private function auSubRegions(): self private function auSubRegions(): self
{ {
$this->regions->AU->subregions = new \stdClass(); $this->regions->AU->subregions = new \stdClass();
@ -387,7 +388,7 @@ class TaxModel
$this->regions->EU->subregions->EE = new \stdClass(); $this->regions->EU->subregions->EE = new \stdClass();
$this->regions->EU->subregions->EE->tax_rate = 20; $this->regions->EU->subregions->EE->tax_rate = 20;
$this->regions->EU->subregions->EE->tax_name = 'KM'; $this->regions->EU->subregions->EE->tax_name = 'KM';
$this->regions->EU->subregions->EE->reduced_tax_rate = 9; $this->regions->EU->subregions->EE->reduced_tax_rate = 9;
$this->regions->EU->subregions->EE->apply_tax = false; $this->regions->EU->subregions->EE->apply_tax = false;

View File

@ -74,7 +74,7 @@ class Rule extends BaseRule implements RuleInterface
Product::PRODUCT_TYPE_SHIPPING => $this->taxShipping($item), Product::PRODUCT_TYPE_SHIPPING => $this->taxShipping($item),
Product::PRODUCT_TYPE_PHYSICAL => $this->taxPhysical($item), Product::PRODUCT_TYPE_PHYSICAL => $this->taxPhysical($item),
Product::PRODUCT_TYPE_REDUCED_TAX => $this->taxReduced($item), Product::PRODUCT_TYPE_REDUCED_TAX => $this->taxReduced($item),
Product::PRODUCT_TYPE_OVERRIDE_TAX => $this->override($item), Product::PRODUCT_TYPE_OVERRIDE_TAX => $this->override($item),
Product::PRODUCT_TYPE_ZERO_RATED => $this->zeroRated($item), Product::PRODUCT_TYPE_ZERO_RATED => $this->zeroRated($item),
default => $this->default($item), default => $this->default($item),
}; };
@ -117,10 +117,9 @@ class Rule extends BaseRule implements RuleInterface
*/ */
public function taxService($item): self public function taxService($item): self
{ {
if(in_array($this->tax_data?->txbService,['Y','L'])) { if(in_array($this->tax_data?->txbService, ['Y','L'])) {
$this->default($item); $this->default($item);
} } else {
else {
$this->taxExempt($item); $this->taxExempt($item);
} }
@ -224,4 +223,4 @@ class Rule extends BaseRule implements RuleInterface
return $this; return $this;
} }
} }

View File

@ -53,7 +53,7 @@ class Response
* "district5SalesTax" => 0, * "district5SalesTax" => 0,
* "district5UseTax" => 0, * "district5UseTax" => 0,
* "originDestination" => "D", * "originDestination" => "D",
* *
* ]; * ];
* *
*/ */
@ -114,4 +114,3 @@ class Response
} }
} }

View File

@ -33868,18 +33868,21 @@ class USStates
public static function getState(?string $zip = '90210'): string public static function getState(?string $zip = '90210'): string
{ {
if(isset(self::$zip_code_map[$zip])) if(isset(self::$zip_code_map[$zip])) {
return self::$zip_code_map[$zip]; return self::$zip_code_map[$zip];
}
$prefix_state = self::getStateFromThreeDigitPrefix($zip); $prefix_state = self::getStateFromThreeDigitPrefix($zip);
if($prefix_state) if($prefix_state) {
return $prefix_state; return $prefix_state;
}
$zippo_response = self::getStateFromZippo($zip); $zippo_response = self::getStateFromZippo($zip);
if($zippo_response) if($zippo_response) {
return $zippo_response; return $zippo_response;
}
throw new \Exception('Zip code not found'); throw new \Exception('Zip code not found');
} }
@ -33905,8 +33908,9 @@ class USStates
$response = Http::get("https://api.zippopotam.us/us/{$zip}"); $response = Http::get("https://api.zippopotam.us/us/{$zip}");
if($response->failed()) if($response->failed()) {
return false; return false;
}
$data = $response->object(); $data = $response->object();
@ -33921,7 +33925,7 @@ class USStates
public static function getStateFromThreeDigitPrefix($zip): mixed public static function getStateFromThreeDigitPrefix($zip): mixed
{ {
/* 000 to 999 */ /* 000 to 999 */
$zip_by_state = [ $zip_by_state = [
'--', '--', '--', '--', '--', 'NY', 'PR', 'PR', 'VI', 'PR', 'MA', 'MA', 'MA', '--', '--', '--', '--', '--', 'NY', 'PR', 'PR', 'VI', 'PR', 'MA', 'MA', 'MA',
'MA', 'MA', 'MA', 'MA', 'MA', 'MA', 'MA', 'MA', 'MA', 'MA', 'MA', 'MA', 'MA', 'MA', 'MA', 'MA', 'MA', 'MA', 'MA', 'MA', 'MA', 'MA', 'MA', 'MA', 'MA', 'MA',
@ -34004,7 +34008,7 @@ class USStates
$prefix = substr($zip, 0, 3); $prefix = substr($zip, 0, 3);
$index = intval($prefix); $index = intval($prefix);
/* converts prefix to integer */ /* converts prefix to integer */
return $zip_by_state[$index] == "--" ? false : $zip_by_state[$index]; return $zip_by_state[$index] == "--" ? false : $zip_by_state[$index];
} }

View File

@ -49,9 +49,9 @@ class AccountCreated
// * // *
// * @return Channel|array // * @return Channel|array
// */ // */
public function broadcastOn() public function broadcastOn()
{ {
return []; return [];
// return new PrivateChannel('channel-name'); // return new PrivateChannel('channel-name');
} }
} }

View File

@ -12,11 +12,9 @@
namespace App\Events\Account; namespace App\Events\Account;
use App\Models\Company; use App\Models\Company;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets; use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
/** /**
* Class StripeConnectFailure. * Class StripeConnectFailure.

View File

@ -15,7 +15,6 @@ use App\Models\Client;
use App\Models\Company; use App\Models\Company;
use Illuminate\Broadcasting\Channel; use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets; use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels; use Illuminate\Queue\SerializesModels;
@ -54,8 +53,8 @@ class ClientWasArchived
// * // *
// * @return Channel|array // * @return Channel|array
// */ // */
public function broadcastOn() public function broadcastOn()
{ {
return []; return [];
} }
} }

View File

@ -14,7 +14,6 @@ namespace App\Events\Company;
use App\Models\Company; use App\Models\Company;
use Illuminate\Broadcasting\Channel; use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets; use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels; use Illuminate\Queue\SerializesModels;
@ -42,8 +41,8 @@ class CompanyDocumentsDeleted
* *
* @return Channel|array * @return Channel|array
*/ */
public function broadcastOn() public function broadcastOn()
{ {
return []; return [];
} }
} }

View File

@ -14,7 +14,6 @@ namespace App\Events\Contact;
use App\Models\ClientContact; use App\Models\ClientContact;
use Illuminate\Broadcasting\Channel; use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets; use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels; use Illuminate\Queue\SerializesModels;
@ -50,8 +49,8 @@ class ContactLoggedIn
* *
* @return Channel|array * @return Channel|array
*/ */
public function broadcastOn() public function broadcastOn()
{ {
return []; return [];
} }
} }

View File

@ -15,7 +15,6 @@ use App\Models\Company;
use App\Models\Design; use App\Models\Design;
use Illuminate\Broadcasting\Channel; use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets; use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels; use Illuminate\Queue\SerializesModels;
@ -35,8 +34,8 @@ class DesignWasArchived
* *
* @return Channel|array * @return Channel|array
*/ */
public function broadcastOn() public function broadcastOn()
{ {
return []; return [];
} }
} }

View File

@ -11,10 +11,10 @@
namespace App\Events\Design; namespace App\Events\Design;
use App\Models\Design;
use App\Models\Company; use App\Models\Company;
use Illuminate\Queue\SerializesModels; use App\Models\Design;
use Illuminate\Broadcasting\PrivateChannel; use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Queue\SerializesModels;
/** /**
* Class DesignWasCreated. * Class DesignWasCreated.
@ -32,8 +32,8 @@ class DesignWasCreated
* *
* @return PrivateChannel|array * @return PrivateChannel|array
*/ */
public function broadcastOn() public function broadcastOn()
{ {
return []; return [];
} }
} }

View File

@ -11,10 +11,10 @@
namespace App\Events\Design; namespace App\Events\Design;
use App\Models\Design;
use App\Models\Company; use App\Models\Company;
use Illuminate\Queue\SerializesModels; use App\Models\Design;
use Illuminate\Broadcasting\PrivateChannel; use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Queue\SerializesModels;
/** /**
* Class DesignWasDeleted. * Class DesignWasDeleted.
@ -32,8 +32,8 @@ class DesignWasDeleted
* *
* @return PrivateChannel|array * @return PrivateChannel|array
*/ */
public function broadcastOn() public function broadcastOn()
{ {
return []; return [];
} }
} }

View File

@ -11,10 +11,10 @@
namespace App\Events\Design; namespace App\Events\Design;
use App\Models\Design;
use App\Models\Company; use App\Models\Company;
use Illuminate\Queue\SerializesModels; use App\Models\Design;
use Illuminate\Broadcasting\PrivateChannel; use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Queue\SerializesModels;
/** /**
* Class DesignWasRestored. * Class DesignWasRestored.
@ -32,8 +32,8 @@ class DesignWasRestored
* *
* @return PrivateChannel|array * @return PrivateChannel|array
*/ */
public function broadcastOn() public function broadcastOn()
{ {
return []; return [];
} }
} }

View File

@ -11,10 +11,10 @@
namespace App\Events\Design; namespace App\Events\Design;
use App\Models\Design;
use App\Models\Company; use App\Models\Company;
use Illuminate\Queue\SerializesModels; use App\Models\Design;
use Illuminate\Broadcasting\PrivateChannel; use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Queue\SerializesModels;
/** /**
* Class DesignWasUpdated. * Class DesignWasUpdated.
@ -32,8 +32,8 @@ class DesignWasUpdated
* *
* @return PrivateChannel|array * @return PrivateChannel|array
*/ */
public function broadcastOn() public function broadcastOn()
{ {
return []; return [];
} }
} }

View File

@ -15,7 +15,6 @@ use App\Models\Company;
use App\Models\Document; use App\Models\Document;
use Illuminate\Broadcasting\Channel; use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets; use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels; use Illuminate\Queue\SerializesModels;

View File

@ -15,7 +15,6 @@ use App\Models\ClientGatewayToken;
use App\Models\Company; use App\Models\Company;
use Illuminate\Broadcasting\Channel; use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets; use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels; use Illuminate\Queue\SerializesModels;
@ -51,8 +50,8 @@ class MethodDeleted
* *
* @return Channel|array * @return Channel|array
*/ */
public function broadcastOn() public function broadcastOn()
{ {
return []; return [];
} }
} }

View File

@ -11,12 +11,12 @@
namespace App\Events\Payment; namespace App\Events\Payment;
use App\Models\ClientContact;
use App\Models\Company; use App\Models\Company;
use App\Models\Payment; use App\Models\Payment;
use App\Models\ClientContact;
use Illuminate\Queue\SerializesModels;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets; use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
/** /**
* Class PaymentWasEmailed. * Class PaymentWasEmailed.

View File

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

View File

@ -12,7 +12,6 @@
namespace App\Events\Quote; namespace App\Events\Quote;
use App\Models\Company; use App\Models\Company;
use App\Models\Quote;
use App\Models\QuoteInvitation; use App\Models\QuoteInvitation;
use Illuminate\Queue\SerializesModels; use Illuminate\Queue\SerializesModels;

View File

@ -5,7 +5,6 @@ namespace App\Events\Subscription;
use App\Models\Company; use App\Models\Company;
use App\Models\Subscription; use App\Models\Subscription;
use Illuminate\Broadcasting\InteractsWithSockets; use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels; use Illuminate\Queue\SerializesModels;
@ -45,8 +44,8 @@ class SubscriptionWasCreated
* *
* @return \Illuminate\Broadcasting\Channel|array * @return \Illuminate\Broadcasting\Channel|array
*/ */
public function broadcastOn() public function broadcastOn()
{ {
return []; return [];
} }
} }

View File

@ -15,7 +15,6 @@ use App\Models\Company;
use App\Models\User; use App\Models\User;
use Illuminate\Broadcasting\Channel; use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets; use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels; use Illuminate\Queue\SerializesModels;
@ -35,8 +34,8 @@ class UserLoggedIn
* *
* @return Channel|array * @return Channel|array
*/ */
public function broadcastOn() public function broadcastOn()
{ {
return []; return [];
} }
} }

View File

@ -15,7 +15,6 @@ use App\Models\Company;
use App\Models\User; use App\Models\User;
use Illuminate\Broadcasting\Channel; use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets; use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels; use Illuminate\Queue\SerializesModels;
@ -35,8 +34,8 @@ class UserWasArchived
* *
* @return Channel|array * @return Channel|array
*/ */
public function broadcastOn() public function broadcastOn()
{ {
return []; return [];
} }
} }

View File

@ -15,7 +15,6 @@ use App\Models\Company;
use App\Models\User; use App\Models\User;
use Illuminate\Broadcasting\Channel; use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets; use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels; use Illuminate\Queue\SerializesModels;
@ -35,8 +34,8 @@ class UserWasCreated
* *
* @return Channel|array * @return Channel|array
*/ */
public function broadcastOn() public function broadcastOn()
{ {
return []; return [];
} }
} }

View File

@ -15,7 +15,6 @@ use App\Models\Company;
use App\Models\User; use App\Models\User;
use Illuminate\Broadcasting\Channel; use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets; use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels; use Illuminate\Queue\SerializesModels;
@ -54,8 +53,8 @@ class UserWasDeleted
* *
* @return Channel|array * @return Channel|array
*/ */
public function broadcastOn() public function broadcastOn()
{ {
return []; return [];
} }
} }

View File

@ -15,7 +15,6 @@ use App\Models\Company;
use App\Models\User; use App\Models\User;
use Illuminate\Broadcasting\Channel; use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets; use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels; use Illuminate\Queue\SerializesModels;
@ -54,8 +53,8 @@ class UserWasRestored
* *
* @return Channel|array * @return Channel|array
*/ */
public function broadcastOn() public function broadcastOn()
{ {
return []; return [];
} }
} }

View File

@ -15,7 +15,6 @@ use App\Models\Company;
use App\Models\User; use App\Models\User;
use Illuminate\Broadcasting\Channel; use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets; use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels; use Illuminate\Queue\SerializesModels;
@ -54,8 +53,8 @@ class UserWasUpdated
* *
* @return Channel|array * @return Channel|array
*/ */
public function broadcastOn() public function broadcastOn()
{ {
return []; return [];
} }
} }

View File

@ -14,9 +14,9 @@ namespace App\Events\Vendor;
use App\Models\Company; use App\Models\Company;
use App\Models\VendorContact; use App\Models\VendorContact;
use Illuminate\Broadcasting\Channel; use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets; use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
/** /**
* Class VendorContactLoggedIn. * Class VendorContactLoggedIn.

View File

@ -11,31 +11,31 @@
namespace App\Exceptions; namespace App\Exceptions;
use Throwable;
use PDOException;
use App\Utils\Ninja; use App\Utils\Ninja;
use Sentry\State\Scope;
use Illuminate\Support\Arr;
use Illuminate\Http\Request;
use InvalidArgumentException;
use Sentry\Laravel\Integration;
use Illuminate\Support\Facades\Schema;
use Aws\Exception\CredentialsException; use Aws\Exception\CredentialsException;
use GuzzleHttp\Exception\ConnectException; use GuzzleHttp\Exception\ConnectException;
use Illuminate\Auth\AuthenticationException;
use League\Flysystem\UnableToCreateDirectory;
use Illuminate\Session\TokenMismatchException;
use Illuminate\Validation\ValidationException;
use Illuminate\Auth\Access\AuthorizationException; use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Queue\MaxAttemptsExceededException; use Illuminate\Auth\AuthenticationException;
use Illuminate\Http\Exceptions\ThrottleRequestsException; use Illuminate\Database\Eloquent\ModelNotFoundException as ModelNotFoundException;
use Symfony\Component\Process\Exception\RuntimeException;
use Illuminate\Database\Eloquent\RelationNotFoundException; use Illuminate\Database\Eloquent\RelationNotFoundException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Http\Exceptions\ThrottleRequestsException;
use Illuminate\Http\Request;
use Illuminate\Queue\MaxAttemptsExceededException;
use Illuminate\Session\TokenMismatchException;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Schema;
use Illuminate\Validation\ValidationException;
use InvalidArgumentException;
use League\Flysystem\UnableToCreateDirectory;
use PDOException;
use Sentry\Laravel\Integration;
use Sentry\State\Scope;
use Symfony\Component\Console\Exception\CommandNotFoundException; use Symfony\Component\Console\Exception\CommandNotFoundException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException; use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Illuminate\Database\Eloquent\ModelNotFoundException as ModelNotFoundException; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Process\Exception\RuntimeException;
use Throwable;
class Handler extends ExceptionHandler class Handler extends ExceptionHandler
{ {
@ -223,8 +223,8 @@ class Handler extends ExceptionHandler
return response()->json(['message' => $exception->getMessage()], 500); return response()->json(['message' => $exception->getMessage()], 500);
} elseif ($exception instanceof ThrottleRequestsException && $request->expectsJson()) { } elseif ($exception instanceof ThrottleRequestsException && $request->expectsJson()) {
return response()->json(['message'=>'Too many requests'], 429); return response()->json(['message'=>'Too many requests'], 429);
// } elseif ($exception instanceof FatalThrowableError && $request->expectsJson()) { // } elseif ($exception instanceof FatalThrowableError && $request->expectsJson()) {
// return response()->json(['message'=>'Fatal error'], 500); //@deprecated // return response()->json(['message'=>'Fatal error'], 500); //@deprecated
} elseif ($exception instanceof AuthorizationException && $request->expectsJson()) { } elseif ($exception instanceof AuthorizationException && $request->expectsJson()) {
return response()->json(['message'=> $exception->getMessage()], 401); return response()->json(['message'=> $exception->getMessage()], 401);
} elseif ($exception instanceof TokenMismatchException) { } elseif ($exception instanceof TokenMismatchException) {

View File

@ -13,8 +13,8 @@
namespace App\Exceptions; namespace App\Exceptions;
use Exception; use Exception;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class PaymentRefundFailed extends Exception class PaymentRefundFailed extends Exception
{ {

View File

@ -13,8 +13,8 @@
namespace App\Exceptions; namespace App\Exceptions;
use Exception; use Exception;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class QuoteConversion extends Exception class QuoteConversion extends Exception
{ {

View File

@ -13,8 +13,8 @@
namespace App\Exceptions; namespace App\Exceptions;
use Exception; use Exception;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class YodleeApiException extends Exception class YodleeApiException extends Exception
{ {

View File

@ -11,17 +11,17 @@
namespace App\Export\CSV; namespace App\Export\CSV;
use App\Models\Task;
use App\Utils\Ninja;
use League\Csv\Writer;
use App\Models\Company;
use App\Models\Activity;
use App\Libraries\MultiDB; use App\Libraries\MultiDB;
use App\Models\Activity;
use App\Models\Company;
use App\Models\DateFormat; use App\Models\DateFormat;
use App\Models\Task;
use App\Transformers\ActivityTransformer;
use App\Utils\Ninja;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Carbon; use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\App; use Illuminate\Support\Facades\App;
use Illuminate\Database\Eloquent\Builder; use League\Csv\Writer;
use App\Transformers\ActivityTransformer;
class ActivityExport extends BaseExport class ActivityExport extends BaseExport
{ {
@ -53,44 +53,44 @@ class ActivityExport extends BaseExport
$headerdisplay = $this->buildHeader(); $headerdisplay = $this->buildHeader();
$header = collect($this->input['report_keys'])->map(function ($key, $value) use($headerdisplay){ $header = collect($this->input['report_keys'])->map(function ($key, $value) use ($headerdisplay) {
return ['identifier' => $key, 'display_value' => $headerdisplay[$value]]; return ['identifier' => $key, 'display_value' => $headerdisplay[$value]];
})->toArray(); })->toArray();
$report = $query->cursor() $report = $query->cursor()
->map(function ($resource) { ->map(function ($resource) {
$row = $this->buildActivityRow($resource); $row = $this->buildActivityRow($resource);
return $this->processMetaData($row, $resource); return $this->processMetaData($row, $resource);
})->toArray(); })->toArray();
return array_merge(['columns' => $header], $report); return array_merge(['columns' => $header], $report);
} }
private function buildActivityRow(Activity $activity): array private function buildActivityRow(Activity $activity): array
{ {
return [ return [
Carbon::parse($activity->created_at)->format($this->date_format), Carbon::parse($activity->created_at)->format($this->date_format),
ctrans("texts.activity_{$activity->activity_type_id}",[ ctrans("texts.activity_{$activity->activity_type_id}", [
'payment_amount' => $activity->payment ? $activity->payment->amount : '', 'payment_amount' => $activity->payment ? $activity->payment->amount : '',
'adjustment' => $activity->payment ? $activity->payment->refunded : '', 'adjustment' => $activity->payment ? $activity->payment->refunded : '',
'client' => $activity->client ? $activity->client->present()->name() : '', 'client' => $activity->client ? $activity->client->present()->name() : '',
'contact' => $activity->contact ? $activity->contact->present()->name() : '', 'contact' => $activity->contact ? $activity->contact->present()->name() : '',
'quote' => $activity->quote ? $activity->quote->number : '', 'quote' => $activity->quote ? $activity->quote->number : '',
'user' => $activity->user ? $activity->user->present()->name() : 'System', 'user' => $activity->user ? $activity->user->present()->name() : 'System',
'expense' => $activity->expense ? $activity->expense->number : '', 'expense' => $activity->expense ? $activity->expense->number : '',
'invoice' => $activity->invoice ? $activity->invoice->number : '', 'invoice' => $activity->invoice ? $activity->invoice->number : '',
'recurring_invoice' => $activity->recurring_invoice ? $activity->recurring_invoice->number : '', 'recurring_invoice' => $activity->recurring_invoice ? $activity->recurring_invoice->number : '',
'payment' => $activity->payment ? $activity->payment->number : '', 'payment' => $activity->payment ? $activity->payment->number : '',
'credit' => $activity->credit ? $activity->credit->number : '', 'credit' => $activity->credit ? $activity->credit->number : '',
'task' => $activity->task ? $activity->task->number : '', 'task' => $activity->task ? $activity->task->number : '',
'vendor' => $activity->vendor ? $activity->vendor->present()->name() : '', 'vendor' => $activity->vendor ? $activity->vendor->present()->name() : '',
'purchase_order' => $activity->purchase_order ? $activity->purchase_order->number : '', 'purchase_order' => $activity->purchase_order ? $activity->purchase_order->number : '',
'subscription' => $activity->subscription ? $activity->subscription->name : '', 'subscription' => $activity->subscription ? $activity->subscription->name : '',
'vendor_contact' => $activity->vendor_contact ? $activity->vendor_contact->present()->name() : '', 'vendor_contact' => $activity->vendor_contact ? $activity->vendor_contact->present()->name() : '',
'recurring_expense' => $activity->recurring_expense ? $activity->recurring_expense->number : '', 'recurring_expense' => $activity->recurring_expense ? $activity->recurring_expense->number : '',
]), ]),
$activity->ip, $activity->ip,
]; ];
} }
@ -169,6 +169,6 @@ class ActivityExport extends BaseExport
} }
return $clean_row; return $clean_row;
} }
} }

View File

@ -11,30 +11,28 @@
namespace App\Export\CSV; namespace App\Export\CSV;
use App\Models\Activity;
use App\Models\Quote;
use App\Utils\Number;
use App\Models\Client; use App\Models\Client;
use App\Models\Credit; use App\Models\ClientContact;
use App\Utils\Helpers;
use App\Models\Company; use App\Models\Company;
use App\Models\Credit;
use App\Models\Document;
use App\Models\Expense; use App\Models\Expense;
use App\Models\Invoice; use App\Models\Invoice;
use App\Models\Payment; use App\Models\Payment;
use App\Models\Document;
use League\Fractal\Manager;
use App\Models\ClientContact;
use App\Models\PurchaseOrder;
use App\Models\RecurringInvoice;
use Illuminate\Support\Carbon;
use App\Utils\Traits\MakesHash;
use App\Transformers\TaskTransformer;
use App\Transformers\PaymentTransformer;
use Illuminate\Database\Eloquent\Builder;
use League\Fractal\Serializer\ArraySerializer;
use App\Models\Product; use App\Models\Product;
use App\Models\PurchaseOrder;
use App\Models\Quote;
use App\Models\RecurringInvoice;
use App\Models\Task; use App\Models\Task;
use App\Models\Vendor; use App\Models\Vendor;
use App\Transformers\PaymentTransformer;
use App\Transformers\TaskTransformer;
use App\Utils\Helpers;
use App\Utils\Traits\MakesHash;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Carbon;
use League\Fractal\Manager;
use League\Fractal\Serializer\ArraySerializer;
class BaseExport class BaseExport
{ {
@ -172,7 +170,7 @@ class BaseExport
'recurring_invoice' => 'invoice.recurring_id', 'recurring_invoice' => 'invoice.recurring_id',
]; ];
protected array $recurring_invoice_report_keys = [ protected array $recurring_invoice_report_keys = [
"invoice_number" => "recurring_invoice.number", "invoice_number" => "recurring_invoice.number",
"amount" => "recurring_invoice.amount", "amount" => "recurring_invoice.amount",
"balance" => "recurring_invoice.balance", "balance" => "recurring_invoice.balance",
@ -446,8 +444,7 @@ class BaseExport
$client = Client::withTrashed()->find($this->input['client_id']); $client = Client::withTrashed()->find($this->input['client_id']);
$this->client_description = $client->present()->name; $this->client_description = $client->present()->name;
return $query->where('client_id', $this->input['client_id']); return $query->where('client_id', $this->input['client_id']);
} } elseif(isset($this->input['clients']) && count($this->input['clients']) > 0) {
elseif(isset($this->input['clients']) && count($this->input['clients']) > 0) {
$this->client_description = 'Multiple Clients'; $this->client_description = 'Multiple Clients';
return $query->whereIn('client_id', $this->input['clients']); return $query->whereIn('client_id', $this->input['clients']);
@ -459,8 +456,9 @@ class BaseExport
{ {
$parts = explode(".", $key); $parts = explode(".", $key);
if(!is_array($parts) || count($parts) < 2) if(!is_array($parts) || count($parts) < 2) {
return ''; return '';
}
$value = ''; $value = '';
@ -497,8 +495,9 @@ class BaseExport
private function resolveVendorContactKey($column, $entity, $transformer) private function resolveVendorContactKey($column, $entity, $transformer)
{ {
if(!$entity->vendor) if(!$entity->vendor) {
return ""; return "";
}
$primary_contact = $entity->vendor->primary_contact()->first() ?? $entity->vendor->contacts()->first(); $primary_contact = $entity->vendor->primary_contact()->first() ?? $entity->vendor->contacts()->first();
@ -510,18 +509,21 @@ class BaseExport
private function resolveExpenseKey($column, $entity, $transformer) private function resolveExpenseKey($column, $entity, $transformer)
{ {
if($column == 'user' && $entity?->expense?->user) if($column == 'user' && $entity?->expense?->user) {
return $entity->expense->user->present()->name() ?? ' '; return $entity->expense->user->present()->name() ?? ' ';
}
if($column == 'assigned_user' && $entity?->expense?->assigned_user) if($column == 'assigned_user' && $entity?->expense?->assigned_user) {
return $entity->expense->assigned_user->present()->name() ?? ' '; return $entity->expense->assigned_user->present()->name() ?? ' ';
}
if($column == 'category' && $entity->expense) { if($column == 'category' && $entity->expense) {
return $entity->expense->category?->name ?? ' '; return $entity->expense->category?->name ?? ' ';
} }
if($entity instanceof Expense) if($entity instanceof Expense) {
return ''; return '';
}
$transformed_entity = $transformer->includeExpense($entity); $transformed_entity = $transformer->includeExpense($entity);
@ -529,11 +531,13 @@ class BaseExport
$manager->setSerializer(new ArraySerializer()); $manager->setSerializer(new ArraySerializer());
$transformed_entity = $manager->createData($transformed_entity)->toArray(); $transformed_entity = $manager->createData($transformed_entity)->toArray();
if(array_key_exists($column, $transformed_entity)) if(array_key_exists($column, $transformed_entity)) {
return $transformed_entity[$column]; return $transformed_entity[$column];
}
if(property_exists($entity, $column)) if(property_exists($entity, $column)) {
return $entity?->{$column} ?? ''; return $entity?->{$column} ?? '';
}
nlog("export: Could not resolve expense key: {$column}"); nlog("export: Could not resolve expense key: {$column}");
@ -560,8 +564,9 @@ class BaseExport
private function resolveVendorKey($column, $entity, $transformer) private function resolveVendorKey($column, $entity, $transformer)
{ {
if(!$entity->vendor) if(!$entity->vendor) {
return ''; return '';
}
$transformed_entity = $transformer->includeVendor($entity); $transformed_entity = $transformer->includeVendor($entity);
@ -569,24 +574,29 @@ class BaseExport
$manager->setSerializer(new ArraySerializer()); $manager->setSerializer(new ArraySerializer());
$transformed_entity = $manager->createData($transformed_entity)->toArray(); $transformed_entity = $manager->createData($transformed_entity)->toArray();
if($column == 'name') if($column == 'name') {
return $entity->vendor->present()->name() ?: ''; return $entity->vendor->present()->name() ?: '';
}
if($column == 'user_id') if($column == 'user_id') {
return $entity->vendor->user->present()->name() ?: ''; return $entity->vendor->user->present()->name() ?: '';
}
if($column == 'country_id') if($column == 'country_id') {
return $entity->vendor->country ? ctrans("texts.country_{$entity->vendor->country->name}") : ''; return $entity->vendor->country ? ctrans("texts.country_{$entity->vendor->country->name}") : '';
}
if ($column == 'currency_id') { if ($column == 'currency_id') {
return $entity->vendor->currency() ? $entity->vendor->currency()->code : $entity->company->currency()->code; return $entity->vendor->currency() ? $entity->vendor->currency()->code : $entity->company->currency()->code;
} }
if($column == 'status') if($column == 'status') {
return $entity->stringStatus($entity->status_id) ?: ''; return $entity->stringStatus($entity->status_id) ?: '';
}
if(array_key_exists($column, $transformed_entity)) if(array_key_exists($column, $transformed_entity)) {
return $transformed_entity[$column]; return $transformed_entity[$column];
}
// nlog("export: Could not resolve vendor key: {$column}"); // nlog("export: Could not resolve vendor key: {$column}");
@ -598,8 +608,9 @@ class BaseExport
private function resolveClientKey($column, $entity, $transformer) private function resolveClientKey($column, $entity, $transformer)
{ {
if(!$entity->client) if(!$entity->client) {
return ''; return '';
}
$transformed_client = $transformer->includeClient($entity); $transformed_client = $transformer->includeClient($entity);
@ -607,36 +618,46 @@ class BaseExport
$manager->setSerializer(new ArraySerializer()); $manager->setSerializer(new ArraySerializer());
$transformed_client = $manager->createData($transformed_client)->toArray(); $transformed_client = $manager->createData($transformed_client)->toArray();
if(in_array($column, ['client.name', 'name'])) if(in_array($column, ['client.name', 'name'])) {
return $transformed_client['display_name']; return $transformed_client['display_name'];
}
if(in_array($column, ['client.user_id', 'user_id'])) if(in_array($column, ['client.user_id', 'user_id'])) {
return $entity->client->user->present()->name(); return $entity->client->user->present()->name();
}
if(in_array($column, ['client.assigned_user_id', 'assigned_user_id'])) if(in_array($column, ['client.assigned_user_id', 'assigned_user_id'])) {
return $entity->client->assigned_user->present()->name(); return $entity->client->assigned_user->present()->name();
}
if(in_array($column, ['client.country_id', 'country_id'])) if(in_array($column, ['client.country_id', 'country_id'])) {
return $entity->client->country ? ctrans("texts.country_{$entity->client->country->name}") : ''; return $entity->client->country ? ctrans("texts.country_{$entity->client->country->name}") : '';
}
if(in_array($column, ['client.shipping_country_id', 'shipping_country_id'])) if(in_array($column, ['client.shipping_country_id', 'shipping_country_id'])) {
return $entity->client->shipping_country ? ctrans("texts.country_{$entity->client->shipping_country->name}") : ''; return $entity->client->shipping_country ? ctrans("texts.country_{$entity->client->shipping_country->name}") : '';
}
if(in_array($column, ['client.size_id', 'size_id'])) if(in_array($column, ['client.size_id', 'size_id'])) {
return $entity->client->size?->name ?? ''; return $entity->client->size?->name ?? '';
}
if(in_array($column, ['client.industry_id', 'industry_id'])) if(in_array($column, ['client.industry_id', 'industry_id'])) {
return $entity->client->industry?->name ?? ''; return $entity->client->industry?->name ?? '';
}
if (in_array($column, ['client.currency_id', 'currency_id'])) if (in_array($column, ['client.currency_id', 'currency_id'])) {
return $entity->client->currency() ? $entity->client->currency()->code : $entity->company->currency()->code; return $entity->client->currency() ? $entity->client->currency()->code : $entity->company->currency()->code;
}
if(in_array($column, ['payment_terms', 'client.payment_terms'])) if(in_array($column, ['payment_terms', 'client.payment_terms'])) {
return $entity->client->getSetting('payment_terms'); return $entity->client->getSetting('payment_terms');
}
if(array_key_exists($column, $transformed_client)) if(array_key_exists($column, $transformed_client)) {
return $transformed_client[$column]; return $transformed_client[$column];
}
// nlog("export: Could not resolve client key: {$column}"); // nlog("export: Could not resolve client key: {$column}");
@ -650,8 +671,9 @@ class BaseExport
$transformed_entity = $transformer->transform($entity); $transformed_entity = $transformer->transform($entity);
if($column == 'status') if($column == 'status') {
return $entity->stringStatus($entity->status_id); return $entity->stringStatus($entity->status_id);
}
return ''; return '';
} }
@ -682,16 +704,19 @@ class BaseExport
$manager->setSerializer(new ArraySerializer()); $manager->setSerializer(new ArraySerializer());
$transformed_invoices = $manager->createData($transformed_invoices)->toArray(); $transformed_invoices = $manager->createData($transformed_invoices)->toArray();
if(!isset($transformed_invoices['App\\Models\\Invoice'])) if(!isset($transformed_invoices['App\\Models\\Invoice'])) {
return ''; return '';
}
$transformed_invoices = $transformed_invoices['App\\Models\\Invoice']; $transformed_invoices = $transformed_invoices['App\\Models\\Invoice'];
if(count($transformed_invoices) == 1 && array_key_exists($column, $transformed_invoices[0])) if(count($transformed_invoices) == 1 && array_key_exists($column, $transformed_invoices[0])) {
return $transformed_invoices[0][$column]; return $transformed_invoices[0][$column];
}
if(count($transformed_invoices) > 1 && array_key_exists($column, $transformed_invoices[0])) if(count($transformed_invoices) > 1 && array_key_exists($column, $transformed_invoices[0])) {
return implode(', ', array_column($transformed_invoices, $column)); return implode(', ', array_column($transformed_invoices, $column));
}
return ""; return "";
@ -700,8 +725,9 @@ class BaseExport
if($transformer instanceof TaskTransformer && ($entity->invoice ?? false)) { if($transformer instanceof TaskTransformer && ($entity->invoice ?? false)) {
$transformed_invoice = $transformer->includeInvoice($entity); $transformed_invoice = $transformer->includeInvoice($entity);
if(!$transformed_invoice) if(!$transformed_invoice) {
return ''; return '';
}
$manager = new Manager(); $manager = new Manager();
$manager->setSerializer(new ArraySerializer()); $manager->setSerializer(new ArraySerializer());
@ -721,7 +747,7 @@ class BaseExport
private function resolvePaymentKey($column, $entity, $transformer) private function resolvePaymentKey($column, $entity, $transformer)
{ {
if($entity instanceof Payment){ if($entity instanceof Payment) {
$transformed_payment = $transformer->transform($entity); $transformed_payment = $transformer->transform($entity);
@ -737,8 +763,9 @@ class BaseExport
} }
if($column == 'amount') if($column == 'amount') {
return $entity->payments()->exists() ? $entity->payments()->withoutTrashed()->sum('paymentables.amount') : ctrans('texts.unpaid'); return $entity->payments()->exists() ? $entity->payments()->withoutTrashed()->sum('paymentables.amount') : ctrans('texts.unpaid');
}
if($column == 'refunded') { if($column == 'refunded') {
return $entity->payments()->exists() ? $entity->payments()->withoutTrashed()->sum('paymentables.refunded') : ''; return $entity->payments()->exists() ? $entity->payments()->withoutTrashed()->sum('paymentables.refunded') : '';
@ -753,24 +780,28 @@ class BaseExport
$payment = $entity->payments()->withoutTrashed()->first(); $payment = $entity->payments()->withoutTrashed()->first();
if(!$payment) if(!$payment) {
return ''; return '';
}
if($column == 'method') if($column == 'method') {
return $payment->translatedType(); return $payment->translatedType();
}
if($column == 'currency') if($column == 'currency') {
return $payment?->currency?->code ?? ''; return $payment?->currency?->code ?? '';
}
$payment_transformer = new PaymentTransformer(); $payment_transformer = new PaymentTransformer();
$transformed_payment = $payment_transformer->transform($payment); $transformed_payment = $payment_transformer->transform($payment);
if($column == 'status'){ if($column == 'status') {
return $payment->stringStatus($transformed_payment['status_id']); return $payment->stringStatus($transformed_payment['status_id']);
} }
if(array_key_exists($column, $transformed_payment)) if(array_key_exists($column, $transformed_payment)) {
return $transformed_payment[$column]; return $transformed_payment[$column];
}
return ''; return '';
@ -782,8 +813,9 @@ class BaseExport
$status_parameters = explode(',', $status); $status_parameters = explode(',', $status);
if(in_array('all', $status_parameters)) if(in_array('all', $status_parameters)) {
return $query; return $query;
}
$query->where(function ($nested) use ($status_parameters) { $query->where(function ($nested) use ($status_parameters) {
@ -816,9 +848,9 @@ class BaseExport
->orWhere('partial_due_date', '<', Carbon::now()); ->orWhere('partial_due_date', '<', Carbon::now());
} }
if(in_array('viewed', $status_parameters)){ if(in_array('viewed', $status_parameters)) {
$nested->whereHas('invitations', function ($q){ $nested->whereHas('invitations', function ($q) {
$q->whereNotNull('viewed_date')->whereNotNull('deleted_at'); $q->whereNotNull('viewed_date')->whereNotNull('deleted_at');
}); });
@ -884,8 +916,9 @@ class BaseExport
$first_month_of_year = $this->company->getSetting('first_month_of_year') ?? 1; $first_month_of_year = $this->company->getSetting('first_month_of_year') ?? 1;
$fin_year_start = now()->createFromDate(now()->year, $first_month_of_year, 1); $fin_year_start = now()->createFromDate(now()->year, $first_month_of_year, 1);
if(now()->lt($fin_year_start)) if(now()->lt($fin_year_start)) {
$fin_year_start->subYearNoOverflow(); $fin_year_start->subYearNoOverflow();
}
$this->start_date = $fin_year_start->format('Y-m-d'); $this->start_date = $fin_year_start->format('Y-m-d');
$this->end_date = $fin_year_start->copy()->addYear()->subDay()->format('Y-m-d'); $this->end_date = $fin_year_start->copy()->addYear()->subDay()->format('Y-m-d');
@ -896,8 +929,9 @@ class BaseExport
$fin_year_start = now()->createFromDate(now()->year, $first_month_of_year, 1); $fin_year_start = now()->createFromDate(now()->year, $first_month_of_year, 1);
$fin_year_start->subYearNoOverflow(); $fin_year_start->subYearNoOverflow();
if(now()->subYear()->lt($fin_year_start)) if(now()->subYear()->lt($fin_year_start)) {
$fin_year_start->subYearNoOverflow(); $fin_year_start->subYearNoOverflow();
}
$this->start_date = $fin_year_start->format('Y-m-d'); $this->start_date = $fin_year_start->format('Y-m-d');
$this->end_date = $fin_year_start->copy()->addYear()->subDay()->format('Y-m-d'); $this->end_date = $fin_year_start->copy()->addYear()->subDay()->format('Y-m-d');
@ -914,7 +948,7 @@ class BaseExport
} }
/** /**
* Returns the merged array of * Returns the merged array of
* the entity with the matching * the entity with the matching
* item report keys * item report keys
* *
@ -979,8 +1013,9 @@ class BaseExport
$prefix = ctrans('texts.expense')." "; $prefix = ctrans('texts.expense')." ";
$key = array_search($value, $this->expense_report_keys); $key = array_search($value, $this->expense_report_keys);
if(!$key && $value == 'expense.category') if(!$key && $value == 'expense.category') {
$key = 'category'; $key = 'category';
}
} }
if(!$key) { if(!$key) {
@ -1024,42 +1059,36 @@ class BaseExport
$key = str_replace('product.', '', $key); $key = str_replace('product.', '', $key);
$key = str_replace('task.', '', $key); $key = str_replace('task.', '', $key);
if(stripos($value, 'custom_value') !== false) if(stripos($value, 'custom_value') !== false) {
{
$parts = explode(".", $value); $parts = explode(".", $value);
if(count($parts) == 2 && in_array($parts[0], ['credit','quote','invoice','purchase_order','recurring_invoice'])){ if(count($parts) == 2 && in_array($parts[0], ['credit','quote','invoice','purchase_order','recurring_invoice'])) {
$entity = "invoice".substr($parts[1], -1); $entity = "invoice".substr($parts[1], -1);
$prefix = ctrans("texts.".$parts[0]); $prefix = ctrans("texts.".$parts[0]);
$fallback = "custom_value".substr($parts[1], -1); $fallback = "custom_value".substr($parts[1], -1);
$custom_field_label = $helper->makeCustomField($this->company->custom_fields, $entity); $custom_field_label = $helper->makeCustomField($this->company->custom_fields, $entity);
if(strlen($custom_field_label) > 1) if(strlen($custom_field_label) > 1) {
$header[] = $custom_field_label; $header[] = $custom_field_label;
else { } else {
$header[] = $prefix . " ". ctrans("texts.{$fallback}"); $header[] = $prefix . " ". ctrans("texts.{$fallback}");
} }
} } elseif(count($parts) == 2 && (stripos($parts[0], 'vendor_contact') !== false || stripos($parts[0], 'contact') !== false)) {
elseif(count($parts) == 2 && (stripos($parts[0], 'vendor_contact') !== false || stripos($parts[0], 'contact') !== false)) {
$parts[0] = str_replace('vendor_contact', 'contact', $parts[0]); $parts[0] = str_replace('vendor_contact', 'contact', $parts[0]);
$entity = "contact".substr($parts[1], -1); $entity = "contact".substr($parts[1], -1);
$custom_field_string = strlen($helper->makeCustomField($this->company->custom_fields, $entity)) > 1 ? $helper->makeCustomField($this->company->custom_fields, $entity) : ctrans("texts.{$parts[1]}"); $custom_field_string = strlen($helper->makeCustomField($this->company->custom_fields, $entity)) > 1 ? $helper->makeCustomField($this->company->custom_fields, $entity) : ctrans("texts.{$parts[1]}");
$header[] = ctrans("texts.{$parts[0]}") . " " . $custom_field_string; $header[] = ctrans("texts.{$parts[0]}") . " " . $custom_field_string;
} } elseif(count($parts) == 2 && in_array(substr($original_key, 0, -1), ['credit','quote','invoice','purchase_order','recurring_invoice','task'])) {
elseif(count($parts) == 2 && in_array(substr($original_key, 0, -1), ['credit','quote','invoice','purchase_order','recurring_invoice','task'])){ $custom_field_string = strlen($helper->makeCustomField($this->company->custom_fields, "product".substr($original_key, -1))) > 1 ? $helper->makeCustomField($this->company->custom_fields, "product".substr($original_key, -1)) : ctrans("texts.{$parts[1]}");
$custom_field_string = strlen($helper->makeCustomField($this->company->custom_fields, "product".substr($original_key,-1))) > 1 ? $helper->makeCustomField($this->company->custom_fields, "product".substr($original_key,-1)) : ctrans("texts.{$parts[1]}");
$header[] = ctrans("texts.{$parts[0]}") . " " . $custom_field_string; $header[] = ctrans("texts.{$parts[0]}") . " " . $custom_field_string;
} } else {
else{
$header[] = "{$prefix}" . ctrans("texts.{$key}"); $header[] = "{$prefix}" . ctrans("texts.{$key}");
} }
} } else {
else
{
$header[] = "{$prefix}" . ctrans("texts.{$key}"); $header[] = "{$prefix}" . ctrans("texts.{$key}");
} }
} }
@ -1104,7 +1133,7 @@ class BaseExport
$value = 'image'; $value = 'image';
} }
if($value == 'tax_id') { if($value == 'tax_id') {
$column_key = 'tax_category'; $column_key = 'tax_category';
$value = 'tax_category'; $value = 'tax_category';
} }
@ -1119,7 +1148,7 @@ class BaseExport
} }
return $clean_row; return $clean_row;
} }
public function processItemMetaData(array $row, $resource): array public function processItemMetaData(array $row, $resource): array
{ {
@ -1146,11 +1175,13 @@ class BaseExport
$column_key = $value; $column_key = $value;
if($value == 'type_id' || $value == 'item.type_id') if($value == 'type_id' || $value == 'item.type_id') {
$column_key = 'type'; $column_key = 'type';
}
if($value == 'tax_id' || $value == 'item.tax_id') if($value == 'tax_id' || $value == 'item.tax_id') {
$column_key = 'tax_category'; $column_key = 'tax_category';
}
$clean_row[$key]['entity'] = $report_keys[0]; $clean_row[$key]['entity'] = $report_keys[0];
$clean_row[$key]['id'] = $report_keys[1] ?? $report_keys[0]; $clean_row[$key]['id'] = $report_keys[1] ?? $report_keys[0];
@ -1162,6 +1193,6 @@ class BaseExport
} }
return $clean_row; return $clean_row;
} }
} }

View File

@ -11,16 +11,16 @@
namespace App\Export\CSV; namespace App\Export\CSV;
use App\Libraries\MultiDB;
use App\Models\Client;
use App\Models\Company;
use App\Transformers\ClientContactTransformer;
use App\Transformers\ClientTransformer;
use App\Utils\Ninja; use App\Utils\Ninja;
use App\Utils\Number; use App\Utils\Number;
use App\Models\Client;
use League\Csv\Writer;
use App\Models\Company;
use App\Libraries\MultiDB;
use Illuminate\Support\Facades\App;
use App\Transformers\ClientTransformer;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
use App\Transformers\ClientContactTransformer; use Illuminate\Support\Facades\App;
use League\Csv\Writer;
class ClientExport extends BaseExport class ClientExport extends BaseExport
{ {
@ -92,9 +92,9 @@ class ClientExport extends BaseExport
$headerdisplay = $this->buildHeader(); $headerdisplay = $this->buildHeader();
$header = collect($this->input['report_keys'])->map(function ($key, $value) use($headerdisplay){ $header = collect($this->input['report_keys'])->map(function ($key, $value) use ($headerdisplay) {
return ['identifier' => $key, 'display_value' => $headerdisplay[$value]]; return ['identifier' => $key, 'display_value' => $headerdisplay[$value]];
})->toArray(); })->toArray();
$report = $query->cursor() $report = $query->cursor()
->map(function ($client) { ->map(function ($client) {
@ -126,7 +126,7 @@ class ClientExport extends BaseExport
$query = $this->addDateRange($query); $query = $this->addDateRange($query);
return $query; return $query;
} }
@ -191,10 +191,11 @@ class ClientExport extends BaseExport
$clean_row[$key]['value'] = $row[$column_key]; $clean_row[$key]['value'] = $row[$column_key];
$clean_row[$key]['identifier'] = $value; $clean_row[$key]['identifier'] = $value;
if(in_array($clean_row[$key]['id'], ['paid_to_date', 'balance', 'credit_balance','payment_balance'])) if(in_array($clean_row[$key]['id'], ['paid_to_date', 'balance', 'credit_balance','payment_balance'])) {
$clean_row[$key]['display_value'] = Number::formatMoney($row[$column_key], $resource); $clean_row[$key]['display_value'] = Number::formatMoney($row[$column_key], $resource);
else } else {
$clean_row[$key]['display_value'] = $row[$column_key]; $clean_row[$key]['display_value'] = $row[$column_key];
}
} }

View File

@ -88,9 +88,9 @@ class ContactExport extends BaseExport
$headerdisplay = $this->buildHeader(); $headerdisplay = $this->buildHeader();
$header = collect($this->input['report_keys'])->map(function ($key, $value) use($headerdisplay){ $header = collect($this->input['report_keys'])->map(function ($key, $value) use ($headerdisplay) {
return ['identifier' => $key, 'display_value' => $headerdisplay[$value]]; return ['identifier' => $key, 'display_value' => $headerdisplay[$value]];
})->toArray(); })->toArray();
$report = $query->cursor() $report = $query->cursor()
->map(function ($contact) { ->map(function ($contact) {

View File

@ -11,15 +11,15 @@
namespace App\Export\CSV; namespace App\Export\CSV;
use App\Libraries\MultiDB;
use App\Models\Company;
use App\Models\Credit;
use App\Transformers\CreditTransformer;
use App\Utils\Ninja; use App\Utils\Ninja;
use App\Utils\Number; use App\Utils\Number;
use App\Models\Credit;
use League\Csv\Writer;
use App\Models\Company;
use App\Libraries\MultiDB;
use Illuminate\Support\Facades\App;
use App\Transformers\CreditTransformer;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\App;
use League\Csv\Writer;
class CreditExport extends BaseExport class CreditExport extends BaseExport
{ {
@ -43,9 +43,9 @@ class CreditExport extends BaseExport
$headerdisplay = $this->buildHeader(); $headerdisplay = $this->buildHeader();
$header = collect($this->input['report_keys'])->map(function ($key, $value) use($headerdisplay){ $header = collect($this->input['report_keys'])->map(function ($key, $value) use ($headerdisplay) {
return ['identifier' => $key, 'display_value' => $headerdisplay[$value]]; return ['identifier' => $key, 'display_value' => $headerdisplay[$value]];
})->toArray(); })->toArray();
$report = $query->cursor() $report = $query->cursor()
->map(function ($credit) { ->map(function ($credit) {
@ -70,10 +70,11 @@ class CreditExport extends BaseExport
$clean_row[$key]['value'] = $row[$column_key]; $clean_row[$key]['value'] = $row[$column_key];
$clean_row[$key]['identifier'] = $value; $clean_row[$key]['identifier'] = $value;
if(in_array($clean_row[$key]['id'], ['paid_to_date','total_taxes','amount', 'balance', 'partial', 'refunded', 'applied','unit_cost','cost','price'])) if(in_array($clean_row[$key]['id'], ['paid_to_date','total_taxes','amount', 'balance', 'partial', 'refunded', 'applied','unit_cost','cost','price'])) {
$clean_row[$key]['display_value'] = Number::formatMoney($row[$column_key], $resource->client); $clean_row[$key]['display_value'] = Number::formatMoney($row[$column_key], $resource->client);
else } else {
$clean_row[$key]['display_value'] = $row[$column_key]; $clean_row[$key]['display_value'] = $row[$column_key];
}
} }
@ -139,10 +140,9 @@ class CreditExport extends BaseExport
$entity[$keyval] = $transformed_credit[$credit_key]; $entity[$keyval] = $transformed_credit[$credit_key];
} elseif (isset($transformed_credit[$keyval])) { } elseif (isset($transformed_credit[$keyval])) {
$entity[$keyval] = $transformed_credit[$keyval]; $entity[$keyval] = $transformed_credit[$keyval];
} elseif(isset($transformed_credit[$searched_credit_key])){ } elseif(isset($transformed_credit[$searched_credit_key])) {
$entity[$keyval] = $transformed_credit[$searched_credit_key]; $entity[$keyval] = $transformed_credit[$searched_credit_key];
} } else {
else {
$entity[$keyval] = $this->resolveKey($keyval, $credit, $this->credit_transformer); $entity[$keyval] = $this->resolveKey($keyval, $credit, $this->credit_transformer);
} }

View File

@ -49,9 +49,9 @@ class DocumentExport extends BaseExport
$headerdisplay = $this->buildHeader(); $headerdisplay = $this->buildHeader();
$header = collect($this->input['report_keys'])->map(function ($key, $value) use($headerdisplay){ $header = collect($this->input['report_keys'])->map(function ($key, $value) use ($headerdisplay) {
return ['identifier' => $key, 'display_value' => $headerdisplay[$value]]; return ['identifier' => $key, 'display_value' => $headerdisplay[$value]];
})->toArray(); })->toArray();
$report = $query->cursor() $report = $query->cursor()
->map(function ($document) { ->map(function ($document) {

View File

@ -43,9 +43,9 @@ class ExpenseExport extends BaseExport
$headerdisplay = $this->buildHeader(); $headerdisplay = $this->buildHeader();
$header = collect($this->input['report_keys'])->map(function ($key, $value) use($headerdisplay){ $header = collect($this->input['report_keys'])->map(function ($key, $value) use ($headerdisplay) {
return ['identifier' => $key, 'display_value' => $headerdisplay[$value]]; return ['identifier' => $key, 'display_value' => $headerdisplay[$value]];
})->toArray(); })->toArray();
$report = $query->cursor() $report = $query->cursor()
->map(function ($resource) { ->map(function ($resource) {

View File

@ -11,16 +11,14 @@
namespace App\Export\CSV; namespace App\Export\CSV;
use App\Utils\Ninja; use App\Libraries\MultiDB;
use App\Utils\Number;
use League\Csv\Writer;
use App\Models\Company; use App\Models\Company;
use App\Models\Invoice; use App\Models\Invoice;
use App\Libraries\MultiDB;
use App\Export\CSV\BaseExport;
use Illuminate\Support\Facades\App;
use App\Transformers\InvoiceTransformer; use App\Transformers\InvoiceTransformer;
use App\Utils\Ninja;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\App;
use League\Csv\Writer;
class InvoiceExport extends BaseExport class InvoiceExport extends BaseExport
{ {
@ -74,9 +72,9 @@ class InvoiceExport extends BaseExport
$headerdisplay = $this->buildHeader(); $headerdisplay = $this->buildHeader();
$header = collect($this->input['report_keys'])->map(function ($key, $value) use($headerdisplay){ $header = collect($this->input['report_keys'])->map(function ($key, $value) use ($headerdisplay) {
return ['identifier' => $key, 'display_value' => $headerdisplay[$value]]; return ['identifier' => $key, 'display_value' => $headerdisplay[$value]];
})->toArray(); })->toArray();
$report = $query->cursor() $report = $query->cursor()
->map(function ($resource) { ->map(function ($resource) {

View File

@ -82,9 +82,9 @@ class InvoiceItemExport extends BaseExport
$headerdisplay = $this->buildHeader(); $headerdisplay = $this->buildHeader();
$header = collect($this->input['report_keys'])->map(function ($key, $value) use($headerdisplay){ $header = collect($this->input['report_keys'])->map(function ($key, $value) use ($headerdisplay) {
return ['identifier' => $key, 'display_value' => $headerdisplay[$value]]; return ['identifier' => $key, 'display_value' => $headerdisplay[$value]];
})->toArray(); })->toArray();
$query->cursor() $query->cursor()
@ -131,7 +131,7 @@ 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(array_intersect($this->input['report_keys'], $this->item_report_keys)) as $key) { //items iterator produces item array foreach (array_values(array_intersect($this->input['report_keys'], $this->item_report_keys)) as $key) { //items iterator produces item array
@ -139,16 +139,17 @@ class InvoiceItemExport extends BaseExport
$tmp_key = str_replace("item.", "", $key); $tmp_key = str_replace("item.", "", $key);
if($tmp_key == 'type_id') if($tmp_key == 'type_id') {
$tmp_key = 'type'; $tmp_key = 'type';
}
if($tmp_key == 'tax_id') if($tmp_key == 'tax_id') {
$tmp_key = 'tax_category'; $tmp_key = 'tax_category';
}
if (property_exists($item, $tmp_key)) { if (property_exists($item, $tmp_key)) {
$item_array[$key] = $item->{$tmp_key}; $item_array[$key] = $item->{$tmp_key};
} } else {
else {
$item_array[$key] = ''; $item_array[$key] = '';
} }
} }
@ -174,15 +175,15 @@ class InvoiceItemExport extends BaseExport
$parts = explode('.', $key); $parts = explode('.', $key);
if(is_array($parts) && $parts[0] == 'item') if(is_array($parts) && $parts[0] == 'item') {
continue; continue;
}
if (is_array($parts) && $parts[0] == 'invoice' && array_key_exists($parts[1], $transformed_invoice)) { if (is_array($parts) && $parts[0] == 'invoice' && array_key_exists($parts[1], $transformed_invoice)) {
$entity[$key] = $transformed_invoice[$parts[1]]; $entity[$key] = $transformed_invoice[$parts[1]];
}else if (array_key_exists($key, $transformed_invoice)) { } elseif (array_key_exists($key, $transformed_invoice)) {
$entity[$key] = $transformed_invoice[$key]; $entity[$key] = $transformed_invoice[$key];
} } else {
else {
$entity[$key] = $this->resolveKey($key, $invoice, $this->invoice_transformer); $entity[$key] = $this->resolveKey($key, $invoice, $this->invoice_transformer);
} }
} }

View File

@ -41,14 +41,14 @@ class ProductExport extends BaseExport
$headerdisplay = $this->buildHeader(); $headerdisplay = $this->buildHeader();
$header = collect($this->input['report_keys'])->map(function ($key, $value) use($headerdisplay){ $header = collect($this->input['report_keys'])->map(function ($key, $value) use ($headerdisplay) {
return ['identifier' => $key, 'display_value' => $headerdisplay[$value]]; return ['identifier' => $key, 'display_value' => $headerdisplay[$value]];
})->toArray(); })->toArray();
$report = $query->cursor() $report = $query->cursor()
->map(function ($resource) { ->map(function ($resource) {
$row = $this->buildRow($resource); $row = $this->buildRow($resource);
return $this->processMetaData($row, $resource); return $this->processMetaData($row, $resource);
})->toArray(); })->toArray();
return array_merge(['columns' => $header], $report); return array_merge(['columns' => $header], $report);

View File

@ -11,15 +11,14 @@
namespace App\Export\CSV; namespace App\Export\CSV;
use App\Utils\Ninja;
use App\Utils\Number;
use League\Csv\Writer;
use App\Models\Company;
use App\Libraries\MultiDB; use App\Libraries\MultiDB;
use App\Models\Company;
use App\Models\PurchaseOrder; use App\Models\PurchaseOrder;
use Illuminate\Support\Facades\App;
use App\Transformers\PurchaseOrderTransformer; use App\Transformers\PurchaseOrderTransformer;
use App\Utils\Ninja;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\App;
use League\Csv\Writer;
class PurchaseOrderExport extends BaseExport class PurchaseOrderExport extends BaseExport
{ {
@ -116,9 +115,9 @@ class PurchaseOrderExport extends BaseExport
$headerdisplay = $this->buildHeader(); $headerdisplay = $this->buildHeader();
$header = collect($this->input['report_keys'])->map(function ($key, $value) use($headerdisplay){ $header = collect($this->input['report_keys'])->map(function ($key, $value) use ($headerdisplay) {
return ['identifier' => $key, 'display_value' => $headerdisplay[$value]]; return ['identifier' => $key, 'display_value' => $headerdisplay[$value]];
})->toArray(); })->toArray();
$report = $query->cursor() $report = $query->cursor()
->map(function ($resource) { ->map(function ($resource) {

View File

@ -11,14 +11,14 @@
namespace App\Export\CSV; namespace App\Export\CSV;
use App\Utils\Ninja;
use League\Csv\Writer;
use App\Models\Company;
use App\Libraries\MultiDB; use App\Libraries\MultiDB;
use App\Models\Company;
use App\Models\PurchaseOrder; use App\Models\PurchaseOrder;
use Illuminate\Support\Facades\App;
use Illuminate\Database\Eloquent\Builder;
use App\Transformers\PurchaseOrderTransformer; use App\Transformers\PurchaseOrderTransformer;
use App\Utils\Ninja;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\App;
use League\Csv\Writer;
class PurchaseOrderItemExport extends BaseExport class PurchaseOrderItemExport extends BaseExport
{ {
@ -74,21 +74,21 @@ class PurchaseOrderItemExport extends BaseExport
$headerdisplay = $this->buildHeader(); $headerdisplay = $this->buildHeader();
$header = collect($this->input['report_keys'])->map(function ($key, $value) use($headerdisplay){ $header = collect($this->input['report_keys'])->map(function ($key, $value) use ($headerdisplay) {
return ['identifier' => $key, 'display_value' => $headerdisplay[$value]]; return ['identifier' => $key, 'display_value' => $headerdisplay[$value]];
})->toArray(); })->toArray();
$query->cursor() $query->cursor()
->each(function ($resource) { ->each(function ($resource) {
$this->iterateItems($resource); $this->iterateItems($resource);
foreach($this->storage_array as $row) { foreach($this->storage_array as $row) {
$this->storage_item_array[] = $this->processItemMetaData($row, $resource); $this->storage_item_array[] = $this->processItemMetaData($row, $resource);
} }
$this->storage_array = []; $this->storage_array = [];
}); });
return array_merge(['columns' => $header], $this->storage_item_array); return array_merge(['columns' => $header], $this->storage_item_array);
} }

View File

@ -76,23 +76,23 @@ class QuoteItemExport extends BaseExport
$headerdisplay = $this->buildHeader(); $headerdisplay = $this->buildHeader();
$header = collect($this->input['report_keys'])->map(function ($key, $value) use($headerdisplay){ $header = collect($this->input['report_keys'])->map(function ($key, $value) use ($headerdisplay) {
return ['identifier' => $key, 'display_value' => $headerdisplay[$value]]; return ['identifier' => $key, 'display_value' => $headerdisplay[$value]];
})->toArray(); })->toArray();
$query->cursor() $query->cursor()
->each(function ($resource) { ->each(function ($resource) {
$this->iterateItems($resource); $this->iterateItems($resource);
foreach($this->storage_array as $row) { foreach($this->storage_array as $row) {
$this->storage_item_array[] = $this->processItemMetaData($row, $resource); $this->storage_item_array[] = $this->processItemMetaData($row, $resource);
} }
$this->storage_array = []; $this->storage_array = [];
}); });
return array_merge(['columns' => $header], $this->storage_item_array); return array_merge(['columns' => $header], $this->storage_item_array);
} }
@ -103,7 +103,7 @@ class QuoteItemExport extends BaseExport
//load the CSV document from a string //load the CSV document from a string
$this->csv = Writer::createFromString(); $this->csv = Writer::createFromString();
$query = $this->init(); $query = $this->init();
//insert the header //insert the header
$this->csv->insertOne($this->buildHeader()); $this->csv->insertOne($this->buildHeader());
@ -127,7 +127,7 @@ class QuoteItemExport extends BaseExport
$transformed_items = []; $transformed_items = [];
foreach ($quote->line_items as $item) { foreach ($quote->line_items as $item) {
$item_array = []; $item_array = [];
foreach (array_values(array_intersect($this->input['report_keys'], $this->item_report_keys)) as $key) { //items iterator produces item array foreach (array_values(array_intersect($this->input['report_keys'], $this->item_report_keys)) as $key) { //items iterator produces item array
@ -135,16 +135,17 @@ class QuoteItemExport extends BaseExport
$tmp_key = str_replace("item.", "", $key); $tmp_key = str_replace("item.", "", $key);
if($tmp_key == 'type_id') if($tmp_key == 'type_id') {
$tmp_key = 'type'; $tmp_key = 'type';
}
if($tmp_key == 'tax_id') if($tmp_key == 'tax_id') {
$tmp_key = 'tax_category'; $tmp_key = 'tax_category';
}
if (property_exists($item, $tmp_key)) { if (property_exists($item, $tmp_key)) {
$item_array[$key] = $item->{$tmp_key}; $item_array[$key] = $item->{$tmp_key};
} } else {
else {
$item_array[$key] = ''; $item_array[$key] = '';
} }
} }

View File

@ -88,9 +88,9 @@ class RecurringInvoiceExport extends BaseExport
$headerdisplay = $this->buildHeader(); $headerdisplay = $this->buildHeader();
$header = collect($this->input['report_keys'])->map(function ($key, $value) use($headerdisplay){ $header = collect($this->input['report_keys'])->map(function ($key, $value) use ($headerdisplay) {
return ['identifier' => $key, 'display_value' => $headerdisplay[$value]]; return ['identifier' => $key, 'display_value' => $headerdisplay[$value]];
})->toArray(); })->toArray();
$report = $query->cursor() $report = $query->cursor()
->map(function ($resource) { ->map(function ($resource) {

View File

@ -101,17 +101,16 @@ class TaskExport extends BaseExport
$headerdisplay = $this->buildHeader(); $headerdisplay = $this->buildHeader();
$header = collect($this->input['report_keys'])->map(function ($key, $value) use($headerdisplay){ $header = collect($this->input['report_keys'])->map(function ($key, $value) use ($headerdisplay) {
return ['identifier' => $key, 'display_value' => $headerdisplay[$value]]; return ['identifier' => $key, 'display_value' => $headerdisplay[$value]];
})->toArray(); })->toArray();
$query->cursor() $query->cursor()
->each(function ($resource) { ->each(function ($resource) {
$this->buildRow($resource); $this->buildRow($resource);
foreach($this->storage_array as $row) foreach($this->storage_array as $row) {
{
$this->storage_item_array[] = $this->processMetaData($row, $resource); $this->storage_item_array[] = $this->processMetaData($row, $resource);
} }

View File

@ -12,8 +12,8 @@
namespace App\Export\CSV; namespace App\Export\CSV;
use App\Libraries\MultiDB; use App\Libraries\MultiDB;
use App\Models\Vendor;
use App\Models\Company; use App\Models\Company;
use App\Models\Vendor;
use App\Transformers\VendorContactTransformer; use App\Transformers\VendorContactTransformer;
use App\Transformers\VendorTransformer; use App\Transformers\VendorTransformer;
use App\Utils\Ninja; use App\Utils\Ninja;
@ -73,9 +73,9 @@ class VendorExport extends BaseExport
$headerdisplay = $this->buildHeader(); $headerdisplay = $this->buildHeader();
$header = collect($this->input['report_keys'])->map(function ($key, $value) use($headerdisplay){ $header = collect($this->input['report_keys'])->map(function ($key, $value) use ($headerdisplay) {
return ['identifier' => $key, 'display_value' => $headerdisplay[$value]]; return ['identifier' => $key, 'display_value' => $headerdisplay[$value]];
})->toArray(); })->toArray();
$report = $query->cursor() $report = $query->cursor()
->map(function ($resource) { ->map(function ($resource) {

View File

@ -11,13 +11,13 @@
namespace App\Factory; namespace App\Factory;
use App\Utils\Ninja;
use App\Models\Company;
use App\Libraries\MultiDB;
use App\Utils\Traits\MakesHash;
use App\DataMapper\Tax\TaxModel;
use App\DataMapper\CompanySettings;
use App\DataMapper\ClientRegistrationFields; use App\DataMapper\ClientRegistrationFields;
use App\DataMapper\CompanySettings;
use App\DataMapper\Tax\TaxModel;
use App\Libraries\MultiDB;
use App\Models\Company;
use App\Utils\Ninja;
use App\Utils\Traits\MakesHash;
class CompanyFactory class CompanyFactory
{ {

View File

@ -63,7 +63,7 @@ class InvoiceItemFactory
$item->line_total = $item->quantity * $item->cost; $item->line_total = $item->quantity * $item->cost;
$item->is_amount_discount = true; $item->is_amount_discount = true;
$item->discount = $faker->numberBetween(1, 10); $item->discount = $faker->numberBetween(1, 10);
$item->notes = str_replace(['"',"'"],['',""], $faker->realText(20)); $item->notes = str_replace(['"',"'"], ['',""], $faker->realText(20));
$item->product_key = $faker->word(); $item->product_key = $faker->word();
// $item->custom_value1 = $faker->realText(10); // $item->custom_value1 = $faker->realText(10);
// $item->custom_value2 = $faker->realText(10); // $item->custom_value2 = $faker->realText(10);

View File

@ -248,10 +248,10 @@ class RecurringExpenseToExpenseFactory
$final_date = now()->addMonths($output-now()->month); $final_date = now()->addMonths($output-now()->month);
$output = \sprintf( $output = \sprintf(
'%s %s', '%s %s',
$final_date->translatedFormat('F'), $final_date->translatedFormat('F'),
$final_date->year, $final_date->year,
); );
} }
$value = preg_replace( $value = preg_replace(

View File

@ -27,7 +27,7 @@ class UserFactory
$user->last_login = now(); $user->last_login = now();
$user->failed_logins = 0; $user->failed_logins = 0;
$user->signature = ''; $user->signature = '';
$user->theme_id = 0; $user->theme_id = 0;
$user->user_logged_in_notification = true; $user->user_logged_in_notification = true;
return $user; return $user;

View File

@ -53,19 +53,19 @@ class BankTransactionFilters extends QueryFilters
} }
/** /**
* Filter based on client status. * Filter based on client status.
* *
* Statuses we need to handle * Statuses we need to handle
* - all * - all
* - unmatched * - unmatched
* - matched * - matched
* - converted * - converted
* - deposits * - deposits
* - withdrawals * - withdrawals
* *
* @return Builder * @return Builder
*/ */
public function client_status(string $value = ''): Builder public function client_status(string $value = ''): Builder
{ {
if (strlen($value) == 0) { if (strlen($value) == 0) {

View File

@ -144,7 +144,7 @@ class CreditFilters extends QueryFilters
return $this->builder->company(); return $this->builder->company();
} }
// return $this->builder->whereCompanyId(auth()->user()->company()->id); // return $this->builder->whereCompanyId(auth()->user()->company()->id);
} }
/** /**

View File

@ -77,7 +77,7 @@ class DesignFilters extends QueryFilters
/** @var \App\Models\User $user */ /** @var \App\Models\User $user */
$user = auth()->user(); $user = auth()->user();
return $this->builder->where(function ($query) use($user){ return $this->builder->where(function ($query) use ($user) {
$query->where('company_id', $user->company()->id)->orWhere('company_id', null)->orderBy('id', 'asc'); $query->where('company_id', $user->company()->id)->orWhere('company_id', null)->orderBy('id', 'asc');
}); });
} }

View File

@ -40,8 +40,8 @@ class ExpenseFilters extends QueryFilters
->orWhere('custom_value3', 'like', '%'.$filter.'%') ->orWhere('custom_value3', 'like', '%'.$filter.'%')
->orWhere('custom_value4', 'like', '%'.$filter.'%') ->orWhere('custom_value4', 'like', '%'.$filter.'%')
->orWhereHas('category', function ($q) use ($filter) { ->orWhereHas('category', function ($q) use ($filter) {
$q->where('name', 'like', '%'.$filter.'%'); $q->where('name', 'like', '%'.$filter.'%');
}); });
}); });
} }
@ -125,9 +125,9 @@ class ExpenseFilters extends QueryFilters
$search_key = $split[0] == 'client' ? 'client_id' : 'project_id'; $search_key = $split[0] == 'client' ? 'client_id' : 'project_id';
return $this->builder->whereHas('invoice', function ($query) use ($search_key, $split){ return $this->builder->whereHas('invoice', function ($query) use ($search_key, $split) {
$query->where($search_key, $this->decodePrimaryKey($split[1])) $query->where($search_key, $this->decodePrimaryKey($split[1]))
->whereIn('status_id', [\App\Models\Invoice::STATUS_DRAFT, \App\Models\Invoice::STATUS_SENT, \App\Models\Invoice::STATUS_PARTIAL]); ->whereIn('status_id', [\App\Models\Invoice::STATUS_DRAFT, \App\Models\Invoice::STATUS_SENT, \App\Models\Invoice::STATUS_PARTIAL]);
}); });
} }

View File

@ -11,14 +11,13 @@
namespace App\Filters; namespace App\Filters;
use RuntimeException;
use App\Models\Client; use App\Models\Client;
use App\Models\Invoice; use App\Models\Invoice;
use App\Filters\QueryFilters;
use InvalidArgumentException;
use Illuminate\Support\Carbon;
use App\Utils\Traits\MakesHash; use App\Utils\Traits\MakesHash;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Carbon;
use InvalidArgumentException;
use RuntimeException;
/** /**
* InvoiceFilters. * InvoiceFilters.
@ -241,15 +240,13 @@ class InvoiceFilters extends QueryFilters
return $this->builder; return $this->builder;
} }
try{ try {
$start_date = Carbon::parse($parts[1]); $start_date = Carbon::parse($parts[1]);
$end_date = Carbon::parse($parts[2]); $end_date = Carbon::parse($parts[2]);
return $this->builder->whereBetween($parts[0], [$start_date, $end_date]); return $this->builder->whereBetween($parts[0], [$start_date, $end_date]);
} } catch(\Exception $e) {
catch(\Exception $e){
return $this->builder; return $this->builder;
} }

View File

@ -12,9 +12,8 @@
namespace App\Filters; namespace App\Filters;
use App\Models\Payment; use App\Models\Payment;
use Illuminate\Support\Carbon;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
use Illuminate\Contracts\Database\Eloquent\Builder as EloquentBuilder; use Illuminate\Support\Carbon;
/** /**
* PaymentFilters. * PaymentFilters.
@ -37,39 +36,39 @@ class PaymentFilters extends QueryFilters
return $this->builder->where(function ($query) use ($filter) { return $this->builder->where(function ($query) use ($filter) {
$query->where('amount', 'like', '%'.$filter.'%') $query->where('amount', 'like', '%'.$filter.'%')
->orWhere('date', 'like', '%'.$filter.'%') ->orWhere('date', 'like', '%'.$filter.'%')
->orWhere('number','like', '%'.$filter.'%') ->orWhere('number', 'like', '%'.$filter.'%')
->orWhere('transaction_reference', 'like', '%'.$filter.'%') ->orWhere('transaction_reference', 'like', '%'.$filter.'%')
->orWhere('custom_value1', 'like', '%'.$filter.'%') ->orWhere('custom_value1', 'like', '%'.$filter.'%')
->orWhere('custom_value2', 'like', '%'.$filter.'%') ->orWhere('custom_value2', 'like', '%'.$filter.'%')
->orWhere('custom_value3', 'like', '%'.$filter.'%') ->orWhere('custom_value3', 'like', '%'.$filter.'%')
->orWhere('custom_value4', 'like', '%'.$filter.'%') ->orWhere('custom_value4', 'like', '%'.$filter.'%')
->orWhereHas('client', function ($q) use ($filter) { ->orWhereHas('client', function ($q) use ($filter) {
$q->where('name', 'like', '%'.$filter.'%'); $q->where('name', 'like', '%'.$filter.'%');
}) })
->orWhereHas('client.contacts', function ($q) use ($filter) { ->orWhereHas('client.contacts', function ($q) use ($filter) {
$q->where('first_name', 'like', '%'.$filter.'%') $q->where('first_name', 'like', '%'.$filter.'%')
->orWhere('last_name', 'like', '%'.$filter.'%') ->orWhere('last_name', 'like', '%'.$filter.'%')
->orWhere('email', 'like', '%'.$filter.'%'); ->orWhere('email', 'like', '%'.$filter.'%');
}); });
}); });
} }
/** /**
* Filter based on client status. * Filter based on client status.
* *
* Statuses we need to handle * Statuses we need to handle
* - all * - all
* - pending * - pending
* - cancelled * - cancelled
* - failed * - failed
* - completed * - completed
* - partially refunded * - partially refunded
* - refunded * - refunded
* *
* @param string $value The payment status as seen by the client * @param string $value The payment status as seen by the client
* @return Builder * @return Builder
*/ */
public function client_status(string $value = ''): Builder public function client_status(string $value = ''): Builder
{ {
if (strlen($value) == 0) { if (strlen($value) == 0) {
@ -190,15 +189,13 @@ class PaymentFilters extends QueryFilters
return $this->builder; return $this->builder;
} }
try{ try {
$start_date = Carbon::parse($parts[1]); $start_date = Carbon::parse($parts[1]);
$end_date = Carbon::parse($parts[2]); $end_date = Carbon::parse($parts[2]);
return $this->builder->whereBetween($parts[0], [$start_date, $end_date]); return $this->builder->whereBetween($parts[0], [$start_date, $end_date]);
} } catch(\Exception $e) {
catch(\Exception $e){
return $this->builder; return $this->builder;
} }

View File

@ -145,7 +145,7 @@ class PurchaseOrderFilters extends QueryFilters
return $this->builder->company(); return $this->builder->company();
} }
// return $this->builder->whereCompanyId(auth()->user()->company()->id); // return $this->builder->whereCompanyId(auth()->user()->company()->id);
} }
/** /**

View File

@ -42,10 +42,10 @@ class QuoteFilters extends QueryFilters
$q->where('name', 'like', '%'.$filter.'%'); $q->where('name', 'like', '%'.$filter.'%');
}) })
->orWhereHas('client.contacts', function ($q) use ($filter) { ->orWhereHas('client.contacts', function ($q) use ($filter) {
$q->where('first_name', 'like', '%'.$filter.'%') $q->where('first_name', 'like', '%'.$filter.'%')
->orWhere('last_name', 'like', '%'.$filter.'%') ->orWhere('last_name', 'like', '%'.$filter.'%')
->orWhere('email', 'like', '%'.$filter.'%'); ->orWhere('email', 'like', '%'.$filter.'%');
}); });
}); });
} }
@ -146,7 +146,7 @@ class QuoteFilters extends QueryFilters
return $this->builder; return $this->builder;
} }
if($sort_col[0] == 'client_id'){ if($sort_col[0] == 'client_id') {
return $this->builder->orderBy(\App\Models\Client::select('name') return $this->builder->orderBy(\App\Models\Client::select('name')
->whereColumn('clients.id', 'quotes.client_id'), $sort_col[1]); ->whereColumn('clients.id', 'quotes.client_id'), $sort_col[1]);

View File

@ -34,20 +34,20 @@ class RecurringInvoiceFilters extends QueryFilters
} }
return $this->builder->where(function ($query) use ($filter) { return $this->builder->where(function ($query) use ($filter) {
$query->where('date', 'like', '%'.$filter.'%') $query->where('date', 'like', '%'.$filter.'%')
->orWhere('amount', 'like', '%'.$filter.'%') ->orWhere('amount', 'like', '%'.$filter.'%')
->orWhere('custom_value1', 'like', '%'.$filter.'%') ->orWhere('custom_value1', 'like', '%'.$filter.'%')
->orWhere('custom_value2', 'like', '%'.$filter.'%') ->orWhere('custom_value2', 'like', '%'.$filter.'%')
->orWhere('custom_value3', 'like', '%'.$filter.'%') ->orWhere('custom_value3', 'like', '%'.$filter.'%')
->orWhere('custom_value4', 'like', '%'.$filter.'%') ->orWhere('custom_value4', 'like', '%'.$filter.'%')
->orWhereHas('client', function ($q) use ($filter) { ->orWhereHas('client', function ($q) use ($filter) {
$q->where('name', 'like', '%'.$filter.'%'); $q->where('name', 'like', '%'.$filter.'%');
}) })
->orWhereHas('client.contacts', function ($q) use ($filter) { ->orWhereHas('client.contacts', function ($q) use ($filter) {
$q->where('first_name', 'like', '%'.$filter.'%') $q->where('first_name', 'like', '%'.$filter.'%')
->orWhere('last_name', 'like', '%'.$filter.'%') ->orWhere('last_name', 'like', '%'.$filter.'%')
->orWhere('email', 'like', '%'.$filter.'%'); ->orWhere('email', 'like', '%'.$filter.'%');
}); });
}); });
} }

View File

@ -41,16 +41,16 @@ class TaskFilters extends QueryFilters
->orWhere('custom_value3', 'like', '%'.$filter.'%') ->orWhere('custom_value3', 'like', '%'.$filter.'%')
->orWhere('custom_value4', 'like', '%'.$filter.'%') ->orWhere('custom_value4', 'like', '%'.$filter.'%')
->orWhereHas('project', function ($q) use ($filter) { ->orWhereHas('project', function ($q) use ($filter) {
$q->where('name', 'like', '%'.$filter.'%'); $q->where('name', 'like', '%'.$filter.'%');
}) })
->orWhereHas('client', function ($q) use ($filter) { ->orWhereHas('client', function ($q) use ($filter) {
$q->where('name', 'like', '%'.$filter.'%'); $q->where('name', 'like', '%'.$filter.'%');
}) })
->orWhereHas('client.contacts', function ($q) use ($filter) { ->orWhereHas('client.contacts', function ($q) use ($filter) {
$q->where('first_name', 'like', '%'.$filter.'%') $q->where('first_name', 'like', '%'.$filter.'%')
->orWhere('last_name', 'like', '%'.$filter.'%') ->orWhere('last_name', 'like', '%'.$filter.'%')
->orWhere('email', 'like', '%'.$filter.'%'); ->orWhere('email', 'like', '%'.$filter.'%');
}); });
}); });
} }
@ -136,7 +136,7 @@ class TaskFilters extends QueryFilters
$status_parameters = explode(',', $value); $status_parameters = explode(',', $value);
if(count($status_parameters) >= 1){ if(count($status_parameters) >= 1) {
$this->builder->where(function ($query) use ($status_parameters) { $this->builder->where(function ($query) use ($status_parameters) {
$query->whereIn('status_id', $this->transformKeys($status_parameters))->whereNull('invoice_id'); $query->whereIn('status_id', $this->transformKeys($status_parameters))->whereNull('invoice_id');

View File

@ -11,10 +11,9 @@
namespace App\Helpers\Bank\Yodlee\DTO; namespace App\Helpers\Bank\Yodlee\DTO;
use Spatie\LaravelData\Data;
use Spatie\LaravelData\Attributes\MapInputName;
use Spatie\LaravelData\Attributes\MapOutputName;
use Illuminate\Support\Collection; use Illuminate\Support\Collection;
use Spatie\LaravelData\Attributes\MapInputName;
use Spatie\LaravelData\Data;
/** /**
* [ * [
@ -72,40 +71,40 @@ use Illuminate\Support\Collection;
*/ */
class AccountSummary extends Data class AccountSummary extends Data
{ {
public ?int $id; public ?int $id;
#[MapInputName('CONTAINER')] #[MapInputName('CONTAINER')]
public ?string $account_type = ''; public ?string $account_type = '';
#[MapInputName('accountName')] #[MapInputName('accountName')]
public ?string $account_name = ''; public ?string $account_name = '';
#[MapInputName('accountStatus')] #[MapInputName('accountStatus')]
public ?string $account_status = ''; public ?string $account_status = '';
#[MapInputName('accountNumber')] #[MapInputName('accountNumber')]
public ?string $account_number = ''; public ?string $account_number = '';
#[MapInputName('providerAccountId')] #[MapInputName('providerAccountId')]
public int $provider_account_id; public int $provider_account_id;
#[MapInputName('providerId')] #[MapInputName('providerId')]
public ?string $provider_id = ''; public ?string $provider_id = '';
#[MapInputName('providerName')] #[MapInputName('providerName')]
public ?string $provider_name = ''; public ?string $provider_name = '';
public ?string $nickname = ''; public ?string $nickname = '';
public ?float $current_balance = 0; public ?float $current_balance = 0;
public ?string $account_currency = ''; public ?string $account_currency = '';
public static function prepareForPipeline(Collection $properties) : Collection public static function prepareForPipeline(Collection $properties) : Collection
{ {
$properties->put('current_balance', $properties['currentBalance']['amount'] ?? 0); $properties->put('current_balance', $properties['currentBalance']['amount'] ?? 0);
$properties->put('account_currency', $properties['currentBalance']['currency'] ?? 0); $properties->put('account_currency', $properties['currentBalance']['currency'] ?? 0);
return $properties; return $properties;
} }
} }

View File

@ -88,20 +88,19 @@ class AccountTransformer implements AccountTransformerInterface
if(property_exists($account, 'currentBalance')) { if(property_exists($account, 'currentBalance')) {
$current_balance = $account->currentBalance->amount ?? 0; $current_balance = $account->currentBalance->amount ?? 0;
$account_currency = $account->currentBalance->currency ?? ''; $account_currency = $account->currentBalance->currency ?? '';
} } elseif(property_exists($account, 'balance')) {
elseif(property_exists($account, 'balance')){
$current_balance = $account->balance->amount ?? 0; $current_balance = $account->balance->amount ?? 0;
$account_currency = $account->balance->currency ?? ''; $account_currency = $account->balance->currency ?? '';
} }
$account_status = $account->accountStatus; $account_status = $account->accountStatus;
if(property_exists($account, 'dataset')){ if(property_exists($account, 'dataset')) {
$dataset = $account->dataset[0]; $dataset = $account->dataset[0];
$status = false; $status = false;
$update = false; $update = false;
match($dataset->additionalStatus ?? ''){ match($dataset->additionalStatus ?? '') {
'LOGIN_IN_PROGRESS' => $status = 'Data retrieval in progress.', 'LOGIN_IN_PROGRESS' => $status = 'Data retrieval in progress.',
'USER_INPUT_REQUIRED' => $status = 'Please reconnect your account, authentication required.', 'USER_INPUT_REQUIRED' => $status = 'Please reconnect your account, authentication required.',
'LOGIN_SUCCESS' => $status = 'Data retrieval in progress', 'LOGIN_SUCCESS' => $status = 'Data retrieval in progress',
@ -113,24 +112,23 @@ class AccountTransformer implements AccountTransformerInterface
'PARTIAL_DATA_RETRIEVED' => $status = 'Partial data update failed.', 'PARTIAL_DATA_RETRIEVED' => $status = 'Partial data update failed.',
'PARTIAL_DATA_RETRIEVED_REM_SCHED' => $status = 'Partial data update failed.', 'PARTIAL_DATA_RETRIEVED_REM_SCHED' => $status = 'Partial data update failed.',
'SUCCESS' => $status = 'All accounts added or updated successfully.', 'SUCCESS' => $status = 'All accounts added or updated successfully.',
default => $status = false default => $status = false
}; };
if($status){ if($status) {
$account_status = $status; $account_status = $status;
} }
match($dataset->updateEligibility ?? ''){ match($dataset->updateEligibility ?? '') {
'ALLOW_UPDATE' => $update = 'Account connection stable.', 'ALLOW_UPDATE' => $update = 'Account connection stable.',
'ALLOW_UPDATE_WITH_CREDENTIALS' => $update = 'Please reconnect your account with updated credentials.', 'ALLOW_UPDATE_WITH_CREDENTIALS' => $update = 'Please reconnect your account with updated credentials.',
'DISALLOW_UPDATE' => $update = 'Update not available due to technical issues.', 'DISALLOW_UPDATE' => $update = 'Update not available due to technical issues.',
default => $update = false, default => $update = false,
}; };
if($status && $update){ if($status && $update) {
$account_status = $status . ' - ' . $update; $account_status = $status . ' - ' . $update;
} } elseif($update) {
elseif($update){
$account_status = $update; $account_status = $update;
} }

View File

@ -127,12 +127,14 @@ class IncomeTransformer implements BankRevenueInterface
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;
}
//some object do no store amounts ignore these //some object do no store amounts ignore these
if(!property_exists($transaction, 'amount')) if(!property_exists($transaction, 'amount')) {
continue; continue;
}
$data[] = $this->transformTransaction($transaction); $data[] = $this->transformTransaction($transaction);
} }

View File

@ -300,7 +300,7 @@ class Yodlee
/** /**
* updateEligibility * updateEligibility
* *
* ALLOW_UPDATE * ALLOW_UPDATE
* ALLOW_UPDATE_WITH_CREDENTIALS * ALLOW_UPDATE_WITH_CREDENTIALS
* DISALLOW_UPDATE * DISALLOW_UPDATE
@ -308,7 +308,7 @@ class Yodlee
/** /**
* additionalStatus * additionalStatus
* *
* LOGIN_IN_PROGRESS * LOGIN_IN_PROGRESS
* DATA_RETRIEVAL_IN_PROGRESS * DATA_RETRIEVAL_IN_PROGRESS
* ACCT_SUMMARY_RECEIVED * ACCT_SUMMARY_RECEIVED
@ -339,7 +339,7 @@ class Yodlee
* CONSENT_REVOKED * CONSENT_REVOKED
* INCORRECT_OAUTH_TOKEN * INCORRECT_OAUTH_TOKEN
* MIGRATION_IN_PROGRESS * MIGRATION_IN_PROGRESS
*/ */
/** /**
* IN_PROGRESS LOGIN_IN_PROGRESS Provider login is in progress. * IN_PROGRESS LOGIN_IN_PROGRESS Provider login is in progress.
@ -356,12 +356,12 @@ class Yodlee
* SUCCESS All accounts under the provider was added or updated successfully. * SUCCESS All accounts under the provider was added or updated successfully.
*/ */
/** /**
* updateEligibility * updateEligibility
* *
* ALLOW_UPDATE The status indicates that the account is eligible for the next update and applies to both MFA and non-MFA accounts. For MFA-based accounts, the user may have to provide the MFA details during account refresh. * ALLOW_UPDATE The status indicates that the account is eligible for the next update and applies to both MFA and non-MFA accounts. For MFA-based accounts, the user may have to provide the MFA details during account refresh.
* ALLOW_UPDATE_WITH_CREDENTIALS The status indicates updating or refreshing the account by directing the user to edit the provided credentials. * ALLOW_UPDATE_WITH_CREDENTIALS The status indicates updating or refreshing the account by directing the user to edit the provided credentials.
* DISALLOW_UPDATE The status indicates the account is not eligible for the update or refresh process due to a site issue or a technical error. * DISALLOW_UPDATE The status indicates the account is not eligible for the update or refresh process due to a site issue or a technical error.
*/ */
} }

View File

@ -64,7 +64,7 @@ class EpcQrGenerator
} catch(\Exception $e) { } catch(\Exception $e) {
nlog("EPC QR failure => ".$e->getMessage()); nlog("EPC QR failure => ".$e->getMessage());
return ''; return '';
} catch( InvalidArgumentException $e) { } catch(InvalidArgumentException $e) {
nlog("EPC QR failure => ".$e->getMessage()); nlog("EPC QR failure => ".$e->getMessage());
return ''; return '';
} }

View File

@ -11,16 +11,16 @@
namespace App\Helpers\Invoice; namespace App\Helpers\Invoice;
use App\Models\Quote; use App\DataMapper\BaseSettings;
use App\DataMapper\InvoiceItem;
use App\DataMapper\Tax\RuleInterface;
use App\Models\Client; use App\Models\Client;
use App\Models\Credit; use App\Models\Credit;
use App\Models\Invoice; use App\Models\Invoice;
use App\Models\PurchaseOrder; use App\Models\PurchaseOrder;
use App\Models\RecurringQuote; use App\Models\Quote;
use App\DataMapper\InvoiceItem;
use App\DataMapper\BaseSettings;
use App\Models\RecurringInvoice; use App\Models\RecurringInvoice;
use App\DataMapper\Tax\RuleInterface; use App\Models\RecurringQuote;
use App\Utils\Traits\NumberFormatter; use App\Utils\Traits\NumberFormatter;
class InvoiceItemSum class InvoiceItemSum
@ -125,7 +125,7 @@ class InvoiceItemSum
private RuleInterface $rule; private RuleInterface $rule;
public function __construct( RecurringInvoice | Invoice | Quote | Credit | PurchaseOrder | RecurringQuote $invoice) public function __construct(RecurringInvoice | Invoice | Quote | Credit | PurchaseOrder | RecurringQuote $invoice)
{ {
$this->tax_collection = collect([]); $this->tax_collection = collect([]);
@ -175,14 +175,15 @@ class InvoiceItemSum
return $this; return $this;
} }
if (in_array($this->client->company->country()->iso_3166_2, $this->tax_jurisdictions) ) { //only calculate for supported tax jurisdictions if (in_array($this->client->company->country()->iso_3166_2, $this->tax_jurisdictions)) { //only calculate for supported tax jurisdictions
$class = "App\DataMapper\Tax\\".$this->client->company->country()->iso_3166_2."\\Rule"; $class = "App\DataMapper\Tax\\".$this->client->company->country()->iso_3166_2."\\Rule";
$this->rule = new $class(); $this->rule = new $class();
if($this->rule->regionWithNoTaxCoverage($this->client->country->iso_3166_2)) if($this->rule->regionWithNoTaxCoverage($this->client->country->iso_3166_2)) {
return $this; return $this;
}
$this->rule $this->rule
->setEntity($this->invoice) ->setEntity($this->invoice)
@ -399,7 +400,7 @@ class InvoiceItemSum
$item_tax = 0; $item_tax = 0;
//$amount = $this->item->line_total - ($this->item->line_total * ($this->invoice->discount / $this->sub_total)); //$amount = $this->item->line_total - ($this->item->line_total * ($this->invoice->discount / $this->sub_total));
$amount = ($this->sub_total > 0) ? $this->item->line_total - ($this->invoice->discount * ( $this->item->line_total / $this->sub_total)) : 0; $amount = ($this->sub_total > 0) ? $this->item->line_total - ($this->invoice->discount * ($this->item->line_total / $this->sub_total)) : 0;
$item_tax_rate1_total = $this->calcAmountLineTax($this->item->tax_rate1, $amount); $item_tax_rate1_total = $this->calcAmountLineTax($this->item->tax_rate1, $amount);

View File

@ -11,14 +11,14 @@
namespace App\Helpers\Invoice; namespace App\Helpers\Invoice;
use App\Models\Quote; use App\DataMapper\Tax\RuleInterface;
use App\Models\Client; use App\Models\Client;
use App\Models\Credit; use App\Models\Credit;
use App\Models\Invoice; use App\Models\Invoice;
use App\Models\PurchaseOrder; use App\Models\PurchaseOrder;
use App\Models\RecurringQuote; use App\Models\Quote;
use App\Models\RecurringInvoice; use App\Models\RecurringInvoice;
use App\DataMapper\Tax\RuleInterface; use App\Models\RecurringQuote;
use App\Utils\Traits\NumberFormatter; use App\Utils\Traits\NumberFormatter;
class InvoiceItemSumInclusive class InvoiceItemSumInclusive
@ -404,14 +404,15 @@ class InvoiceItemSumInclusive
return $this; return $this;
} }
if (in_array($this->client->company->country()->iso_3166_2, $this->tax_jurisdictions) ) { //only calculate for supported tax jurisdictions if (in_array($this->client->company->country()->iso_3166_2, $this->tax_jurisdictions)) { //only calculate for supported tax jurisdictions
$class = "App\DataMapper\Tax\\".$this->client->company->country()->iso_3166_2."\\Rule"; $class = "App\DataMapper\Tax\\".$this->client->company->country()->iso_3166_2."\\Rule";
$this->rule = new $class(); $this->rule = new $class();
if($this->rule->regionWithNoTaxCoverage($this->client->country->iso_3166_2)) if($this->rule->regionWithNoTaxCoverage($this->client->country->iso_3166_2)) {
return $this; return $this;
}
$this->rule $this->rule
->setEntity($this->invoice) ->setEntity($this->invoice)

View File

@ -11,15 +11,15 @@
namespace App\Helpers\Invoice; namespace App\Helpers\Invoice;
use App\Models\Quote;
use App\Utils\Number;
use App\Models\Credit; use App\Models\Credit;
use App\Models\Invoice; use App\Models\Invoice;
use App\Models\PurchaseOrder; use App\Models\PurchaseOrder;
use App\Models\RecurringQuote; use App\Models\Quote;
use App\Models\RecurringInvoice; use App\Models\RecurringInvoice;
use Illuminate\Support\Collection; use App\Models\RecurringQuote;
use App\Utils\Number;
use App\Utils\Traits\NumberFormatter; use App\Utils\Traits\NumberFormatter;
use Illuminate\Support\Collection;
class InvoiceSum class InvoiceSum
{ {

View File

@ -11,15 +11,14 @@
namespace App\Helpers\Invoice; namespace App\Helpers\Invoice;
use App\Models\Quote;
use App\Models\Credit; use App\Models\Credit;
use App\Models\Invoice; use App\Models\Invoice;
use App\Models\PurchaseOrder; use App\Models\PurchaseOrder;
use App\Models\RecurringQuote; use App\Models\Quote;
use App\Models\RecurringInvoice; use App\Models\RecurringInvoice;
use Illuminate\Support\Collection; use App\Models\RecurringQuote;
use App\Utils\Traits\NumberFormatter; use App\Utils\Traits\NumberFormatter;
use App\Helpers\Invoice\InvoiceItemSumInclusive; use Illuminate\Support\Collection;
class InvoiceSumInclusive class InvoiceSumInclusive
{ {

View File

@ -57,7 +57,7 @@ class SwissQrGenerator
// - with specified amount // - with specified amount
// - with human-readable additional information // - with human-readable additional information
// - using your QR-IBAN // - using your QR-IBAN
// //
// Likely the most common use-case in the business world. // Likely the most common use-case in the business world.
// Create a new instance of QrBill, containing default headers with fixed values // Create a new instance of QrBill, containing default headers with fixed values
@ -83,7 +83,7 @@ class SwissQrGenerator
// Add debtor information // Add debtor information
// Who has to pay the invoice? This part is optional. // Who has to pay the invoice? This part is optional.
// //
// Notice how you can use two different styles of addresses: CombinedAddress or StructuredAddress // Notice how you can use two different styles of addresses: CombinedAddress or StructuredAddress
// They are interchangeable for creditor as well as debtor. // They are interchangeable for creditor as well as debtor.
$qrBill->setUltimateDebtor( $qrBill->setUltimateDebtor(
@ -121,7 +121,7 @@ class SwissQrGenerator
$array = str_split($tempInvoiceNumber); $array = str_split($tempInvoiceNumber);
foreach ($array as $char) { foreach ($array as $char) {
if (is_numeric($char)) { if (is_numeric($char)) {
// //
} else { } else {
if ($char) { if ($char) {
$char = strtolower($char); $char = strtolower($char);

View File

@ -11,17 +11,17 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use App\Models\Account;
use App\Libraries\MultiDB;
use App\Utils\TruthSource;
use App\Models\CompanyUser;
use Illuminate\Http\Response;
use App\Jobs\Account\CreateAccount;
use App\Transformers\AccountTransformer;
use App\Transformers\CompanyUserTransformer;
use Illuminate\Foundation\Bus\DispatchesJobs;
use App\Http\Requests\Account\CreateAccountRequest; use App\Http\Requests\Account\CreateAccountRequest;
use App\Http\Requests\Account\UpdateAccountRequest; use App\Http\Requests\Account\UpdateAccountRequest;
use App\Jobs\Account\CreateAccount;
use App\Libraries\MultiDB;
use App\Models\Account;
use App\Models\CompanyUser;
use App\Transformers\AccountTransformer;
use App\Transformers\CompanyUserTransformer;
use App\Utils\TruthSource;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Http\Response;
class AccountController extends BaseController class AccountController extends BaseController
{ {

View File

@ -11,19 +11,19 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use stdClass;
use App\Utils\Ninja;
use App\Models\Activity;
use Illuminate\Http\Request;
use App\Utils\Traits\MakesHash;
use App\Utils\PhantomJS\Phantom;
use App\Utils\HostedPDF\NinjaPdf;
use App\Utils\Traits\Pdf\PdfMaker;
use App\Utils\Traits\Pdf\PageNumbering;
use Illuminate\Support\Facades\Storage;
use App\Transformers\ActivityTransformer;
use App\Http\Requests\Activity\ShowActivityRequest;
use App\Http\Requests\Activity\DownloadHistoricalEntityRequest; use App\Http\Requests\Activity\DownloadHistoricalEntityRequest;
use App\Http\Requests\Activity\ShowActivityRequest;
use App\Models\Activity;
use App\Transformers\ActivityTransformer;
use App\Utils\HostedPDF\NinjaPdf;
use App\Utils\Ninja;
use App\Utils\PhantomJS\Phantom;
use App\Utils\Traits\MakesHash;
use App\Utils\Traits\Pdf\PageNumbering;
use App\Utils\Traits\Pdf\PdfMaker;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use stdClass;
class ActivityController extends BaseController class ActivityController extends BaseController
{ {

View File

@ -11,13 +11,13 @@
namespace App\Http\Controllers\Auth; namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Libraries\MultiDB;
use App\Models\Account; use App\Models\Account;
use App\Models\Company; use App\Models\Company;
use App\Libraries\MultiDB;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Password;
use Illuminate\Foundation\Auth\SendsPasswordResetEmails; use Illuminate\Foundation\Auth\SendsPasswordResetEmails;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Password;
class ForgotPasswordController extends Controller class ForgotPasswordController extends Controller
{ {
@ -90,7 +90,7 @@ class ForgotPasswordController extends Controller
$account = Account::find($account_id); $account = Account::find($account_id);
} }
$is_react = request()->has('react') ? true : false; $is_react = request()->has('react') ? true : false;
return $this->render('auth.passwords.request', ['root' => 'themes', 'account' => $account, 'is_react' => $is_react]); return $this->render('auth.passwords.request', ['root' => 'themes', 'account' => $account, 'is_react' => $is_react]);
} }

View File

@ -25,4 +25,3 @@ class PasswordTimeoutController extends Controller
return $cached ? response()->json(['message' => 'Password is valid'], 200) : response()->json(['message' => 'Invalid Password'], 412); return $cached ? response()->json(['message' => 'Password is valid'], 200) : response()->json(['message' => 'Invalid Password'], 412);
} }
} }

View File

@ -111,8 +111,9 @@ class ResetPasswordController extends Controller
{ {
auth()->logout(); auth()->logout();
if(request()->has('react') || request()->hasHeader('X-React')) if(request()->has('react') || request()->hasHeader('X-React')) {
return redirect(config('ninja.react_url').'/#/login'); return redirect(config('ninja.react_url').'/#/login');
}
return redirect('/'); return redirect('/');
} }
@ -130,11 +131,11 @@ class ResetPasswordController extends Controller
return new JsonResponse(['message' => trans($response)], 200); return new JsonResponse(['message' => trans($response)], 200);
} }
if($request->hasHeader('X-REACT') || $request->has('react')){ if($request->hasHeader('X-REACT') || $request->has('react')) {
return redirect(config('ninja.react_url').'/#/login'); return redirect(config('ninja.react_url').'/#/login');
} else {
return redirect('/#/login');
} }
else
return redirect('/#/login');
return redirect($this->redirectPath()) return redirect($this->redirectPath())
->with('status', trans($response)); ->with('status', trans($response));

View File

@ -12,13 +12,13 @@
namespace App\Http\Controllers\Bank; namespace App\Http\Controllers\Bank;
use App\Helpers\Bank\Yodlee\DTO\AccountSummary; use App\Helpers\Bank\Yodlee\DTO\AccountSummary;
use Illuminate\Http\Request;
use App\Models\BankIntegration;
use App\Helpers\Bank\Yodlee\Yodlee; use App\Helpers\Bank\Yodlee\Yodlee;
use App\Http\Controllers\BaseController; use App\Http\Controllers\BaseController;
use App\Jobs\Bank\ProcessBankTransactions;
use App\Http\Requests\Yodlee\YodleeAuthRequest;
use App\Http\Requests\Yodlee\YodleeAdminRequest; use App\Http\Requests\Yodlee\YodleeAdminRequest;
use App\Http\Requests\Yodlee\YodleeAuthRequest;
use App\Jobs\Bank\ProcessBankTransactions;
use App\Models\BankIntegration;
use Illuminate\Http\Request;
class YodleeController extends BaseController class YodleeController extends BaseController
{ {
@ -100,69 +100,69 @@ class YodleeController extends BaseController
} }
/** /**
* Process Yodlee Refresh Webhook. * Process Yodlee Refresh Webhook.
* *
* *
* @OA\Post( * @OA\Post(
* path="/api/v1/yodlee/refresh", * path="/api/v1/yodlee/refresh",
* operationId="yodleeRefreshWebhook", * operationId="yodleeRefreshWebhook",
* tags={"yodlee"}, * tags={"yodlee"},
* summary="Processing webhooks from Yodlee", * summary="Processing webhooks from Yodlee",
* description="Notifies the system when a data point can be refreshed", * description="Notifies the system when a data point can be refreshed",
* @OA\Parameter(ref="#/components/parameters/X-API-TOKEN"), * @OA\Parameter(ref="#/components/parameters/X-API-TOKEN"),
* @OA\Parameter(ref="#/components/parameters/X-Requested-With"), * @OA\Parameter(ref="#/components/parameters/X-Requested-With"),
* @OA\Parameter(ref="#/components/parameters/include"), * @OA\Parameter(ref="#/components/parameters/include"),
* @OA\Response( * @OA\Response(
* response=200, * response=200,
* description="", * description="",
* @OA\Header(header="X-MINIMUM-CLIENT-VERSION", ref="#/components/headers/X-MINIMUM-CLIENT-VERSION"), * @OA\Header(header="X-MINIMUM-CLIENT-VERSION", ref="#/components/headers/X-MINIMUM-CLIENT-VERSION"),
* @OA\Header(header="X-RateLimit-Remaining", ref="#/components/headers/X-RateLimit-Remaining"), * @OA\Header(header="X-RateLimit-Remaining", ref="#/components/headers/X-RateLimit-Remaining"),
* @OA\Header(header="X-RateLimit-Limit", ref="#/components/headers/X-RateLimit-Limit"), * @OA\Header(header="X-RateLimit-Limit", ref="#/components/headers/X-RateLimit-Limit"),
* @OA\JsonContent(ref="#/components/schemas/Credit"), * @OA\JsonContent(ref="#/components/schemas/Credit"),
* ), * ),
* @OA\Response( * @OA\Response(
* response=422, * response=422,
* description="Validation error", * description="Validation error",
* @OA\JsonContent(ref="#/components/schemas/ValidationError"), * @OA\JsonContent(ref="#/components/schemas/ValidationError"),
* *
* ), * ),
* @OA\Response( * @OA\Response(
* response="default", * response="default",
* description="Unexpected Error", * description="Unexpected Error",
* @OA\JsonContent(ref="#/components/schemas/Error"), * @OA\JsonContent(ref="#/components/schemas/Error"),
* ), * ),
* ) * )
*/ */
/* /*
{ {
"event":{ "event":{
"info":"REFRESH.PROCESS_COMPLETED", "info":"REFRESH.PROCESS_COMPLETED",
"loginName":"fri21", "loginName":"fri21",
"data":{ "data":{
"providerAccount":[ "providerAccount":[
{ {
"id":10995860, "id":10995860,
"providerId":16441, "providerId":16441,
"isManual":false, "isManual":false,
"createdDate":"2017-12-22T05:47:35Z", "createdDate":"2017-12-22T05:47:35Z",
"aggregationSource":"USER", "aggregationSource":"USER",
"status":"SUCCESS", "status":"SUCCESS",
"requestId":"NSyMGo+R4dktywIu3hBIkc3PgWA=", "requestId":"NSyMGo+R4dktywIu3hBIkc3PgWA=",
"dataset":[ "dataset":[
{ {
"name":"BASIC_AGG_DATA", "name":"BASIC_AGG_DATA",
"additionalStatus":"AVAILABLE_DATA_RETRIEVED", "additionalStatus":"AVAILABLE_DATA_RETRIEVED",
"updateEligibility":"ALLOW_UPDATE", "updateEligibility":"ALLOW_UPDATE",
"lastUpdated":"2017-12-22T05:48:16Z", "lastUpdated":"2017-12-22T05:48:16Z",
"lastUpdateAttempt":"2017-12-22T05:48:16Z" "lastUpdateAttempt":"2017-12-22T05:48:16Z"
} }
] ]
} }
] ]
}
} }
}
}*/ }*/
public function refreshWebhook(Request $request) public function refreshWebhook(Request $request)
{ {
@ -177,28 +177,28 @@ class YodleeController extends BaseController
// return response()->json(['message' => 'Unauthorized'], 403); // return response()->json(['message' => 'Unauthorized'], 403);
} }
/* /*
{ {
"event":{ "event":{
"notificationId":"63c73475-4db5-49ef-8553-8303337ca7c3", "notificationId":"63c73475-4db5-49ef-8553-8303337ca7c3",
"info":"LATEST_BALANCE_UPDATES", "info":"LATEST_BALANCE_UPDATES",
"loginName":"user1", "loginName":"user1",
"data":{ "data":{
"providerAccountId":658552, "providerAccountId":658552,
"latestBalanceEvent":[ "latestBalanceEvent":[
{ {
"accountId":12345, "accountId":12345,
"status":"SUCCESS" "status":"SUCCESS"
}, },
{ {
"accountId":12346, "accountId":12346,
"status":"FAILED" "status":"FAILED"
} }
] ]
} }
} }
} }
*/ */
public function balanceWebhook(Request $request) public function balanceWebhook(Request $request)
{ {
nlog("yodlee refresh"); nlog("yodlee refresh");
@ -211,29 +211,29 @@ class YodleeController extends BaseController
// return response()->json(['message' => 'Unauthorized'], 403); // return response()->json(['message' => 'Unauthorized'], 403);
} }
/* /*
{ {
"event":{ "event":{
"data":[ "data":[
{ {
"autoRefresh":{ "autoRefresh":{
"additionalStatus":"SCHEDULED", "additionalStatus":"SCHEDULED",
"status":"ENABLED" "status":"ENABLED"
}, },
"accountIds":[ "accountIds":[
1112645899, 1112645899,
1112645898 1112645898
], ],
"loginName":"YSL1555332811628", "loginName":"YSL1555332811628",
"providerAccountId":11381459 "providerAccountId":11381459
} }
], ],
"notificationTime":"2019-06-14T04:49:39Z", "notificationTime":"2019-06-14T04:49:39Z",
"notificationId":"4e672150-156048777", "notificationId":"4e672150-156048777",
"info":"AUTO_REFRESH_UPDATES" "info":"AUTO_REFRESH_UPDATES"
} }
} }
*/ */
public function refreshUpdatesWebhook(Request $request) public function refreshUpdatesWebhook(Request $request)
{ {
//notifies a user if there are problems with yodlee accessing the data //notifies a user if there are problems with yodlee accessing the data
@ -248,27 +248,27 @@ class YodleeController extends BaseController
} }
/* /*
"event": { "event": {
"notificationId": "64b7ed1a-1530523285", "notificationId": "64b7ed1a-1530523285",
"info": "DATA_UPDATES.USER_DATA", "info": "DATA_UPDATES.USER_DATA",
"data": { "data": {
"userCount": 1, "userCount": 1,
"fromDate": "2017-11-10T10:18:44Z", "fromDate": "2017-11-10T10:18:44Z",
"toDate": "2017-11-10T11:18:43Z", "toDate": "2017-11-10T11:18:43Z",
"userData": [{ "userData": [{
"user": { "user": {
"loginName": "YSL1484052178554" "loginName": "YSL1484052178554"
}, },
"links": [{ "links": [{
"methodType": "GET", "methodType": "GET",
"rel": "getUserData", "rel": "getUserData",
"href": "dataExtracts/userData?fromDate=2017-11-10T10:18:44Z&toDate=2017-11-10T11:18:43Z&loginName=YSL1484052178554" "href": "dataExtracts/userData?fromDate=2017-11-10T10:18:44Z&toDate=2017-11-10T11:18:43Z&loginName=YSL1484052178554"
}]
}] }]
}] }
} }
} */
*/
public function dataUpdatesWebhook(Request $request) public function dataUpdatesWebhook(Request $request)
{ {
//this is the main hook we use for notifications //this is the main hook we use for notifications
@ -292,8 +292,9 @@ class YodleeController extends BaseController
->where('account_id', $account_number) ->where('account_id', $account_number)
->exists(); ->exists();
if(!$bank_integration) if(!$bank_integration) {
return response()->json(['message' => 'Account does not exist.'], 400); return response()->json(['message' => 'Account does not exist.'], 400);
}
$yodlee = new Yodlee($user->account->bank_integration_account_id); $yodlee = new Yodlee($user->account->bank_integration_account_id);

View File

@ -11,26 +11,25 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Models\BankIntegration;
use App\Utils\Traits\MakesHash;
use Illuminate\Http\JsonResponse;
use App\Helpers\Bank\Yodlee\Yodlee;
use Illuminate\Support\Facades\Cache;
use App\Factory\BankIntegrationFactory; use App\Factory\BankIntegrationFactory;
use App\Filters\BankIntegrationFilters; use App\Filters\BankIntegrationFilters;
use App\Jobs\Bank\ProcessBankTransactions; use App\Helpers\Bank\Yodlee\Yodlee;
use App\Repositories\BankIntegrationRepository; use App\Http\Requests\BankIntegration\AdminBankIntegrationRequest;
use App\Transformers\BankIntegrationTransformer;
use App\Http\Requests\BankIntegration\BulkBankIntegrationRequest; use App\Http\Requests\BankIntegration\BulkBankIntegrationRequest;
use App\Http\Requests\BankIntegration\CreateBankIntegrationRequest;
use App\Http\Requests\BankIntegration\DestroyBankIntegrationRequest;
use App\Http\Requests\BankIntegration\EditBankIntegrationRequest; use App\Http\Requests\BankIntegration\EditBankIntegrationRequest;
use App\Http\Requests\BankIntegration\ShowBankIntegrationRequest; use App\Http\Requests\BankIntegration\ShowBankIntegrationRequest;
use App\Http\Requests\BankIntegration\AdminBankIntegrationRequest;
use App\Http\Requests\BankIntegration\StoreBankIntegrationRequest; use App\Http\Requests\BankIntegration\StoreBankIntegrationRequest;
use App\Http\Requests\BankIntegration\CreateBankIntegrationRequest;
use App\Http\Requests\BankIntegration\UpdateBankIntegrationRequest; use App\Http\Requests\BankIntegration\UpdateBankIntegrationRequest;
use App\Http\Requests\BankIntegration\DestroyBankIntegrationRequest; use App\Jobs\Bank\ProcessBankTransactions;
use App\Models\BankIntegration;
use App\Repositories\BankIntegrationRepository;
use App\Transformers\BankIntegrationTransformer;
use App\Utils\Traits\MakesHash;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Cache;
class BankIntegrationController extends BaseController class BankIntegrationController extends BaseController
{ {
@ -109,7 +108,7 @@ class BankIntegrationController extends BaseController
* @param CreateBankIntegrationRequest $request * @param CreateBankIntegrationRequest $request
* @return Response * @return Response
* *
* *
*/ */
public function create(CreateBankIntegrationRequest $request) public function create(CreateBankIntegrationRequest $request)
{ {
@ -210,12 +209,11 @@ class BankIntegrationController extends BaseController
$accounts = $yodlee->getAccounts(); $accounts = $yodlee->getAccounts();
foreach ($accounts as $account) { foreach ($accounts as $account) {
if ($bi = BankIntegration::withTrashed()->where('bank_account_id', $account['id'])->where('company_id', $user->company()->id)->first()){ if ($bi = BankIntegration::withTrashed()->where('bank_account_id', $account['id'])->where('company_id', $user->company()->id)->first()) {
$bi->balance = $account['current_balance']; $bi->balance = $account['current_balance'];
$bi->currency = $account['account_currency']; $bi->currency = $account['account_currency'];
$bi->save(); $bi->save();
} } else {
else {
$bank_integration = new BankIntegration(); $bank_integration = new BankIntegration();
$bank_integration->company_id = $user->company()->id; $bank_integration->company_id = $user->company()->id;
$bank_integration->account_id = $user->account_id; $bank_integration->account_id = $user->account_id;
@ -293,7 +291,7 @@ class BankIntegrationController extends BaseController
/** @var \App\Models\User $user */ /** @var \App\Models\User $user */
$user = auth()->user(); $user = auth()->user();
$user->account->bank_integrations->each(function ($bank_integration) use ($user){ $user->account->bank_integrations->each(function ($bank_integration) use ($user) {
(new ProcessBankTransactions($user->account->bank_integration_account_id, $bank_integration))->handle(); (new ProcessBankTransactions($user->account->bank_integration_account_id, $bank_integration))->handle();
}); });

View File

@ -11,20 +11,20 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use App\Utils\Traits\MakesHash;
use App\Models\BankTransactionRule;
use App\Factory\BankTransactionRuleFactory; use App\Factory\BankTransactionRuleFactory;
use App\Filters\BankTransactionRuleFilters; use App\Filters\BankTransactionRuleFilters;
use App\Repositories\BankTransactionRuleRepository;
use App\Transformers\BankTransactionRuleTransformer;
use App\Http\Requests\BankTransactionRule\BulkBankTransactionRuleRequest; use App\Http\Requests\BankTransactionRule\BulkBankTransactionRuleRequest;
use App\Http\Requests\BankTransactionRule\CreateBankTransactionRuleRequest;
use App\Http\Requests\BankTransactionRule\DestroyBankTransactionRuleRequest;
use App\Http\Requests\BankTransactionRule\EditBankTransactionRuleRequest; use App\Http\Requests\BankTransactionRule\EditBankTransactionRuleRequest;
use App\Http\Requests\BankTransactionRule\ShowBankTransactionRuleRequest; use App\Http\Requests\BankTransactionRule\ShowBankTransactionRuleRequest;
use App\Http\Requests\BankTransactionRule\StoreBankTransactionRuleRequest; use App\Http\Requests\BankTransactionRule\StoreBankTransactionRuleRequest;
use App\Http\Requests\BankTransactionRule\CreateBankTransactionRuleRequest;
use App\Http\Requests\BankTransactionRule\UpdateBankTransactionRuleRequest; use App\Http\Requests\BankTransactionRule\UpdateBankTransactionRuleRequest;
use App\Http\Requests\BankTransactionRule\DestroyBankTransactionRuleRequest; use App\Models\BankTransactionRule;
use App\Repositories\BankTransactionRuleRepository;
use App\Services\Bank\BankMatchingService; use App\Services\Bank\BankMatchingService;
use App\Transformers\BankTransactionRuleTransformer;
use App\Utils\Traits\MakesHash;
class BankTransactionRuleController extends BaseController class BankTransactionRuleController extends BaseController
{ {

View File

@ -531,7 +531,7 @@ class BaseController extends Controller
$paginator = $query->paginate($limit); $paginator = $query->paginate($limit);
/** @phpstan-ignore-next-line **/ /** @phpstan-ignore-next-line **/
$query = $paginator->getCollection(); $query = $paginator->getCollection();
$resource = new Collection($query, $transformer, $this->entity_type); $resource = new Collection($query, $transformer, $this->entity_type);
@ -889,7 +889,7 @@ class BaseController extends Controller
$resource = new Collection($query, $transformer, $this->entity_type); $resource = new Collection($query, $transformer, $this->entity_type);
$resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator));
} }
// else { // else {
// $resource = new Collection($query, $transformer, $this->entity_type); // $resource = new Collection($query, $transformer, $this->entity_type);
@ -924,10 +924,9 @@ class BaseController extends Controller
if ($this->entity_type == BankIntegration::class && !$user->isSuperUser() && $user->hasIntersectPermissions(['create_bank_transaction','edit_bank_transaction','view_bank_transaction'])) { if ($this->entity_type == BankIntegration::class && !$user->isSuperUser() && $user->hasIntersectPermissions(['create_bank_transaction','edit_bank_transaction','view_bank_transaction'])) {
$query->exclude(["balance"]); $query->exclude(["balance"]);
} //allows us to selective display bank integrations back to the user if they can view / create bank transactions but without the bank balance being present in the response } //allows us to selective display bank integrations back to the user if they can view / create bank transactions but without the bank balance being present in the response
elseif($this->entity_type == TaxRate::class && $user->hasIntersectPermissions(['create_invoice','edit_invoice','create_quote','edit_quote','create_purchase_order','edit_purchase_order'])){ elseif($this->entity_type == TaxRate::class && $user->hasIntersectPermissions(['create_invoice','edit_invoice','create_quote','edit_quote','create_purchase_order','edit_purchase_order'])) {
// need to show tax rates if the user has the ability to create documents. // need to show tax rates if the user has the ability to create documents.
} } else {
else {
$query->where('user_id', '=', $user->id); $query->where('user_id', '=', $user->id);
} }
} elseif (in_array($this->entity_type, [Design::class, GroupSetting::class, PaymentTerm::class, TaskStatus::class])) { } elseif (in_array($this->entity_type, [Design::class, GroupSetting::class, PaymentTerm::class, TaskStatus::class])) {

View File

@ -11,36 +11,36 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use App\Utils\Ninja;
use App\Models\Client;
use App\Models\Account;
use App\Models\Company;
use App\Models\SystemLog;
use Postmark\PostmarkClient;
use Illuminate\Http\Response;
use App\Factory\ClientFactory;
use App\Filters\ClientFilters;
use App\Utils\Traits\MakesHash;
use App\Utils\Traits\Uploadable;
use App\Utils\Traits\BulkOptions;
use App\Jobs\Client\UpdateTaxData;
use App\Utils\Traits\SavesDocuments;
use App\Repositories\ClientRepository;
use App\Events\Client\ClientWasCreated; use App\Events\Client\ClientWasCreated;
use App\Events\Client\ClientWasUpdated; use App\Events\Client\ClientWasUpdated;
use App\Transformers\ClientTransformer; use App\Factory\ClientFactory;
use Illuminate\Support\Facades\Storage; use App\Filters\ClientFilters;
use App\Http\Requests\Client\BulkClientRequest; use App\Http\Requests\Client\BulkClientRequest;
use App\Http\Requests\Client\EditClientRequest;
use App\Http\Requests\Client\ShowClientRequest;
use App\Http\Requests\Client\PurgeClientRequest;
use App\Http\Requests\Client\StoreClientRequest;
use App\Http\Requests\Client\CreateClientRequest; use App\Http\Requests\Client\CreateClientRequest;
use App\Http\Requests\Client\DestroyClientRequest;
use App\Http\Requests\Client\EditClientRequest;
use App\Http\Requests\Client\PurgeClientRequest;
use App\Http\Requests\Client\ReactivateClientEmailRequest;
use App\Http\Requests\Client\ShowClientRequest;
use App\Http\Requests\Client\StoreClientRequest;
use App\Http\Requests\Client\UpdateClientRequest; use App\Http\Requests\Client\UpdateClientRequest;
use App\Http\Requests\Client\UploadClientRequest; use App\Http\Requests\Client\UploadClientRequest;
use App\Http\Requests\Client\DestroyClientRequest; use App\Jobs\Client\UpdateTaxData;
use App\Http\Requests\Client\ReactivateClientEmailRequest;
use App\Jobs\PostMark\ProcessPostmarkWebhook; use App\Jobs\PostMark\ProcessPostmarkWebhook;
use App\Models\Account;
use App\Models\Client;
use App\Models\Company;
use App\Models\SystemLog;
use App\Repositories\ClientRepository;
use App\Transformers\ClientTransformer;
use App\Utils\Ninja;
use App\Utils\Traits\BulkOptions;
use App\Utils\Traits\MakesHash;
use App\Utils\Traits\SavesDocuments;
use App\Utils\Traits\Uploadable;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Storage;
use Postmark\PostmarkClient;
/** /**
* Class ClientController. * Class ClientController.
@ -74,10 +74,10 @@ class ClientController extends BaseController
} }
/** /**
* *
* @param ClientFilters $filters * @param ClientFilters $filters
* @return Response * @return Response
* *
*/ */
public function index(ClientFilters $filters) public function index(ClientFilters $filters)
{ {
@ -275,15 +275,15 @@ class ClientController extends BaseController
//todo add an event here using the client name as reference for purge event //todo add an event here using the client name as reference for purge event
} }
/** /**
* Update the specified resource in storage. * Update the specified resource in storage.
* *
* @param PurgeClientRequest $request * @param PurgeClientRequest $request
* @param Client $client * @param Client $client
* @param string $mergeable_client * @param string $mergeable_client
* @return \Illuminate\Http\JsonResponse * @return \Illuminate\Http\JsonResponse
* *
*/ */
public function merge(PurgeClientRequest $request, Client $client, string $mergeable_client) public function merge(PurgeClientRequest $request, Client $client, string $mergeable_client)
{ {
@ -313,8 +313,9 @@ class ClientController extends BaseController
*/ */
public function updateTaxData(PurgeClientRequest $request, Client $client) public function updateTaxData(PurgeClientRequest $request, Client $client)
{ {
if($client->company->account->isPaid()) if($client->company->account->isPaid()) {
(new UpdateTaxData($client, $client->company))->handle(); (new UpdateTaxData($client, $client->company))->handle();
}
return $this->itemResponse($client->fresh()); return $this->itemResponse($client->fresh());
} }
@ -331,8 +332,8 @@ class ClientController extends BaseController
/** @var \App\Models\User $user */ /** @var \App\Models\User $user */
$user = auth()->user(); $user = auth()->user();
if(stripos($bounce_id, '-') !== false){ if(stripos($bounce_id, '-') !== false) {
$log = $log =
SystemLog::query() SystemLog::query()
->where('company_id', $user->company()->id) ->where('company_id', $user->company()->id)
->where('type_id', SystemLog::TYPE_WEBHOOK_RESPONSE) ->where('type_id', SystemLog::TYPE_WEBHOOK_RESPONSE)
@ -343,16 +344,16 @@ class ClientController extends BaseController
$resolved_bounce_id = false; $resolved_bounce_id = false;
if($log && ($log?->log['ID'] ?? false)){ if($log && ($log?->log['ID'] ?? false)) {
$resolved_bounce_id = $log->log['ID'] ?? false; $resolved_bounce_id = $log->log['ID'] ?? false;
} }
if(!$resolved_bounce_id){ if(!$resolved_bounce_id) {
$ppwebhook = new ProcessPostmarkWebhook([]); $ppwebhook = new ProcessPostmarkWebhook([]);
$resolved_bounce_id = $ppwebhook->getBounceId($bounce_id); $resolved_bounce_id = $ppwebhook->getBounceId($bounce_id);
} }
if(!$resolved_bounce_id){ if(!$resolved_bounce_id) {
return response()->json(['message' => 'Bounce ID not found'], 400); return response()->json(['message' => 'Bounce ID not found'], 400);
} }
@ -367,8 +368,7 @@ class ClientController extends BaseController
return response()->json(['message' => 'Success'], 200); return response()->json(['message' => 'Success'], 200);
} } catch(\Exception $e) {
catch(\Exception $e){
return response()->json(['message' => $e->getMessage(), 400]); return response()->json(['message' => $e->getMessage(), 400]);

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