1
0
mirror of https://github.com/invoiceninja/invoiceninja.git synced 2024-11-14 15:13:29 +01:00
invoiceninja/app/Services/Client/Statement.php

421 lines
13 KiB
PHP
Raw Normal View History

2021-09-14 13:55:24 +02:00
<?php
/**
* Invoice Ninja (https://invoiceninja.com).
*
* @link https://github.com/invoiceninja/invoiceninja source repository
*
2023-01-28 23:21:40 +01:00
* @copyright Copyright (c) 2023. Invoice Ninja LLC (https://invoiceninja.com)
2021-09-14 13:55:24 +02:00
*
* @license https://www.elastic.co/licensing/elastic-license
*/
namespace App\Services\Client;
2021-09-16 15:04:24 +02:00
use App\Factory\InvoiceFactory;
use App\Factory\InvoiceInvitationFactory;
use App\Factory\InvoiceItemFactory;
2021-09-14 13:55:24 +02:00
use App\Models\Client;
use App\Models\Design;
use App\Models\Invoice;
use App\Models\Payment;
use App\Services\PdfMaker\Design as PdfMakerDesign;
use App\Services\PdfMaker\PdfMaker;
use App\Utils\HostedPDF\NinjaPdf;
use App\Utils\HtmlEngine;
use App\Utils\Number;
use App\Utils\PhantomJS\Phantom;
use App\Utils\Traits\Pdf\PdfMaker as PdfMakerTrait;
2021-12-19 05:58:59 +01:00
use Illuminate\Support\Carbon;
2023-01-17 09:42:34 +01:00
use Illuminate\Support\Facades\DB;
use App\Models\Credit;
2021-09-14 13:55:24 +02:00
class Statement
{
use PdfMakerTrait;
/**
* @var Invoice|Payment|null
*/
protected $entity;
2021-09-16 15:04:24 +02:00
protected bool $rollback = false;
2023-02-16 02:36:09 +01:00
public function __construct(protected Client $client, public array $options)
{
}
2021-09-14 13:55:24 +02:00
2023-01-17 01:00:12 +01:00
public function run() :?string
2021-09-14 13:55:24 +02:00
{
2021-09-15 17:21:31 +02:00
$this
->setupOptions()
->setupEntity();
2021-09-14 13:55:24 +02:00
$html = new HtmlEngine($this->getInvitation());
if ($this->getDesign()->is_custom) {
$this->options['custom_partials'] = \json_decode(\json_encode($this->getDesign()->design), true);
$template = new PdfMakerDesign(\App\Services\PdfMaker\Design::CUSTOM, $this->options);
} else {
$template = new PdfMakerDesign(strtolower($this->getDesign()->name), $this->options);
}
$variables = $html->generateLabelsAndValues();
$variables['values']['$show_paid_stamp'] = 'none'; //do not show paid stamp on statement
2021-09-14 13:55:24 +02:00
$state = [
'template' => $template->elements([
'client' => $this->client,
2021-09-14 13:55:24 +02:00
'entity' => $this->entity,
'pdf_variables' => (array) $this->entity->company->settings->pdf_variables,
2021-09-14 13:55:24 +02:00
'$product' => $this->getDesign()->design->product,
'variables' => $variables,
'invoices' => $this->getInvoices(),
'payments' => $this->getPayments(),
'credits' => $this->getCredits(),
2021-09-14 13:55:24 +02:00
'aging' => $this->getAging(),
], \App\Services\PdfMaker\Design::STATEMENT),
'variables' => $variables,
'options' => [],
'process_markdown' => $this->entity->client->company->markdown_enabled,
];
$maker = new PdfMaker($state);
$maker
->design($template)
->build();
$pdf = null;
try {
if (config('ninja.phantomjs_pdf_generation') || config('ninja.pdf_generator') == 'phantom') {
$pdf = (new Phantom)->convertHtmlToPdf($maker->getCompiledHTML(true));
} elseif (config('ninja.invoiceninja_hosted_pdf_generation') || config('ninja.pdf_generator') == 'hosted_ninja') {
$pdf = (new NinjaPdf())->build($maker->getCompiledHTML(true));
} else {
$pdf = $this->makePdf(null, null, $maker->getCompiledHTML(true));
}
} catch (\Exception $e) {
nlog(print_r($e->getMessage(), 1));
}
2021-09-16 15:04:24 +02:00
if ($this->rollback) {
2021-12-18 22:54:38 +01:00
\DB::connection(config('database.default'))->rollBack();
2021-09-16 15:04:24 +02:00
}
2022-11-01 11:20:28 +01:00
$maker = null;
$state = null;
2023-01-17 01:00:12 +01:00
2021-09-14 13:55:24 +02:00
return $pdf;
}
/**
* Setup correct entity instance.
*
* @return Statement
*/
protected function setupEntity(): self
{
if ($this->getInvoices()->count() >= 1) {
2021-09-14 13:55:24 +02:00
$this->entity = $this->getInvoices()->first();
}
2021-09-16 15:04:24 +02:00
if (\is_null($this->entity)) {
2023-01-17 09:42:34 +01:00
DB::connection(config('database.default'))->beginTransaction();
2021-12-18 22:54:38 +01:00
2021-09-16 15:04:24 +02:00
$this->rollback = true;
$invoice = InvoiceFactory::create($this->client->company->id, $this->client->user->id);
$invoice->client_id = $this->client->id;
$invoice->line_items = $this->buildLineItems();
$invoice->save();
$invitation = InvoiceInvitationFactory::create($invoice->company_id, $invoice->user_id);
$invitation->invoice_id = $invoice->id;
$invitation->client_contact_id = $this->client->contacts->first()->id;
$invitation->save();
$this->entity = $invoice;
}
2021-09-14 13:55:24 +02:00
return $this;
}
2021-09-16 15:04:24 +02:00
protected function buildLineItems($count = 1)
{
$line_items = [];
for ($x = 0; $x < $count; $x++) {
$item = InvoiceItemFactory::create();
$item->quantity = 1;
//$item->cost = 10;
if (rand(0, 1)) {
$item->tax_name1 = 'GST';
$item->tax_rate1 = 10.00;
}
if (rand(0, 1)) {
$item->tax_name1 = 'VAT';
$item->tax_rate1 = 17.50;
}
if (rand(0, 1)) {
$item->tax_name1 = 'Sales Tax';
$item->tax_rate1 = 5;
}
//$product = Product::first();
$product = new \stdClass;
$item->cost = (float) 10;
$item->product_key = 'test';
$item->notes = 'test notes';
$item->custom_value1 = 'custom value1';
$item->custom_value2 = 'custom value2';
$item->custom_value3 = 'custom value3';
$item->custom_value4 = 'custom value4';
2021-09-16 15:04:24 +02:00
$line_items[] = $item;
}
return $line_items;
}
2021-09-14 13:55:24 +02:00
/**
* Setup & prepare options.
*
* @return Statement
*/
protected function setupOptions(): self
{
2021-09-15 17:21:31 +02:00
if (! \array_key_exists('start_date', $this->options)) {
2021-09-14 13:55:24 +02:00
$this->options['start_date'] = now()->startOfYear()->format('Y-m-d');
}
2021-09-15 17:21:31 +02:00
if (! \array_key_exists('end_date', $this->options)) {
2021-09-14 13:55:24 +02:00
$this->options['end_date'] = now()->format('Y-m-d');
}
2021-09-15 17:21:31 +02:00
if (! \array_key_exists('show_payments_table', $this->options)) {
2021-09-14 13:55:24 +02:00
$this->options['show_payments_table'] = false;
}
2021-09-15 17:21:31 +02:00
if (! \array_key_exists('show_aging_table', $this->options)) {
2021-09-14 13:55:24 +02:00
$this->options['show_aging_table'] = false;
}
if (! \array_key_exists('show_credits_table', $this->options)) {
$this->options['show_credits_table'] = false;
}
if (!\array_key_exists('only_clients_with_invoices', $this->options)) {
$this->options['only_clients_with_invoices'] = false;
}
2021-09-14 13:55:24 +02:00
return $this;
}
/**
* The collection of invoices for the statement.
*
* @return Invoice[]|\Illuminate\Support\LazyCollection
2021-09-14 13:55:24 +02:00
*/
public function getInvoices(): \Illuminate\Support\LazyCollection
2021-09-14 13:55:24 +02:00
{
return Invoice::withTrashed()
2022-06-22 06:26:10 +02:00
->with('payments.type')
2021-10-13 08:29:23 +02:00
->where('is_deleted', false)
->where('company_id', $this->client->company_id)
2021-09-14 13:55:24 +02:00
->where('client_id', $this->client->id)
->whereIn('status_id', $this->invoiceStatuses())
->whereBetween('date', [Carbon::parse($this->options['start_date']), Carbon::parse($this->options['end_date'])])
2022-04-19 01:56:26 +02:00
->orderBy('due_date', 'ASC')
->orderBy('date', 'ASC')
->cursor();
2021-09-14 13:55:24 +02:00
}
private function invoiceStatuses() :array
{
$status = 'all';
2022-01-11 10:01:03 +01:00
if (array_key_exists('status', $this->options)) {
$status = $this->options['status'];
}
switch ($status) {
case 'all':
return [Invoice::STATUS_SENT, Invoice::STATUS_PARTIAL, Invoice::STATUS_PAID];
2023-05-01 00:07:41 +02:00
case 'paid':
2022-05-13 09:20:16 +02:00
return [Invoice::STATUS_PAID];
2023-05-01 00:07:41 +02:00
case 'unpaid':
2022-05-13 09:20:16 +02:00
return [Invoice::STATUS_SENT, Invoice::STATUS_PARTIAL];
2023-05-01 00:07:41 +02:00
default:
return [Invoice::STATUS_SENT, Invoice::STATUS_PARTIAL, Invoice::STATUS_PAID];
2023-05-01 00:07:41 +02:00
}
}
2021-09-14 13:55:24 +02:00
/**
* The collection of payments for the statement.
*
* @return Payment[]|\Illuminate\Support\LazyCollection
2021-09-14 13:55:24 +02:00
*/
2021-12-19 05:58:59 +01:00
protected function getPayments(): \Illuminate\Support\LazyCollection
2021-09-14 13:55:24 +02:00
{
return Payment::withTrashed()
->with('client.country', 'invoices')
2021-10-13 08:29:23 +02:00
->where('is_deleted', false)
->where('company_id', $this->client->company_id)
2021-09-14 13:55:24 +02:00
->where('client_id', $this->client->id)
->whereIn('status_id', [Payment::STATUS_COMPLETED, Payment::STATUS_PARTIALLY_REFUNDED, Payment::STATUS_REFUNDED])
->whereBetween('date', [Carbon::parse($this->options['start_date']), Carbon::parse($this->options['end_date'])])
->orderBy('date', 'ASC')
->cursor();
2021-09-14 13:55:24 +02:00
}
/**
* The collection of credits for the statement.
*
* @return Credit[]|\Illuminate\Support\LazyCollection
*/
protected function getCredits(): \Illuminate\Support\LazyCollection
{
return Credit::withTrashed()
->with('client.country', 'invoices')
->where('is_deleted', false)
->where('company_id', $this->client->company_id)
->where('client_id', $this->client->id)
->whereIn('status_id', [Credit::STATUS_SENT, Credit::STATUS_PARTIAL, Credit::STATUS_APPLIED])
->whereBetween('date', [Carbon::parse($this->options['start_date']), Carbon::parse($this->options['end_date'])])
->where(function ($query) {
$query->whereDate('due_date', '>=', $this->options['end_date'])
->orWhereNull('due_date');
})
->orderBy('date', 'ASC')
->cursor();
}
2021-09-14 13:55:24 +02:00
/**
* Get correct invitation ID.
*
* @return int|bool
*/
protected function getInvitation()
{
if ($this->entity instanceof Invoice || $this->entity instanceof Payment) {
return $this->entity->invitations->first();
}
2021-09-16 15:04:24 +02:00
2021-09-14 13:55:24 +02:00
return false;
}
/**
* Get the array of aging data.
*
* @return array
*/
protected function getAging(): array
{
return [
'0-30' => $this->getAgingAmount('30'),
'30-60' => $this->getAgingAmount('60'),
'60-90' => $this->getAgingAmount('90'),
'90-120' => $this->getAgingAmount('120'),
'120+' => $this->getAgingAmount('120+'),
];
}
/**
* Generate aging amount.
*
* @param mixed $range
* @return string
*/
private function getAgingAmount($range)
{
$ranges = $this->calculateDateRanges($range);
2021-09-21 14:50:44 +02:00
2021-09-14 13:55:24 +02:00
$from = $ranges[0];
$to = $ranges[1];
2021-10-13 08:29:23 +02:00
$amount = Invoice::withTrashed()
->where('client_id', $this->client->id)
2021-09-21 14:45:28 +02:00
->where('company_id', $this->client->company_id)
2021-09-14 13:55:24 +02:00
->whereIn('status_id', [Invoice::STATUS_SENT, Invoice::STATUS_PARTIAL])
->where('balance', '>', 0)
2021-09-21 14:45:28 +02:00
->where('is_deleted', 0)
2021-10-12 23:43:38 +02:00
->whereBetween('due_date', [$to, $from])
2021-09-14 13:55:24 +02:00
->sum('balance');
return Number::formatMoney($amount, $this->client);
2021-09-14 13:55:24 +02:00
}
/**
* Calculate date ranges for aging.
*
* @param mixed $range
* @return array
*/
private function calculateDateRanges($range)
{
$ranges = [];
switch ($range) {
case '30':
2021-09-21 14:45:28 +02:00
$ranges[0] = now()->startOfDay();
$ranges[1] = now()->startOfDay()->subDays(30);
2021-09-14 13:55:24 +02:00
return $ranges;
case '60':
2023-06-09 06:52:59 +02:00
$ranges[0] = now()->startOfDay()->subDays(31);
2021-09-21 14:45:28 +02:00
$ranges[1] = now()->startOfDay()->subDays(60);
2021-09-14 13:55:24 +02:00
return $ranges;
case '90':
2023-06-09 06:52:59 +02:00
$ranges[0] = now()->startOfDay()->subDays(61);
2021-09-21 14:45:28 +02:00
$ranges[1] = now()->startOfDay()->subDays(90);
2021-09-14 13:55:24 +02:00
return $ranges;
case '120':
2023-06-09 06:52:59 +02:00
$ranges[0] = now()->startOfDay()->subDays(91);
2021-09-21 14:45:28 +02:00
$ranges[1] = now()->startOfDay()->subDays(120);
2021-09-14 13:55:24 +02:00
return $ranges;
case '120+':
2023-06-09 06:52:59 +02:00
$ranges[0] = now()->startOfDay()->subDays(121);
2021-10-12 23:43:38 +02:00
$ranges[1] = now()->startOfDay()->subYears(20);
2021-09-14 13:55:24 +02:00
return $ranges;
default:
2023-06-09 06:52:59 +02:00
$ranges[0] = now()->startOfDay();
$ranges[1] = now()->startOfDay()->subDays(30);
2021-09-14 13:55:24 +02:00
return $ranges;
}
}
/**
* Get correct design for statement.
*
* @return \App\Models\Design
*/
protected function getDesign(): Design
{
$id = 1;
if (! empty($this->client->getSetting('entity_design_id'))) {
2021-09-14 13:55:24 +02:00
$id = (int) $this->client->getSetting('entity_design_id');
}
return Design::withTrashed()->find($id);
2021-09-14 13:55:24 +02:00
}
}