From 74cb5304ae5831f43770d760e557be158eb7c050 Mon Sep 17 00:00:00 2001 From: JoaoVictorLNacional Date: Tue, 1 Dec 2020 15:40:01 -0300 Subject: [PATCH 01/52] update in fork origin --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7afed8b..8b6d108 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ A [NFE.io](https://nfe.io "NFE.io") é um sistema de emissão de notas fiscais q ------------ ## CAPTURAS DE TELA -Clique nas imagens para ampliar +Clique nas imagens para ampliar [![](https://s3.amazonaws.com/uploads.gofas.me/wp-content/uploads/2020/08/26153535/config_screenshot.png)](https://s3.amazonaws.com/uploads.gofas.me/wp-content/uploads/2020/08/26153535/config_screenshot.png) *Configurações* From 22663a417ebfed9e738892f2a4f775c65ab23d61 Mon Sep 17 00:00:00 2001 From: JoaoVictorLNacional Date: Fri, 4 Dec 2020 14:37:44 -0300 Subject: [PATCH 02/52] adicionado se o cnpj estiver preencido emitir a NFE com o nome da empresa --- modules/addons/gofasnfeio/callback.php | 149 ++++++++++-------- .../addons/gofasnfeio/hooks/aftercronjob.php | 143 +++++++++-------- .../addons/gofasnfeio/hooks/dailycronjob.php | 122 +++++++------- 3 files changed, 227 insertions(+), 187 deletions(-) diff --git a/modules/addons/gofasnfeio/callback.php b/modules/addons/gofasnfeio/callback.php index 3d620c0..1a27e95 100644 --- a/modules/addons/gofasnfeio/callback.php +++ b/modules/addons/gofasnfeio/callback.php @@ -12,143 +12,154 @@ require_once __DIR__ . '/../../../init.php'; use WHMCS\Database\Capsule; $post = json_decode(file_get_contents('php://input'), true); -if($post){ +if ($post) { require_once __DIR__ . '/functions.php'; - $params = array(); - foreach( Capsule::table('tbladdonmodules') -> where( 'module', '=', 'gofasnfeio' ) -> get( array( 'setting', 'value') ) as $settings ) { + $params = []; + foreach ( Capsule::table('tbladdonmodules')->where( 'module', '=', 'gofasnfeio' )->get( ['setting', 'value'] ) as $settings ) { $params[$settings->setting] = $settings->value; } - foreach( Capsule::table('gofasnfeio')->where('nfe_id', '=', $post['id'])-> - get(array( 'invoice_id', 'user_id', 'nfe_id', 'status', 'services_amount', 'environment', 'flow_status', 'pdf', 'created_at', 'updated_at' )) as $key => $value ) { - $nfe_for_invoice[$key] = json_decode(json_encode($value), true); + foreach ( Capsule::table('gofasnfeio')->where('nfe_id', '=', $post['id'])-> + get(['invoice_id', 'user_id', 'nfe_id', 'status', 'services_amount', 'environment', 'flow_status', 'pdf', 'created_at', 'updated_at']) as $key => $value ) { + $nfe_for_invoice[$key] = json_decode(json_encode($value), true); } $nfe = $nfe_for_invoice['0']; - if((string)$nfe['nfe_id'] === (string)$post['id'] and $nfe['status'] !== (string)$post['status'] ){ - $new_nfe = array( - 'invoice_id'=>$nfe['invoice_id'], - 'user_id'=>$nfe['user_id'], - 'nfe_id'=>$nfe['nfe_id'], - 'status'=>$post['status'], - 'services_amount'=>$nfe['services_amount'], - 'environment'=>$nfe['environment'], - 'flow_status'=>$post['flowStatus'], - 'pdf'=>$nfe['pdf'], - 'created_at'=>$nfe['created_at'], - 'updated_at'=>date("Y-m-d H:i:s"), - ); + if ((string)$nfe['nfe_id'] === (string)$post['id'] and $nfe['status'] !== (string)$post['status'] ) { + $new_nfe = [ + 'invoice_id' => $nfe['invoice_id'], + 'user_id' => $nfe['user_id'], + 'nfe_id' => $nfe['nfe_id'], + 'status' => $post['status'], + 'services_amount' => $nfe['services_amount'], + 'environment' => $nfe['environment'], + 'flow_status' => $post['flowStatus'], + 'pdf' => $nfe['pdf'], + 'created_at' => $nfe['created_at'], + 'updated_at' => date('Y-m-d H:i:s'), + ]; try { $save_nfe = Capsule::table('gofasnfeio')->where('nfe_id', '=', $post['id'])->update($new_nfe); - } - catch (\Exception $e) { + } catch (\Exception $e) { $e->getMessage(); } } - if($params['debug']) { - logModuleCall('gofas_nfeio', 'receive_callback', array('post'=>$post), 'post', array('nfe_local'=>$nfe), 'replaceVars'); + 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( array( 'invoice_id' )) as $waiting ) { - foreach( Capsule::table('tblinvoices')->where('id', '=', $waiting->invoice_id)->get( array( 'id', 'userid', 'total' ) ) as $invoices ) { - $invoice = localAPI('GetInvoice', array('invoiceid' => $waiting->invoice_id), false); - $client = localAPI('GetClientsDetails',array( 'clientid' => $invoice['userid'], 'stats' => false, ), false); - foreach( $invoice['items']['item'] as $value){ - $line_items[] = $value['description']; + foreach ( Capsule::table('gofasnfeio')->orderBy('id', 'desc')->where('status', '=', 'Waiting')->take(1)->get( ['invoice_id']) as $waiting ) { + foreach ( Capsule::table('tblinvoices')->where('id', '=', $waiting->invoice_id)->get( ['id', 'userid', 'total'] ) 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'] ){ + 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']){ + } 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']){ + } 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'){ + 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']){ + } 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'])){ + } 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; } + $cnpj = $client['customfields2']; + $cpf = $client['customfields1']; + $namePF = $client['fullname']; + + $numberId = $cnpj ? $cnpj : $cpf; + $name = $cnpj ? $client['companyname'] : $name; + + $numberId = str_replace('.', '', $numberId); + $numberId = str_replace('/', '', $numberId); + $numberId = str_replace('-', '', $numberId); + if (!strlen($customer['insc_municipal']) == 0) { - $postfields = array( + $postfields = [ 'cityServiceCode' => $params['service_code'], 'description' => substr(implode("\n", $line_items), 0, 600), 'servicesAmount' => $invoice['total'], - 'borrower' => array( - 'federalTaxNumber' => $customer['document'], + 'borrower' => [ + 'federalTaxNumber' => $numberId, 'municipalTaxNumber' => $customer['insc_municipal'], - 'name' => $customer['name'], + 'name' => $name, 'email' => $client['email'], - 'address' => array( + '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' => array( - 'code' => gnfe_ibge(preg_replace("/[^0-9]/", "", $client['postcode'])), + '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 = array( + ]; + } else { + $postfields = [ 'cityServiceCode' => $params['service_code'], 'description' => substr(implode("\n", $line_items), 0, 600), 'servicesAmount' => $invoice['total'], - 'borrower' => array( - 'federalTaxNumber' => $customer['document'], - 'name' => $customer['name'], + 'borrower' => [ + 'federalTaxNumber' => $numberId, + 'name' => $name, 'email' => $client['email'], - 'address' => array( + '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' => array( - 'code' => gnfe_ibge(preg_replace("/[^0-9]/", "", $client['postcode'])), + '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) { + 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")); - if($gnfe_update_nfe and $gnfe_update_nfe !== 'success') { + 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')); + if ($gnfe_update_nfe and $gnfe_update_nfe !== 'success') { $error = $gnfe_update_nfe; } $update_rps = gnfe_update_rps($rps_serial_number_, $rps_number); - if($update_rps and $update_rps !== 'success') { + if ($update_rps and $update_rps !== 'success') { $error = $update_rps; } } } - if($params['debug']) { - logModuleCall('gofas_nfeio', 'after_receive_callback', array('$params'=>$params, '$datepaid'=>$datepaid, '$datepaid_to_issue'=>$datepaid_to_issue), 'post', array('$processed_invoices'=>$processed_invoices, '$nfe'=>$nfe,'error'=>$error ), 'replaceVars'); + 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'); } } } \ No newline at end of file diff --git a/modules/addons/gofasnfeio/hooks/aftercronjob.php b/modules/addons/gofasnfeio/hooks/aftercronjob.php index b69e48f..2996616 100644 --- a/modules/addons/gofasnfeio/hooks/aftercronjob.php +++ b/modules/addons/gofasnfeio/hooks/aftercronjob.php @@ -9,112 +9,125 @@ * @support https://github.com/nfe/whmcs-addon/issues * @version 1.2.4 */ -if (!defined("WHMCS")){die();} +if (!defined('WHMCS')) { + die(); +} use WHMCS\Database\Capsule; $params = gnfe_config(); -foreach( Capsule::table('gofasnfeio')->orderBy('id', 'desc')->where('status', '=', 'Waiting')->take(1)->get( array( 'invoice_id' )) as $waiting ) { - //$invoices[] = $Waiting->invoice_id; - foreach( Capsule::table('tblinvoices')->where('id', '=', $waiting->invoice_id)->get( array( 'id', 'userid', 'total' ) ) as $invoices ) { - $invoice = localAPI('GetInvoice', array('invoiceid' => $waiting->invoice_id), false); - $client = localAPI('GetClientsDetails',array( '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(!strlen($customer['insc_municipal']) == 0) { - $postfields = array( +foreach ( Capsule::table('gofasnfeio')->orderBy('id', 'desc')->where('status', '=', 'Waiting')->take(1)->get( ['invoice_id']) as $waiting ) { + //$invoices[] = $Waiting->invoice_id; + foreach ( Capsule::table('tblinvoices')->where('id', '=', $waiting->invoice_id)->get( ['id', 'userid', 'total'] ) 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; + } + + $cnpj = $client['customfields2']; + $cpf = $client['customfields1']; + $namePF = $client['fullname']; + + $numberId = $cnpj ? $cnpj : $cpf; + $name = $cnpj ? $client['companyname'] : $name; + + $numberId = str_replace('.', '', $numberId); + $numberId = str_replace('/', '', $numberId); + $numberId = str_replace('-', '', $numberId); + + if (!strlen($customer['insc_municipal']) == 0) { + $postfields = [ 'cityServiceCode' => $params['service_code'], 'description' => substr(implode("\n", $line_items), 0, 600), 'servicesAmount' => $invoice['total'], - 'borrower' => array( + 'borrower' => [ 'federalTaxNumber' => $customer['document'], - 'municipalTaxNumber' => $customer['insc_municipal'], - 'name' => $customer['name'], + 'municipalTaxNumber' => $numberId, + 'name' => $name, 'email' => $client['email'], - 'address' => array( + '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' => array( - 'code' => gnfe_ibge(preg_replace("/[^0-9]/", "", $client['postcode'])), + '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 = array( + ]; + } else { + $postfields = [ 'cityServiceCode' => $params['service_code'], 'description' => substr(implode("\n", $line_items), 0, 600), 'servicesAmount' => $invoice['total'], - 'borrower' => array( - 'federalTaxNumber' => $customer['document'], - 'name' => $customer['name'], + 'borrower' => [ + 'federalTaxNumber' => $numberId, + 'name' => $name, 'email' => $client['email'], - 'address' => array( + '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' => array( - 'code' => gnfe_ibge(preg_replace("/[^0-9]/", "", $client['postcode'])), + '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) { + 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")); - if($gnfe_update_nfe and $gnfe_update_nfe !== 'success') { + 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')); + if ($gnfe_update_nfe and $gnfe_update_nfe !== 'success') { $error = $gnfe_update_nfe; } $update_rps = gnfe_update_rps($rps_serial_number_, $rps_number); - if($update_rps and $update_rps !== 'success') { + if ($update_rps and $update_rps !== 'success') { $error = $update_rps; } } } - if($params['debug']) { - logModuleCall('gofas_nfeio', 'aftercronjob', array('$params'=>$params, '$datepaid'=>$datepaid, '$datepaid_to_issue'=>$datepaid_to_issue), 'post', array('$processed_invoices'=>$processed_invoices, '$nfe'=>$nfe,'error'=>$error ), 'replaceVars'); - } + 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'); + } } \ No newline at end of file diff --git a/modules/addons/gofasnfeio/hooks/dailycronjob.php b/modules/addons/gofasnfeio/hooks/dailycronjob.php index 445ccc0..142fc22 100644 --- a/modules/addons/gofasnfeio/hooks/dailycronjob.php +++ b/modules/addons/gofasnfeio/hooks/dailycronjob.php @@ -9,100 +9,116 @@ * @support https://github.com/nfe/whmcs-addon/issues * @version 1.2.4 */ -if (!defined("WHMCS")){die();} +if (!defined('WHMCS')) { + die(); +} use WHMCS\Database\Capsule; $params = gnfe_config(); -if( $params['issue_note_after'] and (int)$params['issue_note_after'] > 0 ) { - foreach( Capsule::table('tblinvoices')->where('status', '=', 'Paid')->get( array( 'id', 'userid', 'datepaid','total' ) ) as $invoices ) { - $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,array('nfe_id', 'status', 'services_amount','created_at')); - $client = localAPI('GetClientsDetails',array( 'clientid' => $invoices->userid, 'stats' => false, ), false); - $invoice = localAPI('GetInvoice', array('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']; +if ( $params['issue_note_after'] and (int)$params['issue_note_after'] > 0 ) { + foreach ( Capsule::table('tblinvoices')->where('status', '=', 'Paid')->get( ['id', 'userid', 'datepaid', 'total'] ) as $invoices ) { + $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(!strlen($customer['insc_municipal']) == 0) { - $postfields = array( + $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(); + + $cnpj = $client['customfields2']; + $cpf = $client['customfields1']; + $namePF = $client['fullname']; + + $numberId = $cnpj ? $cnpj : $cpf; + $name = $cnpj ? $client['companyname'] : $name; + + $numberId = str_replace('.', '', $numberId); + $numberId = str_replace('/', '', $numberId); + $numberId = str_replace('-', '', $numberId); + + if (!strlen($customer['insc_municipal']) == 0) { + $postfields = [ 'cityServiceCode' => $params['service_code'], 'description' => substr(implode("\n", $line_items), 0, 600), 'servicesAmount' => $invoices->total, - 'borrower' => array( - 'federalTaxNumber' => $customer['document'], + 'borrower' => [ + 'federalTaxNumber' => $numberId, 'municipalTaxNumber' => $customer['insc_municipal'], - 'name' => $customer['name'], + 'name' => $name, 'email' => $client['email'], - 'address' => array( + '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' => array( - 'code' => gnfe_ibge(preg_replace("/[^0-9]/", "", $client['postcode'])), + '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 = array( + ]; + } else { + $postfields = [ 'cityServiceCode' => $params['service_code'], 'description' => substr(implode("\n", $line_items), 0, 600), 'servicesAmount' => $invoices->total, - 'borrower' => array( - 'federalTaxNumber' => $customer['document'], - 'name' => $customer['name'], + 'borrower' => [ + 'federalTaxNumber' => $numberId, + 'name' => $name, 'email' => $client['email'], - 'address' => array( + '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' => array( - 'code' => gnfe_ibge(preg_replace("/[^0-9]/", "", $client['postcode'])), + '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, - ); + ]; } - - $waiting = array(); - foreach( Capsule::table('gofasnfeio') -> where( 'status', '=', 'Waiting' ) -> get( array( 'invoice_id', 'status') ) as $Waiting ) { + 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($invoices->id); - if($queue !== 'success') { + if ($queue !== 'success') { $error .= $queue; } - if($queue === 'success') {} + if ($queue === 'success') { + } } } } - if($params['debug']) { - logModuleCall('gofas_nfeio', 'dailycronjob', array('$params'=>$params, '$datepaid'=>$datepaid, '$datepaid_to_issue'=>$datepaid_to_issue,'gnfe_get_nfes'=> gnfe_get_nfes() ), 'post', array('processed_invoices'=>$processed_invoices, 'queue'=>$queue,'error'=>$error ), 'replaceVars'); + 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'); } } \ No newline at end of file From fc87a1f704af143d1311778ffb4202dfa34ae9df Mon Sep 17 00:00:00 2001 From: JoaoVictorLNacional Date: Fri, 4 Dec 2020 15:58:20 -0300 Subject: [PATCH 03/52] =?UTF-8?q?removido=20a=20formata=C3=A7=C3=A3o=20do?= =?UTF-8?q?=20CPF/CNPJ=20para=20usar=20p=20ja=20formatado=20pela=20fun?= =?UTF-8?q?=C3=A7=C3=A3o=20gnfe=5Fcustomer?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- modules/addons/gofasnfeio/callback.php | 14 +++--------- modules/addons/gofasnfeio/hooks.php | 22 ++++++++++--------- .../addons/gofasnfeio/hooks/aftercronjob.php | 14 +++--------- .../addons/gofasnfeio/hooks/dailycronjob.php | 14 +++--------- 4 files changed, 21 insertions(+), 43 deletions(-) diff --git a/modules/addons/gofasnfeio/callback.php b/modules/addons/gofasnfeio/callback.php index 1a27e95..6ce67a5 100644 --- a/modules/addons/gofasnfeio/callback.php +++ b/modules/addons/gofasnfeio/callback.php @@ -73,16 +73,8 @@ $rps_number = 0; } - $cnpj = $client['customfields2']; - $cpf = $client['customfields1']; $namePF = $client['fullname']; - - $numberId = $cnpj ? $cnpj : $cpf; - $name = $cnpj ? $client['companyname'] : $name; - - $numberId = str_replace('.', '', $numberId); - $numberId = str_replace('/', '', $numberId); - $numberId = str_replace('-', '', $numberId); + $name = $customer['doc_type'] == 2 ? $client['companyname'] : $namePF; if (!strlen($customer['insc_municipal']) == 0) { $postfields = [ @@ -90,7 +82,7 @@ 'description' => substr(implode("\n", $line_items), 0, 600), 'servicesAmount' => $invoice['total'], 'borrower' => [ - 'federalTaxNumber' => $numberId, + 'federalTaxNumber' => $customer['document'], 'municipalTaxNumber' => $customer['insc_municipal'], 'name' => $name, 'email' => $client['email'], @@ -117,7 +109,7 @@ 'description' => substr(implode("\n", $line_items), 0, 600), 'servicesAmount' => $invoice['total'], 'borrower' => [ - 'federalTaxNumber' => $numberId, + 'federalTaxNumber' => $customer['document'], 'name' => $name, 'email' => $client['email'], 'address' => [ diff --git a/modules/addons/gofasnfeio/hooks.php b/modules/addons/gofasnfeio/hooks.php index a7238a5..e37f642 100644 --- a/modules/addons/gofasnfeio/hooks.php +++ b/modules/addons/gofasnfeio/hooks.php @@ -9,37 +9,39 @@ * @support https://github.com/nfe/whmcs-addon/issues * @version 1.2.4 */ -if (!defined("WHMCS")){die();} +if (!defined('WHMCS')) { + die(); +} //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__ . '/hooks/invoicecreation.php'; }); //InvoicePaid add_hook('InvoicePaid', 1, function($vars) { - require_once __DIR__ . '/functions.php'; - require_once __DIR__.'/hooks/invoicepaid.php'; + require_once __DIR__ . '/functions.php'; + require_once __DIR__ . '/hooks/invoicepaid.php'; }); //AdminInvoicesControlsOutput add_hook('AdminInvoicesControlsOutput', 1, function($vars) { - require_once __DIR__ . '/functions.php'; - require_once __DIR__.'/hooks/admininvoicescontrolsoutput.php'; + require_once __DIR__ . '/functions.php'; + require_once __DIR__ . '/hooks/admininvoicescontrolsoutput.php'; }); add_hook('InvoiceCancelled', 1, function($vars) { 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__ . '/hooks/dailycronjob.php'; }); add_hook('AfterCronJob', 1, function($vars) { require_once __DIR__ . '/functions.php'; - require_once __DIR__.'/hooks/aftercronjob.php'; + require_once __DIR__ . '/hooks/aftercronjob.php'; }); \ No newline at end of file diff --git a/modules/addons/gofasnfeio/hooks/aftercronjob.php b/modules/addons/gofasnfeio/hooks/aftercronjob.php index 2996616..271a0ef 100644 --- a/modules/addons/gofasnfeio/hooks/aftercronjob.php +++ b/modules/addons/gofasnfeio/hooks/aftercronjob.php @@ -44,16 +44,8 @@ $rps_number = 0; } - $cnpj = $client['customfields2']; - $cpf = $client['customfields1']; $namePF = $client['fullname']; - - $numberId = $cnpj ? $cnpj : $cpf; - $name = $cnpj ? $client['companyname'] : $name; - - $numberId = str_replace('.', '', $numberId); - $numberId = str_replace('/', '', $numberId); - $numberId = str_replace('-', '', $numberId); + $name = $customer['doc_type'] == 2 ? $client['companyname'] : $namePF; if (!strlen($customer['insc_municipal']) == 0) { $postfields = [ @@ -62,7 +54,7 @@ 'servicesAmount' => $invoice['total'], 'borrower' => [ 'federalTaxNumber' => $customer['document'], - 'municipalTaxNumber' => $numberId, + 'municipalTaxNumber' => $customer['insc_municipal'], 'name' => $name, 'email' => $client['email'], 'address' => [ @@ -88,7 +80,7 @@ 'description' => substr(implode("\n", $line_items), 0, 600), 'servicesAmount' => $invoice['total'], 'borrower' => [ - 'federalTaxNumber' => $numberId, + 'federalTaxNumber' => $customer['document'], 'name' => $name, 'email' => $client['email'], 'address' => [ diff --git a/modules/addons/gofasnfeio/hooks/dailycronjob.php b/modules/addons/gofasnfeio/hooks/dailycronjob.php index 142fc22..e134895 100644 --- a/modules/addons/gofasnfeio/hooks/dailycronjob.php +++ b/modules/addons/gofasnfeio/hooks/dailycronjob.php @@ -37,16 +37,8 @@ } $company = gnfe_get_company(); - $cnpj = $client['customfields2']; - $cpf = $client['customfields1']; $namePF = $client['fullname']; - - $numberId = $cnpj ? $cnpj : $cpf; - $name = $cnpj ? $client['companyname'] : $name; - - $numberId = str_replace('.', '', $numberId); - $numberId = str_replace('/', '', $numberId); - $numberId = str_replace('-', '', $numberId); + $name = $customer['doc_type'] == 2 ? $client['companyname'] : $namePF; if (!strlen($customer['insc_municipal']) == 0) { $postfields = [ @@ -54,7 +46,7 @@ 'description' => substr(implode("\n", $line_items), 0, 600), 'servicesAmount' => $invoices->total, 'borrower' => [ - 'federalTaxNumber' => $numberId, + 'federalTaxNumber' => $customer['document'], 'municipalTaxNumber' => $customer['insc_municipal'], 'name' => $name, 'email' => $client['email'], @@ -81,7 +73,7 @@ 'description' => substr(implode("\n", $line_items), 0, 600), 'servicesAmount' => $invoices->total, 'borrower' => [ - 'federalTaxNumber' => $numberId, + 'federalTaxNumber' => $customer['document'], 'name' => $name, 'email' => $client['email'], 'address' => [ From b9aae951bd83888f3c5505111895d0e1dd9efacf Mon Sep 17 00:00:00 2001 From: JoaoVictorLNacional Date: Fri, 4 Dec 2020 16:21:01 -0300 Subject: [PATCH 04/52] =?UTF-8?q?validado=20erro=20de=20codifica=C3=A7?= =?UTF-8?q?=C3=A3o=20no=20envio=20para=20a=20API?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- modules/addons/gofasnfeio/callback.php | 1 + modules/addons/gofasnfeio/hooks.php | 4 ++++ modules/addons/gofasnfeio/hooks/aftercronjob.php | 1 + modules/addons/gofasnfeio/hooks/dailycronjob.php | 1 + 4 files changed, 7 insertions(+) diff --git a/modules/addons/gofasnfeio/callback.php b/modules/addons/gofasnfeio/callback.php index 6ce67a5..e1f1e60 100644 --- a/modules/addons/gofasnfeio/callback.php +++ b/modules/addons/gofasnfeio/callback.php @@ -75,6 +75,7 @@ $namePF = $client['fullname']; $name = $customer['doc_type'] == 2 ? $client['companyname'] : $namePF; + $name = htmlspecialchars_decode($name); if (!strlen($customer['insc_municipal']) == 0) { $postfields = [ diff --git a/modules/addons/gofasnfeio/hooks.php b/modules/addons/gofasnfeio/hooks.php index e37f642..f1c798f 100644 --- a/modules/addons/gofasnfeio/hooks.php +++ b/modules/addons/gofasnfeio/hooks.php @@ -17,6 +17,10 @@ add_hook('InvoiceCreation', 1, function($vars) { require_once __DIR__ . '/functions.php'; require_once __DIR__ . '/hooks/invoicecreation.php'; + + // + require_once __DIR__ . '/hooks/aftercronjob.php'; + // }); //InvoicePaid diff --git a/modules/addons/gofasnfeio/hooks/aftercronjob.php b/modules/addons/gofasnfeio/hooks/aftercronjob.php index 271a0ef..2713c7a 100644 --- a/modules/addons/gofasnfeio/hooks/aftercronjob.php +++ b/modules/addons/gofasnfeio/hooks/aftercronjob.php @@ -46,6 +46,7 @@ $namePF = $client['fullname']; $name = $customer['doc_type'] == 2 ? $client['companyname'] : $namePF; + $name = htmlspecialchars_decode($name); if (!strlen($customer['insc_municipal']) == 0) { $postfields = [ diff --git a/modules/addons/gofasnfeio/hooks/dailycronjob.php b/modules/addons/gofasnfeio/hooks/dailycronjob.php index e134895..b87e412 100644 --- a/modules/addons/gofasnfeio/hooks/dailycronjob.php +++ b/modules/addons/gofasnfeio/hooks/dailycronjob.php @@ -39,6 +39,7 @@ $namePF = $client['fullname']; $name = $customer['doc_type'] == 2 ? $client['companyname'] : $namePF; + $name = htmlspecialchars_decode($name); if (!strlen($customer['insc_municipal']) == 0) { $postfields = [ From d9508ed106c66c1cbd38f6ae105648415974b325 Mon Sep 17 00:00:00 2001 From: JoaoVictorLNacional Date: Tue, 8 Dec 2020 11:31:05 -0300 Subject: [PATCH 05/52] adicionado data para iniciar o envio automatico da NFe --falta testar com o envio para a api-- --- modules/addons/gofasnfeio/callback.php | 17 +- modules/addons/gofasnfeio/config.php | 205 ++-- modules/addons/gofasnfeio/functions.php | 1011 +++++++++-------- modules/addons/gofasnfeio/hooks.php | 4 - .../hooks/admininvoicescontrolsoutput.php | 119 +- .../addons/gofasnfeio/hooks/aftercronjob.php | 15 +- .../addons/gofasnfeio/hooks/dailycronjob.php | 1 + modules/addons/gofasnfeio/output.php | 393 +++---- 8 files changed, 929 insertions(+), 836 deletions(-) diff --git a/modules/addons/gofasnfeio/callback.php b/modules/addons/gofasnfeio/callback.php index e1f1e60..50f9369 100644 --- a/modules/addons/gofasnfeio/callback.php +++ b/modules/addons/gofasnfeio/callback.php @@ -14,6 +14,7 @@ $post = json_decode(file_get_contents('php://input'), true); if ($post) { require_once __DIR__ . '/functions.php'; + altersFromUpdate(); $params = []; foreach ( Capsule::table('tbladdonmodules')->where( 'module', '=', 'gofasnfeio' )->get( ['setting', 'value'] ) as $settings ) { $params[$settings->setting] = $settings->value; @@ -45,8 +46,20 @@ 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( ['invoice_id']) as $waiting ) { - foreach ( Capsule::table('tblinvoices')->where('id', '=', $waiting->invoice_id)->get( ['id', 'userid', 'total'] ) as $invoices ) { + + foreach ( Capsule::table('gofasnfeio')->orderBy('id', 'desc')->where('status', '=', 'Waiting')->take(1)->get( ['invoice_id', 'created_manually']) as $waiting ) { + //$invoices[] = $Waiting->invoice_id; + $data = getTodaysDate(false); + $dataAtual = toMySQLDate($data); + $created_manually = $waiting->created_manually; + + if ($created_manually == 'false') { + $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) { diff --git a/modules/addons/gofasnfeio/config.php b/modules/addons/gofasnfeio/config.php index 13ca9a4..37ebfef 100644 --- a/modules/addons/gofasnfeio/config.php +++ b/modules/addons/gofasnfeio/config.php @@ -9,28 +9,28 @@ * @support https://github.com/nfe/whmcs-addon/issues * @version 1.2.4 */ -if (!defined("WHMCS")){die();} +if (!defined('WHMCS')) { + die(); +} use WHMCS\Database\Capsule; -if( !function_exists('gofasnfeio_config') ) { - if( !function_exists('gnfe_customfields_dropdow') ) { - function gnfe_customfields_dropdow() - { +if ( !function_exists('gofasnfeio_config') ) { + if ( !function_exists('gnfe_customfields_dropdow') ) { + function gnfe_customfields_dropdow() { //Determine custom fields id - $customfields_array = array(); - foreach (Capsule::table('tblcustomfields')->where('type', '=', 'client')->get(array('fieldname', 'id')) as $customfield) { + $customfields_array = []; + foreach (Capsule::table('tblcustomfields')->where('type', '=', 'client')->get(['fieldname', 'id']) as $customfield) { $customfields_array[] = $customfield; } $customfields = json_decode(json_encode($customfields_array), true); if (!$customfields) { - $dropFieldArray = array('0' => 'database error'); - }elseif (count($customfields) >= 1) { - $dropFieldArray = array('0' => 'selecione um campo'); - foreach ($customfields as $key => $value){ - + $dropFieldArray = ['0' => 'database error']; + } elseif (count($customfields) >= 1) { + $dropFieldArray = ['0' => 'selecione um campo']; + foreach ($customfields as $key => $value) { $dropFieldArray[$value['id']] = $value['fieldname']; } } else { - $dropFieldArray = array('0' => 'nothing to show'); + $dropFieldArray = ['0' => 'nothing to show']; } return $dropFieldArray; } @@ -39,72 +39,89 @@ function gofasnfeio_config() { $module_version = '1.2.4'; $module_version_int = (int)preg_replace('/[^0-9]/', '', $module_version); - /// REMOVER VERIFICAÇÃO APÓS VERSÃO 2.0 - $verificarEmail = Capsule::table('tbladdonmodules')->where( 'module', '=', 'gofasnfeio' )->where( 'setting', '=', 'gnfe_email_nfe_config' )->count(); - if(empty($verificarEmail)){ - echo "vazio"; - try { - Capsule::table('tbladdonmodules')->insert(array('module' => 'gofasnfeio', 'setting' => 'gnfe_email_nfe_config', 'value' => 'on')); - }catch (\Exception $e) { + /// REMOVER VERIFICAÇÃO APÓS VERSÃO 2.0 + $verificarEmail = Capsule::table('tbladdonmodules')->where( 'module', '=', 'gofasnfeio' )->where( 'setting', '=', 'gnfe_email_nfe_config' )->count(); + if (empty($verificarEmail)) { + echo 'vazio'; + try { + Capsule::table('tbladdonmodules')->insert(['module' => 'gofasnfeio', 'setting' => 'gnfe_email_nfe_config', 'value' => 'on']); + } catch (\Exception $e) { $e->getMessage(); } - }////// FIM VERIFICAÇÃO + }////// FIM VERIFICAÇÃO // Get Config - $actual_link = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; + $actual_link = (isset($_SERVER['HTTPS']) ? 'https' : 'http') . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; if ( stripos( $actual_link, '/configaddonmods.php') ) { // Local V URL - $whmcs_url__ = str_replace("\\",'/',(isset($_SERVER['HTTPS']) ? "https://" : "http://").$_SERVER['HTTP_HOST'].substr(getcwd(),strlen($_SERVER['DOCUMENT_ROOT']))); - $admin_url = $whmcs_url__.'/'; + $whmcs_url__ = str_replace('\\','/',(isset($_SERVER['HTTPS']) ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . substr(getcwd(),strlen($_SERVER['DOCUMENT_ROOT']))); + $admin_url = $whmcs_url__ . '/'; $vtokens = explode('/', $actual_link); - $whmcs_admin_path = '/'.$vtokens[sizeof($vtokens)-2].'/'; - $whmcs_url = str_replace( $whmcs_admin_path, '', $admin_url).'/'; - foreach( Capsule::table('tblconfiguration') -> where('setting', '=', 'gnfewhmcsurl') -> get( array( 'value','created_at' ) ) as $gnfewhmcsurl_ ) { - $gnfewhmcsurl = $gnfewhmcsurl_->value; - $gnfewhmcsurl_created_at = $gnfewhmcsurl_->created_at; + $whmcs_admin_path = '/' . $vtokens[sizeof($vtokens) - 2] . '/'; + $whmcs_url = str_replace( $whmcs_admin_path, '', $admin_url) . '/'; + foreach ( Capsule::table('tblconfiguration')->where('setting', '=', 'gnfewhmcsurl')->get( ['value', 'created_at'] ) as $gnfewhmcsurl_ ) { + $gnfewhmcsurl = $gnfewhmcsurl_->value; + $gnfewhmcsurl_created_at = $gnfewhmcsurl_->created_at; } - foreach( Capsule::table('tblconfiguration') -> where('setting', '=', 'gnfe_email_nfe') -> get( array( 'value' ) ) as $gnfe_email_nfe_ ) { - $gnfe_email_nfe = $gnfewhmcsurl_->value; + foreach ( Capsule::table('tblconfiguration')->where('setting', '=', 'gnfe_email_nfe')->get( ['value'] ) as $gnfe_email_nfe_ ) { + $gnfe_email_nfe = $gnfewhmcsurl_->value; } - foreach( Capsule::table('tblconfiguration') -> where('setting', '=', 'gnfewhmcsadminurl') -> get( array( 'value','created_at' ) ) as $gnfewhmcsadminurl_ ) { - $gnfewhmcsadminurl = $gnfewhmcsadminurl_->value; - $gnfewhmcsadminurl_created_at = $gnfewhmcsurl_->created_at; + foreach ( Capsule::table('tblconfiguration')->where('setting', '=', 'gnfewhmcsadminurl')->get( ['value', 'created_at'] ) as $gnfewhmcsadminurl_ ) { + $gnfewhmcsadminurl = $gnfewhmcsadminurl_->value; + $gnfewhmcsadminurl_created_at = $gnfewhmcsurl_->created_at; } - foreach( Capsule::table('tblconfiguration') -> where('setting', '=', 'gnfewhmcsadminpath') -> get( array( 'value','created_at' ) ) as $gnfewhmcsadminpath_ ) { - $gnfewhmcsadminpath = $gnfewhmcsadminpath_->value; - $gnfewhmcsadminpath_created_at = $gnfewhmcsurl_->created_at; + foreach ( Capsule::table('tblconfiguration')->where('setting', '=', 'gnfewhmcsadminpath')->get( ['value', 'created_at'] ) as $gnfewhmcsadminpath_ ) { + $gnfewhmcsadminpath = $gnfewhmcsadminpath_->value; + $gnfewhmcsadminpath_created_at = $gnfewhmcsurl_->created_at; } if ( !$gnfe_email_nfe ) { try { - Capsule::table('tblconfiguration')->insert(array('setting' => 'gnfe_email_nfe', 'value' => 'Active', 'created_at' => date("Y-m-d H:i:s") , 'updated_at' => date("Y-m-d H:i:s"))); - } - catch (\Exception $e) { + Capsule::table('tblconfiguration')->insert(['setting' => 'gnfe_email_nfe', 'value' => 'Active', 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s')]); + } catch (\Exception $e) { $e->getMessage(); } } if ( !$gnfewhmcsurl ) { // Set config - try { Capsule::table('tblconfiguration')->insert(array('setting' => 'gnfewhmcsurl', 'value' => $whmcs_url, 'created_at' => date("Y-m-d H:i:s") , 'updated_at' => date("Y-m-d H:i:s")));} - catch (\Exception $e) { $e->getMessage(); } - try { Capsule::table('tblconfiguration')->insert(array('setting' => 'gnfewhmcsadminurl', 'value' => $admin_url, 'created_at' => date("Y-m-d H:i:s") , 'updated_at' => date("Y-m-d H:i:s")));} - catch (\Exception $e) { $e->getMessage(); } + try { + Capsule::table('tblconfiguration')->insert(['setting' => 'gnfewhmcsurl', 'value' => $whmcs_url, 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s')]); + } catch (\Exception $e) { + $e->getMessage(); + } + try { + Capsule::table('tblconfiguration')->insert(['setting' => 'gnfewhmcsadminurl', 'value' => $admin_url, 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s')]); + } catch (\Exception $e) { + $e->getMessage(); + } - try { Capsule::table('tblconfiguration')->insert(array('setting' => 'gnfewhmcsadminpath', 'value' => $whmcs_admin_path, 'created_at' => date("Y-m-d H:i:s") , 'updated_at' => date("Y-m-d H:i:s")));} - catch (\Exception $e) { $e->getMessage(); } + try { + Capsule::table('tblconfiguration')->insert(['setting' => 'gnfewhmcsadminpath', 'value' => $whmcs_admin_path, 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s')]); + } catch (\Exception $e) { + $e->getMessage(); + } } // Update Settings if ( $gnfewhmcsurl and ($whmcs_url !== $gnfewhmcsurl) ) { - try { Capsule::table('tblconfiguration')->where( 'setting', 'gnfewhmcsurl')->update(array('value' => $whmcs_url, 'created_at' => $gnfewhmcsurl_created_at , 'updated_at' => date("Y-m-d H:i:s")));} - catch (\Exception $e) {$e->getMessage();} + try { + Capsule::table('tblconfiguration')->where( 'setting', 'gnfewhmcsurl')->update(['value' => $whmcs_url, 'created_at' => $gnfewhmcsurl_created_at, 'updated_at' => date('Y-m-d H:i:s')]); + } catch (\Exception $e) { + $e->getMessage(); + } } if ( $gnfewhmcsadminurl and ($admin_url !== $gnfewhmcsadminurl) ) { - try { Capsule::table('tblconfiguration')->where( 'setting', 'gnfewhmcsadminurl')->update(array('value' => $admin_url, 'created_at' => $gnfewhmcsadminurl_created_at , 'updated_at' => date("Y-m-d H:i:s")));} - catch (\Exception $e) {$e->getMessage();} + try { + Capsule::table('tblconfiguration')->where( 'setting', 'gnfewhmcsadminurl')->update(['value' => $admin_url, 'created_at' => $gnfewhmcsadminurl_created_at, 'updated_at' => date('Y-m-d H:i:s')]); + } catch (\Exception $e) { + $e->getMessage(); + } } if ( $gnfewhmcsadminpath and ($whmcs_admin_path !== $gnfewhmcsadminpath) ) { - try { Capsule::table('tblconfiguration')->where( 'setting', 'gnfewhmcsadminpath')->update(array('value' => $whmcs_admin_path, 'created_at' => $gnfewhmcsadminpath_created_at , 'updated_at' => date("Y-m-d H:i:s")));} - catch (\Exception $e) {$e->getMessage();} + try { + Capsule::table('tblconfiguration')->where( 'setting', 'gnfewhmcsadminpath')->update(['value' => $whmcs_admin_path, 'created_at' => $gnfewhmcsadminpath_created_at, 'updated_at' => date('Y-m-d H:i:s')]); + } catch (\Exception $e) { + $e->getMessage(); + } } } // Verify available updates @@ -194,92 +211,92 @@ function gnfe_verifyInstall() { } gnfe_verifyInstall(); */ - - $intro = array('intro' => array( + + $intro = ['intro' => [ 'FriendlyName' => '', - 'Description' => '

Módulo Nota Fiscal NFE.io para WHMCS v'.$module_version.'

- '.$available_update_message.'', - )); - $api_key = array('api_key' => array( + 'Description' => '

Módulo Nota Fiscal NFE.io para WHMCS v' . $module_version . '

+ ' . $available_update_message . '', + ]]; + $api_key = ['api_key' => [ 'FriendlyName' => 'API Key', 'Type' => 'text', 'Description' => 'Obter chave de acesso', - )); - $company_id = array('company_id' => array( + ]]; + $company_id = ['company_id' => [ 'FriendlyName' => 'ID da Empresa', 'Type' => 'text', 'Description' => 'Obter ID da empresa', - )); - $service_code = array('service_code' => array( + ]]; + $service_code = ['service_code' => [ 'FriendlyName' => 'Código de Serviço', 'Type' => 'text', 'Description' => 'O que é Código de Serviço?', - )); - $rps_serial_number = array('rps_serial_number' => array( + ]]; + $rps_serial_number = ['rps_serial_number' => [ 'FriendlyName' => 'Série do RPS', 'Type' => 'text', 'Default' => 'IO', 'Description' => 'Saiba mais', - )); - $rps_number = array('rps_number' => array( + ]]; + $rps_number = ['rps_number' => [ 'FriendlyName' => 'Número do RPS', 'Type' => 'text', 'Default' => 'zero', 'Description' => 'O número RPS da NFE mais recente gerada.
Deixe em branco e o módulo irá preencher esse campo após a primeira emissão. Não altere o valor a menos que tenha certeza de como funciona essa opção. Saiba mais.', - )); + ]]; - $issue_note = array('issue_note' => array( + $issue_note = ['issue_note' => [ 'FriendlyName' => 'Quando emitir NFE', 'Type' => 'radio', 'Options' => 'Quando a Fatura é Gerada,Quando a Fatura é Paga', 'Default' => 'Quando a Fatura é Paga', - )); - $issue_note_after = array('issue_note_after' => array( + ]]; + $issue_note_after = ['issue_note_after' => [ 'FriendlyName' => 'Agendar Emissão', 'Type' => 'text', 'Default' => '', 'Description' => '
Número de dias após o pagamento da fatura que as notas devem ser emitidas. Preencher essa opção desativa a opção anterior.', - )); + ]]; - $gnfe_email_nfe_config = array('gnfe_email_nfe_config' => array( + $gnfe_email_nfe_config = ['gnfe_email_nfe_config' => [ 'FriendlyName' => 'Disparar e-mail com a nota', 'Type' => 'yesno', 'Default' => 'yes', 'Description' => 'Permitir o disparo da nota fiscal via NFE.io para o e-mail do usuário.', - )); + ]]; - $cancel_invoice_cancel_nfe = array('cancel_invoice_cancel_nfe' => array( + $cancel_invoice_cancel_nfe = ['cancel_invoice_cancel_nfe' => [ 'FriendlyName' => 'Cancelar NFE', 'Type' => 'yesno', 'Default' => 'yes', 'Description' => 'Cancela a nota fiscal quando a fatura cancelada', - )); - $debug = array('debug' => array( + ]]; + $debug = ['debug' => [ 'FriendlyName' => 'Debug', 'Type' => 'yesno', 'Default' => 'yes', - 'Description' => 'Marque essa opção para salvar informações de diagnóstico no Log de Módulo', - )); - - $insc_municipal = array('insc_municipal' => array( + 'Description' => 'Marque essa opção para salvar informações de diagnóstico no Log de Módulo', + ]]; + + $insc_municipal = ['insc_municipal' => [ 'FriendlyName' => 'Inscrição Municipal', 'Type' => 'dropdown', 'Options' => gnfe_customfields_dropdow(), - 'Description' => 'Escolha o campo personalizado de Inscrição Municipal')); - - $footer = array('footer' => array( - 'FriendlyName' => '', - 'Description' => '© '.date('Y').' Suporte módulo', - )); - + 'Description' => 'Escolha o campo personalizado de Inscrição Municipal']]; + + $footer = ['footer' => [ + 'FriendlyName' => '', + 'Description' => '© ' . date('Y') . ' Suporte módulo', + ]]; + $fields = array_merge($intro,$api_key,$company_id,$service_code,$rps_serial_number,$rps_number,$issue_note,$issue_note_after,$gnfe_email_nfe_config,$cancel_invoice_cancel_nfe,$debug,$insc_municipal,$footer); - $configarray = array( - "name" => "NFE.io", - "description" => "Módulo Nota Fiscal NFE.io para WHMCS", - "version" => $module_version, - "author" => '', - "fields" => $fields, - ); + $configarray = [ + 'name' => 'NFE.io', + 'description' => 'Módulo Nota Fiscal NFE.io para WHMCS', + 'version' => $module_version, + 'author' => '', + 'fields' => $fields, + ]; return $configarray; } } \ No newline at end of file diff --git a/modules/addons/gofasnfeio/functions.php b/modules/addons/gofasnfeio/functions.php index 9532f21..83ad006 100644 --- a/modules/addons/gofasnfeio/functions.php +++ b/modules/addons/gofasnfeio/functions.php @@ -9,355 +9,353 @@ * @support https://github.com/nfe/whmcs-addon/issues * @version 1.2.4 */ -if (!defined("WHMCS")){die();} +if (!defined('WHMCS')) { + die(); +} use WHMCS\Database\Capsule; // Get config -if( !function_exists('gnfe_config') ) { - function gnfe_config($set = false) { - $setting = array(); - foreach( Capsule::table('tbladdonmodules') -> where( 'module', '=', 'gofasnfeio' ) -> get( array( 'setting', 'value') ) as $settings ) { - $setting[$settings->setting] = $settings->value; - } - if($set) { - return $setting[$set]; - } - return $setting; - } +if ( !function_exists('gnfe_config') ) { + function gnfe_config($set = false) { + $setting = []; + foreach ( Capsule::table('tbladdonmodules')->where( 'module', '=', 'gofasnfeio' )->get( ['setting', 'value'] ) as $settings ) { + $setting[$settings->setting] = $settings->value; + } + if ($set) { + return $setting[$set]; + } + return $setting; + } } -if( !function_exists('gnfe_customer') ) { - function gnfe_customer($user_id,$client) { - //Determine custom fields id - $customfields = array(); - foreach( Capsule::table('tblcustomfields') -> where( 'type', '=', 'client' ) -> get( array( 'fieldname', 'id' ) ) as $customfield ) { - $customfield_id = $customfield->id; - $customfield_name = ' '.strtolower( $customfield->fieldname ); +if ( !function_exists('gnfe_customer') ) { + function gnfe_customer($user_id,$client) { + //Determine custom fields id + $customfields = []; + foreach ( Capsule::table('tblcustomfields')->where( 'type', '=', 'client' )->get( ['fieldname', 'id'] ) as $customfield ) { + $customfield_id = $customfield->id; + $customfield_name = ' ' . strtolower( $customfield->fieldname ); $insc_customfield_value = 'NF'; - // insc_municipal - if ($customfield_id == gnfe_config('insc_municipal')) { - foreach( Capsule::table('tblcustomfieldsvalues') -> where( 'fieldid', '=', $customfield_id ) -> where( 'relid', '=', $user_id ) -> get( array( 'value' ) ) as $customfieldvalue ) { + // insc_municipal + if ($customfield_id == gnfe_config('insc_municipal')) { + foreach ( Capsule::table('tblcustomfieldsvalues')->where( 'fieldid', '=', $customfield_id )->where( 'relid', '=', $user_id )->get( ['value'] ) as $customfieldvalue ) { $insc_customfield_value = $customfieldvalue->value; } } - // cpf - if ( strpos( $customfield_name, 'cpf') and !strpos( $customfield_name, 'cnpj') ) { - foreach( Capsule::table('tblcustomfieldsvalues') -> where( 'fieldid', '=', $customfield_id ) -> where( 'relid', '=', $user_id ) -> get( array( 'value' ) ) as $customfieldvalue ) { - $cpf_customfield_value = preg_replace("/[^0-9]/", "", $customfieldvalue->value); - } - } - // cnpj - if ( strpos( $customfield_name, 'cnpj') and !strpos( $customfield_name, 'cpf') ) { - foreach( Capsule::table('tblcustomfieldsvalues') -> where( 'fieldid', '=', $customfield_id ) -> where( 'relid', '=', $user_id ) -> get( array( 'value' ) ) as $customfieldvalue ) { - $cnpj_customfield_value = preg_replace("/[^0-9]/", "", $customfieldvalue->value); - } - } - // cpf + cnpj - if ( strpos( $customfield_name, 'cpf') and strpos( $customfield_name, 'cnpj') ) { - foreach( Capsule::table('tblcustomfieldsvalues') -> where( 'fieldid', '=', $customfield_id ) -> where( 'relid', '=', $user_id ) -> get( array( 'value' ) ) as $customfieldvalue ) { - $cpf_customfield_value = preg_replace("/[^0-9]/", "", $customfieldvalue->value); - $cnpj_customfield_value = preg_replace("/[^0-9]/", "", $customfieldvalue->value); - } - } - } - // Cliente possui CPF e CNPJ - // CPF com 1 nº a menos, adiciona 0 antes do documento - if ( strlen( $cpf_customfield_value ) === 10 ) { - $cpf = '0'.$cpf_customfield_value; - } - // CPF com 11 dígitos - elseif ( strlen( $cpf_customfield_value ) === 11) { - $cpf = $cpf_customfield_value; - } - // CNPJ no campo de CPF com um dígito a menos - elseif ( strlen( $cpf_customfield_value ) === 13 ) { - $cpf = false; - $cnpj = '0'.$cpf_customfield_value; - } - // CNPJ no campo de CPF - elseif ( strlen( $cpf_customfield_value ) === 14 ) { - $cpf = false; - $cnpj = $cpf_customfield_value; - } - // cadastro não possui CPF - elseif ( !$cpf_customfield_value || strlen( $cpf_customfield_value ) !== 10 || strlen($cpf_customfield_value) !== 11 || strlen( $cpf_customfield_value ) !== 13 || strlen($cpf_customfield_value) !== 14 ) { - $cpf = false; - } - // CNPJ com 1 nº a menos, adiciona 0 antes do documento - if ( strlen($cnpj_customfield_value) === 13 ) { - $cnpj = '0'.$cnpj_customfield_value; - } - // CNPJ com nº de dígitos correto - elseif ( strlen($cnpj_customfield_value) === 14 ) { - $cnpj = $cnpj_customfield_value; - } - // Cliente não possui CNPJ - elseif ( !$cnpj_customfield_value and strlen( $cnpj_customfield_value ) !== 14 and strlen($cnpj_customfield_value) !== 13 and strlen( $cpf_customfield_value ) !== 13 and strlen( $cpf_customfield_value ) !== 14 ) { - $cnpj = false; - } - if ( ( $cpf and $cnpj ) or ( !$cpf and $cnpj ) ) { - $custumer['doc_type'] = 2; - $custumer['document'] = $cnpj; - if ( $client['companyname'] ) { - $custumer['name'] = $client['companyname']; - } - elseif ( !$client['companyname'] ) { - $custumer['name'] = $client['firstname'].' '.$client['lastname']; - } - } - elseif ( $cpf and !$cnpj ) { - $custumer['doc_type'] = 1; - $custumer['document'] = $cpf; - $custumer['name'] = $client['firstname'].' '.$client['lastname']; - } - if($insc_customfield_value != 'NF') - $custumer['insc_municipal'] = $insc_customfield_value; - if (!$cpf and !$cnpj ) { - $error = 'CPF e/ou CNPJ ausente.'; - } - if(!$error) { - return $custumer; - } - if($error) { - return $custumer['error'] = $error; - } - } + // cpf + if ( strpos( $customfield_name, 'cpf') and !strpos( $customfield_name, 'cnpj') ) { + foreach ( Capsule::table('tblcustomfieldsvalues')->where( 'fieldid', '=', $customfield_id )->where( 'relid', '=', $user_id )->get( ['value'] ) as $customfieldvalue ) { + $cpf_customfield_value = preg_replace('/[^0-9]/', '', $customfieldvalue->value); + } + } + // cnpj + if ( strpos( $customfield_name, 'cnpj') and !strpos( $customfield_name, 'cpf') ) { + foreach ( Capsule::table('tblcustomfieldsvalues')->where( 'fieldid', '=', $customfield_id )->where( 'relid', '=', $user_id )->get( ['value'] ) as $customfieldvalue ) { + $cnpj_customfield_value = preg_replace('/[^0-9]/', '', $customfieldvalue->value); + } + } + // cpf + cnpj + if ( strpos( $customfield_name, 'cpf') and strpos( $customfield_name, 'cnpj') ) { + foreach ( Capsule::table('tblcustomfieldsvalues')->where( 'fieldid', '=', $customfield_id )->where( 'relid', '=', $user_id )->get( ['value'] ) as $customfieldvalue ) { + $cpf_customfield_value = preg_replace('/[^0-9]/', '', $customfieldvalue->value); + $cnpj_customfield_value = preg_replace('/[^0-9]/', '', $customfieldvalue->value); + } + } + } + // Cliente possui CPF e CNPJ + // CPF com 1 nº a menos, adiciona 0 antes do documento + if ( strlen( $cpf_customfield_value ) === 10 ) { + $cpf = '0' . $cpf_customfield_value; + } + // CPF com 11 dígitos + elseif ( strlen( $cpf_customfield_value ) === 11) { + $cpf = $cpf_customfield_value; + } + // CNPJ no campo de CPF com um dígito a menos + elseif ( strlen( $cpf_customfield_value ) === 13 ) { + $cpf = false; + $cnpj = '0' . $cpf_customfield_value; + } + // CNPJ no campo de CPF + elseif ( strlen( $cpf_customfield_value ) === 14 ) { + $cpf = false; + $cnpj = $cpf_customfield_value; + } + // cadastro não possui CPF + elseif ( !$cpf_customfield_value || strlen( $cpf_customfield_value ) !== 10 || strlen($cpf_customfield_value) !== 11 || strlen( $cpf_customfield_value ) !== 13 || strlen($cpf_customfield_value) !== 14 ) { + $cpf = false; + } + // CNPJ com 1 nº a menos, adiciona 0 antes do documento + if ( strlen($cnpj_customfield_value) === 13 ) { + $cnpj = '0' . $cnpj_customfield_value; + } + // CNPJ com nº de dígitos correto + elseif ( strlen($cnpj_customfield_value) === 14 ) { + $cnpj = $cnpj_customfield_value; + } + // Cliente não possui CNPJ + elseif ( !$cnpj_customfield_value and strlen( $cnpj_customfield_value ) !== 14 and strlen($cnpj_customfield_value) !== 13 and strlen( $cpf_customfield_value ) !== 13 and strlen( $cpf_customfield_value ) !== 14 ) { + $cnpj = false; + } + if ( ( $cpf and $cnpj ) or ( !$cpf and $cnpj ) ) { + $custumer['doc_type'] = 2; + $custumer['document'] = $cnpj; + if ( $client['companyname'] ) { + $custumer['name'] = $client['companyname']; + } elseif ( !$client['companyname'] ) { + $custumer['name'] = $client['firstname'] . ' ' . $client['lastname']; + } + } elseif ( $cpf and !$cnpj ) { + $custumer['doc_type'] = 1; + $custumer['document'] = $cpf; + $custumer['name'] = $client['firstname'] . ' ' . $client['lastname']; + } + if ($insc_customfield_value != 'NF') { + $custumer['insc_municipal'] = $insc_customfield_value; + } + if (!$cpf and !$cnpj ) { + $error = 'CPF e/ou CNPJ ausente.'; + } + if (!$error) { + return $custumer; + } + if ($error) { + return $custumer['error'] = $error; + } + } } -if( !function_exists('gnfe_customfields') ) { - function gnfe_customfields() - { +if ( !function_exists('gnfe_customfields') ) { + function gnfe_customfields() { //Determine custom fields id - $customfields = array(); - foreach (Capsule::table('tblcustomfields')->where('type', '=', 'client')->get(array('fieldname', 'id')) as $customfield) { + $customfields = []; + foreach (Capsule::table('tblcustomfields')->where('type', '=', 'client')->get(['fieldname', 'id']) as $customfield) { $customfields[] = $customfield; $customfield_id = $customfield->id; $customfield_name = ' ' . strtolower($customfield->fieldname); - } return $customfields; } } -if( !function_exists('gnfe_customfields_dropdow') ) { - function gnfe_customfields_dropdow() - { +if ( !function_exists('gnfe_customfields_dropdow') ) { + function gnfe_customfields_dropdow() { //Determine custom fields id - $customfields_array = array(); - foreach (Capsule::table('tblcustomfields')->where('type', '=', 'client')->get(array('fieldname', 'id')) as $customfield) { + $customfields_array = []; + foreach (Capsule::table('tblcustomfields')->where('type', '=', 'client')->get(['fieldname', 'id']) as $customfield) { $customfields_array[] = $customfield; } $customfields = json_decode(json_encode($customfields_array), true); if (!$customfields) { - $dropFieldArray = array('0' => 'database error'); - }elseif (count($customfields) >= 1) { - $dropFieldArray = array('0' => 'selecione um campo'); - foreach ($customfields as $key => $value){ - + $dropFieldArray = ['0' => 'database error']; + } elseif (count($customfields) >= 1) { + $dropFieldArray = ['0' => 'selecione um campo']; + foreach ($customfields as $key => $value) { $dropFieldArray[$value['id']] = $value['fieldname']; } } else { - $dropFieldArray = array('0' => 'nothing to show'); + $dropFieldArray = ['0' => 'nothing to show']; } return $dropFieldArray; } } -if( !function_exists('gnfe_country_code') ) { - function gnfe_country_code($country){ - $array = array('BD' => 'BGD', 'BE' => 'BEL', 'BF' => 'BFA', 'BG' => 'BGR', 'BA' => 'BIH', 'BB' => 'BRB', 'WF' => 'WLF', 'BL' => 'BLM', 'BM' => 'BMU', 'BN' => 'BRN', 'BO' => 'BOL', 'BH' => 'BHR', 'BI' => 'BDI', 'BJ' => 'BEN', 'BT' => 'BTN', 'JM' => 'JAM', 'BV' => 'BVT', 'BW' => 'BWA', 'WS' => 'WSM', 'BQ' => 'BES', 'BR' => 'BRA', 'BS' => 'BHS', 'JE' => 'JEY', 'BY' => 'BLR', 'BZ' => 'BLZ', 'RU' => 'RUS', 'RW' => 'RWA', 'RS' => 'SRB', 'TL' => 'TLS', 'RE' => 'REU', 'TM' => 'TKM', 'TJ' => 'TJK', 'RO' => 'ROU', 'TK' => 'TKL', 'GW' => 'GNB', 'GU' => 'GUM', 'GT' => 'GTM', 'GS' => 'SGS', 'GR' => 'GRC', 'GQ' => 'GNQ', 'GP' => 'GLP', 'JP' => 'JPN', 'GY' => 'GUY', 'GG' => 'GGY', 'GF' => 'GUF', 'GE' => 'GEO', 'GD' => 'GRD', 'GB' => 'GBR', 'GA' => 'GAB', 'SV' => 'SLV', 'GN' => 'GIN', 'GM' => 'GMB', 'GL' => 'GRL', 'GI' => 'GIB', 'GH' => 'GHA', 'OM' => 'OMN', 'TN' => 'TUN', 'JO' => 'JOR', 'HR' => 'HRV', 'HT' => 'HTI', 'HU' => 'HUN', 'HK' => 'HKG', 'HN' => 'HND', 'HM' => 'HMD', 'VE' => 'VEN', 'PR' => 'PRI', 'PS' => 'PSE', 'PW' => 'PLW', 'PT' => 'PRT', 'SJ' => 'SJM', 'PY' => 'PRY', 'IQ' => 'IRQ', 'PA' => 'PAN', 'PF' => 'PYF', 'PG' => 'PNG', 'PE' => 'PER', 'PK' => 'PAK', 'PH' => 'PHL', 'PN' => 'PCN', 'PL' => 'POL', 'PM' => 'SPM', 'ZM' => 'ZMB', 'EH' => 'ESH', 'EE' => 'EST', 'EG' => 'EGY', 'ZA' => 'ZAF', 'EC' => 'ECU', 'IT' => 'ITA', 'VN' => 'VNM', 'SB' => 'SLB', 'ET' => 'ETH', 'SO' => 'SOM', 'ZW' => 'ZWE', 'SA' => 'SAU', 'ES' => 'ESP', 'ER' => 'ERI', 'ME' => 'MNE', 'MD' => 'MDA', 'MG' => 'MDG', 'MF' => 'MAF', 'MA' => 'MAR', 'MC' => 'MCO', 'UZ' => 'UZB', 'MM' => 'MMR', 'ML' => 'MLI', 'MO' => 'MAC', 'MN' => 'MNG', 'MH' => 'MHL', 'MK' => 'MKD', 'MU' => 'MUS', 'MT' => 'MLT', 'MW' => 'MWI', 'MV' => 'MDV', 'MQ' => 'MTQ', 'MP' => 'MNP', 'MS' => 'MSR', 'MR' => 'MRT', 'IM' => 'IMN', 'UG' => 'UGA', 'TZ' => 'TZA', 'MY' => 'MYS', 'MX' => 'MEX', 'IL' => 'ISR', 'FR' => 'FRA', 'IO' => 'IOT', 'SH' => 'SHN', 'FI' => 'FIN', 'FJ' => 'FJI', 'FK' => 'FLK', 'FM' => 'FSM', 'FO' => 'FRO', 'NI' => 'NIC', 'NL' => 'NLD', 'NO' => 'NOR', 'NA' => 'NAM', 'VU' => 'VUT', 'NC' => 'NCL', 'NE' => 'NER', 'NF' => 'NFK', 'NG' => 'NGA', 'NZ' => 'NZL', 'NP' => 'NPL', 'NR' => 'NRU', 'NU' => 'NIU', 'CK' => 'COK', 'XK' => 'XKX', 'CI' => 'CIV', 'CH' => 'CHE', 'CO' => 'COL', 'CN' => 'CHN', 'CM' => 'CMR', 'CL' => 'CHL', 'CC' => 'CCK', 'CA' => 'CAN', 'CG' => 'COG', 'CF' => 'CAF', 'CD' => 'COD', 'CZ' => 'CZE', 'CY' => 'CYP', 'CX' => 'CXR', 'CR' => 'CRI', 'CW' => 'CUW', 'CV' => 'CPV', 'CU' => 'CUB', 'SZ' => 'SWZ', 'SY' => 'SYR', 'SX' => 'SXM', 'KG' => 'KGZ', 'KE' => 'KEN', 'SS' => 'SSD', 'SR' => 'SUR', 'KI' => 'KIR', 'KH' => 'KHM', 'KN' => 'KNA', 'KM' => 'COM', 'ST' => 'STP', 'SK' => 'SVK', 'KR' => 'KOR', 'SI' => 'SVN', 'KP' => 'PRK', 'KW' => 'KWT', 'SN' => 'SEN', 'SM' => 'SMR', 'SL' => 'SLE', 'SC' => 'SYC', 'KZ' => 'KAZ', 'KY' => 'CYM', 'SG' => 'SGP', 'SE' => 'SWE', 'SD' => 'SDN', 'DO' => 'DOM', 'DM' => 'DMA', 'DJ' => 'DJI', 'DK' => 'DNK', 'VG' => 'VGB', 'DE' => 'DEU', 'YE' => 'YEM', 'DZ' => 'DZA', 'US' => 'USA', 'UY' => 'URY', 'YT' => 'MYT', 'UM' => 'UMI', 'LB' => 'LBN', 'LC' => 'LCA', 'LA' => 'LAO', 'TV' => 'TUV', 'TW' => 'TWN', 'TT' => 'TTO', 'TR' => 'TUR', 'LK' => 'LKA', 'LI' => 'LIE', 'LV' => 'LVA', 'TO' => 'TON', 'LT' => 'LTU', 'LU' => 'LUX', 'LR' => 'LBR', 'LS' => 'LSO', 'TH' => 'THA', 'TF' => 'ATF', 'TG' => 'TGO', 'TD' => 'TCD', 'TC' => 'TCA', 'LY' => 'LBY', 'VA' => 'VAT', 'VC' => 'VCT', 'AE' => 'ARE', 'AD' => 'AND', 'AG' => 'ATG', 'AF' => 'AFG', 'AI' => 'AIA', 'VI' => 'VIR', 'IS' => 'ISL', 'IR' => 'IRN', 'AM' => 'ARM', 'AL' => 'ALB', 'AO' => 'AGO', 'AQ' => 'ATA', 'AS' => 'ASM', 'AR' => 'ARG', 'AU' => 'AUS', 'AT' => 'AUT', 'AW' => 'ABW', 'IN' => 'IND', 'AX' => 'ALA', 'AZ' => 'AZE', 'IE' => 'IRL', 'ID' => 'IDN', 'UA' => 'UKR', 'QA' => 'QAT', 'MZ' => 'MOZ'); - return $array[$country]; - } +if ( !function_exists('gnfe_country_code') ) { + function gnfe_country_code($country) { + $array = ['BD' => 'BGD', 'BE' => 'BEL', 'BF' => 'BFA', 'BG' => 'BGR', 'BA' => 'BIH', 'BB' => 'BRB', 'WF' => 'WLF', 'BL' => 'BLM', 'BM' => 'BMU', 'BN' => 'BRN', 'BO' => 'BOL', 'BH' => 'BHR', 'BI' => 'BDI', 'BJ' => 'BEN', 'BT' => 'BTN', 'JM' => 'JAM', 'BV' => 'BVT', 'BW' => 'BWA', 'WS' => 'WSM', 'BQ' => 'BES', 'BR' => 'BRA', 'BS' => 'BHS', 'JE' => 'JEY', 'BY' => 'BLR', 'BZ' => 'BLZ', 'RU' => 'RUS', 'RW' => 'RWA', 'RS' => 'SRB', 'TL' => 'TLS', 'RE' => 'REU', 'TM' => 'TKM', 'TJ' => 'TJK', 'RO' => 'ROU', 'TK' => 'TKL', 'GW' => 'GNB', 'GU' => 'GUM', 'GT' => 'GTM', 'GS' => 'SGS', 'GR' => 'GRC', 'GQ' => 'GNQ', 'GP' => 'GLP', 'JP' => 'JPN', 'GY' => 'GUY', 'GG' => 'GGY', 'GF' => 'GUF', 'GE' => 'GEO', 'GD' => 'GRD', 'GB' => 'GBR', 'GA' => 'GAB', 'SV' => 'SLV', 'GN' => 'GIN', 'GM' => 'GMB', 'GL' => 'GRL', 'GI' => 'GIB', 'GH' => 'GHA', 'OM' => 'OMN', 'TN' => 'TUN', 'JO' => 'JOR', 'HR' => 'HRV', 'HT' => 'HTI', 'HU' => 'HUN', 'HK' => 'HKG', 'HN' => 'HND', 'HM' => 'HMD', 'VE' => 'VEN', 'PR' => 'PRI', 'PS' => 'PSE', 'PW' => 'PLW', 'PT' => 'PRT', 'SJ' => 'SJM', 'PY' => 'PRY', 'IQ' => 'IRQ', 'PA' => 'PAN', 'PF' => 'PYF', 'PG' => 'PNG', 'PE' => 'PER', 'PK' => 'PAK', 'PH' => 'PHL', 'PN' => 'PCN', 'PL' => 'POL', 'PM' => 'SPM', 'ZM' => 'ZMB', 'EH' => 'ESH', 'EE' => 'EST', 'EG' => 'EGY', 'ZA' => 'ZAF', 'EC' => 'ECU', 'IT' => 'ITA', 'VN' => 'VNM', 'SB' => 'SLB', 'ET' => 'ETH', 'SO' => 'SOM', 'ZW' => 'ZWE', 'SA' => 'SAU', 'ES' => 'ESP', 'ER' => 'ERI', 'ME' => 'MNE', 'MD' => 'MDA', 'MG' => 'MDG', 'MF' => 'MAF', 'MA' => 'MAR', 'MC' => 'MCO', 'UZ' => 'UZB', 'MM' => 'MMR', 'ML' => 'MLI', 'MO' => 'MAC', 'MN' => 'MNG', 'MH' => 'MHL', 'MK' => 'MKD', 'MU' => 'MUS', 'MT' => 'MLT', 'MW' => 'MWI', 'MV' => 'MDV', 'MQ' => 'MTQ', 'MP' => 'MNP', 'MS' => 'MSR', 'MR' => 'MRT', 'IM' => 'IMN', 'UG' => 'UGA', 'TZ' => 'TZA', 'MY' => 'MYS', 'MX' => 'MEX', 'IL' => 'ISR', 'FR' => 'FRA', 'IO' => 'IOT', 'SH' => 'SHN', 'FI' => 'FIN', 'FJ' => 'FJI', 'FK' => 'FLK', 'FM' => 'FSM', 'FO' => 'FRO', 'NI' => 'NIC', 'NL' => 'NLD', 'NO' => 'NOR', 'NA' => 'NAM', 'VU' => 'VUT', 'NC' => 'NCL', 'NE' => 'NER', 'NF' => 'NFK', 'NG' => 'NGA', 'NZ' => 'NZL', 'NP' => 'NPL', 'NR' => 'NRU', 'NU' => 'NIU', 'CK' => 'COK', 'XK' => 'XKX', 'CI' => 'CIV', 'CH' => 'CHE', 'CO' => 'COL', 'CN' => 'CHN', 'CM' => 'CMR', 'CL' => 'CHL', 'CC' => 'CCK', 'CA' => 'CAN', 'CG' => 'COG', 'CF' => 'CAF', 'CD' => 'COD', 'CZ' => 'CZE', 'CY' => 'CYP', 'CX' => 'CXR', 'CR' => 'CRI', 'CW' => 'CUW', 'CV' => 'CPV', 'CU' => 'CUB', 'SZ' => 'SWZ', 'SY' => 'SYR', 'SX' => 'SXM', 'KG' => 'KGZ', 'KE' => 'KEN', 'SS' => 'SSD', 'SR' => 'SUR', 'KI' => 'KIR', 'KH' => 'KHM', 'KN' => 'KNA', 'KM' => 'COM', 'ST' => 'STP', 'SK' => 'SVK', 'KR' => 'KOR', 'SI' => 'SVN', 'KP' => 'PRK', 'KW' => 'KWT', 'SN' => 'SEN', 'SM' => 'SMR', 'SL' => 'SLE', 'SC' => 'SYC', 'KZ' => 'KAZ', 'KY' => 'CYM', 'SG' => 'SGP', 'SE' => 'SWE', 'SD' => 'SDN', 'DO' => 'DOM', 'DM' => 'DMA', 'DJ' => 'DJI', 'DK' => 'DNK', 'VG' => 'VGB', 'DE' => 'DEU', 'YE' => 'YEM', 'DZ' => 'DZA', 'US' => 'USA', 'UY' => 'URY', 'YT' => 'MYT', 'UM' => 'UMI', 'LB' => 'LBN', 'LC' => 'LCA', 'LA' => 'LAO', 'TV' => 'TUV', 'TW' => 'TWN', 'TT' => 'TTO', 'TR' => 'TUR', 'LK' => 'LKA', 'LI' => 'LIE', 'LV' => 'LVA', 'TO' => 'TON', 'LT' => 'LTU', 'LU' => 'LUX', 'LR' => 'LBR', 'LS' => 'LSO', 'TH' => 'THA', 'TF' => 'ATF', 'TG' => 'TGO', 'TD' => 'TCD', 'TC' => 'TCA', 'LY' => 'LBY', 'VA' => 'VAT', 'VC' => 'VCT', 'AE' => 'ARE', 'AD' => 'AND', 'AG' => 'ATG', 'AF' => 'AFG', 'AI' => 'AIA', 'VI' => 'VIR', 'IS' => 'ISL', 'IR' => 'IRN', 'AM' => 'ARM', 'AL' => 'ALB', 'AO' => 'AGO', 'AQ' => 'ATA', 'AS' => 'ASM', 'AR' => 'ARG', 'AU' => 'AUS', 'AT' => 'AUT', 'AW' => 'ABW', 'IN' => 'IND', 'AX' => 'ALA', 'AZ' => 'AZE', 'IE' => 'IRL', 'ID' => 'IDN', 'UA' => 'UKR', 'QA' => 'QAT', 'MZ' => 'MOZ']; + return $array[$country]; + } } -if( !function_exists('gnfe_ibge') ) { - function gnfe_ibge($zip) { - $curl = curl_init(); - curl_setopt ($curl, CURLOPT_URL, 'https://open.nfe.io/v1/cities/'.$zip.'/postalcode'); - curl_setopt ($curl, CURLOPT_TIMEOUT, 30); - curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); - $response = curl_exec ($curl); - curl_close ($curl); - $city = json_decode(json_encode(json_decode($response))); - return $city->city->code; - } +if ( !function_exists('gnfe_ibge') ) { + function gnfe_ibge($zip) { + $curl = curl_init(); + curl_setopt ($curl, CURLOPT_URL, 'https://open.nfe.io/v1/cities/' . $zip . '/postalcode'); + curl_setopt ($curl, CURLOPT_TIMEOUT, 30); + curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); + $response = curl_exec ($curl); + curl_close ($curl); + $city = json_decode(json_encode(json_decode($response))); + return $city->city->code; + } } -if( !function_exists('gnfe_queue_nfe') ) { - function gnfe_queue_nfe($invoice_id){ - $invoice = localAPI('GetInvoice', array('invoiceid' => $invoice_id), false); - $data = array( - 'invoice_id'=>$invoice_id, - 'user_id'=>$invoice['userid'], - 'nfe_id'=>'waiting', - 'status'=>'Waiting', - 'services_amount'=>$invoice['total'], - 'environment'=>'waiting', - 'flow_status'=>'waiting', - 'pdf'=>'waiting', - 'created_at'=>date("Y-m-d H:i:s"), - 'updated_at'=>'waiting', - 'rpsSerialNumber'=>'waiting', - ); - $nfe_for_invoice = gnfe_get_local_nfe($invoice_id, array('status')); - if(!$nfe_for_invoice['status']) { - try { - $save_nfe = Capsule::table('gofasnfeio')->insert($data); - return 'success'; - } - catch (\Exception $e) { - return $e->getMessage(); - } - } - elseif((string)$nfe_for_invoice['status'] === (string)'Cancelled' or (string)$nfe_for_invoice['status'] === (string)'Error') { - - try { - $update_nfe = Capsule::table('gofasnfeio')->where('invoice_id', '=', $invoice_id)->update($data); - return 'success'; - } - catch (\Exception $e) { - return $e->getMessage(); - } - } - } +if ( !function_exists('gnfe_queue_nfe') ) { + function gnfe_queue_nfe($invoice_id,$addManually = 'false') { + if (!setAddedManually()) { + return ''; + } + + $invoice = localAPI('GetInvoice', ['invoiceid' => $invoice_id], false); + $data = [ + 'invoice_id' => $invoice_id, + 'user_id' => $invoice['userid'], + 'nfe_id' => 'waiting', + 'status' => 'Waiting', + 'services_amount' => $invoice['total'], + 'environment' => 'waiting', + 'flow_status' => 'waiting', + 'pdf' => 'waiting', + 'created_at' => date('Y-m-d H:i:s'), + 'updated_at' => 'waiting', + 'rpsSerialNumber' => 'waiting', + 'created_manually' => (boolval($addManually) ? 'true' : 'false') + ]; + logModuleCall('gofas_nfeio', 'gnfe_queue_nfe', $data,'','',''); + $nfe_for_invoice = gnfe_get_local_nfe($invoice_id, ['status']); + if (!$nfe_for_invoice['status']) { + try { + $save_nfe = Capsule::table('gofasnfeio')->insert($data); + return 'success'; + } catch (\Exception $e) { + return $e->getMessage(); + } + } elseif ((string)$nfe_for_invoice['status'] === (string)'Cancelled' or (string)$nfe_for_invoice['status'] === (string)'Error') { + try { + $update_nfe = Capsule::table('gofasnfeio')->where('invoice_id', '=', $invoice_id)->update($data); + return 'success'; + } catch (\Exception $e) { + return $e->getMessage(); + } + } + } } -if( !function_exists('gnfe_issue_nfe') ) { - function gnfe_issue_nfe($postfields){ - $webhook_url = gnfe_whmcs_url().'modules/addons/gofasnfeio/callback.php'; - foreach( Capsule::table('tblconfiguration') -> where('setting', '=', 'gnfe_webhook_id') -> get( array( 'value' ) ) as $gnfe_webhook_id_ ) { - $gnfe_webhook_id = $gnfe_webhook_id_->value; - } - if($gnfe_webhook_id){ - $check_webhook = gnfe_check_webhook($gnfe_webhook_id); - if($check_webhook['message']) { - $error .= $check_webhook['message']; - } - } - 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']; - } - if($create_webhook['hooks']['id']) { - try { - Capsule::table('tblconfiguration')->where( 'setting', 'gnfe_webhook_id')->update(array('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(); - } - } - $delete_webhook = gnfe_delete_webhook($gnfe_webhook_id); - if($delete_webhook['message']) { - $error .= $create_webhook['message']; - } - } - if(!$gnfe_webhook_id){ - $create_webhook = gnfe_create_webhook($webhook_url); - if($create_webhook['message']) { - $error .= $create_webhook['message']; - } - if($create_webhook['hooks']['id']) { - try { - Capsule::table('tblconfiguration')->insert(array('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(); - } - } - } - if(gnfe_config('debug')) { - logModuleCall('gofas_nfeio', 'check_webhook', array('gnfe_webhook_id'=> $gnfe_webhook_id, 'check_webhook'=>$check_webhook,'check_webhook_url'=>$check_webhook['hooks']['url']), 'post', array('create_webhook'=>$create_webhook, 'delete_webhook'=>$delete_webhook, 'error'=>$error), 'replaceVars'); - } +if ( !function_exists('gnfe_issue_nfe') ) { + function gnfe_issue_nfe($postfields) { + $webhook_url = gnfe_whmcs_url() . 'modules/addons/gofasnfeio/callback.php'; + foreach ( Capsule::table('tblconfiguration')->where('setting', '=', 'gnfe_webhook_id')->get( ['value'] ) as $gnfe_webhook_id_ ) { + $gnfe_webhook_id = $gnfe_webhook_id_->value; + } + if ($gnfe_webhook_id) { + $check_webhook = gnfe_check_webhook($gnfe_webhook_id); + if ($check_webhook['message']) { + $error .= $check_webhook['message']; + } + } + 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']; + } + 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(); + } + } + $delete_webhook = gnfe_delete_webhook($gnfe_webhook_id); + if ($delete_webhook['message']) { + $error .= $create_webhook['message']; + } + } + if (!$gnfe_webhook_id) { + $create_webhook = gnfe_create_webhook($webhook_url); + if ($create_webhook['message']) { + $error .= $create_webhook['message']; + } + 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(); + } + } + } + if (gnfe_config('debug')) { + logModuleCall('gofas_nfeio', 'check_webhook', ['gnfe_webhook_id' => $gnfe_webhook_id, 'check_webhook' => $check_webhook, 'check_webhook_url' => $check_webhook['hooks']['url']], 'post', ['create_webhook' => $create_webhook, 'delete_webhook' => $delete_webhook, 'error' => $error], 'replaceVars'); + } $curl = curl_init(); - curl_setopt($curl, CURLOPT_URL, 'https://api.nfe.io/v1/companies/'.gnfe_config('company_id').'/serviceinvoices'); - curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: text/json', 'Accept: application/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($postfields)); - curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); - $response = curl_exec ($curl); - curl_close ($curl); - return json_decode(json_encode(json_decode($response))); - } + 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); + curl_setopt($curl, CURLOPT_POST, 1); + curl_setopt($curl, CURLOPT_POSTFIELDS,json_encode($postfields)); + curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); + $response = curl_exec ($curl); + curl_close ($curl); + return json_decode(json_encode(json_decode($response))); + } } -if( !function_exists('gnfe_get_nfe') ) { - function gnfe_get_nfe($nf){ - $curl = curl_init(); - curl_setopt($curl, CURLOPT_URL, "https://api.nfe.io/v1/companies/".gnfe_config('company_id')."/serviceinvoices/".$nf); - curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: text/json', 'Accept: application/json', 'Authorization: '.gnfe_config('api_key'))); - curl_setopt($curl, CURLOPT_TIMEOUT, 30); - curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); - $response = curl_exec ($curl); - curl_close ($curl); - return json_decode($response); - } +if ( !function_exists('gnfe_get_nfe') ) { + function gnfe_get_nfe($nf) { + $curl = curl_init(); + curl_setopt($curl, CURLOPT_URL, 'https://api.nfe.io/v1/companies/' . gnfe_config('company_id') . '/serviceinvoices/' . $nf); + curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: text/json', 'Accept: application/json', 'Authorization: ' . gnfe_config('api_key')]); + curl_setopt($curl, CURLOPT_TIMEOUT, 30); + curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); + $response = curl_exec ($curl); + curl_close ($curl); + return json_decode($response); + } } -if( !function_exists('gnfe_get_nfes') ) { - function gnfe_get_nfes(){ - $curl = curl_init(); - curl_setopt($curl, CURLOPT_URL, "https://api.nfe.io/v1/companies/".gnfe_config('company_id')."/serviceinvoices?pageCount=1&pageIndex=1"); - curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: text/json', 'Accept: application/json', 'Authorization: '.gnfe_config('api_key'))); - curl_setopt($curl, CURLOPT_TIMEOUT, 30); - curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); - $response = curl_exec ($curl); - curl_close ($curl); - return json_decode($response, true); - } +if ( !function_exists('gnfe_get_nfes') ) { + function gnfe_get_nfes() { + $curl = curl_init(); + curl_setopt($curl, CURLOPT_URL, 'https://api.nfe.io/v1/companies/' . gnfe_config('company_id') . '/serviceinvoices?pageCount=1&pageIndex=1'); + curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: text/json', 'Accept: application/json', 'Authorization: ' . gnfe_config('api_key')]); + curl_setopt($curl, CURLOPT_TIMEOUT, 30); + curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); + $response = curl_exec ($curl); + curl_close ($curl); + return json_decode($response, true); + } } -if( !function_exists('gnfe_get_invoice_nfes') ) { +if ( !function_exists('gnfe_get_invoice_nfes') ) { function gnfe_get_invoice_nfes($invoice_id) { - $nfes = array(); + $nfes = []; // foreach( Capsule::table('tbladdonmodules') -> where( 'module', '=', 'gofasnfeio' ) -> get( array( 'setting', 'value') ) as $settings ) { - foreach( Capsule::table('gofasnfeio')->where('invoice_id', '=', $invoice_id)->get(array('invoice_id','user_id','nfe_id','status','services_amount','environment','flow_status','pdf','created_at','updated_at','rpsSerialNumber','rpsNumber') ) as $nfe ) { + foreach ( Capsule::table('gofasnfeio')->where('invoice_id', '=', $invoice_id)->get(['invoice_id', 'user_id', 'nfe_id', 'status', 'services_amount', 'environment', 'flow_status', 'pdf', 'created_at', 'updated_at', 'rpsSerialNumber', 'rpsNumber'] ) as $nfe ) { $nfes = $nfe; } $checkfields = json_decode(json_encode($nfes), true); if (!$checkfields) { - $fieldArray = array('status' => 'error', 'message' => 'database error'); - }elseif (count($checkfields) >= 1) { - $fieldArray = array('status' => 'success', 'result' => $checkfields);; + $fieldArray = ['status' => 'error', 'message' => 'database error']; + } elseif (count($checkfields) >= 1) { + $fieldArray = ['status' => 'success', 'result' => $checkfields]; + ; } else { - $fieldArray = array('status' => 'error', 'message' => 'nothing to show'); + $fieldArray = ['status' => 'error', 'message' => 'nothing to show']; } return $fieldArray; } } -if( !function_exists('gnfe_delete_nfe') ) { - function gnfe_delete_nfe($nf){ - $curl = curl_init(); - curl_setopt($curl, CURLOPT_URL, "https://api.nfe.io/v1/companies/".gnfe_config('company_id')."/serviceinvoices/".$nf); - curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: text/json', 'Accept: application/json', 'Authorization: '.gnfe_config('api_key'))); - curl_setopt($curl, CURLOPT_TIMEOUT, 30); - curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); - curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE'); - $response = curl_exec ($curl); - curl_close ($curl); - return json_decode($response); - } +if ( !function_exists('gnfe_delete_nfe') ) { + function gnfe_delete_nfe($nf) { + $curl = curl_init(); + curl_setopt($curl, CURLOPT_URL, 'https://api.nfe.io/v1/companies/' . gnfe_config('company_id') . '/serviceinvoices/' . $nf); + curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: text/json', 'Accept: application/json', 'Authorization: ' . gnfe_config('api_key')]); + curl_setopt($curl, CURLOPT_TIMEOUT, 30); + curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); + curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE'); + $response = curl_exec ($curl); + curl_close ($curl); + return json_decode($response); + } } -if( !function_exists('gnfe_email_nfe') ) { - function gnfe_email_nfe($nf){ - if(gnfe_config('gnfe_email_nfe_config') == "on"){ - $curl = curl_init(); - curl_setopt($curl, CURLOPT_URL, 'https://api.nfe.io/v1/companies/'.gnfe_config('company_id').'/serviceinvoices/'.$nf.'/sendemail'); - curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: text/json', 'Accept: application/json', 'Authorization: '.gnfe_config('api_key'))); - curl_setopt($curl, CURLOPT_TIMEOUT, 30); - curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); - curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT'); - $response = curl_exec ($curl); - curl_close ($curl); - return json_decode($response); - } - } +if ( !function_exists('gnfe_email_nfe') ) { + function gnfe_email_nfe($nf) { + if (gnfe_config('gnfe_email_nfe_config') == 'on') { + $curl = curl_init(); + curl_setopt($curl, CURLOPT_URL, 'https://api.nfe.io/v1/companies/' . gnfe_config('company_id') . '/serviceinvoices/' . $nf . '/sendemail'); + curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: text/json', 'Accept: application/json', 'Authorization: ' . gnfe_config('api_key')]); + curl_setopt($curl, CURLOPT_TIMEOUT, 30); + curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); + curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT'); + $response = curl_exec ($curl); + curl_close ($curl); + return json_decode($response); + } + } } -if( !function_exists('gnfe_pdf_nfe') ) { - function gnfe_pdf_nfe($nf){ - $curl = curl_init(); - curl_setopt($curl, CURLOPT_URL, 'https://api.nfe.io/v1/companies/'.gnfe_config('company_id').'/serviceinvoices/'.$nf.'/pdf'); - curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-type: application/pdf', 'Authorization: '.gnfe_config('api_key'))); - curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); - curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET'); +if ( !function_exists('gnfe_pdf_nfe') ) { + function gnfe_pdf_nfe($nf) { + $curl = curl_init(); + curl_setopt($curl, CURLOPT_URL, 'https://api.nfe.io/v1/companies/' . gnfe_config('company_id') . '/serviceinvoices/' . $nf . '/pdf'); + curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-type: application/pdf', 'Authorization: ' . gnfe_config('api_key')]); + curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); + curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET'); curl_setopt($curl, CURLOPT_RETURNTRANSFER,true); curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($curl, CURLOPT_TIMEOUT, 10); @@ -365,150 +363,150 @@ function gnfe_pdf_nfe($nf){ header('Content-type: application/pdf'); $result = curl_exec($curl); curl_close($curl); - return $result; - } + return $result; + } +} +if ( !function_exists('gnfe_xml_nfe') ) { + function gnfe_xml_nfe($nf) { + $curl = curl_init(); + curl_setopt($curl, CURLOPT_URL, 'https://api.nfe.io/v1/companies/' . gnfe_config('company_id') . '/serviceinvoices/' . $nf . '/xml'); + curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: text/json', 'Accept: application/json', 'Authorization: ' . gnfe_config('api_key')]); + curl_setopt($curl, CURLOPT_TIMEOUT, 30); + curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); + $response = curl_exec ($curl); + curl_close ($curl); + return json_decode($response); + } } -if( !function_exists('gnfe_xml_nfe') ) { - function gnfe_xml_nfe($nf){ - $curl = curl_init(); - curl_setopt($curl, CURLOPT_URL, 'https://api.nfe.io/v1/companies/'.gnfe_config('company_id').'/serviceinvoices/'.$nf.'/xml'); - curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: text/json', 'Accept: application/json', 'Authorization: '.gnfe_config('api_key'))); - curl_setopt($curl, CURLOPT_TIMEOUT, 30); - curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); - $response = curl_exec ($curl); - curl_close ($curl); - return json_decode($response); - } +if ( !function_exists('gnfe_whmcs_url') ) { + function gnfe_whmcs_url() { + foreach ( Capsule::table('tblconfiguration')->where('setting', '=', 'gnfewhmcsurl')->get( ['value'] ) as $gnfewhmcsurl_ ) { + $gnfewhmcsurl = $gnfewhmcsurl_->value; + } + return $gnfewhmcsurl; + } } -if( !function_exists('gnfe_whmcs_url') ) { - function gnfe_whmcs_url(){ - foreach( Capsule::table('tblconfiguration') -> where('setting', '=', 'gnfewhmcsurl') -> get( array('value') ) as $gnfewhmcsurl_ ) { - $gnfewhmcsurl = $gnfewhmcsurl_->value; - } - return $gnfewhmcsurl; - } +if ( !function_exists('gnfe_whmcs_admin_url') ) { + function gnfe_whmcs_admin_url() { + foreach ( Capsule::table('tblconfiguration')->where('setting', '=', 'gnfewhmcsadminurl')->get( ['value'] ) as $gnfewhmcsadminurl_ ) { + $gnfewhmcsadminurl = $gnfewhmcsadminurl_->value; + } + return $gnfewhmcsadminurl; + } +} +if ( !function_exists('gnfe_save_nfe') ) { + function gnfe_save_nfe($nfe,$user_id,$invoice_id,$pdf,$created_at,$updated_at) { + $data = [ + 'invoice_id' => $invoice_id, + 'user_id' => $user_id, + 'nfe_id' => $nfe->id, + 'status' => $nfe->status, + 'services_amount' => $nfe->servicesAmount, + 'environment' => $nfe->environment, + 'flow_status' => $nfe->flowStatus, + 'pdf' => $pdf, + 'created_at' => $created_at, + 'updated_at' => $updated_at, + 'rpsSerialNumber' => $nfe->rpsSerialNumber, + 'rpsNumber' => $nfe->rpsNumber, + ]; + try { + $save_nfe = Capsule::table('gofasnfeio')->insert($data); + return 'success'; + } catch (\Exception $e) { + return $e->getMessage(); + } + } +} +if ( !function_exists('gnfe_update_nfe') ) { + function gnfe_update_nfe($nfe,$user_id,$invoice_id,$pdf,$created_at,$updated_at) { + $data = [ + 'invoice_id' => $invoice_id, + 'user_id' => $user_id, + 'nfe_id' => $nfe->id, + 'status' => $nfe->status, + 'services_amount' => $nfe->servicesAmount, + 'environment' => $nfe->environment, + 'flow_status' => $nfe->flowStatus, + 'pdf' => $pdf, + 'created_at' => $created_at, + 'updated_at' => $updated_at, + 'rpsSerialNumber' => $nfe->rpsSerialNumber, + 'rpsNumber' => $nfe->rpsNumber, + ]; + try { + $save_nfe = Capsule::table('gofasnfeio')->where('invoice_id', '=', $invoice_id)->update($data); + return 'success'; + } catch (\Exception $e) { + return $e->getMessage(); + } + } } -if( !function_exists('gnfe_whmcs_admin_url') ) { - function gnfe_whmcs_admin_url(){ - foreach( Capsule::table('tblconfiguration') -> where('setting', '=', 'gnfewhmcsadminurl') -> get( array('value') ) as $gnfewhmcsadminurl_ ) { - $gnfewhmcsadminurl = $gnfewhmcsadminurl_->value; - } - return $gnfewhmcsadminurl; - } +if ( !function_exists('gnfe_update_rps') ) { + function gnfe_update_rps($rps_serial_number, $rps_number) { + $setting = []; + foreach ( Capsule::table('tbladdonmodules')->where( 'module', '=', 'gofasnfeio' )->get( ['setting', 'value'] ) as $settings ) { + $setting[$settings->setting] = $settings->value; + } + try { + if ($rps_serial_number) { + $update_rps_serial_number = Capsule::table('tbladdonmodules')->where( 'module', '=', 'gofasnfeio' )->where( 'setting', '=', 'rps_serial_number' )->update(['value' => $rps_serial_number]); + } + if ($rps_number) { + $update_serial_number = Capsule::table('tbladdonmodules')->where( 'module', '=', 'gofasnfeio' )->where( 'setting', '=', 'rps_number' )->update(['value' => $rps_number + 1]); + } + return 'success'; + } catch (\Exception $e) { + return $e->getMessage(); + } + } } -if( !function_exists('gnfe_save_nfe') ) { - function gnfe_save_nfe($nfe,$user_id,$invoice_id,$pdf,$created_at,$updated_at) { - $data = array( - 'invoice_id'=>$invoice_id, - 'user_id'=>$user_id, - 'nfe_id'=>$nfe->id, - 'status'=>$nfe->status, - 'services_amount'=>$nfe->servicesAmount, - 'environment'=>$nfe->environment, - 'flow_status'=>$nfe->flowStatus, - 'pdf'=>$pdf, - 'created_at'=>$created_at, - 'updated_at'=>$updated_at, - 'rpsSerialNumber'=>$nfe->rpsSerialNumber, - 'rpsNumber'=>$nfe->rpsNumber, - ); - try { - $save_nfe = Capsule::table('gofasnfeio')->insert($data); - return 'success'; - } - catch (\Exception $e) { - return $e->getMessage(); - } -}} -if( !function_exists('gnfe_update_nfe') ) { - function gnfe_update_nfe($nfe,$user_id,$invoice_id,$pdf,$created_at,$updated_at) { - $data = array( - 'invoice_id'=>$invoice_id, - 'user_id'=>$user_id, - 'nfe_id'=>$nfe->id, - 'status'=>$nfe->status, - 'services_amount'=>$nfe->servicesAmount, - 'environment'=>$nfe->environment, - 'flow_status'=>$nfe->flowStatus, - 'pdf'=>$pdf, - 'created_at'=>$created_at, - 'updated_at'=>$updated_at, - 'rpsSerialNumber'=>$nfe->rpsSerialNumber, - 'rpsNumber'=>$nfe->rpsNumber, - ); - try { - $save_nfe = Capsule::table('gofasnfeio')->where('invoice_id', '=', $invoice_id)->update($data); - return 'success'; - } - catch (\Exception $e) { - return $e->getMessage(); - } -}} -if( !function_exists('gnfe_update_rps') ) { - function gnfe_update_rps($rps_serial_number, $rps_number) { - $setting = array(); - foreach( Capsule::table('tbladdonmodules') -> where( 'module', '=', 'gofasnfeio' ) -> get( array( 'setting', 'value') ) as $settings ) { - $setting[$settings->setting] = $settings->value; - } - try { - if($rps_serial_number){ - $update_rps_serial_number = Capsule::table('tbladdonmodules')-> where( 'module', '=', 'gofasnfeio' )->where( 'setting', '=', 'rps_serial_number' )->update(array('value'=>$rps_serial_number)); - } - if($rps_number){ - $update_serial_number = Capsule::table('tbladdonmodules')-> where( 'module', '=', 'gofasnfeio' )->where( 'setting', '=', 'rps_number' )->update(array('value'=>$rps_number+1)); - } - return 'success'; - } - catch (\Exception $e) { - return $e->getMessage(); - } -}} -if( !function_exists('gnfe_get_local_nfe') ) { - function gnfe_get_local_nfe($invoice_id, $values ) { - foreach( Capsule::table('gofasnfeio')->where('invoice_id', '=', $invoice_id)->get($values) as $key => $value ) { - $nfe_for_invoice[$key] = json_decode(json_encode($value), true); - } - return $nfe_for_invoice['0']; - } +if ( !function_exists('gnfe_get_local_nfe') ) { + function gnfe_get_local_nfe($invoice_id, $values ) { + foreach ( Capsule::table('gofasnfeio')->where('invoice_id', '=', $invoice_id)->get($values) as $key => $value ) { + $nfe_for_invoice[$key] = json_decode(json_encode($value), true); + } + return $nfe_for_invoice['0']; + } } -if( !function_exists('gnfe_check_webhook') ) { - function gnfe_check_webhook($id) { - $curl = curl_init(); - curl_setopt($curl, CURLOPT_URL, "https://api.nfe.io/v1/hooks/".$id); - curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: text/json', 'Accept: application/json', 'Authorization: '.gnfe_config('api_key'))); - curl_setopt($curl, CURLOPT_TIMEOUT, 30); - curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); - $response = curl_exec ($curl); - curl_close ($curl); - return json_decode(json_encode(json_decode($response)), true); - } +if ( !function_exists('gnfe_check_webhook') ) { + function gnfe_check_webhook($id) { + $curl = curl_init(); + curl_setopt($curl, CURLOPT_URL, 'https://api.nfe.io/v1/hooks/' . $id); + curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: text/json', 'Accept: application/json', 'Authorization: ' . gnfe_config('api_key')]); + curl_setopt($curl, CURLOPT_TIMEOUT, 30); + curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); + $response = curl_exec ($curl); + curl_close ($curl); + return json_decode(json_encode(json_decode($response)), true); + } } -if( !function_exists('gnfe_create_webhook') ) { - function gnfe_create_webhook($url) { - $curl = curl_init(); - curl_setopt($curl, CURLOPT_URL, "https://api.nfe.io/v1/hooks"); - curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: text/json', 'Accept: application/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(array('url'=> $url, 'contentType'=> 'application/json', 'secret'=> (string)time(), 'events'=>array('issue', 'cancel'), 'status'=>'Active', ))); - curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); - $response = curl_exec ($curl); - curl_close ($curl); - return json_decode(json_encode(json_decode($response)), true); - } +if ( !function_exists('gnfe_create_webhook') ) { + function gnfe_create_webhook($url) { + $curl = curl_init(); + curl_setopt($curl, CURLOPT_URL, 'https://api.nfe.io/v1/hooks'); + curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: text/json', 'Accept: application/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_RETURNTRANSFER,1); + $response = curl_exec ($curl); + curl_close ($curl); + return json_decode(json_encode(json_decode($response)), true); + } } -if( !function_exists('gnfe_delete_webhook') ) { - function gnfe_delete_webhook($id) { - $curl = curl_init(); - curl_setopt($curl, CURLOPT_URL, "https://api.nfe.io/v1/hooks/".$id); - curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: text/json', 'Accept: application/json', 'Authorization: '.gnfe_config('api_key'))); - curl_setopt($curl, CURLOPT_TIMEOUT, 30); - curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE'); - curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); - $response = curl_exec ($curl); - curl_close ($curl); - return json_decode(json_encode(json_decode($response)), true); - } +if ( !function_exists('gnfe_delete_webhook') ) { + function gnfe_delete_webhook($id) { + $curl = curl_init(); + curl_setopt($curl, CURLOPT_URL, 'https://api.nfe.io/v1/hooks/' . $id); + curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: text/json', 'Accept: application/json', 'Authorization: ' . gnfe_config('api_key')]); + curl_setopt($curl, CURLOPT_TIMEOUT, 30); + curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE'); + curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); + $response = curl_exec ($curl); + curl_close ($curl); + return json_decode(json_encode(json_decode($response)), true); + } } /** * @gnfe_nfe_flowStatus string @@ -517,55 +515,110 @@ function gnfe_delete_webhook($id) { * WaitingDefineRpsNumber, WaitingSend, WaitingSendCancel, WaitingReturn, WaitingDownload * */ -if( !function_exists('gnfe_nfe_flowStatus') ) { - function gnfe_nfe_flowStatus($flowStatus) { - if($flowStatus === 'CancelFailed'){ - $status = 'Cancelado por Erro'; - } - if($flowStatus === 'IssueFailed'){ - $status = 'Falha ao Emitir'; - } - if($flowStatus === 'Issued'){ - $status = 'Emitida'; - } - if($flowStatus === 'Cancelled'){ - $status = 'Cancelada'; - } - if($flowStatus === 'PullFromCityHall'){ - $status = 'Obtendo da Prefeitura'; - } - if($flowStatus === 'WaitingCalculateTaxes'){ - $status = 'Aguardando Calcular Impostos'; - } - if($flowStatus === 'WaitingDefineRpsNumber'){ - $status = 'Aguardando Definir Número Rps'; - } - if($flowStatus === 'WaitingSend'){ - $status = 'Aguardando Enviar'; - } - if($flowStatus === 'WaitingSendCancel'){ - $status = 'Aguardando Cancelar Envio'; - } - if($flowStatus === 'WaitingReturn'){ - $status = 'Aguardando Retorno'; - } - if($flowStatus === 'WaitingDownload'){ - $status = 'Aguardando Download'; - } - - return $status; - } +if ( !function_exists('gnfe_nfe_flowStatus') ) { + function gnfe_nfe_flowStatus($flowStatus) { + if ($flowStatus === 'CancelFailed') { + $status = 'Cancelado por Erro'; + } + if ($flowStatus === 'IssueFailed') { + $status = 'Falha ao Emitir'; + } + if ($flowStatus === 'Issued') { + $status = 'Emitida'; + } + if ($flowStatus === 'Cancelled') { + $status = 'Cancelada'; + } + if ($flowStatus === 'PullFromCityHall') { + $status = 'Obtendo da Prefeitura'; + } + if ($flowStatus === 'WaitingCalculateTaxes') { + $status = 'Aguardando Calcular Impostos'; + } + if ($flowStatus === 'WaitingDefineRpsNumber') { + $status = 'Aguardando Definir Número Rps'; + } + if ($flowStatus === 'WaitingSend') { + $status = 'Aguardando Enviar'; + } + if ($flowStatus === 'WaitingSendCancel') { + $status = 'Aguardando Cancelar Envio'; + } + if ($flowStatus === 'WaitingReturn') { + $status = 'Aguardando Retorno'; + } + if ($flowStatus === 'WaitingDownload') { + $status = 'Aguardando Download'; + } + + return $status; + } +} + +if ( !function_exists('gnfe_get_company') ) { + function gnfe_get_company() { + $curl = curl_init(); + curl_setopt($curl, CURLOPT_URL, 'https://api.nfe.io/v1/companies/' . gnfe_config('company_id')); + curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: text/json', 'Accept: application/json', 'Authorization: ' . gnfe_config('api_key')]); + curl_setopt($curl, CURLOPT_TIMEOUT, 30); + curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); + $response = curl_exec ($curl); + curl_close ($curl); + return json_decode($response, true); + } } -if( !function_exists('gnfe_get_company') ) { - function gnfe_get_company(){ - $curl = curl_init(); - curl_setopt($curl, CURLOPT_URL, "https://api.nfe.io/v1/companies/".gnfe_config('company_id')); - curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: text/json', 'Accept: application/json', 'Authorization: '.gnfe_config('api_key'))); - curl_setopt($curl, CURLOPT_TIMEOUT, 30); - curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); - $response = curl_exec ($curl); - curl_close ($curl); - return json_decode($response, true); - } +if ( !function_exists('setInitalDate') ) { + function setInitalDate() { + $params = gnfe_config(); + $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]); + if ($params['debug']) { + logModuleCall('setInitalDate', 'dataAtual', 'create','','',''); + } + } else { + if ($params['debug']) { + logModuleCall('setInitalDate', 'dataAtual', 'exist','','',''); + } + } + } catch (\Exception $e) { + $e->getMessage(); + if ($params['debug']) { + logModuleCall('setInitalDate', 'dataAtual', $e->getMessage(),'','',''); + } + } + } +} +if ( !function_exists('setAddedManually') ) { + function setAddedManually() { + $params = gnfe_config(); + $pdo = Capsule::connection()->getPdo(); + $pdo->beginTransaction(); + try { + $statement = $pdo->prepare( + 'ALTER TABLE gofasnfeio ADD COLUMN IF NOT EXISTS created_manually Varchar(5) NOT NULL DEFAULT "false";' + ); + + $statement->execute(); + $commit = $pdo->commit(); + if ($params['debug']) { + logModuleCall('gofas_nfeio', 'setAddedManually', $commit,'','',''); + } + return $commit; + } catch (\Exception $e) { + if ($params['debug']) { + logModuleCall('gofas_nfeio', 'setAddedManually', $e->getMessage(),'','',''); + } + $pdo->rollBack(); + } + } +} +if ( !function_exists('setAddedManually') ) { + function altersFromUpdate() { + setAddedManually(); + setInitalDate(); + } } \ No newline at end of file diff --git a/modules/addons/gofasnfeio/hooks.php b/modules/addons/gofasnfeio/hooks.php index f1c798f..e37f642 100644 --- a/modules/addons/gofasnfeio/hooks.php +++ b/modules/addons/gofasnfeio/hooks.php @@ -17,10 +17,6 @@ add_hook('InvoiceCreation', 1, function($vars) { require_once __DIR__ . '/functions.php'; require_once __DIR__ . '/hooks/invoicecreation.php'; - - // - require_once __DIR__ . '/hooks/aftercronjob.php'; - // }); //InvoicePaid diff --git a/modules/addons/gofasnfeio/hooks/admininvoicescontrolsoutput.php b/modules/addons/gofasnfeio/hooks/admininvoicescontrolsoutput.php index 861e409..17c299b 100644 --- a/modules/addons/gofasnfeio/hooks/admininvoicescontrolsoutput.php +++ b/modules/addons/gofasnfeio/hooks/admininvoicescontrolsoutput.php @@ -9,116 +9,117 @@ * @support https://github.com/nfe/whmcs-addon/issues * @version 1.2.4 */ -if (!defined("WHMCS")){die();} +if (!defined('WHMCS')) { + die(); +} use WHMCS\Database\Capsule; $params = gnfe_config(); -$nfe_for_invoice = gnfe_get_local_nfe($vars['invoiceid'],array('invoice_id','user_id','nfe_id', 'status', 'services_amount', 'environment', 'pdf','created_at')); -$invoice = localAPI('GetInvoice', array('invoiceid' => $vars['invoiceid']), false); -$client = localAPI('GetClientsDetails',array( 'clientid' => $vars['userid'], 'stats' => false, ), false); +$nfe_for_invoice = gnfe_get_local_nfe($vars['invoiceid'],['invoice_id', 'user_id', 'nfe_id', 'status', 'services_amount', 'environment', 'pdf', 'created_at']); +$invoice = localAPI('GetInvoice', ['invoiceid' => $vars['invoiceid']], false); +$client = localAPI('GetClientsDetails',['clientid' => $vars['userid'], 'stats' => false, ], false); -foreach( Capsule::table('tblconfiguration') -> where('setting', '=', 'gnfewhmcsadminurl') -> get( array( 'value' ) ) as $gnfewhmcsadminurl_ ) { - $gnfewhmcsadminurl = $gnfewhmcsadminurl_->value; +foreach ( Capsule::table('tblconfiguration')->where('setting', '=', 'gnfewhmcsadminurl')->get( ['value'] ) as $gnfewhmcsadminurl_ ) { + $gnfewhmcsadminurl = $gnfewhmcsadminurl_->value; } -if($_REQUEST['gnfe_create']){ - if($nfe_for_invoice['status'] !== (string)'Created' or $nfe_for_invoice['status'] !== (string)'Issued') { - foreach( $invoice['items']['item'] as $value){ - $line_items[] = $value['description'];//substr( $value['description'], 0, 100); +if ($_REQUEST['gnfe_create']) { + if ($nfe_for_invoice['status'] !== (string)'Created' or $nfe_for_invoice['status'] !== (string)'Issued') { + foreach ( $invoice['items']['item'] as $value) { + $line_items[] = $value['description'];//substr( $value['description'], 0, 100); } $customer = gnfe_customer($invoice['userid'],$client); - $queue = gnfe_queue_nfe($vars['invoiceid']); - if($queue !== 'success') { + $queue = gnfe_queue_nfe($vars['invoiceid'],'true'); + if ($queue !== 'success') { header_remove(); - header('Location: '.$gnfewhmcsadminurl.'invoices.php?action=edit&id='.$vars['invoiceid'].'&gnfe_error=Erro ao criar nota fiscal: '.$queue); + header('Location: ' . $gnfewhmcsadminurl . 'invoices.php?action=edit&id=' . $vars['invoiceid'] . '&gnfe_error=Erro ao criar nota fiscal: ' . $queue); exit; } - if($queue === 'success') { + if ($queue === 'success') { $message = '
Nota Fiscal enviada para processamento
'; header_remove(); - header('Location: '.$gnfewhmcsadminurl.'invoices.php?action=edit&id='.$vars['invoiceid'].'&gnfe_message='.base64_encode(urlencode($message))); + header('Location: ' . $gnfewhmcsadminurl . 'invoices.php?action=edit&id=' . $vars['invoiceid'] . '&gnfe_message=' . base64_encode(urlencode($message))); exit; } } } -if($_REQUEST['gnfe_cancel']){ +if ($_REQUEST['gnfe_cancel']) { $delete_nfe = gnfe_delete_nfe($_REQUEST['gnfe_cancel']); - if(!$delete_nfe->message) { - $gnfe_update_nfe = gnfe_update_nfe((object)array('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") ); + if (!$delete_nfe->message) { + $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(); - header('Location: '.$gnfewhmcsadminurl.'invoices.php?action=edit&id='.$vars['invoiceid'].'&gnfe_message='.base64_encode(urlencode($message)) ); + header('Location: ' . $gnfewhmcsadminurl . 'invoices.php?action=edit&id=' . $vars['invoiceid'] . '&gnfe_message=' . base64_encode(urlencode($message)) ); exit; } - if($delete_nfe->message) { - $message = '
'.$delete_nfe->message.'
'; + if ($delete_nfe->message) { + $message = '
' . $delete_nfe->message . '
'; header_remove(); - header('Location: '.$gnfewhmcsadminurl.'invoices.php?action=edit&id='.$vars['invoiceid'].'&gnfe_message='.base64_encode(urlencode($message))); + header('Location: ' . $gnfewhmcsadminurl . 'invoices.php?action=edit&id=' . $vars['invoiceid'] . '&gnfe_message=' . base64_encode(urlencode($message))); exit; } - } -if($_REQUEST['gnfe_email']){ +if ($_REQUEST['gnfe_email']) { $gnfe_email = gnfe_email_nfe($_REQUEST['gnfe_email']); - if(!$gnfe_email->message) { + if (!$gnfe_email->message) { $message = '
Email Enviado com Sucesso
'; header_remove(); - header('Location: '.$gnfewhmcsadminurl.'invoices.php?action=edit&id='.$vars['invoiceid'].'&gnfe_message='.base64_encode(urlencode($message))); + header('Location: ' . $gnfewhmcsadminurl . 'invoices.php?action=edit&id=' . $vars['invoiceid'] . '&gnfe_message=' . base64_encode(urlencode($message))); exit; } - if($gnfe_email->message) { - $message = '
'.$gnfe_email->message.'
'; + if ($gnfe_email->message) { + $message = '
' . $gnfe_email->message . '
'; header_remove(); - header('Location: '.$gnfewhmcsadminurl.'invoices.php?action=edit&id='.$vars['invoiceid'].'&gnfe_message='.base64_encode(urlencode($message))); + header('Location: ' . $gnfewhmcsadminurl . 'invoices.php?action=edit&id=' . $vars['invoiceid'] . '&gnfe_message=' . base64_encode(urlencode($message))); exit; } } -if($nfe_for_invoice['status'] === (string)'Waiting') { - $invoice_nfe = ' Criada em '.date('d/m/Y H:i:s', strtotime($nfe_for_invoice['created_at'])).' - Status: Aguardando'; - $disabled = array('a'=>'disabled="disabled"','b'=>'disabled="disabled"','c'=>'disabled="disabled"','d'=>'disabled="disabled"' ); +if ($nfe_for_invoice['status'] === (string)'Waiting') { + $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)'Created') { - $invoice_nfe = ' Criada em '.date('d/m/Y H:i:s', strtotime($nfe_for_invoice['created_at'])).' - Status: Processando'; - $disabled = array('a'=>'disabled="disabled"','b'=>'','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"']; } -if($nfe_for_invoice['status'] === (string)'Issued') { - $invoice_nfe = ' Criada em '.date('d/m/Y H:i:s', strtotime($nfe_for_invoice['created_at'])).' - Status: Emitida'; - $disabled = array('a'=>'disabled="disabled"','b'=>'','c'=>'','d'=>'' ); +if ($nfe_for_invoice['status'] === (string)'Issued') { + $invoice_nfe = ' Criada em ' . date('d/m/Y H:i:s', strtotime($nfe_for_invoice['created_at'])) . ' - Status: Emitida'; + $disabled = ['a' => 'disabled="disabled"', 'b' => '', 'c' => '', 'd' => '']; } -if($nfe_for_invoice['status'] === (string)'Cancelled') { - $invoice_nfe = ' Criada em '.date('d/m/Y H:i:s', strtotime($nfe_for_invoice['created_at'])).' - Status: Cancelada'; - $disabled = array('a'=>'','b'=>'','c'=>'disabled="disabled"','d'=>'' ); +if ($nfe_for_invoice['status'] === (string)'Cancelled') { + $invoice_nfe = ' Criada em ' . date('d/m/Y H:i:s', strtotime($nfe_for_invoice['created_at'])) . ' - Status: Cancelada'; + $disabled = ['a' => '', 'b' => '', 'c' => 'disabled="disabled"', 'd' => '']; } -if($nfe_for_invoice['status'] === (string)'Error') { - $invoice_nfe = ' Criada em '.date('d/m/Y H:i:s', strtotime($nfe_for_invoice['created_at'])).' - Status: Falha ao Emitir'; - $disabled = array('a'=>'','b'=>'','c'=>'disabled="disabled"','d'=>'disabled="disabled"' ); +if ($nfe_for_invoice['status'] === (string)'Error') { + $invoice_nfe = ' Criada em ' . date('d/m/Y H:i:s', strtotime($nfe_for_invoice['created_at'])) . ' - Status: Falha ao Emitir'; + $disabled = ['a' => '', 'b' => '', 'c' => 'disabled="disabled"', 'd' => 'disabled="disabled"']; } -if($nfe_for_invoice['status'] === (string)'None') { - $invoice_nfe = ' Criada em '.date('d/m/Y H:i:s', strtotime($nfe_for_invoice['created_at'])).' - Status: Nenhum'; - $disabled = array('a'=>'','b'=>'','c'=>'disabled="disabled"','d'=>'disabled="disabled"' ); +if ($nfe_for_invoice['status'] === (string)'None') { + $invoice_nfe = ' Criada em ' . date('d/m/Y H:i:s', strtotime($nfe_for_invoice['created_at'])) . ' - Status: Nenhum'; + $disabled = ['a' => '', 'b' => '', 'c' => 'disabled="disabled"', 'd' => 'disabled="disabled"']; } -if(!$nfe_for_invoice['status']) { +if (!$nfe_for_invoice['status']) { $invoice_nfe = ' Nenhuma nota fiscal foi emitida para essa fatura.'; - $disabled = array('a'=>'','b'=>'disabled="disabled"','c'=>'disabled="disabled"','d'=>'disabled="disabled"' ); + $disabled = ['a' => '', 'b' => 'disabled="disabled"', 'c' => 'disabled="disabled"', 'd' => 'disabled="disabled"']; } -if((string)$invoice['status'] === (string)'Draft' ) { - $disabled = array('a'=>'disabled="disabled"','b'=>'disabled="disabled"','c'=>'disabled="disabled"','d'=>'disabled="disabled"' ); +if ((string)$invoice['status'] === (string)'Draft' ) { + $disabled = ['a' => 'disabled="disabled"', 'b' => 'disabled="disabled"', 'c' => 'disabled="disabled"', 'd' => 'disabled="disabled"']; } echo '
'; -echo '
Nota Fiscal:'.$invoice_nfe.'
'; +echo '
Nota Fiscal:' . $invoice_nfe . '
'; -echo 'Emitir NFE'; +echo 'Emitir NFE'; -echo 'Visualizar NFE'; +echo 'Visualizar NFE'; -echo 'Cancelar NFE'; +echo 'Cancelar NFE'; -echo 'Enviar Email'; +echo 'Enviar Email'; echo '
'; -if($_REQUEST['gnfe_error']){ - echo '
'.$_REQUEST['gnfe_error'].'
'; +if ($_REQUEST['gnfe_error']) { + echo '
' . $_REQUEST['gnfe_error'] . '
'; } -if($_REQUEST['gnfe_message']){ +if ($_REQUEST['gnfe_message']) { echo urldecode(base64_decode( $_REQUEST['gnfe_message'] )); } \ No newline at end of file diff --git a/modules/addons/gofasnfeio/hooks/aftercronjob.php b/modules/addons/gofasnfeio/hooks/aftercronjob.php index 2713c7a..ca2e349 100644 --- a/modules/addons/gofasnfeio/hooks/aftercronjob.php +++ b/modules/addons/gofasnfeio/hooks/aftercronjob.php @@ -15,9 +15,20 @@ use WHMCS\Database\Capsule; $params = gnfe_config(); -foreach ( Capsule::table('gofasnfeio')->orderBy('id', 'desc')->where('status', '=', 'Waiting')->take(1)->get( ['invoice_id']) as $waiting ) { +//; +altersFromUpdate(); +foreach ( Capsule::table('gofasnfeio')->orderBy('id', 'desc')->where('status', '=', 'Waiting')->take(1)->get( ['invoice_id', 'created_manually']) as $waiting ) { //$invoices[] = $Waiting->invoice_id; - foreach ( Capsule::table('tblinvoices')->where('id', '=', $waiting->invoice_id)->get( ['id', 'userid', 'total'] ) as $invoices ) { + $data = getTodaysDate(false); + $dataAtual = toMySQLDate($data); + $created_manually = $waiting->created_manually; + if ($created_manually == 'false') { + $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) { diff --git a/modules/addons/gofasnfeio/hooks/dailycronjob.php b/modules/addons/gofasnfeio/hooks/dailycronjob.php index b87e412..52ab8ed 100644 --- a/modules/addons/gofasnfeio/hooks/dailycronjob.php +++ b/modules/addons/gofasnfeio/hooks/dailycronjob.php @@ -13,6 +13,7 @@ die(); } use WHMCS\Database\Capsule; +// $params = gnfe_config(); if ( $params['issue_note_after'] and (int)$params['issue_note_after'] > 0 ) { diff --git a/modules/addons/gofasnfeio/output.php b/modules/addons/gofasnfeio/output.php index 23b9e44..f9db916 100644 --- a/modules/addons/gofasnfeio/output.php +++ b/modules/addons/gofasnfeio/output.php @@ -11,138 +11,141 @@ */ use WHMCS\Database\Capsule; -if( !function_exists('gofasnfeio_output') ) { - function gofasnfeio_output($vars) { - require_once __DIR__ . '/functions.php'; - $params = gnfe_config(); - foreach( Capsule::table('tblconfiguration') -> where('setting', '=', 'gnfewhmcsadminurl') -> get( array( 'value' ) ) as $gnfewhmcsadminurl_ ) { - $gnfewhmcsadminurl = $gnfewhmcsadminurl_->value; - } - $nfes = array(); - - foreach( Capsule::table('gofasnfeio')->orderBy('id', 'desc')->get( array( 'id' ) ) as $nfes_ ) { - $nfes[] = $nfes_->id; - } - - if($_REQUEST['page']){ $nfes_page = (int)$_REQUEST['page']; } else { $nfes_page = 1; } - if($_REQUEST['take']){ $take = (int)$_REQUEST['take'];} else { $take = 10; } - - $nfs_keys = array_keys($nfes); - $nfes_total = count($nfes); - if($take > $nfes_total) { - $take = $nfes_total; - } - - $nfes_pages = ceil($nfes_total / $take); - - $nfes_from_ = ( $nfes_page * $take ) - $take; - $nfes_from = $nfs_keys[$nfes_from_+1]; - - $nfes_to_ = ( $nfes_from + $take )-2; - $nfes_to = $nfs_keys[$nfes_to_+1]; - - $nfess = array_slice($nfes, $nfes_from_, $nfes_to); - - if ((int)$nfes_page === (int)$nfes_pages) { - $nfes_to = $nfes_total; - $nfess = array_slice($nfes, $nfes_from_, $nfes_to_); - } - - if ((int)$take >= (int)$nfes_total) { - $nfes_from = 1; - $nfess = array_slice($nfes, $nfes_from_, $nfes_to); - } - - // Pagination - $i = 1; - while ($i <= $nfes_pages ) { - $page_num = $i++; - - if( (int)$page_num !== (int)$nfes_page ) { - $tag = 'a '; - $a_style = ''; - $li_class = 'class="enabled"'; - $href = $gnfewhmcsadminurl.'addonmodules.php?module=gofasnfeio&page='.$page_num; - } - elseif( (int)$page_num === (int)$nfes_page ){ - $tag = 'span '; - $a_style = 'style="background: #337ab7; color: #fff"'; - $li_class = 'class="disabled"'; - $href = ''; - } - $pagination_ .= '
  • <'.$tag.' '.$a_style.' href="'.$href.'" >'.$page_num.'
  • '; - } - if((int)$nfes_page === 1) { - $preview_class = ' class="previous disabled" '; - $preview_href = ''; - $preview_tag = 'span '; - } - else { - $preview_class = ' class="previous" '; - $preview_href = ' href="'.$gnfewhmcsadminurl.'addonmodules.php?module=gofasnfeio&page='.($nfes_page-1).'" '; - $preview_tag = 'a '; - } - if((int)$nfes_page === (int)$nfes_pages) { - $next_class = ' class="next disabled" '; - $next_href = ''; - $next_tag = 'span '; - } - else { - $next_class = ' class="next" '; - $next_href = ' href="'.$gnfewhmcsadminurl.'addonmodules.php?module=gofasnfeio&page='.($nfes_page+1).'" '; - $next_tag = 'a '; - } - $pagination .= '
  • <'.$preview_tag.' '.$preview_href.'>« Página anterior
  • '; - $pagination .= $pagination_; - $pagination .= '
  • <'.$next_tag.' '.$next_href.'>Próxima página »
  • '; - - foreach( Capsule::table('gofasnfeio')-> +if ( !function_exists('gofasnfeio_output') ) { + function gofasnfeio_output($vars) { + require_once __DIR__ . '/functions.php'; + $params = gnfe_config(); + foreach ( Capsule::table('tblconfiguration')->where('setting', '=', 'gnfewhmcsadminurl')->get( ['value'] ) as $gnfewhmcsadminurl_ ) { + $gnfewhmcsadminurl = $gnfewhmcsadminurl_->value; + } + $nfes = []; + + foreach ( Capsule::table('gofasnfeio')->orderBy('id', 'desc')->get( ['id'] ) as $nfes_ ) { + $nfes[] = $nfes_->id; + } + + if ($_REQUEST['page']) { + $nfes_page = (int)$_REQUEST['page']; + } else { + $nfes_page = 1; + } + if ($_REQUEST['take']) { + $take = (int)$_REQUEST['take']; + } else { + $take = 10; + } + + $nfs_keys = array_keys($nfes); + $nfes_total = count($nfes); + if ($take > $nfes_total) { + $take = $nfes_total; + } + + $nfes_pages = ceil($nfes_total / $take); + + $nfes_from_ = ( $nfes_page * $take ) - $take; + $nfes_from = $nfs_keys[$nfes_from_ + 1]; + + $nfes_to_ = ( $nfes_from + $take ) - 2; + $nfes_to = $nfs_keys[$nfes_to_ + 1]; + + $nfess = array_slice($nfes, $nfes_from_, $nfes_to); + + if ((int)$nfes_page === (int)$nfes_pages) { + $nfes_to = $nfes_total; + $nfess = array_slice($nfes, $nfes_from_, $nfes_to_); + } + + if ((int)$take >= (int)$nfes_total) { + $nfes_from = 1; + $nfess = array_slice($nfes, $nfes_from_, $nfes_to); + } + + // Pagination + $i = 1; + while ($i <= $nfes_pages ) { + $page_num = $i++; + + if ( (int)$page_num !== (int)$nfes_page ) { + $tag = 'a '; + $a_style = ''; + $li_class = 'class="enabled"'; + $href = $gnfewhmcsadminurl . 'addonmodules.php?module=gofasnfeio&page=' . $page_num; + } elseif ( (int)$page_num === (int)$nfes_page ) { + $tag = 'span '; + $a_style = 'style="background: #337ab7; color: #fff"'; + $li_class = 'class="disabled"'; + $href = ''; + } + $pagination_ .= '
  • <' . $tag . ' ' . $a_style . ' href="' . $href . '" >' . $page_num . '
  • '; + } + if ((int)$nfes_page === 1) { + $preview_class = ' class="previous disabled" '; + $preview_href = ''; + $preview_tag = 'span '; + } else { + $preview_class = ' class="previous" '; + $preview_href = ' href="' . $gnfewhmcsadminurl . 'addonmodules.php?module=gofasnfeio&page=' . ($nfes_page - 1) . '" '; + $preview_tag = 'a '; + } + if ((int)$nfes_page === (int)$nfes_pages) { + $next_class = ' class="next disabled" '; + $next_href = ''; + $next_tag = 'span '; + } else { + $next_class = ' class="next" '; + $next_href = ' href="' . $gnfewhmcsadminurl . 'addonmodules.php?module=gofasnfeio&page=' . ($nfes_page + 1) . '" '; + $next_tag = 'a '; + } + $pagination .= '
  • <' . $preview_tag . ' ' . $preview_href . '>« Página anterior
  • '; + $pagination .= $pagination_; + $pagination .= '
  • <' . $next_tag . ' ' . $next_href . '>Próxima página »
  • '; + + foreach ( Capsule::table('gofasnfeio')-> orderBy('id', 'desc')-> - whereBetween('id', array( end($nfess), reset($nfess) ))-> + whereBetween('id', [end($nfess), reset($nfess)])-> take($take)-> - get( array('invoice_id','user_id','nfe_id', 'status', 'services_amount', 'environment', 'flow_status', 'pdf', 'created_at','updated_at') ) as $value ) { - - $client = localAPI('GetClientsDetails',array( 'clientid' => $value->user_id, 'stats' => false, ), false); - if($value->status === 'Waiting') { - $status = 'Aguardando'; - $disabled = array('a'=>'disabled="disabled"','b'=>'disabled="disabled"', 'c'=>'disabled="disabled"', 'd'=>'disabled="disabled"'); - } - if($value->status === 'Created') { - $status = 'Processando'; - $disabled = array('a'=>'disabled="disabled"','b'=>'', 'c'=>'disabled="disabled"', 'd'=>'disabled="disabled"'); - } - if($value->status === 'Issued') { - $status = 'Emitida'; - $disabled = array('a'=>'disabled="disabled"','b'=>'', 'c'=>'', 'd'=>''); - } - if($value->status === 'Cancelled') { - $status = 'Cancelada'; - $disabled = array('a'=>'','b'=>'','c'=>'disabled="disabled"','d'=>''); - } - if($value->status === 'Error') { - $status = 'Falha ao Emitir'; - $disabled = array('a'=>'','b'=>'','c'=>'disabled="disabled"','d'=>'disabled="disabled"'); - } - if($value->status === 'None') { - $status = 'Nenhum'; - $disabled = array('a'=>'','b'=>'','c'=>'disabled="disabled"','d'=>'disabled="disabled"'); - } - $html_table .= '#'.$value->invoice_id.' - '.date('d/m/Y', strtotime($value->created_at)) .' - '.$client['fullname'].' - '.number_format( $value->services_amount, 2, ',', '.' ).' - '.$status.' + get( ['invoice_id', 'user_id', 'nfe_id', 'status', 'services_amount', 'environment', 'flow_status', 'pdf', 'created_at', 'updated_at'] ) as $value ) { + $client = localAPI('GetClientsDetails',['clientid' => $value->user_id, 'stats' => false, ], false); + if ($value->status === 'Waiting') { + $status = 'Aguardando'; + $disabled = ['a' => 'disabled="disabled"', 'b' => 'disabled="disabled"', 'c' => 'disabled="disabled"', 'd' => 'disabled="disabled"']; + } + if ($value->status === 'Created') { + $status = 'Processando'; + $disabled = ['a' => 'disabled="disabled"', 'b' => '', 'c' => 'disabled="disabled"', 'd' => 'disabled="disabled"']; + } + if ($value->status === 'Issued') { + $status = 'Emitida'; + $disabled = ['a' => 'disabled="disabled"', 'b' => '', 'c' => '', 'd' => '']; + } + if ($value->status === 'Cancelled') { + $status = 'Cancelada'; + $disabled = ['a' => '', 'b' => '', 'c' => 'disabled="disabled"', 'd' => '']; + } + if ($value->status === 'Error') { + $status = 'Falha ao Emitir'; + $disabled = ['a' => '', 'b' => '', 'c' => 'disabled="disabled"', 'd' => 'disabled="disabled"']; + } + if ($value->status === 'None') { + $status = 'Nenhum'; + $disabled = ['a' => '', 'b' => '', 'c' => 'disabled="disabled"', 'd' => 'disabled="disabled"']; + } + $html_table .= '#' . $value->invoice_id . ' + ' . date('d/m/Y', strtotime($value->created_at)) . ' + ' . $client['fullname'] . ' + ' . number_format( $value->services_amount, 2, ',', '.' ) . ' + ' . $status . ' - Emitir Nova - Visualizar - Cancelar - Enviar por Email'; - - } - - if((int)$nfes_total > 0) { - echo ' -

    Listagem de notas fiscais

    '.$nfes_total.' Itens encontrados.
    Exibindo de '.$nfes_from.' a '.$nfes_to.'. Página '.$nfes_page.' de '.$nfes_pages.'
    + Emitir Nova + Visualizar + Cancelar + Enviar por Email'; + } + + if ((int)$nfes_total > 0) { + echo ' +

    Listagem de notas fiscais

    ' . $nfes_total . ' Itens encontrados.
    Exibindo de ' . $nfes_from . ' a ' . $nfes_to . '. Página ' . $nfes_page . ' de ' . $nfes_pages . '
    @@ -155,7 +158,7 @@ function gofasnfeio_output($vars) { - '.$html_table.' + ' . $html_table . '
    Ações
    @@ -163,76 +166,74 @@ function gofasnfeio_output($vars) {
      - '.$pagination.' + ' . $pagination . '
    '; - } - else { - echo ' + } else { + echo '

    Nenhuma nota fiscal gerada até o momento

    '; - } - - if($_REQUEST['gnfe_create']){ - $invoice = localAPI('GetInvoice', array('invoiceid' => $_REQUEST['invoice_id']), false); - $client = localAPI('GetClientsDetails',array( 'clientid' => $invoice['userid'], 'stats' => false, ), false); - $nfe_for_invoice = gnfe_get_local_nfe($_REQUEST['invoice_id'],array('invoice_id','user_id','nfe_id', 'status', 'services_amount', 'environment', 'pdf','created_at', 'rpsSerialNumber')); - //if($nfe_for_invoice['status'] !== (string)'Created' or $nfe_for_invoice['status'] !== (string)'Issued') { - $queue = gnfe_queue_nfe($_REQUEST['invoice_id']); - 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($_REQUEST['gnfe_cancel']){ - $delete_nfe = gnfe_delete_nfe($_REQUEST['gnfe_cancel']); - if(!$delete_nfe->message) { - $gnfe_update_nfe = gnfe_update_nfe((object)array('id'=>$_REQUEST['gnfe_cancel'], 'status'=>'Cancelled','servicesAmount'=>$_REQUEST['services_amount'],'environment'=>$_REQUEST['environment'],'flow_status' => $_REQUEST['flow_status'] ),$_REQUEST['user_id'],$_REQUEST['invoice_id'],'n/a',$_REQUEST['created_at'],date("Y-m-d H:i:s") ); - $message = '
    Nota fiscal cancelada com sucesso
    '; - header_remove(); - header('Location: '.$gnfewhmcsadminurl.'addonmodules.php?module=gofasnfeio&gnfe_message='.base64_encode(urlencode($message))); - exit; - } - if($delete_nfe->message) { - $message = '
    '.$delete_nfe->message.'
    '; - header_remove(); - header('Location: '.$gnfewhmcsadminurl.'addonmodules.php?module=gofasnfeio&gnfe_message='.base64_encode(urlencode($message))); - exit; - } - } - - if($_REQUEST['gnfe_email']){ - $gnfe_email = gnfe_email_nfe($_REQUEST['gnfe_email']); - if(!$gnfe_email->message) { - $message = '
    Email Enviado com Sucesso
    '; - header_remove(); - header('Location: '.$gnfewhmcsadminurl.'addonmodules.php?module=gofasnfeio&gnfe_message='.base64_encode(urlencode($message))); - exit; - } - if($gnfe_email->message) { - $message = '
    '.$gnfe_email->message.'
    '; - header_remove(); - header('Location: '.$gnfewhmcsadminurl.'addonmodules.php?module=gofasnfeio&gnfe_message='.base64_encode(urlencode($message))); - exit; - } - } - - if($_REQUEST['gnfe_message']){ - echo urldecode(base64_decode( $_REQUEST['gnfe_message'] )); - } - - } + } + + if ($_REQUEST['gnfe_create']) { + $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']); + //if($nfe_for_invoice['status'] !== (string)'Created' or $nfe_for_invoice['status'] !== (string)'Issued') { + $queue = gnfe_queue_nfe($_REQUEST['invoice_id'],'t'); + 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 ($_REQUEST['gnfe_cancel']) { + $delete_nfe = gnfe_delete_nfe($_REQUEST['gnfe_cancel']); + if (!$delete_nfe->message) { + $gnfe_update_nfe = gnfe_update_nfe((object)['id' => $_REQUEST['gnfe_cancel'], 'status' => 'Cancelled', 'servicesAmount' => $_REQUEST['services_amount'], 'environment' => $_REQUEST['environment'], 'flow_status' => $_REQUEST['flow_status']],$_REQUEST['user_id'],$_REQUEST['invoice_id'],'n/a',$_REQUEST['created_at'],date('Y-m-d H:i:s') ); + $message = '
    Nota fiscal cancelada com sucesso
    '; + header_remove(); + header('Location: ' . $gnfewhmcsadminurl . 'addonmodules.php?module=gofasnfeio&gnfe_message=' . base64_encode(urlencode($message))); + exit; + } + if ($delete_nfe->message) { + $message = '
    ' . $delete_nfe->message . '
    '; + header_remove(); + header('Location: ' . $gnfewhmcsadminurl . 'addonmodules.php?module=gofasnfeio&gnfe_message=' . base64_encode(urlencode($message))); + exit; + } + } + + if ($_REQUEST['gnfe_email']) { + $gnfe_email = gnfe_email_nfe($_REQUEST['gnfe_email']); + if (!$gnfe_email->message) { + $message = '
    Email Enviado com Sucesso
    '; + header_remove(); + header('Location: ' . $gnfewhmcsadminurl . 'addonmodules.php?module=gofasnfeio&gnfe_message=' . base64_encode(urlencode($message))); + exit; + } + if ($gnfe_email->message) { + $message = '
    ' . $gnfe_email->message . '
    '; + header_remove(); + header('Location: ' . $gnfewhmcsadminurl . 'addonmodules.php?module=gofasnfeio&gnfe_message=' . base64_encode(urlencode($message))); + exit; + } + } + + if ($_REQUEST['gnfe_message']) { + echo urldecode(base64_decode( $_REQUEST['gnfe_message'] )); + } + } } \ No newline at end of file From 6d2f8d9bdd765b90dbb4cbe2588454d5deae5f29 Mon Sep 17 00:00:00 2001 From: JoaoVictorLNacional Date: Tue, 8 Dec 2020 14:15:22 -0300 Subject: [PATCH 06/52] =?UTF-8?q?removido=20a=20verifica=C3=A7=C3=A3o=20da?= =?UTF-8?q?=20fun=C3=A7=C3=A3o=20altersFromUpdate?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- modules/addons/gofasnfeio/functions.php | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/modules/addons/gofasnfeio/functions.php b/modules/addons/gofasnfeio/functions.php index 83ad006..67ec098 100644 --- a/modules/addons/gofasnfeio/functions.php +++ b/modules/addons/gofasnfeio/functions.php @@ -616,9 +616,7 @@ function setAddedManually() { } } } -if ( !function_exists('setAddedManually') ) { function altersFromUpdate() { setAddedManually(); setInitalDate(); - } -} \ No newline at end of file + } \ No newline at end of file From be500a8b65e1c76e8e50381d90073c3fcc82da97 Mon Sep 17 00:00:00 2001 From: JoaoVictorLNacional Date: Tue, 8 Dec 2020 15:11:58 -0300 Subject: [PATCH 07/52] =?UTF-8?q?modificado=20para=20as=20modifica=C3=A7?= =?UTF-8?q?=C3=B5es=20funcionarem=20na=20atualiza=C3=A7=C3=A3o?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- modules/addons/gofasnfeio/callback.php | 5 +- modules/addons/gofasnfeio/config.php | 98 +++++-------------- modules/addons/gofasnfeio/functions.php | 2 +- .../addons/gofasnfeio/hooks/aftercronjob.php | 6 +- .../addons/gofasnfeio/hooks/dailycronjob.php | 10 +- 5 files changed, 34 insertions(+), 87 deletions(-) diff --git a/modules/addons/gofasnfeio/callback.php b/modules/addons/gofasnfeio/callback.php index 09d4fa8..8ad30ba 100644 --- a/modules/addons/gofasnfeio/callback.php +++ b/modules/addons/gofasnfeio/callback.php @@ -37,13 +37,12 @@ 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( ['invoice_id', 'created_manually']) as $waiting ) { + foreach ( Capsule::table('gofasnfeio')->orderBy('id', 'desc')->where('status', '=', 'Waiting')->take(1)->get( ['invoice_id']) as $waiting ) { //$invoices[] = $Waiting->invoice_id; $data = getTodaysDate(false); $dataAtual = toMySQLDate($data); - $created_manually = $waiting->created_manually; - if ($created_manually == 'false') { + 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']); diff --git a/modules/addons/gofasnfeio/config.php b/modules/addons/gofasnfeio/config.php index 3de32cf..7e349c6 100644 --- a/modules/addons/gofasnfeio/config.php +++ b/modules/addons/gofasnfeio/config.php @@ -1,15 +1,4 @@ where('type', '=', 'client')->get(['fieldname', 'id']) as $customfield) { -======= -if (!defined("WHMCS")){die();} -use WHMCS\Database\Capsule; -if( !function_exists('gofasnfeio_config') ) { - if( !function_exists('gnfe_customfields_dropdow') ) { - function gnfe_customfields_dropdow() - { - $customfields_array = array(); - foreach (Capsule::table('tblcustomfields')->where('type', '=', 'client')->get(array('fieldname', 'id')) as $customfield) { ->>>>>>> upstream/master $customfields_array[] = $customfield; } $customfields = json_decode(json_encode($customfields_array), true); @@ -50,40 +28,21 @@ function gofasnfeio_config() { $module_version = '1.2.4'; $module_version_int = (int)preg_replace('/[^0-9]/', '', $module_version); -<<<<<<< HEAD /// REMOVER VERIFICAÇÃO APÓS VERSÃO 2.0 $verificarEmail = Capsule::table('tbladdonmodules')->where( 'module', '=', 'gofasnfeio' )->where( 'setting', '=', 'gnfe_email_nfe_config' )->count(); if (empty($verificarEmail)) { - echo 'vazio'; + // echo "vazio"; try { Capsule::table('tbladdonmodules')->insert(['module' => 'gofasnfeio', 'setting' => 'gnfe_email_nfe_config', 'value' => 'on']); } catch (\Exception $e) { -======= - /// REMOVER VERIFICAÇÃO APÓS VERSÃO 2.0 - $verificarEmail = Capsule::table('tbladdonmodules')->where( 'module', '=', 'gofasnfeio' )->where( 'setting', '=', 'gnfe_email_nfe_config' )->count(); - if(empty($verificarEmail)){ - // echo "vazio"; - try { - Capsule::table('tbladdonmodules')->insert(array('module' => 'gofasnfeio', 'setting' => 'gnfe_email_nfe_config', 'value' => 'on')); - }catch (\Exception $e) { ->>>>>>> upstream/master $e->getMessage(); } }////// FIM VERIFICAÇÃO -<<<<<<< HEAD - // Get Config $actual_link = (isset($_SERVER['HTTPS']) ? 'https' : 'http') . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; if ( stripos( $actual_link, '/configaddonmods.php') ) { - // Local V URL $whmcs_url__ = str_replace('\\','/',(isset($_SERVER['HTTPS']) ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . substr(getcwd(),strlen($_SERVER['DOCUMENT_ROOT']))); $admin_url = $whmcs_url__ . '/'; -======= - $actual_link = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; - if ( stripos( $actual_link, '/configaddonmods.php') ) { - $whmcs_url__ = str_replace("\\",'/',(isset($_SERVER['HTTPS']) ? "https://" : "http://").$_SERVER['HTTP_HOST'].substr(getcwd(),strlen($_SERVER['DOCUMENT_ROOT']))); - $admin_url = $whmcs_url__.'/'; ->>>>>>> upstream/master $vtokens = explode('/', $actual_link); $whmcs_admin_path = '/' . $vtokens[sizeof($vtokens) - 2] . '/'; $whmcs_url = str_replace( $whmcs_admin_path, '', $admin_url) . '/'; @@ -155,7 +114,7 @@ function gofasnfeio_config() { // Verify available updates $available_update_message = '

    Nova versão disponível no Github

    '; - if( !function_exists('gnfe_verifyInstall') ) { + if ( !function_exists('gnfe_verifyInstall') ) { function gnfe_verifyInstall() { if ( !Capsule::schema()->hasTable('gofasnfeio') ) { try { @@ -176,38 +135,29 @@ function gnfe_verifyInstall() { $table->string('created_at'); $table->string('updated_at'); }); - } - catch (\Exception $e) { + } 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')){ + if (!Capsule::schema()->hasColumn('gofasnfeio', 'rpsNumber')) { try { Capsule::schema()->table('gofasnfeio', function($table){$table->string('rpsNumber');}); - } - catch (\Exception $e) { + } catch (\Exception $e) { $error .= "Não foi possível atualizar a tabela do módulo no banco de dados: {$e->getMessage()}"; } } - if(!$error) { - return array('sucess'=>1); - } - elseif($error) { - return array('error'=>$error); + if (!$error) { + return ['sucess' => 1]; + } elseif ($error) { + return ['error' => $error]; } } } gnfe_verifyInstall(); -<<<<<<< HEAD - */ $intro = ['intro' => [ -======= - - $intro = array('intro' => array( ->>>>>>> upstream/master 'FriendlyName' => '', 'Description' => '

    Módulo Nota Fiscal NFE.io para WHMCS v' . $module_version . '

    ' . $available_update_message . '', @@ -238,8 +188,8 @@ function gnfe_verifyInstall() { 'Type' => 'text', 'Default' => 'zero', 'Description' => 'O número RPS da NFE mais recente gerada.
    Deixe em branco e o módulo irá preencher esse campo após a primeira emissão. Não altere o valor a menos que tenha certeza de como funciona essa opção. Saiba mais.', - )); - $issue_note = array('issue_note' => array( + ]]; + $issue_note = ['issue_note' => [ 'FriendlyName' => 'Quando emitir NFE', 'Type' => 'radio', 'Options' => 'Manualmente, Quando a Fatura é Gerada,Quando a Fatura é Paga', @@ -250,14 +200,14 @@ function gnfe_verifyInstall() { 'Type' => 'text', 'Default' => '', 'Description' => '
    Número de dias após o pagamento da fatura que as notas devem ser emitidas. Preencher essa opção desativa a opção anterior.', - )); - $gnfe_email_nfe_config = array('gnfe_email_nfe_config' => array( + ]]; + $gnfe_email_nfe_config = ['gnfe_email_nfe_config' => [ 'FriendlyName' => 'Disparar e-mail com a nota', 'Type' => 'yesno', 'Default' => 'yes', 'Description' => 'Permitir o disparo da nota fiscal via NFE.io para o e-mail do usuário.', - )); - $cancel_invoice_cancel_nfe = array('cancel_invoice_cancel_nfe' => array( + ]]; + $cancel_invoice_cancel_nfe = ['cancel_invoice_cancel_nfe' => [ 'FriendlyName' => 'Cancelar NFE', 'Type' => 'yesno', 'Default' => 'yes', @@ -267,18 +217,18 @@ 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', - )); - $insc_municipal = array('insc_municipal' => array( + 'Description' => 'Marque essa opção para salvar informações de diagnóstico no Log de Módulo', + ]]; + $insc_municipal = ['insc_municipal' => [ 'FriendlyName' => 'Inscrição Municipal', 'Type' => 'dropdown', 'Options' => gnfe_customfields_dropdow(), - 'Description' => 'Escolha o campo personalizado de Inscrição Municipal')); - - $footer = array('footer' => array( - 'FriendlyName' => '', - 'Description' => '© '.date('Y').' Suporte módulo', - )); + 'Description' => 'Escolha o campo personalizado de Inscrição Municipal']]; + + $footer = ['footer' => [ + 'FriendlyName' => '', + 'Description' => '© ' . date('Y') . ' Suporte módulo', + ]]; $fields = array_merge($intro,$api_key,$company_id,$service_code,$rps_serial_number,$rps_number,$issue_note,$issue_note_after,$gnfe_email_nfe_config,$cancel_invoice_cancel_nfe,$debug,$insc_municipal,$footer); $configarray = [ 'name' => 'NFE.io', diff --git a/modules/addons/gofasnfeio/functions.php b/modules/addons/gofasnfeio/functions.php index eb09bf2..26a3e20 100644 --- a/modules/addons/gofasnfeio/functions.php +++ b/modules/addons/gofasnfeio/functions.php @@ -630,7 +630,7 @@ function setAddedManually() { } } function altersFromUpdate() { - setAddedManually(); + // setAddedManually(); setInitalDate(); } diff --git a/modules/addons/gofasnfeio/hooks/aftercronjob.php b/modules/addons/gofasnfeio/hooks/aftercronjob.php index d34245e..01a74da 100644 --- a/modules/addons/gofasnfeio/hooks/aftercronjob.php +++ b/modules/addons/gofasnfeio/hooks/aftercronjob.php @@ -5,11 +5,11 @@ use WHMCS\Database\Capsule; $params = gnfe_config(); -foreach( Capsule::table('gofasnfeio')->orderBy('id', 'desc')->where('status', '=', 'Waiting')->take(1)->get( array( 'invoice_id','created_manually' )) as $waiting ) { +foreach( Capsule::table('gofasnfeio')->orderBy('id', 'desc')->where('status', '=', 'Waiting')->take(1)->get( array( 'invoice_id' )) as $waiting ) { $data = getTodaysDate(false); $dataAtual = toMySQLDate($data); - $created_manually = $waiting->created_manually; - if ($created_manually == 'false') { + + 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']); diff --git a/modules/addons/gofasnfeio/hooks/dailycronjob.php b/modules/addons/gofasnfeio/hooks/dailycronjob.php index 622b251..12878ad 100644 --- a/modules/addons/gofasnfeio/hooks/dailycronjob.php +++ b/modules/addons/gofasnfeio/hooks/dailycronjob.php @@ -3,8 +3,11 @@ use WHMCS\Database\Capsule; // $params = gnfe_config(); +$data = getTodaysDate(false); +$dataAtual = toMySQLDate($data); + if( $params['issue_note'] !== 'Manualmente' && $params['issue_note_after'] && (int)$params['issue_note_after'] > 0 ) { - foreach( Capsule::table('tblinvoices')->where('status', '=', 'Paid')->get( array( 'id', 'userid', 'datepaid','total' ) ) as $invoices ) { + foreach( Capsule::table('tblinvoices')->whereBetween('date', [$params['initial_date'], $dataAtual])->where('status', '=', 'Paid')->get( array( 'id', 'userid', 'datepaid','total' ) ) as $invoices ) { $datepaid = date('Ymd', strtotime($invoices->datepaid)); $datepaid_to_issue_ = '-'.$params['issue_note_after'].' days'; $datepaid_to_issue = date('Ymd', strtotime($datepaid_to_issue_)); @@ -83,16 +86,11 @@ 'rpsNumber' => (int)$company['companies']['rpsNumber'] + 1, ]; } -<<<<<<< HEAD if ($params['debug']) { logModuleCall('gofas_nfeio', 'dailycronjob',$postfields , '', '', 'replaceVars'); } - $waiting = []; - foreach ( Capsule::table('gofasnfeio')->where( 'status', '=', 'Waiting' )->get( ['invoice_id', 'status'] ) as $Waiting ) { -======= $waiting = array(); foreach( Capsule::table('gofasnfeio') -> where( 'status', '=', 'Waiting' ) -> get( array( 'invoice_id', 'status') ) as $Waiting ) { ->>>>>>> upstream/master $waiting[] = $Waiting->invoice_id; } $queue = gnfe_queue_nfe($invoices->id); From d6b11a9cdd58390e8e856dc663e697334dd92285 Mon Sep 17 00:00:00 2001 From: JoaoVictorLNacional Date: Fri, 11 Dec 2020 17:09:49 -0300 Subject: [PATCH 08/52] codigo individual para cada produto --falta testar-- --- modules/addons/gofasnfeio/functions.php | 136 ++++++++----- modules/addons/gofasnfeio/hooks.php | 1 + .../hooks/admininvoicescontrolsoutput.php | 2 +- .../addons/gofasnfeio/hooks/aftercronjob.php | 72 ++++--- .../addons/gofasnfeio/hooks/dailycronjob.php | 188 +++++++++--------- .../gofasnfeio/hooks/invoicecreation.php | 63 +++--- modules/addons/gofasnfeio/output.php | 2 +- 7 files changed, 258 insertions(+), 206 deletions(-) diff --git a/modules/addons/gofasnfeio/functions.php b/modules/addons/gofasnfeio/functions.php index 26a3e20..f983096 100644 --- a/modules/addons/gofasnfeio/functions.php +++ b/modules/addons/gofasnfeio/functions.php @@ -164,37 +164,41 @@ function gnfe_ibge($zip) { } } if ( !function_exists('gnfe_queue_nfe') ) { - function gnfe_queue_nfe($invoice_id,$addManually = 'false') { - if (!setAddedManually()) { - return ''; - } - + function gnfe_queue_nfe($invoice_id,$item,$create_all = false) { $invoice = localAPI('GetInvoice', ['invoiceid' => $invoice_id], false); $data = [ 'invoice_id' => $invoice_id, 'user_id' => $invoice['userid'], 'nfe_id' => 'waiting', 'status' => 'Waiting', - 'services_amount' => $invoice['total'], + // + 'services_amount' => $item['monthly'], 'environment' => 'waiting', 'flow_status' => 'waiting', 'pdf' => 'waiting', 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => 'waiting', 'rpsSerialNumber' => 'waiting', - 'created_manually' => (boolval($addManually) ? 'true' : 'false') + 'service_code' => $item['value'], + 'monthly' => $item['monthly'] ]; - logModuleCall('gofas_nfeio', 'gnfe_queue_nfe', $data,'','',''); + $nfe_for_invoice = gnfe_get_local_nfe($invoice_id, ['status']); - if (!$nfe_for_invoice['status']) { + logModuleCall('gofas_nfeio', 'nfe_for_invoice',$nfe_for_invoice , '', '', 'replaceVars'); + + if (!$nfe_for_invoice['status'] || $create_all) { try { $save_nfe = Capsule::table('gofasnfeio')->insert($data); + logModuleCall('gofas_nfeio', 'data gnfe_queue_nfe create',$data , '', '', 'replaceVars'); + return 'success'; } catch (\Exception $e) { return $e->getMessage(); } } elseif ((string)$nfe_for_invoice['status'] === (string)'Cancelled' or (string)$nfe_for_invoice['status'] === (string)'Error') { try { + logModuleCall('gofas_nfeio', 'data gnfe_queue_nfe update',$data , '', '', 'replaceVars'); + $update_nfe = Capsule::table('gofasnfeio')->where('invoice_id', '=', $invoice_id)->update($data); return 'success'; } catch (\Exception $e) { @@ -581,58 +585,26 @@ function gnfe_get_company() { } } -if ( !function_exists('setInitalDate') ) { - function setInitalDate() { - $params = gnfe_config(); +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]); - if ($params['debug']) { - logModuleCall('setInitalDate', 'dataAtual', 'create','','',''); - } - } else { - if ($params['debug']) { - logModuleCall('setInitalDate', 'dataAtual', 'exist','','',''); - } } } catch (\Exception $e) { $e->getMessage(); - if ($params['debug']) { - logModuleCall('setInitalDate', 'dataAtual', $e->getMessage(),'','',''); - } } } } -if ( !function_exists('setAddedManually') ) { - function setAddedManually() { - $params = gnfe_config(); - $pdo = Capsule::connection()->getPdo(); - $pdo->beginTransaction(); - try { - $statement = $pdo->prepare( - 'ALTER TABLE gofasnfeio ADD COLUMN IF NOT EXISTS created_manually Varchar(5) NOT NULL DEFAULT "false";' - ); - $statement->execute(); - $commit = $pdo->commit(); - if ($params['debug']) { - logModuleCall('gofas_nfeio', 'setAddedManually', $commit,'','',''); - } - return $commit; - } catch (\Exception $e) { - if ($params['debug']) { - logModuleCall('gofas_nfeio', 'setAddedManually', $e->getMessage(),'','',''); - } - $pdo->rollBack(); + function set_camp_custom_code() { + $num = Capsule::table('tblcustomfields')->where('fieldname', '=', 'Código de Serviço')->where('type', '=', 'product')->count(); + if ($num == 0) { + Capsule::table('tblcustomfields')->insert(['type' => 'product', 'relid' => '0', 'fieldname' => 'Código de Serviço', 'fieldtype' => 'text', 'adminonly' => 'on', 'showorder' => 'on', 'showinvoice' => 'on']); } } -} - function altersFromUpdate() { - // setAddedManually(); - setInitalDate(); - } if ( !function_exists('gnfe_get_company') ) { function gnfe_get_company() { @@ -647,3 +619,73 @@ function gnfe_get_company() { } } +if ( !function_exists('gnfe_customer_service_code') ) { + function gnfe_customer_service_code($item_id) { + $customfields = []; + foreach ( Capsule::table('tblcustomfields')->where( 'type', '=', 'product' )->where( 'fieldname', '=', 'Código de Serviço' )->get( ['fieldname', 'id'] ) as $customfield ) { + $customfield_id = $customfield->id; + $insc_customfield_value = 'NF'; + foreach ( Capsule::table('tblcustomfieldsvalues')->where( 'fieldid', '=', $customfield_id )->where( 'relid', '=', $item_id )->get( ['value'] ) as $customfieldvalue ) { + $insc_customfield_value = $customfieldvalue->value; + return $insc_customfield_value; + } + } + } +} + +function get_prodict_invoice($invoice_id) { + $query = "SELECT DISTINCT tblhosting.packageid,tblpricing.monthly from tblhosting + INNER JOIN tblinvoiceitems ON tblinvoiceitems.relid = tblhosting.id + JOIN tblpricing ON tblpricing.relid = tblhosting.packageid + WHERE tblpricing.type = 'product' AND tblinvoiceitems.invoiceid = :id"; + $pdo = Capsule::connection()->getPdo(); + $pdo->beginTransaction(); + $row = null; + $list = []; + try { + $statement = $pdo->prepare($query); + $statement->execute([':id' => $invoice_id]); + $row = $statement->fetchAll(); + $pdo->commit(); + } catch (\Throwable $th) { + $pdo->rollBack(); + logModuleCall('gofas_nfeio', 'erroGetProdictInvoice',$th , '', '', 'replaceVars'); + } + foreach ($row as $item) { + $pdo->beginTransaction(); + try { + $list2 = []; + $stmt = $pdo->prepare("SELECT val.value FROM tblcustomfields + INNER JOIN tblcustomfieldsvalues val ON val.fieldid = tblcustomfields.id + WHERE tblcustomfields.fieldname='Código de Serviço' AND tblcustomfields.type = 'product' + AND val.relid = :PROD"); + $stmt->execute([':PROD' => $item[0]]); + $row = $stmt->fetchAll(); + $pdo->commit(); + logModuleCall('gofas_nfeio', 'row itens',$row , '', '', 'replaceVars'); + $list2['item'] = $item['packageid']; + $list2['value'] = $row[0]['value']; + $list2['monthly'] = $item['monthly']; + $list[] = $list2; + } catch (\Throwable $th) { + $pdo->rollBack(); + logModuleCall('gofas_nfeio', 'erroForeach',$th , '', '', 'replaceVars'); + } + } + return $list; +} + +if ( !function_exists('set_code_service_camp_gofasnfeio') ) { + function set_code_service_camp_gofasnfeio() { + $pdo = Capsule::connection()->getPdo(); + $pdo->beginTransaction(); + try { + $statement = $pdo->prepare('ALTER TABLE gofasnfeio ADD service_code TEXT; + ALTER TABLE gofasnfeio ADD monthly DECIMAL(16,2)'); + $statement->execute(); + $pdo->commit(); + } catch (\Exception $e) { + $pdo->rollBack(); + } + } +} diff --git a/modules/addons/gofasnfeio/hooks.php b/modules/addons/gofasnfeio/hooks.php index 180884c..46a160d 100644 --- a/modules/addons/gofasnfeio/hooks.php +++ b/modules/addons/gofasnfeio/hooks.php @@ -6,6 +6,7 @@ add_hook('InvoiceCreation', 1, function($vars) { require_once __DIR__ . '/functions.php'; require_once __DIR__ . '/hooks/invoicecreation.php'; + require_once __DIR__ . '/hooks/aftercronjob.php'; }); //InvoicePaid add_hook('InvoicePaid', 1, function($vars) { diff --git a/modules/addons/gofasnfeio/hooks/admininvoicescontrolsoutput.php b/modules/addons/gofasnfeio/hooks/admininvoicescontrolsoutput.php index 98de2c8..769075b 100644 --- a/modules/addons/gofasnfeio/hooks/admininvoicescontrolsoutput.php +++ b/modules/addons/gofasnfeio/hooks/admininvoicescontrolsoutput.php @@ -17,7 +17,7 @@ $line_items[] = $value['description'];//substr( $value['description'], 0, 100); } $customer = gnfe_customer($invoice['userid'],$client); - $queue = gnfe_queue_nfe($vars['invoiceid'],'true'); + $queue = gnfe_queue_nfe($vars['invoiceid']); if ($queue !== 'success') { header_remove(); header('Location: ' . $gnfewhmcsadminurl . 'invoices.php?action=edit&id=' . $vars['invoiceid'] . '&gnfe_error=Erro ao criar nota fiscal: ' . $queue); diff --git a/modules/addons/gofasnfeio/hooks/aftercronjob.php b/modules/addons/gofasnfeio/hooks/aftercronjob.php index 01a74da..354a62e 100644 --- a/modules/addons/gofasnfeio/hooks/aftercronjob.php +++ b/modules/addons/gofasnfeio/hooks/aftercronjob.php @@ -1,11 +1,12 @@ orderBy('id', 'desc')->where('status', '=', 'Waiting')->take(1)->get( array( 'invoice_id' )) as $waiting ) { +foreach ( Capsule::table('gofasnfeio')->orderBy('id', 'desc')->where('status', '=', 'Waiting')->take(1)->get( ['invoice_id', 'service_code', 'monthly']) as $waiting ) { $data = getTodaysDate(false); $dataAtual = toMySQLDate($data); @@ -15,44 +16,40 @@ $getQuery = Capsule::table('tblinvoices')->where('id', '=', $waiting->invoice_id)->get( ['id', 'userid', 'total']); } - foreach( $getQuery as $invoices ) { - $invoice = localAPI('GetInvoice', array('invoiceid' => $waiting->invoice_id), false); - $client = localAPI('GetClientsDetails',array( '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; + 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; } $namePF = $client['fullname']; $name = $customer['doc_type'] == 2 ? $client['companyname'] : $namePF; $name = htmlspecialchars_decode($name); - - if(!strlen($customer['insc_municipal']) == 0) { - $postfields = array( - 'cityServiceCode' => $params['service_code'], + + if (!strlen($customer['insc_municipal']) == 0) { + $postfields = [ + 'cityServiceCode' => $waiting['service_code'], 'description' => substr(implode("\n", $line_items), 0, 600), - 'servicesAmount' => $invoice['total'], + 'servicesAmount' => $waiting['monthly'], 'borrower' => [ 'federalTaxNumber' => $customer['document'], 'municipalTaxNumber' => $customer['insc_municipal'], @@ -77,7 +74,7 @@ ]; } else { $postfields = [ - 'cityServiceCode' => $params['service_code'], + 'cityServiceCode' => $waiting['service_code'], 'description' => substr(implode("\n", $line_items), 0, 600), 'servicesAmount' => $invoice['total'], 'borrower' => [ @@ -104,6 +101,7 @@ } if ($params['debug']) { logModuleCall('gofas_nfeio', 'aftercronjob',$postfields , '', '', 'replaceVars'); + logModuleCall('gofas_nfeio', 'waiting',$waiting , '', '', 'replaceVars'); } $nfe = gnfe_issue_nfe($postfields); if ($nfe->message) { diff --git a/modules/addons/gofasnfeio/hooks/dailycronjob.php b/modules/addons/gofasnfeio/hooks/dailycronjob.php index 12878ad..7e02526 100644 --- a/modules/addons/gofasnfeio/hooks/dailycronjob.php +++ b/modules/addons/gofasnfeio/hooks/dailycronjob.php @@ -1,103 +1,107 @@ 0 ) { - foreach( Capsule::table('tblinvoices')->whereBetween('date', [$params['initial_date'], $dataAtual])->where('status', '=', 'Paid')->get( array( 'id', 'userid', 'datepaid','total' ) ) as $invoices ) { - $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,array('nfe_id', 'status', 'services_amount','created_at')); - $client = localAPI('GetClientsDetails',array( 'clientid' => $invoices->userid, 'stats' => false, ), false); - $invoice = localAPI('GetInvoice', array('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 ( $params['issue_note'] !== 'Manualmente' && $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')->get( ['invoice_id', 'service_code', 'monthly']) 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(); - $namePF = $client['fullname']; - $name = $customer['doc_type'] == 2 ? $client['companyname'] : $namePF; - $name = htmlspecialchars_decode($name); - if(!strlen($customer['insc_municipal']) == 0) { - $postfields = array( - 'cityServiceCode' => $params['service_code'], - 'description' => substr(implode("\n", $line_items), 0, 600), - 'servicesAmount' => $invoices->total, - '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' => $company['companies']['rpsSerialNumber'], - 'rpsNumber' => (int)$company['companies']['rpsNumber'] + 1, - ]; - } else { - $postfields = [ - 'cityServiceCode' => $params['service_code'], - 'description' => substr(implode("\n", $line_items), 0, 600), - 'servicesAmount' => $invoices->total, - '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' => $company['companies']['rpsSerialNumber'], - 'rpsNumber' => (int)$company['companies']['rpsNumber'] + 1, - ]; - } - if ($params['debug']) { - logModuleCall('gofas_nfeio', 'dailycronjob',$postfields , '', '', 'replaceVars'); - } - $waiting = array(); - foreach( Capsule::table('gofasnfeio') -> where( 'status', '=', 'Waiting' ) -> get( array( 'invoice_id', 'status') ) as $Waiting ) { - $waiting[] = $Waiting->invoice_id; - } - $queue = gnfe_queue_nfe($invoices->id); - if ($queue !== 'success') { - $error .= $queue; - } - if ($queue === 'success') { + $namePF = $client['fullname']; + $name = $customer['doc_type'] == 2 ? $client['companyname'] : $namePF; + $name = htmlspecialchars_decode($name); + if (!strlen($customer['insc_municipal']) == 0) { + $postfields = [ + 'cityServiceCode' => $nfeio['service_code'], + 'description' => substr(implode("\n", $line_items), 0, 600), + 'servicesAmount' => $nfeio['monthly'], + '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' => $company['companies']['rpsSerialNumber'], + 'rpsNumber' => (int)$company['companies']['rpsNumber'] + 1, + ]; + } else { + $postfields = [ + 'cityServiceCode' => $nfeio['service_code'], + 'description' => substr(implode("\n", $line_items), 0, 600), + 'servicesAmount' => $nfeio['monthly'], + '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' => $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($invoices->id); + if ($queue !== 'success') { + $error .= $queue; + } + if ($queue === 'success') { + } } } } diff --git a/modules/addons/gofasnfeio/hooks/invoicecreation.php b/modules/addons/gofasnfeio/hooks/invoicecreation.php index 88e6eb2..a66a907 100644 --- a/modules/addons/gofasnfeio/hooks/invoicecreation.php +++ b/modules/addons/gofasnfeio/hooks/invoicecreation.php @@ -1,33 +1,40 @@ $vars['invoiceid']), false); - if( (float)$invoice['total'] > (float)'0.00' and $invoice['status'] !== (string)'Draft' ) { - $nfe_for_invoice = gnfe_get_local_nfe($vars['invoiceid'],array('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') { - $client = localAPI('GetClientsDetails',array( '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']); - if($queue !== 'success') { - 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') {} - } - } +$itens = get_prodict_invoice(241); + +if ( stripos($params['issue_note'], 'Gerada') and (string)$vars['status'] !== (string)'Draft' and (!$params['issue_note_after'] or $params['issue_note_after'] === 0 )) { + $invoice = localAPI('GetInvoice', ['invoiceid' => $vars['invoiceid']], false); + foreach ($itens as $item) { + if ( (float)$item['monthly'] > (float)'0.00' and $invoice['status'] !== (string)'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') { + $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'],$item,true); + if ($queue !== 'success') { + 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') { + } + } + } + } } -if($params['debug']) { - logModuleCall('gofas_nfeio', 'InvoiceCreation', array('vars'=>$vars, 'gnfe_ibge'=> gnfe_ibge(preg_replace("/[^0-9]/", "", $client['postcode'])), 'postifields'=>$postifields), 'post', array( 'params'=>$params, 'invoice'=>$invoice, 'client'=> $client, 'queue' => $queue,'nfe_for_invoice'=> $nfe_for_invoice, 'company'=>$company ), 'replaceVars'); +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/output.php b/modules/addons/gofasnfeio/output.php index 9b7dfe3..be421db 100644 --- a/modules/addons/gofasnfeio/output.php +++ b/modules/addons/gofasnfeio/output.php @@ -161,7 +161,7 @@ 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'); + $queue = gnfe_queue_nfe($_REQUEST['invoice_id']); if ($queue !== 'success') { $message = '
    Erro ao salvar nota fiscal no DB: ' . $queue . '
    '; header_remove(); From a15e020797d62cd0428c761397389e2165e099e7 Mon Sep 17 00:00:00 2001 From: JoaoVictorLNacional Date: Mon, 14 Dec 2020 15:52:41 -0300 Subject: [PATCH 09/52] adicionado codigo individual por produto --- modules/addons/gofasnfeio/callback.php | 1 - modules/addons/gofasnfeio/functions.php | 11 ++++--- .../addons/gofasnfeio/hooks/aftercronjob.php | 31 ++++++++++++------- .../gofasnfeio/hooks/invoicecreation.php | 2 +- 4 files changed, 27 insertions(+), 18 deletions(-) diff --git a/modules/addons/gofasnfeio/callback.php b/modules/addons/gofasnfeio/callback.php index 8ad30ba..9e4309a 100644 --- a/modules/addons/gofasnfeio/callback.php +++ b/modules/addons/gofasnfeio/callback.php @@ -4,7 +4,6 @@ $post = json_decode(file_get_contents('php://input'), true); if ($post) { require_once __DIR__ . '/functions.php'; - altersFromUpdate(); $params = []; foreach ( Capsule::table('tbladdonmodules')->where( 'module', '=', 'gofasnfeio' )->get( ['setting', 'value'] ) as $settings ) { $params[$settings->setting] = $settings->value; diff --git a/modules/addons/gofasnfeio/functions.php b/modules/addons/gofasnfeio/functions.php index f983096..8eec219 100644 --- a/modules/addons/gofasnfeio/functions.php +++ b/modules/addons/gofasnfeio/functions.php @@ -50,6 +50,7 @@ function gnfe_customer($user_id,$client) { } } } + // Cliente possui CPF e CNPJ // CPF com 1 nº a menos, adiciona 0 antes do documento if ( strlen( $cpf_customfield_value ) === 10 ) { @@ -171,7 +172,6 @@ function gnfe_queue_nfe($invoice_id,$item,$create_all = false) { 'user_id' => $invoice['userid'], 'nfe_id' => 'waiting', 'status' => 'Waiting', - // 'services_amount' => $item['monthly'], 'environment' => 'waiting', 'flow_status' => 'waiting', @@ -180,7 +180,6 @@ function gnfe_queue_nfe($invoice_id,$item,$create_all = false) { 'updated_at' => 'waiting', 'rpsSerialNumber' => 'waiting', 'service_code' => $item['value'], - 'monthly' => $item['monthly'] ]; $nfe_for_invoice = gnfe_get_local_nfe($invoice_id, ['status']); @@ -189,7 +188,6 @@ function gnfe_queue_nfe($invoice_id,$item,$create_all = false) { if (!$nfe_for_invoice['status'] || $create_all) { try { $save_nfe = Capsule::table('gofasnfeio')->insert($data); - logModuleCall('gofas_nfeio', 'data gnfe_queue_nfe create',$data , '', '', 'replaceVars'); return 'success'; } catch (\Exception $e) { @@ -437,7 +435,7 @@ function gnfe_save_nfe($nfe,$user_id,$invoice_id,$pdf,$created_at,$updated_at) { } } if ( !function_exists('gnfe_update_nfe') ) { - function gnfe_update_nfe($nfe,$user_id,$invoice_id,$pdf,$created_at,$updated_at) { + function gnfe_update_nfe($nfe,$user_id,$invoice_id,$pdf,$created_at,$updated_at,$id_gofasnfeio) { $data = [ 'invoice_id' => $invoice_id, 'user_id' => $user_id, @@ -452,8 +450,11 @@ function gnfe_update_nfe($nfe,$user_id,$invoice_id,$pdf,$created_at,$updated_at) 'rpsSerialNumber' => $nfe->rpsSerialNumber, 'rpsNumber' => $nfe->rpsNumber, ]; + logModuleCall('gofas_nfeio', '$data',$data , '', '', 'replaceVars'); try { - $save_nfe = Capsule::table('gofasnfeio')->where('invoice_id', '=', $invoice_id)->update($data); + $save_nfe = Capsule::table('gofasnfeio')->where('id', '=', $id_gofasnfeio)->update($data); + logModuleCall('gofas_nfeio', 'save_nfe',$save_nfe , '', '', 'replaceVars'); + return 'success'; } catch (\Exception $e) { return $e->getMessage(); diff --git a/modules/addons/gofasnfeio/hooks/aftercronjob.php b/modules/addons/gofasnfeio/hooks/aftercronjob.php index 354a62e..95a7d27 100644 --- a/modules/addons/gofasnfeio/hooks/aftercronjob.php +++ b/modules/addons/gofasnfeio/hooks/aftercronjob.php @@ -6,7 +6,7 @@ use WHMCS\Database\Capsule; $params = gnfe_config(); -foreach ( Capsule::table('gofasnfeio')->orderBy('id', 'desc')->where('status', '=', 'Waiting')->take(1)->get( ['invoice_id', 'service_code', 'monthly']) as $waiting ) { +foreach ( Capsule::table('gofasnfeio')->orderBy('id', 'desc')->where('status', '=', 'Waiting')->where('invoice_id', '=', '302')->get( ['id', 'invoice_id', 'service_code', 'services_amount']) as $waiting ) { $data = getTodaysDate(false); $dataAtual = toMySQLDate($data); @@ -15,7 +15,6 @@ } 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); @@ -41,15 +40,21 @@ } 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; } - $namePF = $client['fullname']; - $name = $customer['doc_type'] == 2 ? $client['companyname'] : $namePF; + + 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']; + if (!strlen($customer['insc_municipal']) == 0) { $postfields = [ - 'cityServiceCode' => $waiting['service_code'], + 'cityServiceCode' => $service_code, 'description' => substr(implode("\n", $line_items), 0, 600), - 'servicesAmount' => $waiting['monthly'], + 'servicesAmount' => $waiting->services_amount, 'borrower' => [ 'federalTaxNumber' => $customer['document'], 'municipalTaxNumber' => $customer['insc_municipal'], @@ -74,9 +79,9 @@ ]; } else { $postfields = [ - 'cityServiceCode' => $waiting['service_code'], + 'cityServiceCode' => $service_code, 'description' => substr(implode("\n", $line_items), 0, 600), - 'servicesAmount' => $invoice['total'], + 'servicesAmount' => $waiting->services_amount, 'borrower' => [ 'federalTaxNumber' => $customer['document'], 'name' => $name, @@ -99,26 +104,30 @@ 'rpsNumber' => (int)$rps_number + 1, ]; } + logModuleCall('gofas_nfeio', 'rps_number', $rps_number, '', '', 'replaceVars'); + if ($params['debug']) { logModuleCall('gofas_nfeio', 'aftercronjob',$postfields , '', '', 'replaceVars'); - logModuleCall('gofas_nfeio', 'waiting',$waiting , '', '', 'replaceVars'); } $nfe = gnfe_issue_nfe($postfields); + logModuleCall('gofas_nfeio', 'nfe resp',$nfe , '', '', 'replaceVars'); + 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')); + $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 $gnfe_update_nfe !== 'success') { $error = $gnfe_update_nfe; } $update_rps = gnfe_update_rps($rps_serial_number_, $rps_number); + if ($update_rps and $update_rps !== 'success') { $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'); + // logModuleCall('gofas_nfeio', 'aftercronjob', ['$params' => $params, '$datepaid' => $datepaid, '$datepaid_to_issue' => $datepaid_to_issue], 'post', ['$processed_invoices' => $processed_invoices, '$nfe' => $nfe, 'error' => $error], 'replaceVars'); } } \ No newline at end of file diff --git a/modules/addons/gofasnfeio/hooks/invoicecreation.php b/modules/addons/gofasnfeio/hooks/invoicecreation.php index a66a907..a0d964d 100644 --- a/modules/addons/gofasnfeio/hooks/invoicecreation.php +++ b/modules/addons/gofasnfeio/hooks/invoicecreation.php @@ -4,7 +4,7 @@ } use WHMCS\Database\Capsule; $params = gnfe_config(); -$itens = get_prodict_invoice(241); +$itens = get_prodict_invoice($vars['invoiceid']); if ( stripos($params['issue_note'], 'Gerada') and (string)$vars['status'] !== (string)'Draft' and (!$params['issue_note_after'] or $params['issue_note_after'] === 0 )) { $invoice = localAPI('GetInvoice', ['invoiceid' => $vars['invoiceid']], false); From df3b2fb133f1550b0d6b462254aa933f7c480192 Mon Sep 17 00:00:00 2001 From: JoaoVictorLNacional Date: Mon, 14 Dec 2020 16:26:46 -0300 Subject: [PATCH 10/52] add script de codigo individual no callback e no daily cron job --- modules/addons/gofasnfeio/callback.php | 6 +++--- modules/addons/gofasnfeio/functions.php | 12 +++++++++-- modules/addons/gofasnfeio/hooks.php | 1 - .../addons/gofasnfeio/hooks/aftercronjob.php | 8 ++------ .../addons/gofasnfeio/hooks/dailycronjob.php | 20 ++++++++++++------- 5 files changed, 28 insertions(+), 19 deletions(-) diff --git a/modules/addons/gofasnfeio/callback.php b/modules/addons/gofasnfeio/callback.php index 9e4309a..ef621c7 100644 --- a/modules/addons/gofasnfeio/callback.php +++ b/modules/addons/gofasnfeio/callback.php @@ -9,7 +9,7 @@ $params[$settings->setting] = $settings->value; } foreach ( Capsule::table('gofasnfeio')->where('nfe_id', '=', $post['id'])-> - get(['invoice_id', 'user_id', 'nfe_id', 'status', 'services_amount', 'environment', 'flow_status', 'pdf', 'created_at', 'updated_at']) as $key => $value ) { + get(['id', 'invoice_id', 'user_id', 'nfe_id', 'status', 'services_amount', 'environment', 'flow_status', 'pdf', 'created_at', 'updated_at']) as $key => $value ) { $nfe_for_invoice[$key] = json_decode(json_encode($value), true); } $nfe = $nfe_for_invoice['0']; @@ -36,7 +36,7 @@ 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( ['invoice_id']) as $waiting ) { + foreach ( Capsule::table('gofasnfeio')->orderBy('id', 'desc')->where('status', '=', 'Waiting')->take(1)->get( ['id', 'invoice_id']) as $waiting ) { //$invoices[] = $Waiting->invoice_id; $data = getTodaysDate(false); $dataAtual = toMySQLDate($data); @@ -142,7 +142,7 @@ $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')); + $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 $gnfe_update_nfe !== 'success') { $error = $gnfe_update_nfe; } diff --git a/modules/addons/gofasnfeio/functions.php b/modules/addons/gofasnfeio/functions.php index 8eec219..f6e75e4 100644 --- a/modules/addons/gofasnfeio/functions.php +++ b/modules/addons/gofasnfeio/functions.php @@ -435,7 +435,7 @@ function gnfe_save_nfe($nfe,$user_id,$invoice_id,$pdf,$created_at,$updated_at) { } } if ( !function_exists('gnfe_update_nfe') ) { - function gnfe_update_nfe($nfe,$user_id,$invoice_id,$pdf,$created_at,$updated_at,$id_gofasnfeio) { + function gnfe_update_nfe($nfe,$user_id,$invoice_id,$pdf,$created_at,$updated_at,$id_gofasnfeio = false) { $data = [ 'invoice_id' => $invoice_id, 'user_id' => $user_id, @@ -452,7 +452,15 @@ function gnfe_update_nfe($nfe,$user_id,$invoice_id,$pdf,$created_at,$updated_at, ]; logModuleCall('gofas_nfeio', '$data',$data , '', '', 'replaceVars'); try { - $save_nfe = Capsule::table('gofasnfeio')->where('id', '=', $id_gofasnfeio)->update($data); + if (!$id_gofasnfeio) { + $id = $invoice_id; + $camp = 'invoice_id'; + } else { + $id = $id_gofasnfeio; + $camp = 'id'; + } + + $save_nfe = Capsule::table('gofasnfeio')->where($camp, '=',$id)->update($data); logModuleCall('gofas_nfeio', 'save_nfe',$save_nfe , '', '', 'replaceVars'); return 'success'; diff --git a/modules/addons/gofasnfeio/hooks.php b/modules/addons/gofasnfeio/hooks.php index 46a160d..180884c 100644 --- a/modules/addons/gofasnfeio/hooks.php +++ b/modules/addons/gofasnfeio/hooks.php @@ -6,7 +6,6 @@ add_hook('InvoiceCreation', 1, function($vars) { require_once __DIR__ . '/functions.php'; require_once __DIR__ . '/hooks/invoicecreation.php'; - require_once __DIR__ . '/hooks/aftercronjob.php'; }); //InvoicePaid add_hook('InvoicePaid', 1, function($vars) { diff --git a/modules/addons/gofasnfeio/hooks/aftercronjob.php b/modules/addons/gofasnfeio/hooks/aftercronjob.php index 95a7d27..c125b45 100644 --- a/modules/addons/gofasnfeio/hooks/aftercronjob.php +++ b/modules/addons/gofasnfeio/hooks/aftercronjob.php @@ -6,7 +6,7 @@ use WHMCS\Database\Capsule; $params = gnfe_config(); -foreach ( Capsule::table('gofasnfeio')->orderBy('id', 'desc')->where('status', '=', 'Waiting')->where('invoice_id', '=', '302')->get( ['id', 'invoice_id', 'service_code', 'services_amount']) as $waiting ) { +foreach ( Capsule::table('gofasnfeio')->orderBy('id', 'desc')->where('status', '=', 'Waiting')->take(1)->get( ['id', 'invoice_id', 'service_code', 'services_amount']) as $waiting ) { $data = getTodaysDate(false); $dataAtual = toMySQLDate($data); @@ -104,14 +104,10 @@ 'rpsNumber' => (int)$rps_number + 1, ]; } - logModuleCall('gofas_nfeio', 'rps_number', $rps_number, '', '', 'replaceVars'); - if ($params['debug']) { logModuleCall('gofas_nfeio', 'aftercronjob',$postfields , '', '', 'replaceVars'); } $nfe = gnfe_issue_nfe($postfields); - logModuleCall('gofas_nfeio', 'nfe resp',$nfe , '', '', 'replaceVars'); - if ($nfe->message) { $error .= $nfe->message; } @@ -128,6 +124,6 @@ } } 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'); + logModuleCall('gofas_nfeio', 'aftercronjob', ['$params' => $params, '$datepaid' => $datepaid, '$datepaid_to_issue' => $datepaid_to_issue], 'post', ['$processed_invoices' => $processed_invoices, '$nfe' => $nfe, 'error' => $error], 'replaceVars'); } } \ No newline at end of file diff --git a/modules/addons/gofasnfeio/hooks/dailycronjob.php b/modules/addons/gofasnfeio/hooks/dailycronjob.php index 7e02526..5dbe7b7 100644 --- a/modules/addons/gofasnfeio/hooks/dailycronjob.php +++ b/modules/addons/gofasnfeio/hooks/dailycronjob.php @@ -10,7 +10,7 @@ if ( $params['issue_note'] !== 'Manualmente' && $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')->get( ['invoice_id', 'service_code', 'monthly']) as $nfeio ) { + foreach ( Capsule::table('gofasnfeio')->where('status', '=', 'Waiting')->get( ['id', 'invoice_id', 'service_code', 'monthly', '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_)); @@ -32,14 +32,20 @@ }*/ $company = gnfe_get_company(); - $namePF = $client['fullname']; - $name = $customer['doc_type'] == 2 ? $client['companyname'] : $namePF; + 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']; + if (!strlen($customer['insc_municipal']) == 0) { $postfields = [ - 'cityServiceCode' => $nfeio['service_code'], + 'cityServiceCode' => $service_code, 'description' => substr(implode("\n", $line_items), 0, 600), - 'servicesAmount' => $nfeio['monthly'], + 'servicesAmount' => $waiting->services_amount, 'borrower' => [ 'federalTaxNumber' => $customer['document'], 'municipalTaxNumber' => $customer['insc_municipal'], @@ -64,9 +70,9 @@ ]; } else { $postfields = [ - 'cityServiceCode' => $nfeio['service_code'], + 'cityServiceCode' => $service_code, 'description' => substr(implode("\n", $line_items), 0, 600), - 'servicesAmount' => $nfeio['monthly'], + 'servicesAmount' => $waiting->services_amount, 'borrower' => [ 'federalTaxNumber' => $customer['document'], 'name' => $name, From 9c3f981b49115909fc977af0d145fcf4e3727017 Mon Sep 17 00:00:00 2001 From: JoaoVictorLNacional Date: Tue, 15 Dec 2020 12:33:17 -0300 Subject: [PATCH 11/52] =?UTF-8?q?finalizado=20e=20testado=20NFE=20individu?= =?UTF-8?q?al=20para=20cada=20produto=20automatico=20--falta=20modificar?= =?UTF-8?q?=20para=20a=20emiss=C3=A3o=20manual--?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- modules/addons/gofasnfeio/callback.php | 20 ++++++++++++------- .../addons/gofasnfeio/hooks/dailycronjob.php | 9 +++++---- 2 files changed, 18 insertions(+), 11 deletions(-) diff --git a/modules/addons/gofasnfeio/callback.php b/modules/addons/gofasnfeio/callback.php index ef621c7..2dd0809 100644 --- a/modules/addons/gofasnfeio/callback.php +++ b/modules/addons/gofasnfeio/callback.php @@ -36,7 +36,7 @@ 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']) as $waiting ) { + 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); @@ -74,15 +74,21 @@ $rps_number = 0; } - $namePF = $client['fullname']; - $name = $customer['doc_type'] == 2 ? $client['companyname'] : $namePF; + 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']; + if (!strlen($customer['insc_municipal']) == 0) { $postfields = [ - 'cityServiceCode' => $params['service_code'], + 'cityServiceCode' => $service_code, 'description' => substr(implode("\n", $line_items), 0, 600), - 'servicesAmount' => $invoice['total'], + 'servicesAmount' => $waiting->services_amount, 'borrower' => [ 'federalTaxNumber' => $customer['document'], 'municipalTaxNumber' => $customer['insc_municipal'], @@ -107,9 +113,9 @@ ]; } else { $postfields = [ - 'cityServiceCode' => $params['service_code'], + 'cityServiceCode' => $service_code, 'description' => substr(implode("\n", $line_items), 0, 600), - 'servicesAmount' => $invoice['total'], + 'servicesAmount' => $waiting->services_amount, 'borrower' => [ 'federalTaxNumber' => $customer['document'], 'name' => $name, diff --git a/modules/addons/gofasnfeio/hooks/dailycronjob.php b/modules/addons/gofasnfeio/hooks/dailycronjob.php index 5dbe7b7..b62986f 100644 --- a/modules/addons/gofasnfeio/hooks/dailycronjob.php +++ b/modules/addons/gofasnfeio/hooks/dailycronjob.php @@ -10,10 +10,11 @@ if ( $params['issue_note'] !== 'Manualmente' && $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')->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', 'invoice_id', 'service_code', 'monthly', '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_)); + //ver isso com varios registros $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); @@ -39,13 +40,13 @@ } $name = htmlspecialchars_decode($name); - $service_code = $waiting->service_code ? $waiting->service_code : $params['service_code']; + $service_code = $nfeio->service_code ? $nfeio->service_code : $params['service_code']; if (!strlen($customer['insc_municipal']) == 0) { $postfields = [ 'cityServiceCode' => $service_code, 'description' => substr(implode("\n", $line_items), 0, 600), - 'servicesAmount' => $waiting->services_amount, + 'servicesAmount' => $nfeio->services_amount, 'borrower' => [ 'federalTaxNumber' => $customer['document'], 'municipalTaxNumber' => $customer['insc_municipal'], @@ -72,7 +73,7 @@ $postfields = [ 'cityServiceCode' => $service_code, 'description' => substr(implode("\n", $line_items), 0, 600), - 'servicesAmount' => $waiting->services_amount, + 'servicesAmount' => $nfeio->services_amount, 'borrower' => [ 'federalTaxNumber' => $customer['document'], 'name' => $name, From b052c969d1d60da558fe56def206b4eb06b0c01a Mon Sep 17 00:00:00 2001 From: JoaoVictorLNacional Date: Wed, 16 Dec 2020 10:59:15 -0300 Subject: [PATCH 12/52] modificado para criar a NFE com codigo de servico para cada produto quando for manual --- modules/addons/gofasnfeio/functions.php | 101 +++++++++++++++--- .../hooks/admininvoicescontrolsoutput.php | 2 +- .../addons/gofasnfeio/hooks/dailycronjob.php | 2 +- .../gofasnfeio/hooks/invoicecreation.php | 44 ++++---- .../addons/gofasnfeio/hooks/invoicepaid.php | 49 +++++---- modules/addons/gofasnfeio/output.php | 2 +- 6 files changed, 136 insertions(+), 64 deletions(-) diff --git a/modules/addons/gofasnfeio/functions.php b/modules/addons/gofasnfeio/functions.php index f6e75e4..215540d 100644 --- a/modules/addons/gofasnfeio/functions.php +++ b/modules/addons/gofasnfeio/functions.php @@ -165,46 +165,115 @@ function gnfe_ibge($zip) { } } if ( !function_exists('gnfe_queue_nfe') ) { - function gnfe_queue_nfe($invoice_id,$item,$create_all = false) { + function gnfe_queue_nfe($invoice_id,$create_all = false) { $invoice = localAPI('GetInvoice', ['invoiceid' => $invoice_id], false); + $itens = get_prodict_invoice($invoice_id); + logModuleCall('gofas_nfeio', 'gnfe_queue_nfe itens',$itens, '', '', 'replaceVars'); + + foreach ($itens as $item) { + $data = [ + 'invoice_id' => $invoice_id, + 'user_id' => $invoice['userid'], + 'nfe_id' => 'waiting', + 'status' => 'Waiting', + 'services_amount' => $item['monthly'], + 'environment' => 'waiting', + 'flow_status' => 'waiting', + 'pdf' => 'waiting', + 'created_at' => date('Y-m-d H:i:s'), + 'updated_at' => 'waiting', + 'rpsSerialNumber' => 'waiting', + 'service_code' => $item['value'], + ]; + + $nfe_for_invoice = gnfe_get_local_nfe($invoice_id, ['status']); + if (!$nfe_for_invoice['status'] || $create_all) { + try { + $save_nfe = Capsule::table('gofasnfeio')->insert($data); + $create_all = true; + logModuleCall('gofas_nfeio', 'save_nfe var',$save_nfe , '', '', 'replaceVars'); + logModuleCall('gofas_nfeio', 'save_nfe',$data , '', '', 'replaceVars'); + } catch (\Exception $e) { + return $e->getMessage(); + } + } elseif ((string)$nfe_for_invoice['status'] === (string)'Cancelled' or (string)$nfe_for_invoice['status'] === (string)'Error') { + try { + $update_nfe = Capsule::table('gofasnfeio')->where('invoice_id', '=', $invoice_id)->update($data); + } catch (\Exception $e) { + return $e->getMessage(); + } + } + } + return 'success'; + } +} + +if ( !function_exists('gnfe_queue_nfe_edit') ) { + function gnfe_queue_nfe_edit($invoice_id,$gofasnfeio_id) { + $invoice = localAPI('GetInvoice', ['invoiceid' => $invoice_id], false); + $itens = get_prodict_invoice($invoice_id); + logModuleCall('gofas_nfeio', 'gnfe_queue_nfe itens',$itens, '', '', 'replaceVars'); + + foreach ($itens as $item) { + $data = [ + 'invoice_id' => $invoice_id, + 'user_id' => $invoice['userid'], + 'nfe_id' => 'waiting', + 'status' => 'Waiting', + 'services_amount' => $item['monthly'], + 'environment' => 'waiting', + 'flow_status' => 'waiting', + 'pdf' => 'waiting', + 'created_at' => date('Y-m-d H:i:s'), + 'updated_at' => 'waiting', + 'rpsSerialNumber' => 'waiting', + 'service_code' => $item['value'], + ]; + + $nfe_for_invoice = gnfe_get_local_nfe($invoice_id, ['status']); + + if ((string)$nfe_for_invoice['status'] === (string)'Cancelled' or (string)$nfe_for_invoice['status'] === (string)'Error') { + try { + $update_nfe = Capsule::table('gofasnfeio')->where('invoice_id', '=', $invoice_id)->where('id', '=', $gofasnfeio_id)->update($data); + } catch (\Exception $e) { + return $e->getMessage(); + } + } + } + return 'success'; + } +} + +if ( !function_exists('gnfe_queue_nfe_edit_all') ) { + function gnfe_queue_nfe_edit_all($invoice_id) { + $invoice = localAPI('GetInvoice', ['invoiceid' => $invoice_id], false); + $data = [ 'invoice_id' => $invoice_id, 'user_id' => $invoice['userid'], 'nfe_id' => 'waiting', 'status' => 'Waiting', - 'services_amount' => $item['monthly'], 'environment' => 'waiting', 'flow_status' => 'waiting', 'pdf' => 'waiting', 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => 'waiting', 'rpsSerialNumber' => 'waiting', - 'service_code' => $item['value'], ]; $nfe_for_invoice = gnfe_get_local_nfe($invoice_id, ['status']); - logModuleCall('gofas_nfeio', 'nfe_for_invoice',$nfe_for_invoice , '', '', 'replaceVars'); - - if (!$nfe_for_invoice['status'] || $create_all) { - try { - $save_nfe = Capsule::table('gofasnfeio')->insert($data); - return 'success'; - } catch (\Exception $e) { - return $e->getMessage(); - } - } elseif ((string)$nfe_for_invoice['status'] === (string)'Cancelled' or (string)$nfe_for_invoice['status'] === (string)'Error') { + if ((string)$nfe_for_invoice['status'] === (string)'Cancelled' or (string)$nfe_for_invoice['status'] === (string)'Error') { try { - logModuleCall('gofas_nfeio', 'data gnfe_queue_nfe update',$data , '', '', 'replaceVars'); - $update_nfe = Capsule::table('gofasnfeio')->where('invoice_id', '=', $invoice_id)->update($data); - return 'success'; } catch (\Exception $e) { return $e->getMessage(); } } + return 'success'; } } + if ( !function_exists('gnfe_issue_nfe') ) { function gnfe_issue_nfe($postfields) { $webhook_url = gnfe_whmcs_url() . 'modules/addons/gofasnfeio/callback.php'; diff --git a/modules/addons/gofasnfeio/hooks/admininvoicescontrolsoutput.php b/modules/addons/gofasnfeio/hooks/admininvoicescontrolsoutput.php index 769075b..15ea90c 100644 --- a/modules/addons/gofasnfeio/hooks/admininvoicescontrolsoutput.php +++ b/modules/addons/gofasnfeio/hooks/admininvoicescontrolsoutput.php @@ -17,7 +17,7 @@ $line_items[] = $value['description'];//substr( $value['description'], 0, 100); } $customer = gnfe_customer($invoice['userid'],$client); - $queue = gnfe_queue_nfe($vars['invoiceid']); + $queue = gnfe_queue_nfe($vars['invoiceid'],true); if ($queue !== 'success') { header_remove(); header('Location: ' . $gnfewhmcsadminurl . 'invoices.php?action=edit&id=' . $vars['invoiceid'] . '&gnfe_error=Erro ao criar nota fiscal: ' . $queue); diff --git a/modules/addons/gofasnfeio/hooks/dailycronjob.php b/modules/addons/gofasnfeio/hooks/dailycronjob.php index b62986f..ab81155 100644 --- a/modules/addons/gofasnfeio/hooks/dailycronjob.php +++ b/modules/addons/gofasnfeio/hooks/dailycronjob.php @@ -103,7 +103,7 @@ foreach ( Capsule::table('gofasnfeio')->where( 'status', '=', 'Waiting' )->get( ['invoice_id', 'status'] ) as $Waiting ) { $waiting[] = $Waiting->invoice_id; } - $queue = gnfe_queue_nfe($invoices->id); + $queue = gnfe_queue_nfe_edit($invoices->id,$nfeio->id); if ($queue !== 'success') { $error .= $queue; } diff --git a/modules/addons/gofasnfeio/hooks/invoicecreation.php b/modules/addons/gofasnfeio/hooks/invoicecreation.php index a0d964d..d9765c7 100644 --- a/modules/addons/gofasnfeio/hooks/invoicecreation.php +++ b/modules/addons/gofasnfeio/hooks/invoicecreation.php @@ -4,34 +4,32 @@ } use WHMCS\Database\Capsule; $params = gnfe_config(); -$itens = get_prodict_invoice($vars['invoiceid']); if ( stripos($params['issue_note'], 'Gerada') and (string)$vars['status'] !== (string)'Draft' and (!$params['issue_note_after'] or $params['issue_note_after'] === 0 )) { $invoice = localAPI('GetInvoice', ['invoiceid' => $vars['invoiceid']], false); - foreach ($itens as $item) { - if ( (float)$item['monthly'] > (float)'0.00' and $invoice['status'] !== (string)'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') { - $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'],$item,true); - if ($queue !== 'success') { - 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') { + if ( (float)$invoice['total'] > (float)'0.00' and $invoice['status'] !== (string)'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') { + $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') { + 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') { + } } } } diff --git a/modules/addons/gofasnfeio/hooks/invoicepaid.php b/modules/addons/gofasnfeio/hooks/invoicepaid.php index cdf91cf..2166937 100644 --- a/modules/addons/gofasnfeio/hooks/invoicepaid.php +++ b/modules/addons/gofasnfeio/hooks/invoicepaid.php @@ -1,26 +1,31 @@ $vars['invoiceid']), false); - if( (float)$invoice['total'] > (float)'0.00' and $invoice['status'] !== (string)'Draft' ) { - $nfe_for_invoice = gnfe_get_local_nfe($vars['invoiceid'],array('nfe_id', 'status', 'services_amount')); - if($nfe_for_invoice['status'] !== (string)'Created' or $nfe_for_invoice['status'] !== (string)'Issued') { - $client = localAPI('GetClientsDetails',array( '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']); - if($queue !== 'success') { - 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') {} - } - } +logModuleCall('gofas_nfeio', 'vars',$vars , '', '', 'replaceVars'); + +if ( stripos($params['issue_note'], 'Paga') and (string)$vars['status'] !== (string)'Draft' and (!$params['issue_note_after'] or $params['issue_note_after'] === 0 )) { + $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') { + $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_edit_all($vars['invoiceid']); + if ($queue !== 'success') { + 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') { + } + } + } } -if($params['debug']) { - logModuleCall('gofas_nfeio', 'InvoicePaid', array('vars'=>$vars, 'gnfe_ibge'=> gnfe_ibge(preg_replace("/[^0-9]/", "", $client['postcode']))), 'post', array( 'params'=>$params, 'invoice'=>$invoice, 'client'=> $client, 'queue'=>$queue, 'nfe_for_invoice'=> $nfe_for_invoice, ), 'replaceVars'); +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/output.php b/modules/addons/gofasnfeio/output.php index be421db..3b4dcb9 100644 --- a/modules/addons/gofasnfeio/output.php +++ b/modules/addons/gofasnfeio/output.php @@ -161,7 +161,7 @@ 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']); + $queue = gnfe_queue_nfe($_REQUEST['invoice_id'],true); if ($queue !== 'success') { $message = '
    Erro ao salvar nota fiscal no DB: ' . $queue . '
    '; header_remove(); From ca782f95d04558e16eaf9d69b79c2cd7637e1659 Mon Sep 17 00:00:00 2001 From: JoaoVictorLNacional Date: Wed, 16 Dec 2020 17:02:02 -0300 Subject: [PATCH 13/52] =?UTF-8?q?mod=20para=20se=20a=20venda=20tiver=202?= =?UTF-8?q?=20produtos=20com=20o=20mesmo=20codigo=20de=20servi=C3=A7o=20en?= =?UTF-8?q?viar=20para=20a=20NFE=20como=20um=20--precisa=20testar=20outras?= =?UTF-8?q?=20condi=C3=A7=C3=B5es=20de=20emiss=C3=A3o=20de=20NFE--?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- modules/addons/gofasnfeio/callback.php | 2 + modules/addons/gofasnfeio/config.php | 8 +++- modules/addons/gofasnfeio/functions.php | 45 ++++++++++++++----- .../addons/gofasnfeio/hooks/dailycronjob.php | 2 + 4 files changed, 46 insertions(+), 11 deletions(-) diff --git a/modules/addons/gofasnfeio/callback.php b/modules/addons/gofasnfeio/callback.php index 2dd0809..b99d7a4 100644 --- a/modules/addons/gofasnfeio/callback.php +++ b/modules/addons/gofasnfeio/callback.php @@ -3,6 +3,8 @@ use WHMCS\Database\Capsule; $post = json_decode(file_get_contents('php://input'), true); if ($post) { + logModuleCall('gofas_nfeio', 'post resp',$post , '', '', 'replaceVars'); + require_once __DIR__ . '/functions.php'; $params = []; foreach ( Capsule::table('tbladdonmodules')->where( 'module', '=', 'gofasnfeio' )->get( ['setting', 'value'] ) as $settings ) { diff --git a/modules/addons/gofasnfeio/config.php b/modules/addons/gofasnfeio/config.php index 7e349c6..bc9a903 100644 --- a/modules/addons/gofasnfeio/config.php +++ b/modules/addons/gofasnfeio/config.php @@ -225,11 +225,17 @@ function gnfe_verifyInstall() { 'Options' => gnfe_customfields_dropdow(), 'Description' => 'Escolha o campo personalizado de Inscrição Municipal']]; + $tax = ['tax' => [ + 'FriendlyName' => 'Aplicar imposto automaticamente em todos os produtos ?', + 'Type' => 'radio', + 'Options' => 'Sim,Não', + 'Default' => 'Sim', + ]]; $footer = ['footer' => [ 'FriendlyName' => '', 'Description' => '© ' . date('Y') . ' Suporte módulo', ]]; - $fields = array_merge($intro,$api_key,$company_id,$service_code,$rps_serial_number,$rps_number,$issue_note,$issue_note_after,$gnfe_email_nfe_config,$cancel_invoice_cancel_nfe,$debug,$insc_municipal,$footer); + $fields = array_merge($intro,$api_key,$company_id,$service_code,$rps_serial_number,$rps_number,$issue_note,$issue_note_after,$gnfe_email_nfe_config,$cancel_invoice_cancel_nfe,$debug,$insc_municipal,$tax,$footer); $configarray = [ 'name' => 'NFE.io', 'description' => 'Módulo Nota Fiscal NFE.io para WHMCS', diff --git a/modules/addons/gofasnfeio/functions.php b/modules/addons/gofasnfeio/functions.php index 215540d..cc41de8 100644 --- a/modules/addons/gofasnfeio/functions.php +++ b/modules/addons/gofasnfeio/functions.php @@ -168,8 +168,29 @@ function gnfe_ibge($zip) { function gnfe_queue_nfe($invoice_id,$create_all = false) { $invoice = localAPI('GetInvoice', ['invoiceid' => $invoice_id], false); $itens = get_prodict_invoice($invoice_id); - logModuleCall('gofas_nfeio', 'gnfe_queue_nfe itens',$itens, '', '', 'replaceVars'); - + if (!$itens) { + foreach (Capsule::table('tblinvoiceitems')->where( 'invoiceid', '=', $invoice_id )->get( ['userid', 'amount']) as $item_not_salle) { + $data = [ + 'invoice_id' => $invoice_id, + 'user_id' => $item_not_salle->userid, + 'nfe_id' => 'waiting', + 'status' => 'Waiting', + 'services_amount' => $item_not_salle->amount, + 'environment' => 'waiting', + 'flow_status' => 'waiting', + 'pdf' => 'waiting', + 'created_at' => date('Y-m-d H:i:s'), + 'updated_at' => 'waiting', + 'rpsSerialNumber' => 'waiting', + ]; + try { + $save_nfe = Capsule::table('gofasnfeio')->insert($data); + } catch (\Exception $e) { + return $e->getMessage(); + } + } + return 'success'; + } foreach ($itens as $item) { $data = [ 'invoice_id' => $invoice_id, @@ -188,11 +209,18 @@ function gnfe_queue_nfe($invoice_id,$create_all = false) { $nfe_for_invoice = gnfe_get_local_nfe($invoice_id, ['status']); if (!$nfe_for_invoice['status'] || $create_all) { + $create_all = true; try { - $save_nfe = Capsule::table('gofasnfeio')->insert($data); - $create_all = true; - logModuleCall('gofas_nfeio', 'save_nfe var',$save_nfe , '', '', 'replaceVars'); - logModuleCall('gofas_nfeio', 'save_nfe',$data , '', '', 'replaceVars'); + $service_code_row = Capsule::table('gofasnfeio')->where('service_code', '=', $item['value'])->where('invoice_id', '=', $invoice_id)->get(['id', 'services_amount']); + + if (count($service_code_row) == 1) { + $mountDB = floatval($service_code_row[0]->services_amount); + $mount_item = floatval($item['monthly']); + $mount = $mountDB + $mount_item; + $update_nfe = Capsule::table('gofasnfeio')->where('id', '=', $service_code_row[0]->id)->update(['services_amount' => $mount]); + } else { + $save_nfe = Capsule::table('gofasnfeio')->insert($data); + } } catch (\Exception $e) { return $e->getMessage(); } @@ -212,7 +240,6 @@ function gnfe_queue_nfe($invoice_id,$create_all = false) { function gnfe_queue_nfe_edit($invoice_id,$gofasnfeio_id) { $invoice = localAPI('GetInvoice', ['invoiceid' => $invoice_id], false); $itens = get_prodict_invoice($invoice_id); - logModuleCall('gofas_nfeio', 'gnfe_queue_nfe itens',$itens, '', '', 'replaceVars'); foreach ($itens as $item) { $data = [ @@ -328,6 +355,7 @@ function gnfe_issue_nfe($postfields) { curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); $response = curl_exec ($curl); curl_close ($curl); + logModuleCall('gofas_nfeio', 'resp',$response , '', '', 'replaceVars'); return json_decode(json_encode(json_decode($response))); } } @@ -528,10 +556,7 @@ function gnfe_update_nfe($nfe,$user_id,$invoice_id,$pdf,$created_at,$updated_at, $id = $id_gofasnfeio; $camp = 'id'; } - $save_nfe = Capsule::table('gofasnfeio')->where($camp, '=',$id)->update($data); - logModuleCall('gofas_nfeio', 'save_nfe',$save_nfe , '', '', 'replaceVars'); - return 'success'; } catch (\Exception $e) { return $e->getMessage(); diff --git a/modules/addons/gofasnfeio/hooks/dailycronjob.php b/modules/addons/gofasnfeio/hooks/dailycronjob.php index ab81155..f6c704c 100644 --- a/modules/addons/gofasnfeio/hooks/dailycronjob.php +++ b/modules/addons/gofasnfeio/hooks/dailycronjob.php @@ -96,6 +96,8 @@ 'rpsNumber' => (int)$company['companies']['rpsNumber'] + 1, ]; } + logModuleCall('gofas_nfeio', 'postfields daily',$postfields , '', '', 'replaceVars'); + if ($params['debug']) { logModuleCall('gofas_nfeio', 'dailycronjob',$postfields , '', '', 'replaceVars'); } From bec08c26aa4675b00b0a1c12dfd192a8ee33b7ad Mon Sep 17 00:00:00 2001 From: JoaoVictorLNacional Date: Thu, 17 Dec 2020 16:21:43 -0300 Subject: [PATCH 14/52] =?UTF-8?q?alterado=20os=20bot=C3=B5es=20do=20invoic?= =?UTF-8?q?e=20para=20executar=20com=20todas=20as=20notas=20fiscais=20emit?= =?UTF-8?q?idas(visualizar=20e=20cancelar)=20--falta=20o=20enviar=20email-?= =?UTF-8?q?-?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- modules/addons/gofasnfeio/callback.php | 8 +++- modules/addons/gofasnfeio/functions.php | 10 ++++- .../hooks/admininvoicescontrolsoutput.php | 45 ++++++++++++------- .../addons/gofasnfeio/hooks/aftercronjob.php | 8 +++- .../addons/gofasnfeio/hooks/dailycronjob.php | 8 +++- 5 files changed, 56 insertions(+), 23 deletions(-) diff --git a/modules/addons/gofasnfeio/callback.php b/modules/addons/gofasnfeio/callback.php index b99d7a4..5b8eb3f 100644 --- a/modules/addons/gofasnfeio/callback.php +++ b/modules/addons/gofasnfeio/callback.php @@ -86,10 +86,14 @@ $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 referednte a fatura #' . $waiting->invoice_id . ' ' . $gnfewhmcsadminurl . 'viewinvoice.php?id=' . $waiting->invoice_id; if (!strlen($customer['insc_municipal']) == 0) { $postfields = [ 'cityServiceCode' => $service_code, - 'description' => substr(implode("\n", $line_items), 0, 600), + 'description' => $desc, 'servicesAmount' => $waiting->services_amount, 'borrower' => [ 'federalTaxNumber' => $customer['document'], @@ -116,7 +120,7 @@ } else { $postfields = [ 'cityServiceCode' => $service_code, - 'description' => substr(implode("\n", $line_items), 0, 600), + 'description' => $desc, 'servicesAmount' => $waiting->services_amount, 'borrower' => [ 'federalTaxNumber' => $customer['document'], diff --git a/modules/addons/gofasnfeio/functions.php b/modules/addons/gofasnfeio/functions.php index cc41de8..d262075 100644 --- a/modules/addons/gofasnfeio/functions.php +++ b/modules/addons/gofasnfeio/functions.php @@ -184,7 +184,15 @@ function gnfe_queue_nfe($invoice_id,$create_all = false) { 'rpsSerialNumber' => 'waiting', ]; try { - $save_nfe = Capsule::table('gofasnfeio')->insert($data); + $service_code_row = Capsule::table('gofasnfeio')->whereNull('service_code')->where('invoice_id', '=', $invoice_id)->get(['id', 'services_amount']); + if (count($service_code_row) == 1) { + $mountDB = floatval($service_code_row[0]->services_amount); + $mount_item = floatval($item_not_salle->monthly); + $mount = $mountDB + $mount_item; + $update_nfe = Capsule::table('gofasnfeio')->where('id', '=', $service_code_row[0]->id)->update(['services_amount' => $mount]); + } else { + $save_nfe = Capsule::table('gofasnfeio')->insert($data); + } } catch (\Exception $e) { return $e->getMessage(); } diff --git a/modules/addons/gofasnfeio/hooks/admininvoicescontrolsoutput.php b/modules/addons/gofasnfeio/hooks/admininvoicescontrolsoutput.php index 15ea90c..23d5375 100644 --- a/modules/addons/gofasnfeio/hooks/admininvoicescontrolsoutput.php +++ b/modules/addons/gofasnfeio/hooks/admininvoicescontrolsoutput.php @@ -31,29 +31,42 @@ } } } + +if ($_REQUEST['gnfe_open']) { + logModuleCall('gofas_nfeio', '_REQUEST gnfe_open',$_REQUEST['gnfe_open'] , '', '', 'replaceVars'); + foreach (Capsule::table('gofasnfeio')->where( 'invoice_id', '=',$_REQUEST['gnfe_open'] )->get( ['id', 'nfe_id']) as $nfe) { + $url = 'https://app.nfe.io/companies/' . $params['company_id'] . '/service-invoices/' . $nfe->nfe_id; + echo ""; + } +} + if ($_REQUEST['gnfe_cancel']) { - $delete_nfe = gnfe_delete_nfe($_REQUEST['gnfe_cancel']); + 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) { + $message = '
    ' . $delete_nfe->message . '
    '; + header_remove(); + header('Location: ' . $gnfewhmcsadminurl . 'invoices.php?action=edit&id=' . $vars['invoiceid'] . '&gnfe_message=' . base64_encode(urlencode($message))); + return ''; + } + } if (!$delete_nfe->message) { $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(); header('Location: ' . $gnfewhmcsadminurl . 'invoices.php?action=edit&id=' . $vars['invoiceid'] . '&gnfe_message=' . base64_encode(urlencode($message)) ); - exit; - } - if ($delete_nfe->message) { - $message = '
    ' . $delete_nfe->message . '
    '; - header_remove(); - header('Location: ' . $gnfewhmcsadminurl . 'invoices.php?action=edit&id=' . $vars['invoiceid'] . '&gnfe_message=' . base64_encode(urlencode($message))); - exit; + return ''; } } if ($_REQUEST['gnfe_email']) { - $gnfe_email = gnfe_email_nfe($_REQUEST['gnfe_email']); - if (!$gnfe_email->message) { - $message = '
    Email Enviado com Sucesso
    '; - header_remove(); - header('Location: ' . $gnfewhmcsadminurl . 'invoices.php?action=edit&id=' . $vars['invoiceid'] . '&gnfe_message=' . base64_encode(urlencode($message))); - exit; + 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) { + $message = '
    Email Enviado com Sucesso
    '; + header_remove(); + header('Location: ' . $gnfewhmcsadminurl . 'invoices.php?action=edit&id=' . $vars['invoiceid'] . '&gnfe_message=' . base64_encode(urlencode($message))); + exit; + } } if ($gnfe_email->message) { $message = '
    ' . $gnfe_email->message . '
    '; @@ -97,9 +110,9 @@ echo '
    '; echo '
    Nota Fiscal:' . $invoice_nfe . '
    '; echo 'Emitir NFE'; -echo 'Visualizar NFE'; +echo 'Visualizar NFE'; echo 'Cancelar NFE'; -echo 'Enviar Email'; +echo 'Enviar Email'; echo '
    '; if ($_REQUEST['gnfe_error']) { diff --git a/modules/addons/gofasnfeio/hooks/aftercronjob.php b/modules/addons/gofasnfeio/hooks/aftercronjob.php index c125b45..23ec887 100644 --- a/modules/addons/gofasnfeio/hooks/aftercronjob.php +++ b/modules/addons/gofasnfeio/hooks/aftercronjob.php @@ -50,10 +50,14 @@ $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 referednte a fatura #' . $waiting->invoice_id . ' ' . $gnfewhmcsadminurl . 'viewinvoice.php?id=' . $waiting->invoice_id; if (!strlen($customer['insc_municipal']) == 0) { $postfields = [ 'cityServiceCode' => $service_code, - 'description' => substr(implode("\n", $line_items), 0, 600), + 'description' => $desc, 'servicesAmount' => $waiting->services_amount, 'borrower' => [ 'federalTaxNumber' => $customer['document'], @@ -80,7 +84,7 @@ } else { $postfields = [ 'cityServiceCode' => $service_code, - 'description' => substr(implode("\n", $line_items), 0, 600), + 'description' => $desc, 'servicesAmount' => $waiting->services_amount, 'borrower' => [ 'federalTaxNumber' => $customer['document'], diff --git a/modules/addons/gofasnfeio/hooks/dailycronjob.php b/modules/addons/gofasnfeio/hooks/dailycronjob.php index f6c704c..1427b1e 100644 --- a/modules/addons/gofasnfeio/hooks/dailycronjob.php +++ b/modules/addons/gofasnfeio/hooks/dailycronjob.php @@ -42,10 +42,14 @@ $service_code = $nfeio->service_code ? $nfeio->service_code : $params['service_code']; + foreach ( Capsule::table('tblconfiguration')->where('setting', '=', 'Domain')->get( ['value'] ) as $gnfewhmcsadminurl) { + $gnfewhmcsadminurl = $gnfewhmcsadminurl->value; + } + $desc = 'Nota referednte a fatura #' . $nfeio->invoice_id . ' ' . $gnfewhmcsadminurl . 'viewinvoice.php?id=' . $waiting->invoice_id; if (!strlen($customer['insc_municipal']) == 0) { $postfields = [ 'cityServiceCode' => $service_code, - 'description' => substr(implode("\n", $line_items), 0, 600), + 'description' => $desc, 'servicesAmount' => $nfeio->services_amount, 'borrower' => [ 'federalTaxNumber' => $customer['document'], @@ -72,7 +76,7 @@ } else { $postfields = [ 'cityServiceCode' => $service_code, - 'description' => substr(implode("\n", $line_items), 0, 600), + 'description' => $desc, 'servicesAmount' => $nfeio->services_amount, 'borrower' => [ 'federalTaxNumber' => $customer['document'], From 853955d85e302ca8f8aff57547c08ef887ef92fa Mon Sep 17 00:00:00 2001 From: JoaoVictorLNacional Date: Mon, 21 Dec 2020 10:48:10 -0300 Subject: [PATCH 15/52] =?UTF-8?q?alterado=20a=20descri=C3=A7=C3=A3o=20da?= =?UTF-8?q?=20NFE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- modules/addons/gofasnfeio/callback.php | 2 +- modules/addons/gofasnfeio/functions.php | 5 ++++- modules/addons/gofasnfeio/hooks/aftercronjob.php | 2 +- modules/addons/gofasnfeio/hooks/dailycronjob.php | 3 +-- 4 files changed, 7 insertions(+), 5 deletions(-) diff --git a/modules/addons/gofasnfeio/callback.php b/modules/addons/gofasnfeio/callback.php index 5b8eb3f..02f5f1e 100644 --- a/modules/addons/gofasnfeio/callback.php +++ b/modules/addons/gofasnfeio/callback.php @@ -89,7 +89,7 @@ foreach ( Capsule::table('tblconfiguration')->where('setting', '=', 'Domain')->get( ['value'] ) as $gnfewhmcsadminurl) { $gnfewhmcsadminurl = $gnfewhmcsadminurl->value; } - $desc = 'Nota referednte a fatura #' . $waiting->invoice_id . ' ' . $gnfewhmcsadminurl . 'viewinvoice.php?id=' . $waiting->invoice_id; + $desc = 'Nota referednte a fatura #' . $waiting->invoice_id . ' ' . $gnfewhmcsadminurl . 'viewinvoice.php?id=' . $waiting->invoice_id . ' '; if (!strlen($customer['insc_municipal']) == 0) { $postfields = [ 'cityServiceCode' => $service_code, diff --git a/modules/addons/gofasnfeio/functions.php b/modules/addons/gofasnfeio/functions.php index d262075..cbb498a 100644 --- a/modules/addons/gofasnfeio/functions.php +++ b/modules/addons/gofasnfeio/functions.php @@ -185,9 +185,11 @@ function gnfe_queue_nfe($invoice_id,$create_all = false) { ]; try { $service_code_row = Capsule::table('gofasnfeio')->whereNull('service_code')->where('invoice_id', '=', $invoice_id)->get(['id', 'services_amount']); + logModuleCall('gofas_nfeio', 'service_code_row',$service_code_row , '', '', 'replaceVars'); + if (count($service_code_row) == 1) { $mountDB = floatval($service_code_row[0]->services_amount); - $mount_item = floatval($item_not_salle->monthly); + $mount_item = floatval($item_not_salle->amount); $mount = $mountDB + $mount_item; $update_nfe = Capsule::table('gofasnfeio')->where('id', '=', $service_code_row[0]->id)->update(['services_amount' => $mount]); } else { @@ -225,6 +227,7 @@ function gnfe_queue_nfe($invoice_id,$create_all = false) { $mountDB = floatval($service_code_row[0]->services_amount); $mount_item = floatval($item['monthly']); $mount = $mountDB + $mount_item; + $update_nfe = Capsule::table('gofasnfeio')->where('id', '=', $service_code_row[0]->id)->update(['services_amount' => $mount]); } else { $save_nfe = Capsule::table('gofasnfeio')->insert($data); diff --git a/modules/addons/gofasnfeio/hooks/aftercronjob.php b/modules/addons/gofasnfeio/hooks/aftercronjob.php index 23ec887..016ec51 100644 --- a/modules/addons/gofasnfeio/hooks/aftercronjob.php +++ b/modules/addons/gofasnfeio/hooks/aftercronjob.php @@ -53,7 +53,7 @@ foreach ( Capsule::table('tblconfiguration')->where('setting', '=', 'Domain')->get( ['value'] ) as $gnfewhmcsadminurl) { $gnfewhmcsadminurl = $gnfewhmcsadminurl->value; } - $desc = 'Nota referednte a fatura #' . $waiting->invoice_id . ' ' . $gnfewhmcsadminurl . 'viewinvoice.php?id=' . $waiting->invoice_id; + $desc = 'Nota referednte a fatura #' . $waiting->invoice_id . ' ' . $gnfewhmcsadminurl . 'viewinvoice.php?id=' . $waiting->invoice_id . ' '; if (!strlen($customer['insc_municipal']) == 0) { $postfields = [ 'cityServiceCode' => $service_code, diff --git a/modules/addons/gofasnfeio/hooks/dailycronjob.php b/modules/addons/gofasnfeio/hooks/dailycronjob.php index 1427b1e..6dca815 100644 --- a/modules/addons/gofasnfeio/hooks/dailycronjob.php +++ b/modules/addons/gofasnfeio/hooks/dailycronjob.php @@ -45,7 +45,7 @@ foreach ( Capsule::table('tblconfiguration')->where('setting', '=', 'Domain')->get( ['value'] ) as $gnfewhmcsadminurl) { $gnfewhmcsadminurl = $gnfewhmcsadminurl->value; } - $desc = 'Nota referednte a fatura #' . $nfeio->invoice_id . ' ' . $gnfewhmcsadminurl . 'viewinvoice.php?id=' . $waiting->invoice_id; + $desc = 'Nota referednte a fatura #' . $nfeio->invoice_id . ' ' . $gnfewhmcsadminurl . 'viewinvoice.php?id=' . $waiting->invoice_id . ' '; if (!strlen($customer['insc_municipal']) == 0) { $postfields = [ 'cityServiceCode' => $service_code, @@ -100,7 +100,6 @@ 'rpsNumber' => (int)$company['companies']['rpsNumber'] + 1, ]; } - logModuleCall('gofas_nfeio', 'postfields daily',$postfields , '', '', 'replaceVars'); if ($params['debug']) { logModuleCall('gofas_nfeio', 'dailycronjob',$postfields , '', '', 'replaceVars'); From 3546f675af90b7967accd22e4d21a50703be5e37 Mon Sep 17 00:00:00 2001 From: JoaoVictorLNacional Date: Tue, 22 Dec 2020 13:53:14 -0300 Subject: [PATCH 16/52] finalizado layout do codigo de servico --- modules/addons/gofasnfeio/functions.php | 27 ++-- modules/addons/gofasnfeio/gofasnfeio.php | 4 +- modules/addons/gofasnfeio/output.php | 146 +++++++++++++++++++++- modules/addons/gofasnfeio/prod_output.php | 9 ++ 4 files changed, 177 insertions(+), 9 deletions(-) create mode 100644 modules/addons/gofasnfeio/prod_output.php diff --git a/modules/addons/gofasnfeio/functions.php b/modules/addons/gofasnfeio/functions.php index cbb498a..dccd645 100644 --- a/modules/addons/gofasnfeio/functions.php +++ b/modules/addons/gofasnfeio/functions.php @@ -713,13 +713,6 @@ function set_custom_field_ini_date() { } } - function set_camp_custom_code() { - $num = Capsule::table('tblcustomfields')->where('fieldname', '=', 'Código de Serviço')->where('type', '=', 'product')->count(); - if ($num == 0) { - Capsule::table('tblcustomfields')->insert(['type' => 'product', 'relid' => '0', 'fieldname' => 'Código de Serviço', 'fieldtype' => 'text', 'adminonly' => 'on', 'showorder' => 'on', 'showinvoice' => 'on']); - } - } - if ( !function_exists('gnfe_get_company') ) { function gnfe_get_company() { $curl = curl_init(); @@ -803,3 +796,23 @@ function set_code_service_camp_gofasnfeio() { } } } +create_table_product_code(); + function create_table_product_code() { + $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(); + logModuleCall('gofas_nfeio', 'dailycronjob',$e , '', '', 'replaceVars'); + } + } \ No newline at end of file diff --git a/modules/addons/gofasnfeio/gofasnfeio.php b/modules/addons/gofasnfeio/gofasnfeio.php index cb3afb9..36779f1 100644 --- a/modules/addons/gofasnfeio/gofasnfeio.php +++ b/modules/addons/gofasnfeio/gofasnfeio.php @@ -1,4 +1,6 @@ where('setting', '=', 'gnfewhmcsadminurl')->get( ['value'] ) as $gnfewhmcsadminurl_ ) { $gnfewhmcsadminurl = $gnfewhmcsadminurl_->value; } + + if ($_POST['product']) { + $user = localAPI('GetAdminDetails',[]); + $num = Capsule::table('tblproductcode')->where('product_id','=',$_POST['product'])->count(); + if ($num > 0) { + $res = Capsule::table('tblproductcode')->where('product_id','=',$_POST['product'])->update(['code_service' => $_POST['code'], 'update_at' => date('Y-m-d H:i:s')]); + } else { + $res = Capsule::table('tblproductcode')->insert(['code_service' => $_POST['code'], 'product_id' => $_POST['product'], 'create_at' => date('Y-m-d H:i:s'), 'ID_user' => $user['adminid']]); + } + } + + if ($_GET['Prod_code'] === 'yes') { + $html_table = ''; + + foreach ( Capsule::table('tblconfiguration')->where('setting', '=', 'gnfewhmcsadminurl')->get( ['value'] ) as $gnfewhmcsadminurl_ ) { + $gnfewhmcsadminurl = $gnfewhmcsadminurl_->value; + } + $nfes = []; + foreach ( Capsule::table('tblproducts')->orderBy('id', 'desc')->get( ['id'] ) as $nfes_ ) { + $nfes[] = $nfes_->id; + } + if ($_REQUEST['page']) { + $nfes_page = (int)$_REQUEST['page']; + } else { + $nfes_page = 1; + } + if ($_REQUEST['take']) { + $take = (int)$_REQUEST['take']; + } else { + $take = 10; + } + + $nfs_keys = array_keys($nfes); + $nfes_total = count($nfes); + if ($take > $nfes_total) { + $take = $nfes_total; + } + + $nfes_pages = ceil($nfes_total / $take); + $nfes_from_ = ( $nfes_page * $take ) - $take; + $nfes_from = $nfs_keys[$nfes_from_ + 1]; + $nfes_to_ = ( $nfes_from + $take ) - 2; + $nfes_to = $nfs_keys[$nfes_to_ + 1]; + $nfess = array_slice($nfes, $nfes_from_, $nfes_to); + + if ((int)$nfes_page === (int)$nfes_pages) { + $nfes_to = $nfes_total; + $nfess = array_slice($nfes, $nfes_from_, $nfes_to_); + } + if ((int)$take >= (int)$nfes_total) { + $nfes_from = 1; + $nfess = array_slice($nfes, $nfes_from_, $nfes_to); + } + // Pagination + $i = 1; + while ($i <= $nfes_pages ) { + $page_num = $i++; + + if ( (int)$page_num !== (int)$nfes_page ) { + $tag = 'a '; + $a_style = ''; + $li_class = 'class="enabled"'; + $href = $gnfewhmcsadminurl . 'addonmodules.php?module=gofasnfeio&page=' . $page_num; + } elseif ( (int)$page_num === (int)$nfes_page ) { + $tag = 'span '; + $a_style = 'style="background: #337ab7; color: #fff"'; + $li_class = 'class="disabled"'; + $href = ''; + } + $pagination_ .= '
  • <' . $tag . ' ' . $a_style . ' href="' . $href . '" >' . $page_num . '
  • '; + } + if ((int)$nfes_page === 1) { + $preview_class = ' class="previous disabled" '; + $preview_href = ''; + $preview_tag = 'span '; + } else { + $preview_class = ' class="previous" '; + $preview_href = ' href="' . $gnfewhmcsadminurl . 'addonmodules.php?module=gofasnfeio&page=' . ($nfes_page - 1) . '" '; + $preview_tag = 'a '; + } + if ((int)$nfes_page === (int)$nfes_pages) { + $next_class = ' class="next disabled" '; + $next_href = ''; + $next_tag = 'span '; + } else { + $next_class = ' class="next" '; + $next_href = ' href="' . $gnfewhmcsadminurl . 'addonmodules.php?module=gofasnfeio&page=' . ($nfes_page + 1) . '" '; + $next_tag = 'a '; + } + $pagination .= '
  • <' . $preview_tag . ' ' . $preview_href . '>« Página anterior
  • '; + $pagination .= $pagination_; + $pagination .= '
  • <' . $next_tag . ' ' . $next_href . '>Próxima página »
  • '; + + foreach ( Capsule::table('tblproducts')-> + leftJoin('tblproductcode', 'tblproducts.id', '=', 'tblproductcode.product_id')-> + orderBy('tblproducts.id', 'desc')-> + whereBetween('tblproducts.id', [end($nfess), reset($nfess)])-> + take($take)-> + get( ['tblproducts.id', 'tblproducts.name', 'tblproducts.created_at', 'tblproductcode.update_at', 'tblproductcode.code_service'] ) as $product) { + $update_at = $product->updated_at ? date('d/m/Y', strtotime($product->updated_at)) : ''; + //depois linkar o id e o nome com a pagina do produto + $html_table .= '#' . $product->id . ' + ' . date('d/m/Y', strtotime($product->created_at)) . ' + ' . $update_at . ' + ' . $product->name . ' +
    + + + + +
    '; + } + + echo ' + NFE.oi +

    Listagem de notas fiscais

    ' . $nfes_total . ' Itens encontrados.
    Exibindo de ' . $nfes_from . ' a ' . $nfes_to . '. Página ' . $nfes_page . ' de ' . $nfes_pages . '
    +
    + + + + + + + + + + + + ' . $html_table . ' + + +
    IDData de Criação do ProdutoData de Modificação do codigoNome do ProdutoCodigo de ServiçoSalvar
    +
    + +
    +
      + ' . $pagination . ' +
    +
    + '; + return ''; + } + $nfes = []; foreach ( Capsule::table('gofasnfeio')->orderBy('id', 'desc')->get( ['id'] ) as $nfes_ ) { $nfes[] = $nfes_->id; @@ -85,7 +228,7 @@ function gofasnfeio_output($vars) { foreach ( Capsule::table('gofasnfeio')-> orderBy('id', 'desc')-> - whereBetween('id', [end($nfess), reset($nfess)])-> + whereBetween('id', [end($nfess), reset($nfess)])-> take($take)-> get( ['invoice_id', 'user_id', 'nfe_id', 'status', 'services_amount', 'environment', 'flow_status', 'pdf', 'created_at', 'updated_at'] ) as $value ) { $client = localAPI('GetClientsDetails',['clientid' => $value->user_id, 'stats' => false, ], false); @@ -126,6 +269,7 @@ function gofasnfeio_output($vars) { } if ((int)$nfes_total > 0) { echo ' + Codigo dos Produtos

    Listagem de notas fiscais

    ' . $nfes_total . ' Itens encontrados.
    Exibindo de ' . $nfes_from . ' a ' . $nfes_to . '. Página ' . $nfes_page . ' de ' . $nfes_pages . '
    diff --git a/modules/addons/gofasnfeio/prod_output.php b/modules/addons/gofasnfeio/prod_output.php new file mode 100644 index 0000000..e2de8a7 --- /dev/null +++ b/modules/addons/gofasnfeio/prod_output.php @@ -0,0 +1,9 @@ +The date & time are currently ' . date('Y-m-d H:i:s') . '

    '; + } +} \ No newline at end of file From 5d1975e0fb12730e3f592da38464dbb04b21edae Mon Sep 17 00:00:00 2001 From: JoaoVictorLNacional Date: Tue, 22 Dec 2020 16:11:33 -0300 Subject: [PATCH 17/52] =?UTF-8?q?deleta=20da=20tabela=20do=20codigo=20de?= =?UTF-8?q?=20servi=C3=A7o=20quando=20o=20produto=20=C3=A9=20deletado=20e?= =?UTF-8?q?=20usa=20o=20codigo=20de=20servi=C3=A7o=20na=20venda=20--testar?= =?UTF-8?q?=20tudo=20depois--?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- modules/addons/gofasnfeio/callback.php | 2 +- modules/addons/gofasnfeio/functions.php | 12 +++++----- modules/addons/gofasnfeio/hooks.php | 4 ++++ .../addons/gofasnfeio/hooks/aftercronjob.php | 4 ++-- .../addons/gofasnfeio/hooks/dailycronjob.php | 2 +- .../addons/gofasnfeio/hooks/productdelete.php | 3 +++ modules/addons/gofasnfeio/output.php | 22 ++++++++++++------- 7 files changed, 31 insertions(+), 18 deletions(-) create mode 100644 modules/addons/gofasnfeio/hooks/productdelete.php diff --git a/modules/addons/gofasnfeio/callback.php b/modules/addons/gofasnfeio/callback.php index 02f5f1e..174831a 100644 --- a/modules/addons/gofasnfeio/callback.php +++ b/modules/addons/gofasnfeio/callback.php @@ -89,7 +89,7 @@ foreach ( Capsule::table('tblconfiguration')->where('setting', '=', 'Domain')->get( ['value'] ) as $gnfewhmcsadminurl) { $gnfewhmcsadminurl = $gnfewhmcsadminurl->value; } - $desc = 'Nota referednte a fatura #' . $waiting->invoice_id . ' ' . $gnfewhmcsadminurl . 'viewinvoice.php?id=' . $waiting->invoice_id . ' '; + $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, diff --git a/modules/addons/gofasnfeio/functions.php b/modules/addons/gofasnfeio/functions.php index dccd645..b5f6bf4 100644 --- a/modules/addons/gofasnfeio/functions.php +++ b/modules/addons/gofasnfeio/functions.php @@ -168,8 +168,12 @@ function gnfe_ibge($zip) { function gnfe_queue_nfe($invoice_id,$create_all = false) { $invoice = localAPI('GetInvoice', ['invoiceid' => $invoice_id], false); $itens = get_prodict_invoice($invoice_id); + logModuleCall('gofas_nfeio', 'gnfe_queue_nfe itens',$itens , '', '', 'replaceVars'); + if (!$itens) { foreach (Capsule::table('tblinvoiceitems')->where( 'invoiceid', '=', $invoice_id )->get( ['userid', 'amount']) as $item_not_salle) { + logModuleCall('gofas_nfeio', 'gnfe_queue_nfe item_not_salle',$item_not_salle , '', '', 'replaceVars'); + $data = [ 'invoice_id' => $invoice_id, 'user_id' => $item_not_salle->userid, @@ -762,16 +766,12 @@ function get_prodict_invoice($invoice_id) { $pdo->beginTransaction(); try { $list2 = []; - $stmt = $pdo->prepare("SELECT val.value FROM tblcustomfields - INNER JOIN tblcustomfieldsvalues val ON val.fieldid = tblcustomfields.id - WHERE tblcustomfields.fieldname='Código de Serviço' AND tblcustomfields.type = 'product' - AND val.relid = :PROD"); + $stmt = $pdo->prepare('SELECT * FROM tblproductcode WHERE product_id=:PROD'); $stmt->execute([':PROD' => $item[0]]); $row = $stmt->fetchAll(); $pdo->commit(); - logModuleCall('gofas_nfeio', 'row itens',$row , '', '', 'replaceVars'); $list2['item'] = $item['packageid']; - $list2['value'] = $row[0]['value']; + $list2['value'] = $row[0]['code_service']; $list2['monthly'] = $item['monthly']; $list[] = $list2; } catch (\Throwable $th) { diff --git a/modules/addons/gofasnfeio/hooks.php b/modules/addons/gofasnfeio/hooks.php index 180884c..4b7c7ce 100644 --- a/modules/addons/gofasnfeio/hooks.php +++ b/modules/addons/gofasnfeio/hooks.php @@ -28,4 +28,8 @@ add_hook('AfterCronJob', 1, function($vars) { require_once __DIR__ . '/functions.php'; require_once __DIR__ . '/hooks/aftercronjob.php'; +}); +add_hook('ProductDelete', 1, function($vars) { + require_once __DIR__ . '/functions.php'; + require_once __DIR__ . '/hooks/productdelete.php'; }); \ No newline at end of file diff --git a/modules/addons/gofasnfeio/hooks/aftercronjob.php b/modules/addons/gofasnfeio/hooks/aftercronjob.php index 016ec51..4beeb51 100644 --- a/modules/addons/gofasnfeio/hooks/aftercronjob.php +++ b/modules/addons/gofasnfeio/hooks/aftercronjob.php @@ -6,7 +6,7 @@ use WHMCS\Database\Capsule; $params = gnfe_config(); -foreach ( Capsule::table('gofasnfeio')->orderBy('id', 'desc')->where('status', '=', 'Waiting')->take(1)->get( ['id', 'invoice_id', 'service_code', 'services_amount']) as $waiting ) { +foreach ( Capsule::table('gofasnfeio')->orderBy('id', 'desc')->where('status', '=', 'Waiting')->take(1)->get( ['id', 'invoice_id', 'services_amount']) as $waiting ) { $data = getTodaysDate(false); $dataAtual = toMySQLDate($data); @@ -53,7 +53,7 @@ foreach ( Capsule::table('tblconfiguration')->where('setting', '=', 'Domain')->get( ['value'] ) as $gnfewhmcsadminurl) { $gnfewhmcsadminurl = $gnfewhmcsadminurl->value; } - $desc = 'Nota referednte a fatura #' . $waiting->invoice_id . ' ' . $gnfewhmcsadminurl . 'viewinvoice.php?id=' . $waiting->invoice_id . ' '; + $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, diff --git a/modules/addons/gofasnfeio/hooks/dailycronjob.php b/modules/addons/gofasnfeio/hooks/dailycronjob.php index 6dca815..9a5a450 100644 --- a/modules/addons/gofasnfeio/hooks/dailycronjob.php +++ b/modules/addons/gofasnfeio/hooks/dailycronjob.php @@ -45,7 +45,7 @@ foreach ( Capsule::table('tblconfiguration')->where('setting', '=', 'Domain')->get( ['value'] ) as $gnfewhmcsadminurl) { $gnfewhmcsadminurl = $gnfewhmcsadminurl->value; } - $desc = 'Nota referednte a fatura #' . $nfeio->invoice_id . ' ' . $gnfewhmcsadminurl . 'viewinvoice.php?id=' . $waiting->invoice_id . ' '; + $desc = 'Nota referente a fatura #' . $nfeio->invoice_id . ' ' . $gnfewhmcsadminurl . 'viewinvoice.php?id=' . $waiting->invoice_id . ' '; if (!strlen($customer['insc_municipal']) == 0) { $postfields = [ 'cityServiceCode' => $service_code, diff --git a/modules/addons/gofasnfeio/hooks/productdelete.php b/modules/addons/gofasnfeio/hooks/productdelete.php new file mode 100644 index 0000000..79e54c3 --- /dev/null +++ b/modules/addons/gofasnfeio/hooks/productdelete.php @@ -0,0 +1,3 @@ +where('product_id','=',$vars['pid'])->delete(); \ No newline at end of file diff --git a/modules/addons/gofasnfeio/output.php b/modules/addons/gofasnfeio/output.php index b0354aa..a70e650 100644 --- a/modules/addons/gofasnfeio/output.php +++ b/modules/addons/gofasnfeio/output.php @@ -13,12 +13,17 @@ function gofasnfeio_output($vars) { $num = Capsule::table('tblproductcode')->where('product_id','=',$_POST['product'])->count(); if ($num > 0) { $res = Capsule::table('tblproductcode')->where('product_id','=',$_POST['product'])->update(['code_service' => $_POST['code'], 'update_at' => date('Y-m-d H:i:s')]); + if ($_POST['code'] == 0) { + $res = Capsule::table('tblproductcode')->where('product_id','=',$_POST['product'])->delete(); + } } else { - $res = Capsule::table('tblproductcode')->insert(['code_service' => $_POST['code'], 'product_id' => $_POST['product'], 'create_at' => date('Y-m-d H:i:s'), 'ID_user' => $user['adminid']]); + if ($_POST['code'] != 0) { + $res = Capsule::table('tblproductcode')->insert(['code_service' => $_POST['code'], 'product_id' => $_POST['product'], 'create_at' => date('Y-m-d H:i:s'), 'ID_user' => $user['adminid']]); + } } } - if ($_GET['Prod_code'] === 'yes') { + if ($_GET['action'] === 'code_product') { $html_table = ''; foreach ( Capsule::table('tblconfiguration')->where('setting', '=', 'gnfewhmcsadminurl')->get( ['value'] ) as $gnfewhmcsadminurl_ ) { @@ -106,10 +111,11 @@ function gofasnfeio_output($vars) { whereBetween('tblproducts.id', [end($nfess), reset($nfess)])-> take($take)-> get( ['tblproducts.id', 'tblproducts.name', 'tblproducts.created_at', 'tblproductcode.update_at', 'tblproductcode.code_service'] ) as $product) { - $update_at = $product->updated_at ? date('d/m/Y', strtotime($product->updated_at)) : ''; + $created_at = $product->created_at ? date('d/m/Y', strtotime($product->created_at)) : ''; + $update_at = $product->update_at ? date('d/m/Y', strtotime($product->update_at)) : ''; //depois linkar o id e o nome com a pagina do produto $html_table .= ' - + @@ -121,15 +127,15 @@ function gofasnfeio_output($vars) { } echo ' - NFE.oi -

    Listagem de notas fiscais

    ' . $nfes_total . ' Itens encontrados.
    Exibindo de ' . $nfes_from . ' a ' . $nfes_to . '. Página ' . $nfes_page . ' de ' . $nfes_pages . '
    + NFE.oi +

    Listagem produtos

    ' . $nfes_total . ' Itens encontrados.
    Exibindo de ' . $nfes_from . ' a ' . $nfes_to . '. Página ' . $nfes_page . ' de ' . $nfes_pages . '
    #' . $product->id . '' . date('d/m/Y', strtotime($product->created_at)) . '' . $created_at . ' ' . $update_at . ' ' . $product->name . '
    - + @@ -269,7 +275,7 @@ function gofasnfeio_output($vars) { } if ((int)$nfes_total > 0) { echo ' - Codigo dos Produtos + Codigo dos Produtos

    Listagem de notas fiscais

    ' . $nfes_total . ' Itens encontrados.
    Exibindo de ' . $nfes_from . ' a ' . $nfes_to . '. Página ' . $nfes_page . ' de ' . $nfes_pages . '
    ID Data de Criação do ProdutoData de Modificação do codigoData de Alteração Nome do Produto Codigo de Serviço Salvar
    From 74873c159bffa27a405fe51eca86af4cbee1dc80 Mon Sep 17 00:00:00 2001 From: JoaoVictorLNacional Date: Wed, 23 Dec 2020 10:06:22 -0300 Subject: [PATCH 18/52] adicionado alert de codigo salvo e codigo da tabela dos codigos dos produtos colocado em outputproduct.php --- modules/addons/gofasnfeio/output.php | 151 +----------------- modules/addons/gofasnfeio/outputproduct.php | 162 ++++++++++++++++++++ 2 files changed, 164 insertions(+), 149 deletions(-) create mode 100644 modules/addons/gofasnfeio/outputproduct.php diff --git a/modules/addons/gofasnfeio/output.php b/modules/addons/gofasnfeio/output.php index a70e650..17507d0 100644 --- a/modules/addons/gofasnfeio/output.php +++ b/modules/addons/gofasnfeio/output.php @@ -7,154 +7,7 @@ function gofasnfeio_output($vars) { foreach ( Capsule::table('tblconfiguration')->where('setting', '=', 'gnfewhmcsadminurl')->get( ['value'] ) as $gnfewhmcsadminurl_ ) { $gnfewhmcsadminurl = $gnfewhmcsadminurl_->value; } - - if ($_POST['product']) { - $user = localAPI('GetAdminDetails',[]); - $num = Capsule::table('tblproductcode')->where('product_id','=',$_POST['product'])->count(); - if ($num > 0) { - $res = Capsule::table('tblproductcode')->where('product_id','=',$_POST['product'])->update(['code_service' => $_POST['code'], 'update_at' => date('Y-m-d H:i:s')]); - if ($_POST['code'] == 0) { - $res = Capsule::table('tblproductcode')->where('product_id','=',$_POST['product'])->delete(); - } - } else { - if ($_POST['code'] != 0) { - $res = Capsule::table('tblproductcode')->insert(['code_service' => $_POST['code'], 'product_id' => $_POST['product'], 'create_at' => date('Y-m-d H:i:s'), 'ID_user' => $user['adminid']]); - } - } - } - - if ($_GET['action'] === 'code_product') { - $html_table = ''; - - foreach ( Capsule::table('tblconfiguration')->where('setting', '=', 'gnfewhmcsadminurl')->get( ['value'] ) as $gnfewhmcsadminurl_ ) { - $gnfewhmcsadminurl = $gnfewhmcsadminurl_->value; - } - $nfes = []; - foreach ( Capsule::table('tblproducts')->orderBy('id', 'desc')->get( ['id'] ) as $nfes_ ) { - $nfes[] = $nfes_->id; - } - if ($_REQUEST['page']) { - $nfes_page = (int)$_REQUEST['page']; - } else { - $nfes_page = 1; - } - if ($_REQUEST['take']) { - $take = (int)$_REQUEST['take']; - } else { - $take = 10; - } - - $nfs_keys = array_keys($nfes); - $nfes_total = count($nfes); - if ($take > $nfes_total) { - $take = $nfes_total; - } - - $nfes_pages = ceil($nfes_total / $take); - $nfes_from_ = ( $nfes_page * $take ) - $take; - $nfes_from = $nfs_keys[$nfes_from_ + 1]; - $nfes_to_ = ( $nfes_from + $take ) - 2; - $nfes_to = $nfs_keys[$nfes_to_ + 1]; - $nfess = array_slice($nfes, $nfes_from_, $nfes_to); - - if ((int)$nfes_page === (int)$nfes_pages) { - $nfes_to = $nfes_total; - $nfess = array_slice($nfes, $nfes_from_, $nfes_to_); - } - if ((int)$take >= (int)$nfes_total) { - $nfes_from = 1; - $nfess = array_slice($nfes, $nfes_from_, $nfes_to); - } - // Pagination - $i = 1; - while ($i <= $nfes_pages ) { - $page_num = $i++; - - if ( (int)$page_num !== (int)$nfes_page ) { - $tag = 'a '; - $a_style = ''; - $li_class = 'class="enabled"'; - $href = $gnfewhmcsadminurl . 'addonmodules.php?module=gofasnfeio&page=' . $page_num; - } elseif ( (int)$page_num === (int)$nfes_page ) { - $tag = 'span '; - $a_style = 'style="background: #337ab7; color: #fff"'; - $li_class = 'class="disabled"'; - $href = ''; - } - $pagination_ .= '
  • <' . $tag . ' ' . $a_style . ' href="' . $href . '" >' . $page_num . '
  • '; - } - if ((int)$nfes_page === 1) { - $preview_class = ' class="previous disabled" '; - $preview_href = ''; - $preview_tag = 'span '; - } else { - $preview_class = ' class="previous" '; - $preview_href = ' href="' . $gnfewhmcsadminurl . 'addonmodules.php?module=gofasnfeio&page=' . ($nfes_page - 1) . '" '; - $preview_tag = 'a '; - } - if ((int)$nfes_page === (int)$nfes_pages) { - $next_class = ' class="next disabled" '; - $next_href = ''; - $next_tag = 'span '; - } else { - $next_class = ' class="next" '; - $next_href = ' href="' . $gnfewhmcsadminurl . 'addonmodules.php?module=gofasnfeio&page=' . ($nfes_page + 1) . '" '; - $next_tag = 'a '; - } - $pagination .= '
  • <' . $preview_tag . ' ' . $preview_href . '>« Página anterior
  • '; - $pagination .= $pagination_; - $pagination .= '
  • <' . $next_tag . ' ' . $next_href . '>Próxima página »
  • '; - - foreach ( Capsule::table('tblproducts')-> - leftJoin('tblproductcode', 'tblproducts.id', '=', 'tblproductcode.product_id')-> - orderBy('tblproducts.id', 'desc')-> - whereBetween('tblproducts.id', [end($nfess), reset($nfess)])-> - take($take)-> - get( ['tblproducts.id', 'tblproducts.name', 'tblproducts.created_at', 'tblproductcode.update_at', 'tblproductcode.code_service'] ) as $product) { - $created_at = $product->created_at ? date('d/m/Y', strtotime($product->created_at)) : ''; - $update_at = $product->update_at ? date('d/m/Y', strtotime($product->update_at)) : ''; - //depois linkar o id e o nome com a pagina do produto - $html_table .= '
    - - - - - - - - - '; - } - - echo ' - NFE.oi -

    Listagem produtos

    ' . $nfes_total . ' Itens encontrados.
    Exibindo de ' . $nfes_from . ' a ' . $nfes_to . '. Página ' . $nfes_page . ' de ' . $nfes_pages . '
    -
    -
    #' . $product->id . '' . $created_at . '' . $update_at . '' . $product->name . '
    - - - - - - - - - - - ' . $html_table . ' - - -
    IDData de Criação do ProdutoData de AlteraçãoNome do ProdutoCodigo de ServiçoSalvar
    -
    - -
    -
      - ' . $pagination . ' -
    -
    - '; - return ''; - } + require_once __DIR__ . '/outputproduct.php'; $nfes = []; foreach ( Capsule::table('gofasnfeio')->orderBy('id', 'desc')->get( ['id'] ) as $nfes_ ) { @@ -275,7 +128,7 @@ function gofasnfeio_output($vars) { } if ((int)$nfes_total > 0) { echo ' - Codigo dos Produtos + código dos Produtos

    Listagem de notas fiscais

    ' . $nfes_total . ' Itens encontrados.
    Exibindo de ' . $nfes_from . ' a ' . $nfes_to . '. Página ' . $nfes_page . ' de ' . $nfes_pages . '
    diff --git a/modules/addons/gofasnfeio/outputproduct.php b/modules/addons/gofasnfeio/outputproduct.php new file mode 100644 index 0000000..4abff61 --- /dev/null +++ b/modules/addons/gofasnfeio/outputproduct.php @@ -0,0 +1,162 @@ +where('product_id','=',$_POST['product'])->count(); + if ($num > 0) { + $res = Capsule::table('tblproductcode')->where('product_id','=',$_POST['product'])->update(['code_service' => $_POST['code'], 'update_at' => date('Y-m-d H:i:s')]); + if ($_POST['code'] == 0) { + $res = Capsule::table('tblproductcode')->where('product_id','=',$_POST['product'])->delete(); + } + } else { + if ($_POST['code'] != 0) { + $res = Capsule::table('tblproductcode')->insert(['code_service' => $_POST['code'], 'product_id' => $_POST['product'], 'create_at' => date('Y-m-d H:i:s'), 'ID_user' => $user['adminid']]); + } + } + $message = '
    Código Salvo
    '; + header_remove(); + header('Location: ' . $gnfewhmcsadminurl . 'addonmodules.php?module=gofasnfeio&action=code_product&gnfe_message=' . base64_encode(urlencode($message))); + exit; + } catch (\Exception $e) { + $e->getMessage(); + $message = '
    ' . $e->getMessage() . '
    '; + header_remove(); + header('Location: ' . $gnfewhmcsadminurl . 'addonmodules.php?module=gofasnfeio&action=code_product&gnfe_message=' . base64_encode(urlencode($message))); + exit; + } + } + + foreach ( Capsule::table('tblconfiguration')->where('setting', '=', 'gnfewhmcsadminurl')->get( ['value'] ) as $gnfewhmcsadminurl_ ) { + $gnfewhmcsadminurl = $gnfewhmcsadminurl_->value; + } + $nfes = []; + foreach ( Capsule::table('tblproducts')->orderBy('id', 'desc')->get( ['id'] ) as $nfes_ ) { + $nfes[] = $nfes_->id; + } + if ($_REQUEST['page']) { + $nfes_page = (int)$_REQUEST['page']; + } else { + $nfes_page = 1; + } + if ($_REQUEST['take']) { + $take = (int)$_REQUEST['take']; + } else { + $take = 10; + } + + $nfs_keys = array_keys($nfes); + $nfes_total = count($nfes); + if ($take > $nfes_total) { + $take = $nfes_total; + } + + $nfes_pages = ceil($nfes_total / $take); + $nfes_from_ = ( $nfes_page * $take ) - $take; + $nfes_from = $nfs_keys[$nfes_from_ + 1]; + $nfes_to_ = ( $nfes_from + $take ) - 2; + $nfes_to = $nfs_keys[$nfes_to_ + 1]; + $nfess = array_slice($nfes, $nfes_from_, $nfes_to); + + if ((int)$nfes_page === (int)$nfes_pages) { + $nfes_to = $nfes_total; + $nfess = array_slice($nfes, $nfes_from_, $nfes_to_); + } + if ((int)$take >= (int)$nfes_total) { + $nfes_from = 1; + $nfess = array_slice($nfes, $nfes_from_, $nfes_to); + } + // Pagination + $i = 1; + while ($i <= $nfes_pages ) { + $page_num = $i++; + + if ( (int)$page_num !== (int)$nfes_page ) { + $tag = 'a '; + $a_style = ''; + $li_class = 'class="enabled"'; + $href = $gnfewhmcsadminurl . 'addonmodules.php?module=gofasnfeio&page=' . $page_num; + } elseif ( (int)$page_num === (int)$nfes_page ) { + $tag = 'span '; + $a_style = 'style="background: #337ab7; color: #fff"'; + $li_class = 'class="disabled"'; + $href = ''; + } + $pagination_ .= '
  • <' . $tag . ' ' . $a_style . ' href="' . $href . '" >' . $page_num . '
  • '; + } + if ((int)$nfes_page === 1) { + $preview_class = ' class="previous disabled" '; + $preview_href = ''; + $preview_tag = 'span '; + } else { + $preview_class = ' class="previous" '; + $preview_href = ' href="' . $gnfewhmcsadminurl . 'addonmodules.php?module=gofasnfeio&page=' . ($nfes_page - 1) . '" '; + $preview_tag = 'a '; + } + if ((int)$nfes_page === (int)$nfes_pages) { + $next_class = ' class="next disabled" '; + $next_href = ''; + $next_tag = 'span '; + } else { + $next_class = ' class="next" '; + $next_href = ' href="' . $gnfewhmcsadminurl . 'addonmodules.php?module=gofasnfeio&page=' . ($nfes_page + 1) . '" '; + $next_tag = 'a '; + } + $pagination .= '
  • <' . $preview_tag . ' ' . $preview_href . '>« Página anterior
  • '; + $pagination .= $pagination_; + $pagination .= '
  • <' . $next_tag . ' ' . $next_href . '>Próxima página »
  • '; + + foreach ( Capsule::table('tblproducts')-> + leftJoin('tblproductcode', 'tblproducts.id', '=', 'tblproductcode.product_id')-> + orderBy('tblproducts.id', 'desc')-> + whereBetween('tblproducts.id', [end($nfess), reset($nfess)])-> + take($take)-> + get( ['tblproducts.id', 'tblproducts.name', 'tblproducts.created_at', 'tblproductcode.update_at', 'tblproductcode.code_service'] ) as $product) { + $created_at = $product->created_at ? date('d/m/Y', strtotime($product->created_at)) : ''; + $update_at = $product->update_at ? date('d/m/Y', strtotime($product->update_at)) : ''; + //depois linkar o id e o nome com a pagina do produto + $html_table .= ' + + + + + + + + + '; + } + + echo ' + NFE.oi +

    Listagem produtos

    ' . $nfes_total . ' Itens encontrados.
    Exibindo de ' . $nfes_from . ' a ' . $nfes_to . '. Página ' . $nfes_page . ' de ' . $nfes_pages . '
    +
    +
    #' . $product->id . '' . $created_at . '' . $update_at . '' . $product->name . '
    + + + + + + + + + + + ' . $html_table . ' + + +
    IDData de Criação do ProdutoData de AlteraçãoNome do ProdutoCódigo de ServiçoSalvar
    +
    + +
    +
      + ' . $pagination . ' +
    +
    + '; + return ''; +} \ No newline at end of file From a0e0a630bbf0fd230accc731fd3330a958f0f1ae Mon Sep 17 00:00:00 2001 From: JoaoVictorLNacional Date: Wed, 23 Dec 2020 10:18:25 -0300 Subject: [PATCH 19/52] corigido layout addons produtos --- modules/addons/gofasnfeio/output.php | 7 ++++++- modules/addons/gofasnfeio/outputproduct.php | 6 ++---- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/modules/addons/gofasnfeio/output.php b/modules/addons/gofasnfeio/output.php index 17507d0..1ce2e9d 100644 --- a/modules/addons/gofasnfeio/output.php +++ b/modules/addons/gofasnfeio/output.php @@ -7,7 +7,12 @@ function gofasnfeio_output($vars) { foreach ( Capsule::table('tblconfiguration')->where('setting', '=', 'gnfewhmcsadminurl')->get( ['value'] ) as $gnfewhmcsadminurl_ ) { $gnfewhmcsadminurl = $gnfewhmcsadminurl_->value; } - require_once __DIR__ . '/outputproduct.php'; + + if ($_GET['action'] === 'code_product') { + require_once __DIR__ . '/outputproduct.php'; + return ''; + } + logModuleCall('gofas_nfeio', 'teste','saiu' , '', '', 'replaceVars'); $nfes = []; foreach ( Capsule::table('gofasnfeio')->orderBy('id', 'desc')->get( ['id'] ) as $nfes_ ) { diff --git a/modules/addons/gofasnfeio/outputproduct.php b/modules/addons/gofasnfeio/outputproduct.php index 4abff61..a64fdab 100644 --- a/modules/addons/gofasnfeio/outputproduct.php +++ b/modules/addons/gofasnfeio/outputproduct.php @@ -1,8 +1,8 @@
    - '; - return ''; -} \ No newline at end of file + '; \ No newline at end of file From 44fca919fce50c2997c804cd48ed06b5a136367f Mon Sep 17 00:00:00 2001 From: JoaoVictorLNacional Date: Wed, 23 Dec 2020 10:29:45 -0300 Subject: [PATCH 20/52] corigido bug com o alert --- modules/addons/gofasnfeio/hooks/productdelete.php | 2 +- modules/addons/gofasnfeio/output.php | 1 - modules/addons/gofasnfeio/outputproduct.php | 7 ++++--- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/modules/addons/gofasnfeio/hooks/productdelete.php b/modules/addons/gofasnfeio/hooks/productdelete.php index 79e54c3..d4f9996 100644 --- a/modules/addons/gofasnfeio/hooks/productdelete.php +++ b/modules/addons/gofasnfeio/hooks/productdelete.php @@ -1,3 +1,3 @@ where('product_id','=',$vars['pid'])->delete(); \ No newline at end of file diff --git a/modules/addons/gofasnfeio/output.php b/modules/addons/gofasnfeio/output.php index 1ce2e9d..e775833 100644 --- a/modules/addons/gofasnfeio/output.php +++ b/modules/addons/gofasnfeio/output.php @@ -12,7 +12,6 @@ function gofasnfeio_output($vars) { require_once __DIR__ . '/outputproduct.php'; return ''; } - logModuleCall('gofas_nfeio', 'teste','saiu' , '', '', 'replaceVars'); $nfes = []; foreach ( Capsule::table('gofasnfeio')->orderBy('id', 'desc')->get( ['id'] ) as $nfes_ ) { diff --git a/modules/addons/gofasnfeio/outputproduct.php b/modules/addons/gofasnfeio/outputproduct.php index a64fdab..eb4e53d 100644 --- a/modules/addons/gofasnfeio/outputproduct.php +++ b/modules/addons/gofasnfeio/outputproduct.php @@ -2,8 +2,6 @@ use WHMCS\Database\Capsule; $html_table = ''; - logModuleCall('gofas_nfeio', 'teste','saiu' , '', '', 'replaceVars'); - if ($_POST['product']) { $user = localAPI('GetAdminDetails',[]); try { @@ -157,4 +155,7 @@ ' . $pagination . '
    - '; \ No newline at end of file + '; + if ($_REQUEST['gnfe_message']) { + echo urldecode(base64_decode( $_REQUEST['gnfe_message'] )); + } \ No newline at end of file From 322a685c7fb3da5b0a0300c7c5e4b0f6e74708a2 Mon Sep 17 00:00:00 2001 From: JoaoVictorLNacional Date: Thu, 24 Dec 2020 10:57:43 -0300 Subject: [PATCH 21/52] =?UTF-8?q?corigido=20o=20bug=20com=20a=20cria=C3=A7?= =?UTF-8?q?=C3=A3o=20de=20order=20pela=20API?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- modules/addons/gofasnfeio/functions.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/modules/addons/gofasnfeio/functions.php b/modules/addons/gofasnfeio/functions.php index b5f6bf4..ac0b961 100644 --- a/modules/addons/gofasnfeio/functions.php +++ b/modules/addons/gofasnfeio/functions.php @@ -796,7 +796,7 @@ function set_code_service_camp_gofasnfeio() { } } } -create_table_product_code(); +if ( !function_exists('create_table_product_code') ) { function create_table_product_code() { $pdo = Capsule::connection()->getPdo(); $pdo->beginTransaction(); @@ -813,6 +813,6 @@ function create_table_product_code() { $pdo->commit(); } catch (\Exception $e) { $pdo->rollBack(); - logModuleCall('gofas_nfeio', 'dailycronjob',$e , '', '', 'replaceVars'); } - } \ No newline at end of file + } +} \ No newline at end of file From 29c70c8c7ef50b468178a8d3e11a4ad783bc8442 Mon Sep 17 00:00:00 2001 From: JoaoVictorLNacional Date: Mon, 28 Dec 2020 14:42:48 -0300 Subject: [PATCH 22/52] modificado xml e pdf do link do pdf da fatura para abrir varias janelas --- modules/addons/gofasnfeio/createpdf.php | 40 ++++++++++++++ modules/addons/gofasnfeio/createxml.php | 53 +++++++++++++++++++ .../hooks/admininvoicescontrolsoutput.php | 1 - modules/addons/gofasnfeio/pdf.php | 22 +++----- modules/addons/gofasnfeio/xml.php | 26 ++++----- 5 files changed, 109 insertions(+), 33 deletions(-) create mode 100644 modules/addons/gofasnfeio/createpdf.php create mode 100644 modules/addons/gofasnfeio/createxml.php diff --git a/modules/addons/gofasnfeio/createpdf.php b/modules/addons/gofasnfeio/createpdf.php new file mode 100644 index 0000000..acd863b --- /dev/null +++ b/modules/addons/gofasnfeio/createpdf.php @@ -0,0 +1,40 @@ +where('id', '=', $nfe_id)->get(['invoice_id', 'user_id', 'nfe_id', 'status', 'services_amount', 'environment', 'flow_status', 'pdf', 'created_at', 'updated_at', 'id']); + $nfe = $row[0]; + if ((string)$nfe->status === (string)'Issued') { + $nfe_for_invoice = gnfe_pdf_nfe($nfe->nfe_id); + echo $nfe_for_invoice; + } else { + echo 'Not Found'; + } + exit(); + + function gnfe_pdf_nfe($nf) { + $curl = curl_init(); + curl_setopt($curl, CURLOPT_URL, 'https://api.nfe.io/v1/companies/' . gnfe_config('company_id') . '/serviceinvoices/' . $nf . '/pdf'); + curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-type: application/pdf', 'Authorization: ' . gnfe_config('api_key')]); + curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); + curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET'); + curl_setopt($curl, CURLOPT_RETURNTRANSFER,true); + curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); + curl_setopt($curl, CURLOPT_TIMEOUT, 10); + curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 30); + header('Content-type: application/pdf'); + $result = curl_exec($curl); + curl_close($curl); + return $result; + } + function gnfe_config($set = false) { + $setting = []; + foreach ( Capsule::table('tbladdonmodules')->where( 'module', '=', 'gofasnfeio' )->get( ['setting', 'value'] ) as $settings ) { + $setting[$settings->setting] = $settings->value; + } + if ($set) { + return $setting[$set]; + } + return $setting; + } \ No newline at end of file diff --git a/modules/addons/gofasnfeio/createxml.php b/modules/addons/gofasnfeio/createxml.php new file mode 100644 index 0000000..d24613a --- /dev/null +++ b/modules/addons/gofasnfeio/createxml.php @@ -0,0 +1,53 @@ +where('id', '=', $invoice_id)->get(['invoice_id', 'user_id', 'nfe_id', 'status', 'services_amount', 'environment', 'flow_status', 'pdf', 'created_at', 'updated_at', 'id']); + $nfe = $row[0]; + var_dump($nfe); + if ((string)$nfe->status === (string)'Issued') { + $nfe_xml_for_invoice = gnfe_xml_nfe($nfe->nfe_id); + header ('Content-Type:text/xml'); + var_dump($nfe_xml_for_invoice); + } else { + echo 'Sem permissão'; + } + exit(); + + function gnfe_xml_nfe($nf) { + $curl = curl_init(); + curl_setopt($curl, CURLOPT_URL, 'https://api.nfe.io/v1/companies/' . gnfe_config('company_id') . '/serviceinvoices/' . $nf . '/xml'); + curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: text/json', 'Accept: application/json', 'Authorization: ' . gnfe_config('api_key')]); + curl_setopt($curl, CURLOPT_TIMEOUT, 30); + curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); + $response = curl_exec ($curl); + curl_close ($curl); + return json_decode($response); + } + + function gnfe_config($set = false) { + $setting = []; + foreach ( Capsule::table('tbladdonmodules')->where( 'module', '=', 'gofasnfeio' )->get( ['setting', 'value'] ) as $settings ) { + $setting[$settings->setting] = $settings->value; + } + if ($set) { + return $setting[$set]; + } + return $setting; + } + + function gnfe_pdf_nfe($nf) { + $curl = curl_init(); + curl_setopt($curl, CURLOPT_URL, 'https://api.nfe.io/v1/companies/' . gnfe_config('company_id') . '/serviceinvoices/' . $nf . '/pdf'); + curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-type: application/pdf', 'Authorization: ' . gnfe_config('api_key')]); + curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); + curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET'); + curl_setopt($curl, CURLOPT_RETURNTRANSFER,true); + curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); + curl_setopt($curl, CURLOPT_TIMEOUT, 10); + curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 30); + header('Content-type: application/pdf'); + $result = curl_exec($curl); + curl_close($curl); + return $result; + } \ No newline at end of file diff --git a/modules/addons/gofasnfeio/hooks/admininvoicescontrolsoutput.php b/modules/addons/gofasnfeio/hooks/admininvoicescontrolsoutput.php index 23d5375..9bd547e 100644 --- a/modules/addons/gofasnfeio/hooks/admininvoicescontrolsoutput.php +++ b/modules/addons/gofasnfeio/hooks/admininvoicescontrolsoutput.php @@ -33,7 +33,6 @@ } if ($_REQUEST['gnfe_open']) { - logModuleCall('gofas_nfeio', '_REQUEST gnfe_open',$_REQUEST['gnfe_open'] , '', '', 'replaceVars'); foreach (Capsule::table('gofasnfeio')->where( 'invoice_id', '=',$_REQUEST['gnfe_open'] )->get( ['id', 'nfe_id']) as $nfe) { $url = 'https://app.nfe.io/companies/' . $params['company_id'] . '/service-invoices/' . $nfe->nfe_id; echo ""; diff --git a/modules/addons/gofasnfeio/pdf.php b/modules/addons/gofasnfeio/pdf.php index e0c9806..5466735 100644 --- a/modules/addons/gofasnfeio/pdf.php +++ b/modules/addons/gofasnfeio/pdf.php @@ -4,20 +4,12 @@ $invoice_id = $_GET['invoice_id']; if ($invoice_id) { - require_once __DIR__ . '/functions.php'; - foreach( Capsule::table('gofasnfeio')->where('invoice_id', '=', $invoice_id)->get(array( 'invoice_id', 'user_id', 'nfe_id', 'status', 'services_amount', 'environment', 'flow_status', 'pdf', 'created_at', 'updated_at' )) as $key => $value ) { - $nfe_for_invoice[$key] = json_decode(json_encode($value), true); + foreach ( Capsule::table('tblconfiguration')->where('setting', '=', 'Domain')->get( ['value'] ) as $gnfewhmcsadminurl_ ) { + $gnfewhmcsadminurl = $gnfewhmcsadminurl_->value; } - $nfe = $nfe_for_invoice['0']; - if((string)$nfe['user_id'] == (string)$_SESSION['uid']){ - if((string)$nfe['status'] === (string)'Issued') { - $nfe_for_invoice = gnfe_pdf_nfe($nfe['nfe_id']); - echo $nfe_for_invoice; - }else{ - echo 'Not Found'; - } - }else{ - echo 'Not Found'; + foreach (Capsule::table('gofasnfeio')->where( 'invoice_id', '=',$invoice_id )->get( ['id', 'invoice_id']) as $nfe) { + $url = $gnfewhmcsadminurl . 'modules/addons/gofasnfeio/createpdf.php?nfe_id=' . $nfe->id; + echo ""; } - exit(); -} \ No newline at end of file +} +echo ""; diff --git a/modules/addons/gofasnfeio/xml.php b/modules/addons/gofasnfeio/xml.php index c45fd3e..79ebfc5 100644 --- a/modules/addons/gofasnfeio/xml.php +++ b/modules/addons/gofasnfeio/xml.php @@ -1,24 +1,16 @@ + where('invoice_id', '=', $invoice_id)->get(array( 'invoice_id', 'user_id', 'nfe_id', 'status', 'services_amount', 'environment', 'flow_status', 'pdf', 'created_at', 'updated_at' )) as $key => $value ) { - $nfe_for_invoice[$key] = json_decode(json_encode($value), true); + foreach ( Capsule::table('tblconfiguration')->where('setting', '=', 'Domain')->get( ['value'] ) as $gnfewhmcsadminurl_ ) { + $gnfewhmcsadminurl = $gnfewhmcsadminurl_->value; } - $nfe = $nfe_for_invoice['0']; - if((string)$nfe['user_id'] == (string)$_SESSION['uid']){ - - if((string)$nfe['status'] === (string)'Issued') { - $nfe_xml_for_invoice = gnfe_xml_nfe($nfe['nfe_id']); - header ("Content-Type:text/xml"); - echo $nfe_xml_for_invoice; - }else{ - echo 'Sem permissão'; - } - }else{ - echo 'Não encontrado'; + foreach (Capsule::table('gofasnfeio')->where( 'invoice_id', '=',$invoice_id )->get( ['id', 'invoice_id']) as $nfe) { + $url = $gnfewhmcsadminurl . 'modules/addons/gofasnfeio/createxml.php?nfe_id=' . $nfe->id; + echo ""; } - exit(); -} \ No newline at end of file +} +echo ""; From 7b205bd8014b992ebe53e20fa69a6c68bbc78faa Mon Sep 17 00:00:00 2001 From: JoaoVictorLNacional Date: Mon, 28 Dec 2020 15:47:51 -0300 Subject: [PATCH 23/52] =?UTF-8?q?add=20fun=C3=A7=C3=A3o=20para=20modificar?= =?UTF-8?q?=20o=20banco=20para=20essa=20nova=20vers=C3=A3o=20--falta=20ach?= =?UTF-8?q?ar=20o=20melhor=20lugar=20para=20a=20executar=20e=20testar--?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- modules/addons/gofasnfeio/functions.php | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/modules/addons/gofasnfeio/functions.php b/modules/addons/gofasnfeio/functions.php index ac0b961..025e74f 100644 --- a/modules/addons/gofasnfeio/functions.php +++ b/modules/addons/gofasnfeio/functions.php @@ -815,4 +815,16 @@ function create_table_product_code() { $pdo->rollBack(); } } +} + +function update_table() { + $current_version = '1.2.5'; + $row = Capsule::table('tblconfiguration')->where( 'setting', '=', 'version_nfeio' )->get(['value']); + $version = $row[0]; + if ($version != $current_version) { + create_table_product_code(); + set_code_service_camp_gofasnfeio(); + } else { + Capsule::table('tblconfiguration')->insert(['setting' => 'version_nfeio', 'value' => $current_version, 'created_at' => date('Y-m-d H:i:s')]); + } } \ No newline at end of file From 9972a90a2a2653c82f70efefab3b8b0e6bf225d3 Mon Sep 17 00:00:00 2001 From: JoaoVictorLNacional Date: Wed, 30 Dec 2020 15:01:26 -0300 Subject: [PATCH 24/52] =?UTF-8?q?finalizado=20a=20modifica=C3=A7=C3=A3o=20?= =?UTF-8?q?de=20taxa=20sobre=20os=20produtos=20--TESTANDO=20TUDO--?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- modules/addons/gofasnfeio/functions.php | 580 ++++++++++-------- modules/addons/gofasnfeio/hooks.php | 56 +- .../addons/gofasnfeio/hooks/dailycronjob.php | 65 +- .../addons/gofasnfeio/hooks/invoicepaid.php | 36 +- 4 files changed, 418 insertions(+), 319 deletions(-) diff --git a/modules/addons/gofasnfeio/functions.php b/modules/addons/gofasnfeio/functions.php index 025e74f..38e86f3 100644 --- a/modules/addons/gofasnfeio/functions.php +++ b/modules/addons/gofasnfeio/functions.php @@ -1,50 +1,55 @@ where( 'module', '=', 'gofasnfeio' )->get( ['setting', 'value'] ) as $settings ) { + foreach (Capsule::table('tbladdonmodules')->where('module', '=', 'gofasnfeio')->get(['setting', 'value']) as $settings) { $setting[$settings->setting] = $settings->value; } if ($set) { return $setting[$set]; } + return $setting; } } -if ( !function_exists('gnfe_customer') ) { - function gnfe_customer($user_id,$client) { +if (!function_exists('gnfe_customer')) { + function gnfe_customer($user_id, $client) + { //Determine custom fields id $customfields = []; - foreach ( Capsule::table('tblcustomfields')->where( 'type', '=', 'client' )->get( ['fieldname', 'id'] ) as $customfield ) { + foreach (Capsule::table('tblcustomfields')->where('type', '=', 'client')->get(['fieldname', 'id']) as $customfield) { $customfield_id = $customfield->id; - $customfield_name = ' ' . strtolower( $customfield->fieldname ); + $customfield_name = ' '.strtolower($customfield->fieldname); $insc_customfield_value = 'NF'; // insc_municipal if ($customfield_id == gnfe_config('insc_municipal')) { - foreach ( Capsule::table('tblcustomfieldsvalues')->where( 'fieldid', '=', $customfield_id )->where( 'relid', '=', $user_id )->get( ['value'] ) as $customfieldvalue ) { + foreach (Capsule::table('tblcustomfieldsvalues')->where('fieldid', '=', $customfield_id)->where('relid', '=', $user_id)->get(['value']) as $customfieldvalue) { $insc_customfield_value = $customfieldvalue->value; } } // cpf - if ( strpos( $customfield_name, 'cpf') and !strpos( $customfield_name, 'cnpj') ) { - foreach ( Capsule::table('tblcustomfieldsvalues')->where( 'fieldid', '=', $customfield_id )->where( 'relid', '=', $user_id )->get( ['value'] ) as $customfieldvalue ) { + if (strpos($customfield_name, 'cpf') and !strpos($customfield_name, 'cnpj')) { + foreach (Capsule::table('tblcustomfieldsvalues')->where('fieldid', '=', $customfield_id)->where('relid', '=', $user_id)->get(['value']) as $customfieldvalue) { $cpf_customfield_value = preg_replace('/[^0-9]/', '', $customfieldvalue->value); } - } + } // cnpj - if ( strpos( $customfield_name, 'cnpj') and !strpos( $customfield_name, 'cpf') ) { - foreach ( Capsule::table('tblcustomfieldsvalues')->where( 'fieldid', '=', $customfield_id )->where( 'relid', '=', $user_id )->get( ['value'] ) as $customfieldvalue ) { + if (strpos($customfield_name, 'cnpj') and !strpos($customfield_name, 'cpf')) { + foreach (Capsule::table('tblcustomfieldsvalues')->where('fieldid', '=', $customfield_id)->where('relid', '=', $user_id)->get(['value']) as $customfieldvalue) { $cnpj_customfield_value = preg_replace('/[^0-9]/', '', $customfieldvalue->value); } } // cpf + cnpj - if ( strpos( $customfield_name, 'cpf') and strpos( $customfield_name, 'cnpj') ) { - foreach ( Capsule::table('tblcustomfieldsvalues')->where( 'fieldid', '=', $customfield_id )->where( 'relid', '=', $user_id )->get( ['value'] ) as $customfieldvalue ) { + if (strpos($customfield_name, 'cpf') and strpos($customfield_name, 'cnpj')) { + foreach (Capsule::table('tblcustomfieldsvalues')->where('fieldid', '=', $customfield_id)->where('relid', '=', $user_id)->get(['value']) as $customfieldvalue) { $cpf_customfield_value = preg_replace('/[^0-9]/', '', $customfieldvalue->value); $cnpj_customfield_value = preg_replace('/[^0-9]/', '', $customfieldvalue->value); } @@ -53,56 +58,56 @@ function gnfe_customer($user_id,$client) { // Cliente possui CPF e CNPJ // CPF com 1 nº a menos, adiciona 0 antes do documento - if ( strlen( $cpf_customfield_value ) === 10 ) { - $cpf = '0' . $cpf_customfield_value; + if (10 === strlen($cpf_customfield_value)) { + $cpf = '0'.$cpf_customfield_value; } // CPF com 11 dígitos - elseif ( strlen( $cpf_customfield_value ) === 11) { + elseif (11 === strlen($cpf_customfield_value)) { $cpf = $cpf_customfield_value; } // CNPJ no campo de CPF com um dígito a menos - elseif ( strlen( $cpf_customfield_value ) === 13 ) { - $cpf = false; - $cnpj = '0' . $cpf_customfield_value; + elseif (13 === strlen($cpf_customfield_value)) { + $cpf = false; + $cnpj = '0'.$cpf_customfield_value; } // CNPJ no campo de CPF - elseif ( strlen( $cpf_customfield_value ) === 14 ) { + elseif (14 === strlen($cpf_customfield_value)) { $cpf = false; $cnpj = $cpf_customfield_value; } // cadastro não possui CPF - elseif ( !$cpf_customfield_value || strlen( $cpf_customfield_value ) !== 10 || strlen($cpf_customfield_value) !== 11 || strlen( $cpf_customfield_value ) !== 13 || strlen($cpf_customfield_value) !== 14 ) { + elseif (!$cpf_customfield_value || 10 !== strlen($cpf_customfield_value) || 11 !== strlen($cpf_customfield_value) || 13 !== strlen($cpf_customfield_value) || 14 !== strlen($cpf_customfield_value)) { $cpf = false; } // CNPJ com 1 nº a menos, adiciona 0 antes do documento - if ( strlen($cnpj_customfield_value) === 13 ) { - $cnpj = '0' . $cnpj_customfield_value; + if (13 === strlen($cnpj_customfield_value)) { + $cnpj = '0'.$cnpj_customfield_value; } // CNPJ com nº de dígitos correto - elseif ( strlen($cnpj_customfield_value) === 14 ) { + elseif (14 === strlen($cnpj_customfield_value)) { $cnpj = $cnpj_customfield_value; } // Cliente não possui CNPJ - elseif ( !$cnpj_customfield_value and strlen( $cnpj_customfield_value ) !== 14 and strlen($cnpj_customfield_value) !== 13 and strlen( $cpf_customfield_value ) !== 13 and strlen( $cpf_customfield_value ) !== 14 ) { + elseif (!$cnpj_customfield_value and 14 !== strlen($cnpj_customfield_value) and 13 !== strlen($cnpj_customfield_value) and 13 !== strlen($cpf_customfield_value) and 14 !== strlen($cpf_customfield_value)) { $cnpj = false; } - if ( ( $cpf and $cnpj ) or ( !$cpf and $cnpj ) ) { + if (($cpf and $cnpj) or (!$cpf and $cnpj)) { $custumer['doc_type'] = 2; $custumer['document'] = $cnpj; - if ( $client['companyname'] ) { + if ($client['companyname']) { $custumer['name'] = $client['companyname']; - } elseif ( !$client['companyname'] ) { - $custumer['name'] = $client['firstname'] . ' ' . $client['lastname']; + } elseif (!$client['companyname']) { + $custumer['name'] = $client['firstname'].' '.$client['lastname']; } - } elseif ( $cpf and !$cnpj ) { + } elseif ($cpf and !$cnpj) { $custumer['doc_type'] = 1; $custumer['document'] = $cpf; - $custumer['name'] = $client['firstname'] . ' ' . $client['lastname']; + $custumer['name'] = $client['firstname'].' '.$client['lastname']; } - if ($insc_customfield_value != 'NF') { + if ('NF' != $insc_customfield_value) { $custumer['insc_municipal'] = $insc_customfield_value; } - if (!$cpf and !$cnpj ) { + if (!$cpf and !$cnpj) { $error = 'CPF e/ou CNPJ ausente.'; } if (!$error) { @@ -113,20 +118,23 @@ function gnfe_customer($user_id,$client) { } } } -if ( !function_exists('gnfe_customfields') ) { - function gnfe_customfields() { +if (!function_exists('gnfe_customfields')) { + function gnfe_customfields() + { //Determine custom fields id $customfields = []; foreach (Capsule::table('tblcustomfields')->where('type', '=', 'client')->get(['fieldname', 'id']) as $customfield) { $customfields[] = $customfield; $customfield_id = $customfield->id; - $customfield_name = ' ' . strtolower($customfield->fieldname); + $customfield_name = ' '.strtolower($customfield->fieldname); } + return $customfields; } } -if ( !function_exists('gnfe_customfields_dropdow') ) { - function gnfe_customfields_dropdow() { +if (!function_exists('gnfe_customfields_dropdow')) { + function gnfe_customfields_dropdow() + { //Determine custom fields id $customfields_array = []; foreach (Capsule::table('tblcustomfields')->where('type', '=', 'client')->get(['fieldname', 'id']) as $customfield) { @@ -143,37 +151,41 @@ function gnfe_customfields_dropdow() { } else { $dropFieldArray = ['0' => 'nothing to show']; } + return $dropFieldArray; } } -if ( !function_exists('gnfe_country_code') ) { - function gnfe_country_code($country) { +if (!function_exists('gnfe_country_code')) { + function gnfe_country_code($country) + { $array = ['BD' => 'BGD', 'BE' => 'BEL', 'BF' => 'BFA', 'BG' => 'BGR', 'BA' => 'BIH', 'BB' => 'BRB', 'WF' => 'WLF', 'BL' => 'BLM', 'BM' => 'BMU', 'BN' => 'BRN', 'BO' => 'BOL', 'BH' => 'BHR', 'BI' => 'BDI', 'BJ' => 'BEN', 'BT' => 'BTN', 'JM' => 'JAM', 'BV' => 'BVT', 'BW' => 'BWA', 'WS' => 'WSM', 'BQ' => 'BES', 'BR' => 'BRA', 'BS' => 'BHS', 'JE' => 'JEY', 'BY' => 'BLR', 'BZ' => 'BLZ', 'RU' => 'RUS', 'RW' => 'RWA', 'RS' => 'SRB', 'TL' => 'TLS', 'RE' => 'REU', 'TM' => 'TKM', 'TJ' => 'TJK', 'RO' => 'ROU', 'TK' => 'TKL', 'GW' => 'GNB', 'GU' => 'GUM', 'GT' => 'GTM', 'GS' => 'SGS', 'GR' => 'GRC', 'GQ' => 'GNQ', 'GP' => 'GLP', 'JP' => 'JPN', 'GY' => 'GUY', 'GG' => 'GGY', 'GF' => 'GUF', 'GE' => 'GEO', 'GD' => 'GRD', 'GB' => 'GBR', 'GA' => 'GAB', 'SV' => 'SLV', 'GN' => 'GIN', 'GM' => 'GMB', 'GL' => 'GRL', 'GI' => 'GIB', 'GH' => 'GHA', 'OM' => 'OMN', 'TN' => 'TUN', 'JO' => 'JOR', 'HR' => 'HRV', 'HT' => 'HTI', 'HU' => 'HUN', 'HK' => 'HKG', 'HN' => 'HND', 'HM' => 'HMD', 'VE' => 'VEN', 'PR' => 'PRI', 'PS' => 'PSE', 'PW' => 'PLW', 'PT' => 'PRT', 'SJ' => 'SJM', 'PY' => 'PRY', 'IQ' => 'IRQ', 'PA' => 'PAN', 'PF' => 'PYF', 'PG' => 'PNG', 'PE' => 'PER', 'PK' => 'PAK', 'PH' => 'PHL', 'PN' => 'PCN', 'PL' => 'POL', 'PM' => 'SPM', 'ZM' => 'ZMB', 'EH' => 'ESH', 'EE' => 'EST', 'EG' => 'EGY', 'ZA' => 'ZAF', 'EC' => 'ECU', 'IT' => 'ITA', 'VN' => 'VNM', 'SB' => 'SLB', 'ET' => 'ETH', 'SO' => 'SOM', 'ZW' => 'ZWE', 'SA' => 'SAU', 'ES' => 'ESP', 'ER' => 'ERI', 'ME' => 'MNE', 'MD' => 'MDA', 'MG' => 'MDG', 'MF' => 'MAF', 'MA' => 'MAR', 'MC' => 'MCO', 'UZ' => 'UZB', 'MM' => 'MMR', 'ML' => 'MLI', 'MO' => 'MAC', 'MN' => 'MNG', 'MH' => 'MHL', 'MK' => 'MKD', 'MU' => 'MUS', 'MT' => 'MLT', 'MW' => 'MWI', 'MV' => 'MDV', 'MQ' => 'MTQ', 'MP' => 'MNP', 'MS' => 'MSR', 'MR' => 'MRT', 'IM' => 'IMN', 'UG' => 'UGA', 'TZ' => 'TZA', 'MY' => 'MYS', 'MX' => 'MEX', 'IL' => 'ISR', 'FR' => 'FRA', 'IO' => 'IOT', 'SH' => 'SHN', 'FI' => 'FIN', 'FJ' => 'FJI', 'FK' => 'FLK', 'FM' => 'FSM', 'FO' => 'FRO', 'NI' => 'NIC', 'NL' => 'NLD', 'NO' => 'NOR', 'NA' => 'NAM', 'VU' => 'VUT', 'NC' => 'NCL', 'NE' => 'NER', 'NF' => 'NFK', 'NG' => 'NGA', 'NZ' => 'NZL', 'NP' => 'NPL', 'NR' => 'NRU', 'NU' => 'NIU', 'CK' => 'COK', 'XK' => 'XKX', 'CI' => 'CIV', 'CH' => 'CHE', 'CO' => 'COL', 'CN' => 'CHN', 'CM' => 'CMR', 'CL' => 'CHL', 'CC' => 'CCK', 'CA' => 'CAN', 'CG' => 'COG', 'CF' => 'CAF', 'CD' => 'COD', 'CZ' => 'CZE', 'CY' => 'CYP', 'CX' => 'CXR', 'CR' => 'CRI', 'CW' => 'CUW', 'CV' => 'CPV', 'CU' => 'CUB', 'SZ' => 'SWZ', 'SY' => 'SYR', 'SX' => 'SXM', 'KG' => 'KGZ', 'KE' => 'KEN', 'SS' => 'SSD', 'SR' => 'SUR', 'KI' => 'KIR', 'KH' => 'KHM', 'KN' => 'KNA', 'KM' => 'COM', 'ST' => 'STP', 'SK' => 'SVK', 'KR' => 'KOR', 'SI' => 'SVN', 'KP' => 'PRK', 'KW' => 'KWT', 'SN' => 'SEN', 'SM' => 'SMR', 'SL' => 'SLE', 'SC' => 'SYC', 'KZ' => 'KAZ', 'KY' => 'CYM', 'SG' => 'SGP', 'SE' => 'SWE', 'SD' => 'SDN', 'DO' => 'DOM', 'DM' => 'DMA', 'DJ' => 'DJI', 'DK' => 'DNK', 'VG' => 'VGB', 'DE' => 'DEU', 'YE' => 'YEM', 'DZ' => 'DZA', 'US' => 'USA', 'UY' => 'URY', 'YT' => 'MYT', 'UM' => 'UMI', 'LB' => 'LBN', 'LC' => 'LCA', 'LA' => 'LAO', 'TV' => 'TUV', 'TW' => 'TWN', 'TT' => 'TTO', 'TR' => 'TUR', 'LK' => 'LKA', 'LI' => 'LIE', 'LV' => 'LVA', 'TO' => 'TON', 'LT' => 'LTU', 'LU' => 'LUX', 'LR' => 'LBR', 'LS' => 'LSO', 'TH' => 'THA', 'TF' => 'ATF', 'TG' => 'TGO', 'TD' => 'TCD', 'TC' => 'TCA', 'LY' => 'LBY', 'VA' => 'VAT', 'VC' => 'VCT', 'AE' => 'ARE', 'AD' => 'AND', 'AG' => 'ATG', 'AF' => 'AFG', 'AI' => 'AIA', 'VI' => 'VIR', 'IS' => 'ISL', 'IR' => 'IRN', 'AM' => 'ARM', 'AL' => 'ALB', 'AO' => 'AGO', 'AQ' => 'ATA', 'AS' => 'ASM', 'AR' => 'ARG', 'AU' => 'AUS', 'AT' => 'AUT', 'AW' => 'ABW', 'IN' => 'IND', 'AX' => 'ALA', 'AZ' => 'AZE', 'IE' => 'IRL', 'ID' => 'IDN', 'UA' => 'UKR', 'QA' => 'QAT', 'MZ' => 'MOZ']; + return $array[$country]; } } -if ( !function_exists('gnfe_ibge') ) { - function gnfe_ibge($zip) { +if (!function_exists('gnfe_ibge')) { + function gnfe_ibge($zip) + { $curl = curl_init(); - curl_setopt ($curl, CURLOPT_URL, 'https://open.nfe.io/v1/cities/' . $zip . '/postalcode'); - curl_setopt ($curl, CURLOPT_TIMEOUT, 30); - curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); - $response = curl_exec ($curl); - curl_close ($curl); + curl_setopt($curl, CURLOPT_URL, 'https://open.nfe.io/v1/cities/'.$zip.'/postalcode'); + curl_setopt($curl, CURLOPT_TIMEOUT, 30); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); + $response = curl_exec($curl); + curl_close($curl); $city = json_decode(json_encode(json_decode($response))); + return $city->city->code; } } -if ( !function_exists('gnfe_queue_nfe') ) { - function gnfe_queue_nfe($invoice_id,$create_all = false) { - $invoice = localAPI('GetInvoice', ['invoiceid' => $invoice_id], false); +if (!function_exists('gnfe_queue_nfe')) { + function gnfe_queue_nfe($invoice_id, $create_all = false) + { + $invoice = localAPI('GetInvoice', ['invoiceid' => $invoice_id], false); $itens = get_prodict_invoice($invoice_id); - logModuleCall('gofas_nfeio', 'gnfe_queue_nfe itens',$itens , '', '', 'replaceVars'); + logModuleCall('gofas_nfeio', 'itens teste', $itens, '', '', 'replaceVars'); if (!$itens) { - foreach (Capsule::table('tblinvoiceitems')->where( 'invoiceid', '=', $invoice_id )->get( ['userid', 'amount']) as $item_not_salle) { - logModuleCall('gofas_nfeio', 'gnfe_queue_nfe item_not_salle',$item_not_salle , '', '', 'replaceVars'); - + foreach (Capsule::table('tblinvoiceitems')->where('invoiceid', '=', $invoice_id)->get(['userid', 'amount']) as $item_not_salle) { $data = [ 'invoice_id' => $invoice_id, 'user_id' => $item_not_salle->userid, @@ -187,11 +199,12 @@ function gnfe_queue_nfe($invoice_id,$create_all = false) { 'updated_at' => 'waiting', 'rpsSerialNumber' => 'waiting', ]; + try { $service_code_row = Capsule::table('gofasnfeio')->whereNull('service_code')->where('invoice_id', '=', $invoice_id)->get(['id', 'services_amount']); - logModuleCall('gofas_nfeio', 'service_code_row',$service_code_row , '', '', 'replaceVars'); + logModuleCall('gofas_nfeio', 'service_code_row', $service_code_row, '', '', 'replaceVars'); - if (count($service_code_row) == 1) { + if (1 == count($service_code_row)) { $mountDB = floatval($service_code_row[0]->services_amount); $mount_item = floatval($item_not_salle->amount); $mount = $mountDB + $mount_item; @@ -203,6 +216,7 @@ function gnfe_queue_nfe($invoice_id,$create_all = false) { return $e->getMessage(); } } + return 'success'; } foreach ($itens as $item) { @@ -224,10 +238,11 @@ function gnfe_queue_nfe($invoice_id,$create_all = false) { $nfe_for_invoice = gnfe_get_local_nfe($invoice_id, ['status']); if (!$nfe_for_invoice['status'] || $create_all) { $create_all = true; + try { $service_code_row = Capsule::table('gofasnfeio')->where('service_code', '=', $item['value'])->where('invoice_id', '=', $invoice_id)->get(['id', 'services_amount']); - if (count($service_code_row) == 1) { + if (1 == count($service_code_row)) { $mountDB = floatval($service_code_row[0]->services_amount); $mount_item = floatval($item['monthly']); $mount = $mountDB + $mount_item; @@ -239,7 +254,7 @@ function gnfe_queue_nfe($invoice_id,$create_all = false) { } catch (\Exception $e) { return $e->getMessage(); } - } elseif ((string)$nfe_for_invoice['status'] === (string)'Cancelled' or (string)$nfe_for_invoice['status'] === (string)'Error') { + } elseif ((string) $nfe_for_invoice['status'] === (string) 'Cancelled' or (string) $nfe_for_invoice['status'] === (string) 'Error') { try { $update_nfe = Capsule::table('gofasnfeio')->where('invoice_id', '=', $invoice_id)->update($data); } catch (\Exception $e) { @@ -247,13 +262,15 @@ function gnfe_queue_nfe($invoice_id,$create_all = false) { } } } + return 'success'; } } -if ( !function_exists('gnfe_queue_nfe_edit') ) { - function gnfe_queue_nfe_edit($invoice_id,$gofasnfeio_id) { - $invoice = localAPI('GetInvoice', ['invoiceid' => $invoice_id], false); +if (!function_exists('gnfe_queue_nfe_edit')) { + function gnfe_queue_nfe_edit($invoice_id, $gofasnfeio_id) + { + $invoice = localAPI('GetInvoice', ['invoiceid' => $invoice_id], false); $itens = get_prodict_invoice($invoice_id); foreach ($itens as $item) { @@ -274,7 +291,7 @@ function gnfe_queue_nfe_edit($invoice_id,$gofasnfeio_id) { $nfe_for_invoice = gnfe_get_local_nfe($invoice_id, ['status']); - if ((string)$nfe_for_invoice['status'] === (string)'Cancelled' or (string)$nfe_for_invoice['status'] === (string)'Error') { + if ((string) $nfe_for_invoice['status'] === (string) 'Cancelled' or (string) $nfe_for_invoice['status'] === (string) 'Error') { try { $update_nfe = Capsule::table('gofasnfeio')->where('invoice_id', '=', $invoice_id)->where('id', '=', $gofasnfeio_id)->update($data); } catch (\Exception $e) { @@ -282,44 +299,52 @@ function gnfe_queue_nfe_edit($invoice_id,$gofasnfeio_id) { } } } - return 'success'; - } -} -if ( !function_exists('gnfe_queue_nfe_edit_all') ) { - function gnfe_queue_nfe_edit_all($invoice_id) { - $invoice = localAPI('GetInvoice', ['invoiceid' => $invoice_id], false); - - $data = [ - 'invoice_id' => $invoice_id, - 'user_id' => $invoice['userid'], - 'nfe_id' => 'waiting', - 'status' => 'Waiting', - 'environment' => 'waiting', - 'flow_status' => 'waiting', - 'pdf' => 'waiting', - 'created_at' => date('Y-m-d H:i:s'), - 'updated_at' => 'waiting', - 'rpsSerialNumber' => 'waiting', - ]; - - $nfe_for_invoice = gnfe_get_local_nfe($invoice_id, ['status']); - - if ((string)$nfe_for_invoice['status'] === (string)'Cancelled' or (string)$nfe_for_invoice['status'] === (string)'Error') { - try { - $update_nfe = Capsule::table('gofasnfeio')->where('invoice_id', '=', $invoice_id)->update($data); - } catch (\Exception $e) { - return $e->getMessage(); - } - } return 'success'; } } -if ( !function_exists('gnfe_issue_nfe') ) { - function gnfe_issue_nfe($postfields) { - $webhook_url = gnfe_whmcs_url() . 'modules/addons/gofasnfeio/callback.php'; - foreach ( Capsule::table('tblconfiguration')->where('setting', '=', 'gnfe_webhook_id')->get( ['value'] ) as $gnfe_webhook_id_ ) { +// if (!function_exists('gnfe_queue_nfe_edit_all')) { +// function gnfe_queue_nfe_edit_all($invoice_id) +// { +// $invoice = localAPI('GetInvoice', ['invoiceid' => $invoice_id], false); +// $itens = get_prodict_invoice($invoice_id); +// foreach ($itens as $item) { +// $data = [ +// 'invoice_id' => $invoice_id, +// 'user_id' => $invoice['userid'], +// 'nfe_id' => 'waiting', +// 'status' => 'Waiting', +// 'services_amount' => $item['monthly'], +// 'environment' => 'waiting', +// 'flow_status' => 'waiting', +// 'pdf' => 'waiting', +// 'created_at' => date('Y-m-d H:i:s'), +// 'updated_at' => 'waiting', +// 'rpsSerialNumber' => 'waiting', +// 'service_code' => $item['value'], +// ]; + +// $nfe_for_invoice = gnfe_get_local_nfe($invoice_id, ['status']); + +// if (!$nfe_for_invoice['status']) { +// try { +// $save_nfe = Capsule::table('gofasnfeio')->insert($data); +// } catch (\Exception $e) { +// return $e->getMessage(); +// } +// } +// } + +// return 'success'; +// } +// } + +if (!function_exists('gnfe_issue_nfe')) { + function gnfe_issue_nfe($postfields) + { + $webhook_url = gnfe_whmcs_url().'modules/addons/gofasnfeio/callback.php'; + foreach (Capsule::table('tblconfiguration')->where('setting', '=', 'gnfe_webhook_id')->get(['value']) as $gnfe_webhook_id_) { $gnfe_webhook_id = $gnfe_webhook_id_->value; } if ($gnfe_webhook_id) { @@ -328,14 +353,14 @@ function gnfe_issue_nfe($postfields) { $error .= $check_webhook['message']; } } - if ( $gnfe_webhook_id and (string)$check_webhook['hooks']['url'] !== (string)$webhook_url ) { + 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']; } 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')]); + 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(); } @@ -359,50 +384,56 @@ function gnfe_issue_nfe($postfields) { } } if (gnfe_config('debug')) { - logModuleCall('gofas_nfeio', 'check_webhook', ['gnfe_webhook_id' => $gnfe_webhook_id, 'check_webhook' => $check_webhook, 'check_webhook_url' => $check_webhook['hooks']['url']], 'post', ['create_webhook' => $create_webhook, 'delete_webhook' => $delete_webhook, 'error' => $error], 'replaceVars'); + logModuleCall('gofas_nfeio', 'check_webhook', ['gnfe_webhook_id' => $gnfe_webhook_id, 'check_webhook' => $check_webhook, 'check_webhook_url' => $check_webhook['hooks']['url']], 'post', ['create_webhook' => $create_webhook, 'delete_webhook' => $delete_webhook, 'error' => $error], 'replaceVars'); } $curl = curl_init(); - 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_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); curl_setopt($curl, CURLOPT_POST, 1); - curl_setopt($curl, CURLOPT_POSTFIELDS,json_encode($postfields)); - curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); - $response = curl_exec ($curl); - curl_close ($curl); - logModuleCall('gofas_nfeio', 'resp',$response , '', '', 'replaceVars'); + curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($postfields)); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); + $response = curl_exec($curl); + curl_close($curl); + logModuleCall('gofas_nfeio', 'resp', $response, '', '', 'replaceVars'); + return json_decode(json_encode(json_decode($response))); } } -if ( !function_exists('gnfe_get_nfe') ) { - function gnfe_get_nfe($nf) { +if (!function_exists('gnfe_get_nfe')) { + function gnfe_get_nfe($nf) + { $curl = curl_init(); - curl_setopt($curl, CURLOPT_URL, 'https://api.nfe.io/v1/companies/' . gnfe_config('company_id') . '/serviceinvoices/' . $nf); - curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: text/json', 'Accept: application/json', 'Authorization: ' . gnfe_config('api_key')]); + curl_setopt($curl, CURLOPT_URL, 'https://api.nfe.io/v1/companies/'.gnfe_config('company_id').'/serviceinvoices/'.$nf); + curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: text/json', 'Accept: application/json', 'Authorization: '.gnfe_config('api_key')]); curl_setopt($curl, CURLOPT_TIMEOUT, 30); - curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); - $response = curl_exec ($curl); - curl_close ($curl); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); + $response = curl_exec($curl); + curl_close($curl); + return json_decode($response); } } -if ( !function_exists('gnfe_get_nfes') ) { - function gnfe_get_nfes() { +if (!function_exists('gnfe_get_nfes')) { + function gnfe_get_nfes() + { $curl = curl_init(); - curl_setopt($curl, CURLOPT_URL, 'https://api.nfe.io/v1/companies/' . gnfe_config('company_id') . '/serviceinvoices?pageCount=1&pageIndex=1'); - curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: text/json', 'Accept: application/json', 'Authorization: ' . gnfe_config('api_key')]); + curl_setopt($curl, CURLOPT_URL, 'https://api.nfe.io/v1/companies/'.gnfe_config('company_id').'/serviceinvoices?pageCount=1&pageIndex=1'); + curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: text/json', 'Accept: application/json', 'Authorization: '.gnfe_config('api_key')]); curl_setopt($curl, CURLOPT_TIMEOUT, 30); - curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); - $response = curl_exec ($curl); - curl_close ($curl); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); + $response = curl_exec($curl); + curl_close($curl); + return json_decode($response, true); } } -if ( !function_exists('gnfe_get_invoice_nfes') ) { - function gnfe_get_invoice_nfes($invoice_id) { +if (!function_exists('gnfe_get_invoice_nfes')) { + function gnfe_get_invoice_nfes($invoice_id) + { $nfes = []; // foreach( Capsule::table('tbladdonmodules') -> where( 'module', '=', 'gofasnfeio' ) -> get( array( 'setting', 'value') ) as $settings ) { - foreach ( Capsule::table('gofasnfeio')->where('invoice_id', '=', $invoice_id)->get(['invoice_id', 'user_id', 'nfe_id', 'status', 'services_amount', 'environment', 'flow_status', 'pdf', 'created_at', 'updated_at', 'rpsSerialNumber', 'rpsNumber'] ) as $nfe ) { + foreach (Capsule::table('gofasnfeio')->where('invoice_id', '=', $invoice_id)->get(['invoice_id', 'user_id', 'nfe_id', 'status', 'services_amount', 'environment', 'flow_status', 'pdf', 'created_at', 'updated_at', 'rpsSerialNumber', 'rpsNumber']) as $nfe) { $nfes = $nfe; } @@ -412,7 +443,6 @@ function gnfe_get_invoice_nfes($invoice_id) { $fieldArray = ['status' => 'error', 'message' => 'database error']; } elseif (count($checkfields) >= 1) { $fieldArray = ['status' => 'success', 'result' => $checkfields]; - ; } else { $fieldArray = ['status' => 'error', 'message' => 'nothing to show']; } @@ -420,78 +450,89 @@ function gnfe_get_invoice_nfes($invoice_id) { return $fieldArray; } } -if ( !function_exists('gnfe_delete_nfe') ) { - function gnfe_delete_nfe($nf) { +if (!function_exists('gnfe_delete_nfe')) { + function gnfe_delete_nfe($nf) + { $curl = curl_init(); - curl_setopt($curl, CURLOPT_URL, 'https://api.nfe.io/v1/companies/' . gnfe_config('company_id') . '/serviceinvoices/' . $nf); - curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: text/json', 'Accept: application/json', 'Authorization: ' . gnfe_config('api_key')]); + curl_setopt($curl, CURLOPT_URL, 'https://api.nfe.io/v1/companies/'.gnfe_config('company_id').'/serviceinvoices/'.$nf); + curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: text/json', 'Accept: application/json', 'Authorization: '.gnfe_config('api_key')]); curl_setopt($curl, CURLOPT_TIMEOUT, 30); - curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE'); - $response = curl_exec ($curl); - curl_close ($curl); + $response = curl_exec($curl); + curl_close($curl); + return json_decode($response); } } -if ( !function_exists('gnfe_email_nfe') ) { - function gnfe_email_nfe($nf) { - if (gnfe_config('gnfe_email_nfe_config') == 'on') { +if (!function_exists('gnfe_email_nfe')) { + function gnfe_email_nfe($nf) + { + if ('on' == gnfe_config('gnfe_email_nfe_config')) { $curl = curl_init(); - curl_setopt($curl, CURLOPT_URL, 'https://api.nfe.io/v1/companies/' . gnfe_config('company_id') . '/serviceinvoices/' . $nf . '/sendemail'); - curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: text/json', 'Accept: application/json', 'Authorization: ' . gnfe_config('api_key')]); + curl_setopt($curl, CURLOPT_URL, 'https://api.nfe.io/v1/companies/'.gnfe_config('company_id').'/serviceinvoices/'.$nf.'/sendemail'); + curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: text/json', 'Accept: application/json', 'Authorization: '.gnfe_config('api_key')]); curl_setopt($curl, CURLOPT_TIMEOUT, 30); - curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT'); - $response = curl_exec ($curl); - curl_close ($curl); + $response = curl_exec($curl); + curl_close($curl); + return json_decode($response); } } } -if ( !function_exists('gnfe_pdf_nfe') ) { - function gnfe_pdf_nfe($nf) { +if (!function_exists('gnfe_pdf_nfe')) { + function gnfe_pdf_nfe($nf) + { $curl = curl_init(); - curl_setopt($curl, CURLOPT_URL, 'https://api.nfe.io/v1/companies/' . gnfe_config('company_id') . '/serviceinvoices/' . $nf . '/pdf'); - curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-type: application/pdf', 'Authorization: ' . gnfe_config('api_key')]); - curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); + curl_setopt($curl, CURLOPT_URL, 'https://api.nfe.io/v1/companies/'.gnfe_config('company_id').'/serviceinvoices/'.$nf.'/pdf'); + curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-type: application/pdf', 'Authorization: '.gnfe_config('api_key')]); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET'); - curl_setopt($curl, CURLOPT_RETURNTRANSFER,true); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($curl, CURLOPT_TIMEOUT, 10); curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 30); header('Content-type: application/pdf'); $result = curl_exec($curl); curl_close($curl); + return $result; } } -if ( !function_exists('gnfe_xml_nfe') ) { - function gnfe_xml_nfe($nf) { +if (!function_exists('gnfe_xml_nfe')) { + function gnfe_xml_nfe($nf) + { $curl = curl_init(); - curl_setopt($curl, CURLOPT_URL, 'https://api.nfe.io/v1/companies/' . gnfe_config('company_id') . '/serviceinvoices/' . $nf . '/xml'); - curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: text/json', 'Accept: application/json', 'Authorization: ' . gnfe_config('api_key')]); + curl_setopt($curl, CURLOPT_URL, 'https://api.nfe.io/v1/companies/'.gnfe_config('company_id').'/serviceinvoices/'.$nf.'/xml'); + curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: text/json', 'Accept: application/json', 'Authorization: '.gnfe_config('api_key')]); curl_setopt($curl, CURLOPT_TIMEOUT, 30); - curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); - $response = curl_exec ($curl); - curl_close ($curl); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); + $response = curl_exec($curl); + curl_close($curl); + return json_decode($response); } } -if ( !function_exists('gnfe_whmcs_url') ) { - function gnfe_whmcs_url() { - foreach ( Capsule::table('tblconfiguration')->where('setting', '=', 'gnfewhmcsurl')->get( ['value'] ) as $gnfewhmcsurl_ ) { +if (!function_exists('gnfe_whmcs_url')) { + function gnfe_whmcs_url() + { + foreach (Capsule::table('tblconfiguration')->where('setting', '=', 'gnfewhmcsurl')->get(['value']) as $gnfewhmcsurl_) { $gnfewhmcsurl = $gnfewhmcsurl_->value; } + return $gnfewhmcsurl; } } -if ( !function_exists('gnfe_xml_nfe') ) { - function gnfe_xml_nfe($nf) { +if (!function_exists('gnfe_xml_nfe')) { + function gnfe_xml_nfe($nf) + { $curl = curl_init(); curl_setopt_array($curl, [ - CURLOPT_URL => 'https://api.nfe.io/v1/companies/' . gnfe_config('company_id') . '/serviceinvoices/' . $nf . '/xml', + CURLOPT_URL => 'https://api.nfe.io/v1/companies/'.gnfe_config('company_id').'/serviceinvoices/'.$nf.'/xml', CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => '', CURLOPT_MAXREDIRS => 10, @@ -502,28 +543,32 @@ function gnfe_xml_nfe($nf) { CURLOPT_HTTPHEADER => [ 'Content-Type: text/json', 'Accept: application/json', - 'Authorization:' . gnfe_config('api_key') + 'Authorization:'.gnfe_config('api_key'), ], ]); $response = curl_exec($curl); curl_close($curl); + return $response; } } -if ( !function_exists('gnfe_whmcs_admin_url') ) { - function gnfe_whmcs_admin_url() { - foreach ( Capsule::table('tblconfiguration')->where('setting', '=', 'gnfewhmcsadminurl')->get( ['value'] ) as $gnfewhmcsadminurl_ ) { +if (!function_exists('gnfe_whmcs_admin_url')) { + function gnfe_whmcs_admin_url() + { + foreach (Capsule::table('tblconfiguration')->where('setting', '=', 'gnfewhmcsadminurl')->get(['value']) as $gnfewhmcsadminurl_) { $gnfewhmcsadminurl = $gnfewhmcsadminurl_->value; } + return $gnfewhmcsadminurl; } } -if ( !function_exists('gnfe_save_nfe') ) { - function gnfe_save_nfe($nfe,$user_id,$invoice_id,$pdf,$created_at,$updated_at) { +if (!function_exists('gnfe_save_nfe')) { + function gnfe_save_nfe($nfe, $user_id, $invoice_id, $pdf, $created_at, $updated_at) + { $data = [ 'invoice_id' => $invoice_id, 'user_id' => $user_id, @@ -538,16 +583,19 @@ function gnfe_save_nfe($nfe,$user_id,$invoice_id,$pdf,$created_at,$updated_at) { 'rpsSerialNumber' => $nfe->rpsSerialNumber, 'rpsNumber' => $nfe->rpsNumber, ]; + try { $save_nfe = Capsule::table('gofasnfeio')->insert($data); + return 'success'; } catch (\Exception $e) { return $e->getMessage(); } } } -if ( !function_exists('gnfe_update_nfe') ) { - function gnfe_update_nfe($nfe,$user_id,$invoice_id,$pdf,$created_at,$updated_at,$id_gofasnfeio = false) { +if (!function_exists('gnfe_update_nfe')) { + function gnfe_update_nfe($nfe, $user_id, $invoice_id, $pdf, $created_at, $updated_at, $id_gofasnfeio = false) + { $data = [ 'invoice_id' => $invoice_id, 'user_id' => $user_id, @@ -562,7 +610,8 @@ function gnfe_update_nfe($nfe,$user_id,$invoice_id,$pdf,$created_at,$updated_at, 'rpsSerialNumber' => $nfe->rpsSerialNumber, 'rpsNumber' => $nfe->rpsNumber, ]; - logModuleCall('gofas_nfeio', '$data',$data , '', '', 'replaceVars'); + logModuleCall('gofas_nfeio', '$data', $data, '', '', 'replaceVars'); + try { if (!$id_gofasnfeio) { $id = $invoice_id; @@ -571,76 +620,88 @@ function gnfe_update_nfe($nfe,$user_id,$invoice_id,$pdf,$created_at,$updated_at, $id = $id_gofasnfeio; $camp = 'id'; } - $save_nfe = Capsule::table('gofasnfeio')->where($camp, '=',$id)->update($data); + $save_nfe = Capsule::table('gofasnfeio')->where($camp, '=', $id)->update($data); + return 'success'; } catch (\Exception $e) { return $e->getMessage(); } } } -if ( !function_exists('gnfe_update_rps') ) { - function gnfe_update_rps($rps_serial_number, $rps_number) { +if (!function_exists('gnfe_update_rps')) { + function gnfe_update_rps($rps_serial_number, $rps_number) + { $setting = []; - foreach ( Capsule::table('tbladdonmodules')->where( 'module', '=', 'gofasnfeio' )->get( ['setting', 'value'] ) as $settings ) { + foreach (Capsule::table('tbladdonmodules')->where('module', '=', 'gofasnfeio')->get(['setting', 'value']) as $settings) { $setting[$settings->setting] = $settings->value; } + try { if ($rps_serial_number) { - $update_rps_serial_number = Capsule::table('tbladdonmodules')->where( 'module', '=', 'gofasnfeio' )->where( 'setting', '=', 'rps_serial_number' )->update(['value' => $rps_serial_number]); + $update_rps_serial_number = Capsule::table('tbladdonmodules')->where('module', '=', 'gofasnfeio')->where('setting', '=', 'rps_serial_number')->update(['value' => $rps_serial_number]); } if ($rps_number) { - $update_serial_number = Capsule::table('tbladdonmodules')->where( 'module', '=', 'gofasnfeio' )->where( 'setting', '=', 'rps_number' )->update(['value' => $rps_number + 1]); + $update_serial_number = Capsule::table('tbladdonmodules')->where('module', '=', 'gofasnfeio')->where('setting', '=', 'rps_number')->update(['value' => $rps_number + 1]); } + return 'success'; } catch (\Exception $e) { return $e->getMessage(); } } } -if ( !function_exists('gnfe_get_local_nfe') ) { - function gnfe_get_local_nfe($invoice_id, $values ) { - foreach ( Capsule::table('gofasnfeio')->where('invoice_id', '=', $invoice_id)->get($values) as $key => $value ) { +if (!function_exists('gnfe_get_local_nfe')) { + function gnfe_get_local_nfe($invoice_id, $values) + { + foreach (Capsule::table('gofasnfeio')->where('invoice_id', '=', $invoice_id)->get($values) as $key => $value) { $nfe_for_invoice[$key] = json_decode(json_encode($value), true); } + return $nfe_for_invoice['0']; } } -if ( !function_exists('gnfe_check_webhook') ) { - function gnfe_check_webhook($id) { +if (!function_exists('gnfe_check_webhook')) { + function gnfe_check_webhook($id) + { $curl = curl_init(); - curl_setopt($curl, CURLOPT_URL, 'https://api.nfe.io/v1/hooks/' . $id); - curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: text/json', 'Accept: application/json', 'Authorization: ' . gnfe_config('api_key')]); + curl_setopt($curl, CURLOPT_URL, 'https://api.nfe.io/v1/hooks/'.$id); + curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: text/json', 'Accept: application/json', 'Authorization: '.gnfe_config('api_key')]); curl_setopt($curl, CURLOPT_TIMEOUT, 30); - curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); - $response = curl_exec ($curl); - curl_close ($curl); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); + $response = curl_exec($curl); + curl_close($curl); + return json_decode(json_encode(json_decode($response)), true); } } -if ( !function_exists('gnfe_create_webhook') ) { - function gnfe_create_webhook($url) { +if (!function_exists('gnfe_create_webhook')) { + function gnfe_create_webhook($url) + { $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, 'https://api.nfe.io/v1/hooks'); - curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: text/json', 'Accept: application/json', 'Authorization: ' . gnfe_config('api_key')]); + curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: text/json', 'Accept: application/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_RETURNTRANSFER,1); - $response = curl_exec ($curl); - curl_close ($curl); + curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode(['url' => $url, 'contentType' => 'application/json', 'secret' => (string) time(), 'events' => ['issue', 'cancel'], 'status' => 'Active'])); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); + $response = curl_exec($curl); + curl_close($curl); + return json_decode(json_encode(json_decode($response)), true); } } -if ( !function_exists('gnfe_delete_webhook') ) { - function gnfe_delete_webhook($id) { +if (!function_exists('gnfe_delete_webhook')) { + function gnfe_delete_webhook($id) + { $curl = curl_init(); - curl_setopt($curl, CURLOPT_URL, 'https://api.nfe.io/v1/hooks/' . $id); - curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: text/json', 'Accept: application/json', 'Authorization: ' . gnfe_config('api_key')]); + curl_setopt($curl, CURLOPT_URL, 'https://api.nfe.io/v1/hooks/'.$id); + curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: text/json', 'Accept: application/json', 'Authorization: '.gnfe_config('api_key')]); curl_setopt($curl, CURLOPT_TIMEOUT, 30); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE'); - curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); - $response = curl_exec ($curl); - curl_close ($curl); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); + $response = curl_exec($curl); + curl_close($curl); + return json_decode(json_encode(json_decode($response)), true); } } @@ -650,39 +711,40 @@ function gnfe_delete_webhook($id) { * CancelFailed, IssueFailed, Issued, Cancelled, PullFromCityHall, WaitingCalculateTaxes, * WaitingDefineRpsNumber, WaitingSend, WaitingSendCancel, WaitingReturn, WaitingDownload */ -if ( !function_exists('gnfe_nfe_flowStatus') ) { - function gnfe_nfe_flowStatus($flowStatus) { - if ($flowStatus === 'CancelFailed') { +if (!function_exists('gnfe_nfe_flowStatus')) { + function gnfe_nfe_flowStatus($flowStatus) + { + if ('CancelFailed' === $flowStatus) { $status = 'Cancelado por Erro'; } - if ($flowStatus === 'IssueFailed') { + if ('IssueFailed' === $flowStatus) { $status = 'Falha ao Emitir'; } - if ($flowStatus === 'Issued') { + if ('Issued' === $flowStatus) { $status = 'Emitida'; } - if ($flowStatus === 'Cancelled') { + if ('Cancelled' === $flowStatus) { $status = 'Cancelada'; } - if ($flowStatus === 'PullFromCityHall') { + if ('PullFromCityHall' === $flowStatus) { $status = 'Obtendo da Prefeitura'; } - if ($flowStatus === 'WaitingCalculateTaxes') { + if ('WaitingCalculateTaxes' === $flowStatus) { $status = 'Aguardando Calcular Impostos'; } - if ($flowStatus === 'WaitingDefineRpsNumber') { + if ('WaitingDefineRpsNumber' === $flowStatus) { $status = 'Aguardando Definir Número Rps'; } - if ($flowStatus === 'WaitingSend') { + if ('WaitingSend' === $flowStatus) { $status = 'Aguardando Enviar'; } - if ($flowStatus === 'WaitingSendCancel') { + if ('WaitingSendCancel' === $flowStatus) { $status = 'Aguardando Cancelar Envio'; } - if ($flowStatus === 'WaitingReturn') { + if ('WaitingReturn' === $flowStatus) { $status = 'Aguardando Retorno'; } - if ($flowStatus === 'WaitingDownload') { + if ('WaitingDownload' === $flowStatus) { $status = 'Aguardando Download'; } @@ -690,25 +752,29 @@ function gnfe_nfe_flowStatus($flowStatus) { } } -if ( !function_exists('gnfe_get_company') ) { - function gnfe_get_company() { +if (!function_exists('gnfe_get_company')) { + function gnfe_get_company() + { $curl = curl_init(); - curl_setopt($curl, CURLOPT_URL, 'https://api.nfe.io/v1/companies/' . gnfe_config('company_id')); - curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: text/json', 'Accept: application/json', 'Authorization: ' . gnfe_config('api_key')]); + curl_setopt($curl, CURLOPT_URL, 'https://api.nfe.io/v1/companies/'.gnfe_config('company_id')); + curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: text/json', 'Accept: application/json', 'Authorization: '.gnfe_config('api_key')]); curl_setopt($curl, CURLOPT_TIMEOUT, 30); - curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); - $response = curl_exec ($curl); - curl_close ($curl); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); + $response = curl_exec($curl); + curl_close($curl); + return json_decode($response, true); } } -if ( !function_exists('set_custom_field_ini_date') ) { - function set_custom_field_ini_date() { +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) { + 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) { @@ -717,42 +783,58 @@ function set_custom_field_ini_date() { } } -if ( !function_exists('gnfe_get_company') ) { - function gnfe_get_company() { +if (!function_exists('gnfe_get_company')) { + function gnfe_get_company() + { $curl = curl_init(); - curl_setopt($curl, CURLOPT_URL, 'https://api.nfe.io/v1/companies/' . gnfe_config('company_id')); - curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: text/json', 'Accept: application/json', 'Authorization: ' . gnfe_config('api_key')]); + curl_setopt($curl, CURLOPT_URL, 'https://api.nfe.io/v1/companies/'.gnfe_config('company_id')); + curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: text/json', 'Accept: application/json', 'Authorization: '.gnfe_config('api_key')]); curl_setopt($curl, CURLOPT_TIMEOUT, 30); - curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); - $response = curl_exec ($curl); - curl_close ($curl); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); + $response = curl_exec($curl); + curl_close($curl); + return json_decode($response, true); } } -if ( !function_exists('gnfe_customer_service_code') ) { - function gnfe_customer_service_code($item_id) { +if (!function_exists('gnfe_customer_service_code')) { + function gnfe_customer_service_code($item_id) + { $customfields = []; - foreach ( Capsule::table('tblcustomfields')->where( 'type', '=', 'product' )->where( 'fieldname', '=', 'Código de Serviço' )->get( ['fieldname', 'id'] ) as $customfield ) { + foreach (Capsule::table('tblcustomfields')->where('type', '=', 'product')->where('fieldname', '=', 'Código de Serviço')->get(['fieldname', 'id']) as $customfield) { $customfield_id = $customfield->id; $insc_customfield_value = 'NF'; - foreach ( Capsule::table('tblcustomfieldsvalues')->where( 'fieldid', '=', $customfield_id )->where( 'relid', '=', $item_id )->get( ['value'] ) as $customfieldvalue ) { - $insc_customfield_value = $customfieldvalue->value; - return $insc_customfield_value; + foreach (Capsule::table('tblcustomfieldsvalues')->where('fieldid', '=', $customfield_id)->where('relid', '=', $item_id)->get(['value']) as $customfieldvalue) { + return $customfieldvalue->value; } } } } -function get_prodict_invoice($invoice_id) { +function get_prodict_invoice($invoice_id) +{ $query = "SELECT DISTINCT tblhosting.packageid,tblpricing.monthly from tblhosting INNER JOIN tblinvoiceitems ON tblinvoiceitems.relid = tblhosting.id JOIN tblpricing ON tblpricing.relid = tblhosting.packageid - WHERE tblpricing.type = 'product' AND tblinvoiceitems.invoiceid = :id"; + LEFT JOIN tblproducts ON tblproducts.id = tblhosting.packageid + WHERE tblpricing.type = 'product' AND tblinvoiceitems.invoiceid = :id"; $pdo = Capsule::connection()->getPdo(); $pdo->beginTransaction(); + $tax_check = gnfe_config('tax'); $row = null; $list = []; + + if ('Sim' != $tax_check) { + logModuleCall('gofas_nfeio', 'true get_prodict_invoice', $tax_check, '', '', 'replaceVars'); + + $query .= 'AND tblproducts.tax = 1'; + } else { + logModuleCall('gofas_nfeio', 'false get_prodict_invoice', $tax_check, '', '', 'replaceVars'); + + Capsule::table('tblproducts')->update(['tax' => 1]); + } + try { $statement = $pdo->prepare($query); $statement->execute([':id' => $invoice_id]); @@ -760,10 +842,11 @@ function get_prodict_invoice($invoice_id) { $pdo->commit(); } catch (\Throwable $th) { $pdo->rollBack(); - logModuleCall('gofas_nfeio', 'erroGetProdictInvoice',$th , '', '', 'replaceVars'); + logModuleCall('gofas_nfeio', 'erroGetProdictInvoice', $th, '', '', 'replaceVars'); } foreach ($row as $item) { $pdo->beginTransaction(); + try { $list2 = []; $stmt = $pdo->prepare('SELECT * FROM tblproductcode WHERE product_id=:PROD'); @@ -776,16 +859,19 @@ function get_prodict_invoice($invoice_id) { $list[] = $list2; } catch (\Throwable $th) { $pdo->rollBack(); - logModuleCall('gofas_nfeio', 'erroForeach',$th , '', '', 'replaceVars'); + logModuleCall('gofas_nfeio', 'erroForeach', $th, '', '', 'replaceVars'); } } + return $list; } -if ( !function_exists('set_code_service_camp_gofasnfeio') ) { - function set_code_service_camp_gofasnfeio() { +if (!function_exists('set_code_service_camp_gofasnfeio')) { + function set_code_service_camp_gofasnfeio() + { $pdo = Capsule::connection()->getPdo(); $pdo->beginTransaction(); + try { $statement = $pdo->prepare('ALTER TABLE gofasnfeio ADD service_code TEXT; ALTER TABLE gofasnfeio ADD monthly DECIMAL(16,2)'); @@ -796,8 +882,9 @@ function set_code_service_camp_gofasnfeio() { } } } -if ( !function_exists('create_table_product_code') ) { - function create_table_product_code() { +if (!function_exists('create_table_product_code')) { + function create_table_product_code() + { $pdo = Capsule::connection()->getPdo(); $pdo->beginTransaction(); @@ -817,9 +904,10 @@ function create_table_product_code() { } } -function update_table() { +function update_table() +{ $current_version = '1.2.5'; - $row = Capsule::table('tblconfiguration')->where( 'setting', '=', 'version_nfeio' )->get(['value']); + $row = Capsule::table('tblconfiguration')->where('setting', '=', 'version_nfeio')->get(['value']); $version = $row[0]; if ($version != $current_version) { create_table_product_code(); @@ -827,4 +915,4 @@ function update_table() { } else { Capsule::table('tblconfiguration')->insert(['setting' => 'version_nfeio', 'value' => $current_version, 'created_at' => date('Y-m-d H:i:s')]); } -} \ No newline at end of file +} diff --git a/modules/addons/gofasnfeio/hooks.php b/modules/addons/gofasnfeio/hooks.php index 4b7c7ce..1e789c5 100644 --- a/modules/addons/gofasnfeio/hooks.php +++ b/modules/addons/gofasnfeio/hooks.php @@ -1,35 +1,43 @@ 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 ) { +if ('Manualmente' !== $params['issue_note'] && $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) { $datepaid = date('Ymd', strtotime($invoices->datepaid)); - $datepaid_to_issue_ = '-' . $params['issue_note_after'] . ' days'; + $datepaid_to_issue_ = '-'.$params['issue_note_after'].' days'; $datepaid_to_issue = date('Ymd', strtotime($datepaid_to_issue_)); //ver isso com varios registros - $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) { + $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); + $customer = gnfe_customer($invoices->userid, $client); /*if($params['email_nfe']) { $client_email = $client['email']; } @@ -33,20 +34,20 @@ }*/ $company = gnfe_get_company(); - if ($customer['doc_type'] == 2) { + if (2 == $customer['doc_type']) { $name = $client['companyname']; - } elseif ($customer['doc_type'] == 1 || $customer == 'CPF e/ou CNPJ ausente.' || !$customer['doc_type']) { + } elseif (1 == $customer['doc_type'] || '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']; - foreach ( Capsule::table('tblconfiguration')->where('setting', '=', 'Domain')->get( ['value'] ) as $gnfewhmcsadminurl) { + foreach (Capsule::table('tblconfiguration')->where('setting', '=', 'Domain')->get(['value']) as $gnfewhmcsadminurl) { $gnfewhmcsadminurl = $gnfewhmcsadminurl->value; } - $desc = 'Nota referente a fatura #' . $nfeio->invoice_id . ' ' . $gnfewhmcsadminurl . 'viewinvoice.php?id=' . $waiting->invoice_id . ' '; - if (!strlen($customer['insc_municipal']) == 0) { + $desc = 'Nota referente a fatura #'.$nfeio->invoice_id.' '.$gnfewhmcsadminurl.'viewinvoice.php?id='.$waiting->invoice_id.' '; + if (0 == !strlen($customer['insc_municipal'])) { $postfields = [ 'cityServiceCode' => $service_code, 'description' => $desc, @@ -65,13 +66,13 @@ 'district' => $client['address2'], 'city' => [ 'code' => gnfe_ibge(preg_replace('/[^0-9]/', '', $client['postcode'])), - 'name' => $client['city'] + 'name' => $client['city'], ], 'state' => $client['state'], - ] + ], ], 'rpsSerialNumber' => $company['companies']['rpsSerialNumber'], - 'rpsNumber' => (int)$company['companies']['rpsNumber'] + 1, + 'rpsNumber' => (int) $company['companies']['rpsNumber'] + 1, ]; } else { $postfields = [ @@ -91,34 +92,34 @@ 'district' => $client['address2'], 'city' => [ 'code' => gnfe_ibge(preg_replace('/[^0-9]/', '', $client['postcode'])), - 'name' => $client['city'] + 'name' => $client['city'], ], 'state' => $client['state'], - ] + ], ], 'rpsSerialNumber' => $company['companies']['rpsSerialNumber'], - 'rpsNumber' => (int)$company['companies']['rpsNumber'] + 1, + 'rpsNumber' => (int) $company['companies']['rpsNumber'] + 1, ]; } if ($params['debug']) { - logModuleCall('gofas_nfeio', 'dailycronjob',$postfields , '', '', 'replaceVars'); + logModuleCall('gofas_nfeio', 'dailycronjob', $postfields, '', '', 'replaceVars'); } $waiting = []; - foreach ( Capsule::table('gofasnfeio')->where( 'status', '=', 'Waiting' )->get( ['invoice_id', 'status'] ) as $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') { + $queue = gnfe_queue_nfe_edit($invoices->id, $nfeio->id); + if ('success' !== $queue) { $error .= $queue; } - if ($queue === 'success') { + if ('success' === $queue) { } } } } } 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'); + 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'); } -} \ No newline at end of file +} diff --git a/modules/addons/gofasnfeio/hooks/invoicepaid.php b/modules/addons/gofasnfeio/hooks/invoicepaid.php index 2166937..d5b75bf 100644 --- a/modules/addons/gofasnfeio/hooks/invoicepaid.php +++ b/modules/addons/gofasnfeio/hooks/invoicepaid.php @@ -1,31 +1,33 @@ $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') { - $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 (stripos($params['issue_note'], 'Paga') and (string) $vars['status'] !== (string) 'Draft' and (!$params['issue_note_after'] or 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') { + $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_edit_all($vars['invoiceid']); - if ($queue !== 'success') { - 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); + $queue = gnfe_queue_nfe($vars['invoiceid'], true); + if ('success' !== $queue) { + 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') { + if ('success' === $queue) { } } } } 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 + 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'); +} From d8308a8c3846d0f8325aa1ab1a2e100fe8133989 Mon Sep 17 00:00:00 2001 From: JoaoVictorLNacional Date: Thu, 31 Dec 2020 10:46:06 -0300 Subject: [PATCH 25/52] =?UTF-8?q?bugs=20corrigidos=20e=20alguns=20arquivos?= =?UTF-8?q?=20formatados=20para=20o=20modelo=20padr=C3=A3o?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- modules/addons/gofasnfeio/createxml.php | 46 ++-- modules/addons/gofasnfeio/functions.php | 25 +- .../addons/gofasnfeio/hooks/aftercronjob.php | 233 +++++++++--------- .../gofasnfeio/hooks/invoicecreation.php | 37 +-- 4 files changed, 177 insertions(+), 164 deletions(-) diff --git a/modules/addons/gofasnfeio/createxml.php b/modules/addons/gofasnfeio/createxml.php index d24613a..e938209 100644 --- a/modules/addons/gofasnfeio/createxml.php +++ b/modules/addons/gofasnfeio/createxml.php @@ -1,53 +1,61 @@ where('id', '=', $invoice_id)->get(['invoice_id', 'user_id', 'nfe_id', 'status', 'services_amount', 'environment', 'flow_status', 'pdf', 'created_at', 'updated_at', 'id']); $nfe = $row[0]; - var_dump($nfe); - if ((string)$nfe->status === (string)'Issued') { + if ((string) $nfe->status === (string) 'Issued') { $nfe_xml_for_invoice = gnfe_xml_nfe($nfe->nfe_id); - header ('Content-Type:text/xml'); - var_dump($nfe_xml_for_invoice); + header('Content-Type:text/xml'); + echo $nfe_xml_for_invoice; } else { echo 'Sem permissão'; } + exit(); - function gnfe_xml_nfe($nf) { + function gnfe_xml_nfe($nf) + { $curl = curl_init(); - curl_setopt($curl, CURLOPT_URL, 'https://api.nfe.io/v1/companies/' . gnfe_config('company_id') . '/serviceinvoices/' . $nf . '/xml'); - curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: text/json', 'Accept: application/json', 'Authorization: ' . gnfe_config('api_key')]); + curl_setopt($curl, CURLOPT_URL, 'https://api.nfe.io/v1/companies/'.gnfe_config('company_id').'/serviceinvoices/'.$nf.'/xml'); + curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: text/json', 'Accept: application/json', 'Authorization: '.gnfe_config('api_key')]); curl_setopt($curl, CURLOPT_TIMEOUT, 30); - curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); - $response = curl_exec ($curl); - curl_close ($curl); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); + $response = curl_exec($curl); + curl_close($curl); + return json_decode($response); } - function gnfe_config($set = false) { + function gnfe_config($set = false) + { $setting = []; - foreach ( Capsule::table('tbladdonmodules')->where( 'module', '=', 'gofasnfeio' )->get( ['setting', 'value'] ) as $settings ) { + foreach (Capsule::table('tbladdonmodules')->where('module', '=', 'gofasnfeio')->get(['setting', 'value']) as $settings) { $setting[$settings->setting] = $settings->value; } if ($set) { return $setting[$set]; } + return $setting; } - function gnfe_pdf_nfe($nf) { + function gnfe_pdf_nfe($nf) + { $curl = curl_init(); - curl_setopt($curl, CURLOPT_URL, 'https://api.nfe.io/v1/companies/' . gnfe_config('company_id') . '/serviceinvoices/' . $nf . '/pdf'); - curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-type: application/pdf', 'Authorization: ' . gnfe_config('api_key')]); - curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); + curl_setopt($curl, CURLOPT_URL, 'https://api.nfe.io/v1/companies/'.gnfe_config('company_id').'/serviceinvoices/'.$nf.'/pdf'); + curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-type: application/pdf', 'Authorization: '.gnfe_config('api_key')]); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET'); - curl_setopt($curl, CURLOPT_RETURNTRANSFER,true); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($curl, CURLOPT_TIMEOUT, 10); curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 30); header('Content-type: application/pdf'); $result = curl_exec($curl); curl_close($curl); + return $result; - } \ No newline at end of file + } diff --git a/modules/addons/gofasnfeio/functions.php b/modules/addons/gofasnfeio/functions.php index 38e86f3..810b501 100644 --- a/modules/addons/gofasnfeio/functions.php +++ b/modules/addons/gofasnfeio/functions.php @@ -182,7 +182,6 @@ function gnfe_queue_nfe($invoice_id, $create_all = false) { $invoice = localAPI('GetInvoice', ['invoiceid' => $invoice_id], false); $itens = get_prodict_invoice($invoice_id); - logModuleCall('gofas_nfeio', 'itens teste', $itens, '', '', 'replaceVars'); if (!$itens) { foreach (Capsule::table('tblinvoiceitems')->where('invoiceid', '=', $invoice_id)->get(['userid', 'amount']) as $item_not_salle) { @@ -349,6 +348,7 @@ function gnfe_issue_nfe($postfields) } if ($gnfe_webhook_id) { $check_webhook = gnfe_check_webhook($gnfe_webhook_id); + $error = ''; if ($check_webhook['message']) { $error .= $check_webhook['message']; } @@ -383,6 +383,7 @@ function gnfe_issue_nfe($postfields) } } } + if (gnfe_config('debug')) { logModuleCall('gofas_nfeio', 'check_webhook', ['gnfe_webhook_id' => $gnfe_webhook_id, 'check_webhook' => $check_webhook, 'check_webhook_url' => $check_webhook['hooks']['url']], 'post', ['create_webhook' => $create_webhook, 'delete_webhook' => $delete_webhook, 'error' => $error], 'replaceVars'); } @@ -395,7 +396,6 @@ function gnfe_issue_nfe($postfields) curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $response = curl_exec($curl); curl_close($curl); - logModuleCall('gofas_nfeio', 'resp', $response, '', '', 'replaceVars'); return json_decode(json_encode(json_decode($response))); } @@ -610,7 +610,6 @@ function gnfe_update_nfe($nfe, $user_id, $invoice_id, $pdf, $created_at, $update 'rpsSerialNumber' => $nfe->rpsSerialNumber, 'rpsNumber' => $nfe->rpsNumber, ]; - logModuleCall('gofas_nfeio', '$data', $data, '', '', 'replaceVars'); try { if (!$id_gofasnfeio) { @@ -814,35 +813,32 @@ function gnfe_customer_service_code($item_id) function get_prodict_invoice($invoice_id) { - $query = "SELECT DISTINCT tblhosting.packageid,tblpricing.monthly from tblhosting + $query = "SELECT DISTINCT tblhosting.packageid,tblpricing.monthly from tblhosting INNER JOIN tblinvoiceitems ON tblinvoiceitems.relid = tblhosting.id JOIN tblpricing ON tblpricing.relid = tblhosting.packageid LEFT JOIN tblproducts ON tblproducts.id = tblhosting.packageid - WHERE tblpricing.type = 'product' AND tblinvoiceitems.invoiceid = :id"; + WHERE tblpricing.type = 'product' AND tblinvoiceitems.invoiceid = :id"; + $pdo = Capsule::connection()->getPdo(); $pdo->beginTransaction(); $tax_check = gnfe_config('tax'); $row = null; $list = []; - if ('Sim' != $tax_check) { - logModuleCall('gofas_nfeio', 'true get_prodict_invoice', $tax_check, '', '', 'replaceVars'); - - $query .= 'AND tblproducts.tax = 1'; + if ('Não' == $tax_check) { + $query .= ' AND tblproducts.tax = 1'; } else { - logModuleCall('gofas_nfeio', 'false get_prodict_invoice', $tax_check, '', '', 'replaceVars'); - Capsule::table('tblproducts')->update(['tax' => 1]); } + // Capsule::table('tblproducts')->update(['tax' => 1]); try { $statement = $pdo->prepare($query); $statement->execute([':id' => $invoice_id]); $row = $statement->fetchAll(); $pdo->commit(); - } catch (\Throwable $th) { + } catch (\Exception $th) { $pdo->rollBack(); - logModuleCall('gofas_nfeio', 'erroGetProdictInvoice', $th, '', '', 'replaceVars'); } foreach ($row as $item) { $pdo->beginTransaction(); @@ -857,7 +853,7 @@ function get_prodict_invoice($invoice_id) $list2['value'] = $row[0]['code_service']; $list2['monthly'] = $item['monthly']; $list[] = $list2; - } catch (\Throwable $th) { + } catch (\Exception $th) { $pdo->rollBack(); logModuleCall('gofas_nfeio', 'erroForeach', $th, '', '', 'replaceVars'); } @@ -912,6 +908,7 @@ function update_table() if ($version != $current_version) { create_table_product_code(); set_code_service_camp_gofasnfeio(); + set_custom_field_ini_date(); } else { Capsule::table('tblconfiguration')->insert(['setting' => 'version_nfeio', 'value' => $current_version, 'created_at' => date('Y-m-d H:i:s')]); } diff --git a/modules/addons/gofasnfeio/hooks/aftercronjob.php b/modules/addons/gofasnfeio/hooks/aftercronjob.php index 4beeb51..771f913 100644 --- a/modules/addons/gofasnfeio/hooks/aftercronjob.php +++ b/modules/addons/gofasnfeio/hooks/aftercronjob.php @@ -1,133 +1,138 @@ orderBy('id', 'desc')->where('status', '=', 'Waiting')->take(1)->get( ['id', 'invoice_id', 'services_amount']) as $waiting ) { - $data = getTodaysDate(false); - $dataAtual = toMySQLDate($data); +// foreach (Capsule::table('gofasnfeio')->orderBy('id', 'desc')->where('status', '=', 'Waiting')->take(1)->get(['id', 'invoice_id', 'services_amount']) as $waiting) { + foreach (Capsule::table('gofasnfeio')->orderBy('id', 'desc')->where('status', '=', 'Waiting')->get(['id', 'invoice_id', 'services_amount']) as $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']); - } 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; + if ('Manualmente' !== $params['issue_note']) { + $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']); } - 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); + 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; + } + + if (2 == $customer['doc_type']) { + $name = $client['companyname']; + } elseif (1 == $customer['doc_type'] || 'CPF e/ou CNPJ ausente.' == $customer || !$customer['doc_type']) { + $name = $client['fullname']; + } + $name = htmlspecialchars_decode($name); - $service_code = $waiting->service_code ? $waiting->service_code : $params['service_code']; + $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'] + 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 (0 == !strlen($customer['insc_municipal'])) { + $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'], ], - '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'] + ], + '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'], ], - '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 $gnfe_update_nfe !== 'success') { - $error = $gnfe_update_nfe; + ], + '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; } - $update_rps = gnfe_update_rps($rps_serial_number_, $rps_number); + 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 $update_rps !== 'success') { - $error = $update_rps; + 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'); + } } - 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'); - } -} \ No newline at end of file diff --git a/modules/addons/gofasnfeio/hooks/invoicecreation.php b/modules/addons/gofasnfeio/hooks/invoicecreation.php index d9765c7..79725d8 100644 --- a/modules/addons/gofasnfeio/hooks/invoicecreation.php +++ b/modules/addons/gofasnfeio/hooks/invoicecreation.php @@ -1,18 +1,18 @@ $vars['invoiceid']], false); - if ( (float)$invoice['total'] > (float)'0.00' and $invoice['status'] !== (string)'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') { - $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 (stripos($params['issue_note'], 'Gerada') and (string) $vars['status'] !== (string) 'Draft' and (!$params['issue_note_after'] or 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'], ['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') { + $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']) { @@ -21,18 +21,21 @@ elseif(!$params['email_nfe']) { $client_email = $client['email']; }*/ - $queue = gnfe_queue_nfe($vars['invoiceid'],true); - if ($queue !== 'success') { - 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); + + $queue = gnfe_queue_nfe($vars['invoiceid'], true); + + if ('success' !== $queue) { + 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') { + if ('success' === $queue) { } } } } 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 + 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'); +} From d58b1bf8ceb7338762105be53d23847e7d75ffbf Mon Sep 17 00:00:00 2001 From: JoaoVictorLNacional Date: Mon, 4 Jan 2021 14:32:25 -0300 Subject: [PATCH 26/52] =?UTF-8?q?modificado=20a=20fun=C3=A7=C3=A3o=20para?= =?UTF-8?q?=20aplicar=20as=20modifica=C3=A7=C3=B5es=20no=20banco=20de=20da?= =?UTF-8?q?dos=20quando=20o=20modulo=20=C3=A9=20ativado?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- modules/addons/gofasnfeio/activate.php | 21 +++++++++++++++++++++ modules/addons/gofasnfeio/functions.php | 22 ++++++++++------------ modules/addons/gofasnfeio/gofasnfeio.php | 11 ++++++++--- 3 files changed, 39 insertions(+), 15 deletions(-) create mode 100644 modules/addons/gofasnfeio/activate.php diff --git a/modules/addons/gofasnfeio/activate.php b/modules/addons/gofasnfeio/activate.php new file mode 100644 index 0000000..8aa131e --- /dev/null +++ b/modules/addons/gofasnfeio/activate.php @@ -0,0 +1,21 @@ +where('setting', '=', 'version_nfeio')->get(['value']); + $version = $row[0]->value; + if ($version != $current_version) { + create_table_product_code(); + set_code_service_camp_gofasnfeio(); + set_custom_field_ini_date(); + + Capsule::table('tblconfiguration')->insert(['setting' => 'version_nfeio', 'value' => $current_version, 'created_at' => date('Y-m-d H:i:s')]); + } + } +} diff --git a/modules/addons/gofasnfeio/functions.php b/modules/addons/gofasnfeio/functions.php index 810b501..039c1cb 100644 --- a/modules/addons/gofasnfeio/functions.php +++ b/modules/addons/gofasnfeio/functions.php @@ -869,8 +869,16 @@ function set_code_service_camp_gofasnfeio() $pdo->beginTransaction(); try { - $statement = $pdo->prepare('ALTER TABLE gofasnfeio ADD service_code TEXT; - ALTER TABLE gofasnfeio ADD monthly DECIMAL(16,2)'); + $statement = $pdo->prepare('ALTER TABLE gofasnfeio ADD service_code TEXT;'); + $statement->execute(); + $pdo->commit(); + } catch (\Exception $e) { + $pdo->rollBack(); + } + $pdo->beginTransaction(); + + try { + $statement = $pdo->prepare('ALTER TABLE gofasnfeio ADD monthly DECIMAL(16,2)'); $statement->execute(); $pdo->commit(); } catch (\Exception $e) { @@ -902,14 +910,4 @@ function create_table_product_code() function update_table() { - $current_version = '1.2.5'; - $row = Capsule::table('tblconfiguration')->where('setting', '=', 'version_nfeio')->get(['value']); - $version = $row[0]; - if ($version != $current_version) { - create_table_product_code(); - set_code_service_camp_gofasnfeio(); - set_custom_field_ini_date(); - } else { - Capsule::table('tblconfiguration')->insert(['setting' => 'version_nfeio', 'value' => $current_version, 'created_at' => date('Y-m-d H:i:s')]); - } } diff --git a/modules/addons/gofasnfeio/gofasnfeio.php b/modules/addons/gofasnfeio/gofasnfeio.php index 36779f1..0d34c35 100644 --- a/modules/addons/gofasnfeio/gofasnfeio.php +++ b/modules/addons/gofasnfeio/gofasnfeio.php @@ -1,6 +1,11 @@ Date: Mon, 4 Jan 2021 15:48:55 -0300 Subject: [PATCH 27/52] removido logs desnessesarios --- modules/addons/gofasnfeio/callback.php | 79 +++++++++++++------------ modules/addons/gofasnfeio/createpdf.php | 27 +++++---- modules/addons/gofasnfeio/functions.php | 3 +- 3 files changed, 58 insertions(+), 51 deletions(-) diff --git a/modules/addons/gofasnfeio/callback.php b/modules/addons/gofasnfeio/callback.php index 174831a..da8cf91 100644 --- a/modules/addons/gofasnfeio/callback.php +++ b/modules/addons/gofasnfeio/callback.php @@ -1,21 +1,21 @@ where( 'module', '=', 'gofasnfeio' )->get( ['setting', 'value'] ) as $settings ) { + foreach (Capsule::table('tbladdonmodules')->where('module', '=', 'gofasnfeio')->get(['setting', 'value']) as $settings) { $params[$settings->setting] = $settings->value; } - foreach ( Capsule::table('gofasnfeio')->where('nfe_id', '=', $post['id'])-> - get(['id', 'invoice_id', 'user_id', 'nfe_id', 'status', 'services_amount', 'environment', 'flow_status', 'pdf', 'created_at', 'updated_at']) as $key => $value ) { + foreach (Capsule::table('gofasnfeio')->where('nfe_id', '=', $post['id'])-> + get(['id', 'invoice_id', 'user_id', 'nfe_id', 'status', 'services_amount', 'environment', 'flow_status', 'pdf', 'created_at', 'updated_at']) as $key => $value) { $nfe_for_invoice[$key] = json_decode(json_encode($value), true); } $nfe = $nfe_for_invoice['0']; - if ((string)$nfe['nfe_id'] === (string)$post['id'] and $nfe['status'] !== (string)$post['status'] ) { + if ((string) $nfe['nfe_id'] === (string) $post['id'] and $nfe['status'] !== (string) $post['status']) { $new_nfe = [ 'invoice_id' => $nfe['invoice_id'], 'user_id' => $nfe['user_id'], @@ -28,6 +28,7 @@ 'created_at' => $nfe['created_at'], 'updated_at' => date('Y-m-d H:i:s'), ]; + try { $save_nfe = Capsule::table('gofasnfeio')->where('nfe_id', '=', $post['id'])->update($new_nfe); } catch (\Exception $e) { @@ -35,29 +36,29 @@ } } if ($params['debug']) { - logModuleCall('gofas_nfeio', 'receive_callback', ['post' => $post], 'post', ['nfe_local' => $nfe], 'replaceVars'); + 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 ) { + 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']); + if ('Manualmente' !== $params['issue_note']) { + $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']); + $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) { + 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); + $customer = gnfe_customer($invoices->userid, $client); $gnfe_get_nfes = gnfe_get_nfes(); - if ( $params['rps_serial_number'] ) { + 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']) { @@ -68,17 +69,17 @@ $rps_serial_number_ = $rps_serial_number; } /// - if ($params['rps_number'] and (string)$params['rps_number'] !== (string)'zero') { + 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']) { + } 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'])) { + } 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 (2 == $customer['doc_type']) { $name = $client['companyname']; - } elseif ($customer['doc_type'] == 1 || $customer == 'CPF e/ou CNPJ ausente.' || !$customer['doc_type']) { + } elseif (1 == $customer['doc_type'] || 'CPF e/ou CNPJ ausente.' == $customer || !$customer['doc_type']) { $name = $client['fullname']; } @@ -86,11 +87,11 @@ $service_code = $waiting->service_code ? $waiting->service_code : $params['service_code']; - foreach ( Capsule::table('tblconfiguration')->where('setting', '=', 'Domain')->get( ['value'] ) as $gnfewhmcsadminurl) { + 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) { + $desc = 'Nota referente a fatura #'.$waiting->invoice_id.' '.$gnfewhmcsadminurl.'viewinvoice.php?id='.$waiting->invoice_id.' '; + if (0 == !strlen($customer['insc_municipal'])) { $postfields = [ 'cityServiceCode' => $service_code, 'description' => $desc, @@ -109,13 +110,13 @@ 'district' => $client['address2'], 'city' => [ 'code' => gnfe_ibge(preg_replace('/[^0-9]/', '', $client['postcode'])), - 'name' => $client['city'] + 'name' => $client['city'], ], 'state' => $client['state'], - ] + ], ], 'rpsSerialNumber' => $rps_serial_number, - 'rpsNumber' => (int)$rps_number + 1, + 'rpsNumber' => (int) $rps_number + 1, ]; } else { $postfields = [ @@ -135,18 +136,18 @@ 'district' => $client['address2'], 'city' => [ 'code' => gnfe_ibge(preg_replace('/[^0-9]/', '', $client['postcode'])), - 'name' => $client['city'] + 'name' => $client['city'], ], 'state' => $client['state'], - ] + ], ], 'rpsSerialNumber' => $rps_serial_number, - 'rpsNumber' => (int)$rps_number + 1, + 'rpsNumber' => (int) $rps_number + 1, ]; } if ($params['debug']) { - logModuleCall('gofas_nfeio', 'callback',$postfields , '', '', 'replaceVars'); + logModuleCall('gofas_nfeio', 'callback', $postfields, '', '', 'replaceVars'); } $nfe = gnfe_issue_nfe($postfields); @@ -154,18 +155,18 @@ $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 $gnfe_update_nfe !== 'success') { + $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 $update_rps !== 'success') { + 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'); + 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'); } } -} \ No newline at end of file +} diff --git a/modules/addons/gofasnfeio/createpdf.php b/modules/addons/gofasnfeio/createpdf.php index acd863b..ebc45e9 100644 --- a/modules/addons/gofasnfeio/createpdf.php +++ b/modules/addons/gofasnfeio/createpdf.php @@ -1,40 +1,47 @@ where('id', '=', $nfe_id)->get(['invoice_id', 'user_id', 'nfe_id', 'status', 'services_amount', 'environment', 'flow_status', 'pdf', 'created_at', 'updated_at', 'id']); $nfe = $row[0]; - if ((string)$nfe->status === (string)'Issued') { + if ((string) $nfe->status === (string) 'Issued') { $nfe_for_invoice = gnfe_pdf_nfe($nfe->nfe_id); echo $nfe_for_invoice; } else { echo 'Not Found'; } + exit(); - function gnfe_pdf_nfe($nf) { + function gnfe_pdf_nfe($nf) + { $curl = curl_init(); - curl_setopt($curl, CURLOPT_URL, 'https://api.nfe.io/v1/companies/' . gnfe_config('company_id') . '/serviceinvoices/' . $nf . '/pdf'); - curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-type: application/pdf', 'Authorization: ' . gnfe_config('api_key')]); - curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); + curl_setopt($curl, CURLOPT_URL, 'https://api.nfe.io/v1/companies/'.gnfe_config('company_id').'/serviceinvoices/'.$nf.'/pdf'); + curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-type: application/pdf', 'Authorization: '.gnfe_config('api_key')]); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET'); - curl_setopt($curl, CURLOPT_RETURNTRANSFER,true); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($curl, CURLOPT_TIMEOUT, 10); curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 30); header('Content-type: application/pdf'); $result = curl_exec($curl); curl_close($curl); + return $result; } - function gnfe_config($set = false) { + function gnfe_config($set = false) + { $setting = []; - foreach ( Capsule::table('tbladdonmodules')->where( 'module', '=', 'gofasnfeio' )->get( ['setting', 'value'] ) as $settings ) { + foreach (Capsule::table('tbladdonmodules')->where('module', '=', 'gofasnfeio')->get(['setting', 'value']) as $settings) { $setting[$settings->setting] = $settings->value; } if ($set) { return $setting[$set]; } + return $setting; - } \ No newline at end of file + } diff --git a/modules/addons/gofasnfeio/functions.php b/modules/addons/gofasnfeio/functions.php index 039c1cb..f1eada7 100644 --- a/modules/addons/gofasnfeio/functions.php +++ b/modules/addons/gofasnfeio/functions.php @@ -201,7 +201,6 @@ function gnfe_queue_nfe($invoice_id, $create_all = false) try { $service_code_row = Capsule::table('gofasnfeio')->whereNull('service_code')->where('invoice_id', '=', $invoice_id)->get(['id', 'services_amount']); - logModuleCall('gofas_nfeio', 'service_code_row', $service_code_row, '', '', 'replaceVars'); if (1 == count($service_code_row)) { $mountDB = floatval($service_code_row[0]->services_amount); @@ -855,7 +854,7 @@ function get_prodict_invoice($invoice_id) $list[] = $list2; } catch (\Exception $th) { $pdo->rollBack(); - logModuleCall('gofas_nfeio', 'erroForeach', $th, '', '', 'replaceVars'); + logModuleCall('gofas_nfeio', 'get_prodict_invoice erro', $th, '', '', 'replaceVars'); } } From dd515a0c010a9115ef8326b8013dd9d947d7ed4d Mon Sep 17 00:00:00 2001 From: JoaoVictorLNacional Date: Mon, 4 Jan 2021 15:50:47 -0300 Subject: [PATCH 28/52] =?UTF-8?q?modificado=20para=20o=20padr=C3=A3o=20de?= =?UTF-8?q?=20concatena=C3=A7=C3=A3o=20definida=20no=20php=20cs=20fixer?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- modules/addons/gofasnfeio/config.php | 87 ++++++----- .../hooks/admininvoicescontrolsoutput.php | 102 +++++++------ .../gofasnfeio/hooks/invoicecancelled.php | 31 ++-- .../addons/gofasnfeio/hooks/productdelete.php | 4 +- modules/addons/gofasnfeio/output.php | 144 ++++++++++-------- modules/addons/gofasnfeio/outputproduct.php | 88 ++++++----- modules/addons/gofasnfeio/pdf.php | 14 +- modules/addons/gofasnfeio/prod_output.php | 13 +- modules/addons/gofasnfeio/xml.php | 13 +- 9 files changed, 271 insertions(+), 225 deletions(-) diff --git a/modules/addons/gofasnfeio/config.php b/modules/addons/gofasnfeio/config.php index bc9a903..1eb1a7e 100644 --- a/modules/addons/gofasnfeio/config.php +++ b/modules/addons/gofasnfeio/config.php @@ -1,11 +1,14 @@ where('type', '=', 'client')->get(['fieldname', 'id']) as $customfield) { $customfields_array[] = $customfield; @@ -21,15 +24,17 @@ function gnfe_customfields_dropdow() { } else { $dropFieldArray = ['0' => 'nothing to show']; } + return $dropFieldArray; } } - function gofasnfeio_config() { + function gofasnfeio_config() + { $module_version = '1.2.4'; - $module_version_int = (int)preg_replace('/[^0-9]/', '', $module_version); + $module_version_int = (int) preg_replace('/[^0-9]/', '', $module_version); /// REMOVER VERIFICAÇÃO APÓS VERSÃO 2.0 - $verificarEmail = Capsule::table('tbladdonmodules')->where( 'module', '=', 'gofasnfeio' )->where( 'setting', '=', 'gnfe_email_nfe_config' )->count(); + $verificarEmail = Capsule::table('tbladdonmodules')->where('module', '=', 'gofasnfeio')->where('setting', '=', 'gnfe_email_nfe_config')->count(); if (empty($verificarEmail)) { // echo "vazio"; try { @@ -39,43 +44,44 @@ function gofasnfeio_config() { } }////// FIM VERIFICAÇÃO - $actual_link = (isset($_SERVER['HTTPS']) ? 'https' : 'http') . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; - if ( stripos( $actual_link, '/configaddonmods.php') ) { - $whmcs_url__ = str_replace('\\','/',(isset($_SERVER['HTTPS']) ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . substr(getcwd(),strlen($_SERVER['DOCUMENT_ROOT']))); - $admin_url = $whmcs_url__ . '/'; + $actual_link = (isset($_SERVER['HTTPS']) ? 'https' : 'http')."://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}"; + if (stripos($actual_link, '/configaddonmods.php')) { + $whmcs_url__ = str_replace('\\', '/', (isset($_SERVER['HTTPS']) ? 'https://' : 'http://').$_SERVER['HTTP_HOST'].substr(getcwd(), strlen($_SERVER['DOCUMENT_ROOT']))); + $admin_url = $whmcs_url__.'/'; $vtokens = explode('/', $actual_link); - $whmcs_admin_path = '/' . $vtokens[sizeof($vtokens) - 2] . '/'; - $whmcs_url = str_replace( $whmcs_admin_path, '', $admin_url) . '/'; - foreach ( Capsule::table('tblconfiguration')->where('setting', '=', 'gnfewhmcsurl')->get( ['value', 'created_at'] ) as $gnfewhmcsurl_ ) { + $whmcs_admin_path = '/'.$vtokens[sizeof($vtokens) - 2].'/'; + $whmcs_url = str_replace($whmcs_admin_path, '', $admin_url).'/'; + foreach (Capsule::table('tblconfiguration')->where('setting', '=', 'gnfewhmcsurl')->get(['value', 'created_at']) as $gnfewhmcsurl_) { $gnfewhmcsurl = $gnfewhmcsurl_->value; $gnfewhmcsurl_created_at = $gnfewhmcsurl_->created_at; } - foreach ( Capsule::table('tblconfiguration')->where('setting', '=', 'gnfe_email_nfe')->get( ['value'] ) as $gnfe_email_nfe_ ) { + foreach (Capsule::table('tblconfiguration')->where('setting', '=', 'gnfe_email_nfe')->get(['value']) as $gnfe_email_nfe_) { $gnfe_email_nfe = $gnfewhmcsurl_->value; } - foreach ( Capsule::table('tblconfiguration')->where('setting', '=', 'gnfewhmcsadminurl')->get( ['value', 'created_at'] ) as $gnfewhmcsadminurl_ ) { + foreach (Capsule::table('tblconfiguration')->where('setting', '=', 'gnfewhmcsadminurl')->get(['value', 'created_at']) as $gnfewhmcsadminurl_) { $gnfewhmcsadminurl = $gnfewhmcsadminurl_->value; $gnfewhmcsadminurl_created_at = $gnfewhmcsurl_->created_at; } - foreach ( Capsule::table('tblconfiguration')->where('setting', '=', 'gnfewhmcsadminpath')->get( ['value', 'created_at'] ) as $gnfewhmcsadminpath_ ) { + foreach (Capsule::table('tblconfiguration')->where('setting', '=', 'gnfewhmcsadminpath')->get(['value', 'created_at']) as $gnfewhmcsadminpath_) { $gnfewhmcsadminpath = $gnfewhmcsadminpath_->value; $gnfewhmcsadminpath_created_at = $gnfewhmcsurl_->created_at; } - if ( !$gnfe_email_nfe ) { + if (!$gnfe_email_nfe) { try { Capsule::table('tblconfiguration')->insert(['setting' => 'gnfe_email_nfe', 'value' => 'Active', 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s')]); } catch (\Exception $e) { $e->getMessage(); } } - if ( !$gnfewhmcsurl ) { + if (!$gnfewhmcsurl) { // Set config try { Capsule::table('tblconfiguration')->insert(['setting' => 'gnfewhmcsurl', 'value' => $whmcs_url, 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s')]); } catch (\Exception $e) { $e->getMessage(); } + try { Capsule::table('tblconfiguration')->insert(['setting' => 'gnfewhmcsadminurl', 'value' => $admin_url, 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s')]); } catch (\Exception $e) { @@ -89,23 +95,23 @@ function gofasnfeio_config() { } } // Update Settings - if ( $gnfewhmcsurl and ($whmcs_url !== $gnfewhmcsurl) ) { + if ($gnfewhmcsurl and ($whmcs_url !== $gnfewhmcsurl)) { try { - Capsule::table('tblconfiguration')->where( 'setting', 'gnfewhmcsurl')->update(['value' => $whmcs_url, 'created_at' => $gnfewhmcsurl_created_at, 'updated_at' => date('Y-m-d H:i:s')]); + Capsule::table('tblconfiguration')->where('setting', 'gnfewhmcsurl')->update(['value' => $whmcs_url, 'created_at' => $gnfewhmcsurl_created_at, 'updated_at' => date('Y-m-d H:i:s')]); } catch (\Exception $e) { $e->getMessage(); } } - if ( $gnfewhmcsadminurl and ($admin_url !== $gnfewhmcsadminurl) ) { + if ($gnfewhmcsadminurl and ($admin_url !== $gnfewhmcsadminurl)) { try { - Capsule::table('tblconfiguration')->where( 'setting', 'gnfewhmcsadminurl')->update(['value' => $admin_url, 'created_at' => $gnfewhmcsadminurl_created_at, 'updated_at' => date('Y-m-d H:i:s')]); + Capsule::table('tblconfiguration')->where('setting', 'gnfewhmcsadminurl')->update(['value' => $admin_url, 'created_at' => $gnfewhmcsadminurl_created_at, 'updated_at' => date('Y-m-d H:i:s')]); } catch (\Exception $e) { $e->getMessage(); } } - if ( $gnfewhmcsadminpath and ($whmcs_admin_path !== $gnfewhmcsadminpath) ) { + if ($gnfewhmcsadminpath and ($whmcs_admin_path !== $gnfewhmcsadminpath)) { try { - Capsule::table('tblconfiguration')->where( 'setting', 'gnfewhmcsadminpath')->update(['value' => $whmcs_admin_path, 'created_at' => $gnfewhmcsadminpath_created_at, 'updated_at' => date('Y-m-d H:i:s')]); + Capsule::table('tblconfiguration')->where('setting', 'gnfewhmcsadminpath')->update(['value' => $whmcs_admin_path, 'created_at' => $gnfewhmcsadminpath_created_at, 'updated_at' => date('Y-m-d H:i:s')]); } catch (\Exception $e) { $e->getMessage(); } @@ -114,11 +120,12 @@ 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') ) { + if (!function_exists('gnfe_verifyInstall')) { + function gnfe_verifyInstall() + { + if (!Capsule::schema()->hasTable('gofasnfeio')) { try { - Capsule::schema()->create('gofasnfeio', function($table) { + Capsule::schema()->create('gofasnfeio', function ($table) { // incremented id $table->increments('id'); // whmcs info @@ -142,7 +149,7 @@ function gnfe_verifyInstall() { // Added in v 1 dot 1 dot 3 if (!Capsule::schema()->hasColumn('gofasnfeio', 'rpsNumber')) { try { - Capsule::schema()->table('gofasnfeio', function($table){$table->string('rpsNumber');}); + 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()}"; } @@ -150,7 +157,8 @@ function gnfe_verifyInstall() { if (!$error) { return ['sucess' => 1]; - } elseif ($error) { + } + if ($error) { return ['error' => $error]; } } @@ -159,8 +167,8 @@ function gnfe_verifyInstall() { $intro = ['intro' => [ 'FriendlyName' => '', - 'Description' => '

    Módulo Nota Fiscal NFE.io para WHMCS v' . $module_version . '

    - ' . $available_update_message . '', + 'Description' => '

    Módulo Nota Fiscal NFE.io para WHMCS v'.$module_version.'

    + '.$available_update_message.'', ]]; $api_key = ['api_key' => [ 'FriendlyName' => 'API Key', @@ -217,13 +225,13 @@ 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', ]]; $insc_municipal = ['insc_municipal' => [ 'FriendlyName' => 'Inscrição Municipal', 'Type' => 'dropdown', 'Options' => gnfe_customfields_dropdow(), - 'Description' => 'Escolha o campo personalizado de Inscrição Municipal']]; + 'Description' => 'Escolha o campo personalizado de Inscrição Municipal', ]]; $tax = ['tax' => [ 'FriendlyName' => 'Aplicar imposto automaticamente em todos os produtos ?', @@ -233,16 +241,17 @@ function gnfe_verifyInstall() { ]]; $footer = ['footer' => [ 'FriendlyName' => '', - 'Description' => '© ' . date('Y') . ' Suporte módulo', + 'Description' => '© '.date('Y').' Suporte módulo', ]]; - $fields = array_merge($intro,$api_key,$company_id,$service_code,$rps_serial_number,$rps_number,$issue_note,$issue_note_after,$gnfe_email_nfe_config,$cancel_invoice_cancel_nfe,$debug,$insc_municipal,$tax,$footer); + $fields = array_merge($intro, $api_key, $company_id, $service_code, $rps_serial_number, $rps_number, $issue_note, $issue_note_after, $gnfe_email_nfe_config, $cancel_invoice_cancel_nfe, $debug, $insc_municipal, $tax, $footer); $configarray = [ 'name' => 'NFE.io', 'description' => 'Módulo Nota Fiscal NFE.io para WHMCS', 'version' => $module_version, - 'author' => '', + 'author' => '', 'fields' => $fields, ]; + return $configarray; } -} \ No newline at end of file +} diff --git a/modules/addons/gofasnfeio/hooks/admininvoicescontrolsoutput.php b/modules/addons/gofasnfeio/hooks/admininvoicescontrolsoutput.php index 9bd547e..61dd75b 100644 --- a/modules/addons/gofasnfeio/hooks/admininvoicescontrolsoutput.php +++ b/modules/addons/gofasnfeio/hooks/admininvoicescontrolsoutput.php @@ -1,122 +1,130 @@ $vars['invoiceid']], false); -$client = localAPI('GetClientsDetails',['clientid' => $vars['userid'], 'stats' => false, ], false); +$nfe_for_invoice = gnfe_get_local_nfe($vars['invoiceid'], ['invoice_id', 'user_id', 'nfe_id', 'status', 'services_amount', 'environment', 'pdf', 'created_at']); +$invoice = localAPI('GetInvoice', ['invoiceid' => $vars['invoiceid']], false); +$client = localAPI('GetClientsDetails', ['clientid' => $vars['userid'], 'stats' => false], false); -foreach ( Capsule::table('tblconfiguration')->where('setting', '=', 'gnfewhmcsadminurl')->get( ['value'] ) as $gnfewhmcsadminurl_ ) { +foreach (Capsule::table('tblconfiguration')->where('setting', '=', 'gnfewhmcsadminurl')->get(['value']) as $gnfewhmcsadminurl_) { $gnfewhmcsadminurl = $gnfewhmcsadminurl_->value; } if ($_REQUEST['gnfe_create']) { - if ($nfe_for_invoice['status'] !== (string)'Created' or $nfe_for_invoice['status'] !== (string)'Issued') { - foreach ( $invoice['items']['item'] as $value) { - $line_items[] = $value['description'];//substr( $value['description'], 0, 100); + if ($nfe_for_invoice['status'] !== (string) 'Created' or $nfe_for_invoice['status'] !== (string) 'Issued') { + foreach ($invoice['items']['item'] as $value) { + $line_items[] = $value['description']; //substr( $value['description'], 0, 100); } - $customer = gnfe_customer($invoice['userid'],$client); - $queue = gnfe_queue_nfe($vars['invoiceid'],true); - if ($queue !== 'success') { + $customer = gnfe_customer($invoice['userid'], $client); + $queue = gnfe_queue_nfe($vars['invoiceid'], true); + if ('success' !== $queue) { header_remove(); - header('Location: ' . $gnfewhmcsadminurl . 'invoices.php?action=edit&id=' . $vars['invoiceid'] . '&gnfe_error=Erro ao criar nota fiscal: ' . $queue); + header('Location: '.$gnfewhmcsadminurl.'invoices.php?action=edit&id='.$vars['invoiceid'].'&gnfe_error=Erro ao criar nota fiscal: '.$queue); + exit; } - if ($queue === 'success') { + if ('success' === $queue) { $message = '
    Nota Fiscal enviada para processamento
    '; header_remove(); - header('Location: ' . $gnfewhmcsadminurl . 'invoices.php?action=edit&id=' . $vars['invoiceid'] . '&gnfe_message=' . base64_encode(urlencode($message))); + header('Location: '.$gnfewhmcsadminurl.'invoices.php?action=edit&id='.$vars['invoiceid'].'&gnfe_message='.base64_encode(urlencode($message))); + exit; } } } if ($_REQUEST['gnfe_open']) { - foreach (Capsule::table('gofasnfeio')->where( 'invoice_id', '=',$_REQUEST['gnfe_open'] )->get( ['id', 'nfe_id']) as $nfe) { - $url = 'https://app.nfe.io/companies/' . $params['company_id'] . '/service-invoices/' . $nfe->nfe_id; - echo ""; + foreach (Capsule::table('gofasnfeio')->where('invoice_id', '=', $_REQUEST['gnfe_open'])->get(['id', 'nfe_id']) as $nfe) { + $url = 'https://app.nfe.io/companies/'.$params['company_id'].'/service-invoices/'.$nfe->nfe_id; + echo ""; } } if ($_REQUEST['gnfe_cancel']) { - foreach (Capsule::table('gofasnfeio')->where( 'invoice_id', '=',$_REQUEST['id'] )->get( ['id', 'nfe_id']) as $nfe) { + 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) { - $message = '
    ' . $delete_nfe->message . '
    '; + $message = '
    '.$delete_nfe->message.'
    '; header_remove(); - header('Location: ' . $gnfewhmcsadminurl . 'invoices.php?action=edit&id=' . $vars['invoiceid'] . '&gnfe_message=' . base64_encode(urlencode($message))); + header('Location: '.$gnfewhmcsadminurl.'invoices.php?action=edit&id='.$vars['invoiceid'].'&gnfe_message='.base64_encode(urlencode($message))); + return ''; } } if (!$delete_nfe->message) { - $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') ); + $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(); - header('Location: ' . $gnfewhmcsadminurl . 'invoices.php?action=edit&id=' . $vars['invoiceid'] . '&gnfe_message=' . base64_encode(urlencode($message)) ); + header('Location: '.$gnfewhmcsadminurl.'invoices.php?action=edit&id='.$vars['invoiceid'].'&gnfe_message='.base64_encode(urlencode($message))); + return ''; } } if ($_REQUEST['gnfe_email']) { - foreach (Capsule::table('gofasnfeio')->where( 'invoice_id', '=',$_REQUEST['id'] )->get( ['id', 'nfe_id']) as $nfe) { + 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) { $message = '
    Email Enviado com Sucesso
    '; header_remove(); - header('Location: ' . $gnfewhmcsadminurl . 'invoices.php?action=edit&id=' . $vars['invoiceid'] . '&gnfe_message=' . base64_encode(urlencode($message))); + header('Location: '.$gnfewhmcsadminurl.'invoices.php?action=edit&id='.$vars['invoiceid'].'&gnfe_message='.base64_encode(urlencode($message))); + exit; } } if ($gnfe_email->message) { - $message = '
    ' . $gnfe_email->message . '
    '; + $message = '
    '.$gnfe_email->message.'
    '; header_remove(); - header('Location: ' . $gnfewhmcsadminurl . 'invoices.php?action=edit&id=' . $vars['invoiceid'] . '&gnfe_message=' . base64_encode(urlencode($message))); + header('Location: '.$gnfewhmcsadminurl.'invoices.php?action=edit&id='.$vars['invoiceid'].'&gnfe_message='.base64_encode(urlencode($message))); + exit; } } -if ($nfe_for_invoice['status'] === (string)'Waiting') { - $invoice_nfe = ' Criada em ' . date('d/m/Y H:i:s', strtotime($nfe_for_invoice['created_at'])) . ' - Status: Aguardando'; +if ($nfe_for_invoice['status'] === (string) 'Waiting') { + $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)'Created') { - $invoice_nfe = ' Criada em ' . date('d/m/Y H:i:s', strtotime($nfe_for_invoice['created_at'])) . ' - Status: Processando'; +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"']; } -if ($nfe_for_invoice['status'] === (string)'Issued') { - $invoice_nfe = ' Criada em ' . date('d/m/Y H:i:s', strtotime($nfe_for_invoice['created_at'])) . ' - Status: Emitida'; +if ($nfe_for_invoice['status'] === (string) 'Issued') { + $invoice_nfe = ' Criada em '.date('d/m/Y H:i:s', strtotime($nfe_for_invoice['created_at'])).' - Status: Emitida'; $disabled = ['a' => 'disabled="disabled"', 'b' => '', 'c' => '', 'd' => '']; } -if ($nfe_for_invoice['status'] === (string)'Cancelled') { - $invoice_nfe = ' Criada em ' . date('d/m/Y H:i:s', strtotime($nfe_for_invoice['created_at'])) . ' - Status: Cancelada'; +if ($nfe_for_invoice['status'] === (string) 'Cancelled') { + $invoice_nfe = ' Criada em '.date('d/m/Y H:i:s', strtotime($nfe_for_invoice['created_at'])).' - Status: Cancelada'; $disabled = ['a' => '', 'b' => '', 'c' => 'disabled="disabled"', 'd' => '']; } -if ($nfe_for_invoice['status'] === (string)'Error') { - $invoice_nfe = ' Criada em ' . date('d/m/Y H:i:s', strtotime($nfe_for_invoice['created_at'])) . ' - Status: Falha ao Emitir'; +if ($nfe_for_invoice['status'] === (string) 'Error') { + $invoice_nfe = ' Criada em '.date('d/m/Y H:i:s', strtotime($nfe_for_invoice['created_at'])).' - Status: Falha ao Emitir'; $disabled = ['a' => '', 'b' => '', 'c' => 'disabled="disabled"', 'd' => 'disabled="disabled"']; } -if ($nfe_for_invoice['status'] === (string)'None') { - $invoice_nfe = ' Criada em ' . date('d/m/Y H:i:s', strtotime($nfe_for_invoice['created_at'])) . ' - Status: Nenhum'; +if ($nfe_for_invoice['status'] === (string) 'None') { + $invoice_nfe = ' Criada em '.date('d/m/Y H:i:s', strtotime($nfe_for_invoice['created_at'])).' - Status: Nenhum'; $disabled = ['a' => '', 'b' => '', 'c' => 'disabled="disabled"', 'd' => 'disabled="disabled"']; } if (!$nfe_for_invoice['status']) { $invoice_nfe = ' Nenhuma nota fiscal foi emitida para essa fatura.'; $disabled = ['a' => '', 'b' => 'disabled="disabled"', 'c' => 'disabled="disabled"', 'd' => 'disabled="disabled"']; } -if ((string)$invoice['status'] === (string)'Draft' ) { +if ((string) $invoice['status'] === (string) 'Draft') { $disabled = ['a' => 'disabled="disabled"', 'b' => 'disabled="disabled"', 'c' => 'disabled="disabled"', 'd' => 'disabled="disabled"']; } echo '
    '; -echo '
    Nota Fiscal:' . $invoice_nfe . '
    '; -echo 'Emitir NFE'; -echo 'Visualizar NFE'; -echo 'Cancelar NFE'; -echo 'Enviar Email'; +echo '
    Nota Fiscal:'.$invoice_nfe.'
    '; +echo 'Emitir NFE'; +echo 'Visualizar NFE'; +echo 'Cancelar NFE'; +echo 'Enviar Email'; echo '
    '; if ($_REQUEST['gnfe_error']) { - echo '
    ' . $_REQUEST['gnfe_error'] . '
    '; + echo '
    '.$_REQUEST['gnfe_error'].'
    '; } if ($_REQUEST['gnfe_message']) { - echo urldecode(base64_decode( $_REQUEST['gnfe_message'] )); -} \ No newline at end of file + echo urldecode(base64_decode($_REQUEST['gnfe_message'])); +} diff --git a/modules/addons/gofasnfeio/hooks/invoicecancelled.php b/modules/addons/gofasnfeio/hooks/invoicecancelled.php index 0ad07ac..65129b6 100644 --- a/modules/addons/gofasnfeio/hooks/invoicecancelled.php +++ b/modules/addons/gofasnfeio/hooks/invoicecancelled.php @@ -1,17 +1,26 @@ $vars['invoiceid']), false); +if ($params['cancel_invoice_cancel_nfe']) { + $nfe_for_invoice = gnfe_get_local_nfe($vars['invoiceid'], ['nfe_id', 'status', 'services_amount', 'environment']); + if ($nfe_for_invoice['status'] === (string) 'Issued') { + $invoice = localAPI('GetInvoice', ['invoiceid' => $vars['invoiceid']], false); $delete_nfe = gnfe_delete_nfe($nfe_for_invoice['nfe_id']); - if(!$delete_nfe->message) { - $gnfe_update_nfe = gnfe_update_nfe((object)array('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")); + if (!$delete_nfe->message) { + $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')); } } - if($params['debug']) { - logModuleCall('gofas_nfeio', 'InvoiceCancelled', array('vars'=>$vars, 'params'=>$params,'nfe_for_invoice'=>$nfe_for_invoice,'invoice'=>$invoice, ), 'post', - array('nf'=>$nf,'delete_nfe'=>$delete_nfe,), 'replaceVars'); + 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' + ); } -} \ No newline at end of file +} diff --git a/modules/addons/gofasnfeio/hooks/productdelete.php b/modules/addons/gofasnfeio/hooks/productdelete.php index d4f9996..ef4940a 100644 --- a/modules/addons/gofasnfeio/hooks/productdelete.php +++ b/modules/addons/gofasnfeio/hooks/productdelete.php @@ -1,3 +1,5 @@ where('product_id','=',$vars['pid'])->delete(); \ No newline at end of file + +Capsule::table('tblproductcode')->where('product_id', '=', $vars['pid'])->delete(); diff --git a/modules/addons/gofasnfeio/output.php b/modules/addons/gofasnfeio/output.php index e775833..d4492d4 100644 --- a/modules/addons/gofasnfeio/output.php +++ b/modules/addons/gofasnfeio/output.php @@ -1,29 +1,33 @@ where('setting', '=', 'gnfewhmcsadminurl')->get( ['value'] ) as $gnfewhmcsadminurl_ ) { + foreach (Capsule::table('tblconfiguration')->where('setting', '=', 'gnfewhmcsadminurl')->get(['value']) as $gnfewhmcsadminurl_) { $gnfewhmcsadminurl = $gnfewhmcsadminurl_->value; } - if ($_GET['action'] === 'code_product') { - require_once __DIR__ . '/outputproduct.php'; + if ('code_product' === $_GET['action']) { + require_once __DIR__.'/outputproduct.php'; + return ''; } $nfes = []; - foreach ( Capsule::table('gofasnfeio')->orderBy('id', 'desc')->get( ['id'] ) as $nfes_ ) { + foreach (Capsule::table('gofasnfeio')->orderBy('id', 'desc')->get(['id']) as $nfes_) { $nfes[] = $nfes_->id; } if ($_REQUEST['page']) { - $nfes_page = (int)$_REQUEST['page']; + $nfes_page = (int) $_REQUEST['page']; } else { $nfes_page = 1; } if ($_REQUEST['take']) { - $take = (int)$_REQUEST['take']; + $take = (int) $_REQUEST['take']; } else { $take = 10; } @@ -35,105 +39,105 @@ function gofasnfeio_output($vars) { } $nfes_pages = ceil($nfes_total / $take); - $nfes_from_ = ( $nfes_page * $take ) - $take; + $nfes_from_ = ($nfes_page * $take) - $take; $nfes_from = $nfs_keys[$nfes_from_ + 1]; - $nfes_to_ = ( $nfes_from + $take ) - 2; + $nfes_to_ = ($nfes_from + $take) - 2; $nfes_to = $nfs_keys[$nfes_to_ + 1]; $nfess = array_slice($nfes, $nfes_from_, $nfes_to); - if ((int)$nfes_page === (int)$nfes_pages) { + if ((int) $nfes_page === (int) $nfes_pages) { $nfes_to = $nfes_total; $nfess = array_slice($nfes, $nfes_from_, $nfes_to_); } - if ((int)$take >= (int)$nfes_total) { + if ((int) $take >= (int) $nfes_total) { $nfes_from = 1; $nfess = array_slice($nfes, $nfes_from_, $nfes_to); } // Pagination $i = 1; - while ($i <= $nfes_pages ) { + while ($i <= $nfes_pages) { $page_num = $i++; - if ( (int)$page_num !== (int)$nfes_page ) { + if ((int) $page_num !== (int) $nfes_page) { $tag = 'a '; $a_style = ''; $li_class = 'class="enabled"'; - $href = $gnfewhmcsadminurl . 'addonmodules.php?module=gofasnfeio&page=' . $page_num; - } elseif ( (int)$page_num === (int)$nfes_page ) { + $href = $gnfewhmcsadminurl.'addonmodules.php?module=gofasnfeio&page='.$page_num; + } elseif ((int) $page_num === (int) $nfes_page) { $tag = 'span '; $a_style = 'style="background: #337ab7; color: #fff"'; $li_class = 'class="disabled"'; $href = ''; } - $pagination_ .= '
  • <' . $tag . ' ' . $a_style . ' href="' . $href . '" >' . $page_num . '
  • '; + $pagination_ .= '
  • <'.$tag.' '.$a_style.' href="'.$href.'" >'.$page_num.'
  • '; } - if ((int)$nfes_page === 1) { + if (1 === (int) $nfes_page) { $preview_class = ' class="previous disabled" '; $preview_href = ''; $preview_tag = 'span '; } else { $preview_class = ' class="previous" '; - $preview_href = ' href="' . $gnfewhmcsadminurl . 'addonmodules.php?module=gofasnfeio&page=' . ($nfes_page - 1) . '" '; + $preview_href = ' href="'.$gnfewhmcsadminurl.'addonmodules.php?module=gofasnfeio&page='.($nfes_page - 1).'" '; $preview_tag = 'a '; } - if ((int)$nfes_page === (int)$nfes_pages) { + if ((int) $nfes_page === (int) $nfes_pages) { $next_class = ' class="next disabled" '; $next_href = ''; $next_tag = 'span '; } else { $next_class = ' class="next" '; - $next_href = ' href="' . $gnfewhmcsadminurl . 'addonmodules.php?module=gofasnfeio&page=' . ($nfes_page + 1) . '" '; + $next_href = ' href="'.$gnfewhmcsadminurl.'addonmodules.php?module=gofasnfeio&page='.($nfes_page + 1).'" '; $next_tag = 'a '; } - $pagination .= '
  • <' . $preview_tag . ' ' . $preview_href . '>« Página anterior
  • '; + $pagination .= '
  • <'.$preview_tag.' '.$preview_href.'>« Página anterior
  • '; $pagination .= $pagination_; - $pagination .= '
  • <' . $next_tag . ' ' . $next_href . '>Próxima página »
  • '; + $pagination .= '
  • <'.$next_tag.' '.$next_href.'>Próxima página »
  • '; - foreach ( Capsule::table('gofasnfeio')-> - orderBy('id', 'desc')-> + foreach (Capsule::table('gofasnfeio')-> + orderBy('id', 'desc')-> whereBetween('id', [end($nfess), reset($nfess)])-> - take($take)-> - get( ['invoice_id', 'user_id', 'nfe_id', 'status', 'services_amount', 'environment', 'flow_status', 'pdf', 'created_at', 'updated_at'] ) as $value ) { - $client = localAPI('GetClientsDetails',['clientid' => $value->user_id, 'stats' => false, ], false); - if ($value->status === 'Waiting') { + take($take)-> + get(['invoice_id', 'user_id', 'nfe_id', 'status', 'services_amount', 'environment', 'flow_status', 'pdf', 'created_at', 'updated_at']) as $value) { + $client = localAPI('GetClientsDetails', ['clientid' => $value->user_id, 'stats' => false], false); + if ('Waiting' === $value->status) { $status = 'Aguardando'; $disabled = ['a' => 'disabled="disabled"', 'b' => 'disabled="disabled"', 'c' => 'disabled="disabled"', 'd' => 'disabled="disabled"']; } - if ($value->status === 'Created') { + if ('Created' === $value->status) { $status = 'Processando'; $disabled = ['a' => 'disabled="disabled"', 'b' => '', 'c' => 'disabled="disabled"', 'd' => 'disabled="disabled"']; } - if ($value->status === 'Issued') { + if ('Issued' === $value->status) { $status = 'Emitida'; $disabled = ['a' => 'disabled="disabled"', 'b' => '', 'c' => '', 'd' => '']; } - if ($value->status === 'Cancelled') { + if ('Cancelled' === $value->status) { $status = 'Cancelada'; $disabled = ['a' => '', 'b' => '', 'c' => 'disabled="disabled"', 'd' => '']; } - if ($value->status === 'Error') { + if ('Error' === $value->status) { $status = 'Falha ao Emitir'; $disabled = ['a' => '', 'b' => '', 'c' => 'disabled="disabled"', 'd' => 'disabled="disabled"']; } - if ($value->status === 'None') { + if ('None' === $value->status) { $status = 'Nenhum'; $disabled = ['a' => '', 'b' => '', 'c' => 'disabled="disabled"', 'd' => 'disabled="disabled"']; } - $html_table .= '#' . $value->invoice_id . ' - ' . date('d/m/Y', strtotime($value->created_at)) . ' - ' . $client['fullname'] . ' - ' . number_format( $value->services_amount, 2, ',', '.' ) . ' - ' . $status . ' + $html_table .= '#'.$value->invoice_id.' + '.date('d/m/Y', strtotime($value->created_at)).' + '.$client['fullname'].' + '.number_format($value->services_amount, 2, ',', '.').' + '.$status.' - Emitir Nova - Visualizar - Cancelar - Enviar por Email'; + Emitir Nova + Visualizar + Cancelar + Enviar por Email'; } - if ((int)$nfes_total > 0) { + if ((int) $nfes_total > 0) { echo ' - código dos Produtos -

    Listagem de notas fiscais

    ' . $nfes_total . ' Itens encontrados.
    Exibindo de ' . $nfes_from . ' a ' . $nfes_to . '. Página ' . $nfes_page . ' de ' . $nfes_pages . '
    + código dos Produtos +

    Listagem de notas fiscais

    '.$nfes_total.' Itens encontrados.
    Exibindo de '.$nfes_from.' a '.$nfes_to.'. Página '.$nfes_page.' de '.$nfes_pages.'
    @@ -146,7 +150,7 @@ function gofasnfeio_output($vars) { - ' . $html_table . ' + '.$html_table.'
    Ações
    @@ -154,7 +158,7 @@ function gofasnfeio_output($vars) {
      - ' . $pagination . ' + '.$pagination.'
    '; @@ -165,36 +169,40 @@ function gofasnfeio_output($vars) {
    '; } if ($_REQUEST['gnfe_create']) { - $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 . '
    '; + $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 ('success' !== $queue) { + $message = '
    Erro ao salvar nota fiscal no DB: '.$queue.'
    '; header_remove(); - header('Location: ' . $gnfewhmcsadminurl . 'addonmodules.php?module=gofasnfeio&gnfe_message=' . base64_encode(urlencode($message))); + header('Location: '.$gnfewhmcsadminurl.'addonmodules.php?module=gofasnfeio&gnfe_message='.base64_encode(urlencode($message))); + exit; } - if ($queue === 'success') { + if ('success' === $queue) { $message = '
    Nota fiscal enviada para processamento
    '; header_remove(); - header('Location: ' . $gnfewhmcsadminurl . 'addonmodules.php?module=gofasnfeio&gnfe_message=' . base64_encode(urlencode($message))); + header('Location: '.$gnfewhmcsadminurl.'addonmodules.php?module=gofasnfeio&gnfe_message='.base64_encode(urlencode($message))); + exit; } } if ($_REQUEST['gnfe_cancel']) { $delete_nfe = gnfe_delete_nfe($_REQUEST['gnfe_cancel']); if (!$delete_nfe->message) { - $gnfe_update_nfe = gnfe_update_nfe((object)['id' => $_REQUEST['gnfe_cancel'], 'status' => 'Cancelled', 'servicesAmount' => $_REQUEST['services_amount'], 'environment' => $_REQUEST['environment'], 'flow_status' => $_REQUEST['flow_status']],$_REQUEST['user_id'],$_REQUEST['invoice_id'],'n/a',$_REQUEST['created_at'],date('Y-m-d H:i:s') ); + $gnfe_update_nfe = gnfe_update_nfe((object) ['id' => $_REQUEST['gnfe_cancel'], 'status' => 'Cancelled', 'servicesAmount' => $_REQUEST['services_amount'], 'environment' => $_REQUEST['environment'], 'flow_status' => $_REQUEST['flow_status']], $_REQUEST['user_id'], $_REQUEST['invoice_id'], 'n/a', $_REQUEST['created_at'], date('Y-m-d H:i:s')); $message = '
    Nota fiscal cancelada com sucesso
    '; header_remove(); - header('Location: ' . $gnfewhmcsadminurl . 'addonmodules.php?module=gofasnfeio&gnfe_message=' . base64_encode(urlencode($message))); + header('Location: '.$gnfewhmcsadminurl.'addonmodules.php?module=gofasnfeio&gnfe_message='.base64_encode(urlencode($message))); + exit; } if ($delete_nfe->message) { - $message = '
    ' . $delete_nfe->message . '
    '; + $message = '
    '.$delete_nfe->message.'
    '; header_remove(); - header('Location: ' . $gnfewhmcsadminurl . 'addonmodules.php?module=gofasnfeio&gnfe_message=' . base64_encode(urlencode($message))); + header('Location: '.$gnfewhmcsadminurl.'addonmodules.php?module=gofasnfeio&gnfe_message='.base64_encode(urlencode($message))); + exit; } } @@ -203,18 +211,20 @@ function gofasnfeio_output($vars) { if (!$gnfe_email->message) { $message = '
    Email Enviado com Sucesso
    '; header_remove(); - header('Location: ' . $gnfewhmcsadminurl . 'addonmodules.php?module=gofasnfeio&gnfe_message=' . base64_encode(urlencode($message))); + header('Location: '.$gnfewhmcsadminurl.'addonmodules.php?module=gofasnfeio&gnfe_message='.base64_encode(urlencode($message))); + exit; } if ($gnfe_email->message) { - $message = '
    ' . $gnfe_email->message . '
    '; + $message = '
    '.$gnfe_email->message.'
    '; header_remove(); - header('Location: ' . $gnfewhmcsadminurl . 'addonmodules.php?module=gofasnfeio&gnfe_message=' . base64_encode(urlencode($message))); + header('Location: '.$gnfewhmcsadminurl.'addonmodules.php?module=gofasnfeio&gnfe_message='.base64_encode(urlencode($message))); + exit; } } if ($_REQUEST['gnfe_message']) { - echo urldecode(base64_decode( $_REQUEST['gnfe_message'] )); + echo urldecode(base64_decode($_REQUEST['gnfe_message'])); } } -} \ No newline at end of file +} diff --git a/modules/addons/gofasnfeio/outputproduct.php b/modules/addons/gofasnfeio/outputproduct.php index eb4e53d..90ed0d2 100644 --- a/modules/addons/gofasnfeio/outputproduct.php +++ b/modules/addons/gofasnfeio/outputproduct.php @@ -1,48 +1,52 @@ where('product_id','=',$_POST['product'])->count(); + $num = Capsule::table('tblproductcode')->where('product_id', '=', $_POST['product'])->count(); if ($num > 0) { - $res = Capsule::table('tblproductcode')->where('product_id','=',$_POST['product'])->update(['code_service' => $_POST['code'], 'update_at' => date('Y-m-d H:i:s')]); - if ($_POST['code'] == 0) { - $res = Capsule::table('tblproductcode')->where('product_id','=',$_POST['product'])->delete(); + $res = Capsule::table('tblproductcode')->where('product_id', '=', $_POST['product'])->update(['code_service' => $_POST['code'], 'update_at' => date('Y-m-d H:i:s')]); + if (0 == $_POST['code']) { + $res = Capsule::table('tblproductcode')->where('product_id', '=', $_POST['product'])->delete(); } } else { - if ($_POST['code'] != 0) { + if (0 != $_POST['code']) { $res = Capsule::table('tblproductcode')->insert(['code_service' => $_POST['code'], 'product_id' => $_POST['product'], 'create_at' => date('Y-m-d H:i:s'), 'ID_user' => $user['adminid']]); } } $message = '
    Código Salvo
    '; header_remove(); - header('Location: ' . $gnfewhmcsadminurl . 'addonmodules.php?module=gofasnfeio&action=code_product&gnfe_message=' . base64_encode(urlencode($message))); + header('Location: '.$gnfewhmcsadminurl.'addonmodules.php?module=gofasnfeio&action=code_product&gnfe_message='.base64_encode(urlencode($message))); + exit; } catch (\Exception $e) { $e->getMessage(); - $message = '
    ' . $e->getMessage() . '
    '; + $message = '
    '.$e->getMessage().'
    '; header_remove(); - header('Location: ' . $gnfewhmcsadminurl . 'addonmodules.php?module=gofasnfeio&action=code_product&gnfe_message=' . base64_encode(urlencode($message))); + header('Location: '.$gnfewhmcsadminurl.'addonmodules.php?module=gofasnfeio&action=code_product&gnfe_message='.base64_encode(urlencode($message))); + exit; } } - foreach ( Capsule::table('tblconfiguration')->where('setting', '=', 'gnfewhmcsadminurl')->get( ['value'] ) as $gnfewhmcsadminurl_ ) { + foreach (Capsule::table('tblconfiguration')->where('setting', '=', 'gnfewhmcsadminurl')->get(['value']) as $gnfewhmcsadminurl_) { $gnfewhmcsadminurl = $gnfewhmcsadminurl_->value; } $nfes = []; - foreach ( Capsule::table('tblproducts')->orderBy('id', 'desc')->get( ['id'] ) as $nfes_ ) { + foreach (Capsule::table('tblproducts')->orderBy('id', 'desc')->get(['id']) as $nfes_) { $nfes[] = $nfes_->id; } if ($_REQUEST['page']) { - $nfes_page = (int)$_REQUEST['page']; + $nfes_page = (int) $_REQUEST['page']; } else { $nfes_page = 1; } if ($_REQUEST['take']) { - $take = (int)$_REQUEST['take']; + $take = (int) $_REQUEST['take']; } else { $take = 10; } @@ -54,84 +58,84 @@ } $nfes_pages = ceil($nfes_total / $take); - $nfes_from_ = ( $nfes_page * $take ) - $take; + $nfes_from_ = ($nfes_page * $take) - $take; $nfes_from = $nfs_keys[$nfes_from_ + 1]; - $nfes_to_ = ( $nfes_from + $take ) - 2; + $nfes_to_ = ($nfes_from + $take) - 2; $nfes_to = $nfs_keys[$nfes_to_ + 1]; $nfess = array_slice($nfes, $nfes_from_, $nfes_to); - if ((int)$nfes_page === (int)$nfes_pages) { + if ((int) $nfes_page === (int) $nfes_pages) { $nfes_to = $nfes_total; $nfess = array_slice($nfes, $nfes_from_, $nfes_to_); } - if ((int)$take >= (int)$nfes_total) { + if ((int) $take >= (int) $nfes_total) { $nfes_from = 1; $nfess = array_slice($nfes, $nfes_from_, $nfes_to); } // Pagination $i = 1; - while ($i <= $nfes_pages ) { + while ($i <= $nfes_pages) { $page_num = $i++; - if ( (int)$page_num !== (int)$nfes_page ) { + if ((int) $page_num !== (int) $nfes_page) { $tag = 'a '; $a_style = ''; $li_class = 'class="enabled"'; - $href = $gnfewhmcsadminurl . 'addonmodules.php?module=gofasnfeio&page=' . $page_num; - } elseif ( (int)$page_num === (int)$nfes_page ) { + $href = $gnfewhmcsadminurl.'addonmodules.php?module=gofasnfeio&page='.$page_num; + } elseif ((int) $page_num === (int) $nfes_page) { $tag = 'span '; $a_style = 'style="background: #337ab7; color: #fff"'; $li_class = 'class="disabled"'; $href = ''; } - $pagination_ .= '
  • <' . $tag . ' ' . $a_style . ' href="' . $href . '" >' . $page_num . '
  • '; + $pagination_ .= '
  • <'.$tag.' '.$a_style.' href="'.$href.'" >'.$page_num.'
  • '; } - if ((int)$nfes_page === 1) { + if (1 === (int) $nfes_page) { $preview_class = ' class="previous disabled" '; $preview_href = ''; $preview_tag = 'span '; } else { $preview_class = ' class="previous" '; - $preview_href = ' href="' . $gnfewhmcsadminurl . 'addonmodules.php?module=gofasnfeio&page=' . ($nfes_page - 1) . '" '; + $preview_href = ' href="'.$gnfewhmcsadminurl.'addonmodules.php?module=gofasnfeio&page='.($nfes_page - 1).'" '; $preview_tag = 'a '; } - if ((int)$nfes_page === (int)$nfes_pages) { + if ((int) $nfes_page === (int) $nfes_pages) { $next_class = ' class="next disabled" '; $next_href = ''; $next_tag = 'span '; } else { $next_class = ' class="next" '; - $next_href = ' href="' . $gnfewhmcsadminurl . 'addonmodules.php?module=gofasnfeio&page=' . ($nfes_page + 1) . '" '; + $next_href = ' href="'.$gnfewhmcsadminurl.'addonmodules.php?module=gofasnfeio&page='.($nfes_page + 1).'" '; $next_tag = 'a '; } - $pagination .= '
  • <' . $preview_tag . ' ' . $preview_href . '>« Página anterior
  • '; + $pagination .= '
  • <'.$preview_tag.' '.$preview_href.'>« Página anterior
  • '; $pagination .= $pagination_; - $pagination .= '
  • <' . $next_tag . ' ' . $next_href . '>Próxima página »
  • '; + $pagination .= '
  • <'.$next_tag.' '.$next_href.'>Próxima página »
  • '; - foreach ( Capsule::table('tblproducts')-> + foreach (Capsule::table('tblproducts')-> leftJoin('tblproductcode', 'tblproducts.id', '=', 'tblproductcode.product_id')-> orderBy('tblproducts.id', 'desc')-> whereBetween('tblproducts.id', [end($nfess), reset($nfess)])-> take($take)-> - get( ['tblproducts.id', 'tblproducts.name', 'tblproducts.created_at', 'tblproductcode.update_at', 'tblproductcode.code_service'] ) as $product) { + get(['tblproducts.id', 'tblproducts.name', 'tblproducts.created_at', 'tblproductcode.update_at', 'tblproductcode.code_service']) as $product) { $created_at = $product->created_at ? date('d/m/Y', strtotime($product->created_at)) : ''; $update_at = $product->update_at ? date('d/m/Y', strtotime($product->update_at)) : ''; //depois linkar o id e o nome com a pagina do produto - $html_table .= '#' . $product->id . ' - ' . $created_at . ' - ' . $update_at . ' - ' . $product->name . ' + $html_table .= '#'.$product->id.' + '.$created_at.' + '.$update_at.' + '.$product->name.'
    - + - +
    '; } echo ' - NFE.oi -

    Listagem produtos

    ' . $nfes_total . ' Itens encontrados.
    Exibindo de ' . $nfes_from . ' a ' . $nfes_to . '. Página ' . $nfes_page . ' de ' . $nfes_pages . '
    + NFE.oi +

    Listagem produtos

    '.$nfes_total.' Itens encontrados.
    Exibindo de '.$nfes_from.' a '.$nfes_to.'. Página '.$nfes_page.' de '.$nfes_pages.'
    @@ -144,7 +148,7 @@ - ' . $html_table . ' + '.$html_table.'
    Salvar
    @@ -152,10 +156,10 @@
      - ' . $pagination . ' + '.$pagination.'
    '; if ($_REQUEST['gnfe_message']) { - echo urldecode(base64_decode( $_REQUEST['gnfe_message'] )); - } \ No newline at end of file + echo urldecode(base64_decode($_REQUEST['gnfe_message'])); + } diff --git a/modules/addons/gofasnfeio/pdf.php b/modules/addons/gofasnfeio/pdf.php index 5466735..78c79e1 100644 --- a/modules/addons/gofasnfeio/pdf.php +++ b/modules/addons/gofasnfeio/pdf.php @@ -1,15 +1,17 @@ where('setting', '=', 'Domain')->get( ['value'] ) as $gnfewhmcsadminurl_ ) { + foreach (Capsule::table('tblconfiguration')->where('setting', '=', 'Domain')->get(['value']) as $gnfewhmcsadminurl_) { $gnfewhmcsadminurl = $gnfewhmcsadminurl_->value; } - foreach (Capsule::table('gofasnfeio')->where( 'invoice_id', '=',$invoice_id )->get( ['id', 'invoice_id']) as $nfe) { - $url = $gnfewhmcsadminurl . 'modules/addons/gofasnfeio/createpdf.php?nfe_id=' . $nfe->id; - echo ""; + foreach (Capsule::table('gofasnfeio')->where('invoice_id', '=', $invoice_id)->get(['id', 'invoice_id']) as $nfe) { + $url = $gnfewhmcsadminurl.'modules/addons/gofasnfeio/createpdf.php?nfe_id='.$nfe->id; + echo ""; } } -echo ""; +echo ""; diff --git a/modules/addons/gofasnfeio/prod_output.php b/modules/addons/gofasnfeio/prod_output.php index e2de8a7..6d82783 100644 --- a/modules/addons/gofasnfeio/prod_output.php +++ b/modules/addons/gofasnfeio/prod_output.php @@ -1,9 +1,10 @@ The date & time are currently ' . date('Y-m-d H:i:s') . '

    '; + echo '

    The date & time are currently '.date('Y-m-d H:i:s').'

    '; } -} \ No newline at end of file +} diff --git a/modules/addons/gofasnfeio/xml.php b/modules/addons/gofasnfeio/xml.php index 79ebfc5..6c3dfd6 100644 --- a/modules/addons/gofasnfeio/xml.php +++ b/modules/addons/gofasnfeio/xml.php @@ -1,16 +1,17 @@ where('setting', '=', 'Domain')->get( ['value'] ) as $gnfewhmcsadminurl_ ) { + foreach (Capsule::table('tblconfiguration')->where('setting', '=', 'Domain')->get(['value']) as $gnfewhmcsadminurl_) { $gnfewhmcsadminurl = $gnfewhmcsadminurl_->value; } - foreach (Capsule::table('gofasnfeio')->where( 'invoice_id', '=',$invoice_id )->get( ['id', 'invoice_id']) as $nfe) { - $url = $gnfewhmcsadminurl . 'modules/addons/gofasnfeio/createxml.php?nfe_id=' . $nfe->id; - echo ""; + foreach (Capsule::table('gofasnfeio')->where('invoice_id', '=', $invoice_id)->get(['id', 'invoice_id']) as $nfe) { + $url = $gnfewhmcsadminurl.'modules/addons/gofasnfeio/createxml.php?nfe_id='.$nfe->id; + echo ""; } } -echo ""; +echo ""; From df281a76b35c715c1d9a850471224ebf7ea6759c Mon Sep 17 00:00:00 2001 From: JoaoVictorLNacional Date: Mon, 4 Jan 2021 15:59:55 -0300 Subject: [PATCH 29/52] =?UTF-8?q?add=20instru=C3=A7=C3=B5es=20de=20atualiz?= =?UTF-8?q?a=C3=A7=C3=A3o=20no=20readme?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/README.md b/README.md index 7afed8b..84768e5 100644 --- a/README.md +++ b/README.md @@ -48,6 +48,13 @@ Clique nas imagens para ampliar 2. Descompacte o arquivo .zip; 3. Copie o diretório `/gofasnfeio/`, localizados na pasta `/modules/addons/` do arquivo recém descompactado, para a pasta `/modules/addons/` da instalação do WHMCS; +## ATUALIZAÇÂO +1. Faça download do módulo [neste link](https://github.com/nfe/whmcs-addon/archive/master.zip "neste link"); +2. Descompacte o arquivo .zip; +3. Desative a versão anterior do modulo no painel administrativo do WHMCS, em Opções > Módulos Addon > Gofas NFE.io > Desativar. +4. Subistitua o diretório `/gofasnfeio/`, localizado na pasta `/modules/addons/` na instalação do WHMCS, pela pasta `/modules/addons/` do arquivo descompactado; +5. Volte a ativar o modulo no mesmo painel administrativo. + ## PRÉ CONFIGURAÇÃO E ATIVAÇÃO 1. No painel administrativo do WHMCS, crie um campo personalizado de cliente para CPF e/ou CNPJ. Caso prefira, você pode criar dois campos distintos, sendo um campo apenas para CPF e outro campo apenas para CNPJ. O módulo identifica os campos do perfil do cliente automaticamente; 2. Ative o addon no painel administrativo do WHMCS, em Opções > Módulos Addon > Gofas NFE.io > Ativar. From edab2811b53c68a368cb9180c78b4ec58ff836ac Mon Sep 17 00:00:00 2001 From: JoaoVictorLNacional Date: Tue, 5 Jan 2021 13:49:34 -0300 Subject: [PATCH 30/52] =?UTF-8?q?altera=C3=A7=C3=B5es=20de=20acordo=20com?= =?UTF-8?q?=20a=20lista=20do=20trello?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- modules/addons/gofasnfeio/callback.php | 4 ++ modules/addons/gofasnfeio/config.php | 6 +++ modules/addons/gofasnfeio/functions.php | 44 ++----------------- .../addons/gofasnfeio/hooks/aftercronjob.php | 18 +++++--- .../addons/gofasnfeio/hooks/dailycronjob.php | 1 - modules/addons/gofasnfeio/outputproduct.php | 1 - 7 files changed, 28 insertions(+), 48 deletions(-) diff --git a/README.md b/README.md index 84768e5..4dd182c 100644 --- a/README.md +++ b/README.md @@ -51,7 +51,7 @@ Clique nas imagens para ampliar ## ATUALIZAÇÂO 1. Faça download do módulo [neste link](https://github.com/nfe/whmcs-addon/archive/master.zip "neste link"); 2. Descompacte o arquivo .zip; -3. Desative a versão anterior do modulo no painel administrativo do WHMCS, em Opções > Módulos Addon > Gofas NFE.io > Desativar. +3. Desative a versão anterior do módulo no painel administrativo do WHMCS, em Opções > Módulos Addon > Gofas NFE.io > Desativar. 4. Subistitua o diretório `/gofasnfeio/`, localizado na pasta `/modules/addons/` na instalação do WHMCS, pela pasta `/modules/addons/` do arquivo descompactado; 5. Volte a ativar o modulo no mesmo painel administrativo. diff --git a/modules/addons/gofasnfeio/callback.php b/modules/addons/gofasnfeio/callback.php index da8cf91..11ee787 100644 --- a/modules/addons/gofasnfeio/callback.php +++ b/modules/addons/gofasnfeio/callback.php @@ -4,6 +4,8 @@ use WHMCS\Database\Capsule; $post = json_decode(file_get_contents('php://input'), true); +logModuleCall('gofas_nfeio', 'callback', $post, '', '', 'replaceVars'); + if ($post) { require_once __DIR__.'/functions.php'; $params = []; @@ -15,6 +17,8 @@ $nfe_for_invoice[$key] = json_decode(json_encode($value), true); } $nfe = $nfe_for_invoice['0']; + logModuleCall('gofas_nfeio', 'callback2', $nfe, '', '', 'replaceVars'); + if ((string) $nfe['nfe_id'] === (string) $post['id'] and $nfe['status'] !== (string) $post['status']) { $new_nfe = [ 'invoice_id' => $nfe['invoice_id'], diff --git a/modules/addons/gofasnfeio/config.php b/modules/addons/gofasnfeio/config.php index 1eb1a7e..a960e40 100644 --- a/modules/addons/gofasnfeio/config.php +++ b/modules/addons/gofasnfeio/config.php @@ -239,6 +239,12 @@ function gnfe_verifyInstall() 'Options' => 'Sim,Não', 'Default' => 'Sim', ]]; + $tax = ['InvoiceDetails' => [ + 'FriendlyName' => 'O que deve aparecer nos detalhes da fatura ?', + 'Type' => 'radio', + 'Options' => 'Número da fatura,nome dos serviços', + 'Default' => 'Numero da fatura', + ]]; $footer = ['footer' => [ 'FriendlyName' => '', 'Description' => '© '.date('Y').' Suporte módulo', diff --git a/modules/addons/gofasnfeio/functions.php b/modules/addons/gofasnfeio/functions.php index f1eada7..0e95435 100644 --- a/modules/addons/gofasnfeio/functions.php +++ b/modules/addons/gofasnfeio/functions.php @@ -181,7 +181,7 @@ function gnfe_ibge($zip) function gnfe_queue_nfe($invoice_id, $create_all = false) { $invoice = localAPI('GetInvoice', ['invoiceid' => $invoice_id], false); - $itens = get_prodict_invoice($invoice_id); + $itens = get_product_invoice($invoice_id); if (!$itens) { foreach (Capsule::table('tblinvoiceitems')->where('invoiceid', '=', $invoice_id)->get(['userid', 'amount']) as $item_not_salle) { @@ -269,7 +269,7 @@ function gnfe_queue_nfe($invoice_id, $create_all = false) function gnfe_queue_nfe_edit($invoice_id, $gofasnfeio_id) { $invoice = localAPI('GetInvoice', ['invoiceid' => $invoice_id], false); - $itens = get_prodict_invoice($invoice_id); + $itens = get_product_invoice($invoice_id); foreach ($itens as $item) { $data = [ @@ -302,42 +302,6 @@ function gnfe_queue_nfe_edit($invoice_id, $gofasnfeio_id) } } -// if (!function_exists('gnfe_queue_nfe_edit_all')) { -// function gnfe_queue_nfe_edit_all($invoice_id) -// { -// $invoice = localAPI('GetInvoice', ['invoiceid' => $invoice_id], false); -// $itens = get_prodict_invoice($invoice_id); -// foreach ($itens as $item) { -// $data = [ -// 'invoice_id' => $invoice_id, -// 'user_id' => $invoice['userid'], -// 'nfe_id' => 'waiting', -// 'status' => 'Waiting', -// 'services_amount' => $item['monthly'], -// 'environment' => 'waiting', -// 'flow_status' => 'waiting', -// 'pdf' => 'waiting', -// 'created_at' => date('Y-m-d H:i:s'), -// 'updated_at' => 'waiting', -// 'rpsSerialNumber' => 'waiting', -// 'service_code' => $item['value'], -// ]; - -// $nfe_for_invoice = gnfe_get_local_nfe($invoice_id, ['status']); - -// if (!$nfe_for_invoice['status']) { -// try { -// $save_nfe = Capsule::table('gofasnfeio')->insert($data); -// } catch (\Exception $e) { -// return $e->getMessage(); -// } -// } -// } - -// return 'success'; -// } -// } - if (!function_exists('gnfe_issue_nfe')) { function gnfe_issue_nfe($postfields) { @@ -810,7 +774,7 @@ function gnfe_customer_service_code($item_id) } } -function get_prodict_invoice($invoice_id) +function get_product_invoice($invoice_id) { $query = "SELECT DISTINCT tblhosting.packageid,tblpricing.monthly from tblhosting INNER JOIN tblinvoiceitems ON tblinvoiceitems.relid = tblhosting.id @@ -854,7 +818,7 @@ function get_prodict_invoice($invoice_id) $list[] = $list2; } catch (\Exception $th) { $pdo->rollBack(); - logModuleCall('gofas_nfeio', 'get_prodict_invoice erro', $th, '', '', 'replaceVars'); + logModuleCall('gofas_nfeio', 'get_product_invoice erro', $th, '', '', 'replaceVars'); } } diff --git a/modules/addons/gofasnfeio/hooks/aftercronjob.php b/modules/addons/gofasnfeio/hooks/aftercronjob.php index 771f913..dbfba99 100644 --- a/modules/addons/gofasnfeio/hooks/aftercronjob.php +++ b/modules/addons/gofasnfeio/hooks/aftercronjob.php @@ -7,8 +7,8 @@ $params = gnfe_config(); -// foreach (Capsule::table('gofasnfeio')->orderBy('id', 'desc')->where('status', '=', 'Waiting')->take(1)->get(['id', 'invoice_id', 'services_amount']) as $waiting) { - 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')->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) { $data = getTodaysDate(false); $dataAtual = toMySQLDate($data); @@ -19,6 +19,9 @@ } 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) { @@ -53,10 +56,15 @@ $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; + foreach (Capsule::table('tblconfiguration')->where('setting', '=', 'Domain')->get(['value']) as $gnfeWhmcsUrl) { + $gnfeWhmcsUrl = $gnfeWhmcsUrl->value; } - $desc = 'Nota referente a fatura #'.$waiting->invoice_id.' '.$gnfewhmcsadminurl.'viewinvoice.php?id='.$waiting->invoice_id.' '; + if ('Número da fatura' == $params['InvoiceDetails']) { + $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 (0 == !strlen($customer['insc_municipal'])) { $postfields = [ 'cityServiceCode' => $service_code, diff --git a/modules/addons/gofasnfeio/hooks/dailycronjob.php b/modules/addons/gofasnfeio/hooks/dailycronjob.php index 095db77..fc053df 100644 --- a/modules/addons/gofasnfeio/hooks/dailycronjob.php +++ b/modules/addons/gofasnfeio/hooks/dailycronjob.php @@ -15,7 +15,6 @@ $datepaid = date('Ymd', strtotime($invoices->datepaid)); $datepaid_to_issue_ = '-'.$params['issue_note_after'].' days'; $datepaid_to_issue = date('Ymd', strtotime($datepaid_to_issue_)); - //ver isso com varios registros $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); diff --git a/modules/addons/gofasnfeio/outputproduct.php b/modules/addons/gofasnfeio/outputproduct.php index 90ed0d2..48d66df 100644 --- a/modules/addons/gofasnfeio/outputproduct.php +++ b/modules/addons/gofasnfeio/outputproduct.php @@ -120,7 +120,6 @@ get(['tblproducts.id', 'tblproducts.name', 'tblproducts.created_at', 'tblproductcode.update_at', 'tblproductcode.code_service']) as $product) { $created_at = $product->created_at ? date('d/m/Y', strtotime($product->created_at)) : ''; $update_at = $product->update_at ? date('d/m/Y', strtotime($product->update_at)) : ''; - //depois linkar o id e o nome com a pagina do produto $html_table .= '#'.$product->id.' '.$created_at.' '.$update_at.' From d6205a6305fc23c42e4d9c65501cd888f63ce067 Mon Sep 17 00:00:00 2001 From: JoaoVictorLNacional Date: Tue, 5 Jan 2021 14:37:01 -0300 Subject: [PATCH 31/52] =?UTF-8?q?modificado=20o=20local=20das=20fun=C3=A7?= =?UTF-8?q?=C3=B5es=20da=20instala=C3=A7=C3=A3o=20do=20modulo?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- modules/addons/gofasnfeio/activate.php | 22 +-------- modules/addons/gofasnfeio/config.php | 11 ++++- modules/addons/gofasnfeio/functions.php | 49 ++++++++++--------- modules/addons/gofasnfeio/gofasnfeio.php | 2 - .../addons/gofasnfeio/hooks/aftercronjob.php | 1 - .../addons/gofasnfeio/hooks/dailycronjob.php | 6 ++- 6 files changed, 43 insertions(+), 48 deletions(-) diff --git a/modules/addons/gofasnfeio/activate.php b/modules/addons/gofasnfeio/activate.php index 8aa131e..b794998 100644 --- a/modules/addons/gofasnfeio/activate.php +++ b/modules/addons/gofasnfeio/activate.php @@ -1,21 +1,3 @@ -where('setting', '=', 'version_nfeio')->get(['value']); - $version = $row[0]->value; - if ($version != $current_version) { - create_table_product_code(); - set_code_service_camp_gofasnfeio(); - set_custom_field_ini_date(); - - Capsule::table('tblconfiguration')->insert(['setting' => 'version_nfeio', 'value' => $current_version, 'created_at' => date('Y-m-d H:i:s')]); - } - } -} + + \ No newline at end of file diff --git a/modules/addons/gofasnfeio/config.php b/modules/addons/gofasnfeio/config.php index a960e40..8139511 100644 --- a/modules/addons/gofasnfeio/config.php +++ b/modules/addons/gofasnfeio/config.php @@ -5,6 +5,8 @@ } use WHMCS\Database\Capsule; +require_once __DIR__.'/functions.php'; + if (!function_exists('gofasnfeio_config')) { if (!function_exists('gnfe_customfields_dropdow')) { function gnfe_customfields_dropdow() @@ -149,7 +151,9 @@ function gnfe_verifyInstall() // Added in v 1 dot 1 dot 3 if (!Capsule::schema()->hasColumn('gofasnfeio', 'rpsNumber')) { try { - Capsule::schema()->table('gofasnfeio', function ($table) {$table->string('rpsNumber'); }); + 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()}"; } @@ -164,7 +168,10 @@ function gnfe_verifyInstall() } } gnfe_verifyInstall(); - + create_table_product_code(); + set_code_service_camp_gofasnfeio(); + set_custom_field_ini_date(); + $intro = ['intro' => [ 'FriendlyName' => '', 'Description' => '

    Módulo Nota Fiscal NFE.io para WHMCS v'.$module_version.'

    diff --git a/modules/addons/gofasnfeio/functions.php b/modules/addons/gofasnfeio/functions.php index 0e95435..9ea36e4 100644 --- a/modules/addons/gofasnfeio/functions.php +++ b/modules/addons/gofasnfeio/functions.php @@ -828,30 +828,38 @@ function get_product_invoice($invoice_id) if (!function_exists('set_code_service_camp_gofasnfeio')) { function set_code_service_camp_gofasnfeio() { - $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(); - } - $pdo->beginTransaction(); - - try { - $statement = $pdo->prepare('ALTER TABLE gofasnfeio ADD monthly DECIMAL(16,2)'); - $statement->execute(); - $pdo->commit(); - } catch (\Exception $e) { - $pdo->rollBack(); + if (!Capsule::schema()->hasColumn('gofasnfeio', 'service_code') && !Capsule::schema()->hasColumn('gofasnfeio', 'monthly')) { + $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(); + } + $pdo->beginTransaction(); + + try { + $statement = $pdo->prepare('ALTER TABLE gofasnfeio ADD monthly DECIMAL(16,2)'); + $statement->execute(); + $pdo->commit(); + } catch (\Exception $e) { + $pdo->rollBack(); + } } } } + + if (!function_exists('create_table_product_code')) { function create_table_product_code() { + if (Capsule::schema()->hasTable('tblproductcode')) { + return ''; + } + $pdo = Capsule::connection()->getPdo(); $pdo->beginTransaction(); @@ -867,10 +875,7 @@ function create_table_product_code() $pdo->commit(); } catch (\Exception $e) { $pdo->rollBack(); + logModuleCall('gofas_nfeio', 'create_table_product_code error', $e, '', '', 'replaceVars'); } } } - -function update_table() -{ -} diff --git a/modules/addons/gofasnfeio/gofasnfeio.php b/modules/addons/gofasnfeio/gofasnfeio.php index 0d34c35..9cf18e3 100644 --- a/modules/addons/gofasnfeio/gofasnfeio.php +++ b/modules/addons/gofasnfeio/gofasnfeio.php @@ -7,5 +7,3 @@ require_once __DIR__.'/config.php'; require_once __DIR__.'/output.php'; - -require_once __DIR__.'/activate.php'; diff --git a/modules/addons/gofasnfeio/hooks/aftercronjob.php b/modules/addons/gofasnfeio/hooks/aftercronjob.php index dbfba99..6abd414 100644 --- a/modules/addons/gofasnfeio/hooks/aftercronjob.php +++ b/modules/addons/gofasnfeio/hooks/aftercronjob.php @@ -7,7 +7,6 @@ $params = gnfe_config(); -// 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) { $data = getTodaysDate(false); $dataAtual = toMySQLDate($data); diff --git a/modules/addons/gofasnfeio/hooks/dailycronjob.php b/modules/addons/gofasnfeio/hooks/dailycronjob.php index fc053df..45117c7 100644 --- a/modules/addons/gofasnfeio/hooks/dailycronjob.php +++ b/modules/addons/gofasnfeio/hooks/dailycronjob.php @@ -45,7 +45,11 @@ foreach (Capsule::table('tblconfiguration')->where('setting', '=', 'Domain')->get(['value']) as $gnfewhmcsadminurl) { $gnfewhmcsadminurl = $gnfewhmcsadminurl->value; } - $desc = 'Nota referente a fatura #'.$nfeio->invoice_id.' '.$gnfewhmcsadminurl.'viewinvoice.php?id='.$waiting->invoice_id.' '; + if ('Número da fatura' == $params['InvoiceDetails']) { + $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 (0 == !strlen($customer['insc_municipal'])) { $postfields = [ 'cityServiceCode' => $service_code, From 4baae00a2355e1f06d78f1bddc9a0308e940a890 Mon Sep 17 00:00:00 2001 From: JoaoVictorLNacional Date: Tue, 5 Jan 2021 14:37:13 -0300 Subject: [PATCH 32/52] =?UTF-8?q?modificado=20o=20local=20das=20fun=C3=A7?= =?UTF-8?q?=C3=B5es=20da=20instala=C3=A7=C3=A3o=20do=20modulo?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- modules/addons/gofasnfeio/activate.php | 3 --- 1 file changed, 3 deletions(-) delete mode 100644 modules/addons/gofasnfeio/activate.php diff --git a/modules/addons/gofasnfeio/activate.php b/modules/addons/gofasnfeio/activate.php deleted file mode 100644 index b794998..0000000 --- a/modules/addons/gofasnfeio/activate.php +++ /dev/null @@ -1,3 +0,0 @@ - - - \ No newline at end of file From 766408723004d89fb47972cb3c59c8d3c2fbd974 Mon Sep 17 00:00:00 2001 From: JoaoVictorLNacional Date: Tue, 5 Jan 2021 14:42:07 -0300 Subject: [PATCH 33/52] =?UTF-8?q?removido=20o=20passo=20a=20passo=20de=20a?= =?UTF-8?q?tualiza=C3=A7=C3=A3o=20no=20redme?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 7 ------- 1 file changed, 7 deletions(-) diff --git a/README.md b/README.md index 4dd182c..7afed8b 100644 --- a/README.md +++ b/README.md @@ -48,13 +48,6 @@ Clique nas imagens para ampliar 2. Descompacte o arquivo .zip; 3. Copie o diretório `/gofasnfeio/`, localizados na pasta `/modules/addons/` do arquivo recém descompactado, para a pasta `/modules/addons/` da instalação do WHMCS; -## ATUALIZAÇÂO -1. Faça download do módulo [neste link](https://github.com/nfe/whmcs-addon/archive/master.zip "neste link"); -2. Descompacte o arquivo .zip; -3. Desative a versão anterior do módulo no painel administrativo do WHMCS, em Opções > Módulos Addon > Gofas NFE.io > Desativar. -4. Subistitua o diretório `/gofasnfeio/`, localizado na pasta `/modules/addons/` na instalação do WHMCS, pela pasta `/modules/addons/` do arquivo descompactado; -5. Volte a ativar o modulo no mesmo painel administrativo. - ## PRÉ CONFIGURAÇÃO E ATIVAÇÃO 1. No painel administrativo do WHMCS, crie um campo personalizado de cliente para CPF e/ou CNPJ. Caso prefira, você pode criar dois campos distintos, sendo um campo apenas para CPF e outro campo apenas para CNPJ. O módulo identifica os campos do perfil do cliente automaticamente; 2. Ative o addon no painel administrativo do WHMCS, em Opções > Módulos Addon > Gofas NFE.io > Ativar. From 81700653a7b195101c1cab07f19c58682f3ef0da Mon Sep 17 00:00:00 2001 From: Davi Date: Tue, 5 Jan 2021 15:25:31 -0300 Subject: [PATCH 34/52] Update config.php MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ajuste de versão e nomenclatura. --- modules/addons/gofasnfeio/config.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/modules/addons/gofasnfeio/config.php b/modules/addons/gofasnfeio/config.php index 8139511..51fea88 100644 --- a/modules/addons/gofasnfeio/config.php +++ b/modules/addons/gofasnfeio/config.php @@ -32,7 +32,7 @@ function gnfe_customfields_dropdow() } function gofasnfeio_config() { - $module_version = '1.2.4'; + $module_version = '1.2.7'; $module_version_int = (int) preg_replace('/[^0-9]/', '', $module_version); /// REMOVER VERIFICAÇÃO APÓS VERSÃO 2.0 @@ -249,8 +249,8 @@ function gnfe_verifyInstall() $tax = ['InvoiceDetails' => [ 'FriendlyName' => 'O que deve aparecer nos detalhes da fatura ?', 'Type' => 'radio', - 'Options' => 'Número da fatura,nome dos serviços', - 'Default' => 'Numero da fatura', + 'Options' => 'Número da fatura,Nome dos serviços', + 'Default' => 'Número da fatura', ]]; $footer = ['footer' => [ 'FriendlyName' => '', From d5f439c18d04cf39cfa35e82d7ed35333248d89e Mon Sep 17 00:00:00 2001 From: Davi Date: Tue, 5 Jan 2021 15:43:05 -0300 Subject: [PATCH 35/52] Update README.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ajuste readme de acordo com a nova versão. --- README.md | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 8b6d108..cb82395 100644 --- a/README.md +++ b/README.md @@ -48,6 +48,12 @@ Clique nas imagens para ampliar 2. Descompacte o arquivo .zip; 3. Copie o diretório `/gofasnfeio/`, localizados na pasta `/modules/addons/` do arquivo recém descompactado, para a pasta `/modules/addons/` da instalação do WHMCS; +## ATUALIZAÇÃO +1. Faça download do módulo [neste link](https://github.com/nfe/whmcs-addon/archive/master.zip "neste link"); +2. Descompacte o arquivo .zip; +3. Dentro da instalação do seu WHMCS remova a pasta `/modules/addons/gofasnfeio/`; +3. Copie o diretório `/gofasnfeio/`, localizados na pasta `/modules/addons/` do arquivo recém descompactado, para a pasta `/modules/addons/` da instalação do WHMCS; + ## PRÉ CONFIGURAÇÃO E ATIVAÇÃO 1. No painel administrativo do WHMCS, crie um campo personalizado de cliente para CPF e/ou CNPJ. Caso prefira, você pode criar dois campos distintos, sendo um campo apenas para CPF e outro campo apenas para CNPJ. O módulo identifica os campos do perfil do cliente automaticamente; 2. Ative o addon no painel administrativo do WHMCS, em Opções > Módulos Addon > Gofas NFE.io > Ativar. @@ -65,7 +71,7 @@ Clique nas imagens para ampliar 10. Controle de Acesso: Escolha os grupos de administradores ou operadores que terão permissão para acessar a lista de faturas gerada pelo módulo no menu Addons > Gofas NFE.io. ## LINK DA NOTA EM PDF E XML -Para inserir um link da nota fiscal do PDF e XML direto na fatura do template do WHMCS, utilize o exemplo abaixo: +Para inserir um link da nota fiscal do PDF e XML, edite o arquivo viewinvoice.tpl da pasta do template do WHMCS, utilize o exemplo abaixo: ``` {if $status eq "Paid" || $clientsdetails.userid eq "6429"} NOTA FISCAL PDF | XML{/if} ``` @@ -73,6 +79,15 @@ Para inserir um link da nota fiscal do PDF e XML direto na fatura do template do ## CHANGELOG #### IMPORTANTE: Ao atualizar, após substituir os arquivos pelos mais recentes, acesse as configurações do módulo no menu `Opções > Módulos Addon > Gofas NFE.io` do painel administrativo do WHMCS e clique em "Salvar Alterações". Isso garente que os novos parâmetros serão gravados corretamente no banco de dados. +### v1.2.7 +- envio do nome da empresa ao invés do nome pessoa física quando o CNPJ estiver definido +- criar nota fiscal de acordo com o código de serviço de cada serviço +- corrigido erro de caracteres especiais +- opção de criar nota individualmente por tipo de serviço +- emissão de nota fiscal a partir da data de instalação do módulo +- opção de descrição do serviço na nota: referente a fatura ou nome do serviço. +- ajuste de link das notas fiscais na fatura para abrir todas as notas. +- ajuste de instalação do módulo ### v1.2.6 - opção manual para criação de notas fiscais. ### v1.2.5 @@ -101,4 +116,4 @@ Para inserir um link da nota fiscal do PDF e XML direto na fatura do template do #### v1.0.0 - Lançamento. -© 2020 [Gofas Software](https://gofas.net/whmcs/modulo-nfe-io-para-whmcs/) +© 2021 [Manutenção Link Nacional](https://www.linknacional.com.br/suporte-whmcs) From 101eab5c8bb5f15684771e93e46cd350294260c1 Mon Sep 17 00:00:00 2001 From: Davi Date: Tue, 5 Jan 2021 15:44:57 -0300 Subject: [PATCH 36/52] Update config.php MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ajuste nomenclatura código de serviço principal. --- modules/addons/gofasnfeio/config.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/addons/gofasnfeio/config.php b/modules/addons/gofasnfeio/config.php index 51fea88..6ef6836 100644 --- a/modules/addons/gofasnfeio/config.php +++ b/modules/addons/gofasnfeio/config.php @@ -188,7 +188,7 @@ function gnfe_verifyInstall() 'Description' => 'Obter ID da empresa', ]]; $service_code = ['service_code' => [ - 'FriendlyName' => 'Código de Serviço', + 'FriendlyName' => 'Código de Serviço Principal', 'Type' => 'text', 'Description' => 'O que é Código de Serviço?', ]]; From 2dca107f7b468bccda3a70b5d308c5eb3e63f68f Mon Sep 17 00:00:00 2001 From: Davi Date: Tue, 5 Jan 2021 15:48:04 -0300 Subject: [PATCH 37/52] Update config.php MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit correção de bug parâmetro duplicado --- modules/addons/gofasnfeio/config.php | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/modules/addons/gofasnfeio/config.php b/modules/addons/gofasnfeio/config.php index 6ef6836..d757b00 100644 --- a/modules/addons/gofasnfeio/config.php +++ b/modules/addons/gofasnfeio/config.php @@ -239,14 +239,13 @@ function gnfe_verifyInstall() 'Type' => 'dropdown', 'Options' => gnfe_customfields_dropdow(), 'Description' => 'Escolha o campo personalizado de Inscrição Municipal', ]]; - $tax = ['tax' => [ 'FriendlyName' => 'Aplicar imposto automaticamente em todos os produtos ?', 'Type' => 'radio', 'Options' => 'Sim,Não', 'Default' => 'Sim', ]]; - $tax = ['InvoiceDetails' => [ + $invoiceDetails = ['InvoiceDetails' => [ 'FriendlyName' => 'O que deve aparecer nos detalhes da fatura ?', 'Type' => 'radio', 'Options' => 'Número da fatura,Nome dos serviços', @@ -256,7 +255,7 @@ function gnfe_verifyInstall() 'FriendlyName' => '', 'Description' => '© '.date('Y').' Suporte módulo', ]]; - $fields = array_merge($intro, $api_key, $company_id, $service_code, $rps_serial_number, $rps_number, $issue_note, $issue_note_after, $gnfe_email_nfe_config, $cancel_invoice_cancel_nfe, $debug, $insc_municipal, $tax, $footer); + $fields = array_merge($intro, $api_key, $company_id, $service_code, $rps_serial_number, $rps_number, $issue_note, $issue_note_after, $gnfe_email_nfe_config, $cancel_invoice_cancel_nfe, $debug, $insc_municipal, $tax, $invoiceDetails, $footer); $configarray = [ 'name' => 'NFE.io', 'description' => 'Módulo Nota Fiscal NFE.io para WHMCS', From 0a48f6241b6c3bfa2de0aa344cb74c00d19d3458 Mon Sep 17 00:00:00 2001 From: JoaoVictorLNacional Date: Thu, 7 Jan 2021 12:08:26 -0300 Subject: [PATCH 38/52] =?UTF-8?q?adicionado=20logs=20para=20monitorar=20pr?= =?UTF-8?q?oblema=20em=20produ=C3=A7=C3=A3o?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- modules/addons/gofasnfeio/hooks/aftercronjob.php | 8 +++++++- modules/addons/gofasnfeio/hooks/dailycronjob.php | 2 ++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/modules/addons/gofasnfeio/hooks/aftercronjob.php b/modules/addons/gofasnfeio/hooks/aftercronjob.php index 6abd414..5e5a514 100644 --- a/modules/addons/gofasnfeio/hooks/aftercronjob.php +++ b/modules/addons/gofasnfeio/hooks/aftercronjob.php @@ -6,8 +6,9 @@ use WHMCS\Database\Capsule; $params = gnfe_config(); - +logModuleCall('gofas_nfeio', 'enter aftercronjob', '','' , 'replaceVars'); foreach (Capsule::table('gofasnfeio')->orderBy('id', 'desc')->where('status', '=', 'Waiting')->take(1)->get(['id', 'invoice_id', 'services_amount']) as $waiting) { + // foreach (Capsule::table('gofasnfeio')->orderBy('id', 'desc')->where('status', '=', 'Waiting')->get(['id', 'invoice_id', 'services_amount']) as $waiting) { $data = getTodaysDate(false); $dataAtual = toMySQLDate($data); @@ -17,6 +18,11 @@ $getQuery = Capsule::table('tblinvoices')->where('id', '=', $waiting->invoice_id)->get(['id', 'userid', 'total']); } + 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'); + foreach ($getQuery as $invoices) { foreach ($invoice['items']['item'] as $value) { $line_items[] = $value['description']; diff --git a/modules/addons/gofasnfeio/hooks/dailycronjob.php b/modules/addons/gofasnfeio/hooks/dailycronjob.php index 45117c7..6edb0bf 100644 --- a/modules/addons/gofasnfeio/hooks/dailycronjob.php +++ b/modules/addons/gofasnfeio/hooks/dailycronjob.php @@ -9,6 +9,8 @@ $data = getTodaysDate(false); $dataAtual = toMySQLDate($data); +logModuleCall('gofas_nfeio', 'daily cron t', $params['issue_note_after'],'' , 'replaceVars'); +logModuleCall('gofas_nfeio', 'daily cron issue_note', $params['issue_note'],'' , 'replaceVars'); if ('Manualmente' !== $params['issue_note'] && $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) { From 6d1dc8be60633ca34d58bbec675d2359f8e1c906 Mon Sep 17 00:00:00 2001 From: JoaoVictorLNacional Date: Thu, 7 Jan 2021 13:44:15 -0300 Subject: [PATCH 39/52] =?UTF-8?q?removido=20a=20pagina=C3=A7=C3=A3o=20de?= =?UTF-8?q?=20tela=20de=20codigos=20de=20servi=C3=A7o?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../addons/gofasnfeio/hooks/aftercronjob.php | 12 +-- .../addons/gofasnfeio/hooks/dailycronjob.php | 6 +- modules/addons/gofasnfeio/outputproduct.php | 86 +------------------ 3 files changed, 14 insertions(+), 90 deletions(-) diff --git a/modules/addons/gofasnfeio/hooks/aftercronjob.php b/modules/addons/gofasnfeio/hooks/aftercronjob.php index 5e5a514..ce6c4c8 100644 --- a/modules/addons/gofasnfeio/hooks/aftercronjob.php +++ b/modules/addons/gofasnfeio/hooks/aftercronjob.php @@ -6,7 +6,6 @@ use WHMCS\Database\Capsule; $params = gnfe_config(); -logModuleCall('gofas_nfeio', 'enter aftercronjob', '','' , 'replaceVars'); foreach (Capsule::table('gofasnfeio')->orderBy('id', 'desc')->where('status', '=', 'Waiting')->take(1)->get(['id', 'invoice_id', 'services_amount']) as $waiting) { // foreach (Capsule::table('gofasnfeio')->orderBy('id', 'desc')->where('status', '=', 'Waiting')->get(['id', 'invoice_id', 'services_amount']) as $waiting) { $data = getTodaysDate(false); @@ -17,11 +16,12 @@ } else { $getQuery = Capsule::table('tblinvoices')->where('id', '=', $waiting->invoice_id)->get(['id', 'userid', 'total']); } - - 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'); + 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'); + } foreach ($getQuery as $invoices) { foreach ($invoice['items']['item'] as $value) { diff --git a/modules/addons/gofasnfeio/hooks/dailycronjob.php b/modules/addons/gofasnfeio/hooks/dailycronjob.php index 6edb0bf..5191f36 100644 --- a/modules/addons/gofasnfeio/hooks/dailycronjob.php +++ b/modules/addons/gofasnfeio/hooks/dailycronjob.php @@ -9,8 +9,10 @@ $data = getTodaysDate(false); $dataAtual = toMySQLDate($data); -logModuleCall('gofas_nfeio', 'daily cron t', $params['issue_note_after'],'' , 'replaceVars'); -logModuleCall('gofas_nfeio', 'daily cron issue_note', $params['issue_note'],'' , 'replaceVars'); +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 ('Manualmente' !== $params['issue_note'] && $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) { diff --git a/modules/addons/gofasnfeio/outputproduct.php b/modules/addons/gofasnfeio/outputproduct.php index 48d66df..30933cd 100644 --- a/modules/addons/gofasnfeio/outputproduct.php +++ b/modules/addons/gofasnfeio/outputproduct.php @@ -40,89 +40,17 @@ foreach (Capsule::table('tblproducts')->orderBy('id', 'desc')->get(['id']) as $nfes_) { $nfes[] = $nfes_->id; } - if ($_REQUEST['page']) { - $nfes_page = (int) $_REQUEST['page']; - } else { - $nfes_page = 1; - } - if ($_REQUEST['take']) { - $take = (int) $_REQUEST['take']; - } else { - $take = 10; - } - - $nfs_keys = array_keys($nfes); - $nfes_total = count($nfes); - if ($take > $nfes_total) { - $take = $nfes_total; - } - - $nfes_pages = ceil($nfes_total / $take); - $nfes_from_ = ($nfes_page * $take) - $take; - $nfes_from = $nfs_keys[$nfes_from_ + 1]; - $nfes_to_ = ($nfes_from + $take) - 2; - $nfes_to = $nfs_keys[$nfes_to_ + 1]; - $nfess = array_slice($nfes, $nfes_from_, $nfes_to); - - if ((int) $nfes_page === (int) $nfes_pages) { - $nfes_to = $nfes_total; - $nfess = array_slice($nfes, $nfes_from_, $nfes_to_); - } - if ((int) $take >= (int) $nfes_total) { - $nfes_from = 1; - $nfess = array_slice($nfes, $nfes_from_, $nfes_to); - } - // Pagination - $i = 1; - while ($i <= $nfes_pages) { - $page_num = $i++; - - if ((int) $page_num !== (int) $nfes_page) { - $tag = 'a '; - $a_style = ''; - $li_class = 'class="enabled"'; - $href = $gnfewhmcsadminurl.'addonmodules.php?module=gofasnfeio&page='.$page_num; - } elseif ((int) $page_num === (int) $nfes_page) { - $tag = 'span '; - $a_style = 'style="background: #337ab7; color: #fff"'; - $li_class = 'class="disabled"'; - $href = ''; - } - $pagination_ .= '
  • <'.$tag.' '.$a_style.' href="'.$href.'" >'.$page_num.'
  • '; - } - if (1 === (int) $nfes_page) { - $preview_class = ' class="previous disabled" '; - $preview_href = ''; - $preview_tag = 'span '; - } else { - $preview_class = ' class="previous" '; - $preview_href = ' href="'.$gnfewhmcsadminurl.'addonmodules.php?module=gofasnfeio&page='.($nfes_page - 1).'" '; - $preview_tag = 'a '; - } - if ((int) $nfes_page === (int) $nfes_pages) { - $next_class = ' class="next disabled" '; - $next_href = ''; - $next_tag = 'span '; - } else { - $next_class = ' class="next" '; - $next_href = ' href="'.$gnfewhmcsadminurl.'addonmodules.php?module=gofasnfeio&page='.($nfes_page + 1).'" '; - $next_tag = 'a '; - } - $pagination .= '
  • <'.$preview_tag.' '.$preview_href.'>« Página anterior
  • '; - $pagination .= $pagination_; - $pagination .= '
  • <'.$next_tag.' '.$next_href.'>Próxima página »
  • '; - + foreach (Capsule::table('tblproducts')-> leftJoin('tblproductcode', 'tblproducts.id', '=', 'tblproductcode.product_id')-> orderBy('tblproducts.id', 'desc')-> - whereBetween('tblproducts.id', [end($nfess), reset($nfess)])-> - take($take)-> get(['tblproducts.id', 'tblproducts.name', 'tblproducts.created_at', 'tblproductcode.update_at', 'tblproductcode.code_service']) as $product) { $created_at = $product->created_at ? date('d/m/Y', strtotime($product->created_at)) : ''; $update_at = $product->update_at ? date('d/m/Y', strtotime($product->update_at)) : ''; + $html_table .= '#'.$product->id.' - '.$created_at.' - '.$update_at.' + '.$update_at.' '.$product->name.'
    @@ -152,12 +80,6 @@
    - -
    -
      - '.$pagination.' -
    -
    '; if ($_REQUEST['gnfe_message']) { echo urldecode(base64_decode($_REQUEST['gnfe_message'])); From fa88ff515a5850de3528c6cd7f2a48d340022fb8 Mon Sep 17 00:00:00 2001 From: JoaoVictorLNacional Date: Thu, 7 Jan 2021 13:46:01 -0300 Subject: [PATCH 40/52] =?UTF-8?q?corigido=20bug=20css=20da=20pagina=20codi?= =?UTF-8?q?go=20de=20servi=C3=A7o?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- modules/addons/gofasnfeio/outputproduct.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/addons/gofasnfeio/outputproduct.php b/modules/addons/gofasnfeio/outputproduct.php index 30933cd..4880af1 100644 --- a/modules/addons/gofasnfeio/outputproduct.php +++ b/modules/addons/gofasnfeio/outputproduct.php @@ -49,8 +49,8 @@ $update_at = $product->update_at ? date('d/m/Y', strtotime($product->update_at)) : ''; $html_table .= '#'.$product->id.' - '.$update_at.' + '.$created_at.' + '.$update_at.' '.$product->name.' From 04153d750458c471828a76141472d802ba0730b9 Mon Sep 17 00:00:00 2001 From: JoaoVictorLNacional Date: Fri, 8 Jan 2021 17:23:06 -0300 Subject: [PATCH 41/52] alterado nome da columna do banco e add log em aftercronjob --- modules/addons/gofasnfeio/functions.php | 9 ++++++--- modules/addons/gofasnfeio/hooks/aftercronjob.php | 6 ++++-- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/modules/addons/gofasnfeio/functions.php b/modules/addons/gofasnfeio/functions.php index 9ea36e4..4ba5f7a 100644 --- a/modules/addons/gofasnfeio/functions.php +++ b/modules/addons/gofasnfeio/functions.php @@ -828,7 +828,7 @@ function get_product_invoice($invoice_id) if (!function_exists('set_code_service_camp_gofasnfeio')) { function set_code_service_camp_gofasnfeio() { - if (!Capsule::schema()->hasColumn('gofasnfeio', 'service_code') && !Capsule::schema()->hasColumn('gofasnfeio', 'monthly')) { + if (!Capsule::schema()->hasColumn('gofasnfeio', 'service_code')) { $pdo = Capsule::connection()->getPdo(); $pdo->beginTransaction(); @@ -839,10 +839,13 @@ function set_code_service_camp_gofasnfeio() } catch (\Exception $e) { $pdo->rollBack(); } - $pdo->beginTransaction(); + } + if(!Capsule::schema()->hasColumn('gofasnfeio', 'services_amount')){ + $pdo = Capsule::connection()->getPdo(); + $pdo->beginTransaction(); try { - $statement = $pdo->prepare('ALTER TABLE gofasnfeio ADD monthly DECIMAL(16,2)'); + $statement = $pdo->prepare('ALTER TABLE gofasnfeio ADD services_amount DECIMAL(16,2)'); $statement->execute(); $pdo->commit(); } catch (\Exception $e) { diff --git a/modules/addons/gofasnfeio/hooks/aftercronjob.php b/modules/addons/gofasnfeio/hooks/aftercronjob.php index ce6c4c8..235cf8f 100644 --- a/modules/addons/gofasnfeio/hooks/aftercronjob.php +++ b/modules/addons/gofasnfeio/hooks/aftercronjob.php @@ -4,9 +4,11 @@ exit(); } use WHMCS\Database\Capsule; - +if ($params['debug']) { + logModuleCall('gofas_nfeio', 'check', 'check', '', 'replaceVars'); +} $params = gnfe_config(); - foreach (Capsule::table('gofasnfeio')->orderBy('id', 'desc')->where('status', '=', 'Waiting')->take(1)->get(['id', 'invoice_id', 'services_amount']) as $waiting) { + 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')->get(['id', 'invoice_id', 'services_amount']) as $waiting) { $data = getTodaysDate(false); $dataAtual = toMySQLDate($data); From 485c261b3a6edb608647ec47caf74ad893ab5c50 Mon Sep 17 00:00:00 2001 From: JoaoVictorLNacional Date: Mon, 11 Jan 2021 15:11:53 -0300 Subject: [PATCH 42/52] corigido bug do hook e as notas emitidas com -1 --- modules/addons/gofasnfeio/functions.php | 53 ++++++++++++++++--------- 1 file changed, 34 insertions(+), 19 deletions(-) diff --git a/modules/addons/gofasnfeio/functions.php b/modules/addons/gofasnfeio/functions.php index 9ea36e4..268aab4 100644 --- a/modules/addons/gofasnfeio/functions.php +++ b/modules/addons/gofasnfeio/functions.php @@ -185,6 +185,9 @@ function gnfe_queue_nfe($invoice_id, $create_all = false) if (!$itens) { foreach (Capsule::table('tblinvoiceitems')->where('invoiceid', '=', $invoice_id)->get(['userid', 'amount']) as $item_not_salle) { + if($item_not_salle->amount == -1){ + return ''; + } $data = [ 'invoice_id' => $invoice_id, 'user_id' => $item_not_salle->userid, @@ -532,6 +535,9 @@ function gnfe_whmcs_admin_url() if (!function_exists('gnfe_save_nfe')) { function gnfe_save_nfe($nfe, $user_id, $invoice_id, $pdf, $created_at, $updated_at) { + if($nfe->servicesAmount == -1){ + return; + } $data = [ 'invoice_id' => $invoice_id, 'user_id' => $user_id, @@ -636,22 +642,29 @@ function gnfe_check_webhook($id) return json_decode(json_encode(json_decode($response)), true); } } -if (!function_exists('gnfe_create_webhook')) { - function gnfe_create_webhook($url) - { +if( !function_exists('gnfe_create_webhook') ) { + function gnfe_create_webhook($url) { + try { + $curl = curl_init(); - curl_setopt($curl, CURLOPT_URL, 'https://api.nfe.io/v1/hooks'); - curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: text/json', 'Accept: application/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_RETURNTRANSFER, 1); - $response = curl_exec($curl); - curl_close($curl); - + curl_setopt($curl, CURLOPT_URL, "https://api.nfe.io/v1/hooks"); + curl_setopt($curl, CURLOPT_HTTPHEADER, array('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(array('url'=> $url, 'contentType'=> 'application/json', 'secret'=> (string)time(), 'events'=>array('issue', 'cancel'), 'status'=>'Active', ))); + curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); + $response = curl_exec ($curl); + curl_close ($curl); + + } catch (Exception $th) { + logModuleCall('gofas_nfeio', 'Exception', $th->getMessage(), '', '', 'replaceVars'); + + } return json_decode(json_encode(json_decode($response)), true); + } } + if (!function_exists('gnfe_delete_webhook')) { function gnfe_delete_webhook($id) { @@ -828,7 +841,7 @@ function get_product_invoice($invoice_id) if (!function_exists('set_code_service_camp_gofasnfeio')) { function set_code_service_camp_gofasnfeio() { - if (!Capsule::schema()->hasColumn('gofasnfeio', 'service_code') && !Capsule::schema()->hasColumn('gofasnfeio', 'monthly')) { + if (!Capsule::schema()->hasColumn('gofasnfeio', 'service_code')) { $pdo = Capsule::connection()->getPdo(); $pdo->beginTransaction(); @@ -841,12 +854,14 @@ function set_code_service_camp_gofasnfeio() } $pdo->beginTransaction(); - try { - $statement = $pdo->prepare('ALTER TABLE gofasnfeio ADD monthly DECIMAL(16,2)'); - $statement->execute(); - $pdo->commit(); - } catch (\Exception $e) { - $pdo->rollBack(); + if(!Capsule::schema()->hasColumn('gofasnfeio', 'monthly')){ + try { + $statement = $pdo->prepare('ALTER TABLE gofasnfeio ADD monthly DECIMAL(16,2)'); + $statement->execute(); + $pdo->commit(); + } catch (\Exception $e) { + $pdo->rollBack(); + } } } } From bb9cb600389c8cf6e7829002cda2463ff89a0cca Mon Sep 17 00:00:00 2001 From: JoaoVictorLNacional Date: Wed, 13 Jan 2021 11:18:42 -0300 Subject: [PATCH 43/52] add logs in conection hooks --- modules/addons/gofasnfeio/functions.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/modules/addons/gofasnfeio/functions.php b/modules/addons/gofasnfeio/functions.php index 268aab4..7a37acd 100644 --- a/modules/addons/gofasnfeio/functions.php +++ b/modules/addons/gofasnfeio/functions.php @@ -637,6 +637,7 @@ 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); @@ -654,6 +655,7 @@ function gnfe_create_webhook($url) { curl_setopt($curl, CURLOPT_POSTFIELDS,json_encode(array('url'=> $url, 'contentType'=> 'application/json', 'secret'=> (string)time(), 'events'=>array('issue', 'cancel'), '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) { From 1011f8a04d25c01eb97e5353cd853e5ed2f43fd5 Mon Sep 17 00:00:00 2001 From: JoaoVictorLNacional Date: Wed, 13 Jan 2021 16:51:32 -0300 Subject: [PATCH 44/52] merge --- modules/addons/gofasnfeio/functions.php | 96 ++++++++++--------- .../addons/gofasnfeio/hooks/aftercronjob.php | 3 +- 2 files changed, 55 insertions(+), 44 deletions(-) diff --git a/modules/addons/gofasnfeio/functions.php b/modules/addons/gofasnfeio/functions.php index 078f2b7..9221d48 100644 --- a/modules/addons/gofasnfeio/functions.php +++ b/modules/addons/gofasnfeio/functions.php @@ -182,6 +182,12 @@ function gnfe_queue_nfe($invoice_id, $create_all = false) { $invoice = localAPI('GetInvoice', ['invoiceid' => $invoice_id], false); $itens = get_product_invoice($invoice_id); + + + $initial_date = Capsule::table('tbladdonmodules')->where('setting', '=', 'initial_date')->where('module', '=', 'gofasnfeio')->get(['value'])[0]->value; + if( strtotime($initial_date) > strtotime($invoice['date'])){ + return ''; + } if (!$itens) { foreach (Capsule::table('tblinvoiceitems')->where('invoiceid', '=', $invoice_id)->get(['userid', 'amount']) as $item_not_salle) { @@ -221,49 +227,50 @@ function gnfe_queue_nfe($invoice_id, $create_all = false) return 'success'; } foreach ($itens as $item) { - $data = [ - 'invoice_id' => $invoice_id, - 'user_id' => $invoice['userid'], - 'nfe_id' => 'waiting', - 'status' => 'Waiting', - 'services_amount' => $item['monthly'], - 'environment' => 'waiting', - 'flow_status' => 'waiting', - 'pdf' => 'waiting', - 'created_at' => date('Y-m-d H:i:s'), - 'updated_at' => 'waiting', - 'rpsSerialNumber' => 'waiting', - 'service_code' => $item['value'], - ]; + if($item['monthly'] < 0){ + $data = [ + 'invoice_id' => $invoice_id, + 'user_id' => $invoice['userid'], + 'nfe_id' => 'waiting', + 'status' => 'Waiting', + 'services_amount' => $item['monthly'], + 'environment' => 'waiting', + 'flow_status' => 'waiting', + 'pdf' => 'waiting', + 'created_at' => date('Y-m-d H:i:s'), + 'updated_at' => 'waiting', + 'rpsSerialNumber' => 'waiting', + 'service_code' => $item['value'], + ]; - $nfe_for_invoice = gnfe_get_local_nfe($invoice_id, ['status']); - if (!$nfe_for_invoice['status'] || $create_all) { - $create_all = true; + $nfe_for_invoice = gnfe_get_local_nfe($invoice_id, ['status']); + if (!$nfe_for_invoice['status'] || $create_all) { + $create_all = true; - try { - $service_code_row = Capsule::table('gofasnfeio')->where('service_code', '=', $item['value'])->where('invoice_id', '=', $invoice_id)->get(['id', 'services_amount']); + try { + $service_code_row = Capsule::table('gofasnfeio')->where('service_code', '=', $item['value'])->where('invoice_id', '=', $invoice_id)->get(['id', 'services_amount']); - if (1 == count($service_code_row)) { - $mountDB = floatval($service_code_row[0]->services_amount); - $mount_item = floatval($item['monthly']); - $mount = $mountDB + $mount_item; + if (1 == count($service_code_row)) { + $mountDB = floatval($service_code_row[0]->services_amount); + $mount_item = floatval($item['monthly']); + $mount = $mountDB + $mount_item; - $update_nfe = Capsule::table('gofasnfeio')->where('id', '=', $service_code_row[0]->id)->update(['services_amount' => $mount]); - } else { - $save_nfe = Capsule::table('gofasnfeio')->insert($data); + $update_nfe = Capsule::table('gofasnfeio')->where('id', '=', $service_code_row[0]->id)->update(['services_amount' => $mount]); + } else { + $save_nfe = Capsule::table('gofasnfeio')->insert($data); + } + } catch (\Exception $e) { + return $e->getMessage(); + } + } elseif ((string) $nfe_for_invoice['status'] === (string) 'Cancelled' or (string) $nfe_for_invoice['status'] === (string) 'Error') { + try { + $update_nfe = Capsule::table('gofasnfeio')->where('invoice_id', '=', $invoice_id)->update($data); + } catch (\Exception $e) { + return $e->getMessage(); } - } catch (\Exception $e) { - return $e->getMessage(); - } - } elseif ((string) $nfe_for_invoice['status'] === (string) 'Cancelled' or (string) $nfe_for_invoice['status'] === (string) 'Error') { - try { - $update_nfe = Capsule::table('gofasnfeio')->where('invoice_id', '=', $invoice_id)->update($data); - } catch (\Exception $e) { - return $e->getMessage(); } } } - return 'success'; } } @@ -857,14 +864,17 @@ function set_code_service_camp_gofasnfeio() } 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(!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(); + } } } } diff --git a/modules/addons/gofasnfeio/hooks/aftercronjob.php b/modules/addons/gofasnfeio/hooks/aftercronjob.php index 235cf8f..64239d5 100644 --- a/modules/addons/gofasnfeio/hooks/aftercronjob.php +++ b/modules/addons/gofasnfeio/hooks/aftercronjob.php @@ -8,8 +8,9 @@ logModuleCall('gofas_nfeio', 'check', 'check', '', 'replaceVars'); } $params = gnfe_config(); + 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')->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) { $data = getTodaysDate(false); $dataAtual = toMySQLDate($data); From 1e8b0f51ec78b2614b133a049a80a984910db6aa Mon Sep 17 00:00:00 2001 From: JoaoVictorLNacional Date: Thu, 14 Jan 2021 10:30:28 -0300 Subject: [PATCH 45/52] =?UTF-8?q?consertado=20verifica=C3=A7=C3=A3o=20de?= =?UTF-8?q?=20valores=20salvos=20com=20-1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- modules/addons/gofasnfeio/functions.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/addons/gofasnfeio/functions.php b/modules/addons/gofasnfeio/functions.php index 9221d48..ec455be 100644 --- a/modules/addons/gofasnfeio/functions.php +++ b/modules/addons/gofasnfeio/functions.php @@ -227,7 +227,7 @@ function gnfe_queue_nfe($invoice_id, $create_all = false) return 'success'; } foreach ($itens as $item) { - if($item['monthly'] < 0){ + if($item['monthly'] > 0){ $data = [ 'invoice_id' => $invoice_id, 'user_id' => $invoice['userid'], From 9990b0957a474bd8463fe0cd0f381d8424ac3d22 Mon Sep 17 00:00:00 2001 From: JoaoVictorLNacional Date: Thu, 14 Jan 2021 15:35:56 -0300 Subject: [PATCH 46/52] =?UTF-8?q?modificado=20a=20fun=C3=A7=C3=A3o=20get?= =?UTF-8?q?=5Fproduct=5Finvoice?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- modules/addons/gofasnfeio/functions.php | 195 +++++++++--------------- 1 file changed, 73 insertions(+), 122 deletions(-) diff --git a/modules/addons/gofasnfeio/functions.php b/modules/addons/gofasnfeio/functions.php index ec455be..8ab6940 100644 --- a/modules/addons/gofasnfeio/functions.php +++ b/modules/addons/gofasnfeio/functions.php @@ -182,39 +182,37 @@ function gnfe_queue_nfe($invoice_id, $create_all = false) { $invoice = localAPI('GetInvoice', ['invoiceid' => $invoice_id], false); $itens = get_product_invoice($invoice_id); - + $initial_date = Capsule::table('tbladdonmodules')->where('setting', '=', 'initial_date')->where('module', '=', 'gofasnfeio')->get(['value'])[0]->value; - if( strtotime($initial_date) > strtotime($invoice['date'])){ - return ''; - } - - if (!$itens) { - foreach (Capsule::table('tblinvoiceitems')->where('invoiceid', '=', $invoice_id)->get(['userid', 'amount']) as $item_not_salle) { - if($item_not_salle->amount == -1){ - return ''; - } - $data = [ + foreach ($itens as $item) { + $data = [ 'invoice_id' => $invoice_id, - 'user_id' => $item_not_salle->userid, + 'user_id' => $invoice['userid'], 'nfe_id' => 'waiting', 'status' => 'Waiting', - 'services_amount' => $item_not_salle->amount, + 'services_amount' => $item['amount'], 'environment' => 'waiting', 'flow_status' => 'waiting', 'pdf' => 'waiting', 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => 'waiting', 'rpsSerialNumber' => 'waiting', + 'service_code' => $item['code_service'], ]; + $nfe_for_invoice = gnfe_get_local_nfe($invoice_id, ['status']); + if (!$nfe_for_invoice['status'] || $create_all) { + $create_all = true; + try { - $service_code_row = Capsule::table('gofasnfeio')->whereNull('service_code')->where('invoice_id', '=', $invoice_id)->get(['id', 'services_amount']); + $service_code_row = Capsule::table('gofasnfeio')->where('service_code', '=', $item['code_service'])->where('invoice_id', '=', $invoice_id)->get(['id', 'services_amount']); if (1 == count($service_code_row)) { $mountDB = floatval($service_code_row[0]->services_amount); - $mount_item = floatval($item_not_salle->amount); + $mount_item = floatval($item['amount']); $mount = $mountDB + $mount_item; + $update_nfe = Capsule::table('gofasnfeio')->where('id', '=', $service_code_row[0]->id)->update(['services_amount' => $mount]); } else { $save_nfe = Capsule::table('gofasnfeio')->insert($data); @@ -222,52 +220,11 @@ function gnfe_queue_nfe($invoice_id, $create_all = false) } catch (\Exception $e) { return $e->getMessage(); } - } - - return 'success'; - } - foreach ($itens as $item) { - if($item['monthly'] > 0){ - $data = [ - 'invoice_id' => $invoice_id, - 'user_id' => $invoice['userid'], - 'nfe_id' => 'waiting', - 'status' => 'Waiting', - 'services_amount' => $item['monthly'], - 'environment' => 'waiting', - 'flow_status' => 'waiting', - 'pdf' => 'waiting', - 'created_at' => date('Y-m-d H:i:s'), - 'updated_at' => 'waiting', - 'rpsSerialNumber' => 'waiting', - 'service_code' => $item['value'], - ]; - - $nfe_for_invoice = gnfe_get_local_nfe($invoice_id, ['status']); - if (!$nfe_for_invoice['status'] || $create_all) { - $create_all = true; - - try { - $service_code_row = Capsule::table('gofasnfeio')->where('service_code', '=', $item['value'])->where('invoice_id', '=', $invoice_id)->get(['id', 'services_amount']); - - if (1 == count($service_code_row)) { - $mountDB = floatval($service_code_row[0]->services_amount); - $mount_item = floatval($item['monthly']); - $mount = $mountDB + $mount_item; - - $update_nfe = Capsule::table('gofasnfeio')->where('id', '=', $service_code_row[0]->id)->update(['services_amount' => $mount]); - } else { - $save_nfe = Capsule::table('gofasnfeio')->insert($data); - } - } catch (\Exception $e) { - return $e->getMessage(); - } - } elseif ((string) $nfe_for_invoice['status'] === (string) 'Cancelled' or (string) $nfe_for_invoice['status'] === (string) 'Error') { - try { - $update_nfe = Capsule::table('gofasnfeio')->where('invoice_id', '=', $invoice_id)->update($data); - } catch (\Exception $e) { - return $e->getMessage(); - } + } elseif ((string) $nfe_for_invoice['status'] === (string) 'Cancelled' or (string) $nfe_for_invoice['status'] === (string) 'Error') { + try { + $update_nfe = Capsule::table('gofasnfeio')->where('invoice_id', '=', $invoice_id)->update($data); + } catch (\Exception $e) { + return $e->getMessage(); } } } @@ -287,14 +244,14 @@ function gnfe_queue_nfe_edit($invoice_id, $gofasnfeio_id) 'user_id' => $invoice['userid'], 'nfe_id' => 'waiting', 'status' => 'Waiting', - 'services_amount' => $item['monthly'], + 'services_amount' => $item['amount'], 'environment' => 'waiting', 'flow_status' => 'waiting', 'pdf' => 'waiting', 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => 'waiting', 'rpsSerialNumber' => 'waiting', - 'service_code' => $item['value'], + 'service_code' => $item['code_service'], ]; $nfe_for_invoice = gnfe_get_local_nfe($invoice_id, ['status']); @@ -542,7 +499,7 @@ function gnfe_whmcs_admin_url() if (!function_exists('gnfe_save_nfe')) { function gnfe_save_nfe($nfe, $user_id, $invoice_id, $pdf, $created_at, $updated_at) { - if($nfe->servicesAmount == -1){ + if ($nfe->servicesAmount == -1) { return; } $data = [ @@ -650,27 +607,24 @@ function gnfe_check_webhook($id) return json_decode(json_encode(json_decode($response)), true); } } -if( !function_exists('gnfe_create_webhook') ) { - function gnfe_create_webhook($url) { +if (!function_exists('gnfe_create_webhook')) { + function gnfe_create_webhook($url) + { try { - - $curl = curl_init(); - curl_setopt($curl, CURLOPT_URL, "https://api.nfe.io/v1/hooks"); - curl_setopt($curl, CURLOPT_HTTPHEADER, array('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(array('url'=> $url, 'contentType'=> 'application/json', 'secret'=> (string)time(), 'events'=>array('issue', 'cancel'), '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'); - - } + $curl = curl_init(); + curl_setopt($curl, CURLOPT_URL, "https://api.nfe.io/v1/hooks"); + curl_setopt($curl, CURLOPT_HTTPHEADER, array('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(array('url'=> $url, 'contentType'=> 'application/json', 'secret'=> (string)time(), 'events'=>array('issue', 'cancel'), '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); - } } @@ -798,55 +752,54 @@ function gnfe_customer_service_code($item_id) function get_product_invoice($invoice_id) { - $query = "SELECT DISTINCT tblhosting.packageid,tblpricing.monthly from tblhosting - INNER JOIN tblinvoiceitems ON tblinvoiceitems.relid = tblhosting.id - JOIN tblpricing ON tblpricing.relid = tblhosting.packageid - LEFT JOIN tblproducts ON tblproducts.id = tblhosting.packageid - WHERE tblpricing.type = 'product' AND tblinvoiceitems.invoiceid = :id"; - - $pdo = Capsule::connection()->getPdo(); - $pdo->beginTransaction(); + $query ="SELECT tblinvoiceitems.invoiceid ,tblinvoiceitems.type ,tblinvoiceitems.relid,tblinvoiceitems.description,tblinvoiceitems.amount FROM tblinvoiceitems + WHERE tblinvoiceitems.invoiceid = :INVOICEID"; + $tax_check = gnfe_config('tax'); - $row = null; - $list = []; - if ('Não' == $tax_check) { $query .= ' AND tblproducts.tax = 1'; } else { Capsule::table('tblproducts')->update(['tax' => 1]); } - // Capsule::table('tblproducts')->update(['tax' => 1]); - try { - $statement = $pdo->prepare($query); - $statement->execute([':id' => $invoice_id]); - $row = $statement->fetchAll(); - $pdo->commit(); - } catch (\Exception $th) { - $pdo->rollBack(); - } + $pdo = Capsule::connection()->getPdo(); + $pdo->beginTransaction(); + $statement = $pdo->prepare($query); + $statement->execute([':INVOICEID' => $invoice_id]); + $row = $statement->fetchAll(); + $pdo->commit(); + foreach ($row as $item) { - $pdo->beginTransaction(); - - try { - $list2 = []; - $stmt = $pdo->prepare('SELECT * FROM tblproductcode WHERE product_id=:PROD'); - $stmt->execute([':PROD' => $item[0]]); - $row = $stmt->fetchAll(); + $hosting_id = $item["relid"]; + + if ($item["type"] == 'Hosting') { + $query = "SELECT tblhosting.billingcycle ,tblhosting.id,tblproductcode.code_service ,tblhosting.packageid,tblhosting.id FROM tblhosting + LEFT JOIN tblproductcode ON tblhosting.packageid = tblproductcode.product_id + LEFT JOIN tblproducts ON tblproducts.id = tblhosting.packageid + WHERE tblhosting.id = :HOSTING"; + $pdo->beginTransaction(); + $statement = $pdo->prepare($query); + $statement->execute([':HOSTING' => $hosting_id]); + $product = $statement->fetchAll(); $pdo->commit(); - $list2['item'] = $item['packageid']; - $list2['value'] = $row[0]['code_service']; - $list2['monthly'] = $item['monthly']; - $list[] = $list2; - } catch (\Exception $th) { - $pdo->rollBack(); - logModuleCall('gofas_nfeio', 'get_product_invoice erro', $th, '', '', 'replaceVars'); + + $product_array['id_product'] = $product[0]["packageid"]; + $product_array['code_service'] = $product[0]["code_service"]; + $product_array['amount'] = $item["amount"]; + $products_details[] = $product_array; + } else { + $product_array['id_product'] = $item["packageid"]; + $product_array['code_service'] = null; + $product_array['amount'] = $item["amount"]; + $products_details[] = $product_array; } } + logModuleCall('gofas_nfeio', 'products_details', $products_details, '', 'replaceVars'); - return $list; + return $products_details; } + if (!function_exists('set_code_service_camp_gofasnfeio')) { function set_code_service_camp_gofasnfeio() { @@ -862,10 +815,8 @@ function set_code_service_camp_gofasnfeio() $pdo->rollBack(); } } - if(!Capsule::schema()->hasColumn('gofasnfeio', 'services_amount')){ - - if(!Capsule::schema()->hasColumn('gofasnfeio', 'services_amount')){ - + if (!Capsule::schema()->hasColumn('gofasnfeio', 'services_amount')) { + if (!Capsule::schema()->hasColumn('gofasnfeio', 'services_amount')) { $pdo = Capsule::connection()->getPdo(); $pdo->beginTransaction(); try { From d3dc8091f4354c61748fb342a276929650cc2f54 Mon Sep 17 00:00:00 2001 From: JoaoVictorLNacional Date: Thu, 14 Jan 2021 15:50:24 -0300 Subject: [PATCH 47/52] =?UTF-8?q?adicionadoa=20op=C3=A7=C3=A3o=20de=20apli?= =?UTF-8?q?ca=C3=A7=C3=A3o=20de=20taxa=20em=20todos=20os=20produtos=20ou?= =?UTF-8?q?=20n=C3=A3o=20na=20fun=C3=A7=C3=A3o=20get=5Fproduct=5Finvoice?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- modules/addons/gofasnfeio/functions.php | 34 +++++++++++++------------ 1 file changed, 18 insertions(+), 16 deletions(-) diff --git a/modules/addons/gofasnfeio/functions.php b/modules/addons/gofasnfeio/functions.php index 8ab6940..e71106f 100644 --- a/modules/addons/gofasnfeio/functions.php +++ b/modules/addons/gofasnfeio/functions.php @@ -183,7 +183,6 @@ function gnfe_queue_nfe($invoice_id, $create_all = false) $invoice = localAPI('GetInvoice', ['invoiceid' => $invoice_id], false); $itens = get_product_invoice($invoice_id); - $initial_date = Capsule::table('tbladdonmodules')->where('setting', '=', 'initial_date')->where('module', '=', 'gofasnfeio')->get(['value'])[0]->value; foreach ($itens as $item) { $data = [ @@ -752,41 +751,44 @@ function gnfe_customer_service_code($item_id) function get_product_invoice($invoice_id) { - $query ="SELECT tblinvoiceitems.invoiceid ,tblinvoiceitems.type ,tblinvoiceitems.relid,tblinvoiceitems.description,tblinvoiceitems.amount FROM tblinvoiceitems - WHERE tblinvoiceitems.invoiceid = :INVOICEID"; + $query ="SELECT tblinvoiceitems.invoiceid ,tblinvoiceitems.type ,tblinvoiceitems.relid, + tblinvoiceitems.description,tblinvoiceitems.amount FROM tblinvoiceitems WHERE tblinvoiceitems.invoiceid = :INVOICEID"; - $tax_check = gnfe_config('tax'); - if ('Não' == $tax_check) { - $query .= ' AND tblproducts.tax = 1'; - } else { - Capsule::table('tblproducts')->update(['tax' => 1]); - } - $pdo = Capsule::connection()->getPdo(); $pdo->beginTransaction(); $statement = $pdo->prepare($query); $statement->execute([':INVOICEID' => $invoice_id]); $row = $statement->fetchAll(); $pdo->commit(); - + + $tax_check = gnfe_config('tax'); foreach ($row as $item) { $hosting_id = $item["relid"]; if ($item["type"] == 'Hosting') { $query = "SELECT tblhosting.billingcycle ,tblhosting.id,tblproductcode.code_service ,tblhosting.packageid,tblhosting.id FROM tblhosting - LEFT JOIN tblproductcode ON tblhosting.packageid = tblproductcode.product_id LEFT JOIN tblproducts ON tblproducts.id = tblhosting.packageid + LEFT JOIN tblproductcode ON tblhosting.packageid = tblproductcode.product_id WHERE tblhosting.id = :HOSTING"; + + if ('Não' == $tax_check) { + $query .= ' AND tblproducts.tax = 1'; + } else { + Capsule::table('tblproducts')->update(['tax' => 1]); + } + $pdo->beginTransaction(); $statement = $pdo->prepare($query); $statement->execute([':HOSTING' => $hosting_id]); $product = $statement->fetchAll(); $pdo->commit(); - $product_array['id_product'] = $product[0]["packageid"]; - $product_array['code_service'] = $product[0]["code_service"]; - $product_array['amount'] = $item["amount"]; - $products_details[] = $product_array; + if ($product) { + $product_array['id_product'] = $product[0]["packageid"]; + $product_array['code_service'] = $product[0]["code_service"]; + $product_array['amount'] = $item["amount"]; + $products_details[] = $product_array; + } } else { $product_array['id_product'] = $item["packageid"]; $product_array['code_service'] = null; From 101e2f18eace0e73396d077f98dc5bbc25e00ebd Mon Sep 17 00:00:00 2001 From: JoaoVictorLNacional Date: Fri, 15 Jan 2021 11:49:41 -0300 Subject: [PATCH 48/52] add log no envio para a api e checagem do callback --- modules/addons/gofasnfeio/callback.php | 7 ++++++- modules/addons/gofasnfeio/functions.php | 6 +++++- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/modules/addons/gofasnfeio/callback.php b/modules/addons/gofasnfeio/callback.php index 11ee787..c9308ed 100644 --- a/modules/addons/gofasnfeio/callback.php +++ b/modules/addons/gofasnfeio/callback.php @@ -5,9 +5,15 @@ $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'; + 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; @@ -17,7 +23,6 @@ $nfe_for_invoice[$key] = json_decode(json_encode($value), true); } $nfe = $nfe_for_invoice['0']; - logModuleCall('gofas_nfeio', 'callback2', $nfe, '', '', 'replaceVars'); if ((string) $nfe['nfe_id'] === (string) $post['id'] and $nfe['status'] !== (string) $post['status']) { $new_nfe = [ diff --git a/modules/addons/gofasnfeio/functions.php b/modules/addons/gofasnfeio/functions.php index e71106f..2ba33c9 100644 --- a/modules/addons/gofasnfeio/functions.php +++ b/modules/addons/gofasnfeio/functions.php @@ -324,8 +324,12 @@ function gnfe_issue_nfe($postfields) curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($postfields)); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $response = curl_exec($curl); + $info =curl_getinfo($curl); curl_close($curl); - + if ($params['debug']) { + logModuleCall('gofas_nfeio', 'response', $response, '', '', 'replaceVars'); + logModuleCall('gofas_nfeio', 'info', $info, '', '', 'replaceVars'); + } return json_decode(json_encode(json_decode($response))); } } From 3a23a8401fd9deda1a9dd4e4dee8e80c8f02f4cc Mon Sep 17 00:00:00 2001 From: JoaoVictorLNacional Date: Fri, 15 Jan 2021 11:51:58 -0300 Subject: [PATCH 49/52] modificado if da checagem do callback --- modules/addons/gofasnfeio/callback.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/addons/gofasnfeio/callback.php b/modules/addons/gofasnfeio/callback.php index c9308ed..7acda2a 100644 --- a/modules/addons/gofasnfeio/callback.php +++ b/modules/addons/gofasnfeio/callback.php @@ -10,7 +10,7 @@ if ($post) { require_once __DIR__.'/functions.php'; - if (Capsule::table('gofasnfeio')->where('nfe_id', '=', $post['id'])->count() == 0 && $post['environment'] == 'Production') { + if (Capsule::table('gofasnfeio')->where('nfe_id', '=', $post['id'])->count() == 0 || $post['environment'] == 'Production') { return ''; } From 8b73548d2a779edd88605536c5b2e4fea18bdf2f Mon Sep 17 00:00:00 2001 From: JoaoVictorLNacional Date: Fri, 15 Jan 2021 11:56:02 -0300 Subject: [PATCH 50/52] modificado if do callback --- modules/addons/gofasnfeio/callback.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/addons/gofasnfeio/callback.php b/modules/addons/gofasnfeio/callback.php index 7acda2a..8333bf9 100644 --- a/modules/addons/gofasnfeio/callback.php +++ b/modules/addons/gofasnfeio/callback.php @@ -10,7 +10,7 @@ if ($post) { require_once __DIR__.'/functions.php'; - if (Capsule::table('gofasnfeio')->where('nfe_id', '=', $post['id'])->count() == 0 || $post['environment'] == 'Production') { + if (Capsule::table('gofasnfeio')->where('nfe_id', '=', $post['id'])->count() == 0 || $post['environment'] != 'Production') { return ''; } From cd3032deae932e9413219b8655c07cc39ee0364c Mon Sep 17 00:00:00 2001 From: JoaoVictorLNacional Date: Mon, 18 Jan 2021 14:29:24 -0300 Subject: [PATCH 51/52] removido texto desnessesario na pagina de codigos de produtos --- modules/addons/gofasnfeio/outputproduct.php | 1 - 1 file changed, 1 deletion(-) diff --git a/modules/addons/gofasnfeio/outputproduct.php b/modules/addons/gofasnfeio/outputproduct.php index 4880af1..049dd53 100644 --- a/modules/addons/gofasnfeio/outputproduct.php +++ b/modules/addons/gofasnfeio/outputproduct.php @@ -62,7 +62,6 @@ echo ' NFE.oi -

    Listagem produtos

    '.$nfes_total.' Itens encontrados.
    Exibindo de '.$nfes_from.' a '.$nfes_to.'. Página '.$nfes_page.' de '.$nfes_pages.'
    From 4acbd1d7e7ed19f2e04db59900f447970bd12a49 Mon Sep 17 00:00:00 2001 From: JoaoVictorLNacional Date: Mon, 18 Jan 2021 15:46:37 -0300 Subject: [PATCH 52/52] =?UTF-8?q?modificado=20forma=20de=20separar=20o=20e?= =?UTF-8?q?ndere=C3=A7o=20com=20virugla?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../addons/gofasnfeio/hooks/aftercronjob.php | 19 ++++++++++++++----- .../addons/gofasnfeio/hooks/dailycronjob.php | 17 +++++++++++++---- 2 files changed, 27 insertions(+), 9 deletions(-) diff --git a/modules/addons/gofasnfeio/hooks/aftercronjob.php b/modules/addons/gofasnfeio/hooks/aftercronjob.php index 64239d5..1e3e141 100644 --- a/modules/addons/gofasnfeio/hooks/aftercronjob.php +++ b/modules/addons/gofasnfeio/hooks/aftercronjob.php @@ -4,6 +4,7 @@ exit(); } use WHMCS\Database\Capsule; + if ($params['debug']) { logModuleCall('gofas_nfeio', 'check', 'check', '', 'replaceVars'); } @@ -72,7 +73,15 @@ } 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 (0 == !strlen($customer['insc_municipal'])) { $postfields = [ 'cityServiceCode' => $service_code, @@ -86,8 +95,8 @@ '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']), + 'street' => $street, + 'number' => $number, 'additionalInformation' => '', 'district' => $client['address2'], 'city' => [ @@ -112,8 +121,8 @@ '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']), + 'street' => $street, + 'number' => $number, 'additionalInformation' => '', 'district' => $client['address2'], 'city' => [ diff --git a/modules/addons/gofasnfeio/hooks/dailycronjob.php b/modules/addons/gofasnfeio/hooks/dailycronjob.php index 5191f36..9b7422f 100644 --- a/modules/addons/gofasnfeio/hooks/dailycronjob.php +++ b/modules/addons/gofasnfeio/hooks/dailycronjob.php @@ -54,6 +54,15 @@ } 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 (0 == !strlen($customer['insc_municipal'])) { $postfields = [ 'cityServiceCode' => $service_code, @@ -67,8 +76,8 @@ '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']), + 'street' => $street, + 'number' => $number, 'additionalInformation' => '', 'district' => $client['address2'], 'city' => [ @@ -93,8 +102,8 @@ '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']), + 'street' => $street, + 'number' => $number, 'additionalInformation' => '', 'district' => $client['address2'], 'city' => [