diff --git a/modules/addons/gofasnfeio/callback.php b/modules/addons/gofasnfeio/callback.php index c78e911..af89dba 100644 --- a/modules/addons/gofasnfeio/callback.php +++ b/modules/addons/gofasnfeio/callback.php @@ -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; @@ -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', ''); } -} +} \ No newline at end of file diff --git a/modules/addons/gofasnfeio/config.php b/modules/addons/gofasnfeio/config.php index 4ae3729..406dd4c 100644 --- a/modules/addons/gofasnfeio/config.php +++ b/modules/addons/gofasnfeio/config.php @@ -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')) { @@ -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 = '

Você está executando a versão mais recente do módulo.

'; + } else { + $available_update_message = '

Nova versão disponível no Github

'; + } /// REMOVER VERIFICAÇÃO APÓS VERSÃO 2.0 $verificarEmail = Capsule::table('tbladdonmodules')->where('module', '=', 'gofasnfeio')->where('setting', '=', 'gnfe_email_nfe_config')->count(); @@ -117,57 +144,15 @@ function gofasnfeio_config() { } } } - // Verify available updates - $available_update_message = '

Nova versão disponível no Github

'; - 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' => '', @@ -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 Log de Módulo', + 'Description' => 'Marque essa opção para salvar informações de diagnóstico no Log de Módulo | Emitir documento de log AQUI', ]]; $insc_municipal = ['insc_municipal' => [ 'FriendlyName' => 'Inscrição Municipal', diff --git a/modules/addons/gofasnfeio/functions.php b/modules/addons/gofasnfeio/functions.php index 3dea620..8da8377 100644 --- a/modules/addons/gofasnfeio/functions.php +++ b/modules/addons/gofasnfeio/functions.php @@ -165,10 +165,17 @@ function gnfe_ibge($zip) { curl_setopt($curl, CURLOPT_TIMEOUT, 30); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $response = curl_exec($curl); + $err = curl_error($curl); + curl_close($curl); $city = json_decode(json_encode(json_decode($response))); - return $city->city->code; + if ($city->message || $err) { + logModuleCall('gofas_nfeio', 'gnfe_ibge', $zip, $city->message, 'ERROR', ''); + return 'ERROR'; + } else { + return $city->city->code; + } } } if (!function_exists('gnfe_queue_nfe')) { @@ -262,46 +269,41 @@ function gnfe_issue_nfe($postfields) { $check_webhook = gnfe_check_webhook($gnfe_webhook_id); $error = ''; if ($check_webhook['message']) { - $error .= $check_webhook['message']; + logModuleCall('gofas_nfeio', 'gnfe_issue_nfe - check_webhook', $gnfe_webhook_id, $check_webhook['message'], 'ERROR', ''); } } if ($gnfe_webhook_id and (string) $check_webhook['hooks']['url'] !== (string) $webhook_url) { $create_webhook = gnfe_create_webhook($webhook_url); if ($create_webhook['message']) { - $error .= $create_webhook['message']; + logModuleCall('gofas_nfeio', 'gnfe_issue_nfe - gnfe_create_webhook', $webhook_url, $create_webhook['message'], 'ERROR', ''); } if ($create_webhook['hooks']['id']) { try { Capsule::table('tblconfiguration')->where('setting', 'gnfe_webhook_id')->update(['value' => $create_webhook['hooks']['id'], 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s')]); - } catch (\Exception $e) { - $error .= $e->getMessage(); + } catch (Exception $e) { + logModuleCall('gofas_nfeio', 'gnfe_issue_nfe - Capsule::table(tblconfiguration) update', '', $e->getMessage(), 'ERROR', ''); } } $delete_webhook = gnfe_delete_webhook($gnfe_webhook_id); if ($delete_webhook['message']) { - $error .= $create_webhook['message']; + logModuleCall('gofas_nfeio', 'gnfe_issue_nfe - gnfe_delete_webhook', $gnfe_webhook_id, $delete_webhook, 'ERROR', ''); } } if (!$gnfe_webhook_id) { $create_webhook = gnfe_create_webhook($webhook_url); if ($create_webhook['message']) { - $error .= $create_webhook['message']; + logModuleCall('gofas_nfeio', 'gnfe_issue_nfe - gnfe_create_webhook', $webhook_url, $create_webhook, 'ERROR', ''); } if ($create_webhook['hooks']['id']) { try { Capsule::table('tblconfiguration')->insert(['setting' => 'gnfe_webhook_id', 'value' => $create_webhook['hooks']['id'], 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s')]); - } catch (\Exception $e) { - $error .= $e->getMessage(); + } catch (Exception $e) { + logModuleCall('gofas_nfeio', 'gnfe_issue_nfe - Capsule::table(tblconfiguration) insert', '', $e->getMessage(), 'ERROR', ''); } } } - if (gnfe_config('debug')) { - logModuleCall('gofas_nfeio', 'check_webhook', $postfields, 'post', ['create_webhook' => $create_webhook, 'delete_webhook' => $delete_webhook, 'error' => $error], 'replaceVars'); - } $curl = curl_init(); - logModuleCall('gofas_nfeio', 'teste', 'teste', '', '', 'replaceVars'); - curl_setopt($curl, CURLOPT_URL, 'https://api.nfe.io/v1/companies/' . gnfe_config('company_id') . '/serviceinvoices'); curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: text/json', 'Accept: application/json', 'Authorization: ' . gnfe_config('api_key')]); curl_setopt($curl, CURLOPT_TIMEOUT, 30); @@ -309,11 +311,16 @@ function gnfe_issue_nfe($postfields) { curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($postfields)); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $response = curl_exec($curl); + $err = curl_error($curl); $info = curl_getinfo($curl); curl_close($curl); - logModuleCall('gofas_nfeio', 'response', $response, '', '', 'replaceVars'); - logModuleCall('gofas_nfeio', 'info', $info, '', '', 'replaceVars'); - return json_decode(json_encode(json_decode($response))); + logModuleCall('gofas_nfeio', 'gnfe_issue_nfe - curl_init', $error, $info, '', ''); + logModuleCall('gofas_nfeio', 'gnfe_issue_nfe - CURLOPT_POSTFIELDS', json_encode($postfields), '', '', ''); + if ($err) { + return (object) ['message' => $err, 'info' => $info]; + } else { + return json_decode(json_encode(json_decode($response))); + } } } if (!function_exists('gnfe_get_nfe')) { @@ -571,7 +578,6 @@ function gnfe_check_webhook($id) { curl_setopt($curl, CURLOPT_TIMEOUT, 30); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $response = curl_exec($curl); - logModuleCall('gofas_nfeio', 'aftercronjob', curl_getinfo($curl), '', '', 'replaceVars'); curl_close($curl); return json_decode(json_encode(json_decode($response)), true); @@ -585,13 +591,11 @@ function gnfe_create_webhook($url) { curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: application/json', 'Accept: aplication/json', 'Authorization: ' . gnfe_config('api_key')]); curl_setopt($curl, CURLOPT_TIMEOUT, 30); curl_setopt($curl, CURLOPT_POST, 1); - curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode(['url' => $url, 'contentType' => 'application/json', 'secret' => (string)time(), 'events' => ['issue', 'cancel'], 'status' => 'Active', ])); + curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode(['url' => $url, 'contentType' => 'application/json', 'secret' => (string)time(), 'events' => ['issue', 'cancel', 'WaitingCalculateTaxes'], 'status' => 'Active', ])); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $response = curl_exec($curl); - logModuleCall('gofas_nfeio', 'aftercronjob', curl_getinfo($curl), '', '', 'replaceVars'); curl_close($curl); } catch (Exception $th) { - logModuleCall('gofas_nfeio', 'Exception', $th->getMessage(), '', '', 'replaceVars'); } return json_decode(json_encode(json_decode($response)), true); } @@ -671,21 +675,6 @@ function gnfe_get_company() { } } -if (!function_exists('set_custom_field_ini_date')) { - function set_custom_field_ini_date() { - $data = getTodaysDate(false); - $dataAtual = toMySQLDate($data); - - try { - if (Capsule::table('tbladdonmodules')->where('module', '=', 'gofasnfeio')->where('setting', '=', 'initial_date')->count() < 1) { - Capsule::table('tbladdonmodules')->insert(['module' => 'gofasnfeio', 'setting' => 'initial_date', 'value' => $dataAtual]); - } - } catch (\Exception $e) { - $e->getMessage(); - } - } -} - if (!function_exists('gnfe_get_company')) { function gnfe_get_company() { $curl = curl_init(); @@ -759,63 +748,46 @@ function get_product_invoice($invoice_id) { $products_details[] = $product_array; } } - logModuleCall('gofas_nfeio', 'products_details', $products_details, '', 'replaceVars'); return $products_details; } -if (!function_exists('set_code_service_camp_gofasnfeio')) { - function set_code_service_camp_gofasnfeio() { - if (!Capsule::schema()->hasColumn('gofasnfeio', 'service_code')) { - $pdo = Capsule::connection()->getPdo(); - $pdo->beginTransaction(); +function dowload_doc_log() { + $days = 5; + $namefile = 'log-whmcs-nfe.txt'; - try { - $statement = $pdo->prepare('ALTER TABLE gofasnfeio ADD service_code TEXT;'); - $statement->execute(); - $pdo->commit(); - } catch (\Exception $e) { - $pdo->rollBack(); - } - } - if (!Capsule::schema()->hasColumn('gofasnfeio', 'services_amount')) { - if (!Capsule::schema()->hasColumn('gofasnfeio', 'services_amount')) { - $pdo = Capsule::connection()->getPdo(); - $pdo->beginTransaction(); - try { - $statement = $pdo->prepare('ALTER TABLE gofasnfeio ADD services_amount DECIMAL(16,2)'); - $statement->execute(); - $pdo->commit(); - } catch (\Exception $e) { - $pdo->rollBack(); - } - } - } + $configs = []; + foreach (Capsule::table('tbladdonmodules')->where('module','=','gofasnfeio')->get(['setting', 'value']) as $row) { + $configs[$row->setting] = $row->value; } -} -if (!function_exists('create_table_product_code')) { - function create_table_product_code() { - if (Capsule::schema()->hasTable('tblproductcode')) { - return ''; - } + $results = localAPI('WhmcsDetails'); + $v = $results['whmcs']['version']; + $actual_link = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']; - $pdo = Capsule::connection()->getPdo(); - $pdo->beginTransaction(); + $text = '-|date' . PHP_EOL . '-|action' . PHP_EOL . '-|request' . PHP_EOL . '-|response' . PHP_EOL . '-|status' . PHP_EOL; + $text .= 'version =' . $v . PHP_EOL . 'url =' . $actual_link . PHP_EOL . 'conf_module = ' . json_encode($configs) . PHP_EOL; - try { - $statement = $pdo->prepare('CREATE TABLE tblproductcode ( - id int(10) unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY, - product_id int(10) NOT NULL, - code_service int(10) NOT NULL, - create_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, - update_at TIMESTAMP NULL, - ID_user int(10) NOT NULL)'); - $statement->execute(); - $pdo->commit(); - } catch (\Exception $e) { - $pdo->rollBack(); - logModuleCall('gofas_nfeio', 'create_table_product_code error', $e, '', '', 'replaceVars'); - } + $dataAtual = toMySQLDate(getTodaysDate(false)) . ' 23:59:59'; + $dataAnterior = date('Y-m-d',mktime (0, 0, 0, date('m'), date('d') - $days, date('Y'))) . ' 23:59:59'; + + foreach (Capsule::table('tblmodulelog')->where('module','=','gofas_nfeio')->orderBy('date')->whereBetween('date', [$dataAnterior, $dataAtual])->get(['date', 'action', 'request', 'response', 'arrdata']) as $log) { + $text .= PHP_EOL . '==========================================================================================================================================' . PHP_EOL; + $text .= '-|date = ' . $log->date . PHP_EOL . '-|action = ' . $log->action . PHP_EOL . '-|request = ' . ($log->request) . PHP_EOL . '-|response = ' . ($log->response) . PHP_EOL . '-|status = ' . ($log->arrdata); } + $text .= PHP_EOL . '====================================================================FIM DO ARQUIVO======================================================================' . PHP_EOL; + + header('Content-type: text/plain'); + header('Content-Disposition: attachment; filename="default-filename.txt"'); + print $text; + exit(); } + +function update_status_nfe($invoice_id,$status) { + try { + $return = Capsule::table('gofasnfeio')->where('invoice_id','=',$invoice_id)->update(['status' => $status]); + return $return; + } catch (Exception $e) { + return $e->getMessage(); + } +} \ No newline at end of file diff --git a/modules/addons/gofasnfeio/hooks.php b/modules/addons/gofasnfeio/hooks.php index 1e789c5..125ee8f 100644 --- a/modules/addons/gofasnfeio/hooks.php +++ b/modules/addons/gofasnfeio/hooks.php @@ -5,39 +5,40 @@ } //InvoiceCreation add_hook('InvoiceCreation', 1, function ($vars) { - require_once __DIR__.'/functions.php'; - - require_once __DIR__.'/hooks/invoicecreation.php'; + require_once __DIR__ . '/functions.php'; + require_once __DIR__ . '/sendNFE.php'; + require_once __DIR__ . '/hooks/dailycronjob.php'; + require_once __DIR__ . '/hooks/invoicecreation.php'; }); //InvoicePaid add_hook('InvoicePaid', 1, function ($vars) { - require_once __DIR__.'/functions.php'; + require_once __DIR__ . '/functions.php'; - require_once __DIR__.'/hooks/invoicepaid.php'; + require_once __DIR__ . '/hooks/invoicepaid.php'; }); //AdminInvoicesControlsOutput add_hook('AdminInvoicesControlsOutput', 1, function ($vars) { - require_once __DIR__.'/functions.php'; + require_once __DIR__ . '/functions.php'; - require_once __DIR__.'/hooks/admininvoicescontrolsoutput.php'; + require_once __DIR__ . '/hooks/admininvoicescontrolsoutput.php'; }); add_hook('InvoiceCancelled', 1, function ($vars) { - require_once __DIR__.'/functions.php'; + require_once __DIR__ . '/functions.php'; - require_once __DIR__.'/hooks/invoicecancelled.php'; + require_once __DIR__ . '/hooks/invoicecancelled.php'; }); add_hook('DailyCronJob', 1, function ($vars) { - require_once __DIR__.'/functions.php'; - - require_once __DIR__.'/hooks/dailycronjob.php'; + require_once __DIR__ . '/functions.php'; + require_once __DIR__ . '/sendNFE.php'; + require_once __DIR__ . '/hooks/dailycronjob.php'; }); add_hook('AfterCronJob', 1, function ($vars) { - require_once __DIR__.'/functions.php'; - - require_once __DIR__.'/hooks/aftercronjob.php'; + require_once __DIR__ . '/functions.php'; + require_once __DIR__ . '/sendNFE.php'; + require_once __DIR__ . '/hooks/aftercronjob.php'; }); add_hook('ProductDelete', 1, function ($vars) { - require_once __DIR__.'/functions.php'; + require_once __DIR__ . '/functions.php'; - require_once __DIR__.'/hooks/productdelete.php'; + require_once __DIR__ . '/hooks/productdelete.php'; }); diff --git a/modules/addons/gofasnfeio/hooks/admininvoicescontrolsoutput.php b/modules/addons/gofasnfeio/hooks/admininvoicescontrolsoutput.php index 1482875..1e22714 100644 --- a/modules/addons/gofasnfeio/hooks/admininvoicescontrolsoutput.php +++ b/modules/addons/gofasnfeio/hooks/admininvoicescontrolsoutput.php @@ -21,12 +21,14 @@ $customer = gnfe_customer($invoice['userid'], $client); $queue = gnfe_queue_nfe($vars['invoiceid'], true); if ($queue !== 'success') { + logModuleCall('gofas_nfeio', 'admininvoicecontorloutput - gnfe_create',$vars['invoiceid'], $queue, 'ERROR', ''); header_remove(); header('Location: ' . $gnfewhmcsadminurl . 'invoices.php?action=edit&id=' . $vars['invoiceid'] . '&gnfe_error=Erro ao criar nota fiscal: ' . $queue); exit; } if ($queue === 'success') { + logModuleCall('gofas_nfeio', 'admininvoicecontorloutput - gnfe_create',$vars['invoiceid'], $queue, 'OK', ''); $message = '
Nota Fiscal enviada para processamento
'; header_remove(); header('Location: ' . $gnfewhmcsadminurl . 'invoices.php?action=edit&id=' . $vars['invoiceid'] . '&gnfe_message=' . base64_encode(urlencode($message))); @@ -47,6 +49,7 @@ foreach (Capsule::table('gofasnfeio')->where('invoice_id', '=', $_REQUEST['id'])->get(['id', 'nfe_id']) as $nfe) { $delete_nfe = gnfe_delete_nfe($nfe->nfe_id); if ($delete_nfe->message) { + logModuleCall('gofas_nfeio', 'admininvoicecontorloutput - gnfe_cancel',$nfe->nfe_id, $delete_nfe, 'ERROR', ''); $message = '
' . $delete_nfe->message . '
'; header_remove(); header('Location: ' . $gnfewhmcsadminurl . 'invoices.php?action=edit&id=' . $vars['invoiceid'] . '&gnfe_message=' . base64_encode(urlencode($message))); @@ -55,6 +58,7 @@ } } if (!$delete_nfe->message) { + logModuleCall('gofas_nfeio', 'admininvoicecontorloutput - gnfe_cancel',$nfe->nfe_id, $delete_nfe, 'OK', ''); $gnfe_update_nfe = gnfe_update_nfe((object) ['id' => $nfe_for_invoice['nfe_id'], 'status' => 'Cancelled', 'servicesAmount' => $nfe_for_invoice['services_amount'], 'environment' => $nfe_for_invoice['environment'], 'flow_status' => $nfe_for_invoice['flow_status']], $nfe_for_invoice['user_id'], $vars['invoiceid'], 'n/a', $nfe_for_invoice['created_at'], date('Y-m-d H:i:s')); $message = '
Nota Fiscal Cancelada com Sucesso
'; header_remove(); @@ -67,6 +71,7 @@ foreach (Capsule::table('gofasnfeio')->where('invoice_id', '=', $_REQUEST['id'])->get(['id', 'nfe_id']) as $nfe) { $gnfe_email = gnfe_email_nfe($_REQUEST['gnfe_email']); if (!$gnfe_email->message) { + logModuleCall('gofas_nfeio', 'admininvoicecontorloutput - gnfe_email',$_REQUEST['gnfe_email'], $gnfe_email, 'OK', ''); $message = '
Email Enviado com Sucesso
'; header_remove(); header('Location: ' . $gnfewhmcsadminurl . 'invoices.php?action=edit&id=' . $vars['invoiceid'] . '&gnfe_message=' . base64_encode(urlencode($message))); @@ -75,6 +80,7 @@ } } if ($gnfe_email->message) { + logModuleCall('gofas_nfeio', 'admininvoicecontorloutput - gnfe_email',$_REQUEST['gnfe_email'], $gnfe_email, 'ERROR', ''); $message = '
' . $gnfe_email->message . '
'; header_remove(); header('Location: ' . $gnfewhmcsadminurl . 'invoices.php?action=edit&id=' . $vars['invoiceid'] . '&gnfe_message=' . base64_encode(urlencode($message))); @@ -87,6 +93,10 @@ $invoice_nfe = ' Criada em ' . date('d/m/Y H:i:s', strtotime($nfe_for_invoice['created_at'])) . ' - Status: Aguardando'; $disabled = ['a' => 'disabled="disabled"', 'b' => 'disabled="disabled"', 'c' => 'disabled="disabled"', 'd' => 'disabled="disabled"']; } +if ($nfe_for_invoice['status'] === (string) 'Error_cep') { + $invoice_nfe = ' Criada em ' . date('d/m/Y H:i:s', strtotime($nfe_for_invoice['created_at'])) . ' - Status: Erro no CEP do usuário'; + $disabled = ['a' => 'disabled="disabled"', 'b' => 'disabled="disabled"', 'c' => 'disabled="disabled"', 'd' => 'disabled="disabled"']; +} if ($nfe_for_invoice['status'] === (string) 'Created') { $invoice_nfe = ' Criada em ' . date('d/m/Y H:i:s', strtotime($nfe_for_invoice['created_at'])) . ' - Status: Processando'; $disabled = ['a' => 'disabled="disabled"', 'b' => '', 'c' => 'disabled="disabled"', 'd' => 'disabled="disabled"']; diff --git a/modules/addons/gofasnfeio/hooks/aftercronjob.php b/modules/addons/gofasnfeio/hooks/aftercronjob.php index 88777a4..56aec08 100644 --- a/modules/addons/gofasnfeio/hooks/aftercronjob.php +++ b/modules/addons/gofasnfeio/hooks/aftercronjob.php @@ -4,164 +4,27 @@ exit(); } use WHMCS\Database\Capsule; - -if ($params['debug']) { - logModuleCall('gofas_nfeio', 'check', 'check', '', 'replaceVars'); -} $params = gnfe_config(); +logModuleCall('gofas_nfeio', 'carregou', 'aftercronjob', '', 'replaceVars'); + +if (!isset($params['issue_note_after']) || $params['issue_note_after'] <= 0) { foreach (Capsule::table('gofasnfeio')->orderBy('id', 'desc')->where('status', '=', 'Waiting')->get(['id', 'invoice_id', 'services_amount']) as $waiting) { - // foreach (Capsule::table('gofasnfeio')->orderBy('id', 'desc')->where('status', '=', 'Waiting')->take(1)->get(['id', 'invoice_id', 'services_amount']) as $waiting) { + logModuleCall('gofas_nfeio', 'aftercronjob - checktablegofasnfeio', '', $waiting,'', ''); + $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']); + logModuleCall('gofas_nfeio', 'aftercronjob - getQuery', ['date' => [$params['initial_date'], $dataAtual], 'where' => 'id=' . $waiting->invoice_id], $getQuery,'', ''); } else { $getQuery = Capsule::table('tblinvoices')->where('id', '=', $waiting->invoice_id)->get(['id', 'userid', 'total']); - } - if ($params['debug']) { - logModuleCall('gofas_nfeio', 'getQuery', json_decode($getQuery), '', 'replaceVars'); - logModuleCall('gofas_nfeio', 'invoice_id', $waiting->invoice_id, '', 'replaceVars'); - logModuleCall('gofas_nfeio', 'dataAtual', $dataAtual, '', 'replaceVars'); - logModuleCall('gofas_nfeio', 'initial_date', $params['initial_date'], '', 'replaceVars'); + logModuleCall('gofas_nfeio', 'aftercronjob - getQuery', 'id=' . $waiting->invoice_id, $getQuery,'', ''); } foreach ($getQuery as $invoices) { - foreach ($invoice['items']['item'] as $value) { - $line_items[] = $value['description']; - } - $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; - } - - if ($customer['doc_type'] == 2) { - if ($client['companyname'] != '') { - $name = $client['companyname']; - } else { - $name = $client['fullname']; - } - } 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 $gnfeWhmcsUrl) { - $gnfeWhmcsUrl = $gnfeWhmcsUrl->value; - } - if ($params['InvoiceDetails'] == 'Número da fatura') { - $desc = 'Nota referente a fatura #' . $waiting->invoice_id . ' ' . $gnfeWhmcsUrl . 'viewinvoice.php?id=' . $waiting->invoice_id . ' '; - } else { - $desc = substr(implode("\n", $line_items), 0, 600); - } - if (strpos($client['address1'], ',')) { - $array_adress = explode(',', $client['address1']); - $street = $array_adress[0]; - $number = $array_adress[1]; - } else { - $street = str_replace(',', '', preg_replace('/[0-9]+/i', '', $client['address1'])); - $number = preg_replace('/[^0-9]/', '', $client['address1']); - } - - 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' => $street, - 'number' => $number, - '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' => $street, - 'number' => $number, - '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', 'aftercronjob', $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', 'aftercronjob', ['$params' => $params, '$datepaid' => $datepaid, '$datepaid_to_issue' => $datepaid_to_issue], 'post', ['$processed_invoices' => $processed_invoices, '$nfe' => $nfe, 'error' => $error], 'replaceVars'); + emitNFE($invoices,$waiting); } } +} diff --git a/modules/addons/gofasnfeio/hooks/dailycronjob.php b/modules/addons/gofasnfeio/hooks/dailycronjob.php index 0085614..e3c6662 100644 --- a/modules/addons/gofasnfeio/hooks/dailycronjob.php +++ b/modules/addons/gofasnfeio/hooks/dailycronjob.php @@ -8,139 +8,20 @@ $params = gnfe_config(); $data = getTodaysDate(false); $dataAtual = toMySQLDate($data); +logModuleCall('gofas_nfeio', 'carregou', 'dailycronjob', '', ''); -if ($params['debug']) { - logModuleCall('gofas_nfeio', 'daily cron t', $params['issue_note_after'], '', 'replaceVars'); - logModuleCall('gofas_nfeio', 'daily cron issue_note', $params['issue_note'], '', 'replaceVars'); -} -if ( $params['issue_note'] !== 'Manualmente' && $params['issue_note_after'] && (int) $params['issue_note_after'] > 0) { +if (isset($params['issue_note_after']) && (int)$params['issue_note_after'] > 0) { foreach (Capsule::table('tblinvoices')->whereBetween('date', [$params['initial_date'], $dataAtual])->where('status', '=', 'Paid')->get(['id', 'userid', 'datepaid', 'total']) as $invoices) { - foreach (Capsule::table('gofasnfeio')->where('status', '=', 'Waiting')->where('invoice_id', '=', $invoices->id)->get(['id', 'invoice_id', 'service_code', 'monthly', 'services_amount']) as $nfeio) { + foreach (Capsule::table('gofasnfeio')->where('status', '=', 'Waiting')->where('invoice_id', '=', $invoices->id)->get(['id', 'nfe_id', 'status', 'created_at', 'invoice_id', 'service_code', 'services_amount']) as $nfeio) { $datepaid = date('Ymd', strtotime($invoices->datepaid)); $datepaid_to_issue_ = '-' . $params['issue_note_after'] . ' days'; $datepaid_to_issue = date('Ymd', strtotime($datepaid_to_issue_)); - $nfe_for_invoice = gnfe_get_local_nfe($invoices->id, ['nfe_id', 'status', 'services_amount', 'created_at']); - $client = localAPI('GetClientsDetails', ['clientid' => $invoices->userid, 'stats' => false], false); - $invoice = localAPI('GetInvoice', ['invoiceid' => $invoices->id], false); - if ((float) $invoices->total > (float) '0.00' and (int) $datepaid_to_issue >= (int) $datepaid) { - $processed_invoices[$invoices->id] = 'Paid on: ' . $datepaid; - if (!$nfe_for_invoice['status'] or (string) $nfe_for_invoice['status'] === (string) 'Error' or (string) $nfe_for_invoice['status'] === (string) 'None') { - foreach ($invoice['items']['item'] as $value) { - $line_items[] = $value['description']; - } - $customer = gnfe_customer($invoices->userid, $client); - /*if($params['email_nfe']) { - $client_email = $client['email']; - } - elseif(!$params['email_nfe']) { - $client_email = $client['email']; - }*/ - $company = gnfe_get_company(); - - if ($customer['doc_type'] == 2) { - if ($client['companyname'] != '') { - $name = $client['companyname']; - } else { - $name = $client['fullname']; - } - } elseif ($customer['doc_type'] == 1 || 'CPF e/ou CNPJ ausente.' == $customer || !$customer['doc_type']) { - $name = $client['fullname']; - } - - $name = htmlspecialchars_decode($name); - $service_code = $nfeio->service_code ? $nfeio->service_code : $params['service_code']; + if ((float) $invoices->total > '0.00' and (int) $datepaid_to_issue >= (int) $datepaid) { + logModuleCall('gofas_nfeio', 'dailycronjob', 'emitNFE', '', ''); - foreach (Capsule::table('tblconfiguration')->where('setting', '=', 'Domain')->get(['value']) as $gnfewhmcsadminurl) { - $gnfewhmcsadminurl = $gnfewhmcsadminurl->value; - } - if ($params['InvoiceDetails'] == 'Número da fatura') { - $desc = 'Nota referente a fatura #' . $waiting->invoice_id . ' ' . $gnfeWhmcsUrl . 'viewinvoice.php?id=' . $waiting->invoice_id . ' '; - } else { - $desc = substr(implode("\n", $line_items), 0, 600); - } - if (strpos($client['address1'], ',')) { - $array_adress = explode(',', $client['address1']); - $street = $array_adress[0]; - $number = $array_adress[1]; - } else { - $street = str_replace(',', '', preg_replace('/[0-9]+/i', '', $client['address1'])); - $number = preg_replace('/[^0-9]/', '', $client['address1']); - } - - if (!strlen($customer['insc_municipal']) == 0) { - $postfields = [ - 'cityServiceCode' => $service_code, - 'description' => $desc, - 'servicesAmount' => $nfeio->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' => $street, - 'number' => $number, - 'additionalInformation' => '', - 'district' => $client['address2'], - 'city' => [ - 'code' => gnfe_ibge(preg_replace('/[^0-9]/', '', $client['postcode'])), - 'name' => $client['city'], - ], - 'state' => $client['state'], - ], - ], - 'rpsSerialNumber' => $company['companies']['rpsSerialNumber'], - 'rpsNumber' => (int) $company['companies']['rpsNumber'] + 1, - ]; - } else { - $postfields = [ - 'cityServiceCode' => $service_code, - 'description' => $desc, - 'servicesAmount' => $nfeio->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' => $street, - 'number' => $number, - 'additionalInformation' => '', - 'district' => $client['address2'], - 'city' => [ - 'code' => gnfe_ibge(preg_replace('/[^0-9]/', '', $client['postcode'])), - 'name' => $client['city'], - ], - 'state' => $client['state'], - ], - ], - 'rpsSerialNumber' => $company['companies']['rpsSerialNumber'], - 'rpsNumber' => (int) $company['companies']['rpsNumber'] + 1, - ]; - } - - if ($params['debug']) { - logModuleCall('gofas_nfeio', 'dailycronjob', $postfields, '', '', 'replaceVars'); - } - $waiting = []; - foreach (Capsule::table('gofasnfeio')->where('status', '=', 'Waiting')->get(['invoice_id', 'status']) as $Waiting) { - $waiting[] = $Waiting->invoice_id; - } - $queue = gnfe_queue_nfe_edit($invoices->id, $nfeio->id); - if ($queue !== 'success') { - $error .= $queue; - } - if ($queue === 'success') { - } - } + emitNFE($invoices,$nfeio); } } } - if ($params['debug']) { - logModuleCall('gofas_nfeio', 'dailycronjob', ['$params' => $params, '$datepaid' => $datepaid, '$datepaid_to_issue' => $datepaid_to_issue, 'gnfe_get_nfes' => gnfe_get_nfes()], 'post', ['processed_invoices' => $processed_invoices, 'queue' => $queue, 'error' => $error], 'replaceVars'); - } } diff --git a/modules/addons/gofasnfeio/hooks/invoicecancelled.php b/modules/addons/gofasnfeio/hooks/invoicecancelled.php index 65129b6..a5e27e7 100644 --- a/modules/addons/gofasnfeio/hooks/invoicecancelled.php +++ b/modules/addons/gofasnfeio/hooks/invoicecancelled.php @@ -10,17 +10,10 @@ $invoice = localAPI('GetInvoice', ['invoiceid' => $vars['invoiceid']], false); $delete_nfe = gnfe_delete_nfe($nfe_for_invoice['nfe_id']); if (!$delete_nfe->message) { + logModuleCall('gofas_nfeio', 'invoicecancelled', $nfe_for_invoice['nfe_id'], $delete_nfe, 'OK', ''); $gnfe_update_nfe = gnfe_update_nfe((object) ['id' => $nfe_for_invoice['nfe_id'], 'status' => 'Cancelled', 'servicesAmount' => $nfe_for_invoice['services_amount'], 'environment' => $nfe_for_invoice['environment'], 'flow_status' => $nfe_for_invoice['flow_status']], $invoice['userid'], $vars['invoiceid'], 'n/a', $nfe_for_invoice['created_at'], date('Y-m-d H:i:s')); + } else { + logModuleCall('gofas_nfeio', 'invoicecancelled', $nfe_for_invoice['nfe_id'], $delete_nfe, 'ERROR', ''); } } - if ($params['debug']) { - logModuleCall( - 'gofas_nfeio', - 'InvoiceCancelled', - ['vars' => $vars, 'params' => $params, 'nfe_for_invoice' => $nfe_for_invoice, 'invoice' => $invoice], - 'post', - ['nf' => $nf, 'delete_nfe' => $delete_nfe], - 'replaceVars' - ); - } } diff --git a/modules/addons/gofasnfeio/hooks/invoicecreation.php b/modules/addons/gofasnfeio/hooks/invoicecreation.php index d50bb89..0c2fcc1 100644 --- a/modules/addons/gofasnfeio/hooks/invoicecreation.php +++ b/modules/addons/gofasnfeio/hooks/invoicecreation.php @@ -5,37 +5,29 @@ } $params = gnfe_config(); -if (stripos($params['issue_note'], 'Gerada') and (string) $vars['status'] !== (string) 'Draft' and (!$params['issue_note_after'] or 0 === $params['issue_note_after'])) { +if (stripos($params['issue_note'], 'Gerada') && (string) $vars['status'] != 'Draft' && (!$params['issue_note_after'] || 0 == $params['issue_note_after'])) { $invoice = localAPI('GetInvoice', ['invoiceid' => $vars['invoiceid']], false); - if ((float) $invoice['total'] > (float) '0.00' and $invoice['status'] !== (string) 'Draft') { + + if ((float) $invoice['total'] > (float) '0.00' and $invoice['status'] != 'Draft') { $nfe_for_invoice = gnfe_get_local_nfe($vars['invoiceid'], ['invoice_id', 'user_id', 'nfe_id', 'status', 'services_amount', 'environment', 'pdf', 'created_at']); - if ($nfe_for_invoice['status'] !== (string) 'Created' or $nfe_for_invoice['status'] !== (string) 'Issued') { + + if (!$nfe_for_invoice['id']) { $client = localAPI('GetClientsDetails', ['clientid' => $invoice['userid'], 'stats' => false], false); + foreach ($invoice['items']['item'] as $value) { $line_items[] = $value['description']; //substr( $value['description'], 0, 100); } - - /*if($params['email_nfe']) { - $client_email = $client['email']; - } - elseif(!$params['email_nfe']) { - $client_email = $client['email']; - }*/ - $queue = gnfe_queue_nfe($vars['invoiceid'], true); if ($queue !== 'success') { + logModuleCall('gofas_nfeio', 'invoicecreation', $vars['invoiceid'], $queue, 'ERROR', ''); if ('adminarea' === $vars['source']) { header('Location: ' . gnfe_whmcs_admin_url() . 'invoices.php?action=edit&id=' . $vars['invoiceid'] . '&gnfe_error=Erro ao criar nota fiscal: ' . $queue); - exit; } - } - if ($queue === 'success') { + } else { + logModuleCall('gofas_nfeio', 'invoicecreation', $vars['invoiceid'], $queue, 'OK', ''); } } } -} -if ($params['debug']) { - logModuleCall('gofas_nfeio', 'InvoiceCreation', ['vars' => $vars, 'gnfe_ibge' => gnfe_ibge(preg_replace('/[^0-9]/', '', $client['postcode'])), 'postifields' => $postifields], 'post', ['params' => $params, 'invoice' => $invoice, 'client' => $client, 'queue' => $queue, 'nfe_for_invoice' => $nfe_for_invoice, 'company' => $company], 'replaceVars'); -} +} \ No newline at end of file diff --git a/modules/addons/gofasnfeio/hooks/invoicepaid.php b/modules/addons/gofasnfeio/hooks/invoicepaid.php index 3405f04..8fea2af 100644 --- a/modules/addons/gofasnfeio/hooks/invoicepaid.php +++ b/modules/addons/gofasnfeio/hooks/invoicepaid.php @@ -4,30 +4,30 @@ exit(); } $params = gnfe_config(); -logModuleCall('gofas_nfeio', 'invoice paid', $vars, '', '', 'replaceVars'); -if (stripos($params['issue_note'], 'Paga') and (string) $vars['status'] !== (string) 'Draft' and (!$params['issue_note_after'] or 0 === $params['issue_note_after'])) { +if (stripos($params['issue_note'], 'Paga') && $vars['status'] != 'Draft' && (!$params['issue_note_after'] || 0 == $params['issue_note_after'])) { $invoice = localAPI('GetInvoice', ['invoiceid' => $vars['invoiceid']], false); - if ((float) $invoice['total'] > (float) '0.00' and $invoice['status'] !== (string) 'Draft') { - $nfe_for_invoice = gnfe_get_local_nfe($vars['invoiceid'], ['nfe_id', 'status', 'services_amount']); - if ($nfe_for_invoice['status'] !== (string) 'Created' or $nfe_for_invoice['status'] !== (string) 'Issued') { + + if ((float) $invoice['total'] > 0.00 and $invoice['status'] != 'Draft') { + $nfe_for_invoice = gnfe_get_local_nfe($vars['invoiceid'], ['id']); + + if (!$nfe_for_invoice['id']) { $client = localAPI('GetClientsDetails', ['clientid' => $invoice['userid'], 'stats' => false], false); + foreach ($invoice['items']['item'] as $value) { $line_items[] = $value['description']; //substr( $value['description'], 0, 100); } + $queue = gnfe_queue_nfe($vars['invoiceid'], true); - if ($queue !== 'success') { + if ($queue != 'success') { + logModuleCall('gofas_nfeio', 'invoicepaid', $vars['invoiceid'], $queue, 'ERROR', ''); if ($vars['source'] === 'adminarea') { header('Location: ' . gnfe_whmcs_admin_url() . 'invoices.php?action=edit&id=' . $vars['invoiceid'] . '&gnfe_error=Erro ao criar nota fiscal: ' . $queue); - exit; } - } - if ($queue === 'success') { + } else { + logModuleCall('gofas_nfeio', 'invoicepaid', $vars['invoiceid'], $queue, 'OK', ''); } } } -} -if ($params['debug']) { - logModuleCall('gofas_nfeio', 'InvoicePaid', ['vars' => $vars, 'gnfe_ibge' => gnfe_ibge(preg_replace('/[^0-9]/', '', $client['postcode']))], 'post', ['params' => $params, 'invoice' => $invoice, 'client' => $client, 'queue' => $queue, 'nfe_for_invoice' => $nfe_for_invoice], 'replaceVars'); -} +} \ No newline at end of file diff --git a/modules/addons/gofasnfeio/hooks/productdelete.php b/modules/addons/gofasnfeio/hooks/productdelete.php index ef4940a..a19c918 100644 --- a/modules/addons/gofasnfeio/hooks/productdelete.php +++ b/modules/addons/gofasnfeio/hooks/productdelete.php @@ -2,4 +2,9 @@ use WHMCS\Database\Capsule; -Capsule::table('tblproductcode')->where('product_id', '=', $vars['pid'])->delete(); +try { + $delete = Capsule::table('tblproductcode')->where('product_id', '=', $vars['pid'])->delete(); + logModuleCall('gofas_nfeio', 'productdelete', 'product_id=' . $vars['pid'], $delete, 'OK', ''); +} catch (Exception $e) { + logModuleCall('gofas_nfeio', 'productdelete', 'product_id=' . $vars['pid'], $e->getMessage(), 'ERROR', ''); +} diff --git a/modules/addons/gofasnfeio/output.php b/modules/addons/gofasnfeio/output.php index 2221a99..6d306db 100644 --- a/modules/addons/gofasnfeio/output.php +++ b/modules/addons/gofasnfeio/output.php @@ -118,6 +118,10 @@ function gofasnfeio_output($vars) { $status = 'Falha ao Emitir'; $disabled = ['a' => '', 'b' => '', 'c' => 'disabled="disabled"', 'd' => 'disabled="disabled"']; } + if ($value->status === 'Error_cep') { + $status = 'Erro no CEP do usuário'; + $disabled = ['a' => '', 'b' => '', 'c' => 'disabled="disabled"', 'd' => 'disabled="disabled"']; + } if ($value->status === 'None') { $status = 'Nenhum'; $disabled = ['a' => '', 'b' => '', 'c' => 'disabled="disabled"', 'd' => 'disabled="disabled"']; @@ -165,6 +169,7 @@ function gofasnfeio_output($vars) { '; } else { echo ' + Código de Serviços

Nenhuma nota fiscal gerada até o momento

'; @@ -173,20 +178,30 @@ function gofasnfeio_output($vars) { $invoice = localAPI('GetInvoice', ['invoiceid' => $_REQUEST['invoice_id']], false); $client = localAPI('GetClientsDetails', ['clientid' => $invoice['userid'], 'stats' => false], false); $nfe_for_invoice = gnfe_get_local_nfe($_REQUEST['invoice_id'], ['invoice_id', 'user_id', 'nfe_id', 'status', 'services_amount', 'environment', 'pdf', 'created_at', 'rpsSerialNumber']); - $queue = gnfe_queue_nfe($_REQUEST['invoice_id'], true); - if ($queue !== 'success') { - $message = '
Erro ao salvar nota fiscal no DB: ' . $queue . '
'; - header_remove(); - header('Location: ' . $gnfewhmcsadminurl . 'addonmodules.php?module=gofasnfeio&gnfe_message=' . base64_encode(urlencode($message))); - - exit; - } - if ($queue === 'success') { - $message = '
Nota fiscal enviada para processamento
'; - header_remove(); - header('Location: ' . $gnfewhmcsadminurl . 'addonmodules.php?module=gofasnfeio&gnfe_message=' . base64_encode(urlencode($message))); - - exit; + if (!$nfe_for_invoice['id']) { + $queue = gnfe_queue_nfe($_REQUEST['invoice_id'], true); + if ($queue !== 'success') { + $message = '
Erro ao salvar nota fiscal no DB: ' . $queue . '
'; + header_remove(); + header('Location: ' . $gnfewhmcsadminurl . 'addonmodules.php?module=gofasnfeio&gnfe_message=' . base64_encode(urlencode($message))); + + exit; + } + if ($queue === 'success') { + $message = '
Nota fiscal enviada para processamento
'; + header_remove(); + header('Location: ' . $gnfewhmcsadminurl . 'addonmodules.php?module=gofasnfeio&gnfe_message=' . base64_encode(urlencode($message))); + + exit; + } + } else { + if ($queue !== 'success') { + $message = '
Erro ao salvar nota fiscal no DB: ' . 'nota fiscal já solicitada' . '
'; + header_remove(); + header('Location: ' . $gnfewhmcsadminurl . 'addonmodules.php?module=gofasnfeio&gnfe_message=' . base64_encode(urlencode($message))); + + exit; + } } } if ($_REQUEST['gnfe_cancel']) { diff --git a/modules/addons/gofasnfeio/sendNFE.php b/modules/addons/gofasnfeio/sendNFE.php new file mode 100644 index 0000000..3738133 --- /dev/null +++ b/modules/addons/gofasnfeio/sendNFE.php @@ -0,0 +1,148 @@ + $invoices->id], false); + $client = localAPI('GetClientsDetails', ['clientid' => $invoices->userid], false); + + $params = gnfe_config(); + + //create second option from description nfe + foreach ($invoice['items']['item'] as $value) { + $line_items[] = $value['description']; + } + + // CPF/CNPJ/NAME + $customer = gnfe_customer($invoices->userid, $client); + if ($customer['doc_type'] == 2) { + if ($client['companyname'] != '') { + $name = $client['companyname']; + } else { + $name = $client['fullname']; + } + } elseif ($customer['doc_type'] == 1 || 'CPF e/ou CNPJ ausente.' == $customer || !$customer['doc_type']) { + $name = $client['fullname']; + } + $name = htmlspecialchars_decode($name); + + //service_code + $service_code = $nfeio->service_code ? $nfeio->service_code : $params['service_code']; + + //description nfe + if ($params['InvoiceDetails'] == 'Número da fatura') { + $gnfeWhmcsUrl = Capsule::table('tblconfiguration')->where('setting', '=', 'Domain')->get(['value'])[0]->value; + $desc = 'Nota referente a fatura #' . $invoices->id . ' ' . $gnfeWhmcsUrl . 'viewinvoice.php?id=' . $invoices->id . ' '; + } else { + $desc = substr(implode("\n", $line_items), 0, 600); + } + + //define address + if (strpos($client['address1'], ',')) { + $array_adress = explode(',', $client['address1']); + $street = $array_adress[0]; + $number = $array_adress[1]; + } else { + $street = str_replace(',', '', preg_replace('/[0-9]+/i', '', $client['address1'])); + $number = preg_replace('/[^0-9]/', '', $client['address1']); + } + + //define o RPS number + $gnfe_get_nfes = gnfe_get_nfes(); + //rps_serial_number + if ($params['rps_serial_number']) { + $rps_serial_number = $params['rps_serial_number']; + $rps_serial_number_ = false; + //se não tiver salvo no banco mas existir na API + } 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; + //se não tiver salvo no banco e não existir na API + } elseif (!$params['rps_serial_number'] and !$gnfe_get_nfes['serviceInvoices']['0']['rpsSerialNumber']) { + $rps_serial_number = 'IO'; + $rps_serial_number_ = $rps_serial_number; + } + + //rps_number + if ($params['rps_number'] and $params['rps_number'] != 'zero') { + $rps_number = $params['rps_number']; + //se não existir RPS e existir na API + } elseif ((!$params['rps_number'] || $params['rps_number'] == 'zero') && $gnfe_get_nfes['serviceInvoices']['0']['rpsNumber']) { + $rps_number = $gnfe_get_nfes['serviceInvoices']['0']['rpsNumber']; + //se não existir RPS e não existir na API + } elseif (($params['rps_number'] == 'zero' && !$gnfe_get_nfes['serviceInvoices']['0']['rpsNumber']) || (!$params['rps_number'] && !$gnfe_get_nfes['serviceInvoices']['0']['rpsNumber'])) { + $rps_number = 0; + } + + if ($params['email_nfe']) { + $client_email = $client['email']; + } else { + $client_email = ''; + } + + logModuleCall('gofas_nfeio', 'sendNFE - customer', $customer, '','', ''); + $code = gnfe_ibge(preg_replace('/[^0-9]/', '', $client['postcode'])); + if ($code == 'ERROR') { + logModuleCall('gofas_nfeio', 'sendNFE - gnfe_ibge', $customer, '','ERROR', ''); + update_status_nfe($nfeio->invoice_id,'Error_cep'); + } else { + //cria o array do request + $postfields = createRequestFromAPI($service_code,$desc,$nfeio->services_amount,$customer['document'],$customer['insc_municipal'], + $name,$client_email,$client['countrycode'],$client['postcode'],$street,$number,$client['address2'], + $code,$client['city'],$client['state'],$rps_serial_number,$rps_number); + + //envia o requisição + $nfe = gnfe_issue_nfe($postfields); + + if ($nfe->message) { + logModuleCall('gofas_nfeio', 'sendNFE', $postfields, $nfe, 'ERROR', ''); + } + if (!$nfe->message) { + logModuleCall('gofas_nfeio', 'sendNFE', $postfields, $nfe, 'OK', ''); + $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 && $gnfe_update_nfe !== 'success') { + logModuleCall('gofas_nfeio', 'sendNFE - 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], $gnfe_update_nfe, 'ERROR', ''); + } + $update_rps = gnfe_update_rps($rps_serial_number_, $rps_number); + + if ($update_rps && $update_rps !== 'success') { + logModuleCall('gofas_nfeio', 'sendNFE - update_rps', [$rps_serial_number_, $rps_number], $update_rps, 'ERROR', ''); + } + } + } +} + +function createRequestFromAPI($service_code,$desc,$services_amount,$document,$insc_municipal = '', +$name,$email,$countrycode,$postcode,$street,$number,$address2,$code,$city,$state,$rps_serial_number,$rps_number) { + $postfields = [ + 'cityServiceCode' => $service_code, + 'description' => $desc, + 'servicesAmount' => $services_amount, + 'borrower' => [ + 'federalTaxNumber' => $document, + 'municipalTaxNumber' => $insc_municipal, + 'name' => $name, + 'email' => $email, + 'address' => [ + 'country' => gnfe_country_code($countrycode), + 'postalCode' => preg_replace('/[^0-9]/', '', $postcode), + 'street' => $street, + 'number' => $number, + 'additionalInformation' => '', + 'district' => $address2, + 'city' => [ + 'code' => $code, + 'name' => $city, + ], + 'state' => $state, + ], + ], + 'rpsSerialNumber' => $rps_serial_number, + 'rpsNumber' => (int) $rps_number + 1, + ]; + strlen($insc_municipal) == 0 ? '' : $postfields['borrower']['municipalTaxNumber'] = $insc_municipal; + return $postfields; +} \ No newline at end of file diff --git a/modules/addons/gofasnfeio/update.php b/modules/addons/gofasnfeio/update.php new file mode 100644 index 0000000..6a946fb --- /dev/null +++ b/modules/addons/gofasnfeio/update.php @@ -0,0 +1,126 @@ +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->decimal('services_amount',$precision = 16,$scale = 2); + $table->string('environment'); + $table->string('flow_status'); + $table->string('pdf'); + $table->string('rpsSerialNumber'); + $table->string('rpsNumber'); + $table->string('created_at'); + $table->string('updated_at'); + $table->string('service_code')->nullable(true); + $table->string('tics')->nullable(true); + }); + } 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]; + } + } +} + +if (!function_exists('create_table_product_code')) { + function create_table_product_code() { + if (Capsule::schema()->hasTable('tblproductcode')) { + return ''; + } + + $pdo = Capsule::connection()->getPdo(); + $pdo->beginTransaction(); + + try { + $statement = $pdo->prepare('CREATE TABLE tblproductcode ( + id int(10) unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY, + product_id int(10) NOT NULL, + code_service int(10) NOT NULL, + create_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + update_at TIMESTAMP NULL, + ID_user int(10) NOT NULL)'); + $statement->execute(); + $pdo->commit(); + } catch (\Exception $e) { + $pdo->rollBack(); + } + } +} +//=================================================================================== + +if (!function_exists('set_code_service_camp_gofasnfeio')) { + function set_code_service_camp_gofasnfeio() { + if (!Capsule::schema()->hasColumn('gofasnfeio', 'service_code')) { + $pdo = Capsule::connection()->getPdo(); + $pdo->beginTransaction(); + + try { + $statement = $pdo->prepare('ALTER TABLE gofasnfeio ADD service_code TEXT;'); + $statement->execute(); + $pdo->commit(); + } catch (\Exception $e) { + $pdo->rollBack(); + } + } + if (!Capsule::schema()->hasColumn('gofasnfeio', 'services_amount')) { + if (!Capsule::schema()->hasColumn('gofasnfeio', 'services_amount')) { + $pdo = Capsule::connection()->getPdo(); + $pdo->beginTransaction(); + try { + $statement = $pdo->prepare('ALTER TABLE gofasnfeio ADD services_amount DECIMAL(16,2)'); + $statement->execute(); + $pdo->commit(); + } catch (\Exception $e) { + $pdo->rollBack(); + } + } + } + } +} + +if (!function_exists('set_custom_field_ini_date')) { + function set_custom_field_ini_date() { + $data = getTodaysDate(false); + $dataAtual = toMySQLDate($data); + + try { + if (Capsule::table('tbladdonmodules')->where('module', '=', 'gofasnfeio')->where('setting', '=', 'initial_date')->count() < 1) { + Capsule::table('tbladdonmodules')->insert(['module' => 'gofasnfeio', 'setting' => 'initial_date', 'value' => $dataAtual]); + } + } catch (\Exception $e) { + $e->getMessage(); + } + } +} \ No newline at end of file