1
0
mirror of https://github.com/invoiceninja/invoiceninja.git synced 2024-11-10 13:12:50 +01:00

Merge pull request #9648 from turbo124/v5-develop

Static Analysis + Cache refactor
This commit is contained in:
David Bomba 2024-06-18 10:29:04 +10:00 committed by GitHub
commit 4adc9322d6
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
111 changed files with 948 additions and 1064 deletions

View File

@ -31,11 +31,11 @@ class QuoteExport extends BaseExport
private Decorator $decorator;
private array $decorate_keys = [
'client',
'currency',
'invoice',
];
// private array $decorate_keys = [
// 'client',
// 'currency',
// 'invoice',
// ];
public function __construct(Company $company, array $input)
{

View File

@ -31,7 +31,7 @@ class TaskExport extends BaseExport
public string $date_key = 'created_at';
private string $date_format = 'YYYY-MM-DD';
private string $date_format = 'Y-m-d';
public Writer $csv;
@ -180,13 +180,7 @@ class TaskExport extends BaseExport
$logs = json_decode($task->time_log, 1);
$date_format_default = 'Y-m-d';
$date_format = DateFormat::find($task->company->settings->date_format_id);
if ($date_format) {
$date_format_default = $date_format->format;
}
$date_format_default = $this->date_format;
foreach ($logs as $key => $item) {
if (in_array('task.start_date', $this->input['report_keys']) || in_array('start_date', $this->input['report_keys'])) {
@ -236,7 +230,7 @@ class TaskExport extends BaseExport
*/
protected function addTaskStatusFilter(Builder $query, string $status): Builder
{
/** @var array $status_parameters */
$status_parameters = explode(',', $status);
if (in_array('all', $status_parameters) || count($status_parameters) == 0) {

View File

@ -171,16 +171,16 @@ class VendorExport extends BaseExport
return $entity;
}
private function calculateStatus($vendor)
{
if ($vendor->is_deleted) {
return ctrans('texts.deleted');
}
// private function calculateStatus($vendor)
// {
// if ($vendor->is_deleted) {
// return ctrans('texts.deleted');
// }
if ($vendor->deleted_at) {
return ctrans('texts.archived');
}
// if ($vendor->deleted_at) {
// return ctrans('texts.archived');
// }
return ctrans('texts.active');
}
// return ctrans('texts.active');
// }
}

View File

@ -82,11 +82,15 @@ class RecurringExpenseToExpenseFactory
} else {
$locale = $recurring_expense->company->locale();
$date_formats = Cache::get('date_formats');
//@deprecated
// $date_formats = Cache::get('date_formats');
$date_format = $date_formats->filter(function ($item) use ($recurring_expense) {
/** @var \Illuminate\Support\Collection<\App\Models\DateFormat> */
$date_formats = app('date_formats');
$date_format = $date_formats->first(function ($item) use ($recurring_expense) {
return $item->id == $recurring_expense->company->settings->date_format_id;
})->first()->format;
})->format;
}
Carbon::setLocale($locale);
@ -144,7 +148,7 @@ class RecurringExpenseToExpenseFactory
continue;
}
if (Str::contains($match, '|')) {
// if (Str::contains($match, '|')) {
$parts = explode('|', $match); // [ '[MONTH', 'MONTH+2]' ]
$left = substr($parts[0], 1); // 'MONTH'
@ -182,7 +186,7 @@ class RecurringExpenseToExpenseFactory
$value,
1
);
}
// }
}
// Second case with more common calculations.

View File

