Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 0 additions & 3 deletions admin/setup.php
Original file line number Diff line number Diff line change
Expand Up @@ -225,9 +225,6 @@ class="valignmiddle inline-block linkobject hideobject"
$toggle->fieldOverride = ob_get_clean();
}

$formSetup->newItem('ADVANCED_SECTION_TITLE')->setAsTitle();
$spitInvoices = $formSetup->newItem('AUTOVERIFACTU_SPLIT_INVOICES')->setAsYesNo();

$setupnotempty += count($formSetup->items);

/*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,8 @@ public function runTrigger($action, $object, $user, $langs, $conf)
return 0;
}

static $context;
$langs->load('autoverifactu@autoverifactu');

/**
* Tracked invoices types:
* 0: Default ✓
Expand All @@ -98,7 +98,6 @@ public function runTrigger($action, $object, $user, $langs, $conf)
// As far as i know, they have to be declared as invoices to the AEAT, it isn't?
switch ($action) {
case 'BILL_CREATE':

if (isset($object->context['createfromclone'])) {
$object->array_options['options_verifactu_tms'] = null;
$object->array_options['options_verifactu_hash'] = null;
Expand All @@ -111,82 +110,6 @@ public function runTrigger($action, $object, $user, $langs, $conf)
}
}

if (!$context) {
$context = new stdClass;
$context->invoice = $object;
}

if (
$object->origin
&& $object->origin_id
&& getDolGlobalInt('AUTOVERIFACTU_SPLIT_INVOICES')
) {
global $db, $user;

if (isset($context->origin) && $context->origin->element === $object->origin) {
return;
}

if ($object->origin === 'propal') {
dol_include_once('/comm/propal/class/propal.class.php');
$sourceObject = new Propal($db);
} elseif ($object->origin_type === 'order' || $object->origin_type === 'commande') {
dol_include_once('/commande/class/commande.class.php');
$sourceObject = new Commande($db);
} elseif ($object->origin_type === 'contrat' || $object->origin_type === 'contract') {
dol_include_once('/contrat/class/contrat.class.php');
$sourceObject = new Contrat($db);
} elseif ($object->origin_type === 'shipping') {
dol_include_once('/expedition/class/expedition.class.php');
$sourceObject = new Expedition($db);
} elseif ($object->origin_type === 'fichinter') {
dol_include_once('/fichinter/class/fichinter.class.php');
$sourceObject = new Fichinter($db);
}

if (!isset($sourceObject)) {
return;
}

$sourceObject->fetch($object->origin_id);
$sourceObject->fetch_lines();

$context->origin = $sourceObject;

$sourceLines = count($sourceObject->lines);
if ($sourceLines > 12) {
$context->splitInvoice = true;

$sourceLines -= 12;

while ($sourceLines >= 0) {
$siblingId = $object->createFromCurrent($user);
if ($siblingId < 0) {
dol_syslog('Unable to create a copy of the invoice in the split invoices loop', LOG_ERR);
$this->errors[] = $langs->trans('SplitInvoiceError');
return $siblingId;
}

$result = $object->add_object_linked('facture', $siblingId);
if ($result < 0) {
dol_syslog('Unable to link the partial invoice to the source invoice', LOG_ERR);
$this->errors[] = $langs->trans('SplitInvoiceError');
return $result;
}

$result = $sourceObject->add_object_linked('facture', $siblingId);
if ($result < 0) {
dol_syslog('Unable to link the partial invoice to the source entity', LOG_ERR);
$this->errors[] = $langs->trans('SplitInvoiceError');
return $result;
}

$sourceLines -= 12;
}
}
}


//al crear una factura tipo rectificativa tenemos que borrar el hash y los demas campos
if ($object->type == Facture::TYPE_REPLACEMENT || $object->type == Facture::TYPE_CREDIT_NOTE) {
$object->array_options['options_verifactu_tms'] = null;
Expand Down Expand Up @@ -229,19 +152,11 @@ public function runTrigger($action, $object, $user, $langs, $conf)
}
return $result;
case 'BILL_VALIDATE':

// case 'DON_VALIDATE':
/* $object->fetch_lines();
if (is_array($object->lines) && count($object->lines) > 12) {
dol_syslog('Veri*Factu bans invoices with more than 12 lines', LOG_INFO);
$this->errors[] = $langs->trans('MaxInvoiceLinesError');
return -1;
} */
//verificamos que el tiempo de espera a pasado
// y si no lo incluimos en la lista de pendientes de envio

$now = new DateTimeImmutable('now', new DateTimeZone('Europe/Madrid'));

//verificamos que el tiempo de espera a pasado
// y si no lo incluimos en la lista de pendientes de envio
if ($now->getTimestamp() < getDolGlobalString('VERIFACTU_NEXT_DELIVERY_ALLOWED', '0')) {
if (in_array($object->array_options['options_verifactu_status'], array('2','4','5'), true)) {
//en caso de eser facturas con errores,
Expand Down Expand Up @@ -303,75 +218,6 @@ public function runTrigger($action, $object, $user, $langs, $conf)
return -1;
}

break;
case 'LINEBILL_INSERT':
global $db, $mysoc;

$facture = $context->invoice ?? null;

if (!$facture) {
$facture = new Facture($db);
$facture->fetch($object->fk_facture);
}

$facture->fetch_lines();

if (count($facture->lines) > 12) {
if (isset($context->splitInvoice) && $context->splitInvoice) {
$result = $facture->fetchObjectLinked();
if ($result < 0) {
dol_syslog('Error while loading partial invoices relations', LOG_ERR);
$this->errors[] = $langs->trans('FetchSplitInvoicesError');
return $result;
}

$linkedInvoices = $facture->linkedObjects['facture'] ?? array();
foreach ($linkedInvoices as $candidate) {
$candidate->fetch_lines();

if (count($candidate->lines) < 12) {
$linkedInvoice = $candidate;
}
}

if (!isset($linkedInvoice)) {
dol_syslog('Error while loading partial invoices relations', LOG_ERR);
$this->errors[] = $langs->trans('MaxInvoiceLinesError');
return -1;
}

$result = $object->delete(null, 1);
if ($result < 0) {
dol_syslog('Error while shifting lines from split partial invoice', LOG_ERR);
$this->errors[] = $langs->trans('SplitInvoiceLinesError');
return -1;
}

$object->fk_facture = $linkedInvoice->id;
$result = $object->insert($user, 1);
if ($result < 0) {
dol_syslog('Error while shifting lines from a split partial invoice', LOG_ERR);
$this->errors[] = $langs->trans('SplitInvoiceLinesError');
return -1;
}

$linkedInvoice->update_price(1, 'auto', 0, $mysoc);
} else {
dol_syslog('Veri*Factu bans invoices with more than 12 lines', LOG_INFO);
setEventMessage($langs->trans('MaxInvoiceLinesWarn'), 'warnings');
}
}

break;
case 'LINEPROPAL_INSERT':
case 'LINEORDER_INSERT':
case 'LINECONTRACT_INSERT':
case 'LINEFICHINTER_CREATE':
case 'LINESHIPPING_INSERT':
if (!getDolGlobalInt('AUTOVERIFACTU_SPLIT_INVOICES')) {
setEventMessage($langs->trans('MaxEntityLinesWarn'), 'warnings');
}

break;
case 'USER_LOGOUT':
autoverifactu_set_const('AUTOVERIFACTU_DISMISSED_NOTICES', '');
Expand Down
2 changes: 0 additions & 2 deletions langs/ca_ES/autoverifactu.lang
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,6 @@ YourCompanyVat = NIF/CIF
PK12_PATH = ruta/al/teu/certificat.p12
UploadCertificate = Puja el teu certificat
ADVANCED_SECTION_TITLE = Avançat
AUTOVERIFACTU_SPLIT_INVOICES = Generar múltiples factures automàticament en superar el límit de línies
AUTOVERIFACTU_SPLIT_INVOICESTooltip = Durant la generació de factures en base a documents relacionats (pressupost, comanda, contracte, etc.), en cas que el document original super el nombre màxim de línies de factura permeses per Veri*Factu, es generaran múltiples factures automàticament respectant el límit de línies per cadascuna.

#
# Autodeclaration page
Expand Down
2 changes: 0 additions & 2 deletions langs/en_US/autoverifactu.lang
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,6 @@ YourCompanyVat = Your company VAT number
PK12_PATH = path/to/your/certificate.p12
UploadCertificate = Upload your certificate
ADVANCED_SECTION_TITLE = Advaned
AUTOVERIFACTU_SPLIT_INVOICES = Automatically split invoices when maximum number of lines for invoice is reached
AUTOVERIFACTU_SPLIT_INVOICESTooltip = During invoice generation based on related documents (quotation, order, contract, etc.), if the original document exceeds the maximum number of allowed invoice lines by Veri*Factu, it will be splitted into multiple invoices, each adhering to the line limit.

#
# Autodeclaration page
Expand Down
4 changes: 1 addition & 3 deletions langs/es_ES/autoverifactu.lang
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,6 @@ YourCompanyVat = NIF/CIF
PK12_PATH = ruta/a/tu/certificado.p12
UploadCertificate = Sube tu cirtificado
ADVANCED_SECTION_TITLE = Avanzado
AUTOVERIFACTU_SPLIT_INVOICES = Generar múltiples facturas automáticamente al superar el límite de líneas
AUTOVERIFACTU_SPLIT_INVOICESTooltip = Durante la generación de facturas en base a documentos relacionados (presupuesto, pedido, contrato, etc.), en cas que el documento original supere el número máximo de líneas de factura permitidas per Veri*Factu, se generarán múltiples facturas automaticamente respetando el límite de líneas per cada una de ellas.

#
# Autodeclaration page
Expand Down Expand Up @@ -272,4 +270,4 @@ NotValidTaxAmountEquivalenceSurcharge=El valor del Recargo de Equivalencia no es
NotValidTaxAmount=Los valores de los impuestos no son válidos.
NotValueTotal=El valor del total no son válidos.
NotTypeIdentificationThirdparty=Cuando el tercero no es de la unión Europea (no tiene CIF Intra.), debe indicar que tipo de documento identificativo esta usando.
maximumNumberOfTaxRates=Se ha sobrepasado el número máximo de tipos impositivos de una factura.
maximumNumberOfTaxRates=Se ha sobrepasado el número máximo de tipos impositivos de una factura.
28 changes: 5 additions & 23 deletions lib/verifactu.lib.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,19 +58,13 @@
*/
function autoverifactuRegisterInvoice($invoice, $action)
{



global $db, $conf, $hookmanager;

$error;
if ($invoice->type > Facture::TYPE_DEPOSIT) {
// Skip non recordable invoice types.
return 0;
}



if (
$invoice->status == Facture::STATUS_DRAFT &&
!in_array(
Expand Down Expand Up @@ -179,7 +173,6 @@ function autoverifactuRegisterInvoice($invoice, $action)
try {
$record = autoverifactuSendInvoice($invoice, $action, $xml);


// Skip document generation if send does not succeed.
if (!$record) {
return 0;
Expand All @@ -200,7 +193,6 @@ function autoverifactuRegisterInvoice($invoice, $action)
$invoice->array_options['options_verifactu_error_code'] = $error->code;
}


$result = $invoice->insertExtraFields();

if ($result <= 0) {
Expand Down Expand Up @@ -261,7 +253,6 @@ function autoverifactuSendInvoice($invoice, $action, &$xml = '')

$recordType = ($action === 'BILL_VALIDATE' || $action === 'verifactuResend') ? 'alta' : 'anulacion';


if ($recordType === 'alta' && autoverifactuIsInvoiceRecorded($invoice)) {
dol_syslog(
'Skip verifactu invoice registration because invoice #'
Expand All @@ -272,15 +263,14 @@ function autoverifactuSendInvoice($invoice, $action, &$xml = '')
return -1 ;
}


$record = autoverifactuInvoiceToRecord($invoice, $recordType);


if (!$record) {
throw new Exception('Inconsistent invoice data');
}

global $hookmanager;

$parameters = array('record' => &$record, 'invoice' => $invoice, 'action' => $action);
$reshook = $hookmanager->executeHooks(
'autoverifactuRecord',
Expand All @@ -306,6 +296,7 @@ function autoverifactuSendInvoice($invoice, $action, &$xml = '')
'name' => $mysoc->nom,
'idprof1' => $mysoc->idprof1,
);

//no exisiste la funcion autoverifactuValidateIssuer
/*$issuerIsValid = autoverifactuValidateIssuer($issuer);

Expand All @@ -317,7 +308,6 @@ function autoverifactuSendInvoice($invoice, $action, &$xml = '')
$record,
$issuer
);
$res;

try {
$res = autoverifactuSoapRequest($envelope);
Expand All @@ -339,19 +329,12 @@ function autoverifactuSendInvoice($invoice, $action, &$xml = '')
}


$status = $res->getElementsByTagName('EstadoRegistro')[0];
/* echo "<br>";
echo "<br>";
echo "---------------NODE-----------------";
echo "<br>";
var_dump($status->nodeValue);
echo "<br>";
echo "---------------NODE-----------------";
echo "<br>";
echo "<br>"; */
$status = $res->getElementsByTagName('EstadoRegistro')->item(0);

if ($status->nodeValue === 'Incorrecto') {
dol_syslog('# REJECTED SOAP ENVELOPE', LOG_DEBUG);
dol_syslog($envelope, LOG_DEBUG);

if ($operationTypeNode->nodeValue === 'Anulacion') {
//error de anulacion
$invoice->array_options['options_verifactu_status'] = '7';
Expand Down Expand Up @@ -442,7 +425,6 @@ function autoverifactuSendInvoice($invoice, $action, &$xml = '')
*/
function autoverifactuSoapRequest($body, $ttl = 3)
{

global $db;
$testMode = (bool) getDolGlobalString('AUTOVERIFACTU_TEST_MODE');
$base_url = $testMode ? VERIFACTU_TEST_BASE_URL : VERIFACTU_BASE_URL;
Expand Down
Loading