Newer
Older
<?php
/**
* This file contains QUI\ERP\Accounting\Invoice\EventHandler
*/
namespace QUI\ERP\Accounting\Invoice;
use horstoeko\zugferd\ZugferdDocumentBuilder;
use horstoeko\zugferd\ZugferdDocumentPdfBuilder;
use horstoeko\zugferd\ZugferdDocumentPdfMerger;
use QUI\ERP\Accounting\Invoice\Output\OutputProviderCancelled;
use QUI\ERP\Accounting\Invoice\Output\OutputProviderCreditNote;
use QUI\ERP\Accounting\Invoice\Output\OutputProviderInvoice;
use QUI\ERP\Accounting\Payments\Transactions\Transaction;
use QUI\ERP\Products\Handler\Fields;
use QUI\ERP\Products\Handler\Search;
use function dirname;
use function file_exists;
use function file_get_contents;
use function in_array;
/**
* Class EventHandler
*
* @package QUI\ERP
*/
class EventHandler
{
/**
* event: on package setup
*
* @param Package $Package
public static function onPackageSetup(Package $Package): void
{
if ($Package->getName() != 'quiqqer/invoice') {
return;
}
// Patches
try {
self::patchIdWithPrefixColumn();
} catch (\Exception $Exception) {
QUI\System\Log::writeException($Exception);
}
// create invoice payment status
$Handler = ProcessingStatus\Handler::getInstance();
$Factory = ProcessingStatus\Factory::getInstance();
if (!empty($list)) {
return;
}
$languages = QUI::availableLanguages();
$getLocaleTranslations = function ($key) use ($languages) {
foreach ($languages as $language) {
$result[$language] = QUI::getLocale()->getByLang($language, 'quiqqer/invoice', $key);
}
return $result;
};
// Neu
$Factory->createProcessingStatus(1, '#ff8c00', $getLocaleTranslations('processing.status.default.1'));
// In Bearbeitung
$Factory->createProcessingStatus(2, '#9370db', $getLocaleTranslations('processing.status.default.2'));
// Erledigt
$Factory->createProcessingStatus(3, '#228b22', $getLocaleTranslations('processing.status.default.3'));
}
/**
* event: on package setup
* only for the quiqqer/products
* extend products with a product invoice text field
*
* @param Package $Package
*/
public static function onProductsPackageSetup(Package $Package): void
if ($Package->getName() !== 'quiqqer/products') {
return;
}
try {
// if the Field exists, we don't need to create it
Fields::getField(QUI\ERP\Constants::INVOICE_PRODUCT_TEXT_ID);
} catch (QUI\ERP\Products\Field\Exception) {
'id' => QUI\ERP\Constants::INVOICE_PRODUCT_TEXT_ID,
'type' => 'InputMultiLang',
'prefix' => '',
'suffix' => '',
'priority' => 3,
'systemField' => 0,
'standardField' => 1,
'requiredField' => 0,
'publicField' => 0,
'search_type' => Search::SEARCHTYPE_TEXT,
'options' => [
'maxLength' => 255,
'minLength' => 3

Henning Leutz
committed
'de' => 'Rechnungstext',
'en' => 'Invoice text'
} catch (\Exception $Exception) {
QUI\System\Log::addAlert($Exception->getMessage());
}
}
* event: on transaction create
*
* @param Transaction $Transaction
*/
public static function onTransactionCreate(Transaction $Transaction): void
{
$hash = $Transaction->getHash();
try {
$Invoice = Handler::getInstance()->getInvoiceByHash($hash);
} catch (QUI\Exception $Exception) {
QUI\System\Log::writeDebugException($Exception);
return;
}
try {
$Invoice->addTransaction($Transaction);
} catch (\Exception $Exception) {
QUI\System\Log::writeDebugException($Exception);
}
}
/**
* @param Transaction $Transaction
*/
public static function onTransactionStatusChange(Transaction $Transaction): void
{
$hash = $Transaction->getHash();
try {
$Invoice = Handler::getInstance()->getInvoiceByHash($hash);
} catch (QUI\Exception $Exception) {
QUI\System\Log::writeDebugException($Exception);
return;
}
$Invoice->calculatePayments();
}
/**
* template event: on frontend users address top
*
* @param Collector $Collector
* @param QUI\Users\User $User
public static function onFrontendUsersAddressTop(Collector $Collector, QUI\Users\User $User): void
$Engine = QUI::getTemplateManager()->getEngine();
$current = '';
if ($User->getAttribute('quiqqer.erp.address')) {
$current = $User->getAttribute('quiqqer.erp.address');
}
$Engine->assign([
'addresses' => $User->getAddressList(),
$result = '<style>';
$result .= file_get_contents(dirname(__FILE__) . '/FrontendUsers/userProfileAddressSelect.css');
$result .= '</style>';
$result .= $Engine->fetch(dirname(__FILE__) . '/FrontendUsers/userProfileAddressSelect.html');
$Collector->append($result);
}
/**
* @param QUI\Users\User $User
* @throws QUi\Exception
*/
public static function onUserSaveBegin(QUI\Users\User $User): void
{
$Package = QUI::getPackage('quiqqer/frontend-users');
if (!$Config->get('userProfile', 'useAddressManagement')) {
return;
}
$addressId = $Request->get('quiqqer-frontendUsers-userdata-invoice-address');
if (!$addressId) {
return;
}
// quiqqer.erp.address
// look if the address is an address of the user
try {
$User->getAddress($addressId);
$User->setAttribute('quiqqer.erp.address', $addressId);
$User->setAttribute('address', $addressId);
} catch (QUI\Exception $Exception) {
QUI\System\Log::writeDebugException($Exception);
/**
* @param QUI\Users\User $User
* @param QUI\ERP\Comments $Comments
*/
public static function onQuiqqerErpGetCommentsByUser(
QUI\Users\User $User,
QUI\ERP\Comments $Comments
$invoices = $Handler->getInvoicesByUser($User);
foreach ($invoices as $Invoice) {
$Comments->import($Invoice->getComments());
}
}
/**
* quiqqer/customer: onQuiqqerErpGetHistoryByUser
*
* @param QUI\Users\User $User
* @param QUI\ERP\Comments $Comments
*/
public static function onQuiqqerErpGetHistoryByUser(
QUI\Users\User $User,
QUI\ERP\Comments $Comments
$invoices = $Handler->getInvoicesByUser($User);
foreach ($invoices as $Invoice) {
// created invoice
$Comments->addComment(
QUI::getLocale()->get('quiqqer/invoice', 'erp.comment.invoice.created', [
'invoiceId' => $Invoice->getPrefixedNumber()
strtotime($Invoice->getAttribute('c_date')),
'quiqqer/invoice',
Factory::ERP_INVOICE_ICON,
false,
/**
* quiqqer/erp: onQuiqqerErpOutputSendMailBefore
*
* Used to attach customer files that are attached to an invoice to the invoice mail
*
* @param $entityId
* @param string $entityType
* @param string $recipient
*
* @throws Exception
* @throws QUI\Exception
* @throws QUI\Permissions\Exception
*/
public static function onQuiqqerErpOutputSendMailBefore(
$entityId,
string $entityType,
string $recipient,
QUI\Mail\Mailer $Mailer,
string $mailFile = ''
$allowedEntityTypes = [
OutputProviderInvoice::getEntityType(),
OutputProviderCancelled::getEntityType(),
OutputProviderCreditNote::getEntityType()
];
if (!in_array($entityType, $allowedEntityTypes)) {
try {
$Invoice = OutputProviderInvoice::getEntity($entityId);
} catch (\Exception $Exception) {
QUI\System\Log::writeException($Exception);
return;
}
// extend pdf with e-invoice
$Config = QUI::getPackage('quiqqer/invoice')->getConfig();
if (file_exists($mailFile) && $Config->getValue('invoice', 'xInvoiceAttachment')) {
$xmlFile = str_replace('.pdf', '.xml', $mailFile);
$document = QUI\ERP\Accounting\Invoice\Utils\Invoice::getElectronicInvoice(
$Invoice,
$Config->getValue('invoice', 'xInvoiceAttachmentType')
);
$document->writeFile($xmlFile);
$Mailer->addAttachment($xmlFile);
}
if (file_exists($mailFile) && $Config->getValue('invoice', 'zugferdInvoiceAttachment')) {
$document = QUI\ERP\Accounting\Invoice\Utils\Invoice::getElectronicInvoice(
$Invoice,
$Config->getValue('invoice', 'xInvoiceAttachmentType')
);
$pdfBuilder = new ZugferdDocumentPdfBuilder($document, $mailFile);
$pdfBuilder->generateDocument()->saveDocument($mailFile);
}
$customerFiles = $Invoice->getCustomerFiles();
foreach ($customerFiles as $entry) {

Patrick Müller
committed
if (empty($entry['options']['attachToEmail'])) {
continue;
}
$file = QUI\ERP\Customer\CustomerFiles::getFileByHash($Invoice->getCustomer()->getUUID(), $entry['hash']);
$filePath = $file['dirname'] . '/' . $file['basename'];
$Mailer->addAttachment($filePath);
}
}
}
}
/**
* quiqqer/erp: onQuiqqerErpOutputSendMail
*
* Save to invoice that a dunning was sent
*
* @param $entityId
* @param string $entityType
* @param string $recipient
* @return void
*/
public static function onQuiqqerErpOutputSendMail($entityId, string $entityType, string $recipient): void
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
{
switch ($entityType) {
case OutputProviderInvoice::getEntityType():
case OutputProviderCancelled::getEntityType():
case OutputProviderCreditNote::getEntityType():
break;
default:
return;
}
try {
$Invoice = OutputProviderInvoice::getEntity($entityId);
$Invoice->addHistory(
QUI::getLocale()->get(
'quiqqer/invoice',
'message.add.history.sent.to',
[
'recipient' => $recipient
]
)
);
} catch (\Exception $Exception) {
QUI\System\Log::writeException($Exception);
return;
}
}
/**
* PATCH:
*
* Writes values to "id_with_prefix" columns in invoice table.
*
* @return void
*
* @throws QUI\Database\Exception
* @throws QUI\Exception
*/
protected static function patchIdWithPrefixColumn(): void
{
$Conf = QUI::getPackage('quiqqer/invoice')->getConfig();
if (!empty($Conf->getValue('patch', 'id_with_prefix'))) {
return;
}
$table = Handler::getInstance()->invoiceTable();
$result = QUI::getDataBase()->fetch([
'select' => ['id', 'id_prefix'],
]);
foreach ($result as $row) {
QUI::getDataBase()->update(
$table,
[
'id_with_prefix' => $row['id_prefix'] . $row['id']
],
[
'id' => $row['id']
]
);
}
$Conf->setValue('patch', 'id_with_prefix', 1);
$Conf->save();
}
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
/**
* @throws QUI\Database\Exception
*/
public static function onQuiqqerMigrationV2(QUI\System\Console\Tools\MigrationV2 $Console): void
{
$Console->writeLn('- Migrate invoice');
$invoiceTable = Handler::getInstance()->invoiceTable();
// migrate database
$alterOrderId = function ($table) {
$tableInfo = QUI::getDatabase()->table()->getFieldsInfos($table);
$hashFields = [
'c_user' => 'VARCHAR(50) NOT NULL',
'editor_id' => 'VARCHAR(50) NULL',
'customer_id' => 'VARCHAR(50) NOT NULL',
'invoice_address_id' => 'VARCHAR(50) NULL',
'ordered_by' => 'VARCHAR(50) NULL',
'order_id' => 'VARCHAR(50) NULL',
];
foreach ($tableInfo as $tableEntry) {
$tableField = $tableEntry['Field'];
if (!isset($hashFields[$tableField])) {
continue;
}
$swl = $hashFields[$tableField];
if (!str_contains(strtolower($tableEntry['Type']), 'varchar')) {
QUI::getDatabase()->execSQL(
"ALTER TABLE `$table` CHANGE `$tableField` `$tableField` $swl;"
);
}
}
};
$alterOrderId($invoiceTable);
$alterOrderId(Handler::getInstance()->temporaryInvoiceTable());
QUI\Utils\MigrationV1ToV2::migrateUsers(
Handler::getInstance()->invoiceTable(),
[
'customer_id',
'ordered_by',
'c_user',
'editor_id'
]
);
// migrate order ids
$result = QUI::getDataBase()->fetch([
'from' => Handler::getInstance()->invoiceTable()
]);
foreach ($result as $invoice) {
if (!is_numeric($invoice['order_id'])) {
continue;
}
if ($invoice['order_id'] == 0) {
continue;
}
try {
$Order = QUI\ERP\Order\Handler::getInstance()->getOrderById($invoice['order_id']);
QUI::getDataBase()->update(
$invoiceTable,
['order_id' => $Order->getUUID()],
['id' => $invoice['id']]
);
} catch (QUI\Exception) {
}
}
}