@ -79,7 +79,7 @@ class ExpenseFilters extends QueryFilters
$this->builder->where(function ($query) use ($status_parameters) {
if (in_array('logged', $status_parameters)) {
$query->orWhere(function ($query) {
$query->where('amount', '>', 0)
$query->where('amount', '>=', 0)
->whereNull('invoice_id')
->whereNull('payment_date')
->where('should_be_invoiced', false);

View File

@ -271,6 +271,7 @@ class InvoiceFilters extends QueryFilters
if (count($parts) != 2) {
return $this->builder;
}
try {
$start_date = Carbon::parse($parts[0]);
@ -281,7 +282,6 @@ class InvoiceFilters extends QueryFilters
return $this->builder;
}
return $this->builder;
}
/**
@ -307,7 +307,6 @@ class InvoiceFilters extends QueryFilters
return $this->builder;
}
return $this->builder;
}

View File

@ -204,7 +204,6 @@ class PaymentFilters extends QueryFilters
return $this->builder;
}
return $this->builder;
}
/**

View File

@ -162,9 +162,10 @@ class RecurringInvoiceFilters extends QueryFilters
return $this->builder;
}
/** @var array $key_parameters */
$key_parameters = explode(',', $value);
if (count($key_parameters)) {
if (count($key_parameters) > 0) {
return $this->builder->where(function ($query) use ($key_parameters) {
foreach ($key_parameters as $key) {
$query->orWhereJsonContains('line_items', ['product_key' => $key]);
@ -183,6 +184,7 @@ class RecurringInvoiceFilters extends QueryFilters
*/
public function next_send_between(string $range = ''): Builder
{
/** @var array $parts */
$parts = explode('|', $range);
if (!isset($parts[0]) || !isset($parts[1])) {

View File

@ -175,6 +175,7 @@ class TaskFilters extends QueryFilters
return $this->builder;
}
/** @var array $status_parameters */
$status_parameters = explode(',', $value);
if(count($status_parameters) >= 1) {

View File

@ -156,22 +156,16 @@ class TransactionTransformer implements BankRevenueInterface
private function convertCurrency(string $code)
{
$currencies = Cache::get('currencies');
$currencies = app('currencies');
if (!$currencies) {
$this->buildCache(true);
}
$currency = $currencies->filter(function ($item) use ($code) {
$currency = $currencies->first(function ($item) use ($code) {
/** @var \App\Models\Currency $item */
return $item->code == $code;
})->first();
if ($currency) {
return $currency->id;
}
return 1;
});
/** @var \App\Models\Currency $currency */
return $currency ? $currency->id : 1; //@phpstan-ignore-line
}
private function formatDate(string $input)

View File

@ -171,20 +171,16 @@ class IncomeTransformer implements BankRevenueInterface
private function convertCurrency(string $code)
{
$currencies = Cache::get('currencies');
if (! $currencies) {
$this->buildCache(true);
}
$currencies = app('currencies');
$currency = $currencies->filter(function ($item) use ($code) {
$currency = $currencies->first(function ($item) use ($code) {
/** @var \App\Models\Currency $item */
return $item->code == $code;
})->first();
});
if ($currency) {
return $currency->id;
}
/** @var \App\Models\Currency $currency */
return $currency ? $currency->id : 1; //@phpstan-ignore-line
return 1;
}
}

View File

@ -26,15 +26,15 @@ use BaconQrCode\Writer;
*/
class EpcQrGenerator
{
private array $sepa = [
'serviceTag' => 'BCD',
'version' => 2,
'characterSet' => 1,
'identification' => 'SCT',
'bic' => '',
'purpose' => '',
// private array $sepa = [
// 'serviceTag' => 'BCD',
// 'version' => 2,
// 'characterSet' => 1,
// 'identification' => 'SCT',
// 'bic' => '',
// 'purpose' => '',
];
// ];
public function __construct(protected Company $company, protected Invoice|RecurringInvoice $invoice, protected float $amount)
{
@ -61,13 +61,7 @@ class EpcQrGenerator
} catch(\Throwable $e) {
nlog("EPC QR failure => ".$e->getMessage());
return '';
} catch(\Exception $e) {
nlog("EPC QR failure => ".$e->getMessage());
return '';
} catch(InvalidArgumentException $e) {
nlog("EPC QR failure => ".$e->getMessage());
return '';
}
}
}

View File

@ -29,6 +29,7 @@ class InvoiceItemSum
use Discounter;
use Taxer;
//@phpstan-ignore-next-line
private array $eu_tax_jurisdictions = [
'AT', // Austria
'BE', // Belgium
@ -170,7 +171,7 @@ class InvoiceItemSum
private function shouldCalculateTax(): self
{
if (!$this->invoice->company?->calculate_taxes || $this->invoice->company->account->isFreeHostedClient()) {
if (!$this->invoice->company?->calculate_taxes || $this->invoice->company->account->isFreeHostedClient()) { //@phpstan-ignore-line
$this->calc_tax = false;
return $this;
}

View File

@ -27,7 +27,7 @@ class InvoiceItemSumInclusive
use Discounter;
use Taxer;
//@phpstan-ignore-next-line
private array $eu_tax_jurisdictions = [
'AT', // Austria
'BE', // Belgium
@ -98,6 +98,7 @@ class InvoiceItemSumInclusive
private $total_taxes;
/** @phpstan-ignore-next-line */
private $item;
private $line_items;
@ -399,7 +400,7 @@ class InvoiceItemSumInclusive
private function shouldCalculateTax(): self
{
if (!$this->invoice->company?->calculate_taxes || $this->invoice->company->account->isFreeHostedClient()) {
if (!$this->invoice->company?->calculate_taxes || $this->invoice->company->account->isFreeHostedClient()) {//@phpstan-ignore-line
$this->calc_tax = false;
return $this;
}

View File

@ -58,12 +58,12 @@ class ProRata
* Prepares the line items of an invoice
* to be pro rata refunded.
*
* @param Invoice $invoice
* @param ?Invoice $invoice
* @param bool $is_credit
* @return array
* @throws Exception
*/
public function refundItems(Invoice $invoice, $is_credit = false): array
public function refundItems(?Invoice $invoice, $is_credit = false): array
{
if (! $invoice) {
return [];

View File

@ -118,7 +118,7 @@ class ContactForgotPasswordController extends Controller
})->first();
}
$response = false;
// $response = false;
if ($contact) {
/* Update all instances of the client */
@ -131,16 +131,16 @@ class ContactForgotPasswordController extends Controller
}
if ($request->ajax()) {
if ($response == Password::RESET_THROTTLED) {
if ($response == Password::RESET_THROTTLED) { // @phpstan-ignore-line
return response()->json(['message' => ctrans('passwords.throttled'), 'status' => false], 429);
}
return $response == Password::RESET_LINK_SENT
return $response == Password::RESET_LINK_SENT // @phpstan-ignore-line
? response()->json(['message' => 'Reset link sent to your email.', 'status' => true], 201)
: response()->json(['message' => 'Email not found', 'status' => false], 401);
}
return $response == Password::RESET_LINK_SENT
return $response == Password::RESET_LINK_SENT // @phpstan-ignore-line
? $this->sendResetLinkResponse($request, $response)
: $this->sendResetLinkFailedResponse($request, $response);
}

View File

@ -55,7 +55,7 @@ class ContactLoginController extends Controller
$company = Company::where('company_key', $company_key)->first();
}
/** @var \App\Models\Company $company **/
/** @var ?\App\Models\Company $company **/
if ($company) {
$account = $company->account;
} elseif (! $company && strpos($request->getHost(), config('ninja.app_domain')) !== false) {

View File

@ -137,8 +137,8 @@ class ResetPasswordController extends Controller
return redirect('/#/login');
}
return redirect($this->redirectPath())
->with('status', trans($response));
// return redirect($this->redirectPath())
// ->with('status', trans($response));
}
}

View File

@ -1035,7 +1035,7 @@ class BaseController extends Controller
$resource = new Item($item, $transformer, $this->entity_type);
/** @var \App\Models\User $user */
/** @var ?\App\Models\User $user */
$user = auth()->user();
if ($user && request()->include_static) {

View File

@ -19,7 +19,6 @@ use Illuminate\Http\Request;
*/
class BrevoController extends BaseController
{
private $invitation;
public function __construct()
{

View File

@ -141,7 +141,7 @@ class ClientController extends BaseController
return $request->disallowUpdate();
}
/** @var \App\Models\User $user */
/** @var ?\App\Models\User $user */
$user = auth()->user();
$client = $this->client_repo->save($request->all(), $client);
@ -426,7 +426,7 @@ class ClientController extends BaseController
try {
/** @var \Postmark\Models\DynamicResponseModel $response */
/** @var ?\Postmark\Models\DynamicResponseModel $response */
$response = $postmark->activateBounce((int)$bounce_id);
if($response && $response?->Message == 'OK' && !$response->Bounce->Inactive && $response->Bounce->Email) {

View File

@ -146,6 +146,7 @@ class InvitationController extends Controller
}
private function fireEntityViewedEvent($invitation, $entity_string)
{
switch ($entity_string) {

View File

@ -97,12 +97,12 @@ class InvoiceController extends Controller
$invitation = false;
match($data['entity_type'] ?? false) {
match($data['entity_type'] ?? 'invoice') {
'invoice' => $invitation = InvoiceInvitation::withTrashed()->find($data['invitation_id']),
'quote' => $invitation = QuoteInvitation::withTrashed()->find($data['invitation_id']),
'credit' => $invitation = CreditInvitation::withTrashed()->find($data['invitation_id']),
'recurring_invoice' => $invitation = RecurringInvoiceInvitation::withTrashed()->find($data['invitation_id']),
false => $invitation = false,
default => $invitation = false,
};
if (! $invitation) {

View File

@ -77,6 +77,7 @@ class PaymentController extends Controller
'EUR' => $data = $bt->formatDataforEur($payment_intent),
'JPY' => $data = $bt->formatDataforJp($payment_intent),
'GBP' => $data = $bt->formatDataforUk($payment_intent),
default => $data = $bt->formatDataforUk($payment_intent),
};
$gateway = $stripe;

View File

@ -90,15 +90,20 @@ class SubscriptionPurchaseController extends Controller
* Set locale for incoming request.
*
* @param string $locale
* @return string
*/
private function setLocale(string $locale): void
private function setLocale(string $locale): string
{
$record = Cache::get('languages')->filter(function ($item) use ($locale) {
return $item->locale == $locale;
})->first();
/** @var \Illuminate\Support\Collection<\App\Models\Language> */
$languages = app('languages');
if ($record) {
App::setLocale($record->locale);
}
$record = $languages->first(function ($item) use ($locale) {
/** @var \App\Models\Language $item */
return $item->locale == $locale;
});
return $record ? $record->locale : 'en';
}
}

View File

@ -693,7 +693,7 @@ class CompanyController extends BaseController
public function updateOriginTaxData(DefaultCompanyRequest $request, Company $company)
{
if($company->settings->country_id == "840" && !$company?->account->isFreeHostedClient()) {
if($company->settings->country_id == "840" && !$company->account->isFreeHostedClient()) {
try {
(new CompanyTaxRate($company))->handle();
} catch(\Exception $e) {

View File

@ -119,8 +119,6 @@ class CompanyUserController extends BaseController
if (! $company_user) {
throw new ModelNotFoundException(ctrans('texts.company_user_not_found'));
return;
}
if ($auth_user->isAdmin()) {
@ -152,7 +150,6 @@ class CompanyUserController extends BaseController
if (! $company_user) {
throw new ModelNotFoundException(ctrans('texts.company_user_not_found'));
return;
}
$this->entity_type = User::class;

View File

@ -594,13 +594,11 @@ class CreditController extends BaseController
$credit->service()->markPaid()->save();
return $this->itemResponse($credit);
break;
case 'clone_to_credit':
$credit = CloneCreditFactory::create($credit, auth()->user()->id);
return $this->itemResponse($credit);
break;
case 'history':
// code...
break;
@ -617,7 +615,7 @@ class CreditController extends BaseController
return response()->streamDownload(function () use ($file) {
echo $file;
}, $credit->numberFormatter() . '.pdf', ['Content-Type' => 'application/pdf']);
break;
case 'archive':
$this->credit_repository->archive($credit);
@ -655,7 +653,6 @@ class CreditController extends BaseController
default:
return response()->json(['message' => ctrans('texts.action_unavailable', ['action' => $action])], 400);
break;
}
}

View File

@ -139,19 +139,19 @@ class EmailController extends BaseController
return $this->itemResponse($entity_obj->fresh());
}
private function sendPurchaseOrder($entity_obj, $data, $template)
{
$this->entity_type = PurchaseOrder::class;
// private function sendPurchaseOrder($entity_obj, $data, $template)
// {
// $this->entity_type = PurchaseOrder::class;
$this->entity_transformer = PurchaseOrderTransformer::class;
// $this->entity_transformer = PurchaseOrderTransformer::class;
$data['template'] = $template;
// $data['template'] = $template;
PurchaseOrderEmail::dispatch($entity_obj, $entity_obj->company, $data);
$entity_obj->sendEvent(Webhook::EVENT_SENT_PURCHASE_ORDER, "vendor");
// PurchaseOrderEmail::dispatch($entity_obj, $entity_obj->company, $data);
// $entity_obj->sendEvent(Webhook::EVENT_SENT_PURCHASE_ORDER, "vendor");
return $this->itemResponse($entity_obj);
}
// return $this->itemResponse($entity_obj);
// }
private function resolveClass(string $entity): string
{

View File

@ -280,186 +280,172 @@ class MigrationController extends BaseController
}
}
if (app()->environment() === 'local') {
}
try {
return response()->json([
'_id' => Str::uuid(),
'method' => config('queue.default'),
'started_at' => now(),
], 200);
} finally {
// Controller logic here
foreach ($companies as $company) {
if (! is_array($company)) {
continue;
}
$company = (array) $company;
$user = auth()->user();
$company_count = $user->account->companies()->count();
$fresh_company = false;
// Look for possible existing company (based on company keys).
$existing_company = Company::query()->whereRaw('BINARY `company_key` = ?', [$company['company_key']])->first();
App::forgetInstance('translator');
$t = app('translator');
$t->replace(Ninja::transformTranslations($user->account->companies()->first()->settings));
App::setLocale($user->account->companies()->first()->getLocale());
if (! $existing_company && $company_count >= 10) {
$nmo = new NinjaMailerObject();
$nmo->mailable = new MaxCompanies($user->account->companies()->first());
$nmo->company = $user->account->companies()->first();
$nmo->settings = $user->account->companies()->first()->settings;
$nmo->to_user = $user;
if(!$this->silent_migration) {
NinjaMailerJob::dispatch($nmo, true);
}
return;
} elseif ($existing_company && $company_count > 10) {
$nmo = new NinjaMailerObject();
$nmo->mailable = new MaxCompanies($user->account->companies()->first());
$nmo->company = $user->account->companies()->first();
$nmo->settings = $user->account->companies()->first()->settings;
$nmo->to_user = $user;
if(!$this->silent_migration) {
NinjaMailerJob::dispatch($nmo, true);
}
return;
}
$checks = [
'existing_company' => $existing_company ? (bool) 1 : false,
'force' => array_key_exists('force', $company) ? (bool) $company['force'] : false,
];
// If there's existing company and ** no ** force is provided - skip migration.
if ($checks['existing_company'] == true && $checks['force'] == false) {
nlog('Migrating: Existing company without force. (CASE_01)');
$nmo = new NinjaMailerObject();
$nmo->mailable = new ExistingMigration($existing_company);
$nmo->company = $user->account->companies()->first();
$nmo->settings = $user->account->companies()->first();
$nmo->to_user = $user;
if(!$this->silent_migration) {
NinjaMailerJob::dispatch($nmo, true);
}
return response()->json([
'_id' => Str::uuid(),
'method' => config('queue.default'),
'started_at' => now(),
], 200);
}
// If there's existing company and force ** is provided ** - purge the company and migrate again.
if ($checks['existing_company'] == true && $checks['force'] == true) {
nlog('purging the existing company here');
$this->purgeCompanyWithForceFlag($existing_company);
$account = auth()->user()->account;
$fresh_company = (new ImportMigrations())->getCompany($account);
$fresh_company->is_disabled = true;
$fresh_company->save();
$account->default_company_id = $fresh_company->id;
$account->save();
$fresh_company_token = new CompanyToken();
$fresh_company_token->user_id = $user->id;
$fresh_company_token->company_id = $fresh_company->id;
$fresh_company_token->account_id = $account->id;
$fresh_company_token->name = $request->token_name ?? Str::random(12);
$fresh_company_token->token = $request->token ?? Str::random(64);
$fresh_company_token->is_system = true;
$fresh_company_token->save();
/** @var \App\Models\User $user */
$user->companies()->attach($fresh_company->id, [
'account_id' => $account->id,
'is_owner' => 1,
'is_admin' => 1,
'is_locked' => 0,
'notifications' => CompanySettings::notificationDefaults(),
'permissions' => '',
'settings' => null,
]);
}
// If there's no existing company migrate just normally.
if ($checks['existing_company'] == false) {
nlog('creating fresh company');
$account = auth()->user()->account;
$fresh_company = (new ImportMigrations())->getCompany($account);
$fresh_company->is_disabled = true;
$fresh_company->save();
$fresh_company_token = new CompanyToken();
$fresh_company_token->user_id = $user->id;
$fresh_company_token->company_id = $fresh_company->id;
$fresh_company_token->account_id = $account->id;
$fresh_company_token->name = $request->token_name ?? Str::random(12);
$fresh_company_token->token = $request->token ?? Str::random(64);
$fresh_company_token->is_system = true;
$fresh_company_token->save();
/** @var \App\Models\User $user */
$user->companies()->attach($fresh_company->id, [
'account_id' => $account->id,
'is_owner' => 1,
'is_admin' => 1,
'is_locked' => 0,
'notifications' => CompanySettings::notificationDefaults(),
'permissions' => '',
'settings' => null,
]);
}
$migration_file = $request->file($company['company_index'])
->storeAs(
'migrations',
$request->file($company['company_index'])->getClientOriginalName(),
'public'
);
if (app()->environment() == 'testing') {
nlog('environment is testing = bailing out now');
return;
}
nlog('starting migration job');
nlog($migration_file);
if (Ninja::isHosted()) {
StartMigration::dispatch($migration_file, $user, $fresh_company, $this->silent_migration)->onQueue('migration');
} else {
StartMigration::dispatch($migration_file, $user, $fresh_company, $this->silent_migration);
}
foreach ($companies as $company) {
if (! is_array($company)) {
continue;
}
return response()->json([
'_id' => Str::uuid(),
'method' => config('queue.default'),
'started_at' => now(),
], 200);
$company = (array) $company;
$user = auth()->user();
$company_count = $user->account->companies()->count();
$fresh_company = false;
// Look for possible existing company (based on company keys).
$existing_company = Company::query()->whereRaw('BINARY `company_key` = ?', [$company['company_key']])->first();
App::forgetInstance('translator');
$t = app('translator');
$t->replace(Ninja::transformTranslations($user->account->companies()->first()->settings));
App::setLocale($user->account->companies()->first()->getLocale());
if (! $existing_company && $company_count >= 10) {
$nmo = new NinjaMailerObject();
$nmo->mailable = new MaxCompanies($user->account->companies()->first());
$nmo->company = $user->account->companies()->first();
$nmo->settings = $user->account->companies()->first()->settings;
$nmo->to_user = $user;
if(!$this->silent_migration) {
NinjaMailerJob::dispatch($nmo, true);
}
return;
} elseif ($existing_company && $company_count > 10) {
$nmo = new NinjaMailerObject();
$nmo->mailable = new MaxCompanies($user->account->companies()->first());
$nmo->company = $user->account->companies()->first();
$nmo->settings = $user->account->companies()->first()->settings;
$nmo->to_user = $user;
if(!$this->silent_migration) {
NinjaMailerJob::dispatch($nmo, true);
}
return;
}
$checks = [
'existing_company' => $existing_company ? (bool) 1 : false,
'force' => array_key_exists('force', $company) ? (bool) $company['force'] : false,
];
// If there's existing company and ** no ** force is provided - skip migration.
if ($checks['existing_company'] == true && $checks['force'] == false) {
nlog('Migrating: Existing company without force. (CASE_01)');
$nmo = new NinjaMailerObject();
$nmo->mailable = new ExistingMigration($existing_company);
$nmo->company = $user->account->companies()->first();
$nmo->settings = $user->account->companies()->first();
$nmo->to_user = $user;
if(!$this->silent_migration) {
NinjaMailerJob::dispatch($nmo, true);
}
return response()->json([
'_id' => Str::uuid(),
'method' => config('queue.default'),
'started_at' => now(),
], 200);
}
// If there's existing company and force ** is provided ** - purge the company and migrate again.
if ($checks['existing_company'] == true && $checks['force'] == true) {
nlog('purging the existing company here');
$this->purgeCompanyWithForceFlag($existing_company);
$account = auth()->user()->account;
$fresh_company = (new ImportMigrations())->getCompany($account);
$fresh_company->is_disabled = true;
$fresh_company->save();
$account->default_company_id = $fresh_company->id;
$account->save();
$fresh_company_token = new CompanyToken();
$fresh_company_token->user_id = $user->id;
$fresh_company_token->company_id = $fresh_company->id;
$fresh_company_token->account_id = $account->id;
$fresh_company_token->name = $request->token_name ?? Str::random(12);
$fresh_company_token->token = $request->token ?? Str::random(64);
$fresh_company_token->is_system = true;
$fresh_company_token->save();
/** @var \App\Models\User $user */
$user->companies()->attach($fresh_company->id, [
'account_id' => $account->id,
'is_owner' => 1,
'is_admin' => 1,
'is_locked' => 0,
'notifications' => CompanySettings::notificationDefaults(),
'permissions' => '',
'settings' => null,
]);
}
// If there's no existing company migrate just normally.
if ($checks['existing_company'] == false) {
nlog('creating fresh company');
$account = auth()->user()->account;
$fresh_company = (new ImportMigrations())->getCompany($account);
$fresh_company->is_disabled = true;
$fresh_company->save();
$fresh_company_token = new CompanyToken();
$fresh_company_token->user_id = $user->id;
$fresh_company_token->company_id = $fresh_company->id;
$fresh_company_token->account_id = $account->id;
$fresh_company_token->name = $request->token_name ?? Str::random(12);
$fresh_company_token->token = $request->token ?? Str::random(64);
$fresh_company_token->is_system = true;
$fresh_company_token->save();
/** @var \App\Models\User $user */
$user->companies()->attach($fresh_company->id, [
'account_id' => $account->id,
'is_owner' => 1,
'is_admin' => 1,
'is_locked' => 0,
'notifications' => CompanySettings::notificationDefaults(),
'permissions' => '',
'settings' => null,
]);
}
$migration_file = $request->file($company['company_index'])
->storeAs(
'migrations',
$request->file($company['company_index'])->getClientOriginalName(),
'public'
);
if (app()->environment() == 'testing') {
nlog('environment is testing = bailing out now');
return;
}
nlog('starting migration job');
nlog($migration_file);
if (Ninja::isHosted()) {
StartMigration::dispatch($migration_file, $user, $fresh_company, $this->silent_migration)->onQueue('migration');
} else {
StartMigration::dispatch($migration_file, $user, $fresh_company, $this->silent_migration);
}
}
return response()->json([
'_id' => Str::uuid(),
'method' => config('queue.default'),
'started_at' => now(),
], 200);
}
}

View File

@ -22,8 +22,6 @@ use Illuminate\Support\Str;
class OneTimeTokenController extends BaseController
{
private $contexts = [
];
public function __construct()
{

View File

@ -19,7 +19,6 @@ use Illuminate\Http\Request;
*/
class PostMarkController extends BaseController
{
private $invitation;
public function __construct()
{

View File

@ -219,139 +219,6 @@ class PreviewPurchaseOrderController extends BaseController
}
public function livex(PreviewPurchaseOrderRequest $request)
{
/** @var \App\Models\User $user */
$user = auth()->user();
$company = $user->company();
$file_path = (new PreviewPdf('<html></html>', $company))->handle();
$response = Response::make($file_path, 200);
$response->header('Content-Type', 'application/pdf');
return $response;
MultiDB::setDb($company->db);
$repo = new PurchaseOrderRepository();
$entity_obj = PurchaseOrderFactory::create($company->id, $user->id);
$class = PurchaseOrder::class;
try {
DB::connection(config('database.default'))->beginTransaction();
if ($request->has('entity_id')) {
/** @var \App\Models\PurchaseOrder|\Illuminate\Contracts\Database\Eloquent\Builder $entity_obj **/
$entity_obj = \App\Models\PurchaseOrder::on(config('database.default'))
->with('vendor.company')
->where('id', $this->decodePrimaryKey($request->input('entity_id')))
->where('company_id', $company->id)
->withTrashed()
->first();
}
$entity_obj = $repo->save($request->all(), $entity_obj);
if (!$request->has('entity_id')) {
$entity_obj->service()->fillDefaults()->save();
}
App::forgetInstance('translator');
$t = app('translator');
App::setLocale($entity_obj->company->locale());
$t->replace(Ninja::transformTranslations($entity_obj->company->settings));
$html = new VendorHtmlEngine($entity_obj->invitations()->first());
/** @var \App\Models\Design $design */
$design = \App\Models\Design::withTrashed()->find($entity_obj->design_id);
/* Catch all in case migration doesn't pass back a valid design */
if (!$design) {
$design = \App\Models\Design::find(2);
}
if ($design->is_custom) {
$options = [
'custom_partials' => json_decode(json_encode($design->design), true)
];
$template = new PdfMakerDesign(PdfDesignModel::CUSTOM, $options);
} else {
$template = new PdfMakerDesign(strtolower($design->name));
}
$variables = $html->generateLabelsAndValues();
$state = [
'template' => $template->elements([
'client' => null,
'vendor' => $entity_obj->vendor,
'entity' => $entity_obj,
'pdf_variables' => (array) $entity_obj->company->settings->pdf_variables,
'variables' => $html->generateLabelsAndValues(),
'$product' => $design->design->product,
]),
'variables' => $html->generateLabelsAndValues(),
'options' => [
'client' => null,
'vendor' => $entity_obj->vendor,
'purchase_orders' => [$entity_obj],
'variables' => $html->generateLabelsAndValues(),
],
'process_markdown' => $entity_obj->company->markdown_enabled,
];
$maker = new PdfMaker($state);
$maker
->design($template)
->build();
DB::connection(config('database.default'))->rollBack();
if (request()->query('html') == 'true') {
return $maker->getCompiledHTML();
}
} catch(\Exception $e) {
DB::connection(config('database.default'))->rollBack();
return;
}
/** @var \App\Models\User $user */
$user = auth()->user();
//if phantom js...... inject here..
if (config('ninja.phantomjs_pdf_generation') || config('ninja.pdf_generator') == 'phantom') {
return (new Phantom())->convertHtmlToPdf($maker->getCompiledHTML(true));
}
if (config('ninja.invoiceninja_hosted_pdf_generation') || config('ninja.pdf_generator') == 'hosted_ninja') {
$pdf = (new NinjaPdf())->build($maker->getCompiledHTML(true));
$numbered_pdf = $this->pageNumbering($pdf, $user->company());
if ($numbered_pdf) {
$pdf = $numbered_pdf;
}
return $pdf;
}
$file_path = (new PreviewPdf($maker->getCompiledHTML(true), $company))->handle();
if (Ninja::isHosted()) {
LightLogs::create(new LivePreview())
->increment()
->batch();
}
$response = Response::make($file_path, 200);
$response->header('Content-Type', 'application/pdf');
return $response;
}
private function blankEntity()
{
/** @var \App\Models\User $user */

View File

@ -25,7 +25,6 @@ class ProtectedDownloadController extends BaseController
if (!$hashed_path) {
throw new SystemError('File no longer available', 404);
abort(404, 'File no longer available');
}
return response()->streamDownload(function () use ($hashed_path) {

View File

@ -717,7 +717,7 @@ class PurchaseOrderController extends BaseController
default:
return response()->json(['message' => ctrans('texts.action_unavailable', ['action' => $action])], 400);
break;
}
}

View File

@ -787,7 +787,6 @@ class QuoteController extends BaseController
break;
default:
return response()->json(['message' => ctrans('texts.action_unavailable', ['action' => $action])], 400);
break;
}
}

View File

@ -234,24 +234,6 @@ class SetupController extends Controller
}
}
private function testPhantom()
{
try {
$key = config('ninja.phantomjs_key');
$url = 'https://www.invoiceninja.org/';
$phantom_url = "https://phantomjscloud.com/api/browser/v2/{$key}/?request=%7Burl:%22{$url}%22,renderType:%22pdf%22%7D";
$pdf = CurlUtils::get($phantom_url);
Storage::disk(config('filesystems.default'))->put('test.pdf', $pdf);
Storage::disk('local')->put('test.pdf', $pdf);
return response(['url' => Storage::disk('local')->url('test.pdf')], 200);
} catch (Exception $e) {
return response([], 500);
}
}
public function clearCompiledCache()
{
$cacheCompiled = base_path('bootstrap/cache/compiled.php');

View File

@ -61,7 +61,7 @@ class PasswordProtection
return $next($request);
} elseif(strlen(auth()->user()->oauth_provider_id) > 2 && !auth()->user()->company()->oauth_password_required) {
return $next($request);
} elseif ($request->header('X-API-OAUTH-PASSWORD') && strlen($request->header('X-API-OAUTH-PASSWORD')) >= 1) {
} elseif ($request->header('X-API-OAUTH-PASSWORD') && strlen($request->header('X-API-OAUTH-PASSWORD')) > 1) {
//user is attempting to reauth with OAuth - check the token value
//todo expand this to include all OAuth providers
if (auth()->user()->oauth_provider_id == 'google') {

View File

@ -185,48 +185,44 @@ class StoreClientRequest extends Request
];
}
private function getLanguageId($language_code)
private function getLanguageId(string $language_code)
{
$languages = Cache::get('languages');
/** @var \Illuminate\Support\Collection<\App\Models\Language> */
$languages = app('languages');
$language = $languages->filter(function ($item) use ($language_code) {
$language = $languages->first(function ($item) use ($language_code) {
return $item->locale == $language_code;
})->first();
});
if ($language) {
return (string) $language->id;
}
return $language ? (string)$language->id : '';
return '';
}
private function getCountryCode($country_code)
private function getCountryCode(string $country_code)
{
$countries = Cache::get('countries');
/** @var \Illuminate\Support\Collection<\App\Models\Country> */
$countries = app('countries');
$country = $countries->filter(function ($item) use ($country_code) {
$country = $countries->first(function ($item) use ($country_code) {
return $item->iso_3166_2 == $country_code || $item->iso_3166_3 == $country_code;
})->first();
});
if ($country) {
return (string) $country->id;
}
return '';
return $country ? (string) $country->id : '';
}
private function getCurrencyCode($code)
{
$currencies = Cache::get('currencies');
/** @var \Illuminate\Support\Collection<\App\Models\Currency> */
$currencies = app('currencies');
$currency = $currencies->filter(function ($item) use ($code) {
$currency = $currencies->first(function ($item) use ($code) {
return $item->code == $code;
})->first();
});
if ($currency) {
return (string) $currency->id;
}
return '';
return $currency ? (string)$currency->id : '';
}
}

View File

@ -139,32 +139,28 @@ class UpdateClientRequest extends Request
private function getCountryCode($country_code)
{
$countries = Cache::get('countries');
/** @var \Illuminate\Support\Collection<\App\Models\Country> */
$countries = app('countries');
$country = $countries->filter(function ($item) use ($country_code) {
$country = $countries->first(function ($item) use ($country_code) {
return $item->iso_3166_2 == $country_code || $item->iso_3166_3 == $country_code;
})->first();
});
if ($country) {
return (string) $country->id;
}
return '';
return $country ? (string) $country->id : '';
}
private function getLanguageId($language_code)
{
$languages = Cache::get('languages');
/** @var \Illuminate\Support\Collection<\App\Models\Language> */
$languages = app('languages');
$language = $languages->filter(function ($item) use ($language_code) {
$language = $languages->first(function ($item) use ($language_code) {
return $item->locale == $language_code;
})->first();
});
if ($language) {
return (string) $language->id;
}
return '';
return $language ? (string) $language->id : '';
}
/**

View File

@ -130,7 +130,7 @@ class StorePaymentRequest extends Request
}
if (! isset($input['idempotency_key'])) {
$input['idempotency_key'] = substr(sha1(json_encode($input)).time()."{$input['date']}{$input['amount']}{$user->id}", 0, 64);
$input['idempotency_key'] = substr(time()."{$input['date']}{$input['amount']}{$credits_total}{$this->client_id}{$user->company()->company_key}", 0, 64);
}
$this->replace($input);

View File

@ -88,7 +88,8 @@ class PreviewInvoiceRequest extends Request
public function resolveInvitation()
{
$invitation = false;
/** @phpstan-ignore-next-line */
if(! $this->entity_id ?? false) {
return $this->stubInvitation();
}
@ -98,6 +99,7 @@ class PreviewInvoiceRequest extends Request
'quote' => $invitation = QuoteInvitation::withTrashed()->where('quote_id', $this->entity_id)->first(),
'credit' => $invitation = CreditInvitation::withTrashed()->where('credit_id', $this->entity_id)->first(),
'recurring_invoice' => $invitation = RecurringInvoiceInvitation::withTrashed()->where('recurring_invoice_id', $this->entity_id)->first(),
default => $invitation = false,
};
if($invitation) {

View File

@ -155,23 +155,27 @@ class StoreShopClientRequest extends Request
private function getCountryCode($country_code)
{
$countries = Cache::get('countries');
/** @var \Illuminate\Support\Collection<\App\Models\Country> */
$countries = app('countries');
$country = $countries->filter(function ($item) use ($country_code) {
$country = $countries->first(function ($item) use ($country_code) {
return $item->iso_3166_2 == $country_code || $item->iso_3166_3 == $country_code;
})->first();
});
return (string) $country->id;
return $country ? (string) $country->id : '';
}
private function getCurrencyCode($code)
{
$currencies = Cache::get('currencies');
/** @var \Illuminate\Support\Collection<\App\Models\Country> */
$currencies = app('currencies');
$currency = $currencies->filter(function ($item) use ($code) {
$currency = $currencies->first(function ($item) use ($code) {
return $item->code == $code;
})->first();
});
return (string) $currency->id;
return $currency ? (string) $currency->id : '';
}
}

View File

@ -119,17 +119,18 @@ class BaseTransformer
{
$code = array_key_exists($key, $data) ? $data[$key] : false;
$currencies = Cache::get('currencies');
if(!$code)
return $this->company->settings->currency_id;
$currency = $currencies
->filter(function ($item) use ($code) {
return $item->code == $code;
})
->first();
/** @var \Illuminate\Support\Collection<\App\Models\Currency> */
$currencies = app('currencies');
$currency = $currencies->first(function ($item) use ($code) {
return $item->code == $code;
});
return $currency ? (string) $currency->id : $this->company->settings->currency_id;
return $currency
? $currency->id
: $this->company->settings->currency_id;
}
public function getFrequency($frequency = RecurringInvoice::FREQUENCY_MONTHLY): int
@ -653,12 +654,11 @@ class BaseTransformer
/**
* @param $name
*
* @return int|null
* @return int
*/
public function getExpenseCategoryId($name)
{
/** @var \App\Models\ExpenseCategory $ec */
/** @var ?\App\Models\ExpenseCategory $ec */
$ec = ExpenseCategory::query()->where('company_id', $this->company->id)
->where('is_deleted', false)
->whereRaw("LOWER(REPLACE(`name`, ' ' ,'')) = ?", [
@ -674,7 +674,7 @@ class BaseTransformer
$ec->name = $name;
$ec->save();
return $ec ? $ec->id : null;
return $ec->id;
}
public function getOrCreateExpenseCategry($name)

View File

@ -277,7 +277,7 @@ class InvoiceTransformer extends BaseTransformer
if($key == 0) {
continue;
}
/** @var array $row */
if(is_array($row[5])) {
$csv = str_getcsv($row[5][0], ";");
$row[5] = array_combine(explode(",", $csv[0]), explode(",", $csv[1]));

View File

@ -50,7 +50,7 @@ class InvoiceTransformer extends BaseTransformer
'client_id' => $this->getClient($customer_name = $this->getString($invoice_data, $customer_key), null),
'number' => $invoice_number = $this->getString($invoice_data, 'Invoice Number'),
'date' => $this->parseDate($invoice_data[$date_key]) ?: now()->format('Y-m-d'), //27-01-2022
'currency_id' => $this->getCurrencyByCode($invoice_data, 'Currency'),
// 'currency_id' => $this->getCurrencyByCode($invoice_data, 'Currency'),
'status_id' => Invoice::STATUS_SENT,
'due_date' => array_key_exists('Due Date', $invoice_data) ? $this->parseDate($invoice_data['Due Date']) : null,
];

View File

@ -1205,6 +1205,7 @@ class CompanyImport implements ShouldQueue
continue;
}
/** @var string $storage_url */
$storage_url = (object)$this->getObject('storage_url', true);
if (!Storage::exists($document->url) && is_string($storage_url)) {
@ -1351,45 +1352,31 @@ class CompanyImport implements ShouldQueue
switch ($type) {
case Company::class:
return $this->company->id;
break;
case Client::class:
return $this->transformId('clients', $id);
break;
case ClientContact::class:
return $this->transformId('client_contacts', $id);
break;
case Credit::class:
return $this->transformId('credits', $id);
break;
case Expense::class:
return $this->transformId('expenses', $id);
break;
case 'invoices':
return $this->transformId('invoices', $id);
break;
case Payment::class:
return $this->transformId('payments', $id);
break;
case Project::class:
return $this->transformId('projects', $id);
break;
case Product::class:
return $this->transformId('products', $id);
break;
case Quote::class:
return $this->transformId('quotes', $id);
break;
case RecurringInvoice::class:
return $this->transformId('recurring_invoices', $id);
break;
case Company::class:
return $this->transformId('clients', $id);
break;
default:
return false;
break;
}
}
@ -1420,10 +1407,10 @@ class CompanyImport implements ShouldQueue
switch ($type) {
case 'invoices':
return $this->transformId('invoices', $id);
break;
case Credit::class:
return $this->transformId('credits', $id);
break;
case Payment::class:
return $this->transformId('payments', $id);
default:

View File

@ -65,9 +65,9 @@ class SubscriptionCron
//Requires the crons to be updated and set to hourly @ 00:01
private function timezoneAware()
{
$grouped_company_ids =
Invoice::select('company_id')
Invoice::query()
->with('company')
->where('is_deleted', 0)
->whereIn('status_id', [Invoice::STATUS_SENT, Invoice::STATUS_PARTIAL])
->where('balance', '>', 0)
@ -77,10 +77,11 @@ class SubscriptionCron
->whereNotNull('subscription_id')
->groupBy('company_id')
->cursor()
->each(function ($company_id) {
->each(function ($invoice) {
/** @var \App\Models\Company $company */
$company = Company::find($company_id);
// $company = Company::find($invoice->company_id);
$company = $invoice->company;
$timezone_now = now()->setTimezone($company->timezone()->name ?? 'Pacific/Midway');

View File

@ -40,7 +40,7 @@ class CreateRawPdf
public Invoice | Credit | Quote | RecurringInvoice | PurchaseOrder $entity;
public $company;
public \App\Models\Company $company;
public $contact;
@ -55,6 +55,7 @@ class CreateRawPdf
{
$this->invitation = $invitation;
$this->company = $invitation->company;
if ($invitation instanceof InvoiceInvitation) {
$this->entity = $invitation->invoice;
@ -115,7 +116,14 @@ class CreateRawPdf
}
if ($this->entity_string == "invoice" && $this->entity->client->getSetting("merge_e_invoice_to_pdf")) {
$pdf = (new MergeEDocument($this->entity, $pdf))->handle();
}
$merge_docs = $this->entity->client ? $this->entity->client->getSetting('embed_documents') : $this->company->getSetting('embed_documents');
if($merge_docs && ($this->entity->documents()->where('is_public', true)->count() > 0 || $this->company->documents()->where('is_public', true)->count() > 0)) {
$pdf = $this->entity->documentMerge($pdf);
}
return $pdf;
}

View File

@ -192,7 +192,7 @@ class CreateUbl implements ShouldQueue
/**
* @param $item
* @param $invoice_total
* @return float|int
* @return float
*/
private function getItemTaxable($item, $invoice_total)
{

View File

@ -63,7 +63,7 @@ class TaskScheduler implements ShouldQueue
//@var \App\Models\Schedule $scheduler
$scheduler->service()->runTask();
} catch(\Exception $e) {
nlog($e->getMessage());
nlog("Exception:: TaskScheduler:: Doing job {$scheduler->name}" . $e->getMessage());
}
});

View File

@ -1455,30 +1455,23 @@ class Import implements ShouldQueue
switch ($status_id) {
case 1:
return $payment;
break;
case 2:
return $payment->service()->deletePayment();
break;
case 3:
return $payment->service()->deletePayment();
break;
case 4:
return $payment;
break;
case 5:
$payment->status_id = Payment::STATUS_PARTIALLY_REFUNDED;
$payment->save();
return $payment;
break;
case 6:
$payment->status_id = Payment::STATUS_REFUNDED;
$payment->save();
return $payment;
break;
default:
return $payment;
break;
}
}

View File

@ -100,18 +100,6 @@ class CreatePurchaseOrderPdf implements ShouldQueue
return $ps->boot()->getPdf();
$pdf = $this->rawPdf();
if ($pdf) {
try {
Storage::disk($this->disk)->put($this->file_path, $pdf);
} catch(\Exception $e) {
throw new FilePermissionsFailure($e->getMessage());
}
}
return $this->file_path;
}
public function rawPdf()

View File

@ -130,7 +130,6 @@ class OAuth
return $this;
default:
return null;
break;
}
}

View File

@ -256,7 +256,9 @@ class RegisterOrLogin extends Component
public function render()
{
$countries = Cache::get('countries');
/** @var \Illuminate\Support\Collection<\App\Models\Country> */
$countries = app('countries');
return view('billing-portal.v3.authentication.register-or-login', [
'countries' => $countries,

View File

@ -281,17 +281,25 @@ class BillingPortalPurchase extends Component
}
if (array_key_exists('currency_id', $this->request_data)) {
$currency = Cache::get('currencies')->filter(function ($item) {
/** @var \Illuminate\Support\Collection<\App\Models\Currency> */
$currencies = app('currencies');
$currency = $currencies->first(function ($item) {
return $item->id == $this->request_data['currency_id'];
})->first();
});
if ($currency) {
$data['settings']->currency_id = $currency->id;
}
} elseif ($this->subscription->group_settings && property_exists($this->subscription->group_settings->settings, 'currency_id')) {
$currency = Cache::get('currencies')->filter(function ($item) {
/** @var \Illuminate\Support\Collection<\App\Models\Currency> */
$currencies = app('currencies');
$currency = $currencies->first(function ($item) {
return $item->id == $this->subscription->group_settings->settings->currency_id;
})->first();
});
if ($currency) {
$data['settings']->currency_id = $currency->id;
@ -300,10 +308,12 @@ class BillingPortalPurchase extends Component
if (array_key_exists('locale', $this->request_data)) {
$request = $this->request_data;
$record = Cache::get('languages')->filter(function ($item) use ($request) {
/** @var \Illuminate\Support\Collection<\App\Models\Language> */
$languages = app('languages');
$record = $languages->first(function ($item) use ($request) {
return $item->locale == $request['locale'];
})->first();
});
if ($record) {
$data['settings']['language_id'] = (string)$record->id;

View File

@ -676,17 +676,25 @@ class BillingPortalPurchasev2 extends Component
}
if (array_key_exists('currency_id', $this->request_data)) {
$currency = Cache::get('currencies')->filter(function ($item) {
/** @var \Illuminate\Support\Collection<\App\Models\Currency> */
$currencies = app('currencies');
$currency = $currencies->first(function ($item) {
return $item->id == $this->request_data['currency_id'];
})->first();
});
if ($currency) {
$data['settings']->currency_id = $currency->id;
}
} elseif ($this->subscription->group_settings && property_exists($this->subscription->group_settings->settings, 'currency_id')) {
$currency = Cache::get('currencies')->filter(function ($item) {
/** @var \Illuminate\Support\Collection<\App\Models\Currency> */
$currencies = app('currencies');
$currency = $currencies->first(function ($item) {
return $item->id == $this->subscription->group_settings->settings->currency_id;
})->first();
});
if ($currency) {
$data['settings']->currency_id = $currency->id;
@ -696,9 +704,12 @@ class BillingPortalPurchasev2 extends Component
if (array_key_exists('locale', $this->request_data)) {
$request = $this->request_data;
$record = Cache::get('languages')->filter(function ($item) use ($request) {
/** @var \Illuminate\Support\Collection<\App\Models\Language> */
$languages = app('languages');
$record = $languages->first(function ($item) use ($request) {
return $item->locale == $request['locale'];
})->first();
});
if ($record) {
$data['settings']['language_id'] = (string)$record->id;

View File

@ -516,14 +516,5 @@ class PaymentEmailEngine extends BaseEmailEngine
';
return '
<table border="0" cellspacing="0" cellpadding="0" align="center">
<tr style="border: 0 !important; ">
<td class="new_button" style="padding: 12px 18px 12px 18px; border-radius:5px;" align="center">
<a href="'. $link .'" target="_blank" style="border: 0 !important;font-size: 18px; font-family: Helvetica, Arial, sans-serif; color: #ffffff; text-decoration: none; display: inline-block;">'. $text .'</a>
</td>
</tr>
</table>
';
}
}

View File

@ -374,7 +374,12 @@ class BaseModel extends Model
$files->push($company_docs);
$pdf = (new PdfMerge($files->flatten()->toArray()))->run();
try{
$pdf = (new PdfMerge($files->flatten()->toArray()))->run();
}
catch(\Exception $e){
nlog("Exception:: BaseModel:: PdfMerge::" . $e->getMessage());
}
return $pdf;
}

View File

@ -378,15 +378,11 @@ class Client extends BaseModel implements HasLocalePreference
public function language()
{
$languages = app('languages');
// $languages = Cache::get('languages');
// if (! $languages) {
// $this->buildCache(true);
// }
/** @var \Illuminate\Support\Collection<\App\Models\Language> */
$languages = app('languages');
return $languages->first(function ($item) {
/** @var \stdClass $item */
return $item->id == $this->getSetting('language_id');
});
}
@ -412,17 +408,10 @@ class Client extends BaseModel implements HasLocalePreference
public function date_format()
{
/** @var \Illuminate\Support\Collection $date_formats */
/** @var \Illuminate\Support\Collection<DateFormat> */
$date_formats = app('date_formats');
// $date_formats = Cache::get('date_formats');
// if (! $date_formats) {
// $this->buildCache(true);
// }
return $date_formats->first(function ($item) {
/** @var \stdClass $item */
return $item->id == $this->getSetting('date_format_id');
})->format;
}
@ -430,17 +419,10 @@ class Client extends BaseModel implements HasLocalePreference
public function currency()
{
/** @var \Illuminate\Support\Collection $currencies */
/** @var \Illuminate\Support\Collection<Currency> */
$currencies = app('currencies');
// $currencies = Cache::get('currencies');
// if (! $currencies) {
// $this->buildCache(true);
// }
return $currencies->first(function ($item) {
/** @var \stdClass $item */
return $item->id == $this->getSetting('currency_id');
});
}
@ -751,16 +733,6 @@ class Client extends BaseModel implements HasLocalePreference
public function preferredLocale()
{
$this->language()->locale ?? 'en';
// $languages = app('languages');
// $languages = Cache::get('languages');
// if (! $languages) {
// $this->buildCache(true);
// }
// return $languages->first(function ($item) {
// return $item->id == $this->getSetting('language_id');
// })->locale;
}
public function backup_path(): string

View File

@ -271,15 +271,13 @@ class ClientContact extends Authenticatable implements HasLocalePreference
public function preferredLocale()
{
$languages = Cache::get('languages');
/** @var \Illuminate\Support\Collection<\App\Models\Language> */
$languages = app('languages');
if (! $languages) {
$this->buildCache(true);
}
return $languages->filter(function ($item) {
return $languages->first(function ($item) {
return $item->id == $this->client->getSetting('language_id');
})->first()->locale;
})->locale;
}
public function routeNotificationForMail($notification)

View File

@ -636,24 +636,13 @@ class Company extends BaseModel
public function country()
{
/** @var \Illuminate\Support\Collection<\App\Models\Country> */
$countries = app('countries');
// $countries = Cache::get('countries');
// if (! $companies) {
// $this->buildCache(true);
// $companies = Cache::get('countries');
// }
return $countries->first(function ($item) {
/** @var \stdClass $item */
return $item->id == $this->getSetting('country_id');
});
// return $this->belongsTo(Country::class);
// return Country::find($this->settings->country_id);
}
public function group_settings()
@ -663,20 +652,14 @@ class Company extends BaseModel
public function timezone()
{
// $timezones = Cache::get('timezones');
/** @var \Illuminate\Support\Collection<\App\Models\TimeZone> */
$timezones = app('timezones');
// if (! $timezones) {
// $this->buildCache(true);
// }
return $timezones->first(function ($item) {
/** @var \stdClass $item */
return $item->id == $this->settings->timezone_id;
});
// return Timezone::find($this->settings->timezone_id);
}
public function designs()
@ -701,22 +684,15 @@ class Company extends BaseModel
public function language()
{
$languages = Cache::get('languages');
/** @var \Illuminate\Support\Collection<\App\Models\Language> */
$languages = app('languages');
//build cache and reinit
if (! $languages) {
$this->buildCache(true);
$languages = Cache::get('languages');
}
//if the cache is still dead, get from DB
if (!$languages && property_exists($this->settings, 'language_id')) {
return Language::find($this->settings->language_id);
}
return $languages->filter(function ($item) {
$language = $languages->first(function ($item) {
return $item->id == $this->settings->language_id;
})->first();
});
return $language ?? $languages->first();
}
public function getLocale()
@ -757,11 +733,13 @@ class Company extends BaseModel
public function currency()
{
$currencies = Cache::get('currencies');
/** @var \Illuminate\Support\Collection<\App\Models\Currency> */
$currencies = app('currencies');
return $currencies->filter(function ($item) {
return $currencies->first(function ($item) {
return $item->id == $this->settings->currency_id;
})->first();
});
}
/**
@ -974,15 +952,13 @@ class Company extends BaseModel
public function date_format()
{
$date_formats = Cache::get('date_formats');
/** @var \Illuminate\Support\Collection<\App\Models\DateFormat> */
$date_formats = app('date_formats');
if (! $date_formats) {
$this->buildCache(true);
}
return $date_formats->filter(function ($item) {
return $date_formats->first(function ($item) {
return $item->id == $this->getSetting('date_format_id');
})->first()->format;
})->format;
}
public function getInvoiceCert()

View File

@ -130,7 +130,6 @@ use Laracasts\Presenter\PresentableTrait;
* @property-read \Illuminate\Database\Eloquent\Collection<int, \App\Models\InvoiceInvitation> $invitations
* @property-read \Illuminate\Database\Eloquent\Collection<int, \App\Models\Payment> $payments
* @property-read \Illuminate\Database\Eloquent\Collection<int, \App\Models\Task> $tasks
* @method static \Illuminate\Database\Eloquent\Builder|BaseModel company()
* @property object|null $tax_data
* @mixin \Eloquent
*/

View File

@ -58,7 +58,7 @@ use Illuminate\Database\Eloquent\SoftDeletes;
* @property int|null $exchange_currency_id
* @property \App\Models\Paymentable $paymentable
* @property object|null $meta
* @property object|null $refund_meta
* @property array|null $refund_meta
* @property string|null $custom_value1
* @property string|null $custom_value2
* @property string|null $custom_value3

View File

@ -60,7 +60,7 @@ use Laracasts\Presenter\PresentableTrait;
* @property bool $is_deleted
* @property string|null $last_login
* @property string|null $signature
* @property string $password
* @property string|null $password
* @property string $language_id
* @property string|null $remember_token
* @property string|null $custom_value1
@ -264,6 +264,7 @@ class User extends Authenticatable implements MustVerifyEmail
{
$truth = app()->make(TruthSource::class);
// @phpstan-ignore-next-line
if ($this->company) {
return $this->company;
} elseif ($truth->getCompany()) {

View File

@ -177,19 +177,17 @@ class Vendor extends BaseModel
public function currency()
{
$currencies = Cache::get('currencies');
if (! $currencies) {
$this->buildCache(true);
}
/** @var \Illuminate\Support\Collection<\App\Models\Currency> */
$currencies = app('currencies');
if (! $this->currency_id) {
return $this->company->currency();
}
return $currencies->filter(function ($item) {
return $currencies->first(function ($item) {
return $item->id == $this->currency_id;
})->first();
});
}
public function timezone()

View File

@ -183,11 +183,13 @@ class VendorContact extends Authenticatable implements HasLocalePreference
public function preferredLocale()
{
$languages = Cache::get('languages');
/** @var \Illuminate\Support\Collection<\App\Models\Language> */
$languages = app('languages');
return $languages->filter(function ($item) {
return $languages->first(function ($item) {
return $item->id == $this->company->getSetting('language_id');
})->first()->locale;
})->locale;
}
/**

View File

@ -161,11 +161,13 @@ class AuthorizeCustomer
private function getCountryCode($country_code)
{
$countries = Cache::get('countries');
/** @var \Illuminate\Support\Collection<\App\Models\Country> */
$countries = app('countries');
$country = $countries->filter(function ($item) use ($country_code) {
$country = $countries->first(function ($item) use ($country_code) {
return $item->iso_3166_2 == $country_code || $item->iso_3166_3 == $country_code;
})->first();
});
return (string) $country->id;
}

View File

@ -53,7 +53,7 @@ class CreditCard
* Credit card payment page.
*
* @param array $data
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
* @return array
*/
private function threeDParameters(array $data)

View File

@ -354,7 +354,6 @@ class BraintreePaymentDriver extends BaseDriver
return false;
}
return false;
}
private function findTokens(string $gateway_customer_reference)

View File

@ -46,7 +46,7 @@ class CheckoutWebhook implements ShouldQueue
public function handle()
{
nlog("Checkout Webhook");
// nlog("Checkout Webhook");
MultiDB::findAndSetDbByCompanyKey($this->company_key);
@ -56,6 +56,7 @@ class CheckoutWebhook implements ShouldQueue
nlog("Checkout Webhook type not set");
}
/** @phpstan-ignore-next-line */
match($this->webhook_array['type']) {
'payment_approved' => $this->paymentApproved(),
};

View File

@ -103,6 +103,7 @@ class PayPalBasePaymentDriver extends BaseDriver
"25" => $method = PaymentType::VENMO,
"28" => $method = PaymentType::PAY_LATER,
"29" => $method = PaymentType::CREDIT_CARD_OTHER,
default => $method = PaymentType::PAYPAL,
};
return $method;
@ -114,8 +115,16 @@ class PayPalBasePaymentDriver extends BaseDriver
$this->api_endpoint_url = $this->company_gateway->getConfigField('testMode') ? 'https://api-m.sandbox.paypal.com' : 'https://api-m.paypal.com';
$secret = $this->company_gateway->getConfigField('secret');
$client_id = $this->company_gateway->getConfigField('clientId');
if(\App\Utils\Ninja::isHosted()) {
$secret = config('ninja.paypal.secret');
$client_id = config('ninja.paypal.client_id');
}
else {
$secret = $this->company_gateway->getConfigField('secret');
$client_id = $this->company_gateway->getConfigField('clientId');
}
if($this->access_token && $this->token_expiry && $this->token_expiry->isFuture()) {
return $this;
@ -186,7 +195,7 @@ class PayPalBasePaymentDriver extends BaseDriver
{
return '';
/** @var \App\Models\ClientGatewayToken $cgt */
/** @var ?\App\Models\ClientGatewayToken $cgt */
$cgt = ClientGatewayToken::where('company_gateway_id', $this->company_gateway->id)
->where('client_id', $this->client->id)
->first();
@ -442,11 +451,11 @@ class PayPalBasePaymentDriver extends BaseDriver
switch ($response['name']) {
case 'NOT_AUTHORIZED':
throw new PaymentFailed("There was a permissions issue processing this payment, please contact the merchant. ", 401);
break;
default:
throw new PaymentFailed("Unknown error occurred processing payment. Please contact merchant.", 500);
break;
}
}

View File

@ -63,7 +63,7 @@ class PayPalWebhook implements ShouldQueue
if($this->verifyWebhook()) {
nlog('verified');
match($this->webhook_request['event_type']) {
match($this->webhook_request['event_type']) {//@phpstan-ignore-line
'CHECKOUT.ORDER.COMPLETED' => $this->checkoutOrderCompleted(),
};
@ -307,7 +307,7 @@ class PayPalWebhook implements ShouldQueue
});
return $gateway ?? false;
return $gateway ?? null;
}
//--------------------------------------------------------------------------------------//

View File

@ -284,6 +284,10 @@ class PayPalPPCPPaymentDriver extends PayPalBasePaymentDriver
$r = $this->gatewayRequest('/v2/checkout/orders', 'post', $order);
if(!isset($r->json()['id'])) {
$this->handleProcessingFailure($r->json());
}
$this->payment_hash->withData("orderID", $r->json()['id']);
return $r->json()['id'];

View File

@ -344,8 +344,6 @@ class ACH
return redirect()->route('client.payment_methods.verification', ['payment_method' => $cgt->hashed_id, 'method' => GatewayType::BANK_TRANSFER]);
$data['message'] = 'Invalid parameters were supplied to Stripe\'s API';
break;
case $e instanceof AuthenticationException:
$data['message'] = 'Authentication with Stripe\'s API failed';
break;

View File

@ -80,7 +80,7 @@ class BankTransfer
*/
private function resolveBankType()
{
return match ($this->stripe->client->currency()->code) {
return match ($this->stripe->client->currency()->code) { //@phpstan-ignore-line
'GBP' => ['type' => 'gb_bank_transfer'],
'EUR' => ['type' => 'eu_bank_transfer', 'eu_bank_transfer' => ['country' => $this->stripe->client->country->iso_3166_2]],
'JPY' => ['type' => 'jp_bank_transfer'],
@ -128,8 +128,8 @@ class BankTransfer
}
/* Create a pending payment */
if ($pi->status == 'requires_action' && $pi->next_action->type == 'display_bank_transfer_instructions') {
match ($pi->next_action->display_bank_transfer_instructions->currency) {
if ($pi->status == 'requires_action' && $pi->next_action->type == 'display_bank_transfer_instructions') { //@phpstan-ignore-line
match ($pi->next_action->display_bank_transfer_instructions->currency) { //@phpstan-ignore-line
'mxn' => $data['bank_details'] = $this->formatDataforMx($pi),
'gbp' => $data['bank_details'] = $this->formatDataforUk($pi),
'eur' => $data['bank_details'] = $this->formatDataforEur($pi),

View File

@ -489,11 +489,7 @@ class StripePaymentDriver extends BaseDriver
{
$customer = Customer::retrieve($customer_id, $this->stripe_connect_auth);
if ($customer) {
return $customer;
}
return null;
return $customer ?? null;
}
/**

View File

@ -53,7 +53,7 @@ class WePayPaymentDriver extends BaseDriver
throw new \Exception("Gateway no longer supported", 500);
return $this;
// return $this;
}
/**

View File

@ -33,56 +33,61 @@ class StaticServiceProvider extends ServiceProvider
*/
public function register()
{
/** @return \Illuminate\Support\Collection<Currency> */
app()->singleton('currencies', function ($app) {
return Currency::query()->orderBy('name')->get();
});
/** @return \Illuminate\Support\Collection<Language> */
app()->singleton('languages', function ($app) {
return Language::query()->orderBy('name')->get();
});
/** @return \Illuminate\Support\Collection<Country> */
app()->singleton('countries', function ($app) {
return Country::query()->orderBy('name')->get();
});
/** @return \Illuminate\Support\Collection<PaymentTerm> */
app()->singleton('payment_types', function ($app) {
return PaymentTerm::query()->orderBy('num_days')->get();
});
/** @return \Illuminate\Support\Collection<Industry> */
app()->singleton('industries', function ($app) {
return Industry::query()->orderBy('name')->get();
});
/** @return \Illuminate\Support\Collection<Bank> */
app()->singleton('banks', function ($app) {
return Bank::query()->orderBy('name')->get();
});
/** @return \Illuminate\Support\Collection<DateFormat> */
app()->singleton('date_formats', function ($app) {
return DateFormat::query()->orderBy('id')->get();
});
/** @return \Illuminate\Support\Collection<Timezone> */
app()->singleton('timezones', function ($app) {
return Timezone::query()->orderBy('id')->get();
});
/** @return \Illuminate\Support\Collection<Gateway> */
app()->singleton('gateways', function ($app) {
return Gateway::query()->orderBy('id')->get();
});
/** @return \Illuminate\Support\Collection<Industry> */
app()->singleton('industries', function ($app) {
return Industry::query()->orderBy('id')->get();
});
/** @return \Illuminate\Support\Collection<Size> */
app()->singleton('sizes', function ($app) {
return Size::query()->orderBy('id')->get();
});
/** @deprecated */
app()->singleton('banks', function ($app) {
return Bank::query()->orderBy('id')->get();
});
app()->singleton('templates', function ($app) {
return [

View File

@ -59,7 +59,7 @@ class PaymentRepository extends BaseRepository
* @param Payment $payment The $payment entity
* @return Payment The updated/created payment object
*/
private function applyPayment(array $data, Payment $payment): ?Payment
private function applyPayment(array $data, Payment $payment): Payment
{
$is_existing_payment = true;
$client = false;

View File

@ -57,7 +57,9 @@ class ChartService
/* Merge and filter by unique */
$currencies = $currencies->merge($expense_currencies)->unique();
$cache_currencies = Cache::get('currencies');
/** @var \Illuminate\Support\Collection<\App\Models\Currency> */
$cache_currencies = app('currencies');
$filtered_currencies = $cache_currencies->whereIn('id', $currencies)->all();
@ -162,7 +164,9 @@ class ChartService
private function addCurrencyCodes($data_set): array
{
$currencies = Cache::get('currencies');
/** @var \Illuminate\Support\Collection<\App\Models\Currency> */
$currencies = app('currencies');
foreach ($data_set as $key => $value) {
$data_set[$key]->currency_id = str_replace('"', '', $value->currency_id);

View File

@ -53,7 +53,9 @@ class ChartServiceLegacy
/* Merge and filter by unique */
$currencies = $currencies->merge($expense_currencies)->unique();
$cache_currencies = Cache::get('currencies');
/** @var \Illuminate\Support\Collection<\App\Models\Currency> */
$cache_currencies = app('currencies');
$filtered_currencies = $cache_currencies->whereIn('id', $currencies)->all();
@ -135,7 +137,9 @@ class ChartServiceLegacy
private function addCurrencyCodes($data_set): array
{
$currencies = Cache::get('currencies');
/** @var \Illuminate\Support\Collection<\App\Models\Currency> */
$currencies = app('currencies');
foreach ($data_set as $key => $value) {
$data_set[$key]->currency_id = str_replace('"', '', $value->currency_id);

View File

@ -219,27 +219,6 @@ class CreditService
public function deletePdf()
{
$this->credit->invitations->each(function ($invitation) {
// (new UnlinkFile(config('filesystems.default'), $this->credit->client->credit_filepath($invitation).$this->credit->numberFormatter().'.pdf'))->handle();
//30-06-2023
try {
// if (Storage::disk(config('filesystems.default'))->exists($this->invoice->client->invoice_filepath($invitation).$this->invoice->numberFormatter().'.pdf')) {
Storage::disk(config('filesystems.default'))->delete($this->credit->client->credit_filepath($invitation).$this->credit->numberFormatter().'.pdf');
// }
// if (Ninja::isHosted() && Storage::disk('public')->exists($this->invoice->client->invoice_filepath($invitation).$this->invoice->numberFormatter().'.pdf')) {
if (Ninja::isHosted()) {
Storage::disk('public')->delete($this->credit->client->credit_filepath($invitation).$this->credit->numberFormatter().'.pdf');
}
} catch (\Exception $e) {
nlog($e->getMessage());
}
});
return $this;
}
@ -273,11 +252,14 @@ class CreditService
public function deleteCredit()
{
$paid_to_date = $this->credit->invoice_id ? $this->credit->balance : 0;
$this->credit
->client
->service()
->adjustCreditBalance($this->credit->balance * -1)
->save();
->client
->service()
->updatePaidToDate($paid_to_date)
->adjustCreditBalance($this->credit->balance * -1)
->save();
return $this;
}
@ -285,9 +267,13 @@ class CreditService
public function restoreCredit()
{
$paid_to_date = $this->credit->invoice_id ? $this->credit->balance : 0;
$this->credit
->client
->service()
->updatePaidToDate($paid_to_date * -1)
->adjustCreditBalance($this->credit->balance)
->save();

View File

@ -405,7 +405,7 @@ class RoEInvoice extends AbstractService
/**
* @param $item
* @param $invoice_total
* @return float|int
* @return float
*/
private function getItemTaxable($item, $invoice_total)
{

View File

@ -406,7 +406,7 @@ class EmailDefaults
* @param string $markdown The body to convert
* @return string The parsed markdown response
*/
private function parseMarkdownToHtml(string $markdown): ?string
private function parseMarkdownToHtml(string $markdown): string
{
$converter = new CommonMarkConverter([
'allow_unsafe_links' => false,

View File

@ -993,6 +993,7 @@ class PdfBuilder
PdfService::DELIVERY_NOTE => $this->getDeliveryNoteSections(),
PdfService::STATEMENT => $this->getStatementSections(),
PdfService::PURCHASE_ORDER => $this->getPurchaseOrderSections(),
default => $this->getProductSections(),
};
}

View File

@ -457,15 +457,13 @@ class PdfConfiguration
*/
public function setDateFormat(): self
{
$date_formats = Cache::get('date_formats');
/** @var \Illuminate\Support\Collection<\App\Models\DateFormat> */
$date_formats = app('date_formats');
if (! $date_formats) {
$this->buildCache(true);
}
$this->date_format = $date_formats->filter(function ($item) {
$this->date_format = $date_formats->first(function ($item) {
return $item->id == $this->settings->date_format_id;
})->first()->format;
})->format;
return $this;
}

View File

@ -174,7 +174,8 @@ class PdfMock
match ($this->request['settings_type']) {
'group' => $settings = ClientSettings::buildClientSettings($this->company->settings, $this->request['settings']),
'client' => $settings = ClientSettings::buildClientSettings($this->company->settings, $this->request['settings']),
'company' => $settings = (object)$this->request['settings']
'company' => $settings = (object)$this->request['settings'],
default => $settings = (object)$this->request['settings'],
};
$settings = CompanySettings::setProperties($settings);

View File

@ -46,9 +46,9 @@ class EmailReport
use MakesHash;
use MakesDates;
private Client $client;
// private Client $client;
private bool $multiple_clients = false;
// private bool $multiple_clients = false;
private string $file_name = 'file.csv';
@ -66,6 +66,7 @@ class EmailReport
$data['end_date'] = $start_end_dates[1];
$data['date_range'] = $data['date_range'] ?? 'all';
$data['report_keys'] = $data['report_keys'] ?? [];
$data['include_deleted'] = $data['include_deleted'] ?? false;
$export = false;

View File

@ -117,7 +117,7 @@ class PaymentLinkService
/* 06-04-2022 */
/* We may not be in a state where the user is present */
if (auth()->guard('contact')) {
if (auth()->guard('contact')->user()) {
return $this->handleRedirect('/client/invoices/' . $this->encodePrimaryKey($payment_hash->fee_invoice_id));
}
}

View File

@ -225,9 +225,9 @@ class TaxProvider
{
throw new \Exception("No tax region defined for this country");
$this->provider = EuTax::class;
// $this->provider = EuTax::class;
return $this;
// return $this;
}
/**

View File

@ -102,6 +102,7 @@ class TemplateAction implements ShouldQueue
Expense::class => $resource->with('client'),
Payment::class => $resource->with('invoices', 'client'),
Client::class => $resource,
default => $resource,
};
$result = $resource->withTrashed()
@ -219,6 +220,7 @@ class TemplateAction implements ShouldQueue
Project::class => 'projects',
Client::class => 'clients',
Vendor::class => 'vendors',
default =>'invoices',
};
}

View File

@ -124,7 +124,7 @@ class TemplateService
$this->twig->addFilter($filter);
$allowedTags = ['if', 'for', 'set', 'filter'];
$allowedFilters = ['escape', 'e', 'upper', 'lower', 'capitalize', 'filter', 'length', 'merge','format_currency','map', 'join', 'first', 'date','sum'];
$allowedFilters = ['escape', 'e', 'upper', 'lower', 'capitalize', 'filter', 'length', 'merge','format_currency', 'format_number','format_percent_number','map', 'join', 'first', 'date','sum'];
$allowedFunctions = ['range', 'cycle', 'constant', 'date',];
$allowedProperties = ['type_id'];
$allowedMethods = ['img','t'];
@ -306,9 +306,6 @@ class TemplateService
} catch(SyntaxError $e) {
nlog($e->getMessage());
throw ($e);
} catch(Error $e) {
nlog("error = " . $e->getMessage());
throw ($e);
} catch(RuntimeError $e) {
nlog("runtime = " . $e->getMessage());
throw ($e);
@ -318,8 +315,11 @@ class TemplateService
} catch(SecurityError $e) {
nlog("security = " . $e->getMessage());
throw ($e);
} catch(Error $e) {
nlog("error = " . $e->getMessage());
throw ($e);
}
$template = $template->render($this->data);
$f = $this->document->createDocumentFragment();
@ -620,8 +620,6 @@ class TemplateService
private function transformPayment(Payment $payment): array
{
$data = [];
$this->payment = $payment;
$credits = $payment->credits->map(function ($credit) use ($payment) {
@ -694,8 +692,6 @@ class TemplateService
'refund_activity' => $this->getPaymentRefundActivity($payment),
];
return $data;
}
/**
@ -1196,6 +1192,7 @@ class TemplateService
'company-details' => $this->companyDetails($stack['labels'] == 'true'),
'company-address' => $this->companyAddress($stack['labels'] == 'true'),
'shipping-details' => $this->shippingDetails($stack['labels'] == 'true'),
default => $this->entityDetails(),
};
$this->save();

View File

@ -47,11 +47,11 @@ class ProjectTransformer extends EntityTransformer
{
$transformer = new DocumentTransformer($this->serializer);
if($project->documents) {
// if($project->documents->count() > 0) {
return $this->includeCollection($project->documents, $transformer, Document::class);
}
// }
return null;
// return null;
}
public function includeClient(Project $project): ?\League\Fractal\Resource\Item

View File

@ -63,8 +63,9 @@ class UserTransformer extends EntityTransformer
'has_password' => (bool) empty($user->password) ? false : true,
'oauth_user_token' => empty($user->oauth_user_token) ? '' : '***',
'verified_phone_number' => (bool) $user->verified_phone_number,
'language_id' => (string) $user->language_id ?? '',
'language_id' => (string) $user->language_id ?: '',
'user_logged_in_notification' => (bool) $user->user_logged_in_notification,
'referral_code' => (string) $user->referral_code,
];
}

View File

@ -97,15 +97,15 @@ class Helpers
switch ($custom_field) {
case 'date':
return is_null($entity) ? $value : $this->translateDate($value, $entity->date_format(), $entity->locale());
break;
case 'switch':
return trim($value ?? '') == 'yes' ? ctrans('texts.yes') : ctrans('texts.no');
break;
default:
return is_null($value) ? '' : $this->processReservedKeywords($value, $entity);
break;
}
}
@ -252,7 +252,7 @@ class Helpers
continue;
}
if (Str::contains($match, '|')) {
// if (Str::contains($match, '|')) {
$parts = explode('|', $match); // [ '[MONTH', 'MONTH+2]' ]
$left = substr($parts[0], 1); // 'MONTH'
@ -290,7 +290,7 @@ class Helpers
$value,
1
);
}
// }
}
// Second case with more common calculations.

View File

@ -45,7 +45,7 @@ class HtmlEngine
/** @var \App\Models\Client $client */
public $client;
/** @var \App\Models\ClientContact $contact */
/** @var ?\App\Models\ClientContact $contact */
public $contact;
/** @var \App\Models\Company $company */
@ -120,7 +120,7 @@ class HtmlEngine
{
if (! $this->client->currency()) {
throw new Exception(debug_backtrace()[1]['function'], 1);
exit;
// exit;
}
App::forgetInstance('translator');
@ -132,10 +132,10 @@ class HtmlEngine
$data['$global_margin'] = ['value' => '6.35mm', 'label' => ''];
$data['$company_logo_size'] = ['value' => $this->resolveCompanyLogoSize(), 'label' => ''];
$data['$show_shipping_address'] = ['value' => $this->settings?->show_shipping_address ? 'flex' : 'none', 'label' => ''];
$data['$show_shipping_address_block'] = ['value' => $this->settings?->show_shipping_address ? 'block' : 'none', 'label' => ''];
$data['$show_shipping_address'] = ['value' => $this->settings->show_shipping_address ? 'flex' : 'none', 'label' => ''];
$data['$show_shipping_address_block'] = ['value' => $this->settings->show_shipping_address ? 'block' : 'none', 'label' => ''];
// $data['$show_shipping_address_visibility'] = ['value' => $this->settings?->show_shipping_address ? 'visible' : 'hidden', 'label' => ''];
$data['$show_shipping_address_visibility'] = ['value' => $this->settings?->show_shipping_address ? 1 : 0, 'label' => ''];
$data['$show_shipping_address_visibility'] = ['value' => $this->settings->show_shipping_address ? 1 : 0, 'label' => ''];
$data['$order_number'] = ['value' => '', 'label' => ctrans('texts.order_number')];
$data['$tax'] = ['value' => '', 'label' => ctrans('texts.tax')];
@ -226,7 +226,7 @@ class HtmlEngine
$data['$status_logo'] = ['value' => '<div class="stamp is-paid"> ' . ctrans('texts.paid') .'</div>', 'label' => ''];
$data['$show_paid_stamp'] = ['value' => $this->entity->status_id == 4 && $this->settings?->show_paid_stamp ? 'flex' : 'none', 'label' => ''];
$data['$show_paid_stamp'] = ['value' => $this->entity->status_id == 4 && $this->settings->show_paid_stamp ? 'flex' : 'none', 'label' => ''];
if ($this->entity->vendor) {
$data['$invoice.vendor'] = ['value' => $this->entity->vendor->present()->name(), 'label' => ctrans('texts.vendor_name')];
@ -775,8 +775,7 @@ class HtmlEngine
return '';
}
return
collect($payment->refund_meta)
return collect($payment->refund_meta)
->map(function ($refund) use ($payment) {
$date = \Carbon\Carbon::parse($refund['date'] ?? $payment->date)->addSeconds($payment->client->timezone_offset());
@ -919,39 +918,30 @@ class HtmlEngine
private function getCountryName(): string
{
$countries = Cache::get('countries');
/** @var \Illuminate\Support\Collection<\App\Models\Country> */
$countries = app('countries');
if (! $countries) {
$this->buildCache(true);
$country = $countries->first(function ($item) {
return $item->id == $this->settings->country_id;
});
$countries = Cache::get('countries');
}
if ($countries) {
$country = $countries->filter(function ($item) {
return $item->id == $this->settings->country_id;
})->first();
} else {
$country = Country::find($this->settings->country_id);
}
if ($country) {
return ctrans('texts.country_' . $country->name);
}
return ' ';
return $country ? ctrans('texts.country_' . $country->name) : ctrans('texts.country_' . $countries->first()->name);
}
private function getCountryCode(): string
{
$country = Country::find($this->settings->country_id);
if ($country) {
return $country->iso_3166_2;
}
return ' ';
/** @var \Illuminate\Support\Collection<\App\Models\Country> */
$countries = app('countries');
$country = $countries->first(function ($item) {
return $item->id == $this->settings->country_id;
});
return $country ? $country->iso_3166_2 : ' ';
}
/**
* Due to the way we are compiling the blade template we
@ -962,20 +952,20 @@ class HtmlEngine
* @return string a collection of <tr> rows with line item
* aggregate data
*/
private function makeLineTaxes(): string
{
$tax_map = $this->entity_calc->getTaxMap();
// private function makeLineTaxes(): string
// {
// $tax_map = $this->entity_calc->getTaxMap();
$data = '';
// $data = '';
foreach ($tax_map as $tax) {
$data .= '<tr class="line_taxes">';
$data .= '<td>'.$tax['name'].'</td>';
$data .= '<td>'.Number::formatMoney($tax['total'], $this->client).'</td></tr>';
}
// foreach ($tax_map as $tax) {
// $data .= '<tr class="line_taxes">';
// $data .= '<td>'.$tax['name'].'</td>';
// $data .= '<td>'.Number::formatMoney($tax['total'], $this->client).'</td></tr>';
// }
return $data;
}
// return $data;
// }
private function lineTaxValues(): string
{
@ -990,30 +980,30 @@ class HtmlEngine
return $data;
}
private function makeTotalTaxes(): string
{
$data = '';
// private function makeTotalTaxes(): string
// {
// $data = '';
if (! $this->entity_calc->getTotalTaxMap()) {
return $data;
}
// if (! $this->entity_calc->getTotalTaxMap()) {
// return $data;
// }
foreach ($this->entity_calc->getTotalTaxMap() as $tax) {
$data .= '<tr>';
$data .= '<td colspan="{ count($this->entity->company->settings->pdf_variables->total_columns) - 2 }"></td>';
$data .= '<td>'.$tax['name'].'</td>';
$data .= '<td>'.Number::formatMoney($tax['total'], $this->client).'</td></tr>';
}
// foreach ($this->entity_calc->getTotalTaxMap() as $tax) {
// $data .= '<tr>';
// $data .= '<td colspan="{ count($this->entity->company->settings->pdf_variables->total_columns) - 2 }"></td>';
// $data .= '<td>'.$tax['name'].'</td>';
// $data .= '<td>'.Number::formatMoney($tax['total'], $this->client).'</td></tr>';
// }
return $data;
}
// return $data;
// }
private function parseLabelsAndValues($labels, $values, $section): string
{
$section = strtr($section, $labels);
// private function parseLabelsAndValues($labels, $values, $section): string
// {
// $section = strtr($section, $labels);
return strtr($section, $values);
}
// return strtr($section, $values);
// }
/*
| Ensures the URL doesn't have duplicated trailing slash
@ -1029,98 +1019,98 @@ class HtmlEngine
* of Repeating headers and footers on the PDF.
* @return string The css string
*/
private function generateCustomCSS(): string
{
$header_and_footer = '
.header, .header-space {
height: 160px;
}
// private function generateCustomCSS(): string
// {
// $header_and_footer = '
// .header, .header-space {
// height: 160px;
// }
.footer, .footer-space {
height: 160px;
}
// .footer, .footer-space {
// height: 160px;
// }
.footer {
position: fixed;
bottom: 0;
width: 100%;
}
// .footer {
// position: fixed;
// bottom: 0;
// width: 100%;
// }
.header {
position: fixed;
top: 0mm;
width: 100%;
}
// .header {
// position: fixed;
// top: 0mm;
// width: 100%;
// }
@media print {
thead {display: table-header-group;}
tfoot {display: table-footer-group;}
button {display: none;}
body {margin: 0;}
}';
// @media print {
// thead {display: table-header-group;}
// tfoot {display: table-footer-group;}
// button {display: none;}
// body {margin: 0;}
// }';
$header = '
.header, .header-space {
height: 160px;
}
// $header = '
// .header, .header-space {
// height: 160px;
// }
.header {
position: fixed;
top: 0mm;
width: 100%;
}
// .header {
// position: fixed;
// top: 0mm;
// width: 100%;
// }
@media print {
thead {display: table-header-group;}
button {display: none;}
body {margin: 0;}
}';
// @media print {
// thead {display: table-header-group;}
// button {display: none;}
// body {margin: 0;}
// }';
$footer = '
// $footer = '
.footer, .footer-space {
height: 160px;
}
// .footer, .footer-space {
// height: 160px;
// }
.footer {
position: fixed;
bottom: 0;
width: 100%;
}
// .footer {
// position: fixed;
// bottom: 0;
// width: 100%;
// }
@media print {
tfoot {display: table-footer-group;}
button {display: none;}
body {margin: 0;}
}';
$css = '';
// @media print {
// tfoot {display: table-footer-group;}
// button {display: none;}
// body {margin: 0;}
// }';
// $css = '';
if ($this->settings->all_pages_header && $this->settings->all_pages_footer) {
$css .= $header_and_footer;
} elseif ($this->settings->all_pages_header && ! $this->settings->all_pages_footer) {
$css .= $header;
} elseif (! $this->settings->all_pages_header && $this->settings->all_pages_footer) {
$css .= $footer;
}
// if ($this->settings->all_pages_header && $this->settings->all_pages_footer) {
// $css .= $header_and_footer;
// } elseif ($this->settings->all_pages_header && ! $this->settings->all_pages_footer) {
// $css .= $header;
// } elseif (! $this->settings->all_pages_header && $this->settings->all_pages_footer) {
// $css .= $footer;
// }
$css .= '
.page {
page-break-after: always;
}
// $css .= '
// .page {
// page-break-after: always;
// }
@page {
margin: 0mm
}
// @page {
// margin: 0mm
// }
html {
';
// html {
// ';
$css .= 'font-size:'.$this->settings->font_size.'px;';
// $css .= 'font-size:'.$this->settings->font_size.'px;';
$css .= '}';
// $css .= '}';
return $css;
}
// return $css;
// }
/**
* Generate markup for HTML images on entity.
@ -1200,14 +1190,14 @@ html {
';
return '
<table border="0" cellspacing="0" cellpadding="0" align="center">
<tr style="border: 0 !important; ">
<td class="new_button" style="padding: 12px 18px 12px 18px; border-radius:5px;" align="center">
<a href="'. $link .'" target="_blank" style="border: 0 !important;font-size: 18px; font-family: Helvetica, Arial, sans-serif; color: #ffffff; text-decoration: none; display: inline-block;">'. $text .'</a>
</td>
</tr>
</table>
';
// return '
// <table border="0" cellspacing="0" cellpadding="0" align="center">
// <tr style="border: 0 !important; ">
// <td class="new_button" style="padding: 12px 18px 12px 18px; border-radius:5px;" align="center">
// <a href="'. $link .'" target="_blank" style="border: 0 !important;font-size: 18px; font-family: Helvetica, Arial, sans-serif; color: #ffffff; text-decoration: none; display: inline-block;">'. $text .'</a>
// </td>
// </tr>
// </table>
// ';
}
}

View File

@ -355,14 +355,14 @@ class PaymentHtmlEngine
';
return '
<table border="0" cellspacing="0" cellpadding="0" align="center">
<tr style="border: 0 !important; ">
<td class="new_button" style="padding: 12px 18px 12px 18px; border-radius:5px;" align="center">
<a href="'. $link .'" target="_blank" style="border: 0 !important;font-size: 18px; font-family: Helvetica, Arial, sans-serif; color: #ffffff; text-decoration: none; display: inline-block;">'. $text .'</a>
</td>
</tr>
</table>
';
// return '
// <table border="0" cellspacing="0" cellpadding="0" align="center">
// <tr style="border: 0 !important; ">
// <td class="new_button" style="padding: 12px 18px 12px 18px; border-radius:5px;" align="center">
// <a href="'. $link .'" target="_blank" style="border: 0 !important;font-size: 18px; font-family: Helvetica, Arial, sans-serif; color: #ffffff; text-decoration: none; display: inline-block;">'. $text .'</a>
// </td>
// </tr>
// </table>
// ';
}
}

View File

@ -69,62 +69,81 @@ class Statics
{
$data = [];
foreach (config('ninja.cached_tables') as $name => $class) {
if (! Cache::has($name)) {
// check that the table exists in case the migration is pending
if (! Schema::hasTable((new $class())->getTable())) {
continue;
}
if ($name == 'payment_terms') {
$orderBy = 'num_days';
} elseif ($name == 'fonts') {
$orderBy = 'sort_order';
} elseif (in_array($name, ['currencies', 'industries', 'languages', 'countries', 'banks'])) {
$orderBy = 'name';
} else {
$orderBy = 'id';
}
$tableData = $class::orderBy($orderBy)->get();
if ($tableData->count()) {
Cache::forever($name, $tableData);
}
}
// foreach (config('ninja.cached_tables') as $name => $class) {
// if (! Cache::has($name)) {
// // check that the table exists in case the migration is pending
// if (! Schema::hasTable((new $class())->getTable())) {
// continue;
// }
// if ($name == 'payment_terms') {
// $orderBy = 'num_days';
// } elseif ($name == 'fonts') {
// $orderBy = 'sort_order';
// } elseif (in_array($name, ['currencies', 'industries', 'languages', 'countries', 'banks'])) {
// $orderBy = 'name';
// } else {
// $orderBy = 'id';
// }
// $tableData = $class::orderBy($orderBy)->get();
// if ($tableData->count()) {
// Cache::forever($name, $tableData);
// }
// }
$data[$name] = Cache::get($name);
}
// $data[$name] = app($name);
// }
if ($locale) {
$data['industries'] = Cache::get('industries')->each(function ($industry) {
/** @var \Illuminate\Support\Collection<\App\Models\Industry> */
$industries = app('industries');
$data['industries'] = $industries->each(function ($industry) {
$industry->name = ctrans('texts.industry_'.$industry->name);
})->sortBy(function ($industry) {
return $industry->name;
})->values();
$data['countries'] = Cache::get('countries')->each(function ($country) {
/** @var \Illuminate\Support\Collection<\App\Models\Country> */
$countries = app('countries');
$data['countries'] = $countries->each(function ($country) {
$country->name = ctrans('texts.country_'.$country->name);
})->sortBy(function ($country) {
return $country->name;
})->values();
$data['payment_types'] = Cache::get('payment_types')->each(function ($pType) {
/** @var \Illuminate\Support\Collection<\App\Models\PaymentType> */
$payment_types = app('payment_types');
$data['payment_types'] = $payment_types->each(function ($pType) {
$pType->name = ctrans('texts.payment_type_'.$pType->name);
})->sortBy(function ($pType) {
return $pType->name;
})->values();
$data['languages'] = Cache::get('languages')->each(function ($lang) {
/** @var \Illuminate\Support\Collection<\App\Models\Language> */
$payment_types = app('languages');
$data['languages'] = $payment_types->each(function ($lang) {
$lang->name = ctrans('texts.lang_'.$lang->name);
})->sortBy(function ($lang) {
return $lang->name;
})->values();
$data['currencies'] = Cache::get('currencies')->each(function ($currency) {
/** @var \Illuminate\Support\Collection<\App\Models\Currency> */
$currencies = app('currencies');
$data['currencies'] = $currencies->each(function ($currency) {
$currency->name = ctrans('texts.currency_'.Str::slug($currency->name, '_'));
})->sortBy(function ($currency) {
return $currency->name;
})->values();
$data['templates'] = Cache::get('templates');
$data['templates'] = app('templates');
}
$data['bulk_updates'] = [

View File

@ -240,8 +240,10 @@ class TemplateEngine
} else {
$data['signature'] = $this->settings->email_signature;
$data['settings'] = $this->settings;
$data['whitelabel'] = $this->entity_obj ? $this->entity_obj->company->account->isPaid() : true;
$data['company'] = $this->entity_obj ? $this->entity_obj->company : '';
// $data['whitelabel'] = $this->entity_obj ? $this->entity_obj->company->account->isPaid() : true;
// $data['company'] = $this->entity_obj ? $this->entity_obj->company : '';
$data['whitelabel'] = $this->entity_obj->company->account->isPaid();
$data['company'] = $this->entity_obj->company;
$data['settings'] = $this->settings;
}

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