Skip to content

Commit

Permalink
refact: #156 refatora propriedades de colunas de timestamp
Browse files Browse the repository at this point in the history
Este commit refatora as propriedades das colunas de timestamp para o controle manual dos valores. Isso foi necessario para garantir interoperabilidade entre bancos em MariaDB e MySQL devido as diferentes formas na tratativa do valor para timestamps, o que poderia levar a inconsistencias do registro dependendo das definicoes de fuso horario do banco e PHP.

ref: #156
  • Loading branch information
andrekutianski committed May 29, 2024
1 parent 3199fc9 commit 3c1dee4
Show file tree
Hide file tree
Showing 11 changed files with 74 additions and 23 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
composer.phar
.idea
.scripts
whmcs
rsync-dev1.sh
rsync-dev2.sh
*.zip
Expand Down
2 changes: 1 addition & 1 deletion modules/addons/NFEioServiceInvoices/lib/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ final class Configuration extends \WHMCSExpert\mtLibs\process\AbstractConfigurat

private $encryptHash = '';

public $version = '2.1.8';
public $version = '2.2.0';

public $tablePrefix = 'mod_nfeio_si_';

Expand Down
17 changes: 17 additions & 0 deletions modules/addons/NFEioServiceInvoices/lib/Helpers/Timestamp.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

namespace NFEioServiceInvoices\Helpers;

class Timestamp
{
/**
* Retorna a data e hora atual no formato de timestamp padrão.
*
* @see https://github.com/nfe/whmcs-addon/issues/156
* @return string Data e hora atual no formato de timestamp.
*/
public static function currentTimestamp(): string
{
return date('Y-m-d H:i:s');
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace NFEioServiceInvoices\Hooks;

use NFEioServiceInvoices\Helpers\Timestamp;
use WHMCS\Database\Capsule;

/**
Expand Down Expand Up @@ -38,7 +39,7 @@ public function run()
$storageKey = $this->config->getStorageKey();
$serviceInvoicesTable = $this->serviceInvoicesRepo->tableName();
$storage = new \WHMCSExpert\Addon\Storage($storageKey);
$dataAtual = date('Y-m-d H:i:s');
$dataAtual = Timestamp::currentTimestamp();
// caso não exista valor para initial_date inicia define data que garanta a execução da rotina
$initialDate = (! empty($storage->get('initial_date'))) ? $storage->get('initial_date') : '1970-01-01 00:00:00';

Expand Down
6 changes: 5 additions & 1 deletion modules/addons/NFEioServiceInvoices/lib/Legacy/Functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace NFEioServiceInvoices\Legacy;

use NFEioServiceInvoices\Helpers\Timestamp;
use WHMCS\Database\Capsule;
use NFEioServiceInvoices\Addon;
use NFEioServiceInvoices\Helpers\Validations;
Expand Down Expand Up @@ -681,7 +682,10 @@ function update_status_nfe($invoice_id, $status)
$_tableName = $serviceInvoicesRepo->tableName();

try {
$return = Capsule::table($_tableName)->where('invoice_id', '=', $invoice_id)->update(['status' => $status]);
$return = Capsule::table($_tableName)->where('invoice_id', '=', $invoice_id)->update([
'status' => $status,
'updated_at' => Timestamp::currentTimestamp(),
]);
return $return;
} catch (Exception $e) {
return $e->getMessage();
Expand Down
33 changes: 24 additions & 9 deletions modules/addons/NFEioServiceInvoices/lib/Migrations/Migrations.php
Original file line number Diff line number Diff line change
Expand Up @@ -206,17 +206,14 @@ public static function migrateProductCodes()
*
* @param PDO $pdo The PDO object for database connection
* @param string $columnName The name of the column to be altered
* @param string $alterStatement The ALTER statement for the column
* @return void
*/
private function createAlterColumnTimestampStatement($pdo, $columnName, $alterStatement, $tableName)
private function createAlterColumnTimestampStatement($pdo, $columnName, $tableName)
{
$statement = $pdo->prepare(
sprintf('ALTER TABLE %s CHANGE %s %s TIMESTAMP NOT NULL DEFAULT %s',
sprintf('ALTER TABLE %s MODIFY COLUMN %s TIMESTAMP NULL',
$tableName,
$columnName,
$columnName,
$alterStatement
$columnName
)
);
$statement->execute();
Expand All @@ -235,15 +232,21 @@ public static function migrateTimestampColumns(string $tableName)
$pdo->beginTransaction();
try {
$self = new self();
$self->createAlterColumnTimestampStatement($pdo, 'created_at', 'CURRENT_TIMESTAMP', $tableName);
$self->createAlterColumnTimestampStatement($pdo, 'updated_at', 'CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP', $tableName);
$self->createAlterColumnTimestampStatement($pdo, 'created_at', $tableName);
$self->createAlterColumnTimestampStatement($pdo, 'updated_at', $tableName);
if ($pdo->inTransaction()) {
$pdo->commit();
logModuleCall(
'nfeio_serviceinvoices',
'migrateTimestampColumns',
$tableName,
'success'
);
}
} catch (\Exception $e) {
logModuleCall(
'nfeio_serviceinvoices',
'upgradeServiceInvoicesTimestampColumns_error',
'migrateTimestampColumns',
$e->getMessage(),
$e->getTraceAsString()
);
Expand All @@ -266,6 +269,18 @@ public static function changeProductCodeTimestampColumnsName()

if (Capsule::schema()->hasTable('mod_nfeio_si_productcode')) {

// verifica se a coluna create_at e update_at já foram migradas (existem)
$columns = Capsule::schema()->getColumnListing('mod_nfeio_si_productcode');
if (!in_array('create_at', $columns) || !in_array('update_at', $columns)) {
logModuleCall(
'nfeio_serviceinvoices',
'changeProductCodeTimestampColumnsName',
'nothing to do, columns already exist',
''
);
return;
}

$pdo = Capsule::connection()->getPdo();
$pdo->beginTransaction();
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,13 +93,13 @@ function ($table) {
$table->string('code_service', 30);
// retenção de ISS
$table->float('iss_held', 5, 2)->nullable();
$table->timestamp('created_at')->useCurrent();
$table->timestamp('updated_at')->useCurrent();
$table->timestamp('created_at')->nullable();
$table->timestamp('updated_at')->nullable();
}
);

// Adiciona a coluna updated_at com a configuração de auto update #156
$db->statement(sprintf('ALTER TABLE %s CHANGE updated_at updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP', $this->tableName));
// $db->statement(sprintf('ALTER TABLE %s CHANGE updated_at updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP', $this->tableName));

}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -120,14 +120,14 @@ function ($table) {
$table->increments('id');
$table->integer('product_id');
$table->string('code_service', 30);
$table->timestamp('created_at')->useCurrent();
$table->timestamp('updated_at')->useCurrent();
$table->timestamp('created_at')->nullable();
$table->timestamp('updated_at')->nullable();
$table->integer('ID_user');
}
);

// Adiciona a coluna updated_at com a configuração de auto update #156
$db->statement(sprintf('ALTER TABLE %s CHANGE updated_at updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP', $this->tableName));
// $db->statement(sprintf('ALTER TABLE %s CHANGE updated_at updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP', $this->tableName));

}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace NFEioServiceInvoices\Models\ServiceInvoices;

use Illuminate\Database\Capsule\Manager as Capsule;
use NFEioServiceInvoices\Helpers\Timestamp;

/**
* Classe responsável pela definição do modelo de dados e operações
Expand Down Expand Up @@ -118,16 +119,16 @@ function ($table) {
$table->string('pdf');
$table->string('rpsSerialNumber');
$table->string('rpsNumber');
$table->timestamp('created_at')->useCurrent();
$table->timestamp('updated_at')->useCurrent();
$table->timestamp('created_at')->nullable();
$table->timestamp('updated_at')->nullable();
$table->string('service_code', 30)->nullable(true);
$table->string('tics')->nullable(true);
}
);
}

// Adiciona a coluna updated_at com a configuração de auto update #156
$db->statement(sprintf('ALTER TABLE %s CHANGE updated_at updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP', $this->tableName));
// $db->statement(sprintf('ALTER TABLE %s CHANGE updated_at updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP', $this->tableName));

}

Expand Down Expand Up @@ -264,6 +265,9 @@ public function updateNfStatusByExternalId($externalId, $status, $flowStatus = n
$data['flow_status'] = $flowStatus;
}

// adiciona a data de atualização #156
$data['updated_at'] = Timestamp::currentTimestamp();

try {
Capsule::table($this->tableName)
->where('nfe_external_id', $externalId)
Expand Down Expand Up @@ -304,6 +308,9 @@ public function updateNfStatusByNfeId($nfeId, $status, $flowStatus = null)
$data['flow_status'] = $flowStatus;
}

// adiciona a data de atualização #156
$data['updated_at'] = Timestamp::currentTimestamp();

try {
Capsule::table($this->tableName)
->where('nfe_id', $nfeId)
Expand Down
7 changes: 6 additions & 1 deletion modules/addons/NFEioServiceInvoices/lib/NFEio/Nfe.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace NFEioServiceInvoices\NFEio;

use NFEioServiceInvoices\Helpers\Timestamp;
use WHMCS\Database\Capsule;

/**
Expand Down Expand Up @@ -304,6 +305,10 @@ public function queue($invoiceId, $reissue = false)
continue;
}

// timestamps
$nf['created_at'] = Timestamp::currentTimestamp();
$nf['updated_at'] = Timestamp::currentTimestamp();

$result = Capsule::table($this->serviceInvoicesTable)->insert($nf);
logModuleCall('nfeio_serviceinvoices', 'nf_queue', $nf, $result);
}
Expand Down Expand Up @@ -333,7 +338,7 @@ public function emit($data)

// se dados do cliente retornarem erro, atualiza status da NF e para emissao
if ($customer['error']) {
$this->legacyFunctions->update_status_nfe($invoiceId, 'Doc_Error');
$this->updateLocalNfeStatusByExternalId($externalId, 'Doc_Error');
logModuleCall('nfeio_serviceinvoices', 'nf_emit_error', $data, $customer);
return;
}
Expand Down
2 changes: 1 addition & 1 deletion modules/addons/NFEioServiceInvoices/whmcs.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"type": "whmcs-addons",
"name": "NFEioServiceInvoices",
"license": "MIT",
"category": "utilities",
"category": "finance",
"description": {
"name": "NFE.io NFSe",
"tagline": "Automatize a emissão de notas fiscais no WHMCS com a NFE.io",
Expand Down

0 comments on commit 3c1dee4

Please sign in to comment.