Skip to content

Commit

Permalink
Merge pull request #32 from LinkNacional/master
Browse files Browse the repository at this point in the history
1.2.9 criação de arquivo para debug e ajustes finos.
  • Loading branch information
gblmarquez authored Mar 31, 2021
2 parents eec793f + 44697e1 commit ec8f343
Show file tree
Hide file tree
Showing 14 changed files with 477 additions and 617 deletions.
145 changes: 7 additions & 138 deletions modules/addons/gofasnfeio/callback.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,12 @@
use WHMCS\Database\Capsule;

$post = json_decode(file_get_contents('php://input'), true);
logModuleCall('gofas_nfeio', 'callback', $post, '', '', 'replaceVars');
logModuleCall('gofas_nfeio', 'callback db', Capsule::table('gofasnfeio')->where('nfe_id', '=', $post['id'])->count(), '', '', 'replaceVars');
logModuleCall('gofas_nfeio', 'callback environment', $post['environment'], '', '', 'replaceVars');

if ($post) {
require_once __DIR__ . '/functions.php';
//remover sempre que estiver na instalação de teste
if (Capsule::table('gofasnfeio')->where('nfe_id', '=', $post['id'])->count() == 0 || $post['environment'] != 'Production') {
return '';
}

$params = [];
foreach (Capsule::table('tbladdonmodules')->where('module', '=', 'gofasnfeio')->get(['setting', 'value']) as $settings) {
$params[$settings->setting] = $settings->value;
Expand Down Expand Up @@ -44,138 +40,11 @@
$e->getMessage();
}
}
if ($params['debug']) {
logModuleCall('gofas_nfeio', 'receive_callback', ['post' => $post], 'post', ['nfe_local' => $nfe], 'replaceVars');
}

foreach (Capsule::table('gofasnfeio')->orderBy('id', 'desc')->where('status', '=', 'Waiting')->take(1)->get(['id', 'invoice_id', 'service_code', 'services_amount']) as $waiting) {
//$invoices[] = $Waiting->invoice_id;
$data = getTodaysDate(false);
$dataAtual = toMySQLDate($data);

if ($params['issue_note'] !== 'Manualmente') {
$getQuery = Capsule::table('tblinvoices')->whereBetween('date', [$params['initial_date'], $dataAtual])->where('id', '=', $waiting->invoice_id)->get(['id', 'userid', 'total']);
} else {
$getQuery = Capsule::table('tblinvoices')->where('id', '=', $waiting->invoice_id)->get(['id', 'userid', 'total']);
}

foreach ($getQuery as $invoices) {
$invoice = localAPI('GetInvoice', ['invoiceid' => $waiting->invoice_id], false);
$client = localAPI('GetClientsDetails', ['clientid' => $invoice['userid'], 'stats' => false], false);
foreach ($invoice['items']['item'] as $value) {
$line_items[] = $value['description'];
}
$customer = gnfe_customer($invoices->userid, $client);
$gnfe_get_nfes = gnfe_get_nfes();
if ($params['rps_serial_number']) {
$rps_serial_number = $params['rps_serial_number'];
$rps_serial_number_ = false;
} elseif (!$params['rps_serial_number'] and $gnfe_get_nfes['serviceInvoices']['0']['rpsSerialNumber']) {
$rps_serial_number = $gnfe_get_nfes['serviceInvoices']['0']['rpsSerialNumber'];
$rps_serial_number_ = $rps_serial_number;
} elseif (!$params['rps_serial_number'] and !$gnfe_get_nfes['serviceInvoices']['0']['rpsSerialNumber']) {
$rps_serial_number = 'IO';
$rps_serial_number_ = $rps_serial_number;
}
///
if ($params['rps_number'] and (string) $params['rps_number'] !== (string) 'zero') {
$rps_number = $params['rps_number'];
} elseif ((!$params['rps_number'] or (string) $params['rps_number'] === (string) 'zero') and $gnfe_get_nfes['serviceInvoices']['0']['rpsNumber']) {
$rps_number = $gnfe_get_nfes['serviceInvoices']['0']['rpsNumber'];
} elseif (((string) $params['rps_number'] === (string) 'zero' and !$gnfe_get_nfes['serviceInvoices']['0']['rpsNumber']) or (!$params['rps_number'] and !$gnfe_get_nfes['serviceInvoices']['0']['rpsNumber'])) {
$rps_number = 0;
}
$invoice_id = Capsule::table('gofasnfeio')->where('nfe_id', '=', $post['id'])->get(['invoice_id'])[0];

if ($customer['doc_type'] == 2) {
$name = $client['companyname'];
} elseif ($customer['doc_type'] == 1 || $customer == 'CPF e/ou CNPJ ausente.' || !$customer['doc_type']) {
$name = $client['fullname'];
}

$name = htmlspecialchars_decode($name);

$service_code = $waiting->service_code ? $waiting->service_code : $params['service_code'];

foreach (Capsule::table('tblconfiguration')->where('setting', '=', 'Domain')->get(['value']) as $gnfewhmcsadminurl) {
$gnfewhmcsadminurl = $gnfewhmcsadminurl->value;
}
$desc = 'Nota referente a fatura #' . $waiting->invoice_id . ' ' . $gnfewhmcsadminurl . 'viewinvoice.php?id=' . $waiting->invoice_id . ' ';
if (!strlen($customer['insc_municipal'] == 0)) {
$postfields = [
'cityServiceCode' => $service_code,
'description' => $desc,
'servicesAmount' => $waiting->services_amount,
'borrower' => [
'federalTaxNumber' => $customer['document'],
'municipalTaxNumber' => $customer['insc_municipal'],
'name' => $name,
'email' => $client['email'],
'address' => [
'country' => gnfe_country_code($client['countrycode']),
'postalCode' => preg_replace('/[^0-9]/', '', $client['postcode']),
'street' => str_replace(',', '', preg_replace('/[0-9]+/i', '', $client['address1'])),
'number' => preg_replace('/[^0-9]/', '', $client['address1']),
'additionalInformation' => '',
'district' => $client['address2'],
'city' => [
'code' => gnfe_ibge(preg_replace('/[^0-9]/', '', $client['postcode'])),
'name' => $client['city'],
],
'state' => $client['state'],
],
],
'rpsSerialNumber' => $rps_serial_number,
'rpsNumber' => (int) $rps_number + 1,
];
} else {
$postfields = [
'cityServiceCode' => $service_code,
'description' => $desc,
'servicesAmount' => $waiting->services_amount,
'borrower' => [
'federalTaxNumber' => $customer['document'],
'name' => $name,
'email' => $client['email'],
'address' => [
'country' => gnfe_country_code($client['countrycode']),
'postalCode' => preg_replace('/[^0-9]/', '', $client['postcode']),
'street' => str_replace(',', '', preg_replace('/[0-9]+/i', '', $client['address1'])),
'number' => preg_replace('/[^0-9]/', '', $client['address1']),
'additionalInformation' => '',
'district' => $client['address2'],
'city' => [
'code' => gnfe_ibge(preg_replace('/[^0-9]/', '', $client['postcode'])),
'name' => $client['city'],
],
'state' => $client['state'],
],
],
'rpsSerialNumber' => $rps_serial_number,
'rpsNumber' => (int) $rps_number + 1,
];
}

if ($params['debug']) {
logModuleCall('gofas_nfeio', 'callback', $postfields, '', '', 'replaceVars');
}

$nfe = gnfe_issue_nfe($postfields);
if ($nfe->message) {
$error .= $nfe->message;
}
if (!$nfe->message) {
$gnfe_update_nfe = gnfe_update_nfe($nfe, $invoices->userid, $invoices->id, 'n/a', date('Y-m-d H:i:s'), date('Y-m-d H:i:s'), $waiting->id);
if ($gnfe_update_nfe and 'success' !== $gnfe_update_nfe) {
$error = $gnfe_update_nfe;
}
$update_rps = gnfe_update_rps($rps_serial_number_, $rps_number);
if ($update_rps and 'success' !== $update_rps) {
$error = $update_rps;
}
}
}
if ($params['debug']) {
logModuleCall('gofas_nfeio', 'after_receive_callback', ['$params' => $params, '$datepaid' => $datepaid, '$datepaid_to_issue' => $datepaid_to_issue], 'post', ['$processed_invoices' => $processed_invoices, '$nfe' => $nfe, 'error' => $error], 'replaceVars');
}
if ($post['status'] == 'Error') {
logModuleCall('gofas_nfeio', 'callback', '', $post, 'ERROR', '');
} else {
logModuleCall('gofas_nfeio', 'callback', '', $post, 'OK', '');
}
}
}
85 changes: 35 additions & 50 deletions modules/addons/gofasnfeio/config.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use WHMCS\Database\Capsule;

require_once __DIR__ . '/functions.php';
require_once __DIR__ . '/update.php';

if (!function_exists('gofasnfeio_config')) {
if (!function_exists('gnfe_customfields_dropdow')) {
Expand All @@ -29,9 +30,35 @@ function gnfe_customfields_dropdow() {
return $dropFieldArray;
}
}
function gnfe_verify_module_updates() {
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://api.github.com/repos/nfe/whmcs-addon/releases');
curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-type: application/json', 'User-Agent: whmcs_nfeio']);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 30);
$response = curl_exec($curl);
curl_close($curl);
return json_decode($response)[0]->tag_name;
}
function gofasnfeio_config() {
$module_version = '1.2.8';
if ($_GET['doc_log']) {
dowload_doc_log();
}
$previous_version = Capsule::table('tbladdonmodules')->where('module','=','gofasnfeio')->where('setting','=','version')->get(['value'])[0]->value;

$module_version = '1.2.9';
// Verify available updates
$available_update_ = gnfe_verify_module_updates();
$module_version_int = (int) preg_replace('/[^0-9]/', '', $module_version);
$available_version_int = (int) preg_replace('/[^0-9]/', '', str_replace('v','',$available_update_));

if ($available_version_int <= $module_version_int) {
$available_update_message = '<p style="font-size: 14px;color:green;"><i class="fas fa-check-square"></i> Você está executando a versão mais recente do módulo.</p>';
} else {
$available_update_message = '<p style="font-size: 14px;color:red;"><i class="fas fa-exclamation-triangle"></i> Nova versão disponível no <a style="color:#CC0000;text-decoration:underline;" href="https://github.com/nfe/whmcs-addon/releases" target="_blank">Github</a></p>';
}

/// REMOVER VERIFICAÇÃO APÓS VERSÃO 2.0
$verificarEmail = Capsule::table('tbladdonmodules')->where('module', '=', 'gofasnfeio')->where('setting', '=', 'gnfe_email_nfe_config')->count();
Expand Down Expand Up @@ -117,57 +144,15 @@ function gofasnfeio_config() {
}
}
}
// Verify available updates
$available_update_message = '<p style="font-size: 14px;color:red;"><i class="fas fa-exclamation-triangle"></i> Nova versão disponível no <a style="color:#CC0000;text-decoration:underline;" href="https://github.com/nfe/whmcs-addon/releases" target="_blank">Github</a></p>';

if (!function_exists('gnfe_verifyInstall')) {
function gnfe_verifyInstall() {
if (!Capsule::schema()->hasTable('gofasnfeio')) {
try {
Capsule::schema()->create('gofasnfeio', function ($table) {
// incremented id
$table->increments('id');
// whmcs info
$table->string('invoice_id');
$table->string('user_id');
$table->string('nfe_id');
$table->string('status');
$table->string('services_amount');
$table->string('environment');
$table->string('flow_status');
$table->string('pdf');
$table->string('rpsSerialNumber');
$table->string('rpsNumber');
$table->string('created_at');
$table->string('updated_at');
});
} catch (\Exception $e) {
$error .= "Não foi possível criar a tabela do módulo no banco de dados: {$e->getMessage()}";
}
}
// Added in v 1 dot 1 dot 3
if (!Capsule::schema()->hasColumn('gofasnfeio', 'rpsNumber')) {
try {
Capsule::schema()->table('gofasnfeio', function ($table) {
$table->string('rpsNumber');
});
} catch (\Exception $e) {
$error .= "Não foi possível atualizar a tabela do módulo no banco de dados: {$e->getMessage()}";
}
}

if (!$error) {
return ['sucess' => 1];
}
if ($error) {
return ['error' => $error];
}
}
}
//create tables
gnfe_verifyInstall();
create_table_product_code();
set_code_service_camp_gofasnfeio();
set_custom_field_ini_date();
//
if (version_compare($previous_version,'1.2.7','<')) {
set_code_service_camp_gofasnfeio();
set_custom_field_ini_date();
}

$intro = ['intro' => [
'FriendlyName' => '',
Expand Down Expand Up @@ -229,7 +214,7 @@ function gnfe_verifyInstall() {
'FriendlyName' => 'Debug',
'Type' => 'yesno',
'Default' => 'yes',
'Description' => 'Marque essa opção para salvar informações de diagnóstico no <a target="_blank" style="text-decoration:underline;" href="' . $admin_url . 'systemmodulelog.php">Log de Módulo</a>',
'Description' => 'Marque essa opção para salvar informações de diagnóstico no <a target="_blank" style="text-decoration:underline;" href="' . $admin_url . 'systemmodulelog.php">Log de Módulo</a> | Emitir documento de log <a target="_blank" href="' . $admin_url . 'configaddonmods.php?doc_log=true" style="text-decoration:underline;">AQUI</a>',
]];
$insc_municipal = ['insc_municipal' => [
'FriendlyName' => 'Inscrição Municipal',
Expand Down
Loading

0 comments on commit ec8f343

Please sign in to comment.