1
0
mirror of https://github.com/invoiceninja/invoiceninja.git synced 2024-11-11 21:52:35 +01:00
invoiceninja/app/Services/Pdf/PdfBuilder.php

1748 lines
65 KiB
PHP
Raw Normal View History

2022-12-23 03:58:08 +01:00
<?php
/**
* Invoice Ninja (https://invoiceninja.com).
*
* @link https://github.com/invoiceninja/invoiceninja source repository
*
* @copyright Copyright (c) 2022. Invoice Ninja LLC (https://invoiceninja.com)
*
* @license https://www.elastic.co/licensing/elastic-license
*/
namespace App\Services\Pdf;
use App\Models\Credit;
2023-10-26 04:57:44 +02:00
use App\Models\Quote;
use App\Services\Template\TemplateService;
2022-12-28 09:31:43 +01:00
use App\Utils\Helpers;
use App\Utils\Traits\MakesDates;
2023-10-26 04:57:44 +02:00
use DOMDocument;
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;
2022-12-28 15:50:11 +01:00
use League\CommonMark\CommonMarkConverter;
2022-12-23 03:58:08 +01:00
class PdfBuilder
{
2022-12-27 16:44:12 +01:00
use MakesDates;
2022-12-23 03:58:08 +01:00
public PdfService $service;
2022-12-28 15:50:11 +01:00
private CommonMarkConverter $commonmark;
private float $payment_amount_total = 0;
2022-12-28 10:29:51 +01:00
/**
* an array of sections to be injected into the template
2023-02-21 08:39:07 +01:00
*
2022-12-28 10:29:51 +01:00
* @var array
*/
2022-12-27 16:44:12 +01:00
public array $sections = [];
2022-12-28 15:50:11 +01:00
/**
* The DOM Document;
*
*/
public DomDocument $document;
2022-12-28 10:29:51 +01:00
/**
2023-02-21 08:39:07 +01:00
* @param PdfService $service
* @return void
2022-12-28 10:29:51 +01:00
*/
2022-12-23 03:58:08 +01:00
public function __construct(PdfService $service)
{
$this->service = $service;
2022-12-28 15:50:11 +01:00
$this->commonmark = new CommonMarkConverter([
'allow_unsafe_links' => false,
]);
2022-12-23 03:58:08 +01:00
}
2022-12-28 10:29:51 +01:00
/**
* Builds the template sections
2023-02-21 08:39:07 +01:00
*
2022-12-28 10:29:51 +01:00
* @return self
2023-02-21 08:39:07 +01:00
*
2022-12-28 10:29:51 +01:00
*/
public function build(): self
2022-12-23 03:58:08 +01:00
{
$this->getTemplate()
2022-12-28 15:50:11 +01:00
->buildSections()
2022-12-28 10:29:51 +01:00
->getEmptyElements()
->updateElementProperties()
->parseTwigElements()
2022-12-28 10:29:51 +01:00
->updateVariables();
return $this;
}
2022-12-23 03:58:08 +01:00
2023-10-26 04:57:44 +02:00
/**
* Final method to get compiled HTML.
*
* @param bool $final @deprecated // is it? i still see it being called elsewhere
* @return string
*/
2022-12-28 10:29:51 +01:00
public function getCompiledHTML($final = false)
{
$html = $this->document->saveHTML();
return str_replace('%24', '$', $html);
2022-12-23 03:58:08 +01:00
}
2022-12-28 10:29:51 +01:00
/**
* Generate the template
2023-02-21 08:39:07 +01:00
*
2022-12-28 10:29:51 +01:00
* @return self
2023-02-21 08:39:07 +01:00
*
2022-12-28 10:29:51 +01:00
*/
2022-12-23 03:58:08 +01:00
private function getTemplate() :self
{
$document = new DOMDocument();
$document->validateOnParse = true;
2022-12-28 11:28:58 +01:00
@$document->loadHTML(mb_convert_encoding($this->service->designer->template, 'HTML-ENTITIES', 'UTF-8'));
2022-12-23 03:58:08 +01:00
$this->document = $document;
2022-12-28 11:28:58 +01:00
2023-07-10 14:52:03 +02:00
return $this;
}
private function parseTwigElements()
{
$replacements = [];
$contents = $this->document->getElementsByTagName('ninja');
$template_service = new TemplateService();
$data = $template_service->processData($this->service->options)->getData();
$twig = $template_service->twig;
foreach ($contents as $content) {
$template = $content->ownerDocument->saveHTML($content);
$template = $twig->createTemplate(html_entity_decode($template));
$template = $template->render($data);
$f = $this->document->createDocumentFragment();
$f->appendXML($template);
$replacements[] = $f;
}
foreach($contents as $key => $content) {
$content->parentNode->replaceChild($replacements[$key], $content);
}
$contents = null;
return $this;
}
2023-07-10 14:52:03 +02:00
public function setDocument($document): self
{
$this->document = $document;
2022-12-23 03:58:08 +01:00
return $this;
}
2022-12-28 10:29:51 +01:00
/**
* Generates product entity sections
2023-02-21 08:39:07 +01:00
*
2022-12-28 10:29:51 +01:00
* @return self
2023-02-21 08:39:07 +01:00
*
2022-12-28 10:29:51 +01:00
*/
2022-12-27 16:44:12 +01:00
private function getProductSections(): self
2022-12-23 03:58:08 +01:00
{
2022-12-27 16:44:12 +01:00
$this->genericSectionBuilder()
->getClientDetails()
->getProductAndTaskTables()
->getProductEntityDetails()
->getProductTotals();
2022-12-28 09:31:43 +01:00
2023-02-21 08:39:07 +01:00
return $this;
2022-12-27 16:44:12 +01:00
}
2022-12-28 11:28:58 +01:00
private function mergeSections(array $section) :self
{
$this->sections = array_merge($this->sections, $section);
return $this;
}
2023-07-10 14:52:03 +02:00
public function setSections($sections): self
{
$this->sections = $sections;
return $this;
}
2022-12-28 10:29:51 +01:00
/**
* Generates delivery note sections
2023-02-21 08:39:07 +01:00
*
2022-12-28 10:29:51 +01:00
* @return self
2023-02-21 08:39:07 +01:00
*
2022-12-28 10:29:51 +01:00
*/
2022-12-27 16:44:12 +01:00
private function getDeliveryNoteSections(): self
{
2022-12-28 09:31:43 +01:00
$this->genericSectionBuilder()
->getProductTotals();
2023-02-21 08:39:07 +01:00
$this->mergeSections([
2022-12-23 03:58:08 +01:00
'client-details' => [
'id' => 'client-details',
2022-12-27 16:44:12 +01:00
'elements' => $this->clientDeliveryDetails(),
],
'delivery-note-table' => [
'id' => 'delivery-note-table',
'elements' => $this->deliveryNoteTable(),
],
'entity-details' => [
'id' => 'entity-details',
'elements' => $this->deliveryNoteDetails(),
2022-12-23 03:58:08 +01:00
],
2022-12-28 11:28:58 +01:00
]);
2022-12-27 16:44:12 +01:00
return $this;
}
2022-12-28 10:29:51 +01:00
/**
* Generates statement sections
2023-02-21 08:39:07 +01:00
*
2022-12-28 10:29:51 +01:00
* @return self
2023-02-21 08:39:07 +01:00
*
2022-12-28 10:29:51 +01:00
*/
2022-12-27 16:44:12 +01:00
private function getStatementSections(): self
{
2022-12-28 09:31:43 +01:00
$this->genericSectionBuilder();
2023-02-21 08:39:07 +01:00
$this->mergeSections([
2022-12-28 09:31:43 +01:00
'statement-invoice-table' => [
'id' => 'statement-invoice-table',
'elements' => $this->statementInvoiceTable(),
],
'statement-invoice-table-totals' => [
'id' => 'statement-invoice-table-totals',
'elements' => $this->statementInvoiceTableTotals(),
],
'statement-payment-table' => [
'id' => 'statement-payment-table',
'elements' => $this->statementPaymentTable(),
],
'statement-payment-table-totals' => [
'id' => 'statement-payment-table-totals',
'elements' => $this->statementPaymentTableTotals(),
],
'statement-credits-table' => [
'id' => 'statement-credits-table',
'elements' => $this->statementCreditTable(),
],
'statement-credit-table-totals' => [
'id' => 'statement-credit-table-totals',
'elements' => $this->statementCreditTableTotals(),
],
2022-12-28 09:31:43 +01:00
'statement-aging-table' => [
'id' => 'statement-aging-table',
'elements' => $this->statementAgingTable(),
],
'table-totals' => [
'id' => 'table-totals',
'elements' => $this->statementTableTotals(),
],
2022-12-28 11:28:58 +01:00
]);
2022-12-28 09:31:43 +01:00
return $this;
2022-12-27 16:44:12 +01:00
}
2022-12-28 10:29:51 +01:00
/**
* Parent method for building invoice table totals
* for statements.
*
* @return array
*/
2022-12-28 09:31:43 +01:00
public function statementInvoiceTableTotals(): array
{
$outstanding = $this->service->options['invoices']->sum('balance');
return [
2023-02-23 21:27:27 +01:00
['element' => 'p', 'content' => '$outstanding_label: ' . $this->service->config->formatMoney($outstanding)],
2022-12-28 09:31:43 +01:00
];
}
/**
* Parent method for building payments table within statement.
*
* @return array
*/
public function statementCreditTable(): array
{
if (is_null($this->service->options['credits'])) {
return [];
}
if (\array_key_exists('show_credits_table', $this->service->options) && $this->service->options['show_credits_table'] === false) {
return [];
}
$tbody = [];
foreach ($this->service->options['credits'] as $credit) {
$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) ?: ' '];
$tbody[] = $element;
}
return [
['element' => 'thead', 'elements' => $this->buildTableHeader('statement_invoice')],
['element' => 'tbody', 'elements' => $tbody],
];
}
/**
* Parent method for building invoice table totals
* for statements.
*
* @return array
*/
public function statementCreditTableTotals(): array
{
$outstanding = $this->service->options['credits']->sum('balance');
return [
['element' => 'p', 'content' => '$credit.balance_label: ' . $this->service->config->formatMoney($outstanding)],
];
}
2022-12-28 09:31:43 +01:00
/**
* Parent method for building payments table within statement.
*
* @return array
*/
public function statementPaymentTable(): array
{
2023-02-23 12:08:15 +01:00
if (is_null($this->service->options['payments'])) {
2022-12-28 09:31:43 +01:00
return [];
}
if (\array_key_exists('show_payments_table', $this->service->options) && $this->service->options['show_payments_table'] === false) {
return [];
}
$tbody = [];
//24-03-2022 show payments per invoice
foreach ($this->service->options['invoices'] as $invoice) {
foreach ($invoice->payments as $payment) {
2023-02-21 08:39:07 +01:00
if ($payment->is_deleted) {
2022-12-28 09:31:43 +01:00
continue;
2023-02-21 08:39:07 +01:00
}
2022-12-28 09:31:43 +01:00
$element = ['element' => 'tr', 'elements' => []];
$element['elements'][] = ['element' => 'td', 'content' => $invoice->number];
2023-02-23 13:01:18 +01:00
$element['elements'][] = ['element' => 'td', 'content' => $this->translateDate($payment->date, $this->service->config->date_format, $this->service->config->locale) ?: '&nbsp;'];
2023-03-10 07:49:43 +01:00
$element['elements'][] = ['element' => 'td', 'content' => $payment->translatedType()];
2023-02-23 13:01:18 +01:00
$element['elements'][] = ['element' => 'td', 'content' => $this->service->config->formatMoney($payment->pivot->amount) ?: '&nbsp;'];
2022-12-28 09:31:43 +01:00
$tbody[] = $element;
$this->payment_amount_total += $payment->pivot->amount;
2022-12-28 09:31:43 +01:00
}
}
return [
['element' => 'thead', 'elements' => $this->buildTableHeader('statement_payment')],
['element' => 'tbody', 'elements' => $tbody],
];
}
2022-12-28 10:29:51 +01:00
/**
* Generates the statement payments table
2023-02-21 08:39:07 +01:00
*
2022-12-28 10:29:51 +01:00
* @return array
2023-02-21 08:39:07 +01:00
*
2022-12-28 10:29:51 +01:00
*/
2022-12-28 09:31:43 +01:00
public function statementPaymentTableTotals(): array
{
if (is_null($this->service->options['payments']) || !$this->service->options['payments']->first()) {
return [];
}
if (\array_key_exists('show_payments_table', $this->service->options) && $this->service->options['show_payments_table'] === false) {
return [];
}
$payment = $this->service->options['payments']->first();
return [
2023-02-23 21:27:27 +01:00
['element' => 'p', 'content' => \sprintf('%s: %s', ctrans('texts.amount_paid'), $this->service->config->formatMoney($this->payment_amount_total))],
2023-03-10 07:49:43 +01:00
['element' => 'p', 'content' => \sprintf('%s: %s', ctrans('texts.payment_method'), $payment->translatedType())],
2023-02-23 21:27:27 +01:00
['element' => 'p', 'content' => \sprintf('%s: %s', ctrans('texts.payment_date'), $this->translateDate($payment->date, $this->service->config->date_format, $this->service->config->locale) ?: '&nbsp;')],
2022-12-28 09:31:43 +01:00
];
}
2022-12-28 10:29:51 +01:00
/**
* Generates the statement aging table
2023-02-21 08:39:07 +01:00
*
2022-12-28 10:29:51 +01:00
* @return array
2023-02-21 08:39:07 +01:00
*
2022-12-28 10:29:51 +01:00
*/
2022-12-28 09:31:43 +01:00
public function statementAgingTable(): array
{
if (\array_key_exists('show_aging_table', $this->service->options) && $this->service->options['show_aging_table'] === false) {
return [];
}
$elements = [
['element' => 'thead', 'elements' => []],
['element' => 'tbody', 'elements' => [
['element' => 'tr', 'elements' => []],
]],
];
foreach ($this->service->options['aging'] as $column => $value) {
$elements[0]['elements'][] = ['element' => 'th', 'content' => $column];
$elements[1]['elements'][] = ['element' => 'td', 'content' => $value];
}
return $elements;
}
/**
* Generates the statement aging table
*
* @return array
*
*/
public function statementCreditsTable(): array
{
if (\array_key_exists('show_credits_table', $this->service->options) && $this->service->options['show_credits_table'] === false) {
return [];
}
$elements = [
['element' => 'thead', 'elements' => []],
['element' => 'tbody', 'elements' => [
['element' => 'tr', 'elements' => []],
]],
];
foreach ($this->service->options['credits'] as $column => $value) {
$elements[0]['elements'][] = ['element' => 'th', 'content' => $column];
$elements[1]['elements'][] = ['element' => 'td', 'content' => $value];
}
return $elements;
}
2022-12-28 10:29:51 +01:00
/**
* Generates the purchase order sections
2023-02-21 08:39:07 +01:00
*
2022-12-28 10:29:51 +01:00
* @return self
2023-02-21 08:39:07 +01:00
*
2022-12-28 10:29:51 +01:00
*/
2022-12-27 16:44:12 +01:00
private function getPurchaseOrderSections(): self
{
2022-12-28 09:31:43 +01:00
$this->genericSectionBuilder()
->getProductAndTaskTables()
2022-12-28 09:31:43 +01:00
->getProductTotals();
2023-02-21 08:39:07 +01:00
$this->mergeSections([
2022-12-23 03:58:08 +01:00
'vendor-details' => [
'id' => 'vendor-details',
'elements' => $this->vendorDetails(),
],
'entity-details' => [
'id' => 'entity-details',
2022-12-27 16:44:12 +01:00
'elements' => $this->purchaseOrderDetails(),
2022-12-23 03:58:08 +01:00
],
2022-12-28 11:28:58 +01:00
]);
2022-12-27 16:44:12 +01:00
return $this;
}
2022-12-28 10:29:51 +01:00
/**
* Generates the generic section which apply
* across all design templates
2023-02-21 08:39:07 +01:00
*
2022-12-28 10:29:51 +01:00
* @return self
2023-02-21 08:39:07 +01:00
*
2022-12-28 10:29:51 +01:00
*/
2022-12-27 16:44:12 +01:00
private function genericSectionBuilder(): self
{
2022-12-28 11:28:58 +01:00
$this->mergeSections([
2022-12-27 16:44:12 +01:00
'company-details' => [
'id' => 'company-details',
2022-12-28 10:29:51 +01:00
'elements' => $this->companyDetails(),
2022-12-27 16:44:12 +01:00
],
'company-address' => [
'id' => 'company-address',
2022-12-28 10:29:51 +01:00
'elements' => $this->companyAddress(),
2022-12-27 16:44:12 +01:00
],
'footer-elements' => [
'id' => 'footer',
'elements' => [
$this->sharedFooterElements(),
],
2022-12-23 03:58:08 +01:00
],
2022-12-28 11:28:58 +01:00
]);
2022-12-27 16:44:12 +01:00
return $this;
}
2022-12-28 10:29:51 +01:00
/**
* Generates the invoices table for statements
2023-02-21 08:39:07 +01:00
*
2022-12-28 10:29:51 +01:00
* @return array
2023-02-21 08:39:07 +01:00
*
2022-12-28 10:29:51 +01:00
*/
2022-12-28 09:31:43 +01:00
public function statementInvoiceTable(): array
{
$tbody = [];
foreach ($this->service->options['invoices'] as $invoice) {
$element = ['element' => 'tr', 'elements' => []];
$element['elements'][] = ['element' => 'td', 'content' => $invoice->number];
2023-02-23 13:01:18 +01:00
$element['elements'][] = ['element' => 'td', 'content' => $this->translateDate($invoice->date, $this->service->config->client->date_format(), $this->service->config->locale) ?: ' '];
$element['elements'][] = ['element' => 'td', 'content' => $this->translateDate($invoice->due_date, $this->service->config->client->date_format(), $this->service->config->locale) ?: ' '];
2023-02-23 21:27:27 +01:00
$element['elements'][] = ['element' => 'td', 'content' => $this->service->config->formatMoney($invoice->amount) ?: ' '];
$element['elements'][] = ['element' => 'td', 'content' => $this->service->config->formatMoney($invoice->balance) ?: ' '];
2022-12-28 09:31:43 +01:00
$tbody[] = $element;
}
return [
['element' => 'thead', 'elements' => $this->buildTableHeader('statement_invoice')],
['element' => 'tbody', 'elements' => $tbody],
];
}
/**
* Generate the structure of table body. (<tbody/>)
*
* @param string $type "$product" or "$task"
* @return array
2023-02-21 08:39:07 +01:00
*
2022-12-28 09:31:43 +01:00
*/
public function buildTableBody(string $type): array
{
$elements = [];
2022-12-28 11:28:58 +01:00
$items = $this->transformLineItems($this->service->config->entity->line_items, $type);
2022-12-28 09:31:43 +01:00
$this->processNewLines($items);
if (count($items) == 0) {
return [];
}
if ($type == PdfService::DELIVERY_NOTE) {
$product_customs = [false, false, false, false];
foreach ($items as $row) {
for ($i = 0; $i < count($product_customs); $i++) {
if (!empty($row['delivery_note.delivery_note' . ($i + 1)])) {
$product_customs[$i] = true;
}
}
}
foreach ($items as $row) {
$element = ['element' => 'tr', 'elements' => []];
$element['elements'][] = ['element' => 'td', 'content' => $row['delivery_note.product_key'], 'properties' => ['data-ref' => 'delivery_note_table.product_key-td']];
$element['elements'][] = ['element' => 'td', 'content' => $row['delivery_note.notes'], 'properties' => ['data-ref' => 'delivery_note_table.notes-td']];
$element['elements'][] = ['element' => 'td', 'content' => $row['delivery_note.quantity'], 'properties' => ['data-ref' => 'delivery_note_table.quantity-td']];
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']];
}
}
$elements[] = $element;
}
return $elements;
}
2023-03-15 04:22:12 +01:00
$_type = Str::startsWith($type, '$') ? ltrim($type, '$') : $type;
$table_type = "{$_type}_columns";
if ($_type == 'product' && $this->service->config->entity instanceof Quote && !$this->service->config->settings?->sync_invoice_quote_columns) {
$table_type = "product_quote_columns";
}
2022-12-28 09:31:43 +01:00
foreach ($items as $row) {
$element = ['element' => 'tr', 'elements' => []];
if (
2022-12-28 11:28:58 +01:00
array_key_exists($type, $this->service->options) &&
!empty($this->service->options[$type]) &&
!is_null($this->service->options[$type])
2022-12-28 09:31:43 +01:00
) {
$document = new DOMDocument();
2022-12-28 11:28:58 +01:00
$document->loadHTML($this->service->options[$type], LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
2022-12-28 09:31:43 +01:00
$td = $document->getElementsByTagName('tr')->item(0);
if ($td) {
foreach ($td->childNodes as $child) {
if ($child->nodeType !== 1) {
continue;
}
if ($child->tagName !== 'td') {
continue;
}
$element['elements'][] = ['element' => 'td', 'content' => strtr($child->nodeValue, $row)];
}
}
} else {
$_type = Str::startsWith($type, '$') ? ltrim($type, '$') : $type;
2022-12-28 10:29:51 +01:00
foreach ($this->service->config->pdf_variables["{$_type}_columns"] as $key => $cell) {
2022-12-28 09:31:43 +01:00
// We want to keep aliases like these:
// $task.cost => $task.rate
// $task.quantity => $task.hours
if ($cell == '$task.rate') {
$element['elements'][] = ['element' => 'td', 'content' => $row['$task.cost'], 'properties' => ['data-ref' => 'task_table-task.cost-td']];
} elseif ($cell == '$product.discount' && !$this->service->company->enable_product_discount) {
$element['elements'][] = ['element' => 'td', 'content' => $row['$product.discount'], 'properties' => ['data-ref' => 'product_table-product.discount-td', 'style' => 'display: none;']];
} elseif ($cell == '$product.quantity' && !$this->service->company->enable_product_quantity) {
$element['elements'][] = ['element' => 'td', 'content' => $row['$product.quantity'], 'properties' => ['data-ref' => 'product_table-product.quantity-td', 'style' => 'display: none;']];
} elseif ($cell == '$task.hours') {
$element['elements'][] = ['element' => 'td', 'content' => $row['$task.quantity'], 'properties' => ['data-ref' => 'task_table-task.hours-td']];
} elseif ($cell == '$product.tax_rate1') {
$element['elements'][] = ['element' => 'td', 'content' => $row[$cell], 'properties' => ['data-ref' => 'product_table-product.tax1-td']];
} elseif ($cell == '$product.tax_rate2') {
$element['elements'][] = ['element' => 'td', 'content' => $row[$cell], 'properties' => ['data-ref' => 'product_table-product.tax2-td']];
} elseif ($cell == '$product.tax_rate3') {
$element['elements'][] = ['element' => 'td', 'content' => $row[$cell], 'properties' => ['data-ref' => 'product_table-product.tax3-td']];
2023-02-21 08:39:07 +01:00
} elseif ($cell == '$product.unit_cost' || $cell == '$task.rate') {
2022-12-28 09:31:43 +01:00
$element['elements'][] = ['element' => 'td', 'content' => $row[$cell], 'properties' => ['style' => 'white-space: nowrap;', 'data-ref' => "{$_type}_table-" . substr($cell, 1) . '-td']];
} else {
$element['elements'][] = ['element' => 'td', 'content' => $row[$cell], 'properties' => ['data-ref' => "{$_type}_table-" . substr($cell, 1) . '-td']];
}
}
}
$elements[] = $element;
}
$document = null;
return $elements;
}
/**
* Formats the line items for display.
*
2023-08-06 04:20:18 +02:00
* @param array<\App\DataMapper\InvoiceItem> $items
2022-12-28 09:31:43 +01:00
* @param string $table_type
*
* @return array
*/
public function transformLineItems($items, $table_type = '$product') :array
2023-02-21 08:39:07 +01:00
{
2022-12-28 09:31:43 +01:00
$data = [];
$locale_info = localeconv();
2023-02-23 12:08:15 +01:00
// $this->service->config->entity_currency = $this->service->config->currency;
2022-12-28 09:31:43 +01:00
foreach ($items as $key => $item) {
if ($table_type == '$product' && $item->type_id != 1) {
if ($item->type_id != 4 && $item->type_id != 6 && $item->type_id != 5) {
continue;
}
}
if ($table_type == '$task' && $item->type_id != 2) {
// if ($item->type_id != 4 && $item->type_id != 5) {
2023-02-21 08:39:07 +01:00
continue;
2022-12-28 09:31:43 +01:00
// }
}
$helpers = new Helpers();
$_table_type = ltrim($table_type, '$'); // From $product -> product.
$data[$key][$table_type.'.product_key'] = is_null(optional($item)->product_key) ? $item->item : $item->product_key;
$data[$key][$table_type.'.item'] = is_null(optional($item)->item) ? $item->product_key : $item->item;
$data[$key][$table_type.'.service'] = is_null(optional($item)->service) ? $item->product_key : $item->service;
$currentDateTime = null;
2022-12-28 10:29:51 +01:00
if (isset($this->service->config->entity->next_send_date)) {
$currentDateTime = Carbon::parse($this->service->config->entity->next_send_date);
2022-12-28 09:31:43 +01:00
}
$data[$key][$table_type.'.notes'] = Helpers::processReservedKeywords($item->notes, $this->service->config->currency_entity, $currentDateTime);
$data[$key][$table_type.'.description'] = Helpers::processReservedKeywords($item->notes, $this->service->config->currency_entity, $currentDateTime);
$data[$key][$table_type.".{$_table_type}1"] = strlen($item->custom_value1) >= 1 ? $helpers->formatCustomFieldValue($this->service->company->custom_fields, "{$_table_type}1", $item->custom_value1, $this->service->config->currency_entity) : '';
$data[$key][$table_type.".{$_table_type}2"] = strlen($item->custom_value2) >= 1 ? $helpers->formatCustomFieldValue($this->service->company->custom_fields, "{$_table_type}2", $item->custom_value2, $this->service->config->currency_entity) : '';
$data[$key][$table_type.".{$_table_type}3"] = strlen($item->custom_value3) >= 1 ? $helpers->formatCustomFieldValue($this->service->company->custom_fields, "{$_table_type}3", $item->custom_value3, $this->service->config->currency_entity) : '';
$data[$key][$table_type.".{$_table_type}4"] = strlen($item->custom_value4) >= 1 ? $helpers->formatCustomFieldValue($this->service->company->custom_fields, "{$_table_type}4", $item->custom_value4, $this->service->config->currency_entity) : '';
if ($item->quantity > 0 || $item->cost > 0) {
2023-06-25 08:54:36 +02:00
$data[$key][$table_type.'.quantity'] = $item->quantity;
2022-12-28 09:31:43 +01:00
2023-02-25 02:08:34 +01:00
$data[$key][$table_type.'.unit_cost'] = $this->service->config->formatMoney($item->cost);
2022-12-28 09:31:43 +01:00
2023-02-23 21:27:27 +01:00
$data[$key][$table_type.'.cost'] = $this->service->config->formatMoney($item->cost);
2022-12-28 09:31:43 +01:00
2023-02-23 21:27:27 +01:00
$data[$key][$table_type.'.line_total'] = $this->service->config->formatMoney($item->line_total);
2022-12-28 09:31:43 +01:00
} else {
$data[$key][$table_type.'.quantity'] = '';
$data[$key][$table_type.'.unit_cost'] = '';
$data[$key][$table_type.'.cost'] = '';
$data[$key][$table_type.'.line_total'] = '';
}
if (property_exists($item, 'gross_line_total')) {
2023-02-23 21:27:27 +01:00
$data[$key][$table_type.'.gross_line_total'] = ($item->gross_line_total == 0) ? '' : $this->service->config->formatMoney($item->gross_line_total);
2022-12-28 09:31:43 +01:00
} else {
$data[$key][$table_type.'.gross_line_total'] = '';
}
if (property_exists($item, 'tax_amount')) {
2023-02-23 21:27:27 +01:00
$data[$key][$table_type.'.tax_amount'] = ($item->tax_amount == 0) ? '' : $this->service->config->formatMoney($item->tax_amount);
2022-12-28 09:31:43 +01:00
} else {
$data[$key][$table_type.'.tax_amount'] = '';
}
if (isset($item->discount) && $item->discount > 0) {
if ($item->is_amount_discount) {
2023-02-23 21:27:27 +01:00
$data[$key][$table_type.'.discount'] = $this->service->config->formatMoney($item->discount);
2022-12-28 09:31:43 +01:00
} else {
$data[$key][$table_type.'.discount'] = floatval($item->discount).'%';
}
} else {
$data[$key][$table_type.'.discount'] = '';
}
// Previously we used to check for tax_rate value,
// but that's no longer necessary.
if (isset($item->tax_rate1)) {
$data[$key][$table_type.'.tax_rate1'] = floatval($item->tax_rate1).'%';
$data[$key][$table_type.'.tax1'] = &$data[$key][$table_type.'.tax_rate1'];
}
if (isset($item->tax_rate2)) {
$data[$key][$table_type.'.tax_rate2'] = floatval($item->tax_rate2).'%';
$data[$key][$table_type.'.tax2'] = &$data[$key][$table_type.'.tax_rate2'];
}
if (isset($item->tax_rate3)) {
$data[$key][$table_type.'.tax_rate3'] = floatval($item->tax_rate3).'%';
$data[$key][$table_type.'.tax3'] = &$data[$key][$table_type.'.tax_rate3'];
}
$data[$key]['task_id'] = property_exists($item, 'task_id') ? $item->task_id : '';
}
//nlog(microtime(true) - $start);
return $data;
}
2023-10-26 04:57:44 +02:00
/**
* Generate the structure of table headers. (<thead/>)
*
* @param string $type "product" or "task"
* @return array
*
*/
2022-12-28 09:31:43 +01:00
public function buildTableHeader(string $type): array
{
$this->processTaxColumns($type);
$elements = [];
// Some of column can be aliased. This is simple workaround for these.
$aliases = [
'$product.product_key' => '$product.item',
'$task.product_key' => '$task.service',
'$task.rate' => '$task.cost',
];
2023-03-15 04:22:12 +01:00
$table_type = "{$type}_columns";
if ($type == 'product' && $this->service->config->entity instanceof Quote && !$this->service->config->settings_object?->sync_invoice_quote_columns) {
$table_type = "product_quote_columns";
}
foreach ($this->service->config->pdf_variables[$table_type] as $column) {
2022-12-28 09:31:43 +01:00
if (array_key_exists($column, $aliases)) {
2023-02-23 21:27:27 +01:00
$elements[] = ['element' => 'th', 'content' => $aliases[$column] . '_label', 'properties' => ['data-ref' => "{$type}_table-" . substr($aliases[$column], 1) . '-th', 'hidden' => $this->service->config->settings->hide_empty_columns_on_pdf]];
2022-12-28 09:31:43 +01:00
} elseif ($column == '$product.discount' && !$this->service->company->enable_product_discount) {
$elements[] = ['element' => 'th', 'content' => $column . '_label', 'properties' => ['data-ref' => "{$type}_table-" . substr($column, 1) . '-th', 'style' => 'display: none;']];
} elseif ($column == '$product.quantity' && !$this->service->company->enable_product_quantity) {
$elements[] = ['element' => 'th', 'content' => $column . '_label', 'properties' => ['data-ref' => "{$type}_table-" . substr($column, 1) . '-th', 'style' => 'display: none;']];
} elseif ($column == '$product.tax_rate1') {
2023-02-23 21:27:27 +01:00
$elements[] = ['element' => 'th', 'content' => $column . '_label', 'properties' => ['data-ref' => "{$type}_table-product.tax1-th", 'hidden' => $this->service->config->settings->hide_empty_columns_on_pdf]];
2022-12-28 09:31:43 +01:00
} elseif ($column == '$product.tax_rate2') {
2023-02-23 21:27:27 +01:00
$elements[] = ['element' => 'th', 'content' => $column . '_label', 'properties' => ['data-ref' => "{$type}_table-product.tax2-th", 'hidden' => $this->service->config->settings->hide_empty_columns_on_pdf]];
2022-12-28 09:31:43 +01:00
} elseif ($column == '$product.tax_rate3') {
2023-02-23 21:27:27 +01:00
$elements[] = ['element' => 'th', 'content' => $column . '_label', 'properties' => ['data-ref' => "{$type}_table-product.tax3-th", 'hidden' => $this->service->config->settings->hide_empty_columns_on_pdf]];
2022-12-28 09:31:43 +01:00
} else {
2023-02-23 21:27:27 +01:00
$elements[] = ['element' => 'th', 'content' => $column . '_label', 'properties' => ['data-ref' => "{$type}_table-" . substr($column, 1) . '-th', 'hidden' => $this->service->config->settings->hide_empty_columns_on_pdf]];
2022-12-28 09:31:43 +01:00
}
}
return $elements;
}
2023-01-11 14:16:53 +01:00
/**
2022-12-28 09:31:43 +01:00
* This method will help us decide either we show
* one "tax rate" column in the table or 3 custom tax rates.
*
* Logic below will help us calculate that & inject the result in the
* global state of the $context (design state).
*
* @param string $type "product" or "task"
* @return void
*/
public function processTaxColumns(string $type): void
{
if ($type == 'product') {
$type_id = 1;
}
if ($type == 'task') {
$type_id = 2;
}
// At the moment we pass "task" or "product" as type.
// However, "pdf_variables" contains "$task.tax" or "$product.tax" <-- Notice the dollar sign.
// This sprintf() will help us convert "task" or "product" into "$task" or "$product" without
// evaluating the variable.
if (in_array(sprintf('%s%s.tax', '$', $type), (array) $this->service->config->pdf_variables["{$type}_columns"])) {
$line_items = collect($this->service->config->entity->line_items)->filter(function ($item) use ($type_id) {
return $item->type_id = $type_id;
});
$tax1 = $line_items->where('tax_name1', '<>', '')->where('type_id', $type_id)->count();
$tax2 = $line_items->where('tax_name2', '<>', '')->where('type_id', $type_id)->count();
$tax3 = $line_items->where('tax_name3', '<>', '')->where('type_id', $type_id)->count();
$taxes = [];
if ($tax1 > 0) {
array_push($taxes, sprintf('%s%s.tax_rate1', '$', $type));
}
if ($tax2 > 0) {
array_push($taxes, sprintf('%s%s.tax_rate2', '$', $type));
}
if ($tax3 > 0) {
array_push($taxes, sprintf('%s%s.tax_rate3', '$', $type));
}
$key = array_search(sprintf('%s%s.tax', '$', $type), $this->service->config->pdf_variables["{$type}_columns"], true);
if ($key !== false) {
array_splice($this->service->config->pdf_variables["{$type}_columns"], $key, 1, $taxes);
}
}
}
2022-12-28 10:29:51 +01:00
/**
2023-02-21 08:39:07 +01:00
* Generates the javascript block for
2022-12-28 10:29:51 +01:00
* hiding elements which need to be hidden
2023-02-21 08:39:07 +01:00
*
2022-12-28 10:29:51 +01:00
* @return array
2023-02-21 08:39:07 +01:00
*
2022-12-28 10:29:51 +01:00
*/
2022-12-28 09:31:43 +01:00
public function sharedFooterElements(): array
{
// We want to show headers for statements, no exceptions.
$statements = "
document.querySelectorAll('#statement-invoice-table > thead > tr > th, #statement-payment-table > thead > tr > th, #statement-aging-table > thead > tr > th').forEach(t => {
t.hidden = false;
});
";
$javascript = 'document.addEventListener("DOMContentLoaded",function(){document.querySelectorAll("#product-table > tbody > tr > td, #task-table > tbody > tr > td, #delivery-note-table > tbody > tr > td").forEach(t=>{if(""!==t.innerText){let e=t.getAttribute("data-ref").slice(0,-3);document.querySelector(`th[data-ref="${e}-th"]`).removeAttribute("hidden")}}),document.querySelectorAll("#product-table > tbody > tr > td, #task-table > tbody > tr > td, #delivery-note-table > tbody > tr > td").forEach(t=>{let e=t.getAttribute("data-ref").slice(0,-3);(e=document.querySelector(`th[data-ref="${e}-th"]`)).hasAttribute("hidden")&&""==t.innerText&&t.setAttribute("hidden","true")})},!1);';
// Previously we've been decoding the HTML on the backend and XML parsing isn't good options because it requires,
// strict & valid HTML to even output/decode. Decoding is now done on the frontend with this piece of Javascript.
$html_decode = 'document.addEventListener("DOMContentLoaded",function(){document.querySelectorAll(`[data-state="encoded-html"]`).forEach(e=>e.innerHTML=e.innerText)},!1);';
return ['element' => 'div', 'elements' => [
['element' => 'script', 'content' => $statements],
['element' => 'script', 'content' => $javascript],
['element' => 'script', 'content' => $html_decode],
]];
}
2022-12-28 10:29:51 +01:00
/**
2023-02-21 08:39:07 +01:00
* Generates the totals table for
2022-12-28 10:29:51 +01:00
* the product type entities
2023-02-21 08:39:07 +01:00
*
2022-12-28 10:29:51 +01:00
* @return self
2023-02-21 08:39:07 +01:00
*
2022-12-28 10:29:51 +01:00
*/
2022-12-27 16:44:12 +01:00
private function getProductTotals(): self
{
2023-02-21 08:39:07 +01:00
$this->mergeSections([
2022-12-27 16:44:12 +01:00
'table-totals' => [
'id' => 'table-totals',
2022-12-28 09:31:43 +01:00
'elements' => $this->getTableTotals(),
2022-12-27 16:44:12 +01:00
],
2022-12-28 11:28:58 +01:00
]);
2022-12-27 16:44:12 +01:00
return $this;
}
2022-12-28 10:29:51 +01:00
/**
* Generates the entity details for
* Credits
* Quotes
* Invoices
2023-02-21 08:39:07 +01:00
*
2022-12-28 10:29:51 +01:00
* @return self
2023-02-21 08:39:07 +01:00
*
2022-12-28 10:29:51 +01:00
*/
2022-12-27 16:44:12 +01:00
private function getProductEntityDetails(): self
{
2023-02-21 08:39:07 +01:00
if ($this->service->config->entity_string == 'invoice') {
$this->mergeSections([
2022-12-27 16:44:12 +01:00
'entity-details' => [
'id' => 'entity-details',
'elements' => $this->invoiceDetails(),
],
2022-12-28 11:28:58 +01:00
]);
2023-02-21 08:39:07 +01:00
} elseif ($this->service->config->entity_string == 'quote') {
$this->mergeSections([
2022-12-27 16:44:12 +01:00
'entity-details' => [
'id' => 'entity-details',
'elements' => $this->quoteDetails(),
],
2022-12-28 11:28:58 +01:00
]);
2023-02-21 08:39:07 +01:00
} elseif ($this->service->config->entity_string == 'credit') {
$this->mergeSections([
2022-12-27 16:44:12 +01:00
'entity-details' => [
'id' => 'entity-details',
'elements' => $this->creditDetails(),
],
2022-12-28 11:28:58 +01:00
]);
2022-12-27 16:44:12 +01:00
}
return $this;
}
2022-12-28 10:29:51 +01:00
/**
* Parent entry point when building sections of the design content
2023-02-21 08:39:07 +01:00
*
2022-12-28 10:29:51 +01:00
* @return self
2023-02-21 08:39:07 +01:00
*
2022-12-28 10:29:51 +01:00
*/
2022-12-27 16:44:12 +01:00
private function buildSections() :self
{
2023-01-11 14:16:53 +01:00
return match ($this->service->document_type) {
2022-12-28 11:28:58 +01:00
PdfService::PRODUCT => $this->getProductSections(),
2022-12-27 16:44:12 +01:00
PdfService::DELIVERY_NOTE => $this->getDeliveryNoteSections(),
PdfService::STATEMENT => $this->getStatementSections(),
PdfService::PURCHASE_ORDER => $this->getPurchaseOrderSections(),
2023-02-21 08:39:07 +01:00
};
2022-12-27 16:44:12 +01:00
}
2022-12-28 10:29:51 +01:00
/**
* Generates the table totals for statements
2023-02-21 08:39:07 +01:00
*
2022-12-28 10:29:51 +01:00
* @return array
2023-02-21 08:39:07 +01:00
*
2022-12-28 10:29:51 +01:00
*/
2022-12-27 16:44:12 +01:00
private function statementTableTotals(): array
{
return [
['element' => 'div', 'properties' => ['style' => 'display: flex; flex-direction: column;'], 'elements' => [
['element' => 'div', 'properties' => ['style' => 'margin-top: 1.5rem; display: block; align-items: flex-start; page-break-inside: avoid; visible !important;'], 'elements' => [
2023-02-25 06:11:12 +01:00
['element' => 'img', 'properties' => ['src' => '$invoiceninja.whitelabel', 'style' => 'height: 2.5rem;', 'hidden' => 'false', 'id' => 'invoiceninja-whitelabel-logo']],
2022-12-27 16:44:12 +01:00
]],
]],
];
}
2022-12-28 10:29:51 +01:00
/**
* Performs a variable check to ensure
* the variable exists
2023-02-21 08:39:07 +01:00
*
2023-08-06 04:20:18 +02:00
* @param string $variable
2022-12-28 10:29:51 +01:00
* @return bool
2023-02-21 08:39:07 +01:00
*
2022-12-28 10:29:51 +01:00
*/
2022-12-28 09:31:43 +01:00
public function entityVariableCheck(string $variable): bool
{
// When it comes to invoice balance, we'll always show it.
if ($variable == '$invoice.total') {
return false;
}
// Some variables don't map 1:1 to table columns. This gives us support for such cases.
$aliases = [
'$quote.balance_due' => 'partial',
];
try {
$_variable = explode('.', $variable)[1];
} catch (\Exception $e) {
throw new \Exception('Company settings seems to be broken. Missing $this->service->config->entity.variable type.');
}
if (\in_array($variable, \array_keys($aliases))) {
$_variable = $aliases[$variable];
}
2022-12-28 10:29:51 +01:00
if (is_null($this->service->config->entity->{$_variable})) {
2022-12-28 09:31:43 +01:00
return true;
}
2022-12-28 10:29:51 +01:00
if (empty($this->service->config->entity->{$_variable})) {
2022-12-28 09:31:43 +01:00
return true;
}
return false;
}
//First pass done, need a second pass to abstract this content completely.
2022-12-28 10:29:51 +01:00
/**
* Builds the table totals for all entities, we'll want to split this
2023-02-21 08:39:07 +01:00
*
2022-12-28 10:29:51 +01:00
* @return array
2023-02-21 08:39:07 +01:00
*
2022-12-28 10:29:51 +01:00
*/
2022-12-28 09:31:43 +01:00
public function getTableTotals() :array
2022-12-27 16:44:12 +01:00
{
//need to see where we don't pass all these particular variables. try and refactor thisout
2022-12-28 10:29:51 +01:00
$_variables = array_key_exists('variables', $this->service->options)
? $this->service->options['variables']
2022-12-28 16:22:48 +01:00
: ['values' => ['$entity.public_notes' => $this->service->config->entity->public_notes, '$entity.terms' => $this->service->config->entity->terms, '$entity_footer' => $this->service->config->entity->footer], 'labels' => []];
2022-12-27 16:44:12 +01:00
$variables = $this->service->config->pdf_variables['total_columns'];
$elements = [
['element' => 'div', 'properties' => ['style' => 'display: flex; flex-direction: column;'], 'elements' => [
2022-12-28 16:22:48 +01:00
['element' => 'p', 'content' => strtr(str_replace(["labels","values"], ["",""], $_variables['values']['$entity.public_notes']), $_variables), 'properties' => ['data-ref' => 'total_table-public_notes', 'style' => 'text-align: left;']],
2022-12-27 16:44:12 +01:00
['element' => 'p', 'content' => '', 'properties' => ['style' => 'text-align: left; display: flex; flex-direction: column; page-break-inside: auto;'], 'elements' => [
2022-12-28 16:22:48 +01:00
['element' => 'span', 'content' => '$entity.terms_label: ', 'properties' => ['hidden' => $this->entityVariableCheck('$entity.terms'), 'data-ref' => 'total_table-terms-label', 'style' => 'font-weight: bold; text-align: left; margin-top: 1rem;']],
['element' => 'span', 'content' => strtr(str_replace("labels", "", $_variables['values']['$entity.terms']), $_variables['labels']), 'properties' => ['data-ref' => 'total_table-terms', 'style' => 'text-align: left;']],
2022-12-27 16:44:12 +01:00
]],
['element' => 'img', 'properties' => ['style' => 'max-width: 50%; height: auto;', 'src' => '$contact.signature', 'id' => 'contact-signature']],
['element' => 'div', 'properties' => ['style' => 'margin-top: 1.5rem; display: flex; align-items: flex-start; page-break-inside: auto;'], 'elements' => [
2023-02-25 06:11:12 +01:00
['element' => 'img', 'properties' => ['src' => '$invoiceninja.whitelabel', 'style' => 'height: 2.5rem;', 'hidden' => 'false', 'id' => 'invoiceninja-whitelabel-logo']],
2022-12-27 16:44:12 +01:00
]],
]],
['element' => 'div', 'properties' => ['class' => 'totals-table-right-side', 'dir' => '$dir'], 'elements' => []],
];
2022-12-28 11:28:58 +01:00
if ($this->service->document_type == PdfService::DELIVERY_NOTE) {
2022-12-27 16:44:12 +01:00
return $elements;
}
2022-12-28 09:31:43 +01:00
if ($this->service->config->entity instanceof Quote) {
2022-12-27 16:44:12 +01:00
// We don't want to show Balanace due on the quotes.
if (in_array('$outstanding', $variables)) {
$variables = \array_diff($variables, ['$outstanding']);
}
if ($this->service->config->entity->partial > 0) {
$variables[] = '$partial_due';
}
}
2022-12-28 09:31:43 +01:00
if ($this->service->config->entity instanceof Credit) {
2022-12-27 16:44:12 +01:00
// We don't want to show Balanace due on the quotes.
if (in_array('$paid_to_date', $variables)) {
$variables = \array_diff($variables, ['$paid_to_date']);
}
}
foreach (['discount'] as $property) {
$variable = sprintf('%s%s', '$', $property);
if (
!is_null($this->service->config->entity->{$property}) &&
!empty($this->service->config->entity->{$property}) &&
$this->service->config->entity->{$property} != 0
) {
continue;
}
$variables = array_filter($variables, function ($m) use ($variable) {
return $m != $variable;
});
}
foreach ($variables as $variable) {
if ($variable == '$total_taxes') {
2023-02-25 01:11:09 +01:00
$taxes = $this->service->config->entity->total_tax_map;
2022-12-27 16:44:12 +01:00
if (!$taxes) {
continue;
}
foreach ($taxes as $i => $tax) {
$elements[1]['elements'][] = ['element' => 'div', 'elements' => [
['element' => 'span', 'content', 'content' => $tax['name'], 'properties' => ['data-ref' => 'totals-table-total_tax_' . $i . '-label']],
2023-02-23 21:27:27 +01:00
['element' => 'span', 'content', 'content' => $this->service->config->formatMoney($tax['total']), 'properties' => ['data-ref' => 'totals-table-total_tax_' . $i]],
2022-12-27 16:44:12 +01:00
]];
}
} elseif ($variable == '$line_taxes') {
2023-02-25 01:11:09 +01:00
$taxes = $this->service->config->entity->tax_map;
2022-12-27 16:44:12 +01:00
if (!$taxes) {
continue;
}
foreach ($taxes as $i => $tax) {
$elements[1]['elements'][] = ['element' => 'div', 'elements' => [
['element' => 'span', 'content', 'content' => $tax['name'], 'properties' => ['data-ref' => 'totals-table-line_tax_' . $i . '-label']],
2023-02-23 21:27:27 +01:00
['element' => 'span', 'content', 'content' => $this->service->config->formatMoney($tax['total']), 'properties' => ['data-ref' => 'totals-table-line_tax_' . $i]],
2022-12-27 16:44:12 +01:00
]];
}
} elseif (Str::startsWith($variable, '$custom_surcharge')) {
$_variable = ltrim($variable, '$'); // $custom_surcharge1 -> custom_surcharge1
// $visible = intval($this->service->config->entity->{$_variable}) != 0;
$visible = intval(str_replace(['0','.'], '', $this->service->config->entity->{$_variable})) != 0;
2022-12-27 16:44:12 +01:00
$elements[1]['elements'][] = ['element' => 'div', 'elements' => [
['element' => 'span', 'content' => $variable . '_label', 'properties' => ['hidden' => !$visible, 'data-ref' => 'totals_table-' . substr($variable, 1) . '-label']],
['element' => 'span', 'content' => $variable, 'properties' => ['hidden' => !$visible, 'data-ref' => 'totals_table-' . substr($variable, 1)]],
]];
} elseif (Str::startsWith($variable, '$custom')) {
$field = explode('_', $variable);
2022-12-28 09:31:43 +01:00
$visible = is_object($this->service->company->custom_fields) && property_exists($this->service->company->custom_fields, $field[1]) && !empty($this->service->company->custom_fields->{$field[1]});
2022-12-27 16:44:12 +01:00
$elements[1]['elements'][] = ['element' => 'div', 'elements' => [
['element' => 'span', 'content' => $variable . '_label', 'properties' => ['hidden' => !$visible, 'data-ref' => 'totals_table-' . substr($variable, 1) . '-label']],
['element' => 'span', 'content' => $variable, 'properties' => ['hidden' => !$visible, 'data-ref' => 'totals_table-' . substr($variable, 1)]],
]];
} else {
$elements[1]['elements'][] = ['element' => 'div', 'elements' => [
['element' => 'span', 'content' => $variable . '_label', 'properties' => ['data-ref' => 'totals_table-' . substr($variable, 1) . '-label']],
['element' => 'span', 'content' => $variable, 'properties' => ['data-ref' => 'totals_table-' . substr($variable, 1)]],
]];
}
}
$elements[1]['elements'][] = ['element' => 'div', 'elements' => [
['element' => 'span', 'content' => '',],
['element' => 'span', 'content' => ''],
]];
return $elements;
}
2022-12-28 09:31:43 +01:00
/**
* Generates the product and task tables
2023-02-21 08:39:07 +01:00
*
2022-12-28 09:31:43 +01:00
* @return self
2023-02-21 08:39:07 +01:00
*
2022-12-28 09:31:43 +01:00
*/
2022-12-27 16:44:12 +01:00
public function getProductAndTaskTables(): self
{
2023-02-21 08:39:07 +01:00
$this->mergeSections([
2022-12-23 03:58:08 +01:00
'product-table' => [
'id' => 'product-table',
'elements' => $this->productTable(),
],
'task-table' => [
'id' => 'task-table',
'elements' => $this->taskTable(),
],
2022-12-28 11:28:58 +01:00
]);
2022-12-27 16:44:12 +01:00
return $this;
}
2022-12-28 09:31:43 +01:00
/**
* Generates the client details
2023-02-21 08:39:07 +01:00
*
2022-12-28 09:31:43 +01:00
* @return self
2023-02-21 08:39:07 +01:00
*
2022-12-28 09:31:43 +01:00
*/
2022-12-27 16:44:12 +01:00
public function getClientDetails(): self
{
2023-02-21 08:39:07 +01:00
$this->mergeSections([
2022-12-27 16:44:12 +01:00
'client-details' => [
'id' => 'client-details',
'elements' => $this->clientDetails(),
2022-12-23 03:58:08 +01:00
],
2023-02-25 05:59:32 +01:00
'shipping-details' => [
'id' => 'shipping-details',
'elements' => $this->shippingDetails(),
],
2022-12-28 11:28:58 +01:00
]);
2022-12-23 03:58:08 +01:00
return $this;
2022-12-27 16:44:12 +01:00
}
/**
2022-12-28 09:31:43 +01:00
* Generates the product table
2022-12-27 16:44:12 +01:00
*
* @return array
*/
public function productTable(): array
{
$product_items = collect($this->service->config->entity->line_items)->filter(function ($item) {
return $item->type_id == 1 || $item->type_id == 6 || $item->type_id == 5;
});
if (count($product_items) == 0) {
return [];
}
return [
['element' => 'thead', 'elements' => $this->buildTableHeader('product')],
['element' => 'tbody', 'elements' => $this->buildTableBody('$product')],
];
}
/**
2022-12-28 09:31:43 +01:00
* Generates the task table
2022-12-27 16:44:12 +01:00
*
* @return array
*/
public function taskTable(): array
{
$task_items = collect($this->service->config->entity->line_items)->filter(function ($item) {
return $item->type_id == 2;
});
if (count($task_items) == 0) {
return [];
}
return [
['element' => 'thead', 'elements' => $this->buildTableHeader('task')],
['element' => 'tbody', 'elements' => $this->buildTableBody('$task')],
];
}
2022-12-28 09:31:43 +01:00
/**
* Generates the statement details
2023-02-21 08:39:07 +01:00
*
2022-12-28 09:31:43 +01:00
* @return array
2023-02-21 08:39:07 +01:00
*
2022-12-28 09:31:43 +01:00
*/
2022-12-27 16:44:12 +01:00
public function statementDetails(): array
{
2023-02-23 21:27:27 +01:00
$s_date = $this->translateDate(now(), $this->service->config->date_format, $this->service->config->locale);
2022-12-27 16:44:12 +01:00
return [
['element' => 'tr', 'properties' => ['data-ref' => 'statement-label'], 'elements' => [
['element' => 'th', 'properties' => [], 'content' => ""],
['element' => 'th', 'properties' => [], 'content' => "<h2>".ctrans('texts.statement')."</h2>"],
]],
['element' => 'tr', 'properties' => [], 'elements' => [
['element' => 'th', 'properties' => [], 'content' => ctrans('texts.statement_date')],
['element' => 'th', 'properties' => [], 'content' => $s_date ?? ''],
]],
['element' => 'tr', 'properties' => [], 'elements' => [
['element' => 'th', 'properties' => [], 'content' => '$balance_due_label'],
2023-02-23 21:27:27 +01:00
['element' => 'th', 'properties' => [], 'content' => $this->service->config->formatMoney($this->service->options['invoices']->sum('balance'))],
2022-12-27 16:44:12 +01:00
]],
];
}
2022-12-28 09:31:43 +01:00
/**
* Generates the invoice details
2023-02-21 08:39:07 +01:00
*
2022-12-28 09:31:43 +01:00
* @return array
2023-02-21 08:39:07 +01:00
*
2022-12-28 09:31:43 +01:00
*/
2022-12-27 16:44:12 +01:00
public function invoiceDetails(): array
{
2023-02-21 08:39:07 +01:00
$variables = $this->service->config->pdf_variables['invoice_details'];
2022-12-27 16:44:12 +01:00
return $this->genericDetailsBuilder($variables);
}
2022-12-28 09:31:43 +01:00
/**
* Generates the quote details
2023-02-21 08:39:07 +01:00
*
2022-12-28 09:31:43 +01:00
* @return array
2023-02-21 08:39:07 +01:00
*
2022-12-28 09:31:43 +01:00
*/
2022-12-27 16:44:12 +01:00
public function quoteDetails(): array
{
$variables = $this->service->config->pdf_variables['quote_details'];
if ($this->service->config->entity->partial > 0) {
$variables[] = '$quote.balance_due';
}
return $this->genericDetailsBuilder($variables);
}
2022-12-28 09:31:43 +01:00
/**
* Generates the credit note details
2023-02-21 08:39:07 +01:00
*
2022-12-28 09:31:43 +01:00
* @return array
2023-02-21 08:39:07 +01:00
*
2022-12-28 09:31:43 +01:00
*/
2022-12-27 16:44:12 +01:00
public function creditDetails(): array
{
$variables = $this->service->config->pdf_variables['credit_details'];
return $this->genericDetailsBuilder($variables);
}
2022-12-28 09:31:43 +01:00
/**
* Generates the purchase order details
2023-02-21 08:39:07 +01:00
*
2022-12-28 09:31:43 +01:00
* @return array
*/
2022-12-27 16:44:12 +01:00
public function purchaseOrderDetails(): array
{
$variables = $this->service->config->pdf_variables['purchase_order_details'];
return $this->genericDetailsBuilder($variables);
}
2022-12-28 09:31:43 +01:00
/**
* Generates the deliveyr note details
2023-02-21 08:39:07 +01:00
*
2022-12-28 09:31:43 +01:00
* @return array
2023-02-21 08:39:07 +01:00
*
2022-12-28 09:31:43 +01:00
*/
2022-12-27 16:44:12 +01:00
public function deliveryNoteDetails(): array
{
$variables = $this->service->config->pdf_variables['invoice_details'];
$variables = array_filter($variables, function ($m) {
return !in_array($m, ['$invoice.balance_due', '$invoice.total']);
});
return $this->genericDetailsBuilder($variables);
}
2022-12-28 09:31:43 +01:00
/**
* Generates the custom values for the
* entity.
2023-02-21 08:39:07 +01:00
*
* @param array $variables
2022-12-28 09:31:43 +01:00
* @return array
*/
2022-12-27 16:44:12 +01:00
public function genericDetailsBuilder(array $variables): array
{
$elements = [];
foreach ($variables as $variable) {
$_variable = explode('.', $variable)[1];
$_customs = ['custom1', 'custom2', 'custom3', 'custom4'];
$var = str_replace("custom", "custom_value", $_variable);
if (in_array($_variable, $_customs) && !empty($this->service->config->entity->{$var})) {
$elements[] = ['element' => 'tr', 'elements' => [
['element' => 'th', 'content' => $variable . '_label', 'properties' => ['data-ref' => 'entity_details-' . substr($variable, 1) . '_label']],
['element' => 'th', 'content' => $variable, 'properties' => ['data-ref' => 'entity_details-' . substr($variable, 1)]],
]];
} else {
$elements[] = ['element' => 'tr', 'properties' => ['hidden' => $this->entityVariableCheck($variable)], 'elements' => [
['element' => 'th', 'content' => $variable . '_label', 'properties' => ['data-ref' => 'entity_details-' . substr($variable, 1) . '_label']],
['element' => 'th', 'content' => $variable, 'properties' => ['data-ref' => 'entity_details-' . substr($variable, 1)]],
]];
}
}
return $elements;
}
2022-12-28 09:31:43 +01:00
/**
* Generates the client delivery
* details array
2023-02-21 08:39:07 +01:00
*
2022-12-28 09:31:43 +01:00
* @return array
2023-02-21 08:39:07 +01:00
*
2022-12-28 09:31:43 +01:00
*/
2022-12-27 16:44:12 +01:00
public function clientDeliveryDetails(): array
{
$elements = [];
2023-02-21 08:39:07 +01:00
if (!$this->service->config->client) {
2022-12-27 16:44:12 +01:00
return $elements;
2023-02-21 08:39:07 +01:00
}
2022-12-27 16:44:12 +01:00
$elements = [
['element' => 'p', 'content' => ctrans('texts.delivery_note'), 'properties' => ['data-ref' => 'delivery_note-label', 'style' => 'font-weight: bold; text-transform: uppercase']],
['element' => 'p', 'content' => $this->service->config->client->name, 'show_empty' => false, 'properties' => ['data-ref' => 'delivery_note-client.name']],
['element' => 'p', 'content' => $this->service->config->client->shipping_address1, 'show_empty' => false, 'properties' => ['data-ref' => 'delivery_note-client.shipping_address1']],
['element' => 'p', 'content' => $this->service->config->client->shipping_address2, 'show_empty' => false, 'properties' => ['data-ref' => 'delivery_note-client.shipping_address2']],
['element' => 'p', 'show_empty' => false, 'elements' => [
['element' => 'span', 'content' => "{$this->service->config->client->shipping_city} ", 'properties' => ['ref' => 'delivery_note-client.shipping_city']],
['element' => 'span', 'content' => "{$this->service->config->client->shipping_state} ", 'properties' => ['ref' => 'delivery_note-client.shipping_state']],
['element' => 'span', 'content' => "{$this->service->config->client->shipping_postal_code} ", 'properties' => ['ref' => 'delivery_note-client.shipping_postal_code']],
]],
['element' => 'p', 'content' => optional($this->service->config->client->shipping_country)->name, 'show_empty' => false],
];
2023-02-21 08:39:07 +01:00
if (!is_null($this->service->config->contact)) {
$elements[] = ['element' => 'p', 'content' => $this->service->config->contact->email, 'show_empty' => false, 'properties' => ['data-ref' => 'delivery_note-contact.email']];
}
2022-12-27 16:44:12 +01:00
return $elements;
}
2022-12-28 09:31:43 +01:00
/**
* Generates the client details section
2023-02-21 08:39:07 +01:00
*
2022-12-28 09:31:43 +01:00
* @return array
*/
2022-12-27 16:44:12 +01:00
public function clientDetails(): array
{
$elements = [];
2023-02-21 08:39:07 +01:00
if (!$this->service->config->client) {
2022-12-27 16:44:12 +01:00
return $elements;
2023-02-21 08:39:07 +01:00
}
2022-12-27 16:44:12 +01:00
$variables = $this->service->config->pdf_variables['client_details'];
foreach ($variables as $variable) {
$elements[] = ['element' => 'p', 'content' => $variable, 'show_empty' => false, 'properties' => ['data-ref' => 'client_details-' . substr($variable, 1)]];
}
return $elements;
2022-12-23 03:58:08 +01:00
}
2023-02-25 05:59:32 +01:00
public function shippingDetails(): array
{
$elements = [];
if (!$this->service->config->client) {
return $elements;
}
$elements = [
['element' => 'p', 'content' => ctrans('texts.shipping_address'), 'properties' => ['data-ref' => 'shipping_address-label', 'style' => 'font-weight: bold; text-transform: uppercase']],
['element' => 'p', 'content' => $this->service->config->client->name, 'show_empty' => false, 'properties' => ['data-ref' => 'shipping_address-client.name']],
['element' => 'p', 'content' => $this->service->config->client->shipping_address1, 'show_empty' => false, 'properties' => ['data-ref' => 'shipping_address-client.shipping_address1']],
['element' => 'p', 'content' => $this->service->config->client->shipping_address2, 'show_empty' => false, 'properties' => ['data-ref' => 'shipping_address-client.shipping_address2']],
['element' => 'p', 'show_empty' => false, 'elements' => [
['element' => 'span', 'content' => "{$this->service->config->client->shipping_city} ", 'properties' => ['ref' => 'shipping_address-client.shipping_city']],
['element' => 'span', 'content' => "{$this->service->config->client->shipping_state} ", 'properties' => ['ref' => 'shipping_address-client.shipping_state']],
['element' => 'span', 'content' => "{$this->service->config->client->shipping_postal_code} ", 'properties' => ['ref' => 'shipping_address-client.shipping_postal_code']],
]],
['element' => 'p', 'content' => optional($this->service->config->client->shipping_country)->name, 'show_empty' => false],
];
return $elements;
}
2022-12-28 09:31:43 +01:00
/**
* Generates the delivery note table
2023-02-21 08:39:07 +01:00
*
2022-12-28 09:31:43 +01:00
* @return array
*/
2022-12-27 16:44:12 +01:00
public function deliveryNoteTable(): array
{
2022-12-28 09:31:43 +01:00
/* Static array of delivery note columns*/
2022-12-27 16:44:12 +01:00
$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']],
['element' => 'th', 'content' => '$product.quantity_label', 'properties' => ['data-ref' => 'delivery_note-product.quantity_label']],
];
2022-12-28 11:28:58 +01:00
$items = $this->transformLineItems($this->service->config->entity->line_items, $this->service->document_type);
2022-12-27 16:44:12 +01:00
$this->processNewLines($items);
2022-12-28 09:31:43 +01:00
2022-12-27 16:44:12 +01:00
$product_customs = [false, false, false, false];
foreach ($items as $row) {
for ($i = 0; $i < count($product_customs); $i++) {
if (!empty($row['delivery_note.delivery_note' . ($i + 1)])) {
$product_customs[$i] = true;
}
}
}
for ($i = 0; $i < count($product_customs); $i++) {
if ($product_customs[$i]) {
array_push($thead, ['element' => 'th', 'content' => '$product.product' . ($i + 1) . '_label', 'properties' => ['data-ref' => 'delivery_note-product.product' . ($i + 1) . '_label']]);
}
}
return [
['element' => 'thead', 'elements' => $thead],
2022-12-28 09:31:43 +01:00
['element' => 'tbody', 'elements' => $this->buildTableBody(PdfService::DELIVERY_NOTE)],
2022-12-27 16:44:12 +01:00
];
}
2022-12-28 09:31:43 +01:00
/**
* Passes an array of items by reference
* and performs a nl2br
2023-02-21 08:39:07 +01:00
*
2023-08-06 04:20:18 +02:00
* @param array $items
2022-12-28 09:31:43 +01:00
* @return void
2023-02-21 08:39:07 +01:00
*
2022-12-28 09:31:43 +01:00
*/
public function processNewLines(array &$items): void
{
foreach ($items as $key => $item) {
foreach ($item as $variable => $value) {
$item[$variable] = str_replace("\n", '<br>', $value);
}
$items[$key] = $item;
}
}
2022-12-27 16:44:12 +01:00
2022-12-28 09:31:43 +01:00
/**
* Generates an arary of the company details
2023-02-21 08:39:07 +01:00
*
2022-12-28 09:31:43 +01:00
* @return array
2023-02-21 08:39:07 +01:00
*
2022-12-28 09:31:43 +01:00
*/
2022-12-27 16:44:12 +01:00
public function companyDetails(): array
{
$variables = $this->service->config->pdf_variables['company_details'];
$elements = [];
foreach ($variables as $variable) {
$elements[] = ['element' => 'p', 'content' => $variable, 'show_empty' => false, 'properties' => ['data-ref' => 'company_details-' . substr($variable, 1)]];
}
return $elements;
}
2022-12-28 09:31:43 +01:00
/**
*
* Generates an array of the company address
2023-02-21 08:39:07 +01:00
*
2022-12-28 09:31:43 +01:00
* @return array
2023-02-21 08:39:07 +01:00
*
2022-12-28 09:31:43 +01:00
*/
2022-12-27 16:44:12 +01:00
public function companyAddress(): array
{
$variables = $this->service->config->pdf_variables['company_address'];
$elements = [];
foreach ($variables as $variable) {
$elements[] = ['element' => 'p', 'content' => $variable, 'show_empty' => false, 'properties' => ['data-ref' => 'company_address-' . substr($variable, 1)]];
}
return $elements;
}
2022-12-28 09:31:43 +01:00
/**
*
* Generates an array of vendor details
2023-02-21 08:39:07 +01:00
*
2022-12-28 09:31:43 +01:00
* @return array
2023-02-21 08:39:07 +01:00
*
2022-12-28 09:31:43 +01:00
*/
2022-12-27 16:44:12 +01:00
public function vendorDetails(): array
{
$elements = [];
$variables = $this->service->config->pdf_variables['vendor_details'];
foreach ($variables as $variable) {
$elements[] = ['element' => 'p', 'content' => $variable, 'show_empty' => false, 'properties' => ['data-ref' => 'vendor_details-' . substr($variable, 1)]];
}
return $elements;
}
2022-12-28 11:28:58 +01:00
////////////////////////////////////////
2022-12-28 10:29:51 +01:00
// Dom Traversal
2022-12-28 11:28:58 +01:00
///////////////////////////////////////
2022-12-28 10:29:51 +01:00
public function getSectionNode(string $selector)
{
return $this->document->getElementById($selector);
}
public function updateElementProperties() :self
{
foreach ($this->sections as $element) {
if (isset($element['tag'])) {
$node = $this->document->getElementsByTagName($element['tag'])->item(0);
} elseif (! is_null($this->document->getElementById($element['id']))) {
$node = $this->document->getElementById($element['id']);
} else {
continue;
}
if (isset($element['properties'])) {
foreach ($element['properties'] as $property => $value) {
$this->updateElementProperty($node, $property, $value);
}
}
if (isset($element['elements'])) {
$this->createElementContent($node, $element['elements']);
}
}
2022-12-27 16:44:12 +01:00
2022-12-28 10:29:51 +01:00
return $this;
}
2022-12-27 16:44:12 +01:00
2022-12-28 10:29:51 +01:00
public function updateElementProperty($element, string $attribute, ?string $value)
{
// We have exception for "hidden" property.
// hidden="true" or hidden="false" will both hide the element,
// that's why we have to create an exception here for this rule.
2022-12-23 03:58:08 +01:00
2022-12-28 10:29:51 +01:00
if ($attribute == 'hidden' && ($value == false || $value == 'false')) {
return $element;
}
2022-12-23 03:58:08 +01:00
2022-12-28 10:29:51 +01:00
$element->setAttribute($attribute, $value);
2022-12-23 03:58:08 +01:00
2022-12-28 10:29:51 +01:00
if ($element->getAttribute($attribute) === $value) {
return $element;
}
2022-12-23 03:58:08 +01:00
2022-12-28 10:29:51 +01:00
return $element;
}
2022-12-23 03:58:08 +01:00
2022-12-28 10:29:51 +01:00
public function createElementContent($element, $children) :self
{
foreach ($children as $child) {
$contains_html = false;
2022-12-23 03:58:08 +01:00
2022-12-28 10:29:51 +01:00
if ($child['element'] !== 'script') {
2022-12-28 15:50:11 +01:00
if ($this->service->company->markdown_enabled && array_key_exists('content', $child)) {
2022-12-28 10:29:51 +01:00
$child['content'] = str_replace('<br>', "\r", $child['content']);
$child['content'] = $this->commonmark->convert($child['content'] ?? '');
}
}
2022-12-23 03:58:08 +01:00
2022-12-28 10:29:51 +01:00
if (isset($child['content'])) {
if (isset($child['is_empty']) && $child['is_empty'] === true) {
continue;
}
$contains_html = preg_match('#(?<=<)\w+(?=[^<]*?>)#', $child['content'], $m) != 0;
}
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.
// Later, we decode this using Javascript so it looks like it's normal HTML being injected.
// To get all elements that need frontend decoding, we use 'data-state' property.
$_child = $this->document->createElement($child['element'], '');
$_child->setAttribute('data-state', 'encoded-html');
$_child->nodeValue = htmlspecialchars($child['content']);
} else {
// .. in case string doesn't contain any HTML, we'll just return
// raw $content.
$_child = $this->document->createElement($child['element'], isset($child['content']) ? htmlspecialchars($child['content']) : '');
}
$element->appendChild($_child);
if (isset($child['properties'])) {
foreach ($child['properties'] as $property => $value) {
$this->updateElementProperty($_child, $property, $value);
}
}
if (isset($child['elements'])) {
$this->createElementContent($_child, $child['elements']);
}
}
return $this;
}
public function updateVariables()
{
2023-07-10 14:52:03 +02:00
2022-12-28 11:28:58 +01:00
$html = strtr($this->getCompiledHTML(), $this->service->html_variables['labels']);
2022-12-28 10:29:51 +01:00
2022-12-28 11:28:58 +01:00
$html = strtr($html, $this->service->html_variables['values']);
2022-12-28 10:29:51 +01:00
@$this->document->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
$this->document->saveHTML();
return $this;
}
public function updateVariable(string $element, string $variable, string $value)
{
$element = $this->document->getElementById($element);
$original = $element->nodeValue;
$element->nodeValue = '';
$replaced = strtr($original, [$variable => $value]);
$element->appendChild(
$this->document->createTextNode($replaced)
);
return $element;
}
public function getEmptyElements() :self
{
foreach ($this->sections as $element) {
if (isset($element['elements'])) {
2022-12-28 11:28:58 +01:00
$this->getEmptyChildrens($element['elements'], $this->service->html_variables);
2022-12-28 10:29:51 +01:00
}
}
return $this;
}
public function getEmptyChildrens(array $children)
{
foreach ($children as $key => $child) {
if (isset($child['content']) && isset($child['show_empty']) && $child['show_empty'] === false) {
2022-12-28 11:28:58 +01:00
$value = strtr($child['content'], $this->service->html_variables['values']);
2023-02-26 06:50:57 +01:00
if ($value === '' || $value === '&nbsp;' || $value === ' ') {
2022-12-28 10:29:51 +01:00
$child['is_empty'] = true;
}
}
if (isset($child['elements'])) {
$this->getEmptyChildrens($child['elements']);
}
}
return $this;
}
2023-02-21 08:39:07 +01:00
}