diff --git a/app/Casts/AsTaxEntityCollection.php b/app/Casts/AsTaxEntityCollection.php index d942b4cab2..06286d6b21 100644 --- a/app/Casts/AsTaxEntityCollection.php +++ b/app/Casts/AsTaxEntityCollection.php @@ -1,4 +1,5 @@ null]; } diff --git a/app/Casts/EncryptedCast.php b/app/Casts/EncryptedCast.php index 1fd536dfa7..de0b0b3949 100644 --- a/app/Casts/EncryptedCast.php +++ b/app/Casts/EncryptedCast.php @@ -1,4 +1,5 @@ null]; -} + + if (is_null($value)) { + return [$key => null]; + } -return [ - $key => json_encode([ - 'qb_id' => $value->qb_id, - ]) -]; + return [ + $key => json_encode([ + 'qb_id' => $value->qb_id, + ]) + ]; } diff --git a/app/Casts/PaymentSyncCast.php b/app/Casts/PaymentSyncCast.php index 715b9b7850..eef8d8c432 100644 --- a/app/Casts/PaymentSyncCast.php +++ b/app/Casts/PaymentSyncCast.php @@ -38,7 +38,7 @@ class PaymentSyncCast implements CastsAttributes public function set($model, string $key, $value, array $attributes) { - + if (is_null($value)) { return [$key => null]; } diff --git a/app/Casts/ProductSyncCast.php b/app/Casts/ProductSyncCast.php index d830ca9c04..2687a31f11 100644 --- a/app/Casts/ProductSyncCast.php +++ b/app/Casts/ProductSyncCast.php @@ -1,4 +1,5 @@ null]; -} + + if (is_null($value)) { + return [$key => null]; + } return [ diff --git a/app/Casts/QuickbooksSettingsCast.php b/app/Casts/QuickbooksSettingsCast.php index a0a6e09794..904b5bafaa 100644 --- a/app/Casts/QuickbooksSettingsCast.php +++ b/app/Casts/QuickbooksSettingsCast.php @@ -1,4 +1,5 @@ get() as $design) { - + $invoice_design = new \App\Services\Pdf\DesignExtractor($design->name); $design_object = new stdClass(); diff --git a/app/Console/Commands/EncryptNinja.php b/app/Console/Commands/EncryptNinja.php index fafc14064a..53ff045925 100644 --- a/app/Console/Commands/EncryptNinja.php +++ b/app/Console/Commands/EncryptNinja.php @@ -1,4 +1,5 @@ invitations->count() > 0) { - // event(new InvoiceWasEmailed($invoice->invitations->first(), $invoice->company, Ninja::eventVars(), $reminder_template)); - -event(new \App\Events\General\EntityWasEmailed($invoice->invitations->first(), $invoice->company, Ninja::eventVars(auth()->user() ? auth()->user()->id : null), $reminder_template)); + // event(new InvoiceWasEmailed($invoice->invitations->first(), $invoice->company, Ninja::eventVars(), $reminder_template)); + + event(new \App\Events\General\EntityWasEmailed($invoice->invitations->first(), $invoice->company, Ninja::eventVars(auth()->user() ? auth()->user()->id : null), $reminder_template)); $invoice->entityEmailEvent($invoice->invitations->first(), $reminder_template); } diff --git a/app/Console/Commands/SendTestEmails.php b/app/Console/Commands/SendTestEmails.php index 36fe3d7efd..ea0580781f 100644 --- a/app/Console/Commands/SendTestEmails.php +++ b/app/Console/Commands/SendTestEmails.php @@ -1,4 +1,5 @@ origin_tax_data; - } elseif($this->invoice->location && $this->invoice->location->is_shipping_location && $this->invoice->location->tax_data){ + } elseif ($this->invoice->location && $this->invoice->location->is_shipping_location && $this->invoice->location->tax_data) { $tax_data = $this->invoice->location->tax_data; - + } elseif ($this->client->tax_data) { diff --git a/app/DataMapper/Tax/CY/Rule.php b/app/DataMapper/Tax/CY/Rule.php index dfbce2448a..d50613b6ba 100644 --- a/app/DataMapper/Tax/CY/Rule.php +++ b/app/DataMapper/Tax/CY/Rule.php @@ -1,4 +1,5 @@ $value) { - if($key == 'seller_subregion' && $value == null) { + if ($key == 'seller_subregion' && $value == null) { $value = ''; } @@ -101,7 +102,7 @@ class TaxModel } //@pending Flutter AP upgrade - deploying this breaks the AP. - if($this->version == 'gamma') { + if ($this->version == 'gamma') { $this->regions->EU->subregions->IS = new \stdClass(); $this->regions->EU->subregions->IS->tax_rate = 24; @@ -193,7 +194,7 @@ class TaxModel public function stubVatNumbersOnSubregions(): self { - + // US Subregions $this->regions->US->subregions->AL->vat_number = ''; $this->regions->US->subregions->AK->vat_number = ''; diff --git a/app/DataMapper/Tax/US/Rule.php b/app/DataMapper/Tax/US/Rule.php index fe077ac291..2ded2729b2 100644 --- a/app/DataMapper/Tax/US/Rule.php +++ b/app/DataMapper/Tax/US/Rule.php @@ -1,4 +1,5 @@ credit; } - + public function broadcastIncludes(): array { return [ diff --git a/app/Events/Credit/CreditWasViewed.php b/app/Events/Credit/CreditWasViewed.php index b62f6997e1..3370380e9b 100644 --- a/app/Events/Credit/CreditWasViewed.php +++ b/app/Events/Credit/CreditWasViewed.php @@ -1,4 +1,5 @@ is_amount_discount) && !$entity->is_amount_discount) { + if ($key == 'discount' && isset($entity->is_amount_discount) && !$entity->is_amount_discount) { continue; } diff --git a/app/Export/CSV/ClientExport.php b/app/Export/CSV/ClientExport.php index b7582495a7..6f79d4a07e 100644 --- a/app/Export/CSV/ClientExport.php +++ b/app/Export/CSV/ClientExport.php @@ -1,4 +1,5 @@ csv = Writer::createFromString(); \League\Csv\CharsetConverter::addTo($this->csv, 'UTF-8', 'UTF-8'); - + if ($tax_amount_position = array_search('invoice.total_taxes', $this->input['report_keys'])) { $first_part = array_slice($this->input['report_keys'], 0, $tax_amount_position + 1); $second_part = array_slice($this->input['report_keys'], $tax_amount_position + 1); $labels = []; - - $this->tax_names = $query->get() - ->flatMap(function ($invoice) { - $taxes = []; - /** @var \App\Models\Invoice $invoice */ - // Invoice level taxes - if (!empty($invoice->tax_name1) && !empty($invoice->tax_rate1)) { - $taxes[] = trim($invoice->tax_name1) . ' ' . \App\Utils\Number::formatValueNoTrailingZeroes(floatval($invoice->tax_rate1), $invoice->client) . '%'; - } - if (!empty($invoice->tax_name2) && !empty($invoice->tax_rate2)) { - $taxes[] = trim($invoice->tax_name2) . ' ' . \App\Utils\Number::formatValueNoTrailingZeroes(floatval($invoice->tax_rate2), $invoice->client) . '%'; - } - if (!empty($invoice->tax_name3) && !empty($invoice->tax_rate3)) { - $taxes[] = trim($invoice->tax_name3) . ' ' . \App\Utils\Number::formatValueNoTrailingZeroes(floatval($invoice->tax_rate3), $invoice->client) . '%'; - } + $this->tax_names = $query->get() + ->flatMap(function ($invoice) { + $taxes = []; - // Line item taxes - $line_taxes = collect($invoice->line_items)->flatMap(function ($item) use($invoice){ - $taxes = []; - if (!empty($item->tax_name1) && !empty($item->tax_rate1)) { - $taxes[] = trim($item->tax_name1) . ' ' . \App\Utils\Number::formatValueNoTrailingZeroes(floatval($item->tax_rate1), $invoice->client) . '%'; - } - if (!empty($item->tax_name2) && !empty($item->tax_rate2)) { - $taxes[] = trim($item->tax_name2) . ' ' . \App\Utils\Number::formatValueNoTrailingZeroes(floatval($item->tax_rate2), $invoice->client) . '%'; - } - if (!empty($item->tax_name3) && !empty($item->tax_rate3)) { - $taxes[] = trim($item->tax_name3) . ' ' . \App\Utils\Number::formatValueNoTrailingZeroes(floatval($item->tax_rate3), $invoice->client) . '%'; - } - return $taxes; - }); + /** @var \App\Models\Invoice $invoice */ + // Invoice level taxes + if (!empty($invoice->tax_name1) && !empty($invoice->tax_rate1)) { + $taxes[] = trim($invoice->tax_name1) . ' ' . \App\Utils\Number::formatValueNoTrailingZeroes(floatval($invoice->tax_rate1), $invoice->client) . '%'; + } + if (!empty($invoice->tax_name2) && !empty($invoice->tax_rate2)) { + $taxes[] = trim($invoice->tax_name2) . ' ' . \App\Utils\Number::formatValueNoTrailingZeroes(floatval($invoice->tax_rate2), $invoice->client) . '%'; + } + if (!empty($invoice->tax_name3) && !empty($invoice->tax_rate3)) { + $taxes[] = trim($invoice->tax_name3) . ' ' . \App\Utils\Number::formatValueNoTrailingZeroes(floatval($invoice->tax_rate3), $invoice->client) . '%'; + } - return array_merge($taxes, $line_taxes->toArray()); - }) - ->unique() - ->toArray(); + // Line item taxes + $line_taxes = collect($invoice->line_items)->flatMap(function ($item) use ($invoice) { + $taxes = []; + if (!empty($item->tax_name1) && !empty($item->tax_rate1)) { + $taxes[] = trim($item->tax_name1) . ' ' . \App\Utils\Number::formatValueNoTrailingZeroes(floatval($item->tax_rate1), $invoice->client) . '%'; + } + if (!empty($item->tax_name2) && !empty($item->tax_rate2)) { + $taxes[] = trim($item->tax_name2) . ' ' . \App\Utils\Number::formatValueNoTrailingZeroes(floatval($item->tax_rate2), $invoice->client) . '%'; + } + if (!empty($item->tax_name3) && !empty($item->tax_rate3)) { + $taxes[] = trim($item->tax_name3) . ' ' . \App\Utils\Number::formatValueNoTrailingZeroes(floatval($item->tax_rate3), $invoice->client) . '%'; + } + return $taxes; + }); + + return array_merge($taxes, $line_taxes->toArray()); + }) + ->unique() + ->toArray(); foreach ($this->tax_names as $tax_name) { @@ -196,10 +197,10 @@ class InvoiceExport extends BaseExport if (is_array($parts) && $parts[0] == 'invoice' && array_key_exists($parts[1], $transformed_invoice)) { $entity[$key] = $transformed_invoice[$parts[1]]; - } elseif($decorated_value = $this->decorator->transform($key, $invoice)) { + } elseif ($decorated_value = $this->decorator->transform($key, $invoice)) { $entity[$key] = $decorated_value; - } elseif(count($this->tax_names) > 0) { - + } elseif (count($this->tax_names) > 0) { + $calc = $invoice->calc(); $taxes = $calc->getTaxMap()->merge($calc->getTotalTaxMap())->toArray(); nlog($this->tax_names); @@ -215,7 +216,7 @@ class InvoiceExport extends BaseExport } $entity = $this->decorateAdvancedFields($invoice, $entity); - + return $this->convertFloats($entity); } diff --git a/app/Export/CSV/InvoiceItemExport.php b/app/Export/CSV/InvoiceItemExport.php index 67ddd84dd1..7122759761 100644 --- a/app/Export/CSV/InvoiceItemExport.php +++ b/app/Export/CSV/InvoiceItemExport.php @@ -1,4 +1,5 @@ name = ''; $location->country_id = null; $location->is_deleted = false; - + return $location; } } diff --git a/app/Factory/PaymentFactory.php b/app/Factory/PaymentFactory.php index 1b45b046a8..77e96212f8 100644 --- a/app/Factory/PaymentFactory.php +++ b/app/Factory/PaymentFactory.php @@ -1,4 +1,5 @@ custom_value4 = ''; $product->is_deleted = false; $product->tax_id = 1; - + return $product; } diff --git a/app/Factory/ProjectFactory.php b/app/Factory/ProjectFactory.php index dd5f20d210..e7056aecc0 100644 --- a/app/Factory/ProjectFactory.php +++ b/app/Factory/ProjectFactory.php @@ -1,4 +1,5 @@ e_invoice) + if (!$recurring_invoice->e_invoice) { return null; + } - if(isset($recurring_invoice->e_invoice->Invoice)) { - - if(isset($recurring_invoice->e_invoice->Invoice->InvoicePeriod) && is_array($recurring_invoice->e_invoice->Invoice->InvoicePeriod)) { + if (isset($recurring_invoice->e_invoice->Invoice)) { + + if (isset($recurring_invoice->e_invoice->Invoice->InvoicePeriod) && is_array($recurring_invoice->e_invoice->Invoice->InvoicePeriod)) { $period = $recurring_invoice->e_invoice->Invoice->InvoicePeriod[0]; - - if($description = $period->Description) - { + + if ($description = $period->Description) { $parts = explode('|', $description); - if(count($parts) == 2) - { + if (count($parts) == 2) { $start_template = explode(',', $parts[0]); $end_template = explode(',', $parts[1]); $start_date = date_create('now', new \DateTimeZone($recurring_invoice->client->timezone()->name)); - foreach($start_template as $template) - { + foreach ($start_template as $template) { $start_date->modify($template); } - + $start_date = $start_date->format('Y-m-d'); $end_date = date_create('now', new \DateTimeZone($recurring_invoice->client->timezone()->name)); - foreach($end_template as $template) - { + foreach ($end_template as $template) { $end_date->modify($template); } $end_date = $end_date->format('Y-m-d'); - + $einvoice = new \InvoiceNinja\EInvoice\Models\Peppol\Invoice(); $ip = new \InvoiceNinja\EInvoice\Models\Peppol\PeriodType\InvoicePeriod(); @@ -122,7 +120,7 @@ class RecurringInvoiceToInvoiceFactory $ip->EndDate = new \DateTime($end_date); $einvoice->InvoicePeriod = [$ip]; - + $stub = new \stdClass(); $stub->Invoice = $einvoice; @@ -130,10 +128,10 @@ class RecurringInvoiceToInvoiceFactory } } - + } - + } return null; diff --git a/app/Factory/RecurringQuoteFactory.php b/app/Factory/RecurringQuoteFactory.php index 06c49c798f..e7c17c0da6 100644 --- a/app/Factory/RecurringQuoteFactory.php +++ b/app/Factory/RecurringQuoteFactory.php @@ -1,4 +1,5 @@ builder->getModel()->getTable()))) { return $this->builder; } - + $dir = ($sort_col[1] == 'asc') ? 'asc' : 'desc'; if ($sort_col[0] == 'number') { @@ -185,7 +186,7 @@ class ClientFilters extends QueryFilters if ($sort_col[0] == 'name') { return $this->builder ->select('clients.*') - ->selectSub(function($query) { + ->selectSub(function ($query) { $query->from('client_contacts') ->whereColumn('client_contacts.client_id', 'clients.id') ->whereNull('client_contacts.deleted_at') diff --git a/app/Filters/CompanyGatewayFilters.php b/app/Filters/CompanyGatewayFilters.php index bc21d3b901..b3e7a16bc2 100644 --- a/app/Filters/CompanyGatewayFilters.php +++ b/app/Filters/CompanyGatewayFilters.php @@ -1,4 +1,5 @@ whereColumn('clients.id', 'expenses.client_id'), $sort_col[1]); } - + if ($sort_col[0] == 'project' && in_array($sort_col[1], ['asc', 'desc'])) { return $this->builder ->orderByRaw('ISNULL(project_id), project_id '. $sort_col[1]) diff --git a/app/Filters/GroupSettingFilters.php b/app/Filters/GroupSettingFilters.php index 4da0d93ca0..53616b05fe 100644 --- a/app/Filters/GroupSettingFilters.php +++ b/app/Filters/GroupSettingFilters.php @@ -1,4 +1,5 @@ whereNull('due_date') ->orWhere(function ($q) { - $q->where('due_date', '>=', now()->startOfDay()->subSecond())->where(function ($qq){ + $q->where('due_date', '>=', now()->startOfDay()->subSecond())->where(function ($qq) { $qq->where('partial', 0)->orWhere('balance', '>', 0); }); }) diff --git a/app/Filters/PaymentFilters.php b/app/Filters/PaymentFilters.php index 46afe3778a..a3a99b7198 100644 --- a/app/Filters/PaymentFilters.php +++ b/app/Filters/PaymentFilters.php @@ -1,4 +1,5 @@ builder; - + } + if ($value == 'true') { return $this->builder->where('is_deleted', $value)->withTrashed(); } diff --git a/app/Filters/QuoteFilters.php b/app/Filters/QuoteFilters.php index 14399682cd..37f0a0b32e 100644 --- a/app/Filters/QuoteFilters.php +++ b/app/Filters/QuoteFilters.php @@ -1,4 +1,5 @@ company); - + } diff --git a/app/Helpers/Bank/Nordigen/Transformer/TransactionTransformer.php b/app/Helpers/Bank/Nordigen/Transformer/TransactionTransformer.php index dd38b891c6..f06279a9f7 100644 --- a/app/Helpers/Bank/Nordigen/Transformer/TransactionTransformer.php +++ b/app/Helpers/Bank/Nordigen/Transformer/TransactionTransformer.php @@ -1,4 +1,5 @@ company->e_invoice->Invoice->PaymentMeans) && ($pm = $this->company->e_invoice->Invoice->PaymentMeans[0] ?? false) && in_array($pm->PaymentMeansCode->value, ['30', '58'])) { $iban = $pm->PayeeFinancialAccount->ID->value; $bic = $pm->PayeeFinancialAccount->FinancialInstitutionBranch->FinancialInstitution->ID->value ?? ''; - } - else { - + } else { + $bic = isset($this->company?->custom_fields?->company2) ? $this->company->settings->custom_value2 : ''; $iban = isset($this->company?->custom_fields?->company1) ? $this->company->settings->custom_value1 : ''; - + } $data = [ diff --git a/app/Helpers/Generic.php b/app/Helpers/Generic.php index 6749b3d9ce..2274b01f81 100644 --- a/app/Helpers/Generic.php +++ b/app/Helpers/Generic.php @@ -1,4 +1,5 @@ client->getSetting('enable_e_invoice')) { return $this; } - + collect($this->invoice->line_items) ->flatMap(function ($item) { return collect([1, 2, 3]) @@ -401,8 +402,9 @@ class InvoiceItemSum $key = str_replace(' ', '', $tax_name.$tax_rate); //Handles an edge case where a blank line is entered. - if($tax_rate > 0 && $amount == 0) + if ($tax_rate > 0 && $amount == 0) { return; + } $group_tax = ['key' => $key, 'total' => $tax_total, 'tax_name' => $tax_name.' '.Number::formatValueNoTrailingZeroes(floatval($tax_rate), $this->client).'%', 'tax_id' => $tax_id, 'tax_rate' => $tax_rate, 'base_amount' => $amount]; @@ -428,7 +430,7 @@ class InvoiceItemSum public function setLineTotal($total) { //Here we go! Epsilon in PHP, who would have thunk it.... - $this->item->line_total = round(((float) $total + 0.000000000000004),2); + $this->item->line_total = round(((float) $total + 0.000000000000004), 2); return $this; } diff --git a/app/Helpers/Invoice/InvoiceItemSumInclusive.php b/app/Helpers/Invoice/InvoiceItemSumInclusive.php index 33df617d6a..786efd21fc 100644 --- a/app/Helpers/Invoice/InvoiceItemSumInclusive.php +++ b/app/Helpers/Invoice/InvoiceItemSumInclusive.php @@ -1,4 +1,5 @@ custom_surcharge_map = collect([]); $this->total_discount = 0; - + $this->invoice = $invoice; $this->client = $invoice->client ?? $invoice->vendor; @@ -281,8 +282,8 @@ class InvoiceItemSumInclusive $this->item->tax_amount = $this->formatValue($item_tax, $this->currency->precision); - try{ - $this->item->net_cost = round(($amount - $this->item->tax_amount)/$this->item->quantity, $this->currency->precision); + try { + $this->item->net_cost = round(($amount - $this->item->tax_amount) / $this->item->quantity, $this->currency->precision); } catch (\DivisionByZeroError $e) { $this->item->net_cost = $this->item->cost; } @@ -294,11 +295,11 @@ class InvoiceItemSumInclusive private function getPeppolSurchargeTaxes(): self { - + if (!$this->client->getSetting('enable_e_invoice')) { return $this; } - + $this->custom_surcharge_map = collect([]); collect($this->invoice->line_items) @@ -319,22 +320,22 @@ class InvoiceItemSumInclusive if ($this->invoice->custom_surcharge1) { $tax_component += round($this->invoice->custom_surcharge1 - ($this->invoice->custom_surcharge1 / (1 + ($tax['percentage'] / 100))), 2); - $this->setCustomSurchargeNetMap(['custom_surcharge1' => round($this->invoice->custom_surcharge1 / (1 + ($tax['percentage'] / 100)),2)]); + $this->setCustomSurchargeNetMap(['custom_surcharge1' => round($this->invoice->custom_surcharge1 / (1 + ($tax['percentage'] / 100)), 2)]); } if ($this->invoice->custom_surcharge2) { $tax_component += round($this->invoice->custom_surcharge2 - ($this->invoice->custom_surcharge2 / (1 + ($tax['percentage'] / 100))), 2); - $this->setCustomSurchargeNetMap(['custom_surcharge2' => round($this->invoice->custom_surcharge2 / (1 + ($tax['percentage'] / 100)),2)]); + $this->setCustomSurchargeNetMap(['custom_surcharge2' => round($this->invoice->custom_surcharge2 / (1 + ($tax['percentage'] / 100)), 2)]); } if ($this->invoice->custom_surcharge3) { $tax_component += round($this->invoice->custom_surcharge3 - ($this->invoice->custom_surcharge3 / (1 + ($tax['percentage'] / 100))), 2); - $this->setCustomSurchargeNetMap(['custom_surcharge3' => round($this->invoice->custom_surcharge3 / (1 + ($tax['percentage'] / 100)),2)]); + $this->setCustomSurchargeNetMap(['custom_surcharge3' => round($this->invoice->custom_surcharge3 / (1 + ($tax['percentage'] / 100)), 2)]); } if ($this->invoice->custom_surcharge4) { $tax_component += round($this->invoice->custom_surcharge4 - ($this->invoice->custom_surcharge4 / (1 + ($tax['percentage'] / 100))), 2); - $this->setCustomSurchargeNetMap(['custom_surcharge4' => round($this->invoice->custom_surcharge4 / (1 + ($tax['percentage'] / 100)),2)]); + $this->setCustomSurchargeNetMap(['custom_surcharge4' => round($this->invoice->custom_surcharge4 / (1 + ($tax['percentage'] / 100)), 2)]); } $amount = $this->invoice->custom_surcharge4 + $this->invoice->custom_surcharge3 + $this->invoice->custom_surcharge2 + $this->invoice->custom_surcharge1; @@ -348,7 +349,7 @@ class InvoiceItemSumInclusive return $this; } - private function setCustomSurchargeNetMap(array $surcharge): self + private function setCustomSurchargeNetMap(array $surcharge): self { $this->custom_surcharge_map->push($surcharge); @@ -376,7 +377,7 @@ class InvoiceItemSumInclusive return; } - $group_tax = ['key' => $key, 'total' => $tax_total, 'tax_name' => $tax_name.' '.Number::formatValueNoTrailingZeroes(floatval($tax_rate), $this->client).'%', 'tax_id' => $tax_id, 'tax_rate' => $tax_rate, 'base_amount' => $tax_rate > 0 ? round($amount/(1+($tax_rate/100)),2) : $amount]; + $group_tax = ['key' => $key, 'total' => $tax_total, 'tax_name' => $tax_name.' '.Number::formatValueNoTrailingZeroes(floatval($tax_rate), $this->client).'%', 'tax_id' => $tax_id, 'tax_rate' => $tax_rate, 'base_amount' => $tax_rate > 0 ? round($amount / (1 + ($tax_rate / 100)), 2) : $amount]; $this->tax_collection->push(collect($group_tax)); } @@ -400,9 +401,9 @@ class InvoiceItemSumInclusive public function setLineTotal($total) { - $this->item->gross_line_total = round(($total + 0.000000000000004),2); + $this->item->gross_line_total = round(($total + 0.000000000000004), 2); - $this->item->line_total = round(($total + 0.000000000000004),2); + $this->item->line_total = round(($total + 0.000000000000004), 2); return $this; } @@ -503,8 +504,8 @@ class InvoiceItemSumInclusive $this->item->tax_amount = $item_tax; - try{ - $this->item->net_cost = round($amount * (100 / (100 + ($this->item->tax_rate1+$this->item->tax_rate2+$this->item->tax_rate3))) / $this->item->quantity, $this->currency->precision+1); + try { + $this->item->net_cost = round($amount * (100 / (100 + ($this->item->tax_rate1 + $this->item->tax_rate2 + $this->item->tax_rate3))) / $this->item->quantity, $this->currency->precision + 1); $this->item->net_cost = round($this->item->net_cost, $this->currency->precision); } catch (\DivisionByZeroError $e) { $this->item->net_cost = $this->item->cost; diff --git a/app/Helpers/Invoice/InvoiceSum.php b/app/Helpers/Invoice/InvoiceSum.php index 06ecb33090..7291eeec35 100644 --- a/app/Helpers/Invoice/InvoiceSum.php +++ b/app/Helpers/Invoice/InvoiceSum.php @@ -1,4 +1,5 @@ sub_total,2); + return round($this->sub_total, 2); } public function getGrossSubTotal() { - return round($this->sub_total,2); + return round($this->sub_total, 2); } public function setSubTotal($value) @@ -346,7 +347,7 @@ class InvoiceSumInclusive public function getTotalDiscount() { - return round($this->total_discount,2); + return round($this->total_discount, 2); } public function getTotalTaxes() @@ -361,7 +362,7 @@ class InvoiceSumInclusive public function getTotal() { - return round($this->total,2); + return round($this->total, 2); } public function setTaxMap() @@ -372,7 +373,7 @@ class InvoiceSumInclusive } $this->tax_map = collect(); - + $keys = $this->invoice_items->getGroupedTaxes()->pluck('key')->unique(); $values = $this->invoice_items->getGroupedTaxes(); diff --git a/app/Helpers/Invoice/ProRata.php b/app/Helpers/Invoice/ProRata.php index ded4c78081..42f57ca60c 100644 --- a/app/Helpers/Invoice/ProRata.php +++ b/app/Helpers/Invoice/ProRata.php @@ -1,4 +1,5 @@ setPrintable(false) ->getPaymentPart(); - // return $html; + // return $html; return htmlspecialchars($html); } catch (\Exception $e) { diff --git a/app/Helpers/TranslationHelper.php b/app/Helpers/TranslationHelper.php index 08119eec29..c8fefd22b9 100644 --- a/app/Helpers/TranslationHelper.php +++ b/app/Helpers/TranslationHelper.php @@ -1,4 +1,5 @@ getFile(); $html_backup = $file; - - if(!$file) + + if (!$file) { return response()->json(['message' => ctrans('texts.no_backup_exists'), 'errors' => new stdClass()], 404); + } if (config('ninja.phantomjs_pdf_generation') || config('ninja.pdf_generator') == 'phantom') { $pdf = (new Phantom())->convertHtmlToPdf($html_backup); diff --git a/app/Http/Controllers/Auth/ContactForgotPasswordController.php b/app/Http/Controllers/Auth/ContactForgotPasswordController.php index 08a14e3bb5..e0bf9f5c68 100644 --- a/app/Http/Controllers/Auth/ContactForgotPasswordController.php +++ b/app/Http/Controllers/Auth/ContactForgotPasswordController.php @@ -1,4 +1,5 @@ first(); + } $domain_name = $request->getHost(); if (strpos($domain_name, config('ninja.app_domain')) !== false) { $subdomain = explode('.', $domain_name)[0]; - + $query = ['subdomain' => $subdomain]; - - if($company = MultiDB::findAndSetDbByDomain($query)) + + if ($company = MultiDB::findAndSetDbByDomain($query)) { return $company; + } } $query = [ @@ -63,8 +66,9 @@ class ContactLoginController extends Controller return $company; } - if(Ninja::isSelfHost()) + if (Ninja::isSelfHost()) { return Company::first(); + } return false; } @@ -74,7 +78,7 @@ class ContactLoginController extends Controller $company = false; $account = false; $intended = $request->query('intended') ?: false; - + $request->session()->invalidate(); $request->session()->regenerateToken(); @@ -86,8 +90,7 @@ class ContactLoginController extends Controller if ($company) { $account = $company->account; - } - else { + } else { abort(404, "We could not find this site, if you think this is an error, please contact the administrator."); } diff --git a/app/Http/Controllers/Auth/ContactRegisterController.php b/app/Http/Controllers/Auth/ContactRegisterController.php index 28a5734d36..70177a40d4 100644 --- a/app/Http/Controllers/Auth/ContactRegisterController.php +++ b/app/Http/Controllers/Auth/ContactRegisterController.php @@ -1,4 +1,5 @@ $company->account->isFreeHostedClient(), - 'register_company' => $company, - 'account' => $company->account, - 'submitsForm' => false, + 'register_company' => $company, + 'account' => $company->account, + 'submitsForm' => false, 'show_turnstile' => $show_turnstile ]; @@ -65,7 +66,7 @@ class ContactRegisterController extends Controller public function register(RegisterRequest $request) { - + $company = $request->company(); if (! $company->client_can_register || $company->account->isFreeHostedClient()) { diff --git a/app/Http/Controllers/Auth/ContactResetPasswordController.php b/app/Http/Controllers/Auth/ContactResetPasswordController.php index 06fcf332be..8f26037733 100644 --- a/app/Http/Controllers/Auth/ContactResetPasswordController.php +++ b/app/Http/Controllers/Auth/ContactResetPasswordController.php @@ -1,4 +1,5 @@ has('last_name') ? request()->input('last_name') : $name[1]; } - if($provider == 'apple' && !$user->email){ + if ($provider == 'apple' && !$user->email) { return response()->json(['message' => 'This signup method is not supported as no email was provided'], 403); } diff --git a/app/Http/Controllers/Auth/ResetPasswordController.php b/app/Http/Controllers/Auth/ResetPasswordController.php index ad45eb3698..bb84d17abb 100644 --- a/app/Http/Controllers/Auth/ResetPasswordController.php +++ b/app/Http/Controllers/Auth/ResetPasswordController.php @@ -1,4 +1,5 @@ currency = $nordigen_account['account_currency']; } finally { - if($bank_integration) - { + if ($bank_integration) { $bank_integration->auto_sync = true; $bank_integration->disabled_upstream = false; diff --git a/app/Http/Controllers/Bank/YodleeController.php b/app/Http/Controllers/Bank/YodleeController.php index d7dee86896..7a32a1fe63 100644 --- a/app/Http/Controllers/Bank/YodleeController.php +++ b/app/Http/Controllers/Bank/YodleeController.php @@ -1,4 +1,5 @@ currency = $account['account_currency']; $bank_integration->auto_sync = true; $bank_integration->disabled_upstream = $account['account_status'] == 'READY' ? false : true; - + $bank_integration->save(); } } @@ -279,20 +280,18 @@ class BankIntegrationController extends BaseController $is_account_active = $nordigen->isAccountActive($bank_integration->nordigen_account_id); $account = $nordigen->getAccount($bank_integration->nordigen_account_id); - if(is_array($account) && isset($account['code']) && $account['code'] == 429) { - + if (is_array($account) && isset($account['code']) && $account['code'] == 429) { + $bank_integration->bank_account_status = "429 Rate limit reached, check back later...."; $bank_integration->save(); return; - } - elseif(is_array($account) && isset($account['account_status']) &&!in_array($account['account_status'], ['READY', 'PROCESSING','DISCOVERED'])) { + } elseif (is_array($account) && isset($account['account_status']) && !in_array($account['account_status'], ['READY', 'PROCESSING','DISCOVERED'])) { $bank_integration->disabled_upstream = true; $bank_integration->save(); $nordigen->disabledAccountEmail($bank_integration); return; - } - elseif (!$is_account_active || !$account || isset($account['requisition'])) { + } elseif (!$is_account_active || !$account || isset($account['requisition'])) { $bank_integration->disabled_upstream = true; $bank_integration->save(); diff --git a/app/Http/Controllers/BankTransactionController.php b/app/Http/Controllers/BankTransactionController.php index e69148739b..8562c85f72 100644 --- a/app/Http/Controllers/BankTransactionController.php +++ b/app/Http/Controllers/BankTransactionController.php @@ -1,4 +1,5 @@ client_gateway_token_repo->delete($client_gateway_token); - if($client_gateway_token->is_default) { + if ($client_gateway_token->is_default) { $cgt = ClientGatewayToken::where('client_id', $client_gateway_token->client_id) ->where('company_gateway_id', $client_gateway_token->company_gateway_id) ->first(); - if($cgt){ + if ($cgt) { $cgt->is_default = true; $cgt->save(); } - + } return $this->itemResponse($client_gateway_token->fresh()); diff --git a/app/Http/Controllers/ClientPortal/ApplePayDomainController.php b/app/Http/Controllers/ClientPortal/ApplePayDomainController.php index bf1c9c148b..0400b15a05 100644 --- a/app/Http/Controllers/ClientPortal/ApplePayDomainController.php +++ b/app/Http/Controllers/ClientPortal/ApplePayDomainController.php @@ -1,4 +1,5 @@ has('send_email') && $request->send_email == 'true') { diff --git a/app/Http/Controllers/CompanyController.php b/app/Http/Controllers/CompanyController.php index 1356e60957..d9c282aeaf 100644 --- a/app/Http/Controllers/CompanyController.php +++ b/app/Http/Controllers/CompanyController.php @@ -1,4 +1,5 @@ uploadLogo($request->file('company_logo'), $company, $company); - if($request->has('sync_send_time') && $request->input('sync_send_time') == 'true') { - + if ($request->has('sync_send_time') && $request->input('sync_send_time') == 'true') { + //Update Reminders Invoice::where('company_id', $company->id) ->whereIn('status_id', [Invoice::STATUS_SENT, Invoice::STATUS_PARTIAL]) ->whereNotNull('next_send_date') - ->where('next_send_date','>', now()) + ->where('next_send_date', '>', now()) ->where('balance', '>', 0) ->cursor() - ->each(function ($invoice){ + ->each(function ($invoice) { $invoice->service()->setReminder(); }); - + //Update Recurring Invoices RecurringInvoice::where('company_id', $company->id) ->where('status_id', RecurringInvoice::STATUS_ACTIVE) ->where('next_send_date', '>', now()) ->cursor() - ->each(function ($recurring_invoice){ + ->each(function ($recurring_invoice) { $offset = $recurring_invoice->client->timezone_offset(); $recurring_invoice->next_send_date = \Carbon\Carbon::parse($recurring_invoice->next_send_date_client)->startOfDay()->addSeconds($offset); $recurring_invoice->save(); - - }); + + }); } - - return $this->itemResponse($company); + + return $this->itemResponse($company); } /** diff --git a/app/Http/Controllers/CompanyGatewayController.php b/app/Http/Controllers/CompanyGatewayController.php index 37a2dd8773..952b85a182 100644 --- a/app/Http/Controllers/CompanyGatewayController.php +++ b/app/Http/Controllers/CompanyGatewayController.php @@ -1,4 +1,5 @@ cbapowerboard_key: - + dispatch(function () use ($company_gateway) { MultiDB::setDb($company_gateway->company->db); $company_gateway->driver()->init()->settings()->updateSettings(); @@ -486,7 +487,7 @@ class CompanyGatewayController extends BaseController $company_gateway->setConfig($config); $company_gateway->save(); - + dispatch(function () use ($company_gateway) { MultiDB::setDb($company_gateway->company->db); diff --git a/app/Http/Controllers/CompanyLedgerController.php b/app/Http/Controllers/CompanyLedgerController.php index 28e168e9b7..a9fb877217 100644 --- a/app/Http/Controllers/CompanyLedgerController.php +++ b/app/Http/Controllers/CompanyLedgerController.php @@ -1,4 +1,5 @@ client->service()->updatePaidToDate(-1 * $credit->balance)->save(); // If we mutate the paid to date, we need to reverse the status of the invoice, this will allow the credit note that has been created to be used and double paid to dates prevented. $credit->client->service()->updateBalanceAndPaidToDate(-1 * ($credit->invoice->balance ?? 0), -1 * $credit->balance)->save(); // $invoice = $credit->invoice; - + $invoice = \App\Models\Invoice::withTrashed()->find($credit->invoice_id); if ($invoice) { $invoice->status_id = Invoice::STATUS_REVERSED; @@ -529,7 +530,7 @@ class CreditController extends BaseController if (Ninja::isHosted() && $user->account->emailQuotaExceeded()) { return response(['message' => ctrans('texts.email_quota_exceeded_subject')], 400); } - + if ($user->hasExactPermission('disable_emails') && (stripos($action, 'email') !== false)) { return response(['message' => ctrans('texts.disable_emails_error')], 400); } diff --git a/app/Http/Controllers/DesignController.php b/app/Http/Controllers/DesignController.php index 2ce9a4998f..cf9900a712 100644 --- a/app/Http/Controllers/DesignController.php +++ b/app/Http/Controllers/DesignController.php @@ -1,4 +1,5 @@ update(['design_id' => $design_id]); - + // Recurring Invoice Designs are set using the global company level. if ($settings_level == 'company') { $company->recurring_invoices()->withTrashed()->update(['design_id' => $design_id]); diff --git a/app/Http/Controllers/EInvoiceController.php b/app/Http/Controllers/EInvoiceController.php index 45a364373c..1e1f6132dd 100644 --- a/app/Http/Controllers/EInvoiceController.php +++ b/app/Http/Controllers/EInvoiceController.php @@ -1,4 +1,5 @@ setCompany($company) ->setup($request->validated()); - nlog($response); + nlog($response); if (data_get($response, 'status') === 'error') { return response()->json(data_get($response, 'message'), status: $response['code']); @@ -89,7 +90,7 @@ class EInvoicePeppolController extends BaseController $settings->tax_rate2 = 0; $settings->tax_name3 = ''; $settings->tax_rate3 = 0; - + $settings->e_invoice_type = 'PEPPOL'; // $settings->vat_number = $request->vat_number ?? $company->settings->vat_number; $settings->id_number = $request->id_number ?? $company->settings->id_number; @@ -264,7 +265,7 @@ class EInvoicePeppolController extends BaseController public function retrySend(RetrySendRequest $request) { - + SendEDocument::dispatch($request->entity, $request->entity_id, auth()->user()->company()->db); return response()->json(['message' => 'trying....'], 200); diff --git a/app/Http/Controllers/EInvoiceTokenController.php b/app/Http/Controllers/EInvoiceTokenController.php index 837a20fa45..ef78ac8e74 100644 --- a/app/Http/Controllers/EInvoiceTokenController.php +++ b/app/Http/Controllers/EInvoiceTokenController.php @@ -42,7 +42,7 @@ class EInvoiceTokenController extends BaseController return response()->noContent(); } - + nlog($response->body()); diff --git a/app/Http/Controllers/EmailController.php b/app/Http/Controllers/EmailController.php index 1c9d7639fb..027dd1f3ea 100644 --- a/app/Http/Controllers/EmailController.php +++ b/app/Http/Controllers/EmailController.php @@ -1,4 +1,5 @@ entity_type = PurchaseOrder::class; $this->entity_transformer = PurchaseOrderTransformer::class; - + if ($entity_obj->invitations->count() >= 1) { event(new EntityWasEmailed($entity_obj->invitations->first(), $entity_obj->company, Ninja::eventVars(auth()->user() ? auth()->user()->id : null), 'purchase_order')); $entity_obj->sendEvent(Webhook::EVENT_SENT_PURCHASE_ORDER, "client"); diff --git a/app/Http/Controllers/EmailHistoryController.php b/app/Http/Controllers/EmailHistoryController.php index 962f6306bd..55b38048b7 100644 --- a/app/Http/Controllers/EmailHistoryController.php +++ b/app/Http/Controllers/EmailHistoryController.php @@ -1,4 +1,5 @@ metadata) { + if ($request->metadata) { $metadata = $this->handleChunkedUpload($request); - if(!isset($metadata['uploaded_filepath'])){ + if (!isset($metadata['uploaded_filepath'])) { return response()->json([ 'success' => true, @@ -76,11 +77,10 @@ class ImportJsonController extends BaseController 'fileName' => $metadata['fileName'] ], 200); - } + } - $file_location = $metadata['uploaded_filepath']; - } - else{ + $file_location = $metadata['uploaded_filepath']; + } else { $disk = Ninja::isHosted() ? 'backup' : config('filesystems.default'); @@ -104,23 +104,23 @@ class ImportJsonController extends BaseController unset($metadata['uploaded_filepath']); - return response()->json(array_merge(['message' => 'Processing','success' => true], $metadata ), 200); + return response()->json(array_merge(['message' => 'Processing','success' => true], $metadata), 200); } private function handleChunkedUpload(ImportJsonRequest $request) { - + $metadata = json_decode($request->metadata, true); $chunk = $request->file('file'); $tempPath = sys_get_temp_dir()."/{$metadata['fileHash']}/app/chunks/"; - if(!is_dir($tempPath)) { + if (!is_dir($tempPath)) { mkdir($tempPath, 0777, true); } $chunkPath = $tempPath . '/' . $metadata['currentChunk']; - + file_put_contents($chunkPath, file_get_contents($chunk)); $uploadedChunks = count(glob($tempPath . '/*')); @@ -128,7 +128,7 @@ class ImportJsonController extends BaseController if ($uploadedChunks >= $metadata['totalChunks']) { // Combine all chunks $tempFilePath = $tempPath . $metadata['fileName']; - + $handle = fopen($tempFilePath, 'wb'); for ($i = 0; $i < $metadata['totalChunks']; $i++) { @@ -137,7 +137,7 @@ class ImportJsonController extends BaseController } fclose($handle); - + $disk = Ninja::isHosted() ? 'backup' : config('filesystems.default'); Storage::disk($disk)->put( @@ -151,7 +151,7 @@ class ImportJsonController extends BaseController Storage::deleteDirectory(sys_get_temp_dir()."/{$metadata['fileHash']}"); $metadata['uploaded_filepath'] = 'migrations/'.$metadata['fileName']; - + return $metadata; } @@ -160,7 +160,7 @@ class ImportJsonController extends BaseController } - private function deleteDirectory($dir) + private function deleteDirectory($dir) { $files = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator($dir, \RecursiveDirectoryIterator::SKIP_DOTS), @@ -176,6 +176,6 @@ class ImportJsonController extends BaseController } return rmdir($dir); - + } } diff --git a/app/Http/Controllers/ImportQuickbooksController.php b/app/Http/Controllers/ImportQuickbooksController.php index d055043fc3..295e5d6a3b 100644 --- a/app/Http/Controllers/ImportQuickbooksController.php +++ b/app/Http/Controllers/ImportQuickbooksController.php @@ -1,4 +1,5 @@ sdk()->getAuthorizationUrl(); nlog($authorizationUrl); - + $state = $qb->sdk()->getState(); Cache::put($state, $token, 190); diff --git a/app/Http/Controllers/InAppPurchase/AppleController.php b/app/Http/Controllers/InAppPurchase/AppleController.php index b5c4c9aa99..9d6e011d79 100644 --- a/app/Http/Controllers/InAppPurchase/AppleController.php +++ b/app/Http/Controllers/InAppPurchase/AppleController.php @@ -1,4 +1,5 @@ ctrans('texts.email_quota_exceeded_subject')], 400); } - if($user->hasExactPermission('disable_emails') && (stripos($action, 'email') !== false)){ + if ($user->hasExactPermission('disable_emails') && (stripos($action, 'email') !== false)) { return response(['message' => ctrans('texts.disable_emails_error')], 400); } @@ -552,17 +552,17 @@ class InvoiceController extends BaseController $batch_id = (new \App\Jobs\Invoice\PrintEntityBatch(Invoice::class, $invoices->pluck('id')->toArray(), $user->company()->db))->handle(); $batch = \Illuminate\Support\Facades\Bus::findBatch($batch_id); - $batch_key = $batch->name; + $batch_key = $batch->name; $finished = false; - do{ + do { usleep(300000); $batch = \Illuminate\Support\Facades\Bus::findBatch($batch_id); $finished = $batch->finished(); - }while(!$finished); - - $paths = $invoices->map(function ($invoice) use($batch_key){ + } while (!$finished); + + $paths = $invoices->map(function ($invoice) use ($batch_key) { return \Illuminate\Support\Facades\Cache::pull("{$batch_key}-{$invoice->id}"); })->filter(function ($value) { return !is_null($value); diff --git a/app/Http/Controllers/LicenseController.php b/app/Http/Controllers/LicenseController.php index 8478a8fa8e..9238094a3f 100644 --- a/app/Http/Controllers/LicenseController.php +++ b/app/Http/Controllers/LicenseController.php @@ -1,4 +1,5 @@ all(), $request->header('X-API-SECURITY'))->delay(15); return response()->json(['message' => 'Success'], 200); - } - elseif($request->header('X-API-SECURITY') && stripos($request->header('X-API-SECURITY'), \Illuminate\Support\Facades\Cache::get('client_postmark_keys')) !== false){ + } elseif ($request->header('X-API-SECURITY') && stripos($request->header('X-API-SECURITY'), \Illuminate\Support\Facades\Cache::get('client_postmark_keys')) !== false) { ProcessPostmarkWebhook::dispatch($request->all(), $request->header('X-API-SECURITY'))->delay(15); return response()->json(['message' => 'Success'], 200); diff --git a/app/Http/Controllers/PreviewController.php b/app/Http/Controllers/PreviewController.php index 84c14fdd15..20fd9b84d0 100644 --- a/app/Http/Controllers/PreviewController.php +++ b/app/Http/Controllers/PreviewController.php @@ -1,4 +1,5 @@ input('design.is_template')) { return $this->template(); } @@ -170,12 +171,11 @@ class PreviewController extends BaseController return $this->blankEntity(); } - if($entity_obj->client){ + if ($entity_obj->client) { $entity_obj->load('client'); $locale = $entity_obj->client->preferredLocale(); $settings = $entity_obj->client->getMergedSettings(); - } - else { + } else { $entity_obj->load('vendor'); $locale = $entity_obj->vendor->preferredLocale(); $settings = $entity_obj->vendor->getMergedSettings(); @@ -199,7 +199,7 @@ class PreviewController extends BaseController $ps->builder ->build(); - + if ($request->query('html') == 'true') { return $ps->getHtml(); } @@ -307,11 +307,10 @@ class PreviewController extends BaseController $entity_string = 'invoice'; - if(request()->input('entity') == 'purchase_order') { + if (request()->input('entity') == 'purchase_order') { $invitation = PurchaseOrderInvitation::where('company_id', $company->id)->orderBy('id', 'desc')->first(); $entity_string = 'purchase_order'; - } - else{ + } else { /** @var \App\Models\InvoiceInvitation $invitation */ $invitation = InvoiceInvitation::where('company_id', $company->id)->orderBy('id', 'desc')->first(); } @@ -371,7 +370,7 @@ class PreviewController extends BaseController $request['entity_type'] = request()->input('entity', 'invoice'); $pdf = (new PdfMock($request, $company))->build(); - + if (request()->query('html') == 'true') { return $pdf->getHtml(); } diff --git a/app/Http/Controllers/PreviewPurchaseOrderController.php b/app/Http/Controllers/PreviewPurchaseOrderController.php index 50e5393c64..7e60fdb9cf 100644 --- a/app/Http/Controllers/PreviewPurchaseOrderController.php +++ b/app/Http/Controllers/PreviewPurchaseOrderController.php @@ -1,4 +1,5 @@ mockEntity(); } - + $design_object = json_decode(json_encode(request()->input('design')), true); if (! is_array($design_object)) { @@ -247,9 +248,9 @@ class PreviewPurchaseOrderController extends BaseController private function mockEntity() { - + nlog("mockEntity"); - + $start = microtime(true); $user = auth()->user(); diff --git a/app/Http/Controllers/ProductController.php b/app/Http/Controllers/ProductController.php index c9abfc4500..7153088fbd 100644 --- a/app/Http/Controllers/ProductController.php +++ b/app/Http/Controllers/ProductController.php @@ -1,4 +1,5 @@ whereIn('id', $this->transformKeys($ids))->company()->get(); - if($action == 'invoice' && $user->can('edit', $projects->first())) { - $invoice = $this->project_repo->invoice($projects); - $this->entity_transformer = InvoiceTransformer::class; - $this->entity_type = Invoice::class; - return $this->itemResponse($invoice); + if ($action == 'invoice' && $user->can('edit', $projects->first())) { + $invoice = $this->project_repo->invoice($projects); + $this->entity_transformer = InvoiceTransformer::class; + $this->entity_type = Invoice::class; + return $this->itemResponse($invoice); } if ($action == 'template' && $user->can('view', $projects->first())) { diff --git a/app/Http/Controllers/ProtectedDownloadController.php b/app/Http/Controllers/ProtectedDownloadController.php index b6ed808717..8ae1354b6a 100644 --- a/app/Http/Controllers/ProtectedDownloadController.php +++ b/app/Http/Controllers/ProtectedDownloadController.php @@ -1,4 +1,5 @@ account->emailQuotaExceeded()) { return response(['message' => ctrans('texts.email_quota_exceeded_subject')], 400); } - + if ($user->hasExactPermission('disable_emails') && (stripos($action, 'email') !== false)) { return response(['message' => ctrans('texts.disable_emails_error')], 400); } @@ -522,7 +523,7 @@ class PurchaseOrderController extends BaseController } if ($action == 'bulk_print' && $user->can('view', $purchase_orders->first())) { - + $start = microtime(true); $batch_id = (new \App\Jobs\Invoice\PrintEntityBatch(PurchaseOrder::class, $purchase_orders->pluck('id')->toArray(), $user->company()->db))->handle(); @@ -553,7 +554,7 @@ class PurchaseOrderController extends BaseController 'Server-Timing' => (string)(microtime(true) - $start) ]); - + } if ($action == 'template' && $user->can('view', $purchase_orders->first())) { @@ -702,9 +703,9 @@ class PurchaseOrderController extends BaseController case 'email': case 'send_email': //check query parameter for email_type and set the template else use calculateTemplate - + $purchase_order->service()->sendEmail(); - + if (! $bulk) { return response()->json(['message' => 'email sent'], 200); } diff --git a/app/Http/Controllers/QuoteController.php b/app/Http/Controllers/QuoteController.php index c1e38b0f75..6cfcdf966e 100644 --- a/app/Http/Controllers/QuoteController.php +++ b/app/Http/Controllers/QuoteController.php @@ -1,4 +1,5 @@ account->emailQuotaExceeded()) { return response(['message' => ctrans('texts.email_quota_exceeded_subject')], 400); } - + if ($user->hasExactPermission('disable_emails') && (stripos($action, 'email') !== false)) { return response(['message' => ctrans('texts.disable_emails_error')], 400); } diff --git a/app/Http/Controllers/RecurringExpenseController.php b/app/Http/Controllers/RecurringExpenseController.php index e7f42aca33..911dbab8ce 100644 --- a/app/Http/Controllers/RecurringExpenseController.php +++ b/app/Http/Controllers/RecurringExpenseController.php @@ -1,4 +1,5 @@ user(); - if((stripos($request->action, 'send_now') !== false) && $user->hasExactPermission('disable_emails')){ + if ((stripos($request->action, 'send_now') !== false) && $user->hasExactPermission('disable_emails')) { return response(['message' => ctrans('texts.disable_emails_error')], 400); } diff --git a/app/Http/Controllers/RecurringQuoteController.php b/app/Http/Controllers/RecurringQuoteController.php index a02dc2eff3..2da869d9d9 100644 --- a/app/Http/Controllers/RecurringQuoteController.php +++ b/app/Http/Controllers/RecurringQuoteController.php @@ -1,4 +1,5 @@ input('db_database'); $db_username = $request->input('db_username'); $db_password = $request->input('db_password'); - $mail_port = $request->input('mail_port',0); + $mail_port = $request->input('mail_port', 0); $encryption = $request->input('encryption'); $mail_host = $request->input('mail_host'); $mail_username = $request->input('mail_username'); diff --git a/app/Http/Controllers/Shop/ClientController.php b/app/Http/Controllers/Shop/ClientController.php index 90387cbf3d..55c34c0f3b 100644 --- a/app/Http/Controllers/Shop/ClientController.php +++ b/app/Http/Controllers/Shop/ClientController.php @@ -1,4 +1,5 @@ ctrans('texts.wrong_confirmation'), 'redirect_url' => $react ? config('ninja.react_url')."/#/" : url('/')]); } - + $user->email_verified_at = now(); $user->save(); diff --git a/app/Http/Controllers/TwilioController.php b/app/Http/Controllers/TwilioController.php index c4ae91b040..59dc25edfb 100644 --- a/app/Http/Controllers/TwilioController.php +++ b/app/Http/Controllers/TwilioController.php @@ -1,4 +1,5 @@ check()) { - + request()->session()->invalidate(); request()->session()->regenerateToken(); Auth::guard('contact')->loginUsingId($multiple_contacts[0]->id, true); diff --git a/app/Http/Middleware/CheckForMaintenanceMode.php b/app/Http/Middleware/CheckForMaintenanceMode.php index c34d9b9328..f95e5a3833 100644 --- a/app/Http/Middleware/CheckForMaintenanceMode.php +++ b/app/Http/Middleware/CheckForMaintenanceMode.php @@ -1,4 +1,5 @@ header('X-API-TOKEN') && - ($company_token = MultiDB::getCompanyToken($request->header('X-API-TOKEN')))){ - } - elseif ($request->header('X-API-TOKEN') && ($company_token = CompanyToken::with([ + ($company_token = MultiDB::getCompanyToken($request->header('X-API-TOKEN')))) { + } elseif ($request->header('X-API-TOKEN') && ($company_token = CompanyToken::with([ 'user.account', 'company', - 'account', + 'account', ])->where('token', $request->header('X-API-TOKEN'))->first())) { - } - else { + } else { return response()->json(['message' => 'Invalid token'], 403); } - $user = $company_token->user; + $user = $company_token->user; + $error = [ + 'message' => 'User inactive', + 'errors' => new stdClass(), + ]; + //user who once existed, but has been soft deleted + if (! $user) { + return response()->json($error, 403); + } + + if (Ninja::isHosted() && $company_token->is_system == 0 && ! $user->account->isPaid()) { $error = [ - 'message' => 'User inactive', + 'message' => 'Feature not available with free / unpaid account.', 'errors' => new stdClass(), ]; - //user who once existed, but has been soft deleted - if (! $user) { - return response()->json($error, 403); - } - if (Ninja::isHosted() && $company_token->is_system == 0 && ! $user->account->isPaid()) { - $error = [ - 'message' => 'Feature not available with free / unpaid account.', - 'errors' => new stdClass(), - ]; + return response()->json($error, 403); + } - return response()->json($error, 403); - } + /* + | + | Necessary evil here: As we are authenticating on CompanyToken, + | we need to link the company to the user manually. This allows + | us to decouple a $user and their attached companies completely. + | + */ + $truth = app()->make(TruthSource::class); - /* - | - | Necessary evil here: As we are authenticating on CompanyToken, - | we need to link the company to the user manually. This allows - | us to decouple a $user and their attached companies completely. - | - */ - $truth = app()->make(TruthSource::class); + $truth->setCompanyUser($company_token->cu); + $truth->setUser($company_token->user); + $truth->setCompany($company_token->company); + $truth->setCompanyToken($company_token); + $truth->setPremiumHosted($company_token->account->isPremium()); + /* + | This method binds the db to the jobs created using this + | session + */ + app('queue')->createPayloadUsing(function () use ($company_token) { + return ['db' => $company_token->company->db]; + // return ['db' => $company_token->company->db, 'is_premium' => $company_token->account->isPremium()]; + }); - $truth->setCompanyUser($company_token->cu); - $truth->setUser($company_token->user); - $truth->setCompany($company_token->company); - $truth->setCompanyToken($company_token); - $truth->setPremiumHosted($company_token->account->isPremium()); - /* - | This method binds the db to the jobs created using this - | session - */ - app('queue')->createPayloadUsing(function () use ($company_token) { - return ['db' => $company_token->company->db]; - // return ['db' => $company_token->company->db, 'is_premium' => $company_token->account->isPremium()]; - }); + //user who once existed, but has been soft deleted + if ($company_token->cu->is_locked) { + $error = [ + 'message' => 'User access locked', + 'errors' => new stdClass(), + ]; - //user who once existed, but has been soft deleted - if ($company_token->cu->is_locked) { - $error = [ - 'message' => 'User access locked', - 'errors' => new stdClass(), - ]; + return response()->json($error, 403); + } - return response()->json($error, 403); - } - - //stateless, don't remember the user. - auth()->login($user, false); - auth()->user()->setCompany($company_token->company); + //stateless, don't remember the user. + auth()->login($user, false); + auth()->user()->setCompany($company_token->company); return $next($request); } diff --git a/app/Http/Middleware/TrimStrings.php b/app/Http/Middleware/TrimStrings.php index 34ed3e7b69..8653243397 100644 --- a/app/Http/Middleware/TrimStrings.php +++ b/app/Http/Middleware/TrimStrings.php @@ -1,4 +1,5 @@ 'true', 'ipaddy' => request()->ip()], $this->all())); $input = $this->all(); diff --git a/app/Http/Requests/Account/UpdateAccountRequest.php b/app/Http/Requests/Account/UpdateAccountRequest.php index 93f436b778..ba58712295 100644 --- a/app/Http/Requests/Account/UpdateAccountRequest.php +++ b/app/Http/Requests/Account/UpdateAccountRequest.php @@ -1,4 +1,5 @@ file('documents') && is_array($this->file('documents'))) { - $rules['documents.*'] = $this->fileValidation(); - } elseif ($this->file('documents')) { - $rules['documents'] = $this->fileValidation(); - } - - if ($this->file('file') && is_array($this->file('file'))) { - $rules['file.*'] = $this->fileValidation(); - } elseif ($this->file('file')) { - $rules['file'] = $this->fileValidation(); - } - + $rules['file'] = 'bail|sometimes|array'; + $rules['file.*'] = $this->fileValidation(); + $rules['documents'] = 'bail|sometimes|array'; + $rules['documents.*'] = $this->fileValidation(); $rules['is_public'] = 'sometimes|boolean'; return $rules; @@ -53,11 +45,18 @@ class UploadBankIntegrationRequest extends Request { $input = $this->all(); + if ($this->file('documents') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('documents', [$this->file('documents')]); + } + + if ($this->file('file') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('file', [$this->file('file')]); + } + if (isset($input['is_public'])) { $input['is_public'] = $this->toBoolean($input['is_public']); } $this->replace($input); - } } diff --git a/app/Http/Requests/BankTransaction/AdminBankTransactionRequest.php b/app/Http/Requests/BankTransaction/AdminBankTransactionRequest.php index 8da28d1d7f..be3e0dfc00 100644 --- a/app/Http/Requests/BankTransaction/AdminBankTransactionRequest.php +++ b/app/Http/Requests/BankTransaction/AdminBankTransactionRequest.php @@ -1,4 +1,5 @@ file('documents') && is_array($this->file('documents'))) { - $rules['documents.*'] = $this->fileValidation(); - } elseif ($this->file('documents')) { - $rules['documents'] = $this->fileValidation(); - } - - if ($this->file('file') && is_array($this->file('file'))) { - $rules['file.*'] = $this->fileValidation(); - } elseif ($this->file('file')) { - $rules['file'] = $this->fileValidation(); - } - + $rules['file'] = 'bail|sometimes|array'; + $rules['file.*'] = $this->fileValidation(); + $rules['documents'] = 'bail|sometimes|array'; + $rules['documents.*'] = $this->fileValidation(); $rules['is_public'] = 'sometimes|boolean'; return $rules; @@ -53,6 +46,15 @@ class UploadBankTransactionRequest extends Request { $input = $this->all(); + + if ($this->file('documents') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('documents', [$this->file('documents')]); + } + + if ($this->file('file') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('file', [$this->file('file')]); + } + if (isset($input['is_public'])) { $input['is_public'] = $this->toBoolean($input['is_public']); } diff --git a/app/Http/Requests/BankTransactionRule/BulkBankTransactionRuleRequest.php b/app/Http/Requests/BankTransactionRule/BulkBankTransactionRuleRequest.php index 246ac824ea..05ff52f344 100644 --- a/app/Http/Requests/BankTransactionRule/BulkBankTransactionRuleRequest.php +++ b/app/Http/Requests/BankTransactionRule/BulkBankTransactionRuleRequest.php @@ -1,4 +1,5 @@ user(); - if ($this->file('documents') && is_array($this->file('documents'))) { - $rules['documents.*'] = $this->fileValidation(); - } elseif ($this->file('documents')) { - $rules['documents'] = $this->fileValidation(); - } else { - $rules['documents'] = 'bail|sometimes|array'; - } - - if ($this->file('file') && is_array($this->file('file'))) { - $rules['file.*'] = $this->fileValidation(); - } elseif ($this->file('file')) { - $rules['file'] = $this->fileValidation(); - } + $rules['file'] = 'bail|sometimes|array'; + $rules['file.*'] = $this->fileValidation(); + $rules['documents'] = 'bail|sometimes|array'; + $rules['documents.*'] = $this->fileValidation(); /* Ensure we have a client name, and that all emails are unique*/ //$rules['name'] = 'required|min:1'; @@ -97,6 +89,14 @@ class StoreClientRequest extends Request /** @var \App\Models\User $user */ $user = auth()->user(); + if ($this->file('documents') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('documents', [$this->file('documents')]); + } + + if ($this->file('file') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('file', [$this->file('file')]); + } + /* Default settings */ $settings = (array)ClientSettings::defaults(); diff --git a/app/Http/Requests/Client/UpdateClientRequest.php b/app/Http/Requests/Client/UpdateClientRequest.php index b364aec78b..3d335c1739 100644 --- a/app/Http/Requests/Client/UpdateClientRequest.php +++ b/app/Http/Requests/Client/UpdateClientRequest.php @@ -1,4 +1,5 @@ user(); - if ($this->file('documents') && is_array($this->file('documents'))) { - $rules['documents.*'] = $this->fileValidation(); - } elseif ($this->file('documents')) { - $rules['documents'] = $this->fileValidation(); - } - if ($this->file('file') && is_array($this->file('file'))) { - $rules['file.*'] = $this->fileValidation(); - } elseif ($this->file('file')) { - $rules['file'] = $this->fileValidation(); - } else { - $rules['documents'] = 'bail|sometimes|array'; - } + $rules['file'] = 'bail|sometimes|array'; + $rules['file.*'] = $this->fileValidation(); + $rules['documents'] = 'bail|sometimes|array'; + $rules['documents.*'] = $this->fileValidation(); $rules['company_logo'] = 'mimes:jpeg,jpg,png,gif|max:10000'; $rules['industry_id'] = 'integer|nullable'; @@ -110,11 +103,15 @@ class UpdateClientRequest extends Request /** @var \App\Models\User $user */ $user = auth()->user(); - /* If the user removes the currency we must always set the default */ - // if (array_key_exists('settings', $input) && ! array_key_exists('currency_id', $input['settings'])) { - // $input['settings']['currency_id'] = (string) $user->company()->settings->currency_id; - // } else //2025-03-11 fixes for currency_id not being set - + + if ($this->file('documents') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('documents', [$this->file('documents')]); + } + + if ($this->file('file') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('file', [$this->file('file')]); + } + if (empty($input['settings']['currency_id'])) { $input['settings']['currency_id'] = (string) $user->company()->settings->currency_id; } diff --git a/app/Http/Requests/Client/UploadClientRequest.php b/app/Http/Requests/Client/UploadClientRequest.php index 9582a7c611..d0c602de26 100644 --- a/app/Http/Requests/Client/UploadClientRequest.php +++ b/app/Http/Requests/Client/UploadClientRequest.php @@ -1,4 +1,5 @@ file('documents') && is_array($this->file('documents'))) { - $rules['documents.*'] = $this->fileValidation(); - } elseif ($this->file('documents')) { - $rules['documents'] = $this->fileValidation(); - } - - if ($this->file('file') && is_array($this->file('file'))) { - $rules['file.*'] = $this->fileValidation(); - } elseif ($this->file('file')) { - $rules['file'] = $this->fileValidation(); - } + $rules['file'] = 'bail|sometimes|array'; + $rules['file.*'] = $this->fileValidation(); + $rules['documents'] = 'bail|sometimes|array'; + $rules['documents.*'] = $this->fileValidation(); $rules['is_public'] = 'sometimes|boolean'; @@ -53,6 +47,14 @@ class UploadClientRequest extends Request { $input = $this->all(); + if ($this->file('documents') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('documents', [$this->file('documents')]); + } + + if ($this->file('file') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('file', [$this->file('file')]); + } + if (isset($input['is_public'])) { $input['is_public'] = $this->toBoolean($input['is_public']); } diff --git a/app/Http/Requests/ClientGatewayToken/CreateClientGatewayTokenRequest.php b/app/Http/Requests/ClientGatewayToken/CreateClientGatewayTokenRequest.php index 15cec88ac7..54bce07b13 100644 --- a/app/Http/Requests/ClientGatewayToken/CreateClientGatewayTokenRequest.php +++ b/app/Http/Requests/ClientGatewayToken/CreateClientGatewayTokenRequest.php @@ -1,4 +1,5 @@ company->filterNullsRecursive($input['e_invoice']); } - if(isset($input['calculate_taxes']) && $input['calculate_taxes'] == true) { + if (isset($input['calculate_taxes']) && $input['calculate_taxes'] == true) { $input['settings']['tax_name1'] = ''; $input['settings']['tax_rate1'] = 0; $input['settings']['tax_name2'] = ''; @@ -170,7 +171,7 @@ class UpdateCompanyRequest extends Request $input['enabled_item_tax_rates'] = 1; } - if(isset($input['session_timeout']) && $input['session_timeout'] < 0) { + if (isset($input['session_timeout']) && $input['session_timeout'] < 0) { $input['session_timeout'] = 0; } @@ -200,7 +201,7 @@ class UpdateCompanyRequest extends Request if (Ninja::isHosted()) { foreach ($this->protected_input as $protected_var) { - if(isset($settings[$protected_var])) { + if (isset($settings[$protected_var])) { $settings[$protected_var] = str_replace("script", "", $settings[$protected_var]); } } diff --git a/app/Http/Requests/Company/UploadCompanyRequest.php b/app/Http/Requests/Company/UploadCompanyRequest.php index 77f0ee1544..33f31d837b 100644 --- a/app/Http/Requests/Company/UploadCompanyRequest.php +++ b/app/Http/Requests/Company/UploadCompanyRequest.php @@ -1,4 +1,5 @@ file('documents') && is_array($this->file('documents'))) { - $rules['documents.*'] = $this->fileValidation(); - } elseif ($this->file('documents')) { - $rules['documents'] = $this->fileValidation(); - } - - if ($this->file('file') && is_array($this->file('file'))) { - $rules['file.*'] = $this->fileValidation(); - } elseif ($this->file('file')) { - $rules['file'] = $this->fileValidation(); - } + $rules['file'] = 'bail|sometimes|array'; + $rules['file.*'] = $this->fileValidation(); + $rules['documents'] = 'bail|sometimes|array'; + $rules['documents.*'] = $this->fileValidation(); return $rules; } + + public function prepareForValidation() + { + $input = $this->all(); + + if ($this->file('documents') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('documents', [$this->file('documents')]); + } + + if ($this->file('file') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('file', [$this->file('file')]); + } + + $this->replace($input); + } } diff --git a/app/Http/Requests/CompanyGateway/BulkCompanyGatewayRequest.php b/app/Http/Requests/CompanyGateway/BulkCompanyGatewayRequest.php index ba82cf8abd..6076801da2 100644 --- a/app/Http/Requests/CompanyGateway/BulkCompanyGatewayRequest.php +++ b/app/Http/Requests/CompanyGateway/BulkCompanyGatewayRequest.php @@ -1,4 +1,5 @@ file('documents') && is_array($this->file('documents'))) { - $rules['documents.*'] = $this->fileValidation(); - } elseif ($this->file('documents')) { - $rules['documents'] = $this->fileValidation(); - } else { - $rules['documents'] = 'bail|sometimes|array'; - } - - if ($this->file('file') && is_array($this->file('file'))) { - $rules['file.*'] = $this->fileValidation(); - } elseif ($this->file('file')) { - $rules['file'] = $this->fileValidation(); - } - /** @var \App\Models\User $user */ $user = auth()->user(); + $rules = []; + + $rules['file'] = 'bail|sometimes|array'; + $rules['file.*'] = $this->fileValidation(); + $rules['documents'] = 'bail|sometimes|array'; + $rules['documents.*'] = $this->fileValidation(); + $rules['client_id'] = 'required|exists:clients,id,company_id,'.$user->company()->id; $rules['invitations'] = 'sometimes|bail|array'; $rules['invitations.*.client_contact_id'] = 'bail|required|distinct'; - - // $rules['number'] = new UniqueCreditNumberRule($this->all()); $rules['number'] = ['nullable', Rule::unique('credits')->where('company_id', $user->company()->id)]; $rules['discount'] = 'sometimes|numeric|max:99999999999999'; $rules['is_amount_discount'] = ['boolean']; @@ -103,6 +93,44 @@ class StoreCreditRequest extends Request { $input = $this->all(); + if ($this->file('documents') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('documents', [$this->file('documents')]); + } + + if ($this->file('file') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('file', [$this->file('file')]); + } + + if (array_key_exists('is_amount_discount', $input) && is_bool($input['is_amount_discount'])) { + $input['is_amount_discount'] = $this->setBoolean($input['is_amount_discount']); + } else { + $input['is_amount_discount'] = false; + } + + if (isset($input['exchange_rate'])) { + $input['exchange_rate'] = $this->parseFloat($input['exchange_rate']); + } + + if (isset($input['amount'])) { + $input['amount'] = $this->parseFloat($input['amount']); + } + + if (isset($input['custom_surcharge1'])) { + $input['custom_surcharge1'] = $this->parseFloat($input['custom_surcharge1']); + } + + if (isset($input['custom_surcharge2'])) { + $input['custom_surcharge2'] = $this->parseFloat($input['custom_surcharge2']); + } + + if (isset($input['custom_surcharge3'])) { + $input['custom_surcharge3'] = $this->parseFloat($input['custom_surcharge3']); + } + + if (isset($input['custom_surcharge4'])) { + $input['custom_surcharge4'] = $this->parseFloat($input['custom_surcharge4']); + } + if (array_key_exists('design_id', $input) && is_string($input['design_id'])) { $input['design_id'] = $this->decodePrimaryKey($input['design_id']); } @@ -117,10 +145,6 @@ class StoreCreditRequest extends Request $input['line_items'] = $this->cleanFeeItems($input['line_items']); $input['amount'] = $this->entityTotalAmount($input['line_items']); - if (array_key_exists('exchange_rate', $input) && is_null($input['exchange_rate'])) { - $input['exchange_rate'] = 1; - } - if (isset($input['footer']) && $this->hasHeader('X-REACT')) { $input['footer'] = str_replace("\n", "", $input['footer']); } diff --git a/app/Http/Requests/Credit/UpdateCreditRequest.php b/app/Http/Requests/Credit/UpdateCreditRequest.php index 8f497a85a6..aae291e5ca 100644 --- a/app/Http/Requests/Credit/UpdateCreditRequest.php +++ b/app/Http/Requests/Credit/UpdateCreditRequest.php @@ -1,4 +1,5 @@ file('documents') && is_array($this->file('documents'))) { - $rules['documents.*'] = $this->fileValidation(); - } elseif ($this->file('documents')) { - $rules['documents'] = $this->fileValidation(); - } else { - $rules['documents'] = 'bail|sometimes|array'; - } - if ($this->file('file') && is_array($this->file('file'))) { - $rules['file.*'] = $this->fileValidation(); - } elseif ($this->file('file')) { - $rules['file'] = $this->fileValidation(); - } + $rules['file.*'] = $this->fileValidation(); + $rules['file'] = 'bail|sometimes|array'; + $rules['documents.*'] = $this->fileValidation(); + $rules['documents'] = 'bail|sometimes|array'; + $rules['number'] = ['bail', 'sometimes', 'nullable', Rule::unique('credits')->where('company_id', $user->company()->id)->ignore($this->credit->id)]; @@ -100,6 +94,14 @@ class UpdateCreditRequest extends Request $input = $this->decodePrimaryKeys($input); + if ($this->file('documents') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('documents', [$this->file('documents')]); + } + + if ($this->file('file') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('file', [$this->file('file')]); + } + if (isset($input['partial']) && $input['partial'] == 0) { $input['partial_due_date'] = null; } @@ -107,7 +109,6 @@ class UpdateCreditRequest extends Request if (isset($input['line_items'])) { $input['line_items'] = isset($input['line_items']) ? $this->cleanItems($input['line_items']) : []; $input['amount'] = $this->entityTotalAmount($input['line_items']); - } if (array_key_exists('exchange_rate', $input) && is_null($input['exchange_rate'])) { diff --git a/app/Http/Requests/Credit/UploadCreditRequest.php b/app/Http/Requests/Credit/UploadCreditRequest.php index f07ec6221d..65d5f9f56b 100644 --- a/app/Http/Requests/Credit/UploadCreditRequest.php +++ b/app/Http/Requests/Credit/UploadCreditRequest.php @@ -1,4 +1,5 @@ file('documents') && is_array($this->file('documents'))) { - $rules['documents.*'] = $this->fileValidation(); - } elseif ($this->file('documents')) { - $rules['documents'] = $this->fileValidation(); - } - - if ($this->file('file') && is_array($this->file('file'))) { - $rules['file.*'] = $this->fileValidation(); - } elseif ($this->file('file')) { - $rules['file'] = $this->fileValidation(); - } + $rules['file'] = 'bail|sometimes|array'; + $rules['file.*'] = $this->fileValidation(); + $rules['documents'] = 'bail|sometimes|array'; + $rules['documents.*'] = $this->fileValidation(); $rules['is_public'] = 'sometimes|boolean'; @@ -53,11 +47,18 @@ class UploadCreditRequest extends Request { $input = $this->all(); + if ($this->file('documents') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('documents', [$this->file('documents')]); + } + + if ($this->file('file') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('file', [$this->file('file')]); + } + if (isset($input['is_public'])) { $input['is_public'] = $this->toBoolean($input['is_public']); } $this->replace($input); - } } diff --git a/app/Http/Requests/Design/CreateDesignRequest.php b/app/Http/Requests/Design/CreateDesignRequest.php index effd70a7dc..c5198e54bf 100644 --- a/app/Http/Requests/Design/CreateDesignRequest.php +++ b/app/Http/Requests/Design/CreateDesignRequest.php @@ -1,4 +1,5 @@ all(); - + if (array_key_exists('entity_id', $input)) { $input['entity_id'] = $this->decodePrimaryKey($input['entity_id']); } diff --git a/app/Http/Requests/EInvoice/Peppol/StoreEntityRequest.php b/app/Http/Requests/EInvoice/Peppol/StoreEntityRequest.php index 5654de4a18..e11b54a0d1 100644 --- a/app/Http/Requests/EInvoice/Peppol/StoreEntityRequest.php +++ b/app/Http/Requests/EInvoice/Peppol/StoreEntityRequest.php @@ -76,7 +76,7 @@ class StoreEntityRequest extends FormRequest $input['acts_as_receiver'] = $input['acts_as_receiver'] ?? true; $input['acts_as_sender'] = $input['acts_as_sender'] ?? true; - + $this->replace($input); } diff --git a/app/Http/Requests/EInvoice/Peppol/UpdateEntityRequest.php b/app/Http/Requests/EInvoice/Peppol/UpdateEntityRequest.php index 12e028cb6e..d2ad78995d 100644 --- a/app/Http/Requests/EInvoice/Peppol/UpdateEntityRequest.php +++ b/app/Http/Requests/EInvoice/Peppol/UpdateEntityRequest.php @@ -53,7 +53,7 @@ class UpdateEntityRequest extends FormRequest $this->replace($input); } - // public function after(): array + // public function after(): array // { // return [ // function (Validator $validator) { diff --git a/app/Http/Requests/EInvoice/SignupRequest.php b/app/Http/Requests/EInvoice/SignupRequest.php index 14f92c30a6..f814f21027 100644 --- a/app/Http/Requests/EInvoice/SignupRequest.php +++ b/app/Http/Requests/EInvoice/SignupRequest.php @@ -1,4 +1,5 @@ entity_plural = "purchase_orders"; } @@ -144,7 +145,7 @@ class SendEmailRequest extends Request return false; } - if($user->hasExactPermission('disable_emails')){ + if ($user->hasExactPermission('disable_emails')) { $this->error_message = ctrans('texts.disable_emails_error'); return false; } diff --git a/app/Http/Requests/Expense/BulkExpenseRequest.php b/app/Http/Requests/Expense/BulkExpenseRequest.php index 93d45b509e..35fb28b2d3 100644 --- a/app/Http/Requests/Expense/BulkExpenseRequest.php +++ b/app/Http/Requests/Expense/BulkExpenseRequest.php @@ -1,4 +1,5 @@ file('documents') instanceof \Illuminate\Http\UploadedFile) { $this->files->set('documents', [$this->file('documents')]); } - + $this->replace($input); } diff --git a/app/Http/Requests/Expense/EditExpenseRequest.php b/app/Http/Requests/Expense/EditExpenseRequest.php index e7d30bbc5b..52a124165e 100644 --- a/app/Http/Requests/Expense/EditExpenseRequest.php +++ b/app/Http/Requests/Expense/EditExpenseRequest.php @@ -1,4 +1,5 @@ file('documents') && is_array($this->file('documents'))) { - $rules['documents.*'] = $this->fileValidation(); - } elseif ($this->file('documents')) { - $rules['documents'] = $this->fileValidation(); - } - - if ($this->file('file') && is_array($this->file('file'))) { - $rules['file.*'] = $this->fileValidation(); - } elseif ($this->file('file')) { - $rules['file'] = $this->fileValidation(); - } - + $rules['file'] = 'bail|sometimes|array'; + $rules['file.*'] = $this->fileValidation(); + $rules['documents'] = 'bail|sometimes|array'; + $rules['documents.*'] = $this->fileValidation(); $rules['is_public'] = 'sometimes|boolean'; return $rules; @@ -53,6 +45,14 @@ class UploadExpenseRequest extends Request { $input = $this->all(); + if ($this->file('documents') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('documents', [$this->file('documents')]); + } + + if ($this->file('file') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('file', [$this->file('file')]); + } + if (isset($input['is_public'])) { $input['is_public'] = $this->toBoolean($input['is_public']); } diff --git a/app/Http/Requests/ExpenseCategory/BulkExpenseCategoryRequest.php b/app/Http/Requests/ExpenseCategory/BulkExpenseCategoryRequest.php index 3d6a4db5a6..5e19241a94 100644 --- a/app/Http/Requests/ExpenseCategory/BulkExpenseCategoryRequest.php +++ b/app/Http/Requests/ExpenseCategory/BulkExpenseCategoryRequest.php @@ -1,4 +1,5 @@ file('documents') && is_array($this->file('documents'))) { - $rules['documents.*'] = $this->fileValidation(); - } elseif ($this->file('documents')) { - $rules['documents'] = $this->fileValidation(); - } - - if ($this->file('file') && is_array($this->file('file'))) { - $rules['file.*'] = $this->fileValidation(); - } elseif ($this->file('file')) { - $rules['file'] = $this->fileValidation(); - } + $rules['file'] = 'bail|sometimes|array'; + $rules['file.*'] = $this->fileValidation(); + $rules['documents'] = 'bail|sometimes|array'; + $rules['documents.*'] = $this->fileValidation(); return $rules; } + + public function prepareForValidation() + { + $input = $this->all(); + + if ($this->file('documents') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('documents', [$this->file('documents')]); + } + + if ($this->file('file') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('file', [$this->file('file')]); + } + + $this->replace($input); + } } diff --git a/app/Http/Requests/Import/ImportJsonRequest.php b/app/Http/Requests/Import/ImportJsonRequest.php index 3481bede37..d18dd7231d 100644 --- a/app/Http/Requests/Import/ImportJsonRequest.php +++ b/app/Http/Requests/Import/ImportJsonRequest.php @@ -1,4 +1,5 @@ where('company_id', $user->company()->id)->where('is_deleted', 0)]; - if ($this->file('documents') && is_array($this->file('documents'))) { - $rules['documents.*'] = $this->fileValidation(); - } elseif ($this->file('documents')) { - $rules['documents'] = $this->fileValidation(); - } else { - $rules['documents'] = 'bail|sometimes|array'; - } - - if ($this->file('file') && is_array($this->file('file'))) { - $rules['file.*'] = $this->fileValidation(); - } elseif ($this->file('file')) { - $rules['file'] = $this->fileValidation(); - } - + $rules['file'] = 'bail|sometimes|array'; + $rules['file.*'] = $this->fileValidation(); + $rules['documents'] = 'bail|sometimes|array'; + $rules['documents.*'] = $this->fileValidation(); $rules['number'] = ['bail', 'nullable', Rule::unique('invoices')->where('company_id', $user->company()->id)]; $rules['invitations'] = 'sometimes|bail|array'; @@ -113,6 +104,14 @@ class StoreInvoiceRequest extends Request $input['amount'] = 0; $input['balance'] = 0; + if ($this->file('documents') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('documents', [$this->file('documents')]); + } + + if ($this->file('file') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('file', [$this->file('file')]); + } + if (isset($input['line_items']) && is_array($input['line_items'])) { $input['line_items'] = isset($input['line_items']) ? $this->cleanItems($input['line_items']) : []; $input['line_items'] = $this->cleanFeeItems($input['line_items']); diff --git a/app/Http/Requests/Invoice/UpdateInvoiceRequest.php b/app/Http/Requests/Invoice/UpdateInvoiceRequest.php index c4871ff939..d7dfefc6f4 100644 --- a/app/Http/Requests/Invoice/UpdateInvoiceRequest.php +++ b/app/Http/Requests/Invoice/UpdateInvoiceRequest.php @@ -1,4 +1,5 @@ file('documents') && is_array($this->file('documents'))) { - $rules['documents.*'] = $this->fileValidation(); - } elseif ($this->file('documents')) { - $rules['documents'] = $this->fileValidation(); - } else { - $rules['documents'] = 'bail|sometimes|array'; - } - - if ($this->file('file') && is_array($this->file('file'))) { - $rules['file.*'] = $this->fileValidation(); - } elseif ($this->file('file')) { - $rules['file'] = $this->fileValidation(); - } - - // $rules['id'] = new LockedInvoiceRule($this->invoice); + $rules['file'] = 'bail|sometimes|array'; + $rules['file.*'] = $this->fileValidation(); + $rules['documents'] = 'bail|sometimes|array'; + $rules['documents.*'] = $this->fileValidation(); $rules['number'] = ['bail', 'sometimes', 'nullable', Rule::unique('invoices')->where('company_id', $user->company()->id)->ignore($this->invoice->id)]; @@ -95,7 +85,7 @@ class UpdateInvoiceRequest extends Request $rules['due_date'] = ['bail', 'sometimes', 'nullable', 'after:partial_due_date', 'after_or_equal:date', Rule::requiredIf(fn () => strlen($this->partial_due_date) > 1), 'date']; $rules['e_invoice'] = ['sometimes', 'nullable', new ValidInvoiceScheme()]; - + $rules['location_id'] = ['nullable', 'sometimes','bail', Rule::exists('locations', 'id')->where('company_id', $user->company()->id)->where('client_id', $this->invoice->client_id)]; return $rules; @@ -109,6 +99,14 @@ class UpdateInvoiceRequest extends Request $input['id'] = $this->invoice->id; + if ($this->file('documents') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('documents', [$this->file('documents')]); + } + + if ($this->file('file') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('file', [$this->file('file')]); + } + if (isset($input['partial']) && $input['partial'] == 0) { $input['partial_due_date'] = null; } diff --git a/app/Http/Requests/Invoice/UpdateReminderRequest.php b/app/Http/Requests/Invoice/UpdateReminderRequest.php index 53823325c0..1942f8c3ee 100644 --- a/app/Http/Requests/Invoice/UpdateReminderRequest.php +++ b/app/Http/Requests/Invoice/UpdateReminderRequest.php @@ -1,4 +1,5 @@ file('documents') && is_array($this->file('documents'))) { - $rules['documents.*'] = $this->fileValidation(); - } elseif ($this->file('documents')) { - $rules['documents'] = $this->fileValidation(); - } - - if ($this->file('file') && is_array($this->file('file'))) { - $rules['file.*'] = $this->fileValidation(); - } elseif ($this->file('file')) { - $rules['file'] = $this->fileValidation(); - } - + $rules['file'] = 'bail|sometimes|array'; + $rules['file.*'] = $this->fileValidation(); + $rules['documents'] = 'bail|sometimes|array'; + $rules['documents.*'] = $this->fileValidation(); $rules['is_public'] = 'sometimes|boolean'; return $rules; @@ -53,6 +45,14 @@ class UploadInvoiceRequest extends Request { $input = $this->all(); + if ($this->file('documents') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('documents', [$this->file('documents')]); + } + + if ($this->file('file') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('file', [$this->file('file')]); + } + if (isset($input['is_public'])) { $input['is_public'] = $this->toBoolean($input['is_public']); } diff --git a/app/Http/Requests/Location/BulkLocationRequest.php b/app/Http/Requests/Location/BulkLocationRequest.php index 56590aee06..331917d5ed 100644 --- a/app/Http/Requests/Location/BulkLocationRequest.php +++ b/app/Http/Requests/Location/BulkLocationRequest.php @@ -1,4 +1,5 @@ companyId(); $rules['country_id'] = 'integer|bail|exists:countries,id'; - + return $this->globalRules($rules); } diff --git a/app/Http/Requests/Location/UpdateLocationRequest.php b/app/Http/Requests/Location/UpdateLocationRequest.php index 653fcbe1b3..666827fb3f 100644 --- a/app/Http/Requests/Location/UpdateLocationRequest.php +++ b/app/Http/Requests/Location/UpdateLocationRequest.php @@ -1,4 +1,5 @@ where('company_id', $user->company()->id)->ignore($this->location->id); } - + $rules['client_id'] = 'required_without:vendor_id|nullable|integer|bail|exists:clients,id,company_id,'.$user->companyId(); $rules['vendor_id'] = 'required_without:client_id|nullable|integer|bail|exists:vendors,id,company_id,'.$user->companyId(); diff --git a/app/Http/Requests/Login/LoginRequest.php b/app/Http/Requests/Login/LoginRequest.php index f0ff87f3fc..b37f554994 100644 --- a/app/Http/Requests/Login/LoginRequest.php +++ b/app/Http/Requests/Login/LoginRequest.php @@ -1,4 +1,5 @@ ['bail', 'numeric', new PaymentAmountsBalanceRule(), 'max:99999999999999'], 'number' => ['bail', 'nullable', Rule::unique('payments')->where('company_id', $user->company()->id)], 'idempotency_key' => ['nullable', 'bail', 'string','max:64', Rule::unique('payments')->where('company_id', $user->company()->id)], - 'date' => ['bail','nullable', 'sometimes', 'date:Y-m-d'], + 'date' => ['bail', 'nullable', 'sometimes', 'date:Y-m-d'], ]; - if ($this->file('documents') && is_array($this->file('documents'))) { - $rules['documents.*'] = $this->fileValidation(); - } elseif ($this->file('documents')) { - $rules['documents'] = $this->fileValidation(); - } else { - $rules['documents'] = 'bail|sometimes|array'; - } - - if ($this->file('file') && is_array($this->file('file'))) { - $rules['file.*'] = $this->fileValidation(); - } elseif ($this->file('file')) { - $rules['file'] = $this->fileValidation(); - } + $rules['file'] = 'bail|sometimes|array'; + $rules['file.*'] = $this->fileValidation(); + $rules['documents'] = 'bail|sometimes|array'; + $rules['documents.*'] = $this->fileValidation(); return $rules; } @@ -87,6 +79,14 @@ class StorePaymentRequest extends Request throw new DuplicatePaymentException('Duplicate request.', 429); } + if ($this->file('documents') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('documents', [$this->file('documents')]); + } + + if ($this->file('file') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('file', [$this->file('file')]); + } + \Illuminate\Support\Facades\Cache::put(($this->ip()."|".$this->input('amount', 0)."|".$client_id."|".$user->company()->company_key), true, 1); $input = $this->all(); diff --git a/app/Http/Requests/Payment/UpdatePaymentRequest.php b/app/Http/Requests/Payment/UpdatePaymentRequest.php index 6fc0797b2b..ad5a450cb7 100644 --- a/app/Http/Requests/Payment/UpdatePaymentRequest.php +++ b/app/Http/Requests/Payment/UpdatePaymentRequest.php @@ -1,4 +1,5 @@ ['required', 'bail'], ]; - if ($this->file('documents') && is_array($this->file('documents'))) { - $rules['documents.*'] = $this->fileValidation(); - } elseif ($this->file('documents')) { - $rules['documents'] = $this->fileValidation(); - } else { - $rules['documents'] = 'bail|sometimes|array'; - } - - if ($this->file('file') && is_array($this->file('file'))) { - $rules['file.*'] = $this->fileValidation(); - } elseif ($this->file('file')) { - $rules['file'] = $this->fileValidation(); - } + $rules['file'] = 'bail|sometimes|array'; + $rules['file.*'] = $this->fileValidation(); + $rules['documents'] = 'bail|sometimes|array'; + $rules['documents.*'] = $this->fileValidation(); return $rules; } @@ -74,6 +66,14 @@ class UpdatePaymentRequest extends Request $input = $this->decodePrimaryKeys($input); + if ($this->file('documents') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('documents', [$this->file('documents')]); + } + + if ($this->file('file') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('file', [$this->file('file')]); + } + if (isset($input['amount'])) { unset($input['amount']); } diff --git a/app/Http/Requests/Payment/UploadPaymentRequest.php b/app/Http/Requests/Payment/UploadPaymentRequest.php index b9f42da38f..b78492774d 100644 --- a/app/Http/Requests/Payment/UploadPaymentRequest.php +++ b/app/Http/Requests/Payment/UploadPaymentRequest.php @@ -1,4 +1,5 @@ file('documents') && is_array($this->file('documents'))) { - $rules['documents.*'] = $this->fileValidation(); - } elseif ($this->file('documents')) { - $rules['documents'] = $this->fileValidation(); - } - - if ($this->file('file') && is_array($this->file('file'))) { - $rules['file.*'] = $this->fileValidation(); - } elseif ($this->file('file')) { - $rules['file'] = $this->fileValidation(); - } + $rules['file'] = 'bail|sometimes|array'; + $rules['file.*'] = $this->fileValidation(); + $rules['documents'] = 'bail|sometimes|array'; + $rules['documents.*'] = $this->fileValidation(); $rules['is_public'] = 'sometimes|boolean'; @@ -53,11 +47,18 @@ class UploadPaymentRequest extends Request { $input = $this->all(); + if ($this->file('documents') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('documents', [$this->file('documents')]); + } + + if ($this->file('file') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('file', [$this->file('file')]); + } + if (isset($input['is_public'])) { $input['is_public'] = $this->toBoolean($input['is_public']); } $this->replace($input); - } } diff --git a/app/Http/Requests/PaymentTerm/ActionPaymentTermRequest.php b/app/Http/Requests/PaymentTerm/ActionPaymentTermRequest.php index 73ca148548..33837685da 100644 --- a/app/Http/Requests/PaymentTerm/ActionPaymentTermRequest.php +++ b/app/Http/Requests/PaymentTerm/ActionPaymentTermRequest.php @@ -1,4 +1,5 @@ user(); diff --git a/app/Http/Requests/Preview/ShowPreviewRequest.php b/app/Http/Requests/Preview/ShowPreviewRequest.php index 7b2adba9dc..a794bb2cd5 100644 --- a/app/Http/Requests/Preview/ShowPreviewRequest.php +++ b/app/Http/Requests/Preview/ShowPreviewRequest.php @@ -1,4 +1,5 @@ file('documents') && is_array($this->file('documents'))) { - $rules['documents.*'] = $this->fileValidation(); - } elseif ($this->file('documents')) { - $rules['documents'] = $this->fileValidation(); - } else { - $rules['documents'] = 'bail|sometimes|array'; - } - - if ($this->file('file') && is_array($this->file('file'))) { - $rules['file.*'] = $this->fileValidation(); - } elseif ($this->file('file')) { - $rules['file'] = $this->fileValidation(); - } + $rules = []; + $rules['file'] = 'bail|sometimes|array'; + $rules['file.*'] = $this->fileValidation(); + $rules['documents'] = 'bail|sometimes|array'; + $rules['documents.*'] = $this->fileValidation(); $rules['cost'] = 'sometimes|numeric'; $rules['price'] = 'sometimes|numeric'; @@ -64,6 +57,14 @@ class StoreProductRequest extends Request { $input = $this->all(); + if ($this->file('documents') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('documents', [$this->file('documents')]); + } + + if ($this->file('file') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('file', [$this->file('file')]); + } + if (! isset($input['quantity'])) { $input['quantity'] = 1; } diff --git a/app/Http/Requests/Product/UpdateProductRequest.php b/app/Http/Requests/Product/UpdateProductRequest.php index da613a3e5e..b993c15bd5 100644 --- a/app/Http/Requests/Product/UpdateProductRequest.php +++ b/app/Http/Requests/Product/UpdateProductRequest.php @@ -1,4 +1,5 @@ file('documents') && is_array($this->file('documents'))) { - $rules['documents.*'] = $this->fileValidation(); - } elseif ($this->file('documents')) { - $rules['documents'] = $this->fileValidation(); - } else { - $rules['documents'] = 'bail|sometimes|array'; - } - - if ($this->file('file') && is_array($this->file('file'))) { - $rules['file.*'] = $this->fileValidation(); - } elseif ($this->file('file')) { - $rules['file'] = $this->fileValidation(); - } + $rules = []; + $rules['file'] = 'bail|sometimes|array'; + $rules['file.*'] = $this->fileValidation(); + $rules['documents'] = 'bail|sometimes|array'; + $rules['documents.*'] = $this->fileValidation(); $rules['cost'] = 'numeric'; $rules['price'] = 'numeric'; @@ -62,6 +55,14 @@ class UpdateProductRequest extends Request { $input = $this->all(); + if ($this->file('documents') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('documents', [$this->file('documents')]); + } + + if ($this->file('file') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('file', [$this->file('file')]); + } + if (! isset($input['quantity'])) { $input['quantity'] = 1; } diff --git a/app/Http/Requests/Product/UploadProductRequest.php b/app/Http/Requests/Product/UploadProductRequest.php index 6d2f662e50..e1c35706c0 100644 --- a/app/Http/Requests/Product/UploadProductRequest.php +++ b/app/Http/Requests/Product/UploadProductRequest.php @@ -1,4 +1,5 @@ file('documents') && is_array($this->file('documents'))) { - $rules['documents.*'] = $this->fileValidation(); - } elseif ($this->file('documents')) { - $rules['documents'] = $this->fileValidation(); - } - - if ($this->file('file') && is_array($this->file('file'))) { - $rules['file.*'] = $this->fileValidation(); - } elseif ($this->file('file')) { - $rules['file'] = $this->fileValidation(); - } + $rules['file'] = 'bail|sometimes|array'; + $rules['file.*'] = $this->fileValidation(); + $rules['documents'] = 'bail|sometimes|array'; + $rules['documents.*'] = $this->fileValidation(); $rules['is_public'] = 'sometimes|boolean'; return $rules; @@ -52,11 +46,18 @@ class UploadProductRequest extends Request { $input = $this->all(); + if ($this->file('documents') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('documents', [$this->file('documents')]); + } + + if ($this->file('file') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('file', [$this->file('file')]); + } + if (isset($input['is_public'])) { $input['is_public'] = $this->toBoolean($input['is_public']); } $this->replace($input); - } } diff --git a/app/Http/Requests/Project/BulkProjectRequest.php b/app/Http/Requests/Project/BulkProjectRequest.php index d9864451d9..9c874819e9 100644 --- a/app/Http/Requests/Project/BulkProjectRequest.php +++ b/app/Http/Requests/Project/BulkProjectRequest.php @@ -1,4 +1,5 @@ 'required|string', // 'ids' => 'required|array', - 'ids' => ['required', 'array', function($attribute, $value, $fail) { + 'ids' => ['required', 'array', function ($attribute, $value, $fail) { $projects = \App\Models\Project::withTrashed()->whereIn('id', $this->transformKeys($value))->company()->get(); - if($projects->isEmpty()) { + if ($projects->isEmpty()) { return; } $clientId = $projects->first()->client_id; - - if($this->action == 'invoice' && $projects->contains('client_id', '!=', $clientId)) { + + if ($this->action == 'invoice' && $projects->contains('client_id', '!=', $clientId)) { $fail('All selected projects must belong to the same client.'); } - }], + }], 'template' => 'sometimes|string', 'template_id' => 'sometimes|string', 'send_email' => 'sometimes|bool' diff --git a/app/Http/Requests/Project/CreateProjectRequest.php b/app/Http/Requests/Project/CreateProjectRequest.php index 6f914c92c2..e8f08198cf 100644 --- a/app/Http/Requests/Project/CreateProjectRequest.php +++ b/app/Http/Requests/Project/CreateProjectRequest.php @@ -1,4 +1,5 @@ where('company_id', $user->company()->id); } - if ($this->file('documents') && is_array($this->file('documents'))) { - $rules['documents.*'] = $this->fileValidation(); - } elseif ($this->file('documents')) { - $rules['documents'] = $this->fileValidation(); - } else { - $rules['documents'] = 'bail|sometimes|array'; - } - if ($this->file('file') && is_array($this->file('file'))) { - $rules['file.*'] = $this->fileValidation(); - } elseif ($this->file('file')) { - $rules['file'] = $this->fileValidation(); - } + $rules['file'] = 'bail|sometimes|array'; + $rules['file.*'] = $this->fileValidation(); + $rules['documents'] = 'bail|sometimes|array'; + $rules['documents.*'] = $this->fileValidation(); return $this->globalRules($rules); } @@ -72,6 +65,15 @@ class StoreProjectRequest extends Request { $input = $this->decodePrimaryKeys($this->all()); + + if ($this->file('documents') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('documents', [$this->file('documents')]); + } + + if ($this->file('file') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('file', [$this->file('file')]); + } + if (array_key_exists('color', $input) && is_null($input['color'])) { $input['color'] = ''; } diff --git a/app/Http/Requests/Project/UpdateProjectRequest.php b/app/Http/Requests/Project/UpdateProjectRequest.php index d7209f758a..a927e5a491 100644 --- a/app/Http/Requests/Project/UpdateProjectRequest.php +++ b/app/Http/Requests/Project/UpdateProjectRequest.php @@ -1,4 +1,5 @@ file('documents') && is_array($this->file('documents'))) { - $rules['documents.*'] = $this->fileValidation(); - } elseif ($this->file('documents')) { - $rules['documents'] = $this->fileValidation(); - } else { - $rules['documents'] = 'bail|sometimes|array'; - } - - if ($this->file('file') && is_array($this->file('file'))) { - $rules['file.*'] = $this->fileValidation(); - } elseif ($this->file('file')) { - $rules['file'] = $this->fileValidation(); - } + $rules['file'] = 'bail|sometimes|array'; + $rules['file.*'] = $this->fileValidation(); + $rules['documents'] = 'bail|sometimes|array'; + $rules['documents.*'] = $this->fileValidation(); return $this->globalRules($rules); } @@ -69,6 +60,14 @@ class UpdateProjectRequest extends Request { $input = $this->decodePrimaryKeys($this->all()); + if ($this->file('documents') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('documents', [$this->file('documents')]); + } + + if ($this->file('file') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('file', [$this->file('file')]); + } + if (isset($input['client_id'])) { unset($input['client_id']); } diff --git a/app/Http/Requests/Project/UploadProjectRequest.php b/app/Http/Requests/Project/UploadProjectRequest.php index df2caeba46..6cae8841d6 100644 --- a/app/Http/Requests/Project/UploadProjectRequest.php +++ b/app/Http/Requests/Project/UploadProjectRequest.php @@ -1,4 +1,5 @@ file('documents') && is_array($this->file('documents'))) { - $rules['documents.*'] = $this->fileValidation(); - } elseif ($this->file('documents')) { - $rules['documents'] = $this->fileValidation(); - } - - if ($this->file('file') && is_array($this->file('file'))) { - $rules['file.*'] = $this->fileValidation(); - } elseif ($this->file('file')) { - $rules['file'] = $this->fileValidation(); - } - + $rules['file'] = 'bail|sometimes|array'; + $rules['file.*'] = $this->fileValidation(); + $rules['documents'] = 'bail|sometimes|array'; + $rules['documents.*'] = $this->fileValidation(); $rules['is_public'] = 'sometimes|boolean'; return $rules; @@ -53,11 +46,18 @@ class UploadProjectRequest extends Request { $input = $this->all(); + if ($this->file('documents') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('documents', [$this->file('documents')]); + } + + if ($this->file('file') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('file', [$this->file('file')]); + } + if (isset($input['is_public'])) { $input['is_public'] = $this->toBoolean($input['is_public']); } $this->replace($input); - } } diff --git a/app/Http/Requests/PurchaseOrder/ActionPurchaseOrderRequest.php b/app/Http/Requests/PurchaseOrder/ActionPurchaseOrderRequest.php index f2033c4e00..383f95a7ee 100644 --- a/app/Http/Requests/PurchaseOrder/ActionPurchaseOrderRequest.php +++ b/app/Http/Requests/PurchaseOrder/ActionPurchaseOrderRequest.php @@ -1,4 +1,5 @@ where('company_id', $user->company()->id)]; - $rules['invitations'] = 'sometimes|bail|array'; $rules['invitations.*.vendor_contact_id'] = 'bail|required|distinct'; @@ -58,20 +58,10 @@ class StorePurchaseOrderRequest extends Request $rules['is_amount_discount'] = ['boolean']; $rules['line_items'] = 'array'; - if ($this->file('documents') && is_array($this->file('documents'))) { - $rules['documents.*'] = $this->fileValidation(); - } elseif ($this->file('documents')) { - $rules['documents'] = $this->fileValidation(); - } else { - $rules['documents'] = 'bail|sometimes|array'; - } - - if ($this->file('file') && is_array($this->file('file'))) { - $rules['file.*'] = $this->fileValidation(); - } elseif ($this->file('file')) { - $rules['file'] = $this->fileValidation(); - } - + $rules['file'] = 'bail|sometimes|array'; + $rules['file.*'] = $this->fileValidation(); + $rules['documents'] = 'bail|sometimes|array'; + $rules['documents.*'] = $this->fileValidation(); $rules['status_id'] = 'nullable|integer|in:1,2,3,4,5'; $rules['exchange_rate'] = 'bail|sometimes|numeric'; @@ -95,6 +85,14 @@ class StorePurchaseOrderRequest extends Request $input['amount'] = 0; $input['balance'] = 0; + if ($this->file('documents') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('documents', [$this->file('documents')]); + } + + if ($this->file('file') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('file', [$this->file('file')]); + } + if (isset($input['partial']) && $input['partial'] == 0) { $input['partial_due_date'] = null; } diff --git a/app/Http/Requests/PurchaseOrder/UpdatePurchaseOrderRequest.php b/app/Http/Requests/PurchaseOrder/UpdatePurchaseOrderRequest.php index 1ca6d0fd9a..787662e5aa 100644 --- a/app/Http/Requests/PurchaseOrder/UpdatePurchaseOrderRequest.php +++ b/app/Http/Requests/PurchaseOrder/UpdatePurchaseOrderRequest.php @@ -1,4 +1,5 @@ file('documents') && is_array($this->file('documents'))) { - $rules['documents.*'] = $this->fileValidation(); - } elseif ($this->file('documents')) { - $rules['documents'] = $this->fileValidation(); - } else { - $rules['documents'] = 'bail|sometimes|array'; - } - - if ($this->file('file') && is_array($this->file('file'))) { - $rules['file.*'] = $this->fileValidation(); - } elseif ($this->file('file')) { - $rules['file'] = $this->fileValidation(); - } - + $rules['file'] = 'bail|sometimes|array'; + $rules['file.*'] = $this->fileValidation(); + $rules['documents'] = 'bail|sometimes|array'; + $rules['documents.*'] = $this->fileValidation(); $rules['status_id'] = 'sometimes|integer|in:1,2,3,4,5'; $rules['exchange_rate'] = 'bail|sometimes|numeric'; $rules['amount'] = ['sometimes', 'bail', 'numeric', 'max:99999999999999']; - + $rules['custom_surcharge1'] = ['sometimes', 'nullable', 'bail', 'numeric', 'max:99999999999999']; $rules['custom_surcharge2'] = ['sometimes', 'nullable', 'bail', 'numeric', 'max:99999999999999']; $rules['custom_surcharge3'] = ['sometimes', 'nullable', 'bail', 'numeric', 'max:99999999999999']; @@ -95,6 +86,14 @@ class UpdatePurchaseOrderRequest extends Request $input['id'] = $this->purchase_order->id; + if ($this->file('documents') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('documents', [$this->file('documents')]); + } + + if ($this->file('file') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('file', [$this->file('file')]); + } + if (isset($input['partial']) && $input['partial'] == 0) { $input['partial_due_date'] = null; } diff --git a/app/Http/Requests/PurchaseOrder/UploadPurchaseOrderRequest.php b/app/Http/Requests/PurchaseOrder/UploadPurchaseOrderRequest.php index b8beca6666..02d12102eb 100644 --- a/app/Http/Requests/PurchaseOrder/UploadPurchaseOrderRequest.php +++ b/app/Http/Requests/PurchaseOrder/UploadPurchaseOrderRequest.php @@ -1,4 +1,5 @@ file('documents') && is_array($this->file('documents'))) { - $rules['documents.*'] = $this->fileValidation(); - } elseif ($this->file('documents')) { - $rules['documents'] = $this->fileValidation(); - } - - if ($this->file('file') && is_array($this->file('file'))) { - $rules['file.*'] = $this->fileValidation(); - } elseif ($this->file('file')) { - $rules['file'] = $this->fileValidation(); - } - + $rules['file'] = 'bail|sometimes|array'; + $rules['file.*'] = $this->fileValidation(); + $rules['documents'] = 'bail|sometimes|array'; + $rules['documents.*'] = $this->fileValidation(); $rules['is_public'] = 'sometimes|boolean'; return $rules; @@ -53,11 +46,18 @@ class UploadPurchaseOrderRequest extends Request { $input = $this->all(); + if ($this->file('documents') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('documents', [$this->file('documents')]); + } + + if ($this->file('file') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('file', [$this->file('file')]); + } + if (isset($input['is_public'])) { $input['is_public'] = $this->toBoolean($input['is_public']); } $this->replace($input); - } } diff --git a/app/Http/Requests/Quote/ActionQuoteRequest.php b/app/Http/Requests/Quote/ActionQuoteRequest.php index 03c087f2ae..f821e28cc2 100644 --- a/app/Http/Requests/Quote/ActionQuoteRequest.php +++ b/app/Http/Requests/Quote/ActionQuoteRequest.php @@ -1,4 +1,5 @@ where('company_id', $user->company()->id)->where('is_deleted', 0)]; - if ($this->file('documents') && is_array($this->file('documents'))) { - $rules['documents.*'] = $this->fileValidation(); - } elseif ($this->file('documents')) { - $rules['documents'] = $this->fileValidation(); - } else { - $rules['documents'] = 'bail|sometimes|array'; - } - - if ($this->file('file') && is_array($this->file('file'))) { - $rules['file.*'] = $this->fileValidation(); - } elseif ($this->file('file')) { - $rules['file'] = $this->fileValidation(); - } + $rules['file'] = 'bail|sometimes|array'; + $rules['file.*'] = $this->fileValidation(); + $rules['documents'] = 'bail|sometimes|array'; + $rules['documents.*'] = $this->fileValidation(); $rules['number'] = ['bail','nullable', Rule::unique('quotes')->where('company_id', $user->company()->id)]; @@ -106,6 +98,15 @@ class StoreQuoteRequest extends Request $input['amount'] = 0; $input['balance'] = 0; + + if ($this->file('documents') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('documents', [$this->file('documents')]); + } + + if ($this->file('file') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('file', [$this->file('file')]); + } + if (isset($input['line_items']) && is_array($input['line_items'])) { $input['line_items'] = isset($input['line_items']) ? $this->cleanItems($input['line_items']) : []; $input['line_items'] = $this->cleanFeeItems($input['line_items']); diff --git a/app/Http/Requests/Quote/UpdateQuoteRequest.php b/app/Http/Requests/Quote/UpdateQuoteRequest.php index aa6cc82e5c..3ce9113cf5 100644 --- a/app/Http/Requests/Quote/UpdateQuoteRequest.php +++ b/app/Http/Requests/Quote/UpdateQuoteRequest.php @@ -1,4 +1,5 @@ user(); $rules = []; - if ($this->file('documents') && is_array($this->file('documents'))) { - $rules['documents.*'] = $this->fileValidation(); - } elseif ($this->file('documents')) { - $rules['documents'] = $this->fileValidation(); - } else { - $rules['documents'] = 'bail|sometimes|array'; - } - - if ($this->file('file') && is_array($this->file('file'))) { - $rules['file.*'] = $this->fileValidation(); - } elseif ($this->file('file')) { - $rules['file'] = $this->fileValidation(); - } + $rules['file'] = 'bail|sometimes|array'; + $rules['file.*'] = $this->fileValidation(); + $rules['documents'] = 'bail|sometimes|array'; + $rules['documents.*'] = $this->fileValidation(); $rules['invitations'] = 'sometimes|bail|array'; $rules['invitations.*.client_contact_id'] = 'bail|required|distinct'; @@ -78,7 +70,7 @@ class UpdateQuoteRequest extends Request $rules['custom_surcharge4'] = ['sometimes', 'nullable', 'bail', 'numeric', 'max:99999999999999']; $rules['location_id'] = ['nullable', 'sometimes','bail', Rule::exists('locations', 'id')->where('company_id', $user->company()->id)->where('client_id', $this->quote->client_id)]; - + return $rules; } @@ -90,6 +82,14 @@ class UpdateQuoteRequest extends Request $input['id'] = $this->quote->id; + if ($this->file('documents') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('documents', [$this->file('documents')]); + } + + if ($this->file('file') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('file', [$this->file('file')]); + } + if (isset($input['line_items'])) { $input['line_items'] = isset($input['line_items']) ? $this->cleanItems($input['line_items']) : []; $input['amount'] = $this->entityTotalAmount($input['line_items']); diff --git a/app/Http/Requests/Quote/UploadQuoteRequest.php b/app/Http/Requests/Quote/UploadQuoteRequest.php index cdc6454e33..a3d1ef0486 100644 --- a/app/Http/Requests/Quote/UploadQuoteRequest.php +++ b/app/Http/Requests/Quote/UploadQuoteRequest.php @@ -1,4 +1,5 @@ file('documents') && is_array($this->file('documents'))) { - $rules['documents.*'] = $this->fileValidation(); - } elseif ($this->file('documents')) { - $rules['documents'] = $this->fileValidation(); - } - - if ($this->file('file') && is_array($this->file('file'))) { - $rules['file.*'] = $this->fileValidation(); - } elseif ($this->file('file')) { - $rules['file'] = $this->fileValidation(); - } - + $rules['file'] = 'bail|sometimes|array'; + $rules['file.*'] = $this->fileValidation(); + $rules['documents'] = 'bail|sometimes|array'; + $rules['documents.*'] = $this->fileValidation(); $rules['is_public'] = 'sometimes|boolean'; return $rules; @@ -53,6 +45,14 @@ class UploadQuoteRequest extends Request { $input = $this->all(); + if ($this->file('documents') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('documents', [$this->file('documents')]); + } + + if ($this->file('file') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('file', [$this->file('file')]); + } + if (isset($input['is_public'])) { $input['is_public'] = $this->toBoolean($input['is_public']); } diff --git a/app/Http/Requests/RecurringExpense/BulkRecurringExpenseRequest.php b/app/Http/Requests/RecurringExpense/BulkRecurringExpenseRequest.php index acf6c72ff8..7036c4a308 100644 --- a/app/Http/Requests/RecurringExpense/BulkRecurringExpenseRequest.php +++ b/app/Http/Requests/RecurringExpense/BulkRecurringExpenseRequest.php @@ -1,4 +1,5 @@ file('documents') && is_array($this->file('documents'))) { - $rules['documents.*'] = $this->fileValidation(); - } elseif ($this->file('documents')) { - $rules['documents'] = $this->fileValidation(); - } - - if ($this->file('file') && is_array($this->file('file'))) { - $rules['file.*'] = $this->fileValidation(); - } elseif ($this->file('file')) { - $rules['file'] = $this->fileValidation(); - } + $rules['file'] = 'bail|sometimes|array'; + $rules['file.*'] = $this->fileValidation(); + $rules['documents'] = 'bail|sometimes|array'; + $rules['documents.*'] = $this->fileValidation(); return $this->globalRules($rules); } @@ -81,6 +75,14 @@ class StoreRecurringExpenseRequest extends Request $input = $this->decodePrimaryKeys($input); + if ($this->file('documents') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('documents', [$this->file('documents')]); + } + + if ($this->file('file') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('file', [$this->file('file')]); + } + if (array_key_exists('next_send_date', $input) && is_string($input['next_send_date'])) { $input['next_send_date_client'] = $input['next_send_date']; } diff --git a/app/Http/Requests/RecurringExpense/UpdateRecurringExpenseRequest.php b/app/Http/Requests/RecurringExpense/UpdateRecurringExpenseRequest.php index 9a85efb5b5..e5ddbefd9f 100644 --- a/app/Http/Requests/RecurringExpense/UpdateRecurringExpenseRequest.php +++ b/app/Http/Requests/RecurringExpense/UpdateRecurringExpenseRequest.php @@ -1,4 +1,5 @@ number)) { @@ -47,18 +48,10 @@ class UpdateRecurringExpenseRequest extends Request $rules['tax_amount2'] = 'numeric'; $rules['tax_amount3'] = 'numeric'; $rules['category_id'] = 'bail|nullable|sometimes|exists:expense_categories,id,company_id,'.auth()->user()->company()->id.',is_deleted,0'; - - if ($this->file('documents') && is_array($this->file('documents'))) { - $rules['documents.*'] = $this->fileValidation(); - } elseif ($this->file('documents')) { - $rules['documents'] = $this->fileValidation(); - } - - if ($this->file('file') && is_array($this->file('file'))) { - $rules['file.*'] = $this->fileValidation(); - } elseif ($this->file('file')) { - $rules['file'] = $this->fileValidation(); - } + $rules['file'] = 'bail|sometimes|array'; + $rules['file.*'] = $this->fileValidation(); + $rules['documents'] = 'bail|sometimes|array'; + $rules['documents.*'] = $this->fileValidation(); return $this->globalRules($rules); } @@ -82,6 +75,14 @@ class UpdateRecurringExpenseRequest extends Request $input = $this->decodePrimaryKeys($input); + if ($this->file('documents') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('documents', [$this->file('documents')]); + } + + if ($this->file('file') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('file', [$this->file('file')]); + } + if (array_key_exists('next_send_date', $input) && is_string($input['next_send_date'])) { $input['next_send_date_client'] = $input['next_send_date']; } diff --git a/app/Http/Requests/RecurringExpense/UploadRecurringExpenseRequest.php b/app/Http/Requests/RecurringExpense/UploadRecurringExpenseRequest.php index 36ecda161a..fd1021cb6c 100644 --- a/app/Http/Requests/RecurringExpense/UploadRecurringExpenseRequest.php +++ b/app/Http/Requests/RecurringExpense/UploadRecurringExpenseRequest.php @@ -1,4 +1,5 @@ file('documents') && is_array($this->file('documents'))) { - $rules['documents.*'] = $this->fileValidation(); - } elseif ($this->file('documents')) { - $rules['documents'] = $this->fileValidation(); - } - - if ($this->file('file') && is_array($this->file('file'))) { - $rules['file.*'] = $this->fileValidation(); - } elseif ($this->file('file')) { - $rules['file'] = $this->fileValidation(); - } + $rules['file'] = 'bail|sometimes|array'; + $rules['file.*'] = $this->fileValidation(); + $rules['documents'] = 'bail|sometimes|array'; + $rules['documents.*'] = $this->fileValidation(); return $rules; } + + public function prepareForValidation() + { + + if ($this->file('documents') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('documents', [$this->file('documents')]); + } + + if ($this->file('file') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('file', [$this->file('file')]); + } + } } diff --git a/app/Http/Requests/RecurringInvoice/ActionRecurringInvoiceRequest.php b/app/Http/Requests/RecurringInvoice/ActionRecurringInvoiceRequest.php index 1e20de9cfa..f48c589a8b 100644 --- a/app/Http/Requests/RecurringInvoice/ActionRecurringInvoiceRequest.php +++ b/app/Http/Requests/RecurringInvoice/ActionRecurringInvoiceRequest.php @@ -1,4 +1,5 @@ ['required_if:action,bulk_update', 'string', Rule::in(\App\Models\RecurringInvoice::$bulk_update_columns)], ]; - switch($this->column) { + switch ($this->column) { case 'remaining_cycles': $rules['new_value'] = ['required_if:action,bulk_update', 'string', 'min:1']; break; case 'uses_inclusive_taxes': $rules['new_value'] = ['required_if:action,bulk_update', 'boolean']; break; - + } return $rules; @@ -62,10 +63,10 @@ class BulkRecurringInvoiceRequest extends Request $input['ids'] = $this->transformKeys($input['ids']); } - if(!isset($input['new_value'])) { + if (!isset($input['new_value'])) { $input['new_value'] = ''; } - + $this->replace($input); } } diff --git a/app/Http/Requests/RecurringInvoice/CreateRecurringInvoiceRequest.php b/app/Http/Requests/RecurringInvoice/CreateRecurringInvoiceRequest.php index b76c89eac2..1f4c396bff 100644 --- a/app/Http/Requests/RecurringInvoice/CreateRecurringInvoiceRequest.php +++ b/app/Http/Requests/RecurringInvoice/CreateRecurringInvoiceRequest.php @@ -1,4 +1,5 @@ file('documents') && is_array($this->file('documents'))) { - $rules['documents.*'] = $this->fileValidation(); - } elseif ($this->file('documents')) { - $rules['documents'] = $this->fileValidation(); - } else { - $rules['documents'] = 'bail|sometimes|array'; - } - - if ($this->file('file') && is_array($this->file('file'))) { - $rules['file.*'] = $this->fileValidation(); - } elseif ($this->file('file')) { - $rules['file'] = $this->fileValidation(); - } + $rules['file'] = 'bail|sometimes|array'; + $rules['file.*'] = $this->fileValidation(); + $rules['documents'] = 'bail|sometimes|array'; + $rules['documents.*'] = $this->fileValidation(); $rules['client_id'] = 'required|exists:clients,id,company_id,'.$user->company()->id; @@ -82,7 +74,7 @@ class StoreRecurringInvoiceRequest extends Request $rules['amount'] = ['sometimes', 'bail', 'numeric', 'max:99999999999999']; $rules['location_id'] = ['nullable', 'sometimes','bail', Rule::exists('locations', 'id')->where('company_id', $user->company()->id)->where('client_id', $this->client_id)]; $rules['vendor_id'] = ['nullable', 'sometimes','bail', Rule::exists('vendors', 'id')->where('company_id', $user->company()->id)]; - + return $rules; } @@ -92,6 +84,15 @@ class StoreRecurringInvoiceRequest extends Request $input['amount'] = 0; $input['balance'] = 0; + if ($this->file('documents') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('documents', [$this->file('documents')]); + } + + if ($this->file('file') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('file', [$this->file('file')]); + } + + if (array_key_exists('due_date_days', $input) && is_null($input['due_date_days'])) { $input['due_date_days'] = 'terms'; } diff --git a/app/Http/Requests/RecurringInvoice/UpdateRecurringInvoiceRequest.php b/app/Http/Requests/RecurringInvoice/UpdateRecurringInvoiceRequest.php index b30ca5d58f..696268348c 100644 --- a/app/Http/Requests/RecurringInvoice/UpdateRecurringInvoiceRequest.php +++ b/app/Http/Requests/RecurringInvoice/UpdateRecurringInvoiceRequest.php @@ -1,4 +1,5 @@ file('documents') && is_array($this->file('documents'))) { - $rules['documents.*'] = $this->fileValidation(); - } elseif ($this->file('documents')) { - $rules['documents'] = $this->fileValidation(); - } else { - $rules['documents'] = 'bail|sometimes|array'; - } - - if ($this->file('file') && is_array($this->file('file'))) { - $rules['file.*'] = $this->fileValidation(); - } elseif ($this->file('file')) { - $rules['file'] = $this->fileValidation(); - } + $rules['file'] = 'bail|sometimes|array'; + $rules['file.*'] = $this->fileValidation(); + $rules['documents'] = 'bail|sometimes|array'; + $rules['documents.*'] = $this->fileValidation(); $rules['number'] = ['bail', 'sometimes', Rule::unique('recurring_invoices')->where('company_id', $user->company()->id)->ignore($this->recurring_invoice->id)]; @@ -89,6 +81,14 @@ class UpdateRecurringInvoiceRequest extends Request { $input = $this->all(); + if ($this->file('documents') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('documents', [$this->file('documents')]); + } + + if ($this->file('file') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('file', [$this->file('file')]); + } + if (array_key_exists('due_date_days', $input) && is_null($input['due_date_days'])) { $input['due_date_days'] = 'terms'; } diff --git a/app/Http/Requests/RecurringInvoice/UploadRecurringInvoiceRequest.php b/app/Http/Requests/RecurringInvoice/UploadRecurringInvoiceRequest.php index dd15976d5c..4a3501537c 100644 --- a/app/Http/Requests/RecurringInvoice/UploadRecurringInvoiceRequest.php +++ b/app/Http/Requests/RecurringInvoice/UploadRecurringInvoiceRequest.php @@ -1,4 +1,5 @@ file('documents') && is_array($this->file('documents'))) { - $rules['documents.*'] = $this->fileValidation(); - } elseif ($this->file('documents')) { - $rules['documents'] = $this->fileValidation(); - } - - if ($this->file('file') && is_array($this->file('file'))) { - $rules['file.*'] = $this->fileValidation(); - } elseif ($this->file('file')) { - $rules['file'] = $this->fileValidation(); - } - + $rules['file'] = 'bail|sometimes|array'; + $rules['file.*'] = $this->fileValidation(); + $rules['documents'] = 'bail|sometimes|array'; + $rules['documents.*'] = $this->fileValidation(); $rules['is_public'] = 'sometimes|boolean'; return $rules; @@ -52,6 +44,14 @@ class UploadRecurringInvoiceRequest extends Request public function prepareForValidation() { $input = $this->all(); + + if ($this->file('documents') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('documents', [$this->file('documents')]); + } + + if ($this->file('file') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('file', [$this->file('file')]); + } if (isset($input['is_public'])) { $input['is_public'] = $this->toBoolean($input['is_public']); diff --git a/app/Http/Requests/RecurringQuote/ActionRecurringQuoteRequest.php b/app/Http/Requests/RecurringQuote/ActionRecurringQuoteRequest.php index 83ccf8da86..260fa3e025 100644 --- a/app/Http/Requests/RecurringQuote/ActionRecurringQuoteRequest.php +++ b/app/Http/Requests/RecurringQuote/ActionRecurringQuoteRequest.php @@ -1,4 +1,5 @@ user(); $rules = []; - - if ($this->file('documents') && is_array($this->file('documents'))) { - $rules['documents.*'] = $this->fileValidation(); - } elseif ($this->file('documents')) { - $rules['documents'] = $this->fileValidation(); - } - - if ($this->file('file') && is_array($this->file('file'))) { - $rules['file.*'] = $this->fileValidation(); - } elseif ($this->file('file')) { - $rules['file'] = $this->fileValidation(); - } - + $rules['file'] = 'bail|sometimes|array'; + $rules['file.*'] = $this->fileValidation(); + $rules['documents'] = 'bail|sometimes|array'; + $rules['documents.*'] = $this->fileValidation(); $rules['client_id'] = 'required|exists:clients,id,company_id,'.$user->company()->id; $rules['invitations.*.client_contact_id'] = 'distinct'; $rules['frequency_id'] = 'required|integer|digits_between:1,12'; - $rules['number'] = ['bail', 'nullable', \Illuminate\Validation\Rule::unique('recurring_quotes')->where('company_id', $user->company()->id)]; return $rules; @@ -74,6 +65,14 @@ class StoreRecurringQuoteRequest extends Request $input['line_items'] = isset($input['line_items']) ? $this->cleanItems($input['line_items']) : []; + if ($this->file('documents') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('documents', [$this->file('documents')]); + } + + if ($this->file('file') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('file', [$this->file('file')]); + } + if (isset($input['auto_bill'])) { $input['auto_bill_enabled'] = $this->setAutoBillFlag($input['auto_bill']); } else { diff --git a/app/Http/Requests/RecurringQuote/UpdateRecurringQuoteRequest.php b/app/Http/Requests/RecurringQuote/UpdateRecurringQuoteRequest.php index 3209a803ed..ab546fcf00 100644 --- a/app/Http/Requests/RecurringQuote/UpdateRecurringQuoteRequest.php +++ b/app/Http/Requests/RecurringQuote/UpdateRecurringQuoteRequest.php @@ -1,4 +1,5 @@ file('documents') && is_array($this->file('documents'))) { - $rules['documents.*'] = $this->fileValidation(); - } elseif ($this->file('documents')) { - $rules['documents'] = $this->fileValidation(); - } - - if ($this->file('file') && is_array($this->file('file'))) { - $rules['file.*'] = $this->fileValidation(); - } elseif ($this->file('file')) { - $rules['file'] = $this->fileValidation(); - } + $rules['file'] = 'bail|sometimes|array'; + $rules['file.*'] = $this->fileValidation(); + $rules['documents'] = 'bail|sometimes|array'; + $rules['documents.*'] = $this->fileValidation(); if ($this->number) { $rules['number'] = Rule::unique('recurring_quotes')->where('company_id', auth()->user()->company()->id)->ignore($this->recurring_quote->id); @@ -61,6 +55,14 @@ class UpdateRecurringQuoteRequest extends Request $input = $this->all(); $input = $this->decodePrimaryKeys($input); + if ($this->file('documents') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('documents', [$this->file('documents')]); + } + + if ($this->file('file') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('file', [$this->file('file')]); + } + if (isset($input['line_items'])) { $input['line_items'] = isset($input['line_items']) ? $this->cleanItems($input['line_items']) : []; } diff --git a/app/Http/Requests/RecurringQuote/UploadRecurringQuoteRequest.php b/app/Http/Requests/RecurringQuote/UploadRecurringQuoteRequest.php index 3c8b91f96e..33eaf6db00 100644 --- a/app/Http/Requests/RecurringQuote/UploadRecurringQuoteRequest.php +++ b/app/Http/Requests/RecurringQuote/UploadRecurringQuoteRequest.php @@ -1,4 +1,5 @@ file('documents') && is_array($this->file('documents'))) { - $rules['documents.*'] = $this->fileValidation(); - } elseif ($this->file('documents')) { - $rules['documents'] = $this->fileValidation(); - } - - if ($this->file('file') && is_array($this->file('file'))) { - $rules['file.*'] = $this->fileValidation(); - } elseif ($this->file('file')) { - $rules['file'] = $this->fileValidation(); - } + $rules['file'] = 'bail|sometimes|array'; + $rules['file.*'] = $this->fileValidation(); + $rules['documents'] = 'bail|sometimes|array'; + $rules['documents.*'] = $this->fileValidation(); return $rules; } + + public function prepareForValidation() + { + + if ($this->file('documents') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('documents', [$this->file('documents')]); + } + + if ($this->file('file') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('file', [$this->file('file')]); + } + } + } diff --git a/app/Http/Requests/Report/GenericReportRequest.php b/app/Http/Requests/Report/GenericReportRequest.php index 400be15743..4cedc6bcfe 100644 --- a/app/Http/Requests/Report/GenericReportRequest.php +++ b/app/Http/Requests/Report/GenericReportRequest.php @@ -1,4 +1,5 @@ decodePrimaryKey($input['location_id']); } - + if (array_key_exists('client_id', $input) && is_string($input['client_id'])) { $input['client_id'] = $this->decodePrimaryKey($input['client_id']); } diff --git a/app/Http/Requests/Search/GenericSearchRequest.php b/app/Http/Requests/Search/GenericSearchRequest.php index 9e0bc8b2ce..deb7e6cde3 100644 --- a/app/Http/Requests/Search/GenericSearchRequest.php +++ b/app/Http/Requests/Search/GenericSearchRequest.php @@ -1,4 +1,5 @@ file('documents') && is_array($this->file('documents'))) { - $rules['documents.*'] = $this->fileValidation(); - } elseif ($this->file('documents')) { - $rules['documents'] = $this->fileValidation(); - } else { - $rules['documents'] = 'bail|sometimes|array'; - } - - if ($this->file('file') && is_array($this->file('file'))) { - $rules['file.*'] = $this->fileValidation(); - } elseif ($this->file('file')) { - $rules['file'] = $this->fileValidation(); - } + $rules['file'] = 'bail|sometimes|array'; + $rules['file.*'] = $this->fileValidation(); + $rules['documents'] = 'bail|sometimes|array'; + $rules['documents.*'] = $this->fileValidation(); return $this->globalRules($rules); } @@ -104,6 +96,14 @@ class StoreTaskRequest extends Request $input['status_id'] = $this->decodePrimaryKey($input['status_id']); } + if ($this->file('documents') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('documents', [$this->file('documents')]); + } + + if ($this->file('file') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('file', [$this->file('file')]); + } + /* Ensure the project is related */ if (array_key_exists('project_id', $input) && isset($input['project_id'])) { $project = Project::withTrashed()->where('id', $input['project_id'])->company()->first(); diff --git a/app/Http/Requests/Task/UpdateTaskRequest.php b/app/Http/Requests/Task/UpdateTaskRequest.php index 597704200a..0a82ab8464 100644 --- a/app/Http/Requests/Task/UpdateTaskRequest.php +++ b/app/Http/Requests/Task/UpdateTaskRequest.php @@ -1,4 +1,5 @@ file('documents') && is_array($this->file('documents'))) { - $rules['documents.*'] = $this->fileValidation(); - } elseif ($this->file('documents')) { - $rules['documents'] = $this->fileValidation(); - } else { - $rules['documents'] = 'bail|sometimes|array'; - } - - if ($this->file('file') && is_array($this->file('file'))) { - $rules['file.*'] = $this->fileValidation(); - } elseif ($this->file('file')) { - $rules['file'] = $this->fileValidation(); - } + $rules['file'] = 'bail|sometimes|array'; + $rules['file.*'] = $this->fileValidation(); + $rules['documents'] = 'bail|sometimes|array'; + $rules['documents.*'] = $this->fileValidation(); return $this->globalRules($rules); } @@ -105,6 +97,14 @@ class UpdateTaskRequest extends Request { $input = $this->decodePrimaryKeys($this->all()); + if ($this->file('documents') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('documents', [$this->file('documents')]); + } + + if ($this->file('file') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('file', [$this->file('file')]); + } + if (array_key_exists('status_id', $input) && is_string($input['status_id'])) { $input['status_id'] = $this->decodePrimaryKey($input['status_id']); } diff --git a/app/Http/Requests/Task/UploadTaskRequest.php b/app/Http/Requests/Task/UploadTaskRequest.php index 1ffdf2fbeb..dedaddb5d2 100644 --- a/app/Http/Requests/Task/UploadTaskRequest.php +++ b/app/Http/Requests/Task/UploadTaskRequest.php @@ -1,4 +1,5 @@ file('documents') && is_array($this->file('documents'))) { - $rules['documents.*'] = $this->fileValidation(); - } elseif ($this->file('documents')) { - $rules['documents'] = $this->fileValidation(); - } - - if ($this->file('file') && is_array($this->file('file'))) { - $rules['file.*'] = $this->fileValidation(); - } elseif ($this->file('file')) { - $rules['file'] = $this->fileValidation(); - } - + $rules['file'] = 'bail|sometimes|array'; + $rules['file.*'] = $this->fileValidation(); + $rules['documents'] = 'bail|sometimes|array'; + $rules['documents.*'] = $this->fileValidation(); $rules['is_public'] = 'sometimes|boolean'; return $rules; @@ -53,6 +46,14 @@ class UploadTaskRequest extends Request { $input = $this->all(); + if ($this->file('documents') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('documents', [$this->file('documents')]); + } + + if ($this->file('file') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('file', [$this->file('file')]); + } + if (isset($input['is_public'])) { $input['is_public'] = $this->toBoolean($input['is_public']); } diff --git a/app/Http/Requests/TaskScheduler/CreateSchedulerRequest.php b/app/Http/Requests/TaskScheduler/CreateSchedulerRequest.php index 66a3eb9d9a..e22749ebb2 100644 --- a/app/Http/Requests/TaskScheduler/CreateSchedulerRequest.php +++ b/app/Http/Requests/TaskScheduler/CreateSchedulerRequest.php @@ -1,4 +1,5 @@ file('documents') && is_array($this->file('documents'))) { - $rules['documents.*'] = $this->fileValidation(); - } elseif ($this->file('documents')) { - $rules['documents'] = $this->fileValidation(); - } else { - $rules['documents'] = 'bail|sometimes|array'; - } - - if ($this->file('file') && is_array($this->file('file'))) { - $rules['file.*'] = $this->fileValidation(); - } elseif ($this->file('file')) { - $rules['file'] = $this->fileValidation(); - } - + $rules['file'] = 'bail|sometimes|array'; + $rules['file.*'] = $this->fileValidation(); + $rules['documents'] = 'bail|sometimes|array'; + $rules['documents.*'] = $this->fileValidation(); $rules['language_id'] = 'bail|nullable|sometimes|exists:languages,id'; $rules['classification'] = 'bail|sometimes|nullable|in:individual,business,company,partnership,trust,charity,government,other'; @@ -87,6 +77,14 @@ class StoreVendorRequest extends Request $input = $this->all(); + if ($this->file('documents') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('documents', [$this->file('documents')]); + } + + if ($this->file('file') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('file', [$this->file('file')]); + } + if (!array_key_exists('currency_id', $input) || empty($input['currency_id'])) { $input['currency_id'] = $user->company()->settings->currency_id; } diff --git a/app/Http/Requests/Vendor/UpdateVendorRequest.php b/app/Http/Requests/Vendor/UpdateVendorRequest.php index 10ba8ed889..50b24383d1 100644 --- a/app/Http/Requests/Vendor/UpdateVendorRequest.php +++ b/app/Http/Requests/Vendor/UpdateVendorRequest.php @@ -1,4 +1,5 @@ file('documents') && is_array($this->file('documents'))) { - $rules['documents.*'] = $this->fileValidation(); - } elseif ($this->file('documents')) { - $rules['documents'] = $this->fileValidation(); - } else { - $rules['documents'] = 'bail|sometimes|array'; - } - - if ($this->file('file') && is_array($this->file('file'))) { - $rules['file.*'] = $this->fileValidation(); - } elseif ($this->file('file')) { - $rules['file'] = $this->fileValidation(); - } - + $rules['file'] = 'bail|sometimes|array'; + $rules['file.*'] = $this->fileValidation(); + $rules['documents'] = 'bail|sometimes|array'; + $rules['documents.*'] = $this->fileValidation(); $rules['language_id'] = 'bail|nullable|sometimes|exists:languages,id'; $rules['classification'] = 'bail|sometimes|nullable|in:individual,business,company,partnership,trust,charity,government,other'; @@ -94,6 +84,14 @@ class UpdateVendorRequest extends Request { $input = $this->all(); + if ($this->file('documents') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('documents', [$this->file('documents')]); + } + + if ($this->file('file') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('file', [$this->file('file')]); + } + if (isset($input['name'])) { $input['name'] = strip_tags($input['name']); } diff --git a/app/Http/Requests/Vendor/UploadVendorRequest.php b/app/Http/Requests/Vendor/UploadVendorRequest.php index f53cc45553..00f3c09aca 100644 --- a/app/Http/Requests/Vendor/UploadVendorRequest.php +++ b/app/Http/Requests/Vendor/UploadVendorRequest.php @@ -1,4 +1,5 @@ file('documents') && is_array($this->file('documents'))) { - $rules['documents.*'] = $this->fileValidation(); - } elseif ($this->file('documents')) { - $rules['documents'] = $this->fileValidation(); - } - - if ($this->file('file') && is_array($this->file('file'))) { - $rules['file.*'] = $this->fileValidation(); - } elseif ($this->file('file')) { - $rules['file'] = $this->fileValidation(); - } - + $rules['file'] = 'bail|sometimes|array'; + $rules['file.*'] = $this->fileValidation(); + $rules['documents'] = 'bail|sometimes|array'; + $rules['documents.*'] = $this->fileValidation(); $rules['is_public'] = 'sometimes|boolean'; return $rules; @@ -54,6 +46,14 @@ class UploadVendorRequest extends Request $input['is_public'] = $this->toBoolean($input['is_public']); } + if ($this->file('documents') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('documents', [$this->file('documents')]); + } + + if ($this->file('file') instanceof \Illuminate\Http\UploadedFile) { + $this->files->set('file', [$this->file('file')]); + } + $this->replace($input); } } diff --git a/app/Http/Requests/VendorPortal/PurchaseOrders/ShowPurchaseOrderRequest.php b/app/Http/Requests/VendorPortal/PurchaseOrders/ShowPurchaseOrderRequest.php index 754b1cc63b..53aefa2c63 100644 --- a/app/Http/Requests/VendorPortal/PurchaseOrders/ShowPurchaseOrderRequest.php +++ b/app/Http/Requests/VendorPortal/PurchaseOrders/ShowPurchaseOrderRequest.php @@ -1,4 +1,5 @@ find($value); - if(!$invoice){ + if (!$invoice) { $this->error_message = 'Invoice not found.'; return false; - } - - elseif ($invoice->balance >= $invoice->amount) { + } elseif ($invoice->balance >= $invoice->amount) { $this->error_message = 'Cannot reverse an invoice with no payment applied.'; return false; diff --git a/app/Http/ValidationRules/Design/TwigLint.php b/app/Http/ValidationRules/Design/TwigLint.php index 9bf18331f7..c928ba900a 100644 --- a/app/Http/ValidationRules/Design/TwigLint.php +++ b/app/Http/ValidationRules/Design/TwigLint.php @@ -1,4 +1,5 @@ validateRequest($value['Invoice'], InvoiceLevel::class); - + foreach ($errors as $key => $msg) { $this->validator->errors()->add( @@ -50,22 +50,20 @@ class ValidInvoiceScheme implements ValidationRule, ValidatorAwareRule } - if(isset($value['Invoice']['InvoicePeriod'][0]['Description'])){ + if (isset($value['Invoice']['InvoicePeriod'][0]['Description'])) { $parts = explode('|', $value['Invoice']['InvoicePeriod'][0]['Description']); $parts_count = count($parts); - if($parts_count == 2) - { - if(!$this->isValidDateSyntax($parts[0])){ - + if ($parts_count == 2) { + if (!$this->isValidDateSyntax($parts[0])) { + $this->validator->errors()->add( "e_invoice.InvoicePeriod.Description.0.StartDate", ctrans('texts.invalid_date_create_syntax') ); - } - elseif (!$this->isValidDateSyntax($parts[1])){ - + } elseif (!$this->isValidDateSyntax($parts[1])) { + $this->validator->errors()->add( "e_invoice.InvoicePeriod.Description.0.EndDate", ctrans('texts.invalid_date_create_syntax') @@ -73,9 +71,7 @@ class ValidInvoiceScheme implements ValidationRule, ValidatorAwareRule } - } - elseif($parts_count == 1 && strlen($value['Invoice']['InvoicePeriod'][0]['Description']) > 2) - { + } elseif ($parts_count == 1 && strlen($value['Invoice']['InvoicePeriod'][0]['Description']) > 2) { $this->validator->errors()->add( "e_invoice.InvoicePeriod.Description.0.StartDate", ctrans('texts.start_and_end_date_required') @@ -95,7 +91,7 @@ class ValidInvoiceScheme implements ValidationRule, ValidatorAwareRule return false; } } - + /** * Set the current validator. */ diff --git a/app/Http/ValidationRules/Expense/UniqueExpenseNumberRule.php b/app/Http/ValidationRules/Expense/UniqueExpenseNumberRule.php index 2ee86b2c39..adafd075de 100644 --- a/app/Http/ValidationRules/Expense/UniqueExpenseNumberRule.php +++ b/app/Http/ValidationRules/Expense/UniqueExpenseNumberRule.php @@ -1,4 +1,5 @@ config('ninja.cloudflare.turnstile.secret'), 'response' => $value, 'remoteip' => request()->ip(), - ]); + ]); $data = $response->json(); - if($data['success']){ + if ($data['success']) { - } - else { + } else { $fail("Captcha failed"); } diff --git a/app/Http/ValidationRules/UniqueUserRule.php b/app/Http/ValidationRules/UniqueUserRule.php index 300cf80a51..c902e8ac0b 100644 --- a/app/Http/ValidationRules/UniqueUserRule.php +++ b/app/Http/ValidationRules/UniqueUserRule.php @@ -1,4 +1,5 @@ open($temp_file) === true) { - - $qb_json = $zip->getFromName('backup.json'); + + $qb_json = $zip->getFromName('backup.json'); $this->qb_data = json_decode($qb_json, true); $zip->close(); } - unlink($temp_file); + unlink($temp_file); $this->qb = new QuickbooksService($this->company); - + } public function import(string $entity) @@ -53,28 +52,28 @@ class QBBackup extends BaseImport implements ImportInterface public function client() { - if(isset($this->qb_data['clients'])) { + if (isset($this->qb_data['clients'])) { $this->qb->client->importToNinja($this->qb_data['clients']); } } public function product() { - if(isset($this->qb_data['products'])) { + if (isset($this->qb_data['products'])) { $this->qb->product->syncToNinja($this->qb_data['products']); } } public function invoice() { - if(isset($this->qb_data['invoices'])) { + if (isset($this->qb_data['invoices'])) { $this->qb->invoice->importToNinja($this->qb_data['invoices']); } } public function quote() { - if(isset($this->qb_data['quotes'])) { + if (isset($this->qb_data['quotes'])) { $this->qb->quote->importToNinja($this->qb_data['quotes']); } } @@ -84,38 +83,38 @@ class QBBackup extends BaseImport implements ImportInterface $payments = isset($this->qb_data['payments']) && is_array($this->qb_data['payments']) ? $this->qb_data['payments'] : []; - foreach ($payments as $payment) { + foreach ($payments as $payment) { - $payment_transformer = new PaymentTransformer($this->company); + $payment_transformer = new PaymentTransformer($this->company); - $transformed = $payment_transformer->qbToNinja($payment); + $transformed = $payment_transformer->qbToNinja($payment); - $ninja_payment = $payment_transformer->buildPayment($payment); - $ninja_payment->service()->applyNumber()->save(); + $ninja_payment = $payment_transformer->buildPayment($payment); + $ninja_payment->service()->applyNumber()->save(); - - $invoice = Invoice::query() - ->withTrashed() - ->where('company_id', $this->company->id) - ->where('sync->qb_id', $payment['invoice_id']) - ->first(); - if ($invoice) { + $invoice = Invoice::query() + ->withTrashed() + ->where('company_id', $this->company->id) + ->where('sync->qb_id', $payment['invoice_id']) + ->first(); - $paymentable = new \App\Models\Paymentable(); - $paymentable->payment_id = $ninja_payment->id; - $paymentable->paymentable_id = $invoice->id; - $paymentable->paymentable_type = 'invoices'; - $paymentable->amount = $transformed['applied'] + $ninja_payment->credits->sum('amount'); - $paymentable->created_at = $ninja_payment->date; //@phpstan-ignore-line - $paymentable->save(); + if ($invoice) { - $invoice->service()->applyPayment($ninja_payment, $paymentable->amount); + $paymentable = new \App\Models\Paymentable(); + $paymentable->payment_id = $ninja_payment->id; + $paymentable->paymentable_id = $invoice->id; + $paymentable->paymentable_type = 'invoices'; + $paymentable->amount = $transformed['applied'] + $ninja_payment->credits->sum('amount'); + $paymentable->created_at = $ninja_payment->date; //@phpstan-ignore-line + $paymentable->save(); - } + $invoice->service()->applyPayment($ninja_payment, $paymentable->amount); } + } + } public function vendor() @@ -127,4 +126,4 @@ class QBBackup extends BaseImport implements ImportInterface { } -} \ No newline at end of file +} diff --git a/app/Import/Providers/Zoho.php b/app/Import/Providers/Zoho.php index 53ea35e633..23d80be99f 100644 --- a/app/Import/Providers/Zoho.php +++ b/app/Import/Providers/Zoho.php @@ -1,4 +1,5 @@ getCsvData($entity_type); - + if (empty($data)) { $this->entity_count['invoices'] = 0; diff --git a/app/Import/Transformer/Bank/BankTransformer.php b/app/Import/Transformer/Bank/BankTransformer.php index 17af8370bd..d2cb899239 100644 --- a/app/Import/Transformer/Bank/BankTransformer.php +++ b/app/Import/Transformer/Bank/BankTransformer.php @@ -1,4 +1,5 @@ company = $company; @@ -394,7 +395,7 @@ class BaseTransformer // Convert to float and apply negative sign if necessary $result = (float) $amount; - + return $isNegative ? -$result : $result; diff --git a/app/Import/Transformer/Csv/ClientTransformer.php b/app/Import/Transformer/Csv/ClientTransformer.php index f8d4cd175f..df90d106e6 100644 --- a/app/Import/Transformer/Csv/ClientTransformer.php +++ b/app/Import/Transformer/Csv/ClientTransformer.php @@ -1,4 +1,5 @@ currency_id = (string) $this->getCurrencyByCode($data); diff --git a/app/Import/Transformer/Csv/ExpenseTransformer.php b/app/Import/Transformer/Csv/ExpenseTransformer.php index f84a910238..d8ff5f4fa6 100644 --- a/app/Import/Transformer/Csv/ExpenseTransformer.php +++ b/app/Import/Transformer/Csv/ExpenseTransformer.php @@ -1,4 +1,5 @@ transaction_id = $this->bt->id; $expense->payment_date = $this->bt->date; - if(empty($expense->transaction_reference)) { + if (empty($expense->transaction_reference)) { $expense->transaction_reference = $this->bt->description; } - + $expense->save(); $this->bt->expense_id = $this->coalesceExpenses($expense->hashed_id); @@ -330,7 +331,7 @@ class MatchBankTransactions implements ShouldQueue ->setCalculatedStatus() ->save(); - + event('eloquent.updated: App\Models\Invoice', $this->invoice); } }); diff --git a/app/Jobs/Bank/ProcessBankTransactionsNordigen.php b/app/Jobs/Bank/ProcessBankTransactionsNordigen.php index 0a53406f1c..f1c547d49a 100644 --- a/app/Jobs/Bank/ProcessBankTransactionsNordigen.php +++ b/app/Jobs/Bank/ProcessBankTransactionsNordigen.php @@ -1,4 +1,5 @@ nordigen_account) { return; } diff --git a/app/Jobs/Bank/ProcessBankTransactionsYodlee.php b/app/Jobs/Bank/ProcessBankTransactionsYodlee.php index efc1382b6b..c70e5cc472 100644 --- a/app/Jobs/Bank/ProcessBankTransactionsYodlee.php +++ b/app/Jobs/Bank/ProcessBankTransactionsYodlee.php @@ -1,4 +1,5 @@ location->client; try { - + if (!$this->location->state && $this->location->postal_code) { $this->location->update(['state' => USStates::getState($this->location->postal_code)]); diff --git a/app/Jobs/Client/UpdateTaxData.php b/app/Jobs/Client/UpdateTaxData.php index 49c9b9c1b7..8cdc748bb7 100644 --- a/app/Jobs/Client/UpdateTaxData.php +++ b/app/Jobs/Client/UpdateTaxData.php @@ -1,4 +1,5 @@ client->state && $this->client->postal_code) { - + $this->client->update(['state' => USStates::getState($this->client->postal_code)]); $this->client->refresh(); - + } $tax_provider->setBillingAddress($this->getBillingAddress()) @@ -94,11 +95,11 @@ class UpdateTaxData implements ShouldQueue private function getShippingAddress(): array { - if(strlen($this->client->shipping_address1 ?? '') < 3) { + if (strlen($this->client->shipping_address1 ?? '') < 3) { return $this->getBillingAddress(); } - return + return [ 'address2' => $this->client->shipping_address2, 'address1' => $this->client->shipping_address1, @@ -107,7 +108,7 @@ class UpdateTaxData implements ShouldQueue 'postal_code' => $this->client->shipping_postal_code, 'country' => $this->client->shipping_country()->exists() ? $this->client->shipping_country->name : $this->client->country->name, ]; - + } public function middleware() diff --git a/app/Jobs/Company/CompanyExport.php b/app/Jobs/Company/CompanyExport.php index d905d52b46..530d7bf80b 100644 --- a/app/Jobs/Company/CompanyExport.php +++ b/app/Jobs/Company/CompanyExport.php @@ -1,4 +1,5 @@ export_data['e_invoicing_tokens'] = EInvoicingToken::all()->makeHidden(['id'])->all(); - } - else { + } else { $this->export_data['e_invoicing_tokens'] = []; } @@ -645,7 +645,7 @@ class CompanyExport implements ShouldQueue //////////////////////////////////// fine //////////////////////////////////// $this->writer->end(); - + $this->zipAndSend(); return true; @@ -687,7 +687,7 @@ class CompanyExport implements ShouldQueue foreach ($documents as $document) { try { $content = $document->getFile(); - + if ($content === false) { continue; } @@ -697,7 +697,7 @@ class CompanyExport implements ShouldQueue continue; } } - + // Free up memory after each batch gc_collect_cycles(); }); @@ -713,7 +713,7 @@ class CompanyExport implements ShouldQueue foreach ($backups as $backup) { try { $content = $backup->getFile(); - + if ($content === false) { continue; } @@ -723,7 +723,7 @@ class CompanyExport implements ShouldQueue continue; } } - + // Free up memory after each batch gc_collect_cycles(); }); @@ -736,7 +736,7 @@ class CompanyExport implements ShouldQueue $logo = $this->company->present()->logoFile($this->company->settings); $zip->addFromString("company_logo.png", $logo); - + return $zip; } diff --git a/app/Jobs/Company/CompanyImport.php b/app/Jobs/Company/CompanyImport.php index b65e44f2c6..44c60ace77 100644 --- a/app/Jobs/Company/CompanyImport.php +++ b/app/Jobs/Company/CompanyImport.php @@ -1,4 +1,5 @@ transformId('tasks', $value->task_id); - } - catch(\Exception $e){ + } catch (\Exception $e) { } if ($t_id && $t = Task::withTrashed()->where('company_id', $this->company->id)->where('id', $t_id)->first()) { $items[$key]->task_id = $t->hashed_id; - } - else { + } else { $items[$key]->task_id = null; } @@ -416,16 +415,14 @@ class CompanyImport implements ShouldQueue if (isset($value->expense_id) && strlen($value->expense_id) > 1) { $e_id = false; - try{ + try { $e_id = $this->transformId('expenses', $value->expense_id); - } - catch(\Exception $e){ + } catch (\Exception $e) { } if ($e = Expense::withTrashed()->where('company_id', $this->company->id)->where('id', $e_id)->first()) { $items[$key]->expense_id = $e->hashed_id; - } - else { + } else { $items[$key]->expense_id = null; } @@ -677,17 +674,17 @@ class CompanyImport implements ShouldQueue return $this; } - if(file_exists($logo_path)) { - + if (file_exists($logo_path)) { + $path = (new \App\Jobs\Util\UploadAvatar($logo_path, $this->company->company_key))->handle(); - + if ($path) { $settings = $this->company->settings; $settings->company_logo = $path; $this->company->settings = $settings; $this->company->save(); } - + } return $this; @@ -1360,14 +1357,14 @@ class CompanyImport implements ShouldQueue } } elseif (file_exists("{$this->root_file_path}documents/{$document->url}")) { - - $success = Storage::disk(config('filesystems.default'))->put($new_document_url, file_get_contents("{$this->root_file_path}documents/{$document->url}")); - - if(!$success) - continue; - } - else { + $success = Storage::disk(config('filesystems.default'))->put($new_document_url, file_get_contents("{$this->root_file_path}documents/{$document->url}")); + + if (!$success) { + continue; + } + + } else { continue; } @@ -1736,18 +1733,16 @@ class CompanyImport implements ShouldQueue $new_obj->save(['timestamps' => false]); if ($new_obj instanceof CompanyLedger || $new_obj instanceof EInvoicingToken) { - } - elseif ($new_obj instanceof Backup) { - - if(is_file("{$this->root_file_path}backups/{$obj->filename}")) { + } elseif ($new_obj instanceof Backup) { + + if (is_file("{$this->root_file_path}backups/{$obj->filename}")) { $file = file_get_contents("{$this->root_file_path}backups/{$obj->filename}"); $new_obj->filename = str_replace($this->old_company_key, $this->company->company_key, $obj->filename); $new_obj->save(); $new_obj = $new_obj->fresh(); $new_obj->storeBackupFile($file); } - } - else { + } else { $this->ids["{$object_property}"]["{$obj->hashed_id}"] = $new_obj->id; } } @@ -1954,10 +1949,10 @@ class CompanyImport implements ShouldQueue if (! array_key_exists($resource, $this->ids)) { - if($this->import_notifications_enabled){ + if ($this->import_notifications_enabled) { $this->sendImportMail("The Import failed due to missing data in the import file. Resource {$resource} not available."); } - + throw new \Exception("Resource {$resource} not available."); } @@ -1968,7 +1963,7 @@ class CompanyImport implements ShouldQueue return $this->company_owner->id; } - if($this->import_notifications_enabled){ + if ($this->import_notifications_enabled) { $this->sendImportMail("The Import failed due to missing data in the import file. Key {$old} not found in {$resource}."); } diff --git a/app/Jobs/Company/CompanyTaxRate.php b/app/Jobs/Company/CompanyTaxRate.php index 1d3261c137..736bdb6889 100644 --- a/app/Jobs/Company/CompanyTaxRate.php +++ b/app/Jobs/Company/CompanyTaxRate.php @@ -1,4 +1,5 @@ invoice_id}"); - + $invoice = Invoice::withTrashed()->find($this->invoice_id); - - if($invoice) + + if ($invoice) { $invoice->service()->autoBill(); + } } catch (\Exception $e) { nlog("Failed to capture payment for {$this->invoice_id} ->".$e->getMessage()); @@ -69,7 +71,7 @@ class AutoBill implements ShouldQueue if ($this->send_email_on_failure && $invoice) { $invoice->invitations->each(function ($invitation) use ($invoice) { - + //2025-04-06 additional conditional check to prevent duplicate emails from being sent. if ($invitation->contact && !$invitation->contact->trashed() && strlen($invitation->contact->email) >= 1 && $invoice->client->getSetting('auto_email_invoice') && !$invitation->contact->is_locked && $invoice->client->getSetting('client_online_payment_notification')) { try { diff --git a/app/Jobs/Cron/AutoBillCron.php b/app/Jobs/Cron/AutoBillCron.php index e9527faf5e..915dda501b 100644 --- a/app/Jobs/Cron/AutoBillCron.php +++ b/app/Jobs/Cron/AutoBillCron.php @@ -1,4 +1,5 @@ whereHas('company', function ($query) { $query->where('is_disabled', 0) - ->whereHas('account', function ($q){ - $q->where('is_flagged', false); + ->whereHas('account', function ($q) { + $q->where('is_flagged', false); }); }) ->with('company') @@ -97,14 +98,14 @@ class RecurringInvoicesCron ->whereNotNull('next_send_date') ->where('next_send_date', '<=', now()->toDateTimeString()) ->whereHas('client', function ($query) { - $query->where('is_deleted', false) - ->whereNull('deleted_at'); + $query->where('is_deleted', false) + ->whereNull('deleted_at'); }) ->whereHas('company', function ($query) { $query->where('is_disabled', 0) - ->whereHas('account', function ($q){ - $q->where('is_flagged', false); + ->whereHas('account', function ($q) { + $q->where('is_flagged', false); }); }) ->with('company') diff --git a/app/Jobs/Cron/SubscriptionCron.php b/app/Jobs/Cron/SubscriptionCron.php index bd87f2fe76..7067b914f8 100644 --- a/app/Jobs/Cron/SubscriptionCron.php +++ b/app/Jobs/Cron/SubscriptionCron.php @@ -1,4 +1,5 @@ document))->run(); - + //New implementation now the default 2025-02-04 - requires zugferd_version_two=false to disable + $zugferd = (new ZugferdEDocument($this->document))->run(); + return $this->returnObject ? $zugferd->xdocument : $zugferd->getXml(); case "Facturae_3.2": case "Facturae_3.2.1": diff --git a/app/Jobs/EDocument/EInvoicePullDocs.php b/app/Jobs/EDocument/EInvoicePullDocs.php index 5b65d46043..26c2808dbe 100644 --- a/app/Jobs/EDocument/EInvoicePullDocs.php +++ b/app/Jobs/EDocument/EInvoicePullDocs.php @@ -1,4 +1,5 @@ format('Y-m-d h:i:s')); - + if (Ninja::isHosted()) { return; } @@ -54,14 +55,14 @@ class EInvoicePullDocs implements ShouldQueue $q->whereNotNull('legal_entity_id'); }) ->cursor() - ->each(function ($account){ + ->each(function ($account) { $account->companies->filter(function ($company) { return $company->settings->e_invoice_type == 'PEPPOL' && ($company->tax_data->acts_as_receiver ?? false); }) - ->each(function ($company){ + ->each(function ($company) { $response = \Illuminate\Support\Facades\Http::baseUrl(config('ninja.hosted_ninja_url')) ->withHeaders([ @@ -76,18 +77,17 @@ class EInvoicePullDocs implements ShouldQueue 'legal_entity_id' => $company->legal_entity_id, ]); - if($response->successful()){ + if ($response->successful()) { $hash = $response->header('X-CONFIRMATION-HASH'); $this->handleSuccess($response->json(), $company, $hash); - } - else { + } else { nlog($response->body()); } }); - + }); } @@ -96,25 +96,22 @@ class EInvoicePullDocs implements ShouldQueue $storecove = new Storecove(); - foreach($received_documents as $document) - { + foreach ($received_documents as $document) { nlog($document); $storecove_invoice = $storecove->expense->getStorecoveInvoice(json_encode($document['document']['invoice'])); $expense = $storecove->expense->createExpense($storecove_invoice, $company); $file_name = $document['guid']; - if(strlen($document['html'] ?? '') > 5) - { + if (strlen($document['html'] ?? '') > 5) { $upload_document = TempFile::UploadedFileFromRaw($document['html'], "{$file_name}.html", 'text/html'); $this->saveDocument($upload_document, $expense); $upload_document = null; } - if(strlen($document['original_base64_xml'] ?? '') > 5) - { - + if (strlen($document['original_base64_xml'] ?? '') > 5) { + $upload_document = TempFile::UploadedFileFromBase64($document['original_base64_xml'], "{$file_name}.xml", 'application/xml'); $this->saveDocument($upload_document, $expense); $upload_document = null; @@ -145,7 +142,7 @@ class EInvoicePullDocs implements ShouldQueue 'hash' => $hash ]); - if($response->successful()){ + if ($response->successful()) { } } @@ -154,4 +151,4 @@ class EInvoicePullDocs implements ShouldQueue { nlog($exception->getMessage()); } -} \ No newline at end of file +} diff --git a/app/Jobs/EDocument/ImportEDocument.php b/app/Jobs/EDocument/ImportEDocument.php index 5a85b44bb7..a53f9ed9c9 100644 --- a/app/Jobs/EDocument/ImportEDocument.php +++ b/app/Jobs/EDocument/ImportEDocument.php @@ -1,4 +1,5 @@ document, true))->handle(); - + return(new ZugferdDocumentPdfBuilder($xml, $this->pdf_file))->generateDocument()->downloadString(); default: return $this->pdf_file; diff --git a/app/Jobs/Entity/CreateBatchablePdf.php b/app/Jobs/Entity/CreateBatchablePdf.php index 6b3337951b..2b6bea22ba 100644 --- a/app/Jobs/Entity/CreateBatchablePdf.php +++ b/app/Jobs/Entity/CreateBatchablePdf.php @@ -22,7 +22,10 @@ use Illuminate\Foundation\Bus\Dispatchable; class CreateBatchablePdf implements ShouldQueue { - use Batchable, Dispatchable, InteractsWithQueue, SerializesModels; + use Batchable; + use Dispatchable; + use InteractsWithQueue; + use SerializesModels; private $batch_key; @@ -39,7 +42,7 @@ class CreateBatchablePdf implements ShouldQueue public function handle() { - \App\Libraries\MultiDB::setDb($this->invitation->company->db); + \App\Libraries\MultiDB::setDb($this->invitation->company->db); $pdf = (new CreateRawPdf($this->invitation))->handle(); diff --git a/app/Jobs/Entity/CreateRawPdf.php b/app/Jobs/Entity/CreateRawPdf.php index d5c9fc4c1f..36ced85f4c 100644 --- a/app/Jobs/Entity/CreateRawPdf.php +++ b/app/Jobs/Entity/CreateRawPdf.php @@ -1,4 +1,5 @@ generatePdf(); - if($this->isBlankPdf($pdf)) { - + if ($this->isBlankPdf($pdf)) { + nlog("Blank PDF detected, generating again"); $pdf = $this->generatePdf(); } - + if ($this->isBlankPdf($pdf)) { nlog("Blank PDF detected, generating again!!! :: {$this->entity_string} {$this->entity->id}"); @@ -121,13 +122,14 @@ class CreateRawPdf private function isBlankPdf($pdf): bool { - $size = mb_strlen($pdf, '8bit'); + $size = mb_strlen($pdf, '8bit'); - $blankPdfSize = 12 * 1024; - $tolerance = 100; + $blankPdfSize = 12 * 1024; + $tolerance = 100; - if($size <= $blankPdfSize) + if ($size <= $blankPdfSize) { nlog("PDF EXCEPTION:: size: {$size}, blank PDF size: {$blankPdfSize}, tolerance: {$tolerance}"); + } return abs($size) <= $blankPdfSize; diff --git a/app/Jobs/Entity/EmailEntity.php b/app/Jobs/Entity/EmailEntity.php index 4826a61db6..d2f8e31d9a 100644 --- a/app/Jobs/Entity/EmailEntity.php +++ b/app/Jobs/Entity/EmailEntity.php @@ -1,4 +1,5 @@ db); $batch_key = Str::uuid(); - + $invites = $this->class::with('invitations')->withTrashed() ->whereIn('id', $this->entity_ids) ->get() - ->map(function ($entity) use ($batch_key){ + ->map(function ($entity) use ($batch_key) { return new CreateBatchablePdf($entity->invitations->first(), "{$batch_key}-{$entity->id}"); })->toArray(); $mergedPdf = null; - + $batch = Bus::batch($invites) ->before(function (Batch $batch) { // The batch has been created but no jobs have been added... diff --git a/app/Jobs/Invoice/UpdateReminders.php b/app/Jobs/Invoice/UpdateReminders.php index 8a38fcbfc4..6fcd30533b 100644 --- a/app/Jobs/Invoice/UpdateReminders.php +++ b/app/Jobs/Invoice/UpdateReminders.php @@ -1,4 +1,5 @@ company->db); App::setLocale($this->company->locale()); - + $settings = $this->company->settings; $this->invoices = Invoice::withTrashed() diff --git a/app/Jobs/Ledger/ClientLedgerBalanceUpdate.php b/app/Jobs/Ledger/ClientLedgerBalanceUpdate.php index c800c0e633..709d8c98f7 100644 --- a/app/Jobs/Ledger/ClientLedgerBalanceUpdate.php +++ b/app/Jobs/Ledger/ClientLedgerBalanceUpdate.php @@ -1,4 +1,5 @@ nmo->settings->reply_to_email; } - $this->nmo->mailable->replyTo($this->nmo->settings->reply_to_email, $reply_to_name); + $this->nmo->mailable->replyTo($this->nmo->settings->reply_to_email, $reply_to_name); } elseif (isset($this->nmo->invitation->user)) { $this->nmo->mailable->replyTo($this->nmo->invitation->user->email, $this->nmo->invitation->user->present()->name()); } else { @@ -249,7 +250,7 @@ class NinjaMailerJob implements ShouldQueue if ($e instanceof PostmarkException) { //postmark specific failure - + try { $response = json_decode($e->getMessage(), true); if (is_array($response) && isset($response['Message'])) { @@ -524,7 +525,7 @@ class NinjaMailerJob implements ShouldQueue private function checkValidSendingUser($user) { /* Always ensure the user is set on the correct account */ - if (!$user ||($user->account_id != $this->company->account_id)) { + if (!$user || ($user->account_id != $this->company->account_id)) { $this->nmo->settings->email_sending_method = 'default'; return $this->setMailDriver(); } diff --git a/app/Jobs/Mail/NinjaMailerObject.php b/app/Jobs/Mail/NinjaMailerObject.php index f2438b1f8d..c6fe11a1df 100644 --- a/app/Jobs/Mail/NinjaMailerObject.php +++ b/app/Jobs/Mail/NinjaMailerObject.php @@ -1,4 +1,5 @@ company = $this->company; $nmo->to_user = $contact; $nmo->settings = $settings; - + if ($invitation) { $nmo->invitation = $invitation->withoutRelations(); } diff --git a/app/Jobs/Mail/PaymentFailureMailer.php b/app/Jobs/Mail/PaymentFailureMailer.php index 5697677e09..2c0e50d9f0 100644 --- a/app/Jobs/Mail/PaymentFailureMailer.php +++ b/app/Jobs/Mail/PaymentFailureMailer.php @@ -1,4 +1,5 @@ whereBetween('created_at' , [now()->subHours(12), now()->subHour()]) - ->orderBy('id','desc') + $query->whereBetween('created_at', [now()->subHours(12), now()->subHour()]) + ->orderBy('id', 'desc') ->each(function ($invite) { $token = config('services.postmark.token'); $postmark = new \Postmark\PostmarkClient($token); - + $messageDetail = false; try { diff --git a/app/Jobs/Ninja/QueueSize.php b/app/Jobs/Ninja/QueueSize.php index 905f045ace..d295d3338e 100644 --- a/app/Jobs/Ninja/QueueSize.php +++ b/app/Jobs/Ninja/QueueSize.php @@ -1,4 +1,5 @@ contact->load('client'); - + if ($this->payment->client->getSetting('payment_email_all_contacts') && $this->payment->invoices && $this->payment->invoices->count() >= 1) { $this->emailAllContacts(); return; @@ -112,11 +113,11 @@ class EmailPayment implements ShouldQueue private function emailAllContacts(): void { - + $invoice = $this->payment->invoices->first(); - $invoice->invitations->filter(function ($invite){ - return $invite->contact->send_email && filter_var($invite->contact->email, FILTER_VALIDATE_EMAIL) !== false; + $invoice->invitations->filter(function ($invite) { + return $invite->contact->send_email && filter_var($invite->contact->email, FILTER_VALIDATE_EMAIL) !== false; })->each(function ($invite) { diff --git a/app/Jobs/Payment/EmailRefundPayment.php b/app/Jobs/Payment/EmailRefundPayment.php index b251a191c6..d2c609aa05 100644 --- a/app/Jobs/Payment/EmailRefundPayment.php +++ b/app/Jobs/Payment/EmailRefundPayment.php @@ -1,4 +1,5 @@ getMessage()); } diff --git a/app/Jobs/Product/UpdateOrCreateProduct.php b/app/Jobs/Product/UpdateOrCreateProduct.php index 10077af51b..464130d1e4 100644 --- a/app/Jobs/Product/UpdateOrCreateProduct.php +++ b/app/Jobs/Product/UpdateOrCreateProduct.php @@ -1,4 +1,5 @@ recurring_invoice, $this->recurring_invoice->client); - + // $date = now()->addSeconds($this->recurring_invoice->client->timezone_offset())->format('Y-m-d'); Rev 1 // $date = date('Y-m-d'); //@todo this will always pull UTC date. Rev 2. - // 2025-01-23 - We need to know the current date in the users timezone, as we send recurring invoices around the + // 2025-01-23 - We need to know the current date in the users timezone, as we send recurring invoices around the // clock the actual date is not always the same as the UTC date. // be _very_ careful with this, as it will change the due date of the invoice. $date = now()->setTimezone($this->recurring_invoice->client->timezone()->name)->format('Y-m-d'); @@ -154,7 +155,7 @@ class SendRecurring implements ShouldQueue { //Admin notification for recurring invoice sent. if ($invoice->invitations->count() >= 1) { - + event(new \App\Events\General\EntityWasEmailed($invoice->invitations->first(), $invoice->company, \App\Utils\Ninja::eventVars(auth()->user() ? auth()->user()->id : null), 'invoice')); $invoice->entityEmailEvent($invoice->invitations->first(), 'invoice', 'email_template_invoice'); } diff --git a/app/Jobs/RecurringInvoice/UpdateRecurring.php b/app/Jobs/RecurringInvoice/UpdateRecurring.php index c6608faf5f..521fd18966 100644 --- a/app/Jobs/RecurringInvoice/UpdateRecurring.php +++ b/app/Jobs/RecurringInvoice/UpdateRecurring.php @@ -1,4 +1,5 @@ $csv, 'file_name' => "{$this->file_name}", 'mime' => 'text/csv']; - if(in_array(get_class($export), [ARDetailReport::class, ARSummaryReport::class, ClientBalanceReport::class, ClientSalesReport::class, TaxSummaryReport::class])) { + if (in_array(get_class($export), [ARDetailReport::class, ARSummaryReport::class, ClientBalanceReport::class, ClientSalesReport::class, TaxSummaryReport::class])) { $pdf = base64_encode($export->getPdf()); $files[] = ['file' => $pdf, 'file_name' => str_replace(".csv", ".pdf", $this->file_name), 'mime' => 'application/pdf']; } diff --git a/app/Jobs/Subscription/CleanStaleInvoiceOrder.php b/app/Jobs/Subscription/CleanStaleInvoiceOrder.php index 9efbe2ca26..04c2823280 100644 --- a/app/Jobs/Subscription/CleanStaleInvoiceOrder.php +++ b/app/Jobs/Subscription/CleanStaleInvoiceOrder.php @@ -1,4 +1,5 @@ service()->touchReminder($reminder_template)->save(); $enabled_reminder = 'enable_quote_'.$reminder_template; - + if (in_array($reminder_template, ['reminder1', 'reminder2', 'reminder3', 'reminder_endless', 'endless_reminder']) && $quote->client->getSetting($enabled_reminder) && $quote->client->getSetting('send_reminders') && diff --git a/app/Jobs/Util/ReminderJob.php b/app/Jobs/Util/ReminderJob.php index fb10b06461..913c732195 100644 --- a/app/Jobs/Util/ReminderJob.php +++ b/app/Jobs/Util/ReminderJob.php @@ -1,4 +1,5 @@ client->getSetting('send_reminders') && (Ninja::isSelfHost() || $invoice->company->account->isPaidHostedClient())) { - $event_fired = false; + $event_fired = false; - $invoice->invitations->each(function ($invitation) use ($invoice, $reminder_template, &$event_fired) { - if ($invitation->contact && !$invitation->contact->trashed() && $invitation->contact->email && !$invitation->contact->is_locked) { - EmailEntity::dispatch($invitation->withoutRelations(), $invitation->company->db, $reminder_template); - nrlog("Firing reminder email for invoice {$invoice->number} - {$reminder_template}"); - $invoice->entityEmailEvent($invitation, $reminder_template); - $invoice->sendEvent(Webhook::EVENT_REMIND_INVOICE, "client"); - - if (!$event_fired) { - event(new \App\Events\General\EntityWasEmailed($invitation, $invoice->company, \App\Utils\Ninja::eventVars(auth()->user() ? auth()->user()->id : null), $reminder_template)); - $event_fired = true; - } - - usleep(200000); + $invoice->invitations->each(function ($invitation) use ($invoice, $reminder_template, &$event_fired) { + if ($invitation->contact && !$invitation->contact->trashed() && $invitation->contact->email && !$invitation->contact->is_locked) { + EmailEntity::dispatch($invitation->withoutRelations(), $invitation->company->db, $reminder_template); + nrlog("Firing reminder email for invoice {$invoice->number} - {$reminder_template}"); + $invoice->entityEmailEvent($invitation, $reminder_template); + $invoice->sendEvent(Webhook::EVENT_REMIND_INVOICE, "client"); + + if (!$event_fired) { + event(new \App\Events\General\EntityWasEmailed($invitation, $invoice->company, \App\Utils\Ninja::eventVars(auth()->user() ? auth()->user()->id : null), $reminder_template)); + $event_fired = true; } - }); - } - $invoice->service()->setReminder()->save(); - } else { - $invoice->next_send_date = null; - $invoice->save(); + + usleep(200000); + } + }); } + $invoice->service()->setReminder()->save(); + } else { + $invoice->next_send_date = null; + $invoice->save(); + } } private function addFeeToNewInvoice(Invoice $over_due_invoice, string $reminder_template, array $fees) @@ -296,7 +297,7 @@ class ReminderJob implements ShouldQueue */ private function setLateFee($invoice, $amount, $percent): Invoice { - + $temp_invoice_balance = $invoice->balance; if ($amount <= 0 && $percent <= 0) { diff --git a/app/Jobs/Util/SchedulerCheck.php b/app/Jobs/Util/SchedulerCheck.php index ad1c8c6dfc..6ca85a8565 100644 --- a/app/Jobs/Util/SchedulerCheck.php +++ b/app/Jobs/Util/SchedulerCheck.php @@ -1,4 +1,5 @@ with([ + if ($ct = CompanyToken::on($db)->with([ 'user.account', 'company', - 'account', + 'account', ])->where('token', $token)->first()) { - self::setDB($db); + self::setDB($db); - return $ct; + return $ct; } } diff --git a/app/Libraries/OAuth/OAuth.php b/app/Libraries/OAuth/OAuth.php index 3dba4e16b5..cf9fbea9c2 100644 --- a/app/Libraries/OAuth/OAuth.php +++ b/app/Libraries/OAuth/OAuth.php @@ -1,4 +1,5 @@ client_contact; $contacts = \App\Models\ClientContact::where('company_id', $client_contact->company_id) - ->where('email', $client_contact->email); - + ->where('email', $client_contact->email); + $contacts->update(['last_login' => now()]); \App\Models\Client::withTrashed()->whereIn('id', $contacts->pluck('client_id'))->where('is_deleted', false)->update(['last_login' => now()]); - + } } diff --git a/app/Listeners/Credit/CreditCreatedNotification.php b/app/Listeners/Credit/CreditCreatedNotification.php index b2f82f0333..a3519767d7 100644 --- a/app/Listeners/Credit/CreditCreatedNotification.php +++ b/app/Listeners/Credit/CreditCreatedNotification.php @@ -1,4 +1,5 @@ sent->getMessageId(); diff --git a/app/Listeners/Misc/InvitationViewedListener.php b/app/Listeners/Misc/InvitationViewedListener.php index 9610b3328e..574a9dcf94 100644 --- a/app/Listeners/Misc/InvitationViewedListener.php +++ b/app/Listeners/Misc/InvitationViewedListener.php @@ -1,4 +1,5 @@ settings = $user->account->companies->first()->settings; $nmo->to_user = $user; - try{ + try { NinjaMailerJob::dispatch($nmo, true); } catch (\Exception $e) { //this will catch for users that don't have their mail server configured correctly. diff --git a/app/Listeners/User/UpdatedUserActivity.php b/app/Listeners/User/UpdatedUserActivity.php index 0a83cdacd5..417bf0ae4e 100644 --- a/app/Listeners/User/UpdatedUserActivity.php +++ b/app/Listeners/User/UpdatedUserActivity.php @@ -1,4 +1,5 @@ state['initial_completed'] = true; - if(!$this->subscription()->registration_required){ - + if (!$this->subscription()->registration_required) { + $service = new ClientRegisterService( company: $this->subscription()->company, additional: $this->additional_fields, @@ -76,7 +76,7 @@ class RegisterOrLogin extends Component auth()->guard('contact')->loginUsingId($contact->id, true); $this->dispatch('purchase.next'); return; - + } if ($this->state['otp']) { @@ -280,7 +280,7 @@ class RegisterOrLogin extends Component $this->dispatch('purchase.next'); return; } - + } public function render() diff --git a/app/Livewire/BillingPortal/Purchase.php b/app/Livewire/BillingPortal/Purchase.php index 352a34e21a..a281dbc5ac 100644 --- a/app/Livewire/BillingPortal/Purchase.php +++ b/app/Livewire/BillingPortal/Purchase.php @@ -140,7 +140,7 @@ class Purchase extends Component $sub = Subscription::find($this->decodePrimaryKey($this->subscription_id)); - if(!$sub){ + if (!$sub) { session()->flash('title', __('texts.subscription_unavailable')); @@ -149,7 +149,7 @@ class Purchase extends Component return redirect()->route('client.error'); } - + if ($sub->steps) { $steps = collect(explode(',', $sub->steps)) ->map(fn ($step) => $classes[$step]) diff --git a/app/Livewire/BillingPortalPurchase.php b/app/Livewire/BillingPortalPurchase.php index c6af5d3d3b..ec572588ec 100644 --- a/app/Livewire/BillingPortalPurchase.php +++ b/app/Livewire/BillingPortalPurchase.php @@ -1,4 +1,5 @@ orWhereNull('due_date'); }) // ->orderBy($this->sort_field, $this->sort_asc ? 'asc' : 'desc') - ->when($this->sort_field == 'number', function ($q){ + ->when($this->sort_field == 'number', function ($q) { $q->orderByRaw("REGEXP_REPLACE(number,'[^0-9]+','')+0 " . ($this->sort_asc ? 'desc' : 'asc')); }) - ->when($this->sort_field != 'number', function ($q){ + ->when($this->sort_field != 'number', function ($q) { $q->orderBy($this->sort_field, ($this->sort_asc ? 'desc' : 'asc')); }) ->withTrashed() diff --git a/app/Livewire/DocumentsTable.php b/app/Livewire/DocumentsTable.php index 3ff0b3c503..7976882811 100644 --- a/app/Livewire/DocumentsTable.php +++ b/app/Livewire/DocumentsTable.php @@ -123,7 +123,7 @@ class DocumentsTable extends Component return $client->documents() ->where('is_public', true) ->orWhere(function ($query) use ($client) { - + $query->whereHasMorph('documentable', [Company::class], function ($q) use ($client) { $q->where('is_public', true)->where('company_id', $client->company_id); }); diff --git a/app/Livewire/Flow2/InvoicePay.php b/app/Livewire/Flow2/InvoicePay.php index df91192645..7a2a7a20a2 100644 --- a/app/Livewire/Flow2/InvoicePay.php +++ b/app/Livewire/Flow2/InvoicePay.php @@ -145,8 +145,9 @@ class InvoicePay extends Component $company_gateway = CompanyGateway::query()->find($company_gateway_id); - if(!$company_gateway) + if (!$company_gateway) { return $this->required_fields = false; + } $this->checkRequiredFields($company_gateway); } @@ -291,7 +292,7 @@ class InvoicePay extends Component 'amount' => array_sum(array_column($payable_invoices, 'amount')), 'payable_invoices' => $payable_invoices, ]); - + } public function render(): \Illuminate\Contracts\View\Factory|\Illuminate\View\View diff --git a/app/Livewire/Flow2/InvoiceSummary.php b/app/Livewire/Flow2/InvoiceSummary.php index 209f2b5830..ae29dfe0d1 100644 --- a/app/Livewire/Flow2/InvoiceSummary.php +++ b/app/Livewire/Flow2/InvoiceSummary.php @@ -43,7 +43,7 @@ class InvoiceSummary extends Component #[On(self::CONTEXT_UPDATE)] public function onContextUpdate(): void { - + $_context = $this->getContext(); // refactor logic for updating the price for eg if it changes with under/over pay @@ -57,7 +57,7 @@ class InvoiceSummary extends Component #[On('payment-view-rendered')] public function handlePaymentViewRendered() { - + $_context = $this->getContext(); $contact = $_context['contact'] ?? auth()->guard('contact')->user(); @@ -74,7 +74,7 @@ class InvoiceSummary extends Component $invitation_id = $_context['invitation_id']; $db = $_context['db']; - + $invite = \App\Models\InvoiceInvitation::on($db)->withTrashed()->find($invitation_id); $file_name = $invite->invoice->numberFormatter().'.pdf'; diff --git a/app/Livewire/Flow2/UnderOverPayment.php b/app/Livewire/Flow2/UnderOverPayment.php index efbfcff9ff..c5e8733210 100644 --- a/app/Livewire/Flow2/UnderOverPayment.php +++ b/app/Livewire/Flow2/UnderOverPayment.php @@ -32,7 +32,7 @@ class UnderOverPayment extends Component public function mount() { - + $_context = $this->getContext(); $contact = $_context['contact'] ?? auth()->guard('contact')->user(); diff --git a/app/Livewire/InvoicesTable.php b/app/Livewire/InvoicesTable.php index 8fe27a607b..59d486af6a 100644 --- a/app/Livewire/InvoicesTable.php +++ b/app/Livewire/InvoicesTable.php @@ -51,13 +51,13 @@ class InvoicesTable extends Component ->where('is_deleted', false) ->where('is_proforma', false) ->with('client.gateway_tokens', 'client.contacts') - ->when($this->sort_field == 'number', function ($q){ + ->when($this->sort_field == 'number', function ($q) { $q->orderByRaw("REGEXP_REPLACE(number,'[^0-9]+','')+0 " . ($this->sort_asc ? 'desc' : 'asc')); }) - ->when($this->sort_field != 'number', function ($q){ + ->when($this->sort_field != 'number', function ($q) { $q->orderBy($this->sort_field, ($this->sort_asc ? 'asc' : 'desc')); }); - // ->orderBy($this->sort_field, $this->sort_asc ? 'asc' : 'desc'); + // ->orderBy($this->sort_field, $this->sort_asc ? 'asc' : 'desc'); if (in_array('paid', $this->status)) { $local_status[] = Invoice::STATUS_PAID; diff --git a/app/Livewire/PaymentsTable.php b/app/Livewire/PaymentsTable.php index 197c736d5b..54890e6b0b 100644 --- a/app/Livewire/PaymentsTable.php +++ b/app/Livewire/PaymentsTable.php @@ -48,10 +48,10 @@ class PaymentsTable extends Component ->where('is_deleted', false) ->whereIn('status_id', [Payment::STATUS_FAILED, Payment::STATUS_COMPLETED, Payment::STATUS_PENDING, Payment::STATUS_REFUNDED, Payment::STATUS_PARTIALLY_REFUNDED]) // ->orderBy($this->sort_field, $this->sort_asc ? 'desc' : 'asc') - ->when($this->sort_field == 'number', function ($q){ + ->when($this->sort_field == 'number', function ($q) { $q->orderByRaw("REGEXP_REPLACE(number,'[^0-9]+','')+0 " . ($this->sort_asc ? 'desc' : 'asc')); }) - ->when($this->sort_field != 'number', function ($q){ + ->when($this->sort_field != 'number', function ($q) { $q->orderBy($this->sort_field, ($this->sort_asc ? 'desc' : 'asc')); }) ->withTrashed() diff --git a/app/Livewire/PdfSlot.php b/app/Livewire/PdfSlot.php index d88e00808a..16c900903f 100644 --- a/app/Livewire/PdfSlot.php +++ b/app/Livewire/PdfSlot.php @@ -49,7 +49,7 @@ class PdfSlot extends Component private $entity_type; private $preference_product_notes_for_html_view; - + public $show_cost = true; public $show_quantity = true; @@ -145,7 +145,7 @@ class PdfSlot extends Component $this->settings = $this->entity()->client ? $this->entity()->client->getMergedSettings() : $this->entity()->company->settings; $this->html_entity_option = $this->entity()->client ? $this->entity()->client->getSetting('show_pdfhtml_on_mobile') : $this->entity()->company->getSetting('show_pdfhtml_on_mobile'); $this->preference_product_notes_for_html_view = $this->entity()->client ? $this->entity()->client->getSetting('preference_product_notes_for_html_view') : $this->entity()->company->getSetting('preference_product_notes_for_html_view'); - + $this->show_cost = in_array('$product.unit_cost', $this->settings->pdf_variables->product_columns); $this->show_line_total = in_array('$product.line_total', $this->settings->pdf_variables->product_columns); $this->show_quantity = in_array('$product.quantity', $this->settings->pdf_variables->product_columns); diff --git a/app/Livewire/QuotesTable.php b/app/Livewire/QuotesTable.php index da8ddf12ba..ef05c58c23 100644 --- a/app/Livewire/QuotesTable.php +++ b/app/Livewire/QuotesTable.php @@ -35,7 +35,7 @@ class QuotesTable extends Component public string $db; public string $sort_field = 'date'; - + public function mount() { MultiDB::setDb($this->db); @@ -60,10 +60,10 @@ class QuotesTable extends Component $query = Quote::query() ->with('client.contacts', 'company') // ->orderBy($this->sort, $this->sort_asc ? 'asc' : 'desc'); - ->when($this->sort == 'number', function ($q){ + ->when($this->sort == 'number', function ($q) { $q->orderByRaw("REGEXP_REPLACE(number,'[^0-9]+','')+0 " . ($this->sort_asc ? 'asc' : 'desc')); }) - ->when($this->sort != 'number', function ($q){ + ->when($this->sort != 'number', function ($q) { $q->orderBy($this->sort, ($this->sort_asc ? 'asc' : 'desc')); }); diff --git a/app/Mail/Admin/ClientPaymentFailureObject.php b/app/Mail/Admin/ClientPaymentFailureObject.php index 97cb1c23a6..2cbcefaf3a 100644 --- a/app/Mail/Admin/ClientPaymentFailureObject.php +++ b/app/Mail/Admin/ClientPaymentFailureObject.php @@ -1,4 +1,5 @@ $this->contact->vendor->present()->name(), 'purchase_order' => $this->entity->number, ] - ), + ), ]; $mail_obj->markdown = 'email.admin.generic'; $mail_obj->tag = $this->company->company_key; - + } else { $mail_obj = new stdClass(); $mail_obj->amount = $this->getAmount(); @@ -117,7 +118,7 @@ class EntitySentObject private function setTemplate() { - + switch ($this->template) { case 'invoice': $this->template_subject = 'texts.notification_invoice_sent_subject'; diff --git a/app/Mail/Admin/EntityViewedObject.php b/app/Mail/Admin/EntityViewedObject.php index ff8f9f20d7..4773aeb497 100644 --- a/app/Mail/Admin/EntityViewedObject.php +++ b/app/Mail/Admin/EntityViewedObject.php @@ -1,4 +1,5 @@ 1) { if (\App\Utils\Ninja::isHosted() && $this->company->account->isPaid()) { $mail_obj->bcc = explode(',', str_replace(' ', '', $bccs)); - } - - if(Ninja::isSelfHost()){ + } + + if (Ninja::isSelfHost()) { $mail_obj->bcc = explode(',', str_replace(' ', '', $bccs)); } } diff --git a/app/Mail/Admin/PurchaseOrderAcceptedObject.php b/app/Mail/Admin/PurchaseOrderAcceptedObject.php index 44af90b9ef..03537bb2fb 100644 --- a/app/Mail/Admin/PurchaseOrderAcceptedObject.php +++ b/app/Mail/Admin/PurchaseOrderAcceptedObject.php @@ -1,4 +1,5 @@ template_data) && array_key_exists('body', $this->template_data) && strlen($this->template_data['body']) > 0) { $body_template = $this->template_data['body']; - } elseif($this->reminder_template == 'reminder1' && strlen($this->client->getSetting('email_quote_template_reminder1')) > 0){ + } elseif ($this->reminder_template == 'reminder1' && strlen($this->client->getSetting('email_quote_template_reminder1')) > 0) { $body_template = $this->client->getSetting('email_quote_template_reminder1'); - } elseif($this->reminder_template == 'reminder1'){ + } elseif ($this->reminder_template == 'reminder1') { $body_template = \App\DataMapper\EmailTemplateDefaults::getDefaultTemplate('email_quote_template_reminder1', $this->client->locale()); } else { $body_template = $this->client->getSetting('email_template_'.$this->reminder_template); @@ -83,9 +84,9 @@ class QuoteEmailEngine extends BaseEmailEngine if (is_array($this->template_data) && array_key_exists('subject', $this->template_data) && strlen($this->template_data['subject']) > 0) { $subject_template = $this->template_data['subject']; - } elseif($this->reminder_template == 'reminder1' && strlen($this->client->getSetting('email_quote_subject_reminder1')) > 0){ + } elseif ($this->reminder_template == 'reminder1' && strlen($this->client->getSetting('email_quote_subject_reminder1')) > 0) { $subject_template = $this->client->getSetting('email_quote_subject_reminder1'); - } elseif($this->reminder_template == 'reminder1'){ + } elseif ($this->reminder_template == 'reminder1') { $subject_template = \App\DataMapper\EmailTemplateDefaults::getDefaultTemplate('email_quote_subject_reminder1', $this->client->locale()); } else { $subject_template = $this->client->getSetting('email_subject_'.$this->reminder_template); diff --git a/app/Mail/Import/CompanyImportFailure.php b/app/Mail/Import/CompanyImportFailure.php index 7ea60bc481..6d38899cbe 100644 --- a/app/Mail/Import/CompanyImportFailure.php +++ b/app/Mail/Import/CompanyImportFailure.php @@ -1,4 +1,5 @@ 'boolean', 'updated_at' => 'timestamp', diff --git a/app/Models/Backup.php b/app/Models/Backup.php index 8ab92d7f72..38b5e0b93d 100644 --- a/app/Models/Backup.php +++ b/app/Models/Backup.php @@ -1,4 +1,5 @@ belongsTo(Activity::class); } - + /** * storeRemotely * * @param string $html * @param Client | Vendor $client_or_vendor - * + * * @return void */ public function storeRemotely(?string $html, Client | Vendor $client_or_vendor) @@ -81,10 +82,10 @@ class Backup extends BaseModel $this->disk = $disk; $this->save(); } - + public function storeBackupFile($file) { - + $disk = Ninja::isHosted() ? 'backup' : config('filesystems.default'); Storage::disk($disk)->put($this->filename, $file); @@ -97,25 +98,26 @@ class Backup extends BaseModel * getFile * * pulls backup file from storage - * + * * @return mixed */ public function getFile() { - if(!$this->filename) + if (!$this->filename) { return null; + } $disk = Ninja::isHosted() ? $this->disk : config('filesystems.default'); return Storage::disk($disk)->get($this->filename); } - + /** * deleteFile * * removes backup file from storage - * + * * @return void */ public function deleteFile() diff --git a/app/Models/Bank.php b/app/Models/Bank.php index 2581d73672..30dacb8dad 100644 --- a/app/Models/Bank.php +++ b/app/Models/Bank.php @@ -1,4 +1,5 @@ currency()->code, ['USD']) && in_array(GatewayType::ACSS, array_column($pms, 'gateway_type_id'))) { - // if (in_array($this->currency()->code, ['CAD','USD']) && in_array(GatewayType::ACSS, array_column($pms, 'gateway_type_id'))) { + // if (in_array($this->currency()->code, ['CAD','USD']) && in_array(GatewayType::ACSS, array_column($pms, 'gateway_type_id'))) { // if ($this->currency()->code == 'CAD' && in_array(GatewayType::ACSS, array_column($pms, 'gateway_type_id'))) { foreach ($pms as $pm) { if ($pm['gateway_type_id'] == GatewayType::ACSS) { @@ -1035,31 +1036,33 @@ class Client extends BaseModel implements HasLocalePreference { return $this->getSetting('e_invoice_type') == 'PEPPOL' && $this->company->peppolSendingEnabled() && is_null($this->checkDeliveryNetwork()); } - + /** * checkDeliveryNetwork * * Checks whether the client country is supported * for sending over the PEPPOL network. - * + * * @return string|null */ public function checkDeliveryNetwork(): ?string { - if(!isset($this->country->iso_3166_2)) + if (!isset($this->country->iso_3166_2)) { return "Client has no country set!"; - + } + $br = new \App\DataMapper\Tax\BaseRule(); $government_countries = array_merge($br->peppol_business_countries, $br->peppol_government_countries); - if(in_array($this->country->iso_3166_2, $government_countries) && $this->classification == 'government'){ + if (in_array($this->country->iso_3166_2, $government_countries) && $this->classification == 'government') { return null; } - if(in_array($this->country->iso_3166_2, $br->peppol_business_countries)) + if (in_array($this->country->iso_3166_2, $br->peppol_business_countries)) { return null; + } return "Country {$this->country->full_name} ( {$this->country->iso_3166_2} ) is not supported by the PEPPOL network for e-delivery."; diff --git a/app/Models/ClientContact.php b/app/Models/ClientContact.php index a4e34521cd..73762a6c22 100644 --- a/app/Models/ClientContact.php +++ b/app/Models/ClientContact.php @@ -1,4 +1,5 @@ getMessage()); return null; diff --git a/app/Models/CompanyGateway.php b/app/Models/CompanyGateway.php index d9425efb0a..b29e99a1be 100644 --- a/app/Models/CompanyGateway.php +++ b/app/Models/CompanyGateway.php @@ -1,4 +1,5 @@ company, Ninja::eventVars(auth()->user() ? auth()->user()->id : null), $reminder_template)); break; - + default: // code... break; diff --git a/app/Models/CreditInvitation.php b/app/Models/CreditInvitation.php index 857f4b18ff..f2f2935502 100644 --- a/app/Models/CreditInvitation.php +++ b/app/Models/CreditInvitation.php @@ -1,4 +1,5 @@ belongsTo(Company::class, 'tenant_id', 'id'); } - + } - diff --git a/app/Models/EInvoicingToken.php b/app/Models/EInvoicingToken.php index 2b48ee483d..4d9d48bb2f 100644 --- a/app/Models/EInvoicingToken.php +++ b/app/Models/EInvoicingToken.php @@ -1,4 +1,5 @@ company->locale(); - + App::setLocale($locale); return [ @@ -332,7 +333,7 @@ class Expense extends BaseModel } } - + /** * getTaxAmount * @@ -341,7 +342,7 @@ class Expense extends BaseModel public function getTaxAmount(): float { - $precision = $this->currency->precision ?? 2; + $precision = $this->currency->precision ?? 2; if ($this->calculate_tax_by_amount) { @@ -357,7 +358,7 @@ class Expense extends BaseModel } } } - + /** * calcInclusiveLineTax * diff --git a/app/Models/ExpenseCategory.php b/app/Models/ExpenseCategory.php index 7a7a486e8a..2df30721e1 100644 --- a/app/Models/ExpenseCategory.php +++ b/app/Models/ExpenseCategory.php @@ -1,4 +1,5 @@ company, Ninja::eventVars(auth()->user() ? auth()->user()->id : null), $reminder_template)); diff --git a/app/Models/InvoiceInvitation.php b/app/Models/InvoiceInvitation.php index 83e1d96622..f1628148e2 100644 --- a/app/Models/InvoiceInvitation.php +++ b/app/Models/InvoiceInvitation.php @@ -1,4 +1,5 @@ save(); } - + /** * updateEntity * @@ -148,7 +149,7 @@ class License extends StaticModel */ public function updateEntity(TaxEntity $entity, string $search_key = 'legal_entity_id') { - + if (!is_array($this->entities)) { return; } @@ -169,7 +170,7 @@ class License extends StaticModel public function countEntities(): int { - + if (!is_array($this->entities)) { return 0; } @@ -179,7 +180,7 @@ class License extends StaticModel public function findEntity(string $key, mixed $value): ?TaxEntity { - + if (!is_array($this->entities)) { return null; } diff --git a/app/Models/Location.php b/app/Models/Location.php index d637d6ca58..6ec77c329e 100644 --- a/app/Models/Location.php +++ b/app/Models/Location.php @@ -60,12 +60,11 @@ use Illuminate\Database\Eloquent\SoftDeletes; * @property-read \App\Models\Vendor|null $vendor * @property-read \App\Models\Company $company * @property-read \App\Models\Country|null $country - * + * * @mixin \Eloquent */ class Location extends BaseModel { - use SoftDeletes; use Filterable; use Excludable; diff --git a/app/Models/Payment.php b/app/Models/Payment.php index 5da39c54fe..17d9798587 100644 --- a/app/Models/Payment.php +++ b/app/Models/Payment.php @@ -1,4 +1,5 @@ '.ctrans('texts.payment_status_3').''; case self::STATUS_COMPLETED: - if($this->applied == 0){ + if ($this->applied == 0) { return '
' . ctrans('texts.unapplied') . '
'; - } - elseif ($this->amount > $this->applied) { + } elseif ($this->amount > $this->applied) { return '
' . ctrans('texts.partially_unapplied') . '
'; } diff --git a/app/Models/PaymentHash.php b/app/Models/PaymentHash.php index fa3581e41c..166c1a3c56 100644 --- a/app/Models/PaymentHash.php +++ b/app/Models/PaymentHash.php @@ -1,4 +1,5 @@ [ "verify_peer" => false, diff --git a/app/Models/Presenters/CreditPresenter.php b/app/Models/Presenters/CreditPresenter.php index 0c9967a3bd..c7ca33f258 100644 --- a/app/Models/Presenters/CreditPresenter.php +++ b/app/Models/Presenters/CreditPresenter.php @@ -1,4 +1,5 @@ entity->last_name ?: ''; } - + public function search_display() { return strlen($this->entity->email ?? '') > 2 ? $this->name().' <'.$this->entity->email.'>' : $this->name(); diff --git a/app/Models/Presenters/VendorPresenter.php b/app/Models/Presenters/VendorPresenter.php index 4a685e4bd4..338577534f 100644 --- a/app/Models/Presenters/VendorPresenter.php +++ b/app/Models/Presenters/VendorPresenter.php @@ -1,4 +1,5 @@ hasMany(Quote::class); } - /** - * Service entry points. - * - * @return ProjectService - */ + /** + * Service entry points. + * + * @return ProjectService + */ public function service(): ProjectService { return new ProjectService($this); diff --git a/app/Models/Proposal.php b/app/Models/Proposal.php index 0ec95e93d8..0d17c79765 100644 --- a/app/Models/Proposal.php +++ b/app/Models/Proposal.php @@ -1,4 +1,5 @@ company, Ninja::eventVars(auth()->user() ? auth()->user()->id : null), $reminder_template)); break; - + default: event(new PurchaseOrderWasEmailed($invitation, $invitation->company, Ninja::eventVars(auth()->user() ? auth()->user()->id : null), $reminder_template)); break; diff --git a/app/Models/PurchaseOrderInvitation.php b/app/Models/PurchaseOrderInvitation.php index f2fbbb90f2..9ae8ecfdd4 100644 --- a/app/Models/PurchaseOrderInvitation.php +++ b/app/Models/PurchaseOrderInvitation.php @@ -1,4 +1,5 @@ company, Ninja::eventVars(auth()->user() ? auth()->user()->id : null), $reminder_template)); @@ -505,6 +506,6 @@ class Quote extends BaseModel } } - - + + } diff --git a/app/Models/QuoteInvitation.php b/app/Models/QuoteInvitation.php index 8c830d4174..3a56c04281 100644 --- a/app/Models/QuoteInvitation.php +++ b/app/Models/QuoteInvitation.php @@ -1,4 +1,5 @@ client->timezone_offset() < 0) { // $next_send_date = $this->nextSendDateClient($next_send_date->addDay()->format('Y-m-d')); // } else { - $next_send_date = $this->nextDateByFrequencyNoOffset($next_send_date); + $next_send_date = $this->nextDateByFrequencyNoOffset($next_send_date); // } } diff --git a/app/Models/RecurringInvoiceInvitation.php b/app/Models/RecurringInvoiceInvitation.php index 80d93999a0..974f30f775 100644 --- a/app/Models/RecurringInvoiceInvitation.php +++ b/app/Models/RecurringInvoiceInvitation.php @@ -1,4 +1,5 @@ rate) && $this->rate > 0) { + if (is_numeric($this->rate) && $this->rate > 0) { return $this->rate; } @@ -393,7 +394,7 @@ class Task extends BaseModel if ($this->company->invoice_task_hours) { $duration = $this->logDuration($log[0], $log[1]); - if($this->company->use_comma_as_decimal_place){ + if ($this->company->use_comma_as_decimal_place) { $duration = number_format($duration, 2, ',', '.'); } @@ -407,7 +408,7 @@ class Task extends BaseModel } //need to return early if there is nothing, otherwise we end up injecting a blank new line. - if(count($parts) == 1 && empty($parts[0])) { + if (count($parts) == 1 && empty($parts[0])) { return ''; } diff --git a/app/Models/TaskStatus.php b/app/Models/TaskStatus.php index acca6922ba..7c5d97bb0c 100644 --- a/app/Models/TaskStatus.php +++ b/app/Models/TaskStatus.php @@ -1,4 +1,5 @@ referral_earnings); $updated_earnings = $earnings->map(function ($earning) use ($entity) { diff --git a/app/Models/Vendor.php b/app/Models/Vendor.php index 5726239f58..890e10f724 100644 --- a/app/Models/Vendor.php +++ b/app/Models/Vendor.php @@ -1,4 +1,5 @@ getOriginal('portal_domain'), $company)->onQueue('domain'); } - if(Ninja::isHosted()){ - + if (Ninja::isHosted()) { + $property = 'name'; $original = data_get($company->getOriginal('settings'), $property); $current = data_get($company->settings, $property); - if($original !== $current){ + if ($original !== $current) { try { (new \Modules\Admin\Jobs\Account\FieldQuality())->checkCompanyName($current, $company); } catch (\Throwable $e) { diff --git a/app/Observers/CompanyTokenObserver.php b/app/Observers/CompanyTokenObserver.php index e68387b57a..ad94c16994 100644 --- a/app/Observers/CompanyTokenObserver.php +++ b/app/Observers/CompanyTokenObserver.php @@ -1,4 +1,5 @@ getOriginal('postal_code') != $location->postal_code && $location->country_id == 840 && $location->company->calculate_taxes && !$location->company->account->isFreeHostedClient()) { - UpdateLocationTaxData::dispatch($location, $location->company); + UpdateLocationTaxData::dispatch($location, $location->company); } } @@ -52,7 +54,7 @@ class LocationObserver */ public function deleted(Location $location) { - + } /** @@ -63,7 +65,7 @@ class LocationObserver */ public function restored(Location $location) { - + } /** diff --git a/app/Observers/PaymentObserver.php b/app/Observers/PaymentObserver.php index 996dce46da..4393a73630 100644 --- a/app/Observers/PaymentObserver.php +++ b/app/Observers/PaymentObserver.php @@ -1,4 +1,5 @@ payment_hash->fee_invoice; - if(!$invoice) + if (!$invoice) { return; + } if (collect($invoice->line_items)->contains('unit_code', $this->payment_hash->hash)) { $invoice->service()->toggleFeesPaid($this->payment_hash->hash)->save(); diff --git a/app/PaymentDrivers/Blockonomics/Blockonomics.php b/app/PaymentDrivers/Blockonomics/Blockonomics.php index 40d160b057..3c852b71b1 100644 --- a/app/PaymentDrivers/Blockonomics/Blockonomics.php +++ b/app/PaymentDrivers/Blockonomics/Blockonomics.php @@ -63,7 +63,7 @@ class Blockonomics implements LivewireMethodInterface nlog($response->body()); - if ($response->status() == 401) { + if ($response->status() == 401) { return ['success' => false, 'message' => 'API Key is incorrect']; }; @@ -76,7 +76,7 @@ class Blockonomics implements LivewireMethodInterface } else { return ['success' => false, 'message' => "Could not generate new address (This may be a temporary error. Please try again). \n\n

If this continues, please ask website administrator to check blockonomics registered email address for error messages"]; } - + } public function getBTCPrice() diff --git a/app/PaymentDrivers/BlockonomicsPaymentDriver.php b/app/PaymentDrivers/BlockonomicsPaymentDriver.php index a774d2d12a..8651f28ad3 100644 --- a/app/PaymentDrivers/BlockonomicsPaymentDriver.php +++ b/app/PaymentDrivers/BlockonomicsPaymentDriver.php @@ -211,14 +211,14 @@ class BlockonomicsPaymentDriver extends BaseDriver try { $api_key = $this->company_gateway->getConfigField('apiKey'); - if(!$api_key) { + if (!$api_key) { return 'No API Key'; } $get_stores_response = Http::withToken($api_key) ->get($this->STORES_URL, ['wallets' => 'true']); $get_stores_response_status = $get_stores_response->status(); - if($get_stores_response_status == 401) { + if ($get_stores_response_status == 401) { return 'API Key is incorrect'; } diff --git a/app/PaymentDrivers/Braintree/ACH.php b/app/PaymentDrivers/Braintree/ACH.php index eb791586d6..7665b2ec78 100644 --- a/app/PaymentDrivers/Braintree/ACH.php +++ b/app/PaymentDrivers/Braintree/ACH.php @@ -1,4 +1,5 @@ object(); $message = [ @@ -148,11 +148,11 @@ class ACH implements LivewireMethodInterface public function paymentResponse($request) { nlog($request->all()); - + $payment_hash = PaymentHash::where('hash', $request->input('payment_hash'))->firstOrFail(); //Handle Token Billing - if($request->token && strlen($request->token) > 4){ + if ($request->token && strlen($request->token) > 4) { $cgt = \App\Models\ClientGatewayToken::where('token', $request->token)->firstOrFail(); $payment = $this->tokenBilling($cgt, $payment_hash); @@ -160,8 +160,8 @@ class ACH implements LivewireMethodInterface return redirect()->route('client.payments.show', ['payment' => $payment->hashed_id]); } - //Handle Storing Payment Method + Token Billing - if(isset($this->forte->company_gateway->token_billing) && $this->forte->company_gateway->token_billing != 'off'){ + //Handle Storing Payment Method + Token Billing + if (isset($this->forte->company_gateway->token_billing) && $this->forte->company_gateway->token_billing != 'off') { $data = [ 'account_holder_name' => $request->account_holder_name, @@ -224,7 +224,7 @@ class ACH implements LivewireMethodInterface $payment = $this->forte->createPayment($data, Payment::STATUS_COMPLETED); return redirect()->route('client.payments.show', ['payment' => $payment->hashed_id]); - + } //Handle Failures. diff --git a/app/PaymentDrivers/FortePaymentDriver.php b/app/PaymentDrivers/FortePaymentDriver.php index ad5fac1210..586c332b8c 100644 --- a/app/PaymentDrivers/FortePaymentDriver.php +++ b/app/PaymentDrivers/FortePaymentDriver.php @@ -1,4 +1,5 @@ get("{$forte_base_uri}/organizations/{$forte_organization_id}/locations/{$forte_location_id}/customers/"); $error = $response->json()['response']['response_desc'] ?? 'error'; - + return $response->successful() ? 'ok' : $error; } @@ -277,7 +278,7 @@ class FortePaymentDriver extends BaseDriver ], ]; - if($cgt->gateway_type_id == GatewayType::BANK_TRANSFER) { + if ($cgt->gateway_type_id == GatewayType::BANK_TRANSFER) { $data["echeck"] = [ "sec_code" => "WEB", ]; diff --git a/app/PaymentDrivers/GoCardless/DirectDebit.php b/app/PaymentDrivers/GoCardless/DirectDebit.php index eb86a758e8..0a173e0dbf 100644 --- a/app/PaymentDrivers/GoCardless/DirectDebit.php +++ b/app/PaymentDrivers/GoCardless/DirectDebit.php @@ -71,8 +71,7 @@ class DirectDebit implements MethodInterface, LivewireMethodInterface ] ] ]); - } - catch(\Throwable $e) { + } catch (\Throwable $e) { nlog($e->getMessage()); return $this->processUnsuccessfulAuthorization($e); } @@ -109,7 +108,7 @@ class DirectDebit implements MethodInterface, LivewireMethodInterface /** * Handle unsuccessful authorization. * - * @param \Exception | \Throwable $exception + * @param \Exception | \Throwable $exception * @throws PaymentFailed */ public function processUnsuccessfulAuthorization($exception) diff --git a/app/PaymentDrivers/GoCardlessPaymentDriver.php b/app/PaymentDrivers/GoCardlessPaymentDriver.php index 6ab9f01b1c..f407909efc 100644 --- a/app/PaymentDrivers/GoCardlessPaymentDriver.php +++ b/app/PaymentDrivers/GoCardlessPaymentDriver.php @@ -1,4 +1,5 @@ "); - if(method_exists($response, 'json')) { + if (method_exists($response, 'json')) { nlog($response->json()); } else { nlog($response); diff --git a/app/PaymentDrivers/PaytracePaymentDriver.php b/app/PaymentDrivers/PaytracePaymentDriver.php index c03ec1ec1b..78a3236e0b 100644 --- a/app/PaymentDrivers/PaytracePaymentDriver.php +++ b/app/PaymentDrivers/PaytracePaymentDriver.php @@ -1,4 +1,5 @@ status_id = Payment::STATUS_COMPLETED; $payment->save(); - $references =collect($transactions)->where('id', $payment->transaction_reference)->first(); + $references = collect($transactions)->where('id', $payment->transaction_reference)->first(); - if($references) { + if ($references) { SystemLogger::dispatch( ['response' => $references->toArray(), 'data' => []], SystemLog::CATEGORY_GATEWAY_RESPONSE, @@ -138,16 +139,15 @@ class TransactionReport implements ShouldQueue $error ); - if(collect($transactions)->where('id', $payment->transaction_reference)->first()) - { + if (collect($transactions)->where('id', $payment->transaction_reference)->first()) { SystemLogger::dispatch( ['response' => collect($transactions)->where('id', $payment->transaction_reference)->first()->toArray(), 'data' => []], SystemLog::CATEGORY_GATEWAY_RESPONSE, SystemLog::EVENT_GATEWAY_FAILURE, SystemLog::TYPE_ROTESSA, $payment->client, - $payment->company, - ); + $payment->company, + ); } }); diff --git a/app/PaymentDrivers/Rotessa/PaymentMethod.php b/app/PaymentDrivers/Rotessa/PaymentMethod.php index a5da95d807..baa5aa8cdb 100755 --- a/app/PaymentDrivers/Rotessa/PaymentMethod.php +++ b/app/PaymentDrivers/Rotessa/PaymentMethod.php @@ -194,7 +194,7 @@ class PaymentMethod implements MethodInterface, LivewireMethodInterface } } - + /** * Handle unsuccessful payment for Rotessa. @@ -271,7 +271,7 @@ class PaymentMethod implements MethodInterface, LivewireMethodInterface public function tokenBilling(\App\Models\ClientGatewayToken $customer, \App\Models\PaymentHash $payment_hash) { - + try { $transaction = array_merge($this->transaction, [ diff --git a/app/PaymentDrivers/RotessaPaymentDriver.php b/app/PaymentDrivers/RotessaPaymentDriver.php index 92c173a16f..709a79a4e0 100644 --- a/app/PaymentDrivers/RotessaPaymentDriver.php +++ b/app/PaymentDrivers/RotessaPaymentDriver.php @@ -1,4 +1,5 @@ setPaymentMethod($cgt->gateway_type_id); - + return $this->payment_method->tokenBilling($cgt, $payment_hash); } diff --git a/app/PaymentDrivers/Sample/PaymentDriver.php b/app/PaymentDrivers/Sample/PaymentDriver.php index 51d33ca102..82092a3834 100644 --- a/app/PaymentDrivers/Sample/PaymentDriver.php +++ b/app/PaymentDrivers/Sample/PaymentDriver.php @@ -1,4 +1,5 @@ company_key); - + $company = Company::query()->where('company_key', $this->company_key)->firstOrFail(); foreach ($this->stripe_request as $transaction) { diff --git a/app/PaymentDrivers/Stripe/Jobs/StripeWebhook.php b/app/PaymentDrivers/Stripe/Jobs/StripeWebhook.php index 640d815f05..494cd3a1fc 100644 --- a/app/PaymentDrivers/Stripe/Jobs/StripeWebhook.php +++ b/app/PaymentDrivers/Stripe/Jobs/StripeWebhook.php @@ -1,4 +1,5 @@ init(); - try{ + try { if ($this->stripe_connect) { // Verify Connect configuration if (!strlen($this->company_gateway->getConfigField('account_id')) > 1) { @@ -1054,7 +1054,7 @@ class StripePaymentDriver extends BaseDriver implements SupportsHeadlessInterfac } else { // Test regular API key access $api_key = $this->company_gateway->getConfigField('apiKey'); - + if (empty($api_key)) { return 'error'; } diff --git a/app/PaymentDrivers/WePayPaymentDriver.php b/app/PaymentDrivers/WePayPaymentDriver.php index 5e04525dc0..a534f5371c 100644 --- a/app/PaymentDrivers/WePayPaymentDriver.php +++ b/app/PaymentDrivers/WePayPaymentDriver.php @@ -1,4 +1,5 @@ save(); //rate limiter - if(!in_array($fields->activity_type_id, [Activity::EMAIL_INVOICE, Activity::EMAIL_CREDIT, Activity::EMAIL_QUOTE, Activity::EMAIL_PURCHASE_ORDER])){ + if (!in_array($fields->activity_type_id, [Activity::EMAIL_INVOICE, Activity::EMAIL_CREDIT, Activity::EMAIL_QUOTE, Activity::EMAIL_PURCHASE_ORDER])) { $this->createBackup($entity, $activity); } } @@ -146,7 +147,7 @@ class ActivityRepository extends BaseRepository } elseif ($entity instanceof RecurringInvoice) { $entity_type = 'recurring_invoice'; $entity_design_id = 'invoice_design_id'; - + $entity->load('client.company', 'invitations'); $document_type = 'product'; } elseif ($entity instanceof Quote) { diff --git a/app/Repositories/BankIntegrationRepository.php b/app/Repositories/BankIntegrationRepository.php index d4247e9660..8b8e465b6f 100644 --- a/app/Repositories/BankIntegrationRepository.php +++ b/app/Repositories/BankIntegrationRepository.php @@ -1,4 +1,5 @@ unlink($entity); - parent::delete($bt); + parent::delete($bt); } diff --git a/app/Repositories/BankTransactionRuleRepository.php b/app/Repositories/BankTransactionRuleRepository.php index 7dcadcfe5a..794580824b 100644 --- a/app/Repositories/BankTransactionRuleRepository.php +++ b/app/Repositories/BankTransactionRuleRepository.php @@ -1,4 +1,5 @@ sortByDesc('is_primary')->filter(function ($contact){ + $contacts = $contacts->sortByDesc('is_primary')->filter(function ($contact) { return is_array($contact); })->map(function ($contact) { $contact['is_primary'] = $this->is_primary; diff --git a/app/Repositories/ClientGatewayTokenRepository.php b/app/Repositories/ClientGatewayTokenRepository.php index a9062fe76f..65db94e571 100644 --- a/app/Repositories/ClientGatewayTokenRepository.php +++ b/app/Repositories/ClientGatewayTokenRepository.php @@ -1,4 +1,5 @@ {$client->id} => {$client->number}"); - + $client->contacts()->forceDelete(); $client->tasks()->forceDelete(); $client->invoices()->forceDelete(); diff --git a/app/Repositories/CompanyRepository.php b/app/Repositories/CompanyRepository.php index f2b86e53d1..02dc7d50aa 100644 --- a/app/Repositories/CompanyRepository.php +++ b/app/Repositories/CompanyRepository.php @@ -1,4 +1,5 @@ lockForUpdate()->find($invoice->id); + return \App\Models\Invoice::withTrashed()->lockForUpdate()->find($invoice->id); }); if (!$invoice || $invoice->is_deleted) { @@ -75,7 +76,7 @@ class InvoiceRepository extends BaseRepository $invoice->is_deleted = true; $invoice->saveQuietly(); - + $invoice = $invoice->service()->markDeleted()->save(); return $invoice; diff --git a/app/Repositories/Migration/InvoiceMigrationRepository.php b/app/Repositories/Migration/InvoiceMigrationRepository.php index 7f62184b7f..807cec3dec 100644 --- a/app/Repositories/Migration/InvoiceMigrationRepository.php +++ b/app/Repositories/Migration/InvoiceMigrationRepository.php @@ -1,4 +1,5 @@ where('id', $data['client_id'])->withTrashed()->first(); + $client = Client::query()->where('id', $data['client_id'])->withTrashed()->first(); /*We only update the paid to date ONCE per payment*/ if (array_key_exists('invoices', $data) && is_array($data['invoices']) && count($data['invoices']) > 0) { @@ -93,7 +94,7 @@ class PaymentRepository extends BaseRepository $_credit_totals = array_sum(array_column($data['credits'], 'amount')); $client->service()->updatePaidToDate($_credit_totals)->save(); } - + $client->refresh(); } @@ -198,7 +199,7 @@ class PaymentRepository extends BaseRepository event(new PaymentWasCreated($payment, $payment->company, Ninja::eventVars(auth()->user() ? auth()->user()->id : null))); } - $payment->applied += ($invoice_totals - $credit_totals); + $payment->applied += ($invoice_totals - $credit_totals); $payment->saveQuietly(); diff --git a/app/Repositories/PaymentTermRepository.php b/app/Repositories/PaymentTermRepository.php index 49cb5a5e4c..d1638a87c3 100644 --- a/app/Repositories/PaymentTermRepository.php +++ b/app/Repositories/PaymentTermRepository.php @@ -1,4 +1,5 @@ tasks() ->withTrashed() ->whereNull('invoice_id') @@ -39,19 +40,16 @@ class ProjectRepository extends BaseRepository ->cursor() ->each(function ($task, $key) use (&$lines) { - if (!$task->isRunning()) - { + if (!$task->isRunning()) { if ($key == 0 && $task->company->invoice_task_project) { $body = '
'.$task->project->name.'
' .$task->project?->public_notes ?? ''; //@phpstan-ignore-line $body .= '
'.$task->description().'
'; - } - elseif(!$task->company->invoice_task_hours && !$task->company->invoice_task_timelog && !$task->company->invoice_task_datelog && !$task->company->invoice_task_item_description) { + } elseif (!$task->company->invoice_task_hours && !$task->company->invoice_task_timelog && !$task->company->invoice_task_datelog && !$task->company->invoice_task_item_description) { $body = $task->description ?? ''; - } - else { + } else { $body = '
'.$task->description().'
'; } - + $item = new InvoiceItem(); $item->quantity = $task->getQuantity(); $item->cost = $task->getRate(); @@ -63,7 +61,7 @@ class ProjectRepository extends BaseRepository $lines[] = $item; } - + }); $project->expenses() @@ -96,7 +94,7 @@ class ProjectRepository extends BaseRepository $invoice->uses_inclusive_taxes = $project->company->settings->inclusive_taxes ?? false; $invoice->line_items = $lines; - + return $invoice; } diff --git a/app/Repositories/PurchaseOrderRepository.php b/app/Repositories/PurchaseOrderRepository.php index b200b4aeb6..a0de076e25 100644 --- a/app/Repositories/PurchaseOrderRepository.php +++ b/app/Repositories/PurchaseOrderRepository.php @@ -1,4 +1,5 @@ getMessage()); } diff --git a/app/Services/Bank/BankService.php b/app/Services/Bank/BankService.php index 9fa756e1a5..675435cd42 100644 --- a/app/Services/Bank/BankService.php +++ b/app/Services/Bank/BankService.php @@ -1,4 +1,5 @@ is_admin ? '' : 'AND clients.user_id = '.$this->user->id; - // AND invoices.balance > 0 + // AND invoices.balance > 0 return DB::select(" SELECT @@ -310,7 +311,7 @@ trait ChartQueries { $user_filter = $this->is_admin ? '' : 'AND clients.user_id = '.$this->user->id; -//AND invoices.balance > 0 + //AND invoices.balance > 0 return DB::select(" SELECT SUM(invoices.balance / COALESCE(NULLIF(invoices.exchange_rate, 0), 1)) as amount, @@ -531,6 +532,6 @@ trait ChartQueries 'start_date' => $start_date, 'end_date' => $end_date, ]); - + } } diff --git a/app/Services/Chart/ChartQueriesLegacy.php b/app/Services/Chart/ChartQueriesLegacy.php index 3c764979f1..bc1efb8696 100644 --- a/app/Services/Chart/ChartQueriesLegacy.php +++ b/app/Services/Chart/ChartQueriesLegacy.php @@ -1,4 +1,5 @@ client = Client::withTrashed()->where('id', $this->client->id)->lockForUpdate()->first(); // $this->client->balance += $amount; // $this->client->saveQuietly(); - // }, 2); + // }, 2); // } catch (\Throwable $throwable) { // if (DB::connection(config('database.default'))->transactionLevel() > 0) { diff --git a/app/Services/Client/Merge.php b/app/Services/Client/Merge.php index 73da8aee46..5fcb838d51 100644 --- a/app/Services/Client/Merge.php +++ b/app/Services/Client/Merge.php @@ -1,4 +1,5 @@ getInvitation(); - if(!$invitation) + if (!$invitation) { return null; + } $html = new HtmlEngine($invitation); @@ -69,13 +70,12 @@ class Statement $variables['values']['$end_date'] = $this->translateDate($this->options['end_date'], $this->client->date_format(), $this->client->locale()); $variables['labels']['$start_date_label'] = ctrans('texts.start_date'); $variables['labels']['$end_date_label'] = ctrans('texts.end_date'); - + $pdf = null; - try{ + try { $pdf = $this->templateStatement($variables); - } - catch(\Throwable $e){ + } catch (\Throwable $e) { nlog("wrapped"); nlog($e->getMessage()); } @@ -84,7 +84,7 @@ class Statement } - $variables['values']['$show_paid_stamp'] = 'none'; + $variables['values']['$show_paid_stamp'] = 'none'; $options = [ // 'client' => $this->entity->client, @@ -100,7 +100,7 @@ class Statement ]; $ps = new \App\Services\Pdf\PdfService($invitation, 'statement', array_merge($options, $this->options)); - + $ps->config = (new \App\Services\Pdf\PdfConfiguration($ps))->init(); $ps->config->pdf_variables = (array) $this->entity->company->settings->pdf_variables; @@ -110,7 +110,7 @@ class Statement $ps->designer = (new \App\Services\Pdf\PdfDesigner($ps))->build(); $ps->designer->buildFromPartials((array)$ps->config->design->design); - + $ps->builder = (new \App\Services\Pdf\PdfBuilder($ps))->build(); $pdf = $ps->getPdf(); @@ -153,8 +153,7 @@ class Statement ->where('company_id', $this->client->company_id) ->first(); - if($template) - { + if ($template) { $ts = $template->service(); $ts->addGlobal(['show_credits' => $this->options['show_credits_table']]); $ts->addGlobal(['show_aging' => $this->options['show_aging_table']]); @@ -199,12 +198,11 @@ class Statement { if ($this->getInvoices()->count() >= 1) { $this->entity = $this->getInvoices()->first(); //@phpstan-ignore-line - } - else { + } else { $this->entity = $this->client->invoices()->whereHas('invitations')->first(); } - if(\is_null($this->entity)){ + if (\is_null($this->entity)) { $settings = new \stdClass(); $settings->entity = \App\Models\Client::class; $settings->currency_id = '1'; @@ -214,7 +212,7 @@ class Statement $this->client->settings = $settings; $this->entity = \App\Models\Invoice::factory()->make(); //@phpstan-ignore-line - $this->entity->client =$this->client;//@phpstan-ignore-line + $this->entity->client = $this->client;//@phpstan-ignore-line $ii = \App\Models\InvoiceInvitation::factory()->make(); //@phpstan-ignore-line $ii->setRelation('invoice', $this->entity); //@phpstan-ignore-line $ii->setRelation('contact', $this->client->contacts->first()); //@phpstan-ignore-line @@ -231,7 +229,7 @@ class Statement // $this->entity->setRelation('invitations', \App\Models\InvoiceInvitation::factory()->make()); //@phpstan-ignore-line // $this->entity->setRelation('company', $this->client->company); // $this->entity->setRelation('user', $this->client->user); - + } return $this; @@ -410,16 +408,18 @@ class Statement */ protected function getInvitation() { - if($this->entity instanceof Invoice) { + if ($this->entity instanceof Invoice) { $invitation = $this->entity->invitations->first(); - - if($invitation) - return $invitation; - $invitation = $this->client->invoices()->whereHas('invitations')->first()->invitations->first(); - - if ($invitation) - return $invitation; + if ($invitation) { + return $invitation; + } + + $invitation = $this->client->invoices()->whereHas('invitations')->first()->invitations->first(); + + if ($invitation) { + return $invitation; + } } @@ -467,7 +467,7 @@ class Statement // $q->whereBetween('due_date', [$to, $from])->orWhereNull('due_date'); $query->where(function ($q) use ($to, $from) { $q->whereDate('due_date', '>=', now()->startOfDay()) - ->orWhere(function($q2) use ($to, $from) { + ->orWhere(function ($q2) use ($to, $from) { $q2->whereNull('due_date') ->whereBetween('date', [$to,$from]); }); @@ -541,7 +541,7 @@ class Statement if (! empty($this->client->getSetting('statement_design_id'))) { $id = $this->decodePrimaryKey($this->client->getSetting('statement_design_id')); - } + } return Design::withTrashed()->find($id); } diff --git a/app/Services/Company/CompanyService.php b/app/Services/Company/CompanyService.php index ac5fb0130e..d499fbf318 100644 --- a/app/Services/Company/CompanyService.php +++ b/app/Services/Company/CompanyService.php @@ -1,4 +1,5 @@ credit))->run(); + return (new LocationData($this->credit))->run(); } public function getCreditPdf($invitation) diff --git a/app/Services/Credit/GetCreditPdf.php b/app/Services/Credit/GetCreditPdf.php index 67c498c1d7..e18e546ba7 100644 --- a/app/Services/Credit/GetCreditPdf.php +++ b/app/Services/Credit/GetCreditPdf.php @@ -1,4 +1,5 @@ credit->service()->markSent()->save(); - $this->credit->invitations->load('contact.client.country', 'credit.client.country', 'credit.company')->each(function ($invitation) { + $this->credit->invitations->load('contact.client.country', 'credit.client.country', 'credit.company')->each(function ($invitation) { $mo = new \App\Services\Email\EmailObject(); $mo->entity_id = $this->credit->id; diff --git a/app/Services/Credit/TriggeredActions.php b/app/Services/Credit/TriggeredActions.php index 60d1a1b744..a2676b7f78 100644 --- a/app/Services/Credit/TriggeredActions.php +++ b/app/Services/Credit/TriggeredActions.php @@ -1,4 +1,5 @@ getIndividualEmailRoute(); - if(strlen($client_email) > 2) + if (strlen($client_email) > 2) { $this->setEmailRouting($client_email); + } $code = $this->getClientRoutingCode(); $identifier = false; @@ -615,7 +617,7 @@ class Mutator implements MutatorInterface $identifier = $this->getClientPublicIdentifier($code); } - $identifier = str_ireplace(["FR","BE"],"", $identifier); + $identifier = str_ireplace(["FR","BE"], "", $identifier); $identifier = preg_replace("/[^a-zA-Z0-9]/", "", $identifier); $this->setStorecoveMeta($this->buildRouting([ diff --git a/app/Services/EDocument/Gateway/Storecove/Storecove.php b/app/Services/EDocument/Gateway/Storecove/Storecove.php index 79b3a6cd21..43f78f0cb3 100644 --- a/app/Services/EDocument/Gateway/Storecove/Storecove.php +++ b/app/Services/EDocument/Gateway/Storecove/Storecove.php @@ -1,4 +1,5 @@ router->resolveRouting($data['country'], $data['classification']); - + return (strlen($data['vat_number'] ?? '') > 3 && $this->exists($data['vat_number'], $scheme)) ? [ 'status' => 'error', 'code' => 422, @@ -275,7 +276,7 @@ class Storecove ] ] ] : false; - + } public function setupLegalEntity(array $data): array|\Illuminate\Http\Client\Response @@ -429,7 +430,7 @@ class Storecove return $data; } - + $this->deleteIdentifier($legal_entity_id); return $r; diff --git a/app/Services/EDocument/Gateway/Storecove/StorecoveAdapter.php b/app/Services/EDocument/Gateway/Storecove/StorecoveAdapter.php index 8134eaed9b..b005c91f5b 100644 --- a/app/Services/EDocument/Gateway/Storecove/StorecoveAdapter.php +++ b/app/Services/EDocument/Gateway/Storecove/StorecoveAdapter.php @@ -1,4 +1,5 @@ storecove->checkNetworkStatus($data)){ + if ($already_registered = $this->storecove->checkNetworkStatus($data)) { return $already_registered; } @@ -188,7 +189,7 @@ class StorecoveProxy ]; if ($response->json()) { - $body = gettype($response->json()) === 'string' + $body = gettype($response->json()) === 'string' ? \json_decode($response->json(), associative: true) : $response->json(); diff --git a/app/Services/EDocument/Gateway/Storecove/StorecoveRouter.php b/app/Services/EDocument/Gateway/Storecove/StorecoveRouter.php index 632389e703..ea93e22185 100644 --- a/app/Services/EDocument/Gateway/Storecove/StorecoveRouter.php +++ b/app/Services/EDocument/Gateway/Storecove/StorecoveRouter.php @@ -1,4 +1,5 @@ save($fields, $expense, Ninja::eventVars()); - foreach($storecove_invoice->getAttachments() ?? [] as $attachment){ - + foreach ($storecove_invoice->getAttachments() ?? [] as $attachment) { + $document = \App\Utils\TempFile::UploadedFileFromBase64($attachment->getDocument(), $attachment->getFilename(), $attachment->getMimeType()); $this->saveDocument($document, $expense); diff --git a/app/Services/EDocument/Imports/MindeeEDocument.php b/app/Services/EDocument/Imports/MindeeEDocument.php index 02561180fe..1c15eedd28 100644 --- a/app/Services/EDocument/Imports/MindeeEDocument.php +++ b/app/Services/EDocument/Imports/MindeeEDocument.php @@ -1,4 +1,5 @@ save($data, $expense); - + if ($expense->company->account->hasFeature(\App\Models\Account::FEATURE_DOCUMENTS)) { foreach ($attachments as $attachment) { @@ -193,7 +194,7 @@ class UblEDocument extends AbstractService $a = data_get($attachment, 'Attachment.EmbeddedDocumentBinaryObject', false); - if(!$a) { + if (!$a) { continue; } @@ -201,7 +202,7 @@ class UblEDocument extends AbstractService $mime_type = data_get($a, '@mimeCode', "application/pdf"); $document_data = data_get($a, '#', false); - if($document_data) { + if ($document_data) { $document = \App\Utils\TempFile::UploadedFileFromBase64($document_data, $doc_name, $mime_type); $this->saveDocument($document, $expense); } diff --git a/app/Services/EDocument/Imports/ZugferdEDocument.php b/app/Services/EDocument/Imports/ZugferdEDocument.php index f288a57e10..1b3624aa13 100644 --- a/app/Services/EDocument/Imports/ZugferdEDocument.php +++ b/app/Services/EDocument/Imports/ZugferdEDocument.php @@ -1,4 +1,5 @@ entity::withTrashed()->find($this->id); - if(isset($model->backup->guid) && is_string($model->backup->guid)){ + if (isset($model->backup->guid) && is_string($model->backup->guid)) { nlog("already sent!"); return; } @@ -93,7 +94,7 @@ class SendEDocument implements ShouldQueue 'account_key' => $model->company->account->key, 'e_invoicing_token' => $model->company->account->e_invoicing_token, ]; - + //Self Hosted Sending Code Path if (Ninja::isSelfHost() && ($model instanceof Invoice) && $model->company->peppolSendingEnabled()) { @@ -101,7 +102,7 @@ class SendEDocument implements ShouldQueue ->post(config('ninja.hosted_ninja_url')."/api/einvoice/submission", $payload); if ($r->successful()) { - + if ($r->hasHeader('X-EINVOICE-QUOTA')) { $account = $model->company->account; $account->e_invoice_quota = (int) $r->header('X-EINVOICE-QUOTA'); @@ -215,7 +216,7 @@ class SendEDocument implements ShouldQueue $activity->save(); - if($activity_id == Activity::EINVOICE_DELIVERY_SUCCESS){ + if ($activity_id == Activity::EINVOICE_DELIVERY_SUCCESS) { $backup = ($model->backup && is_object($model->backup)) ? $model->backup : new \stdClass(); $backup->guid = str_replace('"', '', $notes); diff --git a/app/Services/EDocument/Standards/FacturaEInvoice.php b/app/Services/EDocument/Standards/FacturaEInvoice.php index 3b62a19a7b..4cf2fa99fa 100644 --- a/app/Services/EDocument/Standards/FacturaEInvoice.php +++ b/app/Services/EDocument/Standards/FacturaEInvoice.php @@ -1,4 +1,5 @@ PayeeFinancialAccount->Name ?? ''; $bic = $pm->PayeeFinancialAccount->FinancialInstitutionBranch->FinancialInstitution->ID->value ?? ''; $typecode = $pm->PaymentMeansCode->value; - + $this->fac->addPayment(new FacturaePayment([ "method" => FacturaePayment::TYPE_TRANSFER, @@ -372,7 +373,7 @@ class FacturaEInvoice extends AbstractService // } - + /** * buildItems * diff --git a/app/Services/EDocument/Standards/FatturaPA.php b/app/Services/EDocument/Standards/FatturaPA.php index 8073b48b44..b177afcffe 100644 --- a/app/Services/EDocument/Standards/FatturaPA.php +++ b/app/Services/EDocument/Standards/FatturaPA.php @@ -1,4 +1,5 @@ p_invoice = $this->e->decode('Peppol', json_encode($invoice), 'json'); return $this; @@ -409,14 +410,14 @@ class Peppol extends AbstractService private function setOrderReference(): self { - $this->p_invoice->BuyerReference = $this->invoice->po_number ?? ''; + $this->p_invoice->BuyerReference = $this->invoice->po_number ?? ''; - $order_reference = new OrderReference(); - $id = new ID(); - $id->value = strlen($this->invoice->po_number ?? '') > 1 ? $this->invoice->po_number : $this->invoice->number; + $order_reference = new OrderReference(); + $id = new ID(); + $id->value = strlen($this->invoice->po_number ?? '') > 1 ? $this->invoice->po_number : $this->invoice->number; - $order_reference->ID = $id; - $this->p_invoice->OrderReference = $order_reference; + $order_reference->ID = $id; + $this->p_invoice->OrderReference = $order_reference; return $this; @@ -431,7 +432,7 @@ class Peppol extends AbstractService $mime_code = 'application/pdf'; $adr = new \InvoiceNinja\EInvoice\Models\Peppol\DocumentReferenceType\AdditionalDocumentReference(); - + // Set ID $id = new \InvoiceNinja\EInvoice\Models\Peppol\IdentifierType\ID(); $id->value = $filename; @@ -439,20 +440,20 @@ class Peppol extends AbstractService // Create EmbeddedDocumentBinaryObject $attachment = new \InvoiceNinja\EInvoice\Models\Peppol\AttachmentType\Attachment(); - + $binary = new \InvoiceNinja\EInvoice\Models\Peppol\EmbeddedDocumentBinaryObjectType\EmbeddedDocumentBinaryObject(); $binary->value = base64_encode($pdf); $binary->mimeCode = $mime_code; $binary->filename = $filename; $attachment->EmbeddedDocumentBinaryObject = $binary; - + $adr->Attachment = $attachment; // Add to invoice if (!isset($this->p_invoice->AdditionalDocumentReference)) { $this->p_invoice->AdditionalDocumentReference = []; } - + $this->p_invoice->AdditionalDocumentReference[] = $adr; return $this; @@ -628,11 +629,11 @@ class Peppol extends AbstractService $am->amount = number_format($this->calc->getTotalDiscount(), 2, '.', ''); $lmt->AllowanceTotalAmount = $am; - $cta = new \InvoiceNinja\EInvoice\Models\Peppol\AmountType\ChargeTotalAmount(); + $cta = new \InvoiceNinja\EInvoice\Models\Peppol\AmountType\ChargeTotalAmount(); $cta->currencyID = $this->invoice->client->currency()->code; $cta->amount = number_format($this->calc->getTotalSurcharges(), 2, '.', ''); $lmt->ChargeTotalAmount = $cta; - + return $lmt; } @@ -861,7 +862,7 @@ class Peppol extends AbstractService $lea = new LineExtensionAmount(); $lea->currencyID = $this->invoice->client->currency()->code; - $lea->amount = $this->invoice->uses_inclusive_taxes ? round($item->line_total - $this->calcInclusiveLineTax($item->tax_rate1, $item->line_total),2) : round($item->line_total,2); + $lea->amount = $this->invoice->uses_inclusive_taxes ? round($item->line_total - $this->calcInclusiveLineTax($item->tax_rate1, $item->line_total), 2) : round($item->line_total, 2); $line->LineExtensionAmount = $lea; $line->Item = $_item; @@ -1130,14 +1131,14 @@ class Peppol extends AbstractService //@todo if we have an exact GLN/routing number we should update this, otherwise Storecove will proxy and update on transit $id = new \InvoiceNinja\EInvoice\Models\Peppol\IdentifierType\EndpointID(); - $id->value = $this->invoice->client->routing_id - ?? preg_replace("/[^a-zA-Z0-9]/", "", $this->invoice->client->vat_number) + $id->value = $this->invoice->client->routing_id + ?? preg_replace("/[^a-zA-Z0-9]/", "", $this->invoice->client->vat_number) ?? preg_replace("/[^a-zA-Z0-9]/", "", $this->invoice->client->id_number) ?? 'fallback1234'; - + $id->schemeID = $this->resolveScheme(true); $party->EndpointID = $id; - + $party->PartyName[] = $party_name; $locationData = $this->invoice->service()->location(); @@ -1196,7 +1197,7 @@ class Peppol extends AbstractService } $address->PostalZone = $locationData['shipping_postal_code']; - + $country = new Country(); $ic = new IdentificationCode(); @@ -1296,8 +1297,8 @@ class Peppol extends AbstractService } } - if(isset($this->invoice->e_invoice->Invoice)) { - foreach(get_object_vars($this->invoice->e_invoice->Invoice) as $prop => $value) { + if (isset($this->invoice->e_invoice->Invoice)) { + foreach (get_object_vars($this->invoice->e_invoice->Invoice) as $prop => $value) { $this->p_invoice->{$prop} = $value; } } @@ -1328,7 +1329,7 @@ class Peppol extends AbstractService } - if(!isset($this->p_invoice->InvoicePeriod)) { + if (!isset($this->p_invoice->InvoicePeriod)) { $ip = new InvoicePeriod(); $ip->StartDate = new \DateTime($this->invoice->date); $ip->EndDate = new \DateTime($this->invoice->due_date ?? $this->invoice->date); @@ -1337,42 +1338,40 @@ class Peppol extends AbstractService return $this; } - + /** * standardPeppolRules * * Transform UBL => Peppol rules - * + * * 1. FinancialInstitutionBranch - remove * 2. FinancialInstituion - remove - * + * * @return self */ private function standardPeppolRules(): self { - foreach($this->p_invoice->PaymentMeans as &$pm) - { + foreach ($this->p_invoice->PaymentMeans as &$pm) { unset($pm->PayeeFinancialAccount->FinancialInstitutionBranch); } unset($pm); return $this; } - + /** * setPaymentTerms * * If payment terms are defined, we should include these * on the invoice. - * + * * @return self */ private function setPaymentTerms(): self { $terms_string = $this->invoice->client->getSetting('payment_terms'); - if(strlen($terms_string) > 1) - { + if (strlen($terms_string) > 1) { $terms = new \InvoiceNinja\EInvoice\Models\Peppol\PaymentTermsType\PaymentTerms(); $terms->Note = trans('texts.count_days', ['count' => $terms_string]); @@ -1567,7 +1566,7 @@ class Peppol extends AbstractService { $vat_number = $is_client ? preg_replace("/[^a-zA-Z0-9]/", "", $this->invoice->client->vat_number ?? '') : preg_replace("/[^a-zA-Z0-9]/", "", $this->invoice->company->settings->vat_number ?? ''); - $tax_number = $is_client ? preg_replace("/[^a-zA-Z0-9]/", "", $this->invoice->client->id_number ?? ''): preg_replace("/[^a-zA-Z0-9]/", "", $this->invoice->company->settings->id_number ?? ''); + $tax_number = $is_client ? preg_replace("/[^a-zA-Z0-9]/", "", $this->invoice->client->id_number ?? '') : preg_replace("/[^a-zA-Z0-9]/", "", $this->invoice->company->settings->id_number ?? ''); $country_code = $is_client ? $this->invoice->client->country->iso_3166_2 : $this->invoice->company->country()->iso_3166_2; return '0037'; diff --git a/app/Services/EDocument/Standards/Peppol/BaseCountry.php b/app/Services/EDocument/Standards/Peppol/BaseCountry.php index d0b4067a72..a9ecb22e73 100644 --- a/app/Services/EDocument/Standards/Peppol/BaseCountry.php +++ b/app/Services/EDocument/Standards/Peppol/BaseCountry.php @@ -1,4 +1,5 @@ run()->toXml(); - + if (count($p->getErrors()) >= 1) { foreach ($p->getErrors() as $error) { @@ -207,18 +208,19 @@ class EntityLevel if (!in_array($client->classification, ['government', 'individual']) && in_array($client->country->iso_3166_2, $this->eu_country_codes) && !$this->validString($client->vat_number)) { $errors[] = ['field' => 'vat_number', 'label' => ctrans("texts.vat_number")]; } - + //Primary contact email is present. - if($client->present()->email() == 'No Email Set'){ + if ($client->present()->email() == 'No Email Set') { $errors[] = ['field' => 'email', 'label' => ctrans("texts.email")]; } $delivery_network_supported = $client->checkDeliveryNetwork(); - if(is_string($delivery_network_supported)) + if (is_string($delivery_network_supported)) { $errors[] = ['field' => ctrans("texts.country"), 'label' => $delivery_network_supported]; + } + - return $errors; @@ -334,24 +336,24 @@ class EntityLevel // B2C, under threshold, no Company VAT Registerd - must charge origin country VAT if ($is_b2c && !$is_over_threshold && strlen($client->company->settings->vat_number) < 2) { - + } elseif ($is_b2c) { if ($is_over_threshold) { // B2C over threshold - need destination VAT number - if (!isset($client->company->tax_data->regions->EU->subregions->{$client_country_code}->vat_number)) { + if (!isset($client->company->tax_data->regions->EU->subregions->{$client_country_code}->vat_number)) { $this->errors['invoice'][] = "Tax Nexus is client country ({$client_country_code}) - however VAT number not present for this region."; } - } - + } + } elseif ($is_over_threshold && !in_array($company_country_code, $eu_countries)) { - - } - + + } + } return $this; } - + } diff --git a/app/Services/EDocument/Standards/Validation/Peppol/InvoiceLevel.php b/app/Services/EDocument/Standards/Validation/Peppol/InvoiceLevel.php index 3dc6a3bb7f..beb5ab6590 100644 --- a/app/Services/EDocument/Standards/Validation/Peppol/InvoiceLevel.php +++ b/app/Services/EDocument/Standards/Validation/Peppol/InvoiceLevel.php @@ -17,9 +17,8 @@ use InvoiceNinja\EInvoice\Models\Peppol\PeriodType\InvoicePeriod; class InvoiceLevel { - - /** @var InvoicePeriod[] */ - #[SerializedName('cac:InvoicePeriod')] - public array $InvoicePeriod; + /** @var InvoicePeriod[] */ + #[SerializedName('cac:InvoicePeriod')] + public array $InvoicePeriod; } diff --git a/app/Services/EDocument/Standards/Validation/XsltDocumentValidator.php b/app/Services/EDocument/Standards/Validation/XsltDocumentValidator.php index 55443592ca..7758eb2b62 100644 --- a/app/Services/EDocument/Standards/Validation/XsltDocumentValidator.php +++ b/app/Services/EDocument/Standards/Validation/XsltDocumentValidator.php @@ -1,4 +1,5 @@ getTaxType($item["tax_id"] ?? '2') : $this->tax_code; - if($this->document->custom_surcharge1 > 0){ + if ($this->document->custom_surcharge1 > 0) { $surcharge = $this->document->uses_inclusive_taxes ? ($this->document->custom_surcharge1 / (1 + ($item["tax_rate"] / 100))) : $this->document->custom_surcharge1; $this->xdocument->addDocumentAllowanceCharge($surcharge, true, $tax_code, "VAT", $item["tax_rate"]); } - if($this->document->custom_surcharge2 > 0){ + if ($this->document->custom_surcharge2 > 0) { $surcharge = $this->document->uses_inclusive_taxes ? ($this->document->custom_surcharge2 / (1 + ($item["tax_rate"] / 100))) : $this->document->custom_surcharge2; $this->xdocument->addDocumentAllowanceCharge($surcharge, true, $tax_code, "VAT", $item["tax_rate"]); } - if($this->document->custom_surcharge3 > 0){ + if ($this->document->custom_surcharge3 > 0) { $surcharge = $this->document->uses_inclusive_taxes ? ($this->document->custom_surcharge3 / (1 + ($item["tax_rate"] / 100))) : $this->document->custom_surcharge3; $this->xdocument->addDocumentAllowanceCharge($surcharge, true, $tax_code, "VAT", $item["tax_rate"]); } - if($this->document->custom_surcharge4 > 0){ - $surcharge = $this->document->uses_inclusive_taxes ? ($this->document->custom_surcharge4 / (1 + ($item["tax_rate"] / 100))) : $this->document->custom_surcharge4; + if ($this->document->custom_surcharge4 > 0) { + $surcharge = $this->document->uses_inclusive_taxes ? ($this->document->custom_surcharge4 / (1 + ($item["tax_rate"] / 100))) : $this->document->custom_surcharge4; $this->xdocument->addDocumentAllowanceCharge($surcharge, true, $tax_code, "VAT", $item["tax_rate"]); } return $this; } - + /** * setDocumentTaxes - * + * * VATEX-EU-143 - Article 143 - Exemptions on importation * VATEX-EU-146 - Article 146 - Exemptions on exportation * VATEX-EU-148 - Article 148 - Exemptions for international transport @@ -148,12 +148,12 @@ class ZugferdEDocument extends AbstractService private function setDocumentTaxes(): self { if ($this->document->total_taxes == 0) { - + $base_amount = 0; $tax_amount = 0; $tax_rate = 0; - if($this->tax_code == ZugferdDutyTaxFeeCategories::VAT_REVERSE_CHARGE){ //reverse charge + if ($this->tax_code == ZugferdDutyTaxFeeCategories::VAT_REVERSE_CHARGE) { //reverse charge $base_amount = $this->document->amount; } @@ -167,7 +167,7 @@ class ZugferdEDocument extends AbstractService $this->exemption_reason_code ); - + if ($this->calc->getTotalDiscount() > 0) { $this->xdocument->addDocumentAllowanceCharge( @@ -189,7 +189,7 @@ class ZugferdEDocument extends AbstractService $taxable_amount = $this->document->amount - $total_tax; //taxable amount and net subtotal should be the same - $adjustment = round($taxable_amount-$net_subtotal,2); + $adjustment = round($taxable_amount - $net_subtotal, 2); // Process each tax rate group foreach ($tax_map as $item) { @@ -198,14 +198,14 @@ class ZugferdEDocument extends AbstractService $this->xdocument->addDocumentTax( $tax_type, "VAT", - $item["base_amount"]+$adjustment, // Taxable amount after discount + $item["base_amount"] + $adjustment, // Taxable amount after discount $item["total"], $item["tax_rate"], $tax_type == ZugferdDutyTaxFeeCategories::VAT_EXEMPT_FOR_EEA_INTRACOMMUNITY_SUPPLY_OF_GOODS_AND_SERVICES ? ctrans('texts.intracommunity_tax_info') : '' ); - + if ($this->calc->getTotalDiscount() > 0) { $ratio = $item["base_amount"] / $net_subtotal; @@ -259,7 +259,7 @@ class ZugferdEDocument extends AbstractService $item = $this->document->line_items[0] ?? null; - if(is_null($item)){ + if (is_null($item)) { return $this; } @@ -275,8 +275,7 @@ class ZugferdEDocument extends AbstractService } elseif ($item->tax_id == '10') { //intra-community $this->tax_code = ZugferdDutyTaxFeeCategories::VAT_EXEMPT_FOR_EEA_INTRACOMMUNITY_SUPPLY_OF_GOODS_AND_SERVICES; $this->exemption_reason_code = "VATEX-EU-IC"; - } - else { + } else { $this->tax_code = ZugferdDutyTaxFeeCategories::EXEMPT_FROM_TAX; $this->exemption_reason_code = "VATNOTREG"; } @@ -288,12 +287,12 @@ class ZugferdEDocument extends AbstractService private function setDocumentSummation(): self { $document_discount = $this->calc->getTotalDiscount(); - $total_tax = round($this->calc->getTotalTaxes(),2); + $total_tax = round($this->calc->getTotalTaxes(), 2); $taxable_amount = $this->document->amount - $total_tax; $base_taxable_amount = $this->calc->getTaxMap()->sum('base_amount'); $subtotal = $this->document->uses_inclusive_taxes ? ($this->calc->getTotal() - $total_tax - $this->calc->getTotalNetSurcharges() + $this->calc->getTotalDiscount()) : ($this->calc->getSubTotal()); - + // nlog([ // $this->document->amount, // Total amount with VAT // $this->document->balance, // Amount due @@ -304,9 +303,9 @@ class ZugferdEDocument extends AbstractService // $total_tax, // Total tax amount // 0, // // round($this->document->amount - ($base_taxable_amount+$total_tax),2), // Total prepaid amount - // $this->document->amount - $this->document->balance, + // $this->document->amount - $this->document->balance, // ]); - + $this->xdocument->setDocumentSummation( $this->document->amount, // Total amount with VAT $this->document->balance, // Amount due @@ -314,40 +313,40 @@ class ZugferdEDocument extends AbstractService $this->document->uses_inclusive_taxes ? $this->calc->getTotalNetSurcharges() : $this->calc->getTotalSurcharges(), // Total charges $document_discount, // Total allowances $taxable_amount, // Tax basis total (net) - round($total_tax,2), // Total tax amount - 0, + round($total_tax, 2), // Total tax amount + 0, // round($this->document->amount - ($base_taxable_amount+$total_tax),2), // Total rounding amount $this->document->amount - $this->document->balance // Amount already paid ); return $this; } - + private function setLineItems(): self { foreach ($this->document->line_items as $index => $item) { /** @var InvoiceItem $item **/ - - $position_id = (string) ($index+1); + + $position_id = (string) ($index + 1); // 1. Start new position and set basic details $this->xdocument->addNewPosition($position_id) ->setDocumentPositionProductDetails( - strlen($item->product_key ?? '') >= 1 ? $item->product_key : "no product name defined", + strlen($item->product_key ?? '') >= 1 ? $item->product_key : "no product name defined", $item->notes ) ->setDocumentPositionQuantity( - $item->quantity, + $item->quantity, $item->type_id == 2 ? "HUR" : "H87" ) ->setDocumentPositionNetPrice( $this->document->uses_inclusive_taxes ? $item->net_cost : $item->cost ); - + // 2. ALWAYS add tax information (even if zero) - if(strlen($item->tax_name1) > 1) { + if (strlen($item->tax_name1) > 1) { $this->xdocument->addDocumentPositionTax( - $this->getTaxType($item->tax_id ?? '2'), - 'VAT', + $this->getTaxType($item->tax_id ?? '2'), + 'VAT', $item->tax_rate1 ); } else { @@ -362,15 +361,15 @@ class ZugferdEDocument extends AbstractService $line_discount = 0; // 3. Add allowances/charges (discounts) if any - if($item->discount > 0) { + if ($item->discount > 0) { $line_discount = $this->calculateTotalItemDiscountAmount($item); $this->xdocument->addDocumentPositionGrossPriceAllowanceCharge( - abs($line_discount), + abs($line_discount), false ); } // 4. Finally add monetary summation - $this->xdocument->setDocumentPositionLineSummation($this->document->uses_inclusive_taxes ? ($item->line_total-$item->tax_amount) : $item->line_total); + $this->xdocument->setDocumentPositionLineSummation($this->document->uses_inclusive_taxes ? ($item->line_total - $item->tax_amount) : $item->line_total); } return $this; @@ -388,10 +387,11 @@ class ZugferdEDocument extends AbstractService private function setCompanyTaxRegistration(): array { - if (str_contains($this->company->getSetting('vat_number'), "/")) + if (str_contains($this->company->getSetting('vat_number'), "/")) { return ["FC", $this->company->getSetting('vat_number')]; - - return ["VA", $this->company->getSetting('vat_number')]; + } + + return ["VA", $this->company->getSetting('vat_number')]; } private function setPaymentMeans(): self @@ -484,13 +484,13 @@ class ZugferdEDocument extends AbstractService ->setDocumentBuyerCommunication("EM", $this->client->present()->email()) ->addDocumentPaymentTerm(ctrans("texts.xinvoice_payable", ['payeddue' => date_create($this->document->date ?? now()->format('Y-m-d'))->diff(date_create($this->document->due_date ?? now()->format('Y-m-d')))->format("%d"), 'paydate' => $this->document->due_date])); - if(strlen($this->client->vat_number ?? '') > 1) { + if (strlen($this->client->vat_number ?? '') > 1) { $this->xdocument->addDocumentBuyerTaxRegistration($this->getDocumentLevelTaxRegistration(), $this->client->vat_number); } return $this; } - + private function setRoutingNumber(): self { if (empty($this->client->routing_id)) { diff --git a/app/Services/EDocument/Standards/ZugferdEDokument.php b/app/Services/EDocument/Standards/ZugferdEDokument.php index 327ee771b8..2c0fa4fb8c 100644 --- a/app/Services/EDocument/Standards/ZugferdEDokument.php +++ b/app/Services/EDocument/Standards/ZugferdEDokument.php @@ -1,4 +1,5 @@ shipping_address1) && $client->shipping_country) { $this->xdocument->setDocumentShipToAddress($client->shipping_address1, $client->shipping_address2, "", $client->shipping_postal_code, $client->shipping_city, $client->shipping_country->iso_3166_2, $client->shipping_state); } - + $this->injectPaymentMeans($company); if (str_contains($company->getSetting('vat_number'), "/")) { @@ -262,19 +263,19 @@ use horstoeko\zugferd\ZugferdProfiles; return $this; } - + /** - * + * * Expanded functionality to allow injecting UBL Payment Means * into the document - * + * * @return self */ private function injectPaymentMeans(Company $company): self { /**Check if the e_invoice object is populated */ - if(isset($company->e_invoice->Invoice->PaymentMeans) && ($pm = $company->e_invoice->Invoice->PaymentMeans[0] ?? false)){ + if (isset($company->e_invoice->Invoice->PaymentMeans) && ($pm = $company->e_invoice->Invoice->PaymentMeans[0] ?? false)) { switch ($pm->PaymentMeansCode->value ?? false) { case '30': @@ -287,7 +288,7 @@ use horstoeko\zugferd\ZugferdProfiles; $this->xdocument->addDocumentPaymentMean(typeCode: $typecode, payeeIban: $iban, payeeAccountName: $name, payeeBic: $bic); return $this; - + default: # code... break; diff --git a/app/Services/Email/AdminEmail.php b/app/Services/Email/AdminEmail.php index 693f529731..d8cce05bde 100644 --- a/app/Services/Email/AdminEmail.php +++ b/app/Services/Email/AdminEmail.php @@ -1,4 +1,5 @@ Message property using the following */ if ($e instanceof PostmarkException) { //postmark specific failure - + // Try to decode the JSON response if present try { $response = json_decode($e->getMessage(), true); @@ -614,14 +615,14 @@ class Email implements ShouldQueue $this->mailer = 'smtp'; $this->configureSmtpMailer(); return $this; - default: + default: $this->mailer = config('mail.default'); break; } - + $this->mailer = config('mail.default'); - + return $this; } @@ -914,11 +915,11 @@ class Email implements ShouldQueue $job_failure = null; try { - if($this->email_object->invitation){ + if ($this->email_object->invitation) { $this->email_object->invitation->email_error = substr($errors, 0, 150); $this->email_object->invitation->save(); } - }catch(\Throwable $e){ + } catch (\Throwable $e) { nlog("Problem saving email error: {$e->getMessage()}"); } } diff --git a/app/Services/Email/EmailDefaults.php b/app/Services/Email/EmailDefaults.php index 24d9f0b3b6..2ed49732c4 100644 --- a/app/Services/Email/EmailDefaults.php +++ b/app/Services/Email/EmailDefaults.php @@ -1,4 +1,5 @@ company)) + if (empty($this->company)) { throw new \Exception('invalid use of inbound mail engine: no company selected'); + } if ($this->isInvalidOrBlocked($email->from, $email->to)) { return; @@ -174,8 +176,9 @@ class InboundMailEngine // MAIN-PROCESSORS protected function createExpenses(InboundMail $email) { - if (empty($this->company)) + if (empty($this->company)) { throw new \Exception('invalid use of inbound mail engine: no company selected'); + } // Skipping executions: will not result in not saving Metadata to prevent usage of these conditions, to spam if (!$this->company->expense_mailbox_active) { diff --git a/app/Services/Invoice/AddGatewayFee.php b/app/Services/Invoice/AddGatewayFee.php index 5e1371ffbf..36121f83cd 100644 --- a/app/Services/Invoice/AddGatewayFee.php +++ b/app/Services/Invoice/AddGatewayFee.php @@ -1,4 +1,5 @@ invoice->number.' with error '.$e->getMessage()); event(new InvoiceAutoBillFailed($this->invoice, $this->invoice->company, Ninja::eventVars(), $e->getMessage())); - + $this->invoice->increment('auto_bill_tries', 1); $this->invoice->refresh(); diff --git a/app/Services/Invoice/CreateInvitations.php b/app/Services/Invoice/CreateInvitations.php index 83b86d5c45..c6f14e61a7 100644 --- a/app/Services/Invoice/CreateInvitations.php +++ b/app/Services/Invoice/CreateInvitations.php @@ -1,4 +1,5 @@ invoice->line_items = collect($this->invoice->line_items) ->map(function ($item) use ($payment_hash_string) { if ($item->type_id == '3' && (($item->unit_code ?? '') == $payment_hash_string)) { @@ -389,10 +390,10 @@ class InvoiceService return $item; })->toArray(); - - $this->deleteEInvoice(); - return $this; + $this->deleteEInvoice(); + + return $this; } @@ -440,7 +441,7 @@ class InvoiceService $this->invoice->invitations->each(function ($invitation) { try { Storage::disk(config('filesystems.default'))->delete($this->invoice->client->e_document_filepath($invitation).$this->invoice->getFileName("xml")); - + if (Ninja::isHosted()) { Storage::disk('public')->delete($this->invoice->client->e_document_filepath($invitation).$this->invoice->getFileName("xml")); } @@ -620,7 +621,7 @@ class InvoiceService public function location(): array { - return (new LocationData($this->invoice))->run(); + return (new LocationData($this->invoice))->run(); } public function workFlow() diff --git a/app/Services/Invoice/LocationData.php b/app/Services/Invoice/LocationData.php index c65ba1684c..6fb3cd969a 100644 --- a/app/Services/Invoice/LocationData.php +++ b/app/Services/Invoice/LocationData.php @@ -1,4 +1,5 @@ entity->location) { $this->businessLocation = null; $this->shippingLocation = null; - } - elseif($this->entity->location->is_shipping_location) { + } elseif ($this->entity->location->is_shipping_location) { $this->shippingLocation = $this->entity->location; $this->businessLocation = null; } else { @@ -61,7 +61,7 @@ class LocationData extends AbstractService 'country' => $this->getBusinessCountry(), 'country_name' => $this->getBusinessCountryName(), 'country_code' => $this->getBusinessCountryCode(), - + // Shipping Address (from shipping location or client default) 'shipping_location_name' => $this->getShippingLocationName(), 'shipping_address' => $this->getShippingAddress(), @@ -105,7 +105,7 @@ class LocationData extends AbstractService } return $this->entity->client->shipping_country ?? $this->entity->company->country(); - + } public function getCityState() @@ -163,9 +163,9 @@ class LocationData extends AbstractService } } - private function getShippingAddress(): string + private function getShippingAddress(): string { - + $str = ' '; if ($address1 = $this->getShippingAddress1()) { @@ -184,7 +184,7 @@ class LocationData extends AbstractService return $str; } - + private function getBusinessAddress1(): string { if ($this->businessLocation) { diff --git a/app/Services/Invoice/MarkInvoiceDeleted.php b/app/Services/Invoice/MarkInvoiceDeleted.php index 259f328bc3..ca0e80ffcf 100644 --- a/app/Services/Invoice/MarkInvoiceDeleted.php +++ b/app/Services/Invoice/MarkInvoiceDeleted.php @@ -1,4 +1,5 @@ invoice->company->track_inventory) { (new AdjustProductInventory($this->invoice->company, $this->invoice, []))->handleDeletedInvoice(); } @@ -66,11 +67,11 @@ class MarkInvoiceDeleted extends AbstractService { $ba = $this->balance_adjustment * -1; - $aa = $this->adjustment_amount * -1; + $aa = $this->adjustment_amount * -1; $cb = $this->invoice->client->balance; nlog("APB => {$this->invoice->number} - BA={$ba} - AA={$aa} - CB={$cb}"); - + $this->invoice ->client ->service() @@ -139,17 +140,17 @@ class MarkInvoiceDeleted extends AbstractService $this->balance_adjustment = $this->invoice->balance; - $pre_count = count((array)$this->invoice->line_items); + $pre_count = count((array)$this->invoice->line_items); - $items = collect((array)$this->invoice->line_items) - ->filter(function ($item) { - return $item->type_id != '3'; - })->toArray(); + $items = collect((array)$this->invoice->line_items) + ->filter(function ($item) { + return $item->type_id != '3'; + })->toArray(); - if(count($items) < $pre_count) { - $this->invoice->line_items = array_values($items); - $this->invoice = $this->invoice->calc()->getInvoice(); - } + if (count($items) < $pre_count) { + $this->invoice->line_items = array_values($items); + $this->invoice = $this->invoice->calc()->getInvoice(); + } return $this; } @@ -206,10 +207,10 @@ class MarkInvoiceDeleted extends AbstractService ->where('amount', $this->invoice->amount) ->first(); - if($pp) { + if ($pp) { $pp->delete(); } - + }); return $this; diff --git a/app/Services/Invoice/MarkPaid.php b/app/Services/Invoice/MarkPaid.php index 4f2c5a52c4..7a4a8d8456 100644 --- a/app/Services/Invoice/MarkPaid.php +++ b/app/Services/Invoice/MarkPaid.php @@ -1,4 +1,5 @@ invoice->service()->markSent()->save(); - $this->invoice->invitations->filter(function ($invitation){ + $this->invoice->invitations->filter(function ($invitation) { return (! $invitation->contact->trashed() && $invitation->contact->email && !$invitation->contact->is_locked); - })->each(function ($invitation) use($base_template) { - - $mo = new EmailObject(); - $mo->entity_id = $invitation->invoice_id; - $mo->template = $this->reminder_template; - $mo->email_template_body = $this->reminder_template; - $mo->email_template_subject = str_replace("template", "subject", $this->reminder_template); + })->each(function ($invitation) use ($base_template) { - $mo->entity_class = get_class($invitation->invoice); - $mo->invitation_id = $invitation->id; - $mo->client_id = $invitation->contact->client_id ?? null; - $mo->vendor_id = $invitation->contact->vendor_id ?? null; + $mo = new EmailObject(); + $mo->entity_id = $invitation->invoice_id; + $mo->template = $this->reminder_template; + $mo->email_template_body = $this->reminder_template; + $mo->email_template_subject = str_replace("template", "subject", $this->reminder_template); - Email::dispatch($mo, $invitation->company); + $mo->entity_class = get_class($invitation->invoice); + $mo->invitation_id = $invitation->id; + $mo->client_id = $invitation->contact->client_id ?? null; + $mo->vendor_id = $invitation->contact->vendor_id ?? null; - $this->invoice->entityEmailEvent($invitation, $base_template, $base_template); + Email::dispatch($mo, $invitation->company); + + $this->invoice->entityEmailEvent($invitation, $base_template, $base_template); }); diff --git a/app/Services/Invoice/TriggeredActions.php b/app/Services/Invoice/TriggeredActions.php index 0721a6db03..3c2f45bd86 100644 --- a/app/Services/Invoice/TriggeredActions.php +++ b/app/Services/Invoice/TriggeredActions.php @@ -1,4 +1,5 @@ invoice->service()->autoBill(); } catch (\Exception $e) { nlog("Exception:: TriggeredActions::" . $e->getMessage()); - } + } } if ($this->request->has('paid') && $this->request->input('paid') == 'true') { @@ -81,12 +82,12 @@ class TriggeredActions extends AbstractService $company->save(); } - if($this->request->has('retry_e_send') && $this->request->input('retry_e_send') == 'true' && !isset($this->invoice->backup->guid) && $this->invoice->client->peppolSendingEnabled()) { + if ($this->request->has('retry_e_send') && $this->request->input('retry_e_send') == 'true' && !isset($this->invoice->backup->guid) && $this->invoice->client->peppolSendingEnabled()) { \App\Services\EDocument\Jobs\SendEDocument::dispatch(get_class($this->invoice), $this->invoice->id, $this->invoice->company->db); } - if($this->request->has('redirect')) { - + if ($this->request->has('redirect')) { + $redirectUrl = urldecode($this->request->input('redirect')); if (filter_var($redirectUrl, FILTER_VALIDATE_URL)) { @@ -95,7 +96,7 @@ class TriggeredActions extends AbstractService $this->invoice->backup = $backup; $this->invoice->saveQuietly(); } - + } if ($this->updated) { diff --git a/app/Services/Invoice/UpdateBalance.php b/app/Services/Invoice/UpdateBalance.php index 1a6fb4b91b..cb98f78f52 100644 --- a/app/Services/Invoice/UpdateBalance.php +++ b/app/Services/Invoice/UpdateBalance.php @@ -1,4 +1,5 @@ updateInvoiceBalance($net_deletable, "Adjusting invoice {$paymentable_invoice->number} due to deletion of Payment {$this->payment->number}") ->save(); - + // 2025-03-26 - If we are deleting a negative payment, then there is an edge case where the paid to date will be reduced further down. // for this scenario, we skip the update to the client paid to date at this point. $this->payment diff --git a/app/Services/Payment/PaymentService.php b/app/Services/Payment/PaymentService.php index 0fdf542dd0..b1384df4af 100644 --- a/app/Services/Payment/PaymentService.php +++ b/app/Services/Payment/PaymentService.php @@ -1,4 +1,5 @@ payment->load('company', 'invoices'); - + EmailPayment::dispatch($this->payment, $this->payment->company, $this->contact); } diff --git a/app/Services/Payment/UpdateInvoicePayment.php b/app/Services/Payment/UpdateInvoicePayment.php index b3a574b06e..5b6a3ba2a6 100644 --- a/app/Services/Payment/UpdateInvoicePayment.php +++ b/app/Services/Payment/UpdateInvoicePayment.php @@ -1,4 +1,5 @@ design = $design : $this->design = "{$design}.html"; @@ -30,29 +29,29 @@ class DesignExtractor $this->options = $options; } - + public function setHtml(string $html): self { $this->html = $html; - + return $this; } private function getHtml(): string { // nlog($this->design); - if($this->html) { + if ($this->html) { return $this->html; } - $this->html = file_get_contents( config('ninja.designs.base_path') . $this->design ); + $this->html = file_get_contents(config('ninja.designs.base_path') . $this->design); return $this->html; } public function getSectionHTML(string $section, $id = true): ?string { - + $document = new \DOMDocument(); $document->validateOnParse = true; diff --git a/app/Services/Pdf/Markdown.php b/app/Services/Pdf/Markdown.php index 2f85b0f243..fdafee3199 100644 --- a/app/Services/Pdf/Markdown.php +++ b/app/Services/Pdf/Markdown.php @@ -12,7 +12,7 @@ namespace App\Services\Pdf; -class Markdown +class Markdown { public static function parse(string $markdown): string { @@ -24,4 +24,4 @@ class Markdown return $converter->convert($markdown); } -} \ No newline at end of file +} diff --git a/app/Services/Pdf/PdfBuilder.php b/app/Services/Pdf/PdfBuilder.php index f4e3c00463..dccac029a0 100644 --- a/app/Services/Pdf/PdfBuilder.php +++ b/app/Services/Pdf/PdfBuilder.php @@ -86,19 +86,19 @@ class PdfBuilder return $this; } - + /** * removeEmptyElements * * Removes any empty elements from the DomDocument, this improves the vertical spacing of the PDF * This also decodes any encoded HTML elements. - * + * * @return self */ private function removeEmptyElements(): self - { - - $elements =[ + { + + $elements = [ 'product-table', 'task-table', 'delivery-note-table', 'statement-invoice-table', 'statement-payment-table', 'statement-aging-table-totals', 'statement-invoice-table-totals', 'statement-payment-table-totals', 'statement-aging-table', @@ -106,7 +106,7 @@ class PdfBuilder ]; foreach ($elements as $element) { - + $el = $this->document->getElementById($element); if ($el && $el->childElementCount === 0) { @@ -114,7 +114,7 @@ class PdfBuilder } } - + // Decode any HTML based elements. $xpath = new \DOMXPath($this->document); $elements = $xpath->query('//*[@data-state="encoded-html"]'); @@ -190,12 +190,12 @@ class PdfBuilder return $this; } - + /** * parseTwigElements * * Parses any ninja tags in the template and processes them via TWIG. - * + * * @return self */ private function parseTwigElements(): self @@ -218,7 +218,7 @@ class PdfBuilder $template = $template->render($data); $f = $this->document->createDocumentFragment(); - + $template = str_ireplace(['
', '
'], "
", $template); $f->appendXML($template); @@ -235,7 +235,7 @@ class PdfBuilder return $this; } - + /** * setDocument * @@ -265,12 +265,12 @@ class PdfBuilder return $this; } - + /** * mergeSections * * Merges the sections into the sections array. - * + * * @param array $section * @return self */ @@ -280,12 +280,12 @@ class PdfBuilder return $this; } - + /** * setSections * * Sets the sections array. - * + * * @param mixed $sections * @return self */ @@ -430,10 +430,10 @@ class PdfBuilder $element = ['element' => 'tr', 'elements' => []]; - $element['elements'][] = ['element' => 'td', 'content' => $credit->number]; - $element['elements'][] = ['element' => 'td', 'content' => $this->translateDate($credit->date, $this->service->config->client->date_format(), $this->service->config->locale) ?: ' ']; - $element['elements'][] = ['element' => 'td', 'content' => $this->service->config->formatMoney($credit->amount) ?: ' ']; - $element['elements'][] = ['element' => 'td', 'content' => $this->service->config->formatMoney($credit->balance) ?: ' ']; + $element['elements'][] = ['element' => 'td', 'content' => $credit->number]; + $element['elements'][] = ['element' => 'td', 'content' => $this->translateDate($credit->date, $this->service->config->client->date_format(), $this->service->config->locale) ?: ' ']; + $element['elements'][] = ['element' => 'td', 'content' => $this->service->config->formatMoney($credit->amount) ?: ' ']; + $element['elements'][] = ['element' => 'td', 'content' => $this->service->config->formatMoney($credit->balance) ?: ' ']; $tbody[] = $element; } @@ -447,13 +447,13 @@ class PdfBuilder /** * Parent method for building credits table totals for statements. - * + * * @return array */ public function statementCreditTableTotals(): array { $outstanding = $this->service->options['credits']->sum('balance'); - + if (\array_key_exists('show_credits_table', $this->service->options) && $this->service->options['show_credits_table'] === false) { return []; } @@ -516,10 +516,10 @@ class PdfBuilder } $element = ['element' => 'tr', 'elements' => []]; - $element['elements'][] = ['element' => 'td', 'content' => $invoice->number]; - $element['elements'][] = ['element' => 'td', 'content' => $this->translateDate($refund_date, $this->service->config->date_format, $this->service->config->locale) ?: ' ']; - $element['elements'][] = ['element' => 'td', 'content' => ctrans('texts.refund')]; - $element['elements'][] = ['element' => 'td', 'content' => $this->service->config->formatMoney($payment->pivot->refunded) ?: ' ']; + $element['elements'][] = ['element' => 'td', 'content' => $invoice->number]; + $element['elements'][] = ['element' => 'td', 'content' => $this->translateDate($refund_date, $this->service->config->date_format, $this->service->config->locale) ?: ' ']; + $element['elements'][] = ['element' => 'td', 'content' => ctrans('texts.refund')]; + $element['elements'][] = ['element' => 'td', 'content' => $this->service->config->formatMoney($payment->pivot->refunded) ?: ' ']; $tbody[] = $element; @@ -528,7 +528,7 @@ class PdfBuilder } } } - + return [ ['element' => 'thead', 'elements' => $this->buildTableHeader('statement_payment')], ['element' => 'tbody', 'elements' => $tbody], @@ -553,7 +553,7 @@ class PdfBuilder ['element' => 'div', 'content' => \sprintf('%s: %s', ctrans('texts.amount_paid'), $this->service->config->formatMoney($this->payment_amount_total))], ]; } - + /** * Generates the unapplied payments table totals for statements. * @@ -588,7 +588,7 @@ class PdfBuilder } $tbody = []; - + $this->unapplied_total = 0; foreach ($this->service->options['unapplied'] as $unapplied_payment) { @@ -598,10 +598,10 @@ class PdfBuilder $element = ['element' => 'tr', 'elements' => []]; - $element['elements'][] = ['element' => 'td', 'content' => $unapplied_payment->number]; - $element['elements'][] = ['element' => 'td', 'content' => $this->translateDate($unapplied_payment->date, $this->service->config->date_format, $this->service->config->locale) ?: ' ']; - $element['elements'][] = ['element' => 'td', 'content' => $this->service->config->formatMoney($unapplied_payment->amount) ?: ' ']; - $element['elements'][] = ['element' => 'td', 'content' => $this->service->config->formatMoney($unapplied_payment->amount - $unapplied_payment->applied) ?: ' ']; + $element['elements'][] = ['element' => 'td', 'content' => $unapplied_payment->number]; + $element['elements'][] = ['element' => 'td', 'content' => $this->translateDate($unapplied_payment->date, $this->service->config->date_format, $this->service->config->locale) ?: ' ']; + $element['elements'][] = ['element' => 'td', 'content' => $this->service->config->formatMoney($unapplied_payment->amount) ?: ' ']; + $element['elements'][] = ['element' => 'td', 'content' => $this->service->config->formatMoney($unapplied_payment->amount - $unapplied_payment->applied) ?: ' ']; $tbody[] = $element; @@ -738,11 +738,11 @@ class PdfBuilder foreach ($this->service->options['invoices'] as $invoice) { $element = ['element' => 'tr', 'elements' => []]; - $element['elements'][] = ['element' => 'td', 'content' => $invoice->number]; - $element['elements'][] = ['element' => 'td', 'content' => $this->translateDate($invoice->date, $date_format, $this->service->config->locale) ?: ' ']; - $element['elements'][] = ['element' => 'td', 'content' => $this->translateDate($invoice->due_date, $date_format, $this->service->config->locale) ?: ' ']; - $element['elements'][] = ['element' => 'td', 'content' => $this->service->config->formatMoney($invoice->amount) ?: ' ']; - $element['elements'][] = ['element' => 'td', 'content' => $this->service->config->formatMoney($invoice->balance) ?: ' ']; + $element['elements'][] = ['element' => 'td', 'content' => $invoice->number]; + $element['elements'][] = ['element' => 'td', 'content' => $this->translateDate($invoice->date, $date_format, $this->service->config->locale) ?: ' ']; + $element['elements'][] = ['element' => 'td', 'content' => $this->translateDate($invoice->due_date, $date_format, $this->service->config->locale) ?: ' ']; + $element['elements'][] = ['element' => 'td', 'content' => $this->service->config->formatMoney($invoice->amount) ?: ' ']; + $element['elements'][] = ['element' => 'td', 'content' => $this->service->config->formatMoney($invoice->balance) ?: ' ']; $tbody[] = $element; } @@ -752,7 +752,7 @@ class PdfBuilder ['element' => 'tbody', 'elements' => $tbody], ]; } - + /** * Filters the visible elements for a table row and also * assigned the left and right radius classes to the first and last cells @@ -762,7 +762,7 @@ class PdfBuilder */ private function parseVisibleElements(array $element): array { - + $visible_elements = array_filter($element['elements'], function ($el) { if (isset($el['properties']['visi']) && $el['properties']['visi']) { return true; @@ -814,7 +814,7 @@ class PdfBuilder */ public function buildTableBody(string $type): array { - + $elements = []; $items = $this->transformLineItems($this->service->config->entity->line_items, $type); @@ -871,8 +871,8 @@ class PdfBuilder foreach ($items as $row) { $element = ['element' => 'tr', 'elements' => []]; //checks if we have custom columns in the options array with key $product/$task - looks like unused functionality - if (isset($this->service->options[$type]) && !empty($this->service->options[$type])) { - + if (isset($this->service->options[$type]) && !empty($this->service->options[$type])) { + $document = new DOMDocument(); $document->loadHTML($this->service->options[$type], LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD); @@ -892,7 +892,7 @@ class PdfBuilder } } } else { - + foreach ($this->service->config->pdf_variables[$table_type] as $key => $cell) { // We want to keep aliases like these: // $task.cost => $task.rate @@ -925,14 +925,14 @@ class PdfBuilder } } } - + $element = $this->parseVisibleElements($element); $elements[] = $element; } $document = null; - + return $elements; } @@ -1045,18 +1045,18 @@ class PdfBuilder return $data; } - + /** * Filters the visible columns for a table row. * * @param array $items * @param string $type_id - * + * * @return array */ private function getColumnVisibility(array $items, string $type_id): array { - + // Convert type_id to numeric $type_id = $type_id === 'product' ? '1' : '2'; @@ -1126,9 +1126,9 @@ class PdfBuilder $this->processTaxColumns($column_type); $column_visibility = $this->getColumnVisibility($this->service->config->entity->line_items, $type); - + foreach ($this->service->config->pdf_variables[$table_type] as $column) { - + if (array_key_exists($column, $aliases)) { $elements[] = ['element' => 'th', 'content' => $aliases[$column] . '_label', 'properties' => ['data-ref' => "{$type}_table-" . substr($aliases[$column], 1) . '-th', 'visi' => $this->visibilityCheck($column_visibility, $column)]]; } elseif ($column == '$product.discount' && !$this->service->company->enable_product_discount) { @@ -1151,7 +1151,7 @@ class PdfBuilder $elements[] = ['element' => 'th', 'content' => $column . '_label', 'properties' => ['data-ref' => "{$type}_table-" . substr($column, 1) . '-th', 'visi' => $this->visibilityCheck($column_visibility, $column)]]; } } - + $visible_elements = array_filter($elements, function ($element) { return $element['properties']['visi'] ?? true; }); @@ -1174,7 +1174,7 @@ class PdfBuilder $elements[$last_visible]['properties']['class'] .= ' right-radius'; } } - + $elements = array_map(function ($element) { if (isset($element['properties']['visi'])) { if ($element['properties']['visi'] === false) { @@ -1187,7 +1187,7 @@ class PdfBuilder return $elements; } - + /** * visibilityCheck * @@ -1197,11 +1197,11 @@ class PdfBuilder */ private function visibilityCheck(array $column_visibility, string $column): bool { - if(!$this->service->config->settings->hide_empty_columns_on_pdf){ + if (!$this->service->config->settings->hide_empty_columns_on_pdf) { return true; } - if(array_key_exists($column, $column_visibility)){ + if (array_key_exists($column, $column_visibility)) { return !$column_visibility[$column]; } @@ -1402,7 +1402,7 @@ class PdfBuilder if (is_null($this->service->config->entity->{$_variable}) || empty($this->service->config->entity->{$_variable})) { return true; } - + return false; } @@ -1613,8 +1613,9 @@ class PdfBuilder public function taskTable(): array { - if($this->service->config->entity instanceof \App\Models\PurchaseOrder) + if ($this->service->config->entity instanceof \App\Models\PurchaseOrder) { return []; + } $task_items = collect($this->service->config->entity->line_items)->filter(function ($item) { return $item->type_id == 2; @@ -1769,10 +1770,10 @@ class PdfBuilder /** * Generates the client delivery details array - * + * * We also override some variables here to ensure they are * appropriate for the delivery note. - * + * * @return array * */ @@ -1799,7 +1800,7 @@ class PdfBuilder $this->service->html_variables['values']['$balance_due'] = ''; $this->service->html_variables['values']['$amount_due'] = ''; $this->service->html_variables['labels']['$amount_due_label'] = ''; - + $elements = [ ['element' => 'div', 'content' => $this->service->config->client->name, 'show_empty' => false, 'properties' => ['data-ref' => 'delivery_note-client.name']], ['element' => 'div', 'content' => $this->service->html_variables['values']['$client.shipping_address1'], 'show_empty' => false, 'properties' => ['data-ref' => 'delivery_note-client.shipping_address1']], @@ -1832,7 +1833,7 @@ class PdfBuilder $variables = $this->service->config->pdf_variables['client_details']; // 2025-03-03 - Prevent duplicating contact/client name - if(strlen($this->service->config->client->name ?? '') == 0 && in_array('$client.name', $variables) && in_array('$contact.full_name', $variables)) { + if (strlen($this->service->config->client->name ?? '') == 0 && in_array('$client.name', $variables) && in_array('$contact.full_name', $variables)) { $variables = array_diff($variables, ['$contact.full_name']); } @@ -1842,7 +1843,7 @@ class PdfBuilder return $elements; } - + /** * Generates the shipping details section * @@ -1876,7 +1877,7 @@ class PdfBuilder */ public function deliveryNoteTable(): array { - + $thead = [ ['element' => 'th', 'content' => '$item_label', 'properties' => ['data-ref' => 'delivery_note-item_label']], ['element' => 'th', 'content' => '$description_label', 'properties' => ['data-ref' => 'delivery_note-description_label']], @@ -2052,19 +2053,19 @@ class PdfBuilder return $element; } - + /** * isMarkdown * * Checks if the given content is most likely markdown - * + * * @param string $content * @return bool */ private function isMarkdown(string $content): bool { $content = str_ireplace(['
', '
', '
'], "\n", $content); - + $markdownPatterns = [ '/^\s*#{1,6}\s/m', // Headers '/^\s*[-+*]\s/m', // Lists @@ -2093,11 +2094,11 @@ class PdfBuilder public function createElementContent($element, $children): self { - foreach ($children as $child) { + foreach ($children as $child) { if (isset($child['is_empty']) && $child['is_empty'] === true) { continue; } - + $contains_html = false; $child['content'] = $child['content'] ?? ''; @@ -2138,7 +2139,7 @@ class PdfBuilder return $this; } - + /** * updateVariables * @@ -2149,7 +2150,7 @@ class PdfBuilder $html = strtr($this->getCompiledHTML(), $this->service->html_variables['labels']); $html = strtr($html, $this->service->html_variables['values']); - + @$this->document->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8')); //new block diff --git a/app/Services/Pdf/PdfMock.php b/app/Services/Pdf/PdfMock.php index cf6dd5459d..36a5631ca5 100644 --- a/app/Services/Pdf/PdfMock.php +++ b/app/Services/Pdf/PdfMock.php @@ -114,7 +114,7 @@ class PdfMock public function build(): self { $this->mock = $this->initEntity(); - + $this->setPdfService(); return $this; diff --git a/app/Services/Pdf/Purify.php b/app/Services/Pdf/Purify.php index d9df055d21..8a377b82e5 100644 --- a/app/Services/Pdf/Purify.php +++ b/app/Services/Pdf/Purify.php @@ -18,7 +18,7 @@ class Purify // Text Elements 'span', 'strong', 'em', 'b', 'i', 'u', 'small', - 'sub', 'sup', 'del', 'ins', + 'sub', 'sup', 'del', 'ins', // Line Breaks 'br', 'hr', @@ -36,11 +36,11 @@ class Purify 'ninja', // SVG Elements - 'svg', 'path', 'rect', 'circle', 'ellipse', 'line', 'polyline', + 'svg', 'path', 'rect', 'circle', 'ellipse', 'line', 'polyline', 'polygon', 'g', 'text', 'tspan', 'defs', 'use', 'title', ]; - + private static array $allowed_attributes = [ // Global Attributes 'class' => ['*'], @@ -229,20 +229,20 @@ class Purify 'onabort' ]; - private static function isDangerousSvgElement(string $tagName): bool + private static function isDangerousSvgElement(string $tagName): bool { return in_array(strtolower($tagName), self::$dangerous_svg_elements); } public static function clean(string $html): string - { - if(config('ninja.disable_purify_html')){ + { + if (config('ninja.disable_purify_html')) { return str_replace('%24', '$', $html); } $html = str_replace('%24', '$', $html); libxml_use_internal_errors(true); - + $document = new \DOMDocument(); @$document->loadHTML(htmlspecialchars_decode(htmlspecialchars($html, ENT_QUOTES, 'UTF-8')), LIBXML_NONET); @@ -290,7 +290,7 @@ class Purify // Keep only allowed SVG attributes $current_attributes = []; foreach ($node->attributes as $attr) { - + if (in_array($attr->name, self::$dangerous_svg_elements)) { $node->removeAttribute($attr->name); } @@ -298,25 +298,25 @@ class Purify } } else { - // First, remove ALL attributes from the node + // First, remove ALL attributes from the node // while ($node->attributes->length > 0) { // $attr = $node->attributes->item(0); // $node->removeAttribute($attr->nodeName); // } - -if ($node instanceof \DOMElement) { - // Create a list of attributes to remove - $attributes_to_remove = []; - foreach ($node->attributes as $attr) { - $attributes_to_remove[] = $attr->nodeName; - } - // Remove the attributes - foreach ($attributes_to_remove as $attr_name) { - $node->removeAttribute($attr_name); - } -} + if ($node instanceof \DOMElement) { + // Create a list of attributes to remove + $attributes_to_remove = []; + foreach ($node->attributes as $attr) { + $attributes_to_remove[] = $attr->nodeName; + } + + // Remove the attributes + foreach ($attributes_to_remove as $attr_name) { + $node->removeAttribute($attr_name); + } + } } @@ -416,7 +416,7 @@ if ($node instanceof \DOMElement) { nlog('Error cleaning HTML: ' . $e->getMessage()); libxml_clear_errors(); - + throw new \RuntimeException('HTML sanitization failed'); } finally { libxml_clear_errors(); diff --git a/app/Services/PdfMaker/Design.php b/app/Services/PdfMaker/Design.php index e2e61b3959..7b0c072804 100644 --- a/app/Services/PdfMaker/Design.php +++ b/app/Services/PdfMaker/Design.php @@ -22,7 +22,6 @@ use App\Utils\Traits\MakesInvoiceValues; use DOMDocument; use Illuminate\Support\Str; - /** * @deprecated 2025-02-04 */ @@ -103,7 +102,7 @@ class Design extends BaseDesign $design = $this->composeFromPartials( $this->options['custom_partials'] ); - + // Remove NULL bytes $design = str_replace("\0", '', $design); // Remove UTF-7 BOM @@ -119,7 +118,7 @@ class Design extends BaseDesign $path . $this->design ); - + // Remove NULL bytes $design = str_replace("\0", '', $design); // Remove UTF-7 BOM @@ -842,7 +841,7 @@ class Design extends BaseDesign $elements[] = ['element' => 'th', 'content' => $column . '_label', 'properties' => ['data-ref' => "{$type}_table-" . substr($column, 1) . '-th', 'visi' => $this->visibilityCheck($column_visibility, $column)]]; } } - + $visible_elements = array_filter($elements, function ($element) { return $element['properties']['visi'] ?? true; }); @@ -881,11 +880,11 @@ class Design extends BaseDesign private function visibilityCheck(array $column_visibility, string $column): bool { - if(!$this->settings_object->getSetting('hide_empty_columns_on_pdf')){ + if (!$this->settings_object->getSetting('hide_empty_columns_on_pdf')) { return true; } - if(array_key_exists($column, $column_visibility)){ + if (array_key_exists($column, $column_visibility)) { return !$column_visibility[$column]; } @@ -910,7 +909,7 @@ class Design extends BaseDesign return []; } - + $_type = Str::startsWith($type, '$') ? ltrim($type, '$') : $type; $table_type = "{$_type}_columns"; $column_visibility = $this->getColumnVisibility($this->entity->line_items, $_type); @@ -935,7 +934,7 @@ class Design extends BaseDesign for ($i = 0; $i < count($product_customs); $i++) { if ($product_customs[$i]) { - $element['elements'][] = ['element' => 'td', 'content' => $row['delivery_note.delivery_note' . ($i + 1)], 'properties' => ['data-ref' => 'delivery_note_table.product' . ($i + 1) . '-td', 'visi' => $this->visibilityCheck($column_visibility, 'product'.($i+1))]]; + $element['elements'][] = ['element' => 'td', 'content' => $row['delivery_note.delivery_note' . ($i + 1)], 'properties' => ['data-ref' => 'delivery_note_table.product' . ($i + 1) . '-td', 'visi' => $this->visibilityCheck($column_visibility, 'product'.($i + 1))]]; } } @@ -962,18 +961,18 @@ class Design extends BaseDesign } } - // Then, filter the elements array - $element['elements'] = array_map(function ($el) { - if (isset($el['properties']['visi'])) { //@phpstan-ignore-line - if ($el['properties']['visi'] === false) { - $el['properties']['style'] = 'display: none;'; - } - unset($el['properties']['visi']); + // Then, filter the elements array + $element['elements'] = array_map(function ($el) { + if (isset($el['properties']['visi'])) { //@phpstan-ignore-line + if ($el['properties']['visi'] === false) { + $el['properties']['style'] = 'display: none;'; } - return $el; - }, $element['elements']); + unset($el['properties']['visi']); + } + return $el; + }, $element['elements']); - $elements[] = $element; + $elements[] = $element; } @@ -1013,7 +1012,7 @@ class Design extends BaseDesign } } } else { - + foreach ($this->context['pdf_variables'][$table_type] as $key => $cell) { // We want to keep aliases like these: // $task.cost => $task.rate @@ -1039,7 +1038,7 @@ class Design extends BaseDesign $element['elements'][] = ['element' => 'td', 'content' => $row[$cell], 'properties' => ['data-ref' => 'task_table-task.tax2-td', 'visi' => $this->visibilityCheck($column_visibility, $cell)]]; } elseif ($cell == '$task.tax_rate3') { $element['elements'][] = ['element' => 'td', 'content' => $row[$cell], 'properties' => ['data-ref' => 'task_table-task.tax3-td', 'visi' => $this->visibilityCheck($column_visibility, $cell)]]; - }elseif ($cell == '$product.unit_cost' || $cell == '$task.rate') { + } elseif ($cell == '$product.unit_cost' || $cell == '$task.rate') { $element['elements'][] = ['element' => 'td', 'content' => $row[$cell], 'properties' => ['style' => 'white-space: nowrap;', 'data-ref' => "{$_type}_table-" . substr($cell, 1) . '-td', 'visi' => $this->visibilityCheck($column_visibility, $cell)]]; } else { $element['elements'][] = ['element' => 'td', 'content' => $row[$cell], 'properties' => ['data-ref' => "{$_type}_table-" . substr($cell, 1) . '-td', 'visi' => $this->visibilityCheck($column_visibility, $cell)]]; @@ -1047,7 +1046,7 @@ class Design extends BaseDesign } } - + $visible_elements = array_filter($element['elements'], function ($el) { if (isset($el['properties']['visi']) && $el['properties']['visi']) { return true; @@ -1111,7 +1110,7 @@ class Design extends BaseDesign $filtered_items->toArray(), $type_id === '1' ? '$product' : '$task' ); - + $columns = []; // Initialize all columns as empty @@ -1155,7 +1154,7 @@ class Design extends BaseDesign $variables = $this->context['pdf_variables']['total_columns']; $show_terms_label = $this->entityVariableCheck('$entity.terms') ? 'display: none;' : ''; - + $elements = [ ['element' => 'div', 'properties' => ['style' => 'display: flex; flex-direction: column;'], 'elements' => [ ['element' => 'div', 'properties' => ['data-ref' => 'total_table-public_notes', 'style' => 'text-align: left;'], 'elements' => [ diff --git a/app/Services/PdfMaker/PdfMaker.php b/app/Services/PdfMaker/PdfMaker.php index 7094d6c2bd..3810dc945f 100644 --- a/app/Services/PdfMaker/PdfMaker.php +++ b/app/Services/PdfMaker/PdfMaker.php @@ -62,7 +62,7 @@ class PdfMaker public function build() { - + if (isset($this->data['template']) && isset($this->data['variables'])) { $this->getEmptyElements($this->data['template'], $this->data['variables']); } diff --git a/app/Services/PdfMaker/PdfMakerUtilities.php b/app/Services/PdfMaker/PdfMakerUtilities.php index 2aa14192a4..b88997f317 100644 --- a/app/Services/PdfMaker/PdfMakerUtilities.php +++ b/app/Services/PdfMaker/PdfMakerUtilities.php @@ -37,9 +37,9 @@ trait PdfMakerUtilities $element = $this->document->getElementById($selector); if ($section) { - return $element->getAttribute($section); + return $element->getAttribute($section); } - + return $element->nodeValue; } @@ -94,7 +94,7 @@ trait PdfMakerUtilities private function isMarkdown(string $content): bool { $content = str_ireplace('
', "\n", $content); - + $markdownPatterns = [ '/^\s*#{1,6}\s/m', // Headers '/^\s*[-+*]\s/m', // Lists diff --git a/app/Services/PdfMaker/PdfMerge.php b/app/Services/PdfMaker/PdfMerge.php index 5d25e89e7f..b935495584 100644 --- a/app/Services/PdfMaker/PdfMerge.php +++ b/app/Services/PdfMaker/PdfMerge.php @@ -32,7 +32,7 @@ class PdfMerge $pdf = new FPDI(); foreach ($this->files as $file) { - + $pageCount = 0; try { @@ -41,10 +41,10 @@ class PdfMerge } catch (\setasign\Fpdi\PdfParser\PdfParserException $e) { // If FPDI fails, try downgrading the PDF - if(class_exists(\Modules\Admin\Services\PdfParse::class)){ - + if (class_exists(\Modules\Admin\Services\PdfParse::class)) { + $downgradedPdf = \Modules\Admin\Services\PdfParse::downgrade($file); - + $pageCount = $pdf->setSourceFile(StreamReader::createByString($downgradedPdf)); } diff --git a/app/Services/Project/ProjectService.php b/app/Services/Project/ProjectService.php index bb2d1e221e..0c3d3b77fa 100644 --- a/app/Services/Project/ProjectService.php +++ b/app/Services/Project/ProjectService.php @@ -17,7 +17,6 @@ use Illuminate\Support\Carbon; class ProjectService { - public function __construct(public Project $project) { } @@ -29,39 +28,38 @@ class ProjectService $project_start = Carbon::parse($this->project->created_at)->addSeconds($this->project->company->timezone_offset()); $project_due = Carbon::parse($this->project->due_date); $budgeted_hours = $this->project->budgeted_hours; - $project_duration = $project_start->diffInDays($project_due) + 1; + $project_duration = $project_start->diffInDays($project_due) + 1; $average_daily_hours = $budgeted_hours / $project_duration; $task_query = $this->project ->tasks() - ->orderBy('calculated_start_date','asc'); + ->orderBy('calculated_start_date', 'asc'); $average_data = $task_query ->get() - ->map(function ($task){ + ->map(function ($task) { - return [ - 'date' => $task->calculated_start_date ?? \Carbon\Carbon::parse($task->created_at)->format('Y-m-d'), - 'hours_used' => $task->calcDuration()/60/60, - ]; - }); + return [ + 'date' => $task->calculated_start_date ?? \Carbon\Carbon::parse($task->created_at)->format('Y-m-d'), + 'hours_used' => $task->calcDuration() / 60 / 60, + ]; + }); $last_task = $task_query->latest()->first(); $next_date = \Carbon\Carbon::parse($last_task->calculated_start_date ?? now()->format('Y-m-d')); - do{ + do { $next_date->addDay(); $average_data->push([ - 'date' => $next_date->format('Y-m-d'), - 'hours_used' => 0, + 'date' => $next_date->format('Y-m-d'), + 'hours_used' => 0, ]); - } - while($next_date->lt($project_due)); + } while ($next_date->lt($project_due)); return [ 'project_start' => $project_start->toDateString(), @@ -69,7 +67,7 @@ class ProjectService 'hours_used' => $this->project->current_hours, 'average_data' => $average_data, ]; - + } diff --git a/app/Services/PurchaseOrder/ApplyNumber.php b/app/Services/PurchaseOrder/ApplyNumber.php index a72d5767c4..2fef917308 100644 --- a/app/Services/PurchaseOrder/ApplyNumber.php +++ b/app/Services/PurchaseOrder/ApplyNumber.php @@ -1,4 +1,5 @@ purchase_order->last_sent_date = now(); $this->purchase_order->save(); - + $this->purchase_order->invitations->load('contact.vendor.country', 'purchase_order.vendor.country', 'purchase_order.company')->each(function ($invitation) { App::forgetInstance('translator'); diff --git a/app/Services/PurchaseOrder/TriggeredActions.php b/app/Services/PurchaseOrder/TriggeredActions.php index f83825523a..66ed574e66 100644 --- a/app/Services/PurchaseOrder/TriggeredActions.php +++ b/app/Services/PurchaseOrder/TriggeredActions.php @@ -1,4 +1,5 @@ invoice_transformer->qbToNinja($record); $payment_ids = $ninja_invoice_data['payment_ids'] ?? []; @@ -72,16 +73,16 @@ class QbInvoice implements SyncInterface $this->qbInvoiceUpdate($ninja_invoice_data, $invoice); } - if(Invoice::where('company_id', $this->service->company->id) + if (Invoice::where('company_id', $this->service->company->id) ->whereNotNull('number') ->where('number', $ninja_invoice_data['number']) ->exists()) { $ninja_invoice_data['number'] = 'qb_'.$ninja_invoice_data['number'].'_'.rand(1000, 99999); } - $invoice->fill($ninja_invoice_data); - $invoice->saveQuietly(); - + $invoice->fill($ninja_invoice_data); + $invoice->saveQuietly(); + $invoice = $invoice->calc()->getInvoice()->service()->markSent()->applyNumber()->createInvitations()->save(); diff --git a/app/Services/Quickbooks/Models/QbPayment.php b/app/Services/Quickbooks/Models/QbPayment.php index 4cc795349b..5c0876a8ab 100644 --- a/app/Services/Quickbooks/Models/QbPayment.php +++ b/app/Services/Quickbooks/Models/QbPayment.php @@ -1,4 +1,5 @@ invoice = new QbInvoice($this); $this->quote = new QbQuote($this); - + $this->product = new QbProduct($this); $this->client = new QbClient($this); @@ -97,38 +98,38 @@ class QuickbooksService return $this; } - private function checkDefaultAccounts(): self - { + // private function checkDefaultAccounts(): self + // { - $accountQuery = "SELECT * FROM Account WHERE AccountType IN ('Income', 'Cost of Goods Sold')"; + // $accountQuery = "SELECT * FROM Account WHERE AccountType IN ('Income', 'Cost of Goods Sold')"; - if (strlen($this->settings->default_income_account) == 0 || strlen($this->settings->default_expense_account) == 0) { + // if (strlen($this->settings->default_income_account) == 0 || strlen($this->settings->default_expense_account) == 0) { - nlog("Checking default accounts for company {$this->company->company_key}"); - $accounts = $this->sdk->Query($accountQuery); + // nlog("Checking default accounts for company {$this->company->company_key}"); + // $accounts = $this->sdk->Query($accountQuery); - $find_income_account = true; - $find_expense_account = true; + // $find_income_account = true; + // $find_expense_account = true; - foreach ($accounts as $account) { - if ($account->AccountType->value == 'Income' && $find_income_account) { - $this->settings->default_income_account = $account->Id->value; - $find_income_account = false; - } elseif ($account->AccountType->value == 'Cost of Goods Sold' && $find_expense_account) { - $this->settings->default_expense_account = $account->Id->value; - $find_expense_account = false; - } - } + // foreach ($accounts as $account) { + // if ($account->AccountType->value == 'Income' && $find_income_account) { + // $this->settings->default_income_account = $account->Id->value; + // $find_income_account = false; + // } elseif ($account->AccountType->value == 'Cost of Goods Sold' && $find_expense_account) { + // $this->settings->default_expense_account = $account->Id->value; + // $find_expense_account = false; + // } + // } - nlog($this->settings); + // nlog($this->settings); - $this->company->quickbooks->settings = $this->settings; - $this->company->save(); - } + // $this->company->quickbooks->settings = $this->settings; + // $this->company->save(); + // } - return $this; - } + // return $this; + // } private function checkToken(): self { diff --git a/app/Services/Quickbooks/SdkWrapper.php b/app/Services/Quickbooks/SdkWrapper.php index 93359f4e0f..26a14d615a 100644 --- a/app/Services/Quickbooks/SdkWrapper.php +++ b/app/Services/Quickbooks/SdkWrapper.php @@ -1,4 +1,5 @@ data_get($data, 'GivenName', ''), 'last_name' => data_get($data, 'FamilyName', ''), - 'phone' => data_get($data, 'PrimaryPhone.FreeFormNumber',''), + 'phone' => data_get($data, 'PrimaryPhone.FreeFormNumber', ''), 'email' => data_get($data, 'PrimaryEmailAddr.Address', null), ]; diff --git a/app/Services/Quickbooks/Transformers/InvoiceTransformer.php b/app/Services/Quickbooks/Transformers/InvoiceTransformer.php index 389783979c..357f5d5cfa 100644 --- a/app/Services/Quickbooks/Transformers/InvoiceTransformer.php +++ b/app/Services/Quickbooks/Transformers/InvoiceTransformer.php @@ -84,17 +84,17 @@ class InvoiceTransformer extends BaseTransformer private function calculateTotalTax($qb_data) { - $total_tax = data_get($qb_data,'TxnTaxDetail.TotalTax', false); + $total_tax = data_get($qb_data, 'TxnTaxDetail.TotalTax', false); $tax_rate = 0; $tax_name = ''; - if($total_tax == "0") { + if ($total_tax == "0") { return [$tax_rate, $tax_name]; } $taxLines = data_get($qb_data, 'TxnTaxDetail.TaxLine', []) ?? []; - + if (!empty($taxLines) && !isset($taxLines[0])) { $taxLines = [$taxLines]; } @@ -128,7 +128,7 @@ class InvoiceTransformer extends BaseTransformer $tax_rate = $tr->rate; $tax_name = $tr->name; } - + return [$tax_rate, $tax_name]; } @@ -140,7 +140,7 @@ class InvoiceTransformer extends BaseTransformer $qb_payments = data_get($qb_data, 'LinkedTxn', false) ?? []; - if(!empty($qb_payments) && !isset($qb_payments[0])) { + if (!empty($qb_payments) && !isset($qb_payments[0])) { $qb_payments = [$qb_payments]; } @@ -162,8 +162,8 @@ class InvoiceTransformer extends BaseTransformer $items = []; - if(!empty($qb_items) && !isset($qb_items[0])) { - + if (!empty($qb_items) && !isset($qb_items[0])) { + //handle weird statement charges $tax_rate = (float)data_get($qb_data, 'TxnTaxDetail.TaxLine.TaxLineDetail.TaxPercent', 0); $tax_name = $tax_rate > 0 ? "Sales Tax [{$tax_rate}]" : ''; @@ -187,14 +187,14 @@ class InvoiceTransformer extends BaseTransformer foreach ($qb_items as $qb_item) { - $taxCodeRef = data_get($qb_item, 'TaxCodeRef', data_get($qb_item, 'SalesItemLineDetail.TaxCodeRef', 'TAX')); + $taxCodeRef = data_get($qb_item, 'TaxCodeRef', data_get($qb_item, 'SalesItemLineDetail.TaxCodeRef', 'TAX')); if (data_get($qb_item, 'DetailType') == 'SalesItemLineDetail') { $item = new InvoiceItem(); $item->product_key = data_get($qb_item, 'SalesItemLineDetail.ItemRef.name', ''); $item->notes = data_get($qb_item, 'Description', ''); $item->quantity = (float)(data_get($qb_item, 'SalesItemLineDetail.Qty') ?? 1); - $item->cost = (float)(data_get($qb_item, 'SalesItemLineDetail.UnitPrice') ?? data_get($qb_item,'SalesItemLineDetail.MarkupInfo.Value', 0)); + $item->cost = (float)(data_get($qb_item, 'SalesItemLineDetail.UnitPrice') ?? data_get($qb_item, 'SalesItemLineDetail.MarkupInfo.Value', 0)); $item->discount = (float)data_get($item, 'DiscountRate', data_get($qb_item, 'DiscountAmount', 0)); $item->is_amount_discount = data_get($qb_item, 'DiscountAmount', 0) > 0 ? true : false; $item->type_id = stripos(data_get($qb_item, 'ItemAccountRef.name') ?? '', 'Service') !== false ? '2' : '1'; @@ -214,7 +214,7 @@ class InvoiceTransformer extends BaseTransformer $item->cost = (float)data_get($qb_item, 'Amount', 0) * -1; $item->discount = 0; $item->is_amount_discount = true; - + $item->tax_rate1 = (float)$include_discount == 'true' ? $tax_array[0] : 0; $item->tax_name1 = $include_discount == 'true' ? $tax_array[1] : ''; diff --git a/app/Services/Quickbooks/Transformers/PaymentTransformer.php b/app/Services/Quickbooks/Transformers/PaymentTransformer.php index 70dd3911f2..e30578d1d3 100644 --- a/app/Services/Quickbooks/Transformers/PaymentTransformer.php +++ b/app/Services/Quickbooks/Transformers/PaymentTransformer.php @@ -1,4 +1,5 @@ where('sync->qb_id', data_get($qb_data, 'invoice_id')) ->first(); - if(!$invoice) + if (!$invoice) { return; + } $lines = data_get($qb_data, 'Line', []) ?? []; - if(!empty($lines) && !isset($lines[0])) { + if (!empty($lines) && !isset($lines[0])) { $lines = [$lines]; } - foreach($lines as $item) { + foreach ($lines as $item) { $id = data_get($item, 'LinkedTxn.TxnId', false); $tx_type = data_get($item, 'LinkedTxn.TxnType', false); $amount = data_get($item, 'Amount', 0); - if($tx_type == 'Invoice' && $id == $invoice->sync->qb_id && $amount > 0) { + if ($tx_type == 'Invoice' && $id == $invoice->sync->qb_id && $amount > 0) { $paymentable = new \App\Models\Paymentable(); $paymentable->payment_id = $payment->id; @@ -99,7 +101,7 @@ class PaymentTransformer extends BaseTransformer ->where('sync->qb_id', $ninja_payment_data['id']) ->first(); - if($search_payment) { + if ($search_payment) { return $search_payment; } diff --git a/app/Services/Quickbooks/Transformers/QuoteTransformer.php b/app/Services/Quickbooks/Transformers/QuoteTransformer.php index 28dd54c555..03d1f1ae88 100644 --- a/app/Services/Quickbooks/Transformers/QuoteTransformer.php +++ b/app/Services/Quickbooks/Transformers/QuoteTransformer.php @@ -130,25 +130,25 @@ class QuoteTransformer extends BaseTransformer } - private function getPayments(mixed $qb_data) - { - $payments = []; + // private function getPayments(mixed $qb_data) + // { + // $payments = []; - $qb_payments = data_get($qb_data, 'LinkedTxn', false) ?? []; + // $qb_payments = data_get($qb_data, 'LinkedTxn', false) ?? []; - if (!empty($qb_payments) && !isset($qb_payments[0])) { - $qb_payments = [$qb_payments]; - } + // if (!empty($qb_payments) && !isset($qb_payments[0])) { + // $qb_payments = [$qb_payments]; + // } - foreach ($qb_payments as $payment) { - if (data_get($payment, 'TxnType', false) == 'Payment') { - $payments[] = data_get($payment, 'TxnId', false); - } - } + // foreach ($qb_payments as $payment) { + // if (data_get($payment, 'TxnType', false) == 'Payment') { + // $payments[] = data_get($payment, 'TxnId', false); + // } + // } - return $payments; + // return $payments; - } + // } private function getLineItems(mixed $qb_data, array $tax_array) { diff --git a/app/Services/Quote/ApplyNumber.php b/app/Services/Quote/ApplyNumber.php index 68fdaa5f88..cfbfc86775 100644 --- a/app/Services/Quote/ApplyNumber.php +++ b/app/Services/Quote/ApplyNumber.php @@ -1,4 +1,5 @@ quote))->run(); + return (new LocationData($this->quote))->run(); } public function createInvitations() diff --git a/app/Services/Quote/SendEmail.php b/app/Services/Quote/SendEmail.php index 918ef7ceb0..3952f801c6 100644 --- a/app/Services/Quote/SendEmail.php +++ b/app/Services/Quote/SendEmail.php @@ -1,4 +1,5 @@ reminder_template, ["email_quote_template_reminder1","reminder1"])) + if (in_array($this->reminder_template, ["email_quote_template_reminder1","reminder1"])) { $this->reminder_template = "email_quote_template_reminder1"; - elseif(in_array($this->reminder_template, ['custom1','custom2','custom3'])) + } elseif (in_array($this->reminder_template, ['custom1','custom2','custom3'])) { $this->reminder_template = "email_template_".$this->reminder_template; - else + } else { $this->reminder_template = "email_template_".$this->quote->calculateTemplate('quote'); + } $this->quote->service()->markSent()->save(); diff --git a/app/Services/Quote/TriggeredActions.php b/app/Services/Quote/TriggeredActions.php index 48739ae8cf..00dbd766c9 100644 --- a/app/Services/Quote/TriggeredActions.php +++ b/app/Services/Quote/TriggeredActions.php @@ -1,4 +1,5 @@ quote->calculateTemplate('quote'); - + $template_body = 'email_template_quote'; $subject = 'email_subject_quote'; - - if($reminder_template == 'reminder1'){ + + if ($reminder_template == 'reminder1') { $template_body = 'email_quote_template_reminder1'; $subject = 'email_quote_subject_reminder1'; $reminder_template = 'email_quote_template_reminder1'; diff --git a/app/Services/Quote/UpdateReminder.php b/app/Services/Quote/UpdateReminder.php index f0845f8042..de5ce05d16 100644 --- a/app/Services/Quote/UpdateReminder.php +++ b/app/Services/Quote/UpdateReminder.php @@ -1,4 +1,5 @@ recurring_entity))->run(); + return (new LocationData($this->recurring_entity))->run(); } public function save() diff --git a/app/Services/Recurring/UpdatePrice.php b/app/Services/Recurring/UpdatePrice.php index 1a89c16f83..e3741393f8 100644 --- a/app/Services/Recurring/UpdatePrice.php +++ b/app/Services/Recurring/UpdatePrice.php @@ -1,4 +1,5 @@ start_date = (new \Carbon\Carbon('-1 year'))->startOfYear(); $this->end_date = (new \Carbon\Carbon('-1 year'))->endOfYear(); break; - + case 'this_year': $this->start_date = now()->startOfYear(); $this->end_date = now(); diff --git a/app/Services/Report/ProjectReport.php b/app/Services/Report/ProjectReport.php index e9de7277ce..6be93a2ff9 100644 --- a/app/Services/Report/ProjectReport.php +++ b/app/Services/Report/ProjectReport.php @@ -65,11 +65,11 @@ class ProjectReport extends BaseExport $query = \App\Models\Project::with(['invoices','expenses','tasks']) ->where('company_id', $this->company->id); - + $projects = &$this->input['projects']; if ($projects) { - + $transformed_projects = is_string($projects) ? $this->transformKeys(explode(',', $projects)) : $this->transformKeys($projects); if (count($transformed_projects) > 0) { @@ -77,7 +77,7 @@ class ProjectReport extends BaseExport } } - + $clients = &$this->input['clients']; if ($clients) { @@ -114,7 +114,7 @@ class ProjectReport extends BaseExport // private function getTaskAllocationData(Project $project) // { // $tasks = $project->tasks()->withTrashed()->map(function ($task) { - + // return [ // 'label' => strlen($task->description ?? '') > 0 ? $task->description : $task->number, // 'hours' => ($task->calcDuration() / 3600) @@ -123,11 +123,11 @@ class ProjectReport extends BaseExport // }); // $taskAllocationData = [ - // 'labels' => $tasks->pluck('label'), + // 'labels' => $tasks->pluck('label'), // 'datasets' => [ // [ // 'label' => 'Hours Spent', - // 'data' => $tasks->pluck('hours'), + // 'data' => $tasks->pluck('hours'), // 'backgroundColor' => 'rgba(54, 162, 235, 0.2)', // 'borderColor' => 'rgba(54, 162, 235, 1)', // 'borderWidth' => 1 @@ -155,4 +155,4 @@ class ProjectReport extends BaseExport // ]; // }); // } -} \ No newline at end of file +} diff --git a/app/Services/Report/TaxSummaryReport.php b/app/Services/Report/TaxSummaryReport.php index 4298caafbc..99c896a720 100644 --- a/app/Services/Report/TaxSummaryReport.php +++ b/app/Services/Report/TaxSummaryReport.php @@ -1,4 +1,5 @@ sum('amount'), 2); @@ -221,7 +222,7 @@ class TaxSummaryReport extends BaseExport $this->csv->insertOne([]); $this->csv->insertOne([ctrans('texts.cash_accounting')]); $this->csv->insertOne([]); - + $this->csv->insertOne([ctrans('texts.gross'), $cash_gross_sales_money, $cash_gross_sales_formatted]); $this->csv->insertOne([ctrans('texts.taxable_amount'), $cash_taxable_sales_money, $cash_taxable_sales_formatted]); $this->csv->insertOne([ctrans('texts.tax_exempt'), $cash_exempt_sales_money, $cash_exempt_sales_formatted]); @@ -263,7 +264,7 @@ class TaxSummaryReport extends BaseExport $this->taxes['cash_gross_sales'] = $cash_gross_sales_money; $this->taxes['cash_taxable_sales'] = $cash_taxable_sales_money; $this->taxes['cash_exempt_sales'] = $cash_exempt_sales_money; - + $this->taxes['gross_sales'] = $gross_sales_money; $this->taxes['taxable_sales'] = $taxable_sales_money; $this->taxes['exempt_sales'] = $exempt_sales_money; diff --git a/app/Services/Report/UserSalesReport.php b/app/Services/Report/UserSalesReport.php index 43bd442129..b362f34884 100644 --- a/app/Services/Report/UserSalesReport.php +++ b/app/Services/Report/UserSalesReport.php @@ -1,4 +1,5 @@ save([], $recurring_invoice); $recurring_invoice->auto_bill = $this->subscription->auto_bill; $recurring_invoice->auto_bill_enabled = ($this->subscription->auto_bill == 'always' || $this->subscription->auto_bill == 'optout') ? true : false; - + /* Start the recurring service */ $recurring_invoice->service() ->start() diff --git a/app/Services/Subscription/SubscriptionStatus.php b/app/Services/Subscription/SubscriptionStatus.php index 6743accab7..1755726c40 100644 --- a/app/Services/Subscription/SubscriptionStatus.php +++ b/app/Services/Subscription/SubscriptionStatus.php @@ -1,4 +1,5 @@ configureProvider($this->provider, $location->country->iso_3166_2); + $this->configureProvider($this->provider, $location->country->iso_3166_2); $tax_provider = new $this->provider($this->getBillingAddress()); @@ -158,7 +159,7 @@ class TaxProvider } return $this; - } + } /** * taxShippingAddress * @@ -272,7 +273,7 @@ class TaxProvider return $this; } - + public function setShippingAddress(array $address): self { $this->shipping_address = $address; @@ -285,9 +286,9 @@ class TaxProvider return $this->billing_address; } - public function getShippingAddress(): array + public function getShippingAddress(): array { return $this->shipping_address; } - + } diff --git a/app/Services/Tax/Providers/TaxProviderInterface.php b/app/Services/Tax/Providers/TaxProviderInterface.php index bba566f398..2270340639 100644 --- a/app/Services/Tax/Providers/TaxProviderInterface.php +++ b/app/Services/Tax/Providers/TaxProviderInterface.php @@ -1,4 +1,5 @@ '; return $html; // return new \Twig\Markup($html, 'UTF-8'); })); - + $this->twig->addFunction($function); $function = new \Twig\TwigFunction('t', \Closure::fromCallable(function (string $text_key) { @@ -399,7 +400,7 @@ class TemplateService } } - + $html = htmlspecialchars_decode($html, ENT_QUOTES | ENT_HTML5); $html = str_ireplace(['
'], '
', $html); @@ -562,7 +563,7 @@ class TemplateService $this->entity = $invoice; if ($invoice->payments ?? false) { - $payments = $invoice->payments->map(function ($payment) use($invoice) { + $payments = $invoice->payments->map(function ($payment) use ($invoice) { return $this->transformPayment($payment, $invoice); })->toArray(); } @@ -642,7 +643,7 @@ class TemplateService return collect($items)->map(function ($item) use ($client_or_vendor) { $item->cost_raw = $item->cost ?? 0; - + $item->discount_raw = $item->discount ?? 0; $item->line_total_raw = $item->line_total ?? 0; $item->gross_line_total_raw = $item->gross_line_total ?? 0; @@ -653,7 +654,7 @@ class TemplateService $item->net_cost = Number::formatMoney($item->net_cost_raw, $client_or_vendor); $item->cost = Number::formatMoney($item->cost_raw, $client_or_vendor); - + if ($item->is_amount_discount) { $item->discount = Number::formatMoney($item->discount_raw, $client_or_vendor); } @@ -681,7 +682,7 @@ class TemplateService $this->payment = $payment; $credits = $payment->credits - ->when($entity instanceof Credit, function($collection) use ($entity) { + ->when($entity instanceof Credit, function ($collection) use ($entity) { return $collection->where('number', $entity->number); }) ->map(function ($credit) use ($payment) { @@ -702,9 +703,9 @@ class TemplateService }); $pivot = $payment->invoices - ->when($entity instanceof Invoice, function($collection) use ($entity) { + ->when($entity instanceof Invoice, function ($collection) use ($entity) { return $collection->where('number', $entity->number); - }) + }) ->map(function ($invoice) use ($payment) { return [ 'invoice' => $invoice->number, @@ -885,7 +886,7 @@ class TemplateService $this->entity = $credit; if ($credit->payments ?? false) { - $payments = $credit->payments->map(function ($payment) use($credit) { + $payments = $credit->payments->map(function ($payment) use ($credit) { return $this->transformPayment($payment, $credit); })->toArray(); } @@ -1080,7 +1081,7 @@ class TemplateService 'vendor' => $this->getVendor($expense), 'project' => ($expense->project && !$nested) ? $this->transformProject($expense->project, true) : [], ]; - })->toArray(); + })->toArray(); } /** @@ -1671,7 +1672,7 @@ class TemplateService } $contains_html = str_contains($child['content'], '<') && str_contains($child['content'], '>'); - + if ($contains_html) { // If the element contains the HTML, we gonna display it as is. Backend is going to // encode it for us, preventing any errors on the processing stage. diff --git a/app/Services/User/UserService.php b/app/Services/User/UserService.php index 4d661d23df..ce95f4cf5b 100644 --- a/app/Services/User/UserService.php +++ b/app/Services/User/UserService.php @@ -1,4 +1,5 @@ includeCollection($company->locations, $transformer, Location::class); } - + public function includeBankTransactionRules(Company $company) { diff --git a/app/Transformers/CompanyUserTransformer.php b/app/Transformers/CompanyUserTransformer.php index d265743edc..3403659c25 100644 --- a/app/Transformers/CompanyUserTransformer.php +++ b/app/Transformers/CompanyUserTransformer.php @@ -1,4 +1,5 @@ includeItem($credit->location, $transformer, \App\Models\Location::class); } - + public function includeActivities(Credit $credit) { $transformer = new ActivityTransformer($this->serializer); diff --git a/app/Transformers/DesignTransformer.php b/app/Transformers/DesignTransformer.php index 7ba29a0bee..706a051734 100644 --- a/app/Transformers/DesignTransformer.php +++ b/app/Transformers/DesignTransformer.php @@ -1,4 +1,5 @@ includeItem($quote->location, $transformer, \App\Models\Location::class); } - + public function includeActivities(Quote $quote) { $transformer = new ActivityTransformer($this->serializer); diff --git a/app/Transformers/RecurringExpenseTransformer.php b/app/Transformers/RecurringExpenseTransformer.php index 33bf6e86cf..04c642313e 100644 --- a/app/Transformers/RecurringExpenseTransformer.php +++ b/app/Transformers/RecurringExpenseTransformer.php @@ -1,4 +1,5 @@ replace(Ninja::transformTranslations($this->settings)); $locationData = $this->entity->service()->location(); - + $data = []; $data['$date_client_now'] = ['value' => now()->setTimezone($this->client->timezone()->name)->addSeconds($this->client->utc_offset())->format($this->client->date_format()), 'label' => '']; @@ -241,7 +241,7 @@ class HtmlEngine if (strlen($this->company->getSetting('qr_iban')) > 5) { try { $data['$swiss_qr'] = ['value' => (new SwissQrGenerator($this->entity, $this->company))->run(), 'label' => '']; - $data['$swiss_qr_raw'] = ['value' => html_entity_decode($data['$swiss_qr']['value']), 'label' => '']; + $data['$swiss_qr_raw'] = ['value' => html_entity_decode($data['$swiss_qr']['value']), 'label' => '']; } catch (\Exception $e) { $data['$swiss_qr'] = ['value' => '', 'label' => '']; $data['$swiss_qr_raw'] = ['value' => '', 'label' => '']; @@ -679,7 +679,7 @@ class HtmlEngine $data['$contact.signature'] = ['value' => '', 'label' => '']; } - if($this->entity->quote){ + if ($this->entity->quote) { $data['$quote.reference'] = ['value' => $this->entity->quote->number ?: ' ', 'label' => ctrans('texts.quote_number')]; } @@ -970,7 +970,7 @@ class HtmlEngine return $country ? $country->iso_3166_2 : ' '; } - + private function lineTaxValues(): string { $tax_map = $this->entity_calc->getTaxMap(); diff --git a/app/Utils/Ninja.php b/app/Utils/Ninja.php index e38a13366b..c91a5a7767 100644 --- a/app/Utils/Ninja.php +++ b/app/Utils/Ninja.php @@ -1,4 +1,5 @@ company->settings->expense_number_counter; $pattern = $expense->company->settings->expense_number_pattern; - + if (strlen($pattern) > 1 && (stripos($pattern, 'counter') === false)) { $pattern = $pattern.'{$counter}'; } @@ -534,15 +535,15 @@ trait GeneratesCounter $reset_counter_frequency = (int) $client->getSetting('reset_counter_frequency_id'); $settings_entity = $client->getSettingEntity('reset_counter_frequency_id'); $settings = $settings_entity->settings; - + if ($reset_counter_frequency == 0) { - + if ($client->getSetting('reset_counter_date')) { $settings->reset_counter_date = ""; $settings_entity->settings = $settings; $settings_entity->saveQuietly(); } - + return; } diff --git a/app/Utils/Traits/Inviteable.php b/app/Utils/Traits/Inviteable.php index 1a57c9c354..59163053e2 100644 --- a/app/Utils/Traits/Inviteable.php +++ b/app/Utils/Traits/Inviteable.php @@ -1,4 +1,5 @@ setSerializer(new ArraySerializer()); - + $manager->parseIncludes($this->broadcastIncludes()); $class = sprintf('App\\Transformers\\%sTransformer', class_basename($entity)); diff --git a/app/Utils/Traits/MakesDates.php b/app/Utils/Traits/MakesDates.php index a93b0d1b95..3cf40f98bb 100644 --- a/app/Utils/Traits/MakesDates.php +++ b/app/Utils/Traits/MakesDates.php @@ -1,4 +1,5 @@ addDays((int)$num_days_reminder) ->startOfDay() - ->toDateString() === + ->toDateString() === ($entity_send_time === 0 ? now()->startOfDay()->toDateString() : now()->setTimezone($this->client->timezone()->name)->startOfDay()->toDateString()); - + case 'after_quote_date': - + return Carbon::parse($this->date) ->addDays((int)$num_days_reminder) ->startOfDay() @@ -77,7 +78,7 @@ trait MakesReminders ->startOfDay() ->toDateString() === ($entity_send_time === 0 ? now()->startOfDay()->toDateString() : now()->setTimezone($this->client->timezone()->name)->startOfDay()->toDateString()); - + case 'before_valid_until_date': return Carbon::parse($this->due_date) @@ -85,7 +86,7 @@ trait MakesReminders ->startOfDay() ->toDateString() === ($entity_send_time === 0 ? now()->startOfDay()->toDateString() : now()->setTimezone($this->client->timezone()->name)->startOfDay()->toDateString()); - + default: return null; } diff --git a/app/Utils/Traits/MakesTemplateData.php b/app/Utils/Traits/MakesTemplateData.php index f48dcc244a..293eadd2ff 100644 --- a/app/Utils/Traits/MakesTemplateData.php +++ b/app/Utils/Traits/MakesTemplateData.php @@ -1,4 +1,5 @@ clearChromiumArguments(); - // $pdf->addChromiumArguments(config('ninja.snappdf_chromium_arguments')); - $pdf->addChromiumArguments(implode(' ', $chrome_flags)); + // $pdf->clearChromiumArguments(); + // $pdf->addChromiumArguments(config('ninja.snappdf_chromium_arguments')); + $pdf->addChromiumArguments(implode(' ', $chrome_flags)); // } if (config('ninja.snappdf_chromium_path')) { @@ -91,7 +91,7 @@ trait PdfMaker } $html = str_ireplace(['file:/', 'iframe', '', '/etc/'], '', $html); -// nlog($html); + // nlog($html); $generated = $pdf ->setHtml($html) ->generate(); diff --git a/app/Utils/Traits/Recurring/HasRecurrence.php b/app/Utils/Traits/Recurring/HasRecurrence.php index 8288ab1683..4787129376 100644 --- a/app/Utils/Traits/Recurring/HasRecurrence.php +++ b/app/Utils/Traits/Recurring/HasRecurrence.php @@ -1,4 +1,5 @@ getId()) ?? false; - if(!$context){ + if (!$context) { usleep(300000); //@monitor - inject delay to catch delays in cache updating $context = \Illuminate\Support\Facades\Cache::get(session()->getId()) ?? []; } - + return $context; } @@ -63,7 +63,7 @@ trait WithSecureContext $this->dispatch(self::CONTEXT_UPDATE); return $clone; - + } public function resetContext(): void diff --git a/app/Utils/TranslationHelper.php b/app/Utils/TranslationHelper.php index 0dd97aa3de..d57d59e9a2 100644 --- a/app/Utils/TranslationHelper.php +++ b/app/Utils/TranslationHelper.php @@ -1,4 +1,5 @@ '', 'label' => ctrans('texts.item')]; $data['$description'] = ['value' => '', 'label' => ctrans('texts.description')]; - $data['$entity_footer'] = ['value' => Helpers::processReservedKeywords(\nl2br($this->entity->footer ??''), $this->company), 'label' => '']; + $data['$entity_footer'] = ['value' => Helpers::processReservedKeywords(\nl2br($this->entity->footer ?? ''), $this->company), 'label' => '']; $data['$footer'] = &$data['$entity_footer']; $data['$page_size'] = ['value' => $this->settings->page_size, 'label' => ''];