<?php
//----------------------------------------------------------------------
// src/Logging/InvoiceLog.php
//----------------------------------------------------------------------
namespace App\Logging\Activity;
use Doctrine\Persistence\ManagerRegistry;
use App\Entity\Access;
use App\Entity\Platform\Invoice\Invoice;
use App\Entity\Platform\Invoice\InvoiceStatus;
use App\Logging\Tools;
use App\Services\Location\AddressTools;
use App\Services\LogTools;
class InvoiceLog
{
private array $pendingLogArgs = [];
public function __construct(ManagerRegistry $doctrine, LogTools $logTools, Tools $tools)
{
$this->em = $doctrine->getManager();
$this->logTools = $logTools;
$this->tools = $tools;
}
public function logCreation(Invoice $invoice)
{
$pendingLogArgs = [];
//----------------------------------------------------------------------
// Handle EventListener changes
$specialLog = $this->handleSoldeChanges($invoice);
if ($specialLog !== null)
{
$pendingLogArgs[] = $specialLog;
}
//----------------------------------------------------------------------
//----------------------------------------------------------------------
// Fetch eventual info stored in the object
$loggingData = $this->logTools->handleLoggingData($invoice);
$info = $loggingData['info'];
$specialAuthor = $loggingData['special_author'];
$ignore = $loggingData['ignore'];
if ($ignore) return $pendingLogArgs;
//----------------------------------------------------------------------
// Init base log args
// This does not contain action
$args = $this->initArgs($invoice, $loggingData);
//----------------------------------------------------------------------
$action = "invoice_add";
if ($invoice->isDraft())
{
$action = "invoice_draft_add";
}
if ($invoice->isCredit() || $invoice->isCreditFree())
{
$action = "invoice_add_credit";
if ($invoice->isDraft())
{
$action = "invoice_credit_draft_add";
}
}
$args["action"] = $action;
$pendingLogArgs[] = $args;
return $pendingLogArgs;
}
public function logChanges(Invoice $invoice, $changes)
{
$pendingLogArgs = [];
//----------------------------------------------------------------------
// Handle EventListener changes
$specialLog = $this->handleSoldeChanges($invoice);
if ($specialLog !== null)
{
$pendingLogArgs[] = $specialLog;
}
//----------------------------------------------------------------------
//----------------------------------------------------------------------
// Fetch eventual info stored in the object
$loggingData = $this->logTools->handleLoggingData($invoice);
$info = $loggingData['info'];
$specialAuthor = $loggingData['special_author'];
$ignore = $loggingData['ignore'];
if ($ignore) return $pendingLogArgs;
//----------------------------------------------------------------------
// Init base log args
// This does not contain action
$args = $this->initArgs($invoice, $loggingData);
//----------------------------------------------------------------------
// Clear info for special cases
if ($info == "convert_draft")
{
$args["info"] = null;
}
$action = "invoice_edit";
if ($invoice->isDraft())
{
$action = "invoice_draft_edit";
}
$basicChanges = array(
"ref",
"refOrder",
"info",
"internalInfo",
"mentionInfo",
"visibleToClient", // Plan.io Task #4327
"ikeaSent",
);
$labelChanges = array(
"status",
"tva",
"paymentDeadline",
);
// This is triggered when we are actually changing
// the object referenced in Devis :: $interventionAddress
$addressChanges = array(
"interventionAddress",
"billingAddress",
);
// Method getLogLabel() should be defined for these objects/entities
$objectChanges = array(
"template",
"emitter",
"society",
"manager",
"author",
);
$dateChanges = array(
"creationDate",
"paymentDeadlineDate",
);
// See what changed and log (members first)
foreach ($changes as $key => $change)
{
// Something to skip ?
if (strpos($key, "total") === 0 || strpos($key, "solde") === 0)
{
continue;
}
$name = $this->logTools->camelToSnakeCase($key);
$args["action"] = $action."_".$name;
$before = $change[0];
$after = $change[1];
if (in_array($key, $basicChanges))
{
$args = $this->tools->handleBasicChanges($args, $before, $after);
if ($key == "ikeaSent")
{
$ikeaAction = "ikea_service_order_invoice_sent_to_ikea";
$args["action"] = $ikeaAction;
$pendingLogArgs[] = $args;
$ikeaArgs = $this->tools->handleIkeaServiceOrder($after, $invoice, $ikeaAction, $info, $specialAuthor);
foreach ($ikeaArgs as $argsItem)
{
$pendingLogArgs[] = $argsItem;
}
}
else
{
$pendingLogArgs[] = $args;
}
continue;
}
if (in_array($key, $labelChanges))
{
$pendingLogArgs[] = $this->tools->handleLabelChanges($args, $before, $after);
continue;
}
if (in_array($key, $objectChanges))
{
$pendingLogArgs[] = $this->tools->handleObjectChanges($args, $before, $after);
continue;
}
if (in_array($key, $addressChanges))
{
$pendingLogArgs[] = $this->tools->handleAddressChanges($args, $before, $after);
continue;
}
if (in_array($key, $dateChanges))
{
// dateChanges can be null
$changeLogs = $this->tools->handleDateChanges($args, $before, $after);
if ($changeLogs !== null) $pendingLogArgs[] = $changeLogs;
continue;
}
// Plan.io Task #4326
// Handle Converting Drafts to Invoices
if ($key == "draft")
{
if ($info == "convert_draft")
{
$tempAction = "invoice_draft_convert";
if ($invoice->isCredit() || $invoice->isCreditFree())
{
$tempAction = "invoice_credit_draft_convert";
}
$args["action"] = $tempAction;
// Old and new values
$args["old_value"] = $invoice->getOldRef();
$args["new_value"] = $invoice->getRef();
$args["info"] = null;
$pendingLogArgs[] = $args;
}
continue;
}
}
if ($invoice->getProducts()->isDirty())
{
// Make a copy of product changes
$this->saveInvoiceProducts($invoice,
$invoice->getProducts()->getSnapshot(), $invoice->getProducts());
}
// See what changed and log (relationships OneToMany and ManyToMany second)
if ($invoice->getProducts()->isDirty())
{
$old = "";
foreach ($invoice->getProducts()->getSnapshot() as $product)
{
$old .= $product->getRef();
$old .= ", ";
}
if ($old != "")
{
$old = substr($old, 0, -1);
$old = substr($old, 0, -1);
}
$new = "";
foreach ($invoice->getProducts() as $product)
{
$new .= $product->getRef();
$new .= ", ";
}
if ($new != "")
{
$new = substr($new, 0, -1);
$new = substr($new, 0, -1);
}
$args["action"] = "invoice_edit_products";
$args["old_value"] = $old;
$args["new_value"] = $new;
$pendingLogArgs[] = $args;
}
// Invoice :: $interventionAddress and Invoice :: $billingAddress
// are handled in AddressLog
// Triggered when the object does not change, but its members do
return $pendingLogArgs;
}
// This only concerns Drafts
public function logRemoval(Invoice $invoice)
{
if ($invoice->isNotDraft())
{
return [];
}
$pendingLogArgs = [];
//----------------------------------------------------------------------
// Fetch eventual info stored in the object
$loggingData = $this->logTools->handleLoggingData($invoice);
$info = $loggingData['info'];
$specialAuthor = $loggingData['special_author'];
$ignore = $loggingData['ignore'];
if ($ignore) return $pendingLogArgs;
//----------------------------------------------------------------------
// Init base log args
// This does not contain action
$args = $this->initArgs($invoice, $loggingData);
//----------------------------------------------------------------------
$args["action"] = "invoice_draft_delete";
$pendingLogArgs[] = $args;
return $pendingLogArgs;
}
public function initArgs(Invoice $invoice, $loggingData)
{
$receiver = $invoice->getReceiver();
$society = $invoice->getSociety();
$societyGroup = $society->getSocietyGroup();
$mission = $invoice->getMission();
$args = array(
"object_id" => $invoice->getId(),
"object_bundle" => "Platform",
"object_entity" => "Invoice",
"object_display" => $invoice->display(),
"object_client_id" => $receiver !== null ? $receiver->getId() : null,
"object_client_display" => $receiver !== null ? $receiver->getName() : null,
"object_mission_id" => $mission !== null ? $mission->getId() : null,
"object_mission_display" => $mission !== null ? $mission->getRef() : null,
"society_group" => $societyGroup,
"society" => $society,
"info" => $loggingData['info'],
"special_author" => $loggingData['special_author'],
);
return $args;
}
public function saveInvoiceProducts(Invoice $invoice, $oldProducts, $newProducts)
{
// [id][ref][title][product/discount][description][value][quantity][unit_id][unit_abbrv][totalHT][totalHTDevis][readonly][devisProductId][originalProduct_id][originalProduct_ref]
if ($invoice === null)
return null;
$today = new \DateTime();
$stamp = $today->format("Y_m");
// ROOT/custom_logs/product_logs/
$logPath = $this->logTools->getProductLogsDir();
if (!file_exists($logPath))
{
if (!mkdir($logPath, 0775))
{
// Something went bad
$this->logTools->errorlog('Could not create folder '.$logPath);
return null;
}
}
$logFile = $logPath."invoice_products_".$stamp.".log";
error_log("--------------------------------------------------\n", 3, $logFile);
error_log("[".$today->format("Y-m-d H:i:s")."] ".$invoice->getRef()." [".$invoice->getId()."]\n", 3, $logFile);
$oldNb = count($oldProducts);
error_log("Old Products : ".$oldNb."\n", 3, $logFile);
foreach ($oldProducts as $product)
{
error_log($product->getAsString()."\n", 3, $logFile);
}
$newNb = count($newProducts);
error_log("New Products : ".$newNb."\n", 3, $logFile);
foreach ($newProducts as $product)
{
error_log($product->getAsString()."\n", 3, $logFile);
}
error_log("--------------------------------------------------\n", 3, $logFile);
}
// Changes done in prePersist / preUpdate are not registred in the
// $changes recorded by the EntityManager
// So they need to be manually logged
public function handleSoldeChanges(Invoice $invoice)
{
// Store the old value
$oldValue = $invoice->getStatus()->getValue();
// Handle totals and decide on status change
$this->handleSolde($invoice);
// Get the new value
$newValue = $invoice->getStatus()->getValue();
// ... and decide if any logging is needed
if ($oldValue == $newValue)
{
return null;
}
$action = "invoice_auto_status_installment";
$loggingData = array('info' => null, 'special_author' => null);
$args = $this->initArgs($invoice, $loggingData);
$args["action"] = $action;
$args["old_value"] = $oldValue;
$args["new_value"] = $newValue;
return $args;
}
public function handleSolde($invoice)
{
// Do nothing is the invoice is annulled
if ($invoice->isAnnulled())
return false;
// Plan.io Task #4326
if ($invoice->isDraft())
{
return false;
}
// Just in case compute totals
$invoice->computeTotals();
// Case : Solde is ZERO, but Status is not "Solde"
if ($invoice->getSolde() == 0.0)
{
// Solde is zero
// If status is "Solde", do nothing
if ($invoice->isBalanced())
return false;
// Status is not "Solde"
// Update it
$balanced = $this->em->getRepository(InvoiceStatus::class)
->findOneBy(array(
'societyGroup' => $invoice->getSocietyGroup(),
'balanced' => 1,
));
if ($balanced !== null)
{
$invoice->setOldStatus($invoice->getStatus());
$invoice->setStatus($balanced);
return true;
}
}
else
{
// Solde is not zero
// If status is not "Solde", do nothing
if ($invoice->isBalanced() == false)
return false;
// Status is "Solde"
// Update it
if ($invoice->getOldStatus() !== null)
$invoice->setStatus($invoice->getOldStatus());
else
$invoice->setStatus($this->decideStatus($invoice));
return true;
}
return false;
}
}