Skip to content

Instantly share code, notes, and snippets.

@raphox
Created December 20, 2016 12:19
Show Gist options
  • Save raphox/a3d2634c6f90a7a1be2c2fa10c3ce264 to your computer and use it in GitHub Desktop.
Save raphox/a3d2634c6f90a7a1be2c2fa10c3ce264 to your computer and use it in GitHub Desktop.
Symfony 2 + NFePHP + Form + Controller
<?php
namespace Labone\Bundle\OrderBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Doctrine\ORM\Tools\Pagination\Paginator;
use Doctrine\ORM\Query\Expr\Join;
use Labone\Bundle\OrderBundle\Form\NfeType;
use NFePHP\NFe\MakeNFe;
use NFePHP\NFe\ToolsNFe;
use NFePHP\Extras\Danfe;
use NFePHP\Common\Files\FilesFolders;
use \Swift_Attachment;
/**
* Nfe controller.
*
*/
class NfeController extends Controller
{
private $breadcrumbs;
public function preExecute()
{
$this->breadcrumbs = $this->get("white_october_breadcrumbs");
$this->breadcrumbs->addItem('<i class="icon-home"></i>', $this->get("router")->generate("_welcome"));
$this->breadcrumbs->addItem('Pedidos', $this->get("router")->generate("LaboneOrderBundle_request"));
$this->breadcrumbs->addItem('Notas fiscais', $this->get("router")->generate("LaboneOrderBundle_nfe_all"));
}
/**
* Lists all Request entities.
*
*/
public function indexAction()
{
$request = $this->getRequest();
$this->breadcrumbs->addItem("Listar", "#");
if ($request->isXmlHttpRequest() != 'json') {
return $this->render('LaboneOrderBundle:Nfe:index.html.twig');
} else {
$em = $this->getDoctrine()->getManager();
$qb = $em->createQueryBuilder();
$qb->select('a')
->from('LaboneOrderBundle:Request', 'a')
->where($qb->expr()->isNotNull('a.nfeKey'))
->innerJoin('a.client', 'cl');
$aColumns = array('a.nfeNum', 'a.id', 'cl.name', 'a.nfeComp', 'a.nfeTotal', 'a.nfeStatus', 'a.nfeDate', null,
'a.created_at', 'a.updated_at', 'cl.cnpj', 'cl.trade', 'cl.contact');
if ($request->get('iSortCol_0') || $request->get('iSortCol_0') === '0') {
for ($i = 0; $i < intval($request->get('iSortingCols')); $i++) {
if ($request->get('bSortable_' . intval($request->get('iSortCol_' . $i))) == "true") {
if (intval($request->get('iSortCol_'.$i)) == 1) {
$qb->orderBy('a.code', $request->get('sSortDir_' . $i));
$qb->addOrderBy($aColumns[intval($request->get('iSortCol_'.$i))], $request->get('sSortDir_' . $i));
} else {
$qb->orderBy($aColumns[intval($request->get('iSortCol_'.$i))], $request->get('sSortDir_' . $i));
}
}
}
}
if ($request->get('sSearch') != "") {
$orX = $qb->expr()->orX();
$qb->setParameter(count($aColumns), '%' . $request->get('sSearch') . '%');
for ($i = 0; $i < count($aColumns); $i++) {
if ($aColumns[$i]) {
if ($i == 1) {
$orX->add($qb->expr()->like('a.code', '?' . count($aColumns)));
$qb->setParameter(count($aColumns), '%' . $request->get('sSearch') . '%');
$orX->add($qb->expr()->eq($aColumns[$i], '?' . $i));
$qb->setParameter($i, intval($request->get('sSearch')));
} else {
$orX->add($qb->expr()->like($aColumns[$i], '?' . $i));
$qb->setParameter($i, '%' . $request->get('sSearch') . '%');
}
}
}
$qb->andWhere($orX);
}
$query = $qb->getQuery()
->setFirstResult($request->get('iDisplayStart', 0))
->setMaxResults($request->get('iDisplayLength', 10));
$entities = new Paginator($query, $fetchJoinCollection = true);
return $this->render('LaboneOrderBundle:Nfe:index.json.twig', array(
'entities' => $entities->getIterator(),
'total' => $entities->count()
));
}
}
private function getCompanyParameters()
{
$request = $this->getRequest();
$nfe_parameters = $this->container->getParameter('nfe');
$company_emit = $request->get('company');
if (!isset($nfe_parameters[$company_emit])) {
$company_emit = "santos_araujo"; // santos_araujo || labone
}
$companies = array();
foreach ($nfe_parameters as $key => $item) {
if ($key != 'global') {
$companies[$key] = $item['razaosocial'];
}
}
return array_merge($nfe_parameters['global'], $nfe_parameters[$company_emit], array(
'companies' => $companies
));
}
/**
* Generate or print the Nota fiscal
*
*/
public function newAction($id)
{
$this->breadcrumbs->addItem("Gerar/Cancelar", "#");
$request = $this->getRequest();
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('LaboneOrderBundle:Request')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Request entity.');
}
if ($entity->getNfeKey()) {
$url = $this->generateUrl('LaboneOrderBundle_nfe_print', array('id' => $entity->getId() ));
$this->get('session')
->getFlashBag()
->add('alert', 'Atenção! Esse pedido já possiu uma nota fiscal emitida. <a href="'. $url .'" target="_blank">Imprimir</a>');
}
$company = $entity->getClient();
$address = $company->getAddresses()->first();
$parameters = $this->getCompanyParameters();
$form = $this->createForm(new NfeType());
// Get number NFe to `$parameters['company']`
$qb = $em->createQueryBuilder();
$qb->select('MAX(r.nfeNum)')
->from('LaboneOrderBundle:Request', 'r')
->where($qb->expr()->like('r.nfeComp', '?1'))
->setParameter(1, $parameters['company']);
$max = $qb->getQuery()->getSingleScalarResult();
if ($count) {
$nNf = $parameters['nNF'];
} else {
$nNf = $max + 1;
}
$form->get('ide')->setData(array(
'cUF' => $parameters['cUF'],
'cMunFG' => $parameters['cMunFG'],
'cNF' => sprintf("%08d", $entity->getId()),
'nNF' => $entity->getNfeNum() ? $entity->getNfeNum() : sprintf("%08d", $nNf)
));
$form->get('emit')->setData(array(
'CNPJ' => $parameters['cnpj'],
'CPF' => '', // Utilizado para CPF na nota
'xNome' => $parameters['razaosocial'],
'xFant' => $parameters['nomefantasia'],
'IE' => $parameters['ie'],
'IEST' => $parameters['iest'],
'IM' => $parameters['im'],
'CNAE' => $parameters['cnae'],
'CRT' => $parameters['regime'],
'enderEmit' => array(
'xLgr' => $parameters['endereco']['xLgr'],
'nro' => $parameters['endereco']['nro'],
'xCpl' => $parameters['endereco']['xCpl'],
'xBairro' => $parameters['endereco']['xBairro'],
'cMun' => $parameters['endereco']['cMun'],
'xMun' => $parameters['endereco']['xMun'],
'UF' => $parameters['endereco']['UF'],
'CEP' => $parameters['endereco']['CEP'],
'cPais' => $parameters['endereco']['cPais'],
'xPais' => $parameters['endereco']['xPais'],
'fone' => $parameters['endereco']['fone']
)
));
/**
* Destinatário
*/
$cpf = null;
$cnpj = $company->getCnpj();
$phones = $company->getPhones();
$address = $company->getAddress();
$re = "/^([0-9]{2}[\\.]?[0-9]{3}[\\.]?[0-9]{3}[\\/]?[0-9]{4}[-]?[0-9]{2})|([0-9]{3}[\\.]?[0-9]{3}[\\.]?[0-9]{3}[-]?[0-9]{2})$/";
if (!preg_match($re, $cnpj)) {
$cpf = $cnpj;
$cnpj = '';
}
if ($phones && count($phones)) {
$fone = $phones[0]->getNumber();
} else {
$fone = '';
}
$form->get('dest')->setData(array(
'CNPJ' => $cnpj,
'CPF' => $cpf, // Utilizado para CPF na nota
'xNome' => $company->getName(),
'idEstrangeiro' => null,
'indIEDest' => null,
'IE' => $company->getRegistration(),
'ISUF' => '',
'IM' => '',
'email' => $company->getEmail(),
'enderDest' => array(
'xLgr' => $address->getAddress(),
'nro' => $address->getNumber(),
'xCpl' => $address->getComplement(),
'xBairro' => $address->getDistrict(),
'cMun' => $address->getCity()->getCode(),
'xMun' => $address->getCity()->getName(),
'UF' => $address->getCity()->getState()->getUf(),
'CEP' => $address->getZipcode(),
'cPais' => $parameters['endereco']['cPais'],
'xPais' => $parameters['endereco']['xPais'],
'fone' => $fone
)
));
$products = array();
foreach ($entity->getRequestProducts() as $key => $requestProduct) {
$product = $requestProduct->getProduct();
$products[] = array(
'cProd' => $product->getId(),
'cEAN' => null,
'xProd' => $product->getName(),
'NCM' => $product->getNcm(),
'EXTIPI' => null,
'CFOP' => null,
'uCom' => $product->getUnit(),
'qCom' => $product->getQty() * $requestProduct->getQuantity(),
'vUnCom' => $requestProduct->getPriceUnitary(),
'vProd' => $requestProduct->getPriceUnitary() * $requestProduct->getQuantity(),
'uTrib' => $product->getUnitTrib(),
'qTrib' => $product->getQtyTrib() * $requestProduct->getQuantity(),
'vUnTrib' => $requestProduct->getPriceUnitary(),
'cEANTrib' => null,
'vFrete' => null,
'vSeg' => null,
'vDesc' => null,
'vOutro' => null,
'indTot' => null,
'xPed' => null,
'nItemPed' => null,
'nFCI' => null,
'ICMS' => array(
// 'vBC' => number_format($product->getQtyTrib() * $product->getPriceTrib(), 2, '.', ''),
// 'pICMS' => $product->getIcms(),
// 'vICMS' => number_format(($product->getQtyTrib() * $product->getPriceTrib()) * ($product->getIcms() / 100), 2, '.', '')
)
);
}
$form->get('prods')->setData($products);
$form->get('transp')->setData(array(
'modFrete' => null,
'vols' => array(
array()
)
));
return $this->render('LaboneOrderBundle:Nfe:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
'companies' => $parameters['companies']
));
}
/**
* Generate or print the Nota fiscal
*
*/
public function createAction(Request $request, $id)
{
$this->breadcrumbs->addItem("Nota fiscal", "#");
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('LaboneOrderBundle:Request')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Request entity.');
}
$form = $this->createForm(new NfeType());
$form->bind($request);
$parameters = $this->getCompanyParameters();
if (!$entity->getNfeProt()) {
if ($form->isValid()) {
$nfe = new MakeNFe();
$procEmi = '0'; // 0=Emissão de NF-e com aplicativo do contribuinte;
// 1=Emissão de NF-e avulsa pelo Fisco;
// 2=Emissão de NF-e avulsa, pelo contribuinte com seu certificado digital, através do site do Fisco;
// 3=Emissão NF-e pelo contribuinte com aplicativo fornecido pelo Fisco.
$versao = '3.10'; // Versão da nota fiscal
$verProc = '4.0.43'; // Versão do aplicativo emissor
$dhCont = ''; // Entrada em contingência AAAA-MM-DDThh:mm:ssTZD
$xJust = ''; // Justificativa da entrada em contingência
$dhEmi = date("Y-m-d\TH:i:sP"); // Formato: “AAAA-MM-DDThh:mm:ssTZD” (UTC - Universal Coordinated Time).
$dhSaiEnt = date("Y-m-d\TH:i:sP"); // Não informar este campo para a NFC-e.
// Numero e versão da NFe (infNFe)
$ano = date('y', strtotime($dhEmi));
$mes = date('m', strtotime($dhEmi));
$ide = $form->get('ide')->getData();
$emit = $form->get('emit')->getData();
$dest = $form->get('dest')->getData();
$emit_end = $emit['enderEmit'];
$dest_end = $dest['enderDest'];
/**
* Format values from form
*/
$emit['CNPJ'] = $emit['CNPJ'] ? preg_replace('/[^0-9]+/', '', $emit['CNPJ']) : null;
$emit['IE'] = $emit['IE'] ? preg_replace('/[^0-9]+/', '', $emit['IE']) : null;
$dest['CNPJ'] = $dest['CNPJ'] ? preg_replace('/[^0-9]+/', '', $dest['CNPJ']) : null;
$dest['CPF'] = $dest['CPF'] ? preg_replace('/[^0-9]+/', '', $dest['CPF']) : null;
$dest['IE'] = $dest['IE'] ? preg_replace('/[^0-9]+/', '', $dest['IE']) : null;
$emit_end['CEP'] = preg_replace('/[^0-9]+/', '', $emit_end['CEP']);
$dest_end['CEP'] = preg_replace('/[^0-9]+/', '', $dest_end['CEP']);
$dest_end['fone'] = preg_replace('/[^0-9]+/', '', $dest_end['fone']);
$chave = $nfe->montaChave($ide['cUF'], $ano, $mes, $emit['CNPJ'], $ide['mod'], $ide['serie'], $ide['nNF'], $ide['tpEmis'], $ide['cNF']);
$resp = $nfe->taginfNFe($chave, $versao);
$cDV = substr($chave, -1); // Digito Verificador da Chave de Acesso da NF-e, o DV é calculado com a aplicação do algoritmo módulo 11 (base 2,9) da Chave de Acesso.
// Tag IDE
$nfe->tagide($ide['cUF'], $ide['cNF'], $ide['natOp'], $ide['indPag'],
$ide['mod'], $ide['serie'], $ide['nNF'], $dhEmi, $dhSaiEnt, $ide['tpNF'],
$ide['idDest'], $ide['cMunFG'], $ide['tpImp'], $ide['tpEmis'], $cDV, $parameters['tpAmb'],
$ide['finNFe'], $ide['indFinal'], $ide['indPres'], $ide['procEmi'],
$verProc, $dhCont, $xJust);
// Dados do emitente
$nfe->tagemit($emit['CNPJ'], $emit['CPF'], $emit['xNome'], $emit['xFant'], $emit['IE'],
$emit['IEST'], $emit['IM'], $emit['CNAE'], $emit['CRT']);
$nfe->tagenderEmit($emit_end['xLgr'], $emit_end['nro'], $emit_end['xCpl'], $emit_end['xBairro'],
$emit_end['cMun'], $emit_end['xMun'], $emit_end['UF'], $emit_end['CEP'], $emit_end['cPais'],
$emit_end['xPais'], $emit_end['fone']);
// Dados do destinatário
$nfe->tagdest($dest['CNPJ'], $dest['CPF'], $dest['idEstrangeiro'], $dest['xNome'],
$dest['indIEDest'], $dest['IE'], $dest['ISUF'], $dest['IM'], $dest['email']);
$nfe->tagenderDest($dest_end['xLgr'], $dest_end['nro'], $dest_end['xCpl'], $dest_end['xBairro'],
$dest_end['cMun'], $dest_end['xMun'], $dest_end['UF'], $dest_end['CEP'], $dest_end['cPais'],
$dest_end['xPais'], $dest_end['fone']);
if ($parameters['aAut']) {
$aut = $parameters['aAut'];
if (strlen($aut) == 14) {
$nfe->tagautXML($aut);
} else {
$nfe->tagautXML('', $aut);
}
}
/**
* Products
*/
$total = array(
'vBC' => 0.00,
'vICMS' => 0.00,
'vICMSDeson' => 0.00,
'vBCST' => 0.00,
'vST' => 0.00,
'vProd' => 0.00,
'vFrete' => 0.00,
'vSeg' => 0.00,
'vDesc' => 0.00,
'vII' => 0.00,
'vIPI' => 0.00,
'vPIS' => 0.00,
'vCOFINS' => 0.00,
'vOutro' => 0.00
);
$products = $form->get('prods')->getData();
foreach ($products as $key => $product) {
$nItem = $key + 1;
$icms = $product['ICMS'];
$pis = $product['PIS'];
$cofins = $product['COFINS'];
$nfe->tagimposto($nItem, $icms['vICMS'] + $pis['vPIS'] + $cofins['vCOFINS']);
$total['vBC'] += $icms['vBC'] + $pis['vBC'] + $cofins['vBC'];
$total['vICMS'] += $icms['vICMS'];
$total['vPIS'] += $pist['vPIS'];
$total['vCOFINS'] += $cofins['vCOFINS'];
$total['vProd'] += $product['vProd'];
$total['vFrete'] += $product['vFrete'];
$total['vSeg'] += $product['vSeg'];
$total['vDesc'] += $product['vDesc'];
$total['vOutro'] += $product['vOutro'];
$product['vUnCom'] = $this->nullOrCurrency($product['vUnCom']);
$product['vProd'] = $this->nullOrCurrency($product['vProd']);
$product['vUnTrib'] = $this->nullOrCurrency($product['vUnTrib']);
$product['vFrete'] = $this->nullOrCurrency($product['vFrete']);
$product['vSeg'] = $this->nullOrCurrency($product['vSeg']);
$product['vDesc'] = $this->nullOrCurrency($product['vDesc']);
$product['vOutro'] = $this->nullOrCurrency($product['vOutro']);
$nfe->tagprod($nItem, $product['cProd'], $product['cEAN'], $product['xProd'], $product['NCM'],
$product['EXTIPI'], $product['CFOP'], $product['uCom'],
$product['qCom'], $product['vUnCom'], $product['vProd'], $product['cEANTrib'],
$product['uTrib'], $product['qTrib'], $product['vUnTrib'], $product['vFrete'],
$product['vSeg'], $product['vDesc'], $product['vOutro'], $product['indTot'],
$product['xPed'], $product['nItemPed'], $product['nFCI']);
$icms['vBC'] = $this->zeroOrCurrency($product['vOutro']);
$icms['vICMS'] = $this->zeroOrCurrency($product['vICMS']);
$icms['vCredICMSSN'] = $this->zeroOrCurrency($product['vOutro']);
$icms['vBCST'] = $this->zeroOrCurrency($product['vBCST']);
$icms['vICMSST'] = $this->zeroOrCurrency($product['vICMSST']);
$icms['vBCSTRet'] = $this->zeroOrCurrency($product['vBCSTRet']);
$icms['vICMSSTRet'] = $this->zeroOrCurrency($product['vICMSSTRet']);
// ICMS
$nfe->tagICMSSN($nItem, $icms['orig'], $icms['csosn'], $icms['modBC'], $icms['vBC'], $icms['pRedBC'],
$icms['pICMS'], $icms['vICMS'], $icms['pCredSN'], $icms['vCredICMSSN'], $icms['modBCST'],
$icms['pMVAST'], $icms['pRedBCST'], $icms['vBCST'], $icms['pICMSST'], $icms['vICMSST'],
$icms['vBCSTRet'], $icms['vICMSSTRet']);
// PIS
$nfe->tagPIS($nItem, $pis['cst'], $pis['vBC'], $pis['pPIS'], $pis['vPIS'], $pis['qBCProd'],
$pis['vAliqProd']);
// COFINS
$nfe->tagCOFINS($nItem, $cofins['cst'], $cofins['vBC'], $cofins['pCOFINS'], $cofins['vCOFINS'],
$cofins['qBCProd'], $cofins['vAliqProd']);
}
/**
* Total
*/
$vNF = number_format($total['vProd']-$total['vDesc']-$total['vICMSDeson']+$total['vST']+$total['vFrete']+$total['vSeg']+$total['vOutro']+$total['vII']+$total['vIPI'], 2, '.', '');
$vTotTrib = number_format($total['vICMS']+$total['vST']+$total['vII']+$total['vIPI']+$total['vPIS']+$total['vCOFINS']+$total['vIOF']+$total['vISS'], 2, '.', '');
// Format total to currency
$total = array_map(function($item){
return $this->zeroOrCurrency($item);
}, $total);
$nfe->tagICMSTot($total['vBC'], $total['vICMS'], $total['vICMSDeson'], $total['vBCST'], $total['vST'], $total['vProd'], $total['vFrete'], $total['vSeg'], $total['vDesc'], $total['vII'], $total['vIPI'], $total['vPIS'], $total['vCOFINS'], $total['vOutro'], $vNF, $vTotTrib);
/**
* Frete
*/
$transp = $form->get('transp')->getData();
$nfe->tagtransp($transp['modFrete']);
$vols = isset($transp['vols']) ? $transp['vols'] : [];
// Dados dos Volumes Transportados
foreach ($vols as $vol) {
$nfe->tagvol($vol['qVol'], $vol['esp'], $vol['marca'], $vol['nVol'], $vol['pesoL'], $vol['pesoB'], $vol['aLacres']);
}
/**
* Monta a NFe e retorna na tela
*/
$resp = $nfe->montaNFe();
if ($resp) {
$tools = new ToolsNFe(json_encode($parameters));
$xml = $nfe->getXML();
$filename = $this->get('kernel')->getRootDir() . "/../web/nfes/nfe/{$chave}-nfe.xml";
$filename_pdf = $this->get('kernel')->getRootDir() . "/../web/nfes/nfe/{$chave}-danfe.pdf";
$xml = $tools->assina($xml);
if ($tools->validarXml($xml)) {
// Insert key for NF-E to check on the future
$entity->setNfeKey($chave);
$entity->setNfeTotal($vNF);
$entity->setNfeNum($ide['nNF']);
$em->flush();
file_put_contents($filename, $xml);
$result = array();
$idLote = '';
$indSinc = '0';
$flagZip = false;
$tools->sefazEnviaLote($xml, $parameters['tpAmb'], $idLote, $result, $indSinc, $flagZip);
if ($result['nRec']) {
$recibo = $result['nRec'];
$result_status = array();
// Insert response for NF-E to check on the future
$entity->setNfeRec($result['nRec']);
$entity->setNfeStatus($result['xMotivo']);
$em->flush();
// Wait to proccess nfe
sleep(15);
$protocol = $this->setProtocol($em, $entity, $parameters, $tools);
if ($protocol['cStat'] == '100') {
$docxml = FilesFolders::readFile($protocol['filename']);
$danfe = new Danfe($docxml, 'P', 'A4', $parameters['aDocFormat']['pathLogoFile'], 'I', '');
$danfe->montaDANFE();
$danfe->printDANFE($filename_pdf, 'F'); //Salva o PDF na pasta
$response = new BinaryFileResponse($filename_pdf);
$response->headers->set('Content-Type', 'application/pdf');
$response->setContentDisposition(
ResponseHeaderBag::DISPOSITION_ATTACHMENT,
"{$chave}-danfe.pdf"
);
return $response;
} else {
$this->get('session')->getFlashBag()->add('error', "Falhou! Os dados de sua nota não foram validados pela SEFAZ. {$protocol['xMotivo']}");
}
} else {
$entity->setNfeStatus($result['xMotivo']);
$em->flush();
$this->get('session')->getFlashBag()->add('error', "Falhou! Não foi possível enviar sua NFe para a SEFAZ. {$result['xMotivo']}");
}
} else {
$errors = "<ul>";
foreach ($tools->errors as $error) {
if (is_array($error)) {
foreach ($error as $err) {
$errors .= "<li>$err</li>";
}
} else {
$errors .= "<li>$error</li>";
}
}
$errors .= "</ul>";
$this->get('session')->getFlashBag()->add('alert', "Falhou! Foram encontrado erros nos dados de sua NFe:<br /> $errors");
}
} else {
return new Response(var_export($nfe->erros, true));
}
} else {
$this->get('session')->getFlashBag()->add('alert', 'Falhou! Corrija os campos do formulário.');
}
} else {
$this->get('session')->getFlashBag()->add('error', "Já existe uma nota emitida! Cancele a mesma antes de emitir uma nova.");
}
return $this->render('LaboneOrderBundle:Nfe:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
'companies' => $parameters['companies']
));
}
/**
* Displays a data to print an existing Request Nfe entity.
*
*/
public function printAction($id)
{
$this->breadcrumbs->addItem("Imprimir", "#");
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('LaboneOrderBundle:Request')->find($id);
if (!$entity || !$entity->getNfeKey()) {
throw $this->createNotFoundException('Unable to find Request entity.');
}
$chave = $entity->getNfeKey();
$parameters = $this->getCompanyParameters();
$path = $this->get('kernel')->getRootDir() . "/../web/nfes/nfe/";
if ($entity->getNfeProt()) {
$date = $entity->getUpdatedAt()->format('Ym');
$path .= $parameters['tpAmb'] == '1' ? "producao/" : "homologacao/";
$path .= "enviadas/aprovadas/{$date}/";
$filename = "{$path}{$chave}-protNFe.xml";
} else {
$filename = "{$path}{$chave}-nfe.xml";
}
$filename_pdf = $this->get('kernel')->getRootDir() . "/../web/nfes/nfe/{$chave}-danfe.pdf";
$docxml = FilesFolders::readFile($filename);
$danfe = new Danfe($docxml, 'P', 'A4', $parameters['aDocFormat']['pathLogoFile'], 'I', '');
$danfe->montaDANFE();
$danfe->printDANFE($filename_pdf, 'F'); //Salva o PDF na pasta
$response = new BinaryFileResponse($filename_pdf);
$response->headers->set('Content-Type', 'application/pdf');
$response->setContentDisposition(
ResponseHeaderBag::DISPOSITION_INLINE,
"{$chave}-danfe.pdf"
);
return $response;
}
/**
* Displays a data from SEFAZ an existing Request Nfe entity.
*
*/
public function statusAction($id)
{
$this->breadcrumbs->addItem("Status", "#");
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('LaboneOrderBundle:Request')->find($id);
if (!$entity || !$entity->getNfeRec()) {
throw $this->createNotFoundException('Unable to find Request entity.');
}
$parameters = $this->getCompanyParameters();
$tools = new ToolsNFe(json_encode($parameters));
$response = array();
$retorno = $tools->sefazConsultaRecibo($entity->getNfeRec(), $parameters['tpAmb'], $response);
echo '<pre>';
print_r($response);
echo "</pre>";
exit();
}
/**
* Cancel an existing Request Nfe entity.
*
*/
public function cancelAction($id)
{
$request = $this->getRequest();
$this->breadcrumbs->addItem("Cancelar", "#");
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('LaboneOrderBundle:Request')->find($id);
if (!$entity || !$entity->getNfeKey()) {
throw $this->createNotFoundException('Unable to find Request entity.');
}
$parameters = $this->getCompanyParameters();
$tools = new ToolsNFe(json_encode($parameters));
$chave = $entity->getNfeKey();
$nProt = $entity->getNfeProt();
$message = $request->get('message');
$xJust = $message ? $message : 'Teste de cancelamento em ambiente de homologação';
$response = array();
$tools->sefazCancela($chave, $parameters['tpAmb'], $xJust, $nProt, $response);
if ($response['evento'] && (
$response['evento'][0]['cStat'] == '101' ||
$response['evento'][0]['cStat'] == '135' ||
$response['evento'][0]['cStat'] == '151' ||
$response['evento'][0]['cStat'] == '155'
)) {
$entity->setNfeKey(null);
// $entity->setNfeRec(null); Can be used to get status in SEFAZ
$entity->setNfeProt(null);
$entity->setNfeStatus($response['evento'][0]['xMotivo']);
$em->flush();
$this->get('session')->getFlashBag()->add('notice', "Nota fiscal cancelada com sucesso.");
} else {
if ($response['evento']) {
$this->get('session')->getFlashBag()->add('error', "Falhou! Não foi possivel cancelar sua nota fiscal. {$response['evento'][0]['xMotivo']}");
} else {
$this->get('session')->getFlashBag()->add('error', "Falhou! Não foi possivel cancelar sua nota fiscal.");
}
}
return $this->redirect($this->generateUrl('LaboneOrderBundle_nfe', array('id' => $entity->getId() )));
}
/**
* Try protocol again to SEFAZ an existing Request Nfe entity.
*
*/
public function protocolAction($id)
{
$this->breadcrumbs->addItem("Protocol", "#");
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('LaboneOrderBundle:Request')->find($id);
if (!$entity || !$entity->getNfeKey()) {
throw $this->createNotFoundException('Unable to find Request entity.');
}
$parameters = $this->getCompanyParameters();
$tools = new ToolsNFe(json_encode($parameters));
$protocol = $this->setProtocol($em, $entity, $parameters, $tools);
if ($protocol['cStat'] == '100') {
$this->get('session')->getFlashBag()->add('notice', "Sua NFe foi protocoloda com sucesso.");
} else {
$this->get('session')->getFlashBag()->add('error', "Falhou! Os dados de sua nota não foram validados pela SEFAZ. {$protocol['xMotivo']}");
}
return $this->redirect($this->generateUrl('LaboneOrderBundle_nfe', array('id' => $entity->getId() )));
}
private function setProtocol($em, $entity, $parameters, $tools) {
$response = array();
$path = $this->get('kernel')->getRootDir() . "/../web/nfes/nfe/";
$filename = $path . "{$entity->getNfeKey()}-nfe.xml";
$tools->sefazConsultaRecibo($entity->getNfeRec(), $parameters['tpAmb'], $response);
if ($response['aProt'] && $response['aProt'][0]['cStat'] == '100') {
$date = $entity->getUpdatedAt()->format('Ym');
$path .= $parameters['tpAmb'] == '1' ? "producao/" : "homologacao/";
$filename_prot = "{$path}temporarias/{$date}/{$entity->getNfeRec()}-retConsReciNFe.xml";
$tools->addProtocolo($filename, $filename_prot, true);
$filename = "{$path}enviadas/aprovadas/{$date}/{$entity->getNfeKey()}-protNFe.xml";
// Insert prot for NF-E to check on the future
$entity->setNfeProt($response['aProt'][0]['nProt']);
$entity->setNfeComp($parameters['company']);
$entity->setNfeStatus($response['aProt'][0]['xMotivo']);
$entity->setNfeDate(new \DateTime());
$em->flush();
} else if ($response['aProt'] && $response['aProt'][0]) {
$entity->setNfeStatus($response['aProt'][0]['xMotivo']);
$em->flush();
}
return array(
'cStat' => $response['aProt'] && $response['aProt'][0]['cStat'] ? $response['aProt'][0]['cStat'] : null,
'xMotivo' => $response['aProt'] && $response['aProt'][0]['xMotivo'] ? $response['aProt'][0]['xMotivo'] : null,
'filename' => $filename
);
}
private function zeroOrCurrency($value) {
return $value ? number_format($value, 2, '.', '') : '0.00';
}
private function nullOrCurrency($value) {
return $value ? number_format($value, 2, '.', '') : null;
}
}
<?php
namespace Labone\Bundle\OrderBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class NfeType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('ide', new NfeIdeType(), array(
'label' => "Dados da nota fiscal"
))
->add('emit', new NfeEmitType(), array(
'label' => "Emitente"
))
->add('dest', new NfeDestType(), array(
'label' => "Destinatário"
))
->add('prods', 'collection', array(
'type' => new NfeProdType(),
'label' => "Produtos",
'allow_add' => true,
'allow_delete' => true
))
->add('transp', new NfeTranspType())
// ->add('total', new NfeTotalType())
;
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array());
}
/**
* @return string
*/
public function getName()
{
return 'labone_bundle_orderbundle_nfetype';
}
}
class NfeTotalType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('vBC', null, array('label' => "vBC"))
->add('vICMS', null, array('label' => "vICMS"))
->add('vICMSDeson', null, array('label' => "vICMSDeson"))
->add('vBCST', null, array('label' => "vBCST"))
->add('vST', null, array('label' => "vST"))
->add('vProd', null, array('label' => "vProd"))
->add('vFrete', null, array('label' => "Valor do frete (R$)"))
->add('vSeg', null, array('label' => "Valor do seguro (R$)"))
->add('vDesc', null, array('label' => "Valor do desconto (R$)"))
->add('vII', null, array('label' => "vII"))
->add('vIPI', null, array('label' => "vIPI"))
->add('vPIS', null, array('label' => "vPIS"))
->add('vCOFINS', null, array('label' => "vCOFINS"))
->add('vOutro', null, array('label' => "vOutro"))
;
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array());
}
/**
* @return string
*/
public function getName()
{
return 'labone_bundle_orderbundle_nfe_totaltype';
}
}
class NfeTranspType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('modFrete', 'choice', array(
'label' => "Modalidade de Frete",
'empty_value' => '- SELECIONE - ',
'empty_data' => null,
'choices' => self::$MODFRETE_OPTS,
'attr' => array('class' => "chosen_find")
))
->add('vols', 'collection', array(
'label' => "Volumes",
'type' => new NfeTranspVolType(),
'allow_add' => true,
'allow_delete' => true
))
;
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array());
}
/**
* @return string
*/
public function getName()
{
return 'labone_bundle_orderbundle_nfe_transptype';
}
private static $MODFRETE_OPTS = array(
'0' => "POR CONTA DO EMITENTE",
'1' => "POR CONTA DO DESTINATÁRIO",
'2' => "POR CONTA DE TERCEIROS",
'9' => "SEM FRETE",
);
}
class NfeTranspVolType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('qVol', null, array(
'label' => "qVol",
'attr' => array('placeholder' => "Quantidade")
))
->add('esp', null, array(
'label' => "esp",
'attr' => array('placeholder' => "Espécie")
))
->add('marca', null, array(
'label' => "marca",
'attr' => array('placeholder' => "Marca"),
'required' => false
))
->add('nVol', null, array(
'label' => "nVol",
'attr' => array('placeholder' => "Numeração"),
'required' => false
))
->add('pesoL', 'number', array(
'label' => "pesoL",
'grouping' => true,
'attr' => array('placeholder' => "Peso líquido", 'class' => "spinner")
))
->add('pesoB', 'number', array(
'label' => "pesoB",
'grouping' => true,
'attr' => array('placeholder' => "Peso bruto", 'class' => "spinner")
))
// ->add('aLacres', null, array(
// 'label' => "aLacres",
// 'attr' => array('placeholder' => "Lacres"),
// 'required' => false
// ))
;
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array());
}
/**
* @return string
*/
public function getName()
{
return 'labone_bundle_orderbundle_nfe_transp_voltype';
}
}
class NfeEmitType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('CNPJ', null, array(
'label' => "CNPJ"
))
->add('CPF', null, array(
'label' => "CPF",
'required' => false
))
->add('xNome', null, array(
'label' => "Razão social",
'attr' => array('class' => "span8")
))
->add('xFant', null, array(
'label' => "Nome fantasia",
'required' => false,
'attr' => array('class' => "span8")
))
->add('IE', null, array(
'label' => "Inscrição Estadual"
))
->add('IEST', null, array(
'label' => "Inscrição Estadual do subst. tributária",
'required' => false
))
->add('IM', null, array(
'label' => "Inscrição Municipal",
'required' => false
))
->add('CNAE', null, array(
'label' => "CNAE Fiscal",
'required' => false
))
->add('CRT', 'choice', array(
'label' => "Código de Regime Tributário - CRT",
'choices' => self::$CRT_OPTS,
'attr' => array('class' => "chosen_find", 'style' => "width:400px")
))
->add('enderEmit', new NfeEnderType(), array(
'label' => "Endereço"
))
;
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array());
}
/**
* @return string
*/
public function getName()
{
return 'labone_bundle_orderbundle_nfe_emittype';
}
private static $CRT_OPTS = array(
'1' => "SIMPLES NACIONAL",
'2' => "SIMPLES NACIONAL - EXCESSO DE SUBLIMITE DA RECEITA BRUTA",
'3' => "REGIME NORMAL"
);
}
class NfeDestType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('CNPJ', null, array(
'label' => "CNPJ",
'required' => false
))
->add('CPF', null, array(
'label' => "CPF",
'required' => false
))
->add('idEstrangeiro', null, array(
'label' => "ID Estrangeiro",
'required' => false
))
->add('xNome', null, array(
'label' => "Razão social",
'attr' => array('class' => "span8")
))
->add('indIEDest', 'choice', array(
'label' => "Indicador da IE",
'choices' => self::$INDIEDEST_OPTS,
'attr' => array('class' => "chosen_find", 'style' => "width:400px")
))
->add('IE', null, array(
'label' => "Inscrição Estadual",
'required' => false
))
->add('ISUF', null, array(
'label' => "Inscrição SUFRAMA",
'required' => false
))
->add('IM', null, array(
'label' => "Inscrição Municipal",
'required' => false
))
->add('email', null, array(
'label' => "E-mail",
'required' => false
))
->add('enderDest', new NfeEnderType())
;
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array());
}
/**
* @return string
*/
public function getName()
{
return 'labone_bundle_orderbundle_nfe_desttype';
}
private static $INDIEDEST_OPTS = array(
'1' => "CONTRIBUINTE ICMS",
'2' => "CONTRIBUINTE ISENTO DE INSCRIÇÃO NO CADASTRO DE CONTRIBUINTES DO ICMS",
'9' => "NÃO CONTRIBUINTE, QUE PODE OU NÃO POSSUIR INSCRIÇÃO ESTADUAL NO CADASTRO DE CONTRIBUINTES DO ICMS"
);
}
class NfeEnderType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('xLgr', null, array(
'label' => "Logradouro",
'attr' => array('class' => "span8")
))
->add('nro', null, array(
'label' => "Número"
))
->add('xCpl', null, array(
'label' => "Complemento",
'required' => false
))
->add('xBairro', null, array(
'label' => "Bairro"
))
->add('cMun', null, array(
'label' => "Código do município"
))
->add('xMun', null, array(
'label' => "Nome do município"
))
->add('UF', null, array(
'label' => "UF"
))
->add('CEP', null, array(
'label' => "CEP",
'required' => false
))
->add('cPais', null, array(
'label' => "Código do páis",
'required' => false
))
->add('xPais', null, array(
'label' => "País",
'required' => false
))
->add('fone', null, array(
'label' => "Telefone",
'required' => false
))
;
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array());
}
/**
* @return string
*/
public function getName()
{
return 'labone_bundle_orderbundle_nfe_emittype';
}
}
class NfeIdeType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('cUF', 'choice', array(
'label' => "cUF",
'choices' => self::$CUF_OPTS,
'attr' => array('class' => "chosen_find", 'style' => "width:400px")
))
->add('cNF', null, array(
'label' => "cNF"
))
->add('natOp', 'choice', array(
'label' => "Natureza da operação",
'choices' => self::$NATOPE_OPTS,
'attr' => array('class' => "chosen_find", 'style' => "width:400px")
))
->add('indPag', 'choice', array(
'label' => "Indicador da forma de pagamento",
'choices' => self::$INDPAG_OPTS,
'attr' => array('class' => "chosen_find", 'style' => "width:400px")
))
->add('mod', 'text', array(
'data' => 55,
'label' => "Modelo do Documento Fiscal"
))
->add('serie', null, array(
'data' => '1',
'label' => "Série do Documento Fiscal"
))
->add('nNF', null, array(
'label' => "Número do Documento Fiscal"
))
->add('dhEmi', 'datetime', array(
'label' => "Data de emissão",
'data' => new \DateTime(),
'date_widget' => 'single_text',
'date_format' => 'dd/MM/yyyy',
'attr' => array('class' => 'date')
))
->add('dhSaiEnt', 'datetime', array(
'label' => "Data e hora de Saída ou da Entrada da Mercadoria/Produto",
'data' => new \DateTime(),
'date_widget' => 'single_text',
'date_format' => 'dd/MM/yyyy',
'attr' => array('class' => 'date',
'required' => false)
))
->add('tpNF', 'choice', array(
'label' => "Tipo do Documento Fiscal",
'choices' => self::$TPNF_OPTS,
'attr' => array('class' => "chosen_find", 'style' => "width:400px")
))
->add('idDest', 'choice', array(
'label' => "Identificador de local de destino da operação",
'empty_value' => '- SELECIONE - ',
'empty_data' => null,
'choices' => self::$IDDEST_OPTS,
'attr' => array('class' => "chosen_find", 'style' => "width:400px")
))
->add('cMunFG', 'integer', array(
'label' => "Código do Município de Ocorrência do Fato Gerador do ICMS",
'helpBlock' => 'Busque em http://www.ibge.gov.br/home/geociencias/areaterritorial/area.shtm.'
))
->add('tpImp', 'choice', array(
'label' => "Formato de impressão do DANFE",
'choices' => self::$TPIMP_OPTS,
'attr' => array('class' => "chosen_find", 'style' => "width:400px")
))
->add('tpEmis', 'choice', array(
'label' => "Tipo de Emissão",
'choices' => self::$TPEMIS_OPTS,
'attr' => array('class' => "chosen_find", 'style' => "width:400px")
))
->add('finNFe', 'choice', array(
'label' => "Código de identificação do Ambiente",
'choices' => self::$FINNFE_OPTS,
'attr' => array('class' => "chosen_find", 'style' => "width:400px")
))
->add('indFinal', 'choice', array(
'label' => "Indicador de operação com Consumidor final",
'empty_value' => '- SELECIONE - ',
'empty_data' => null,
'choices' => self::$INDFINAL_OPTS,
'attr' => array('class' => "chosen_find", 'style' => "width:400px")
))
->add('indPres', 'choice', array(
'label' => "Indicador de presença do comprador no estabelecimento comercial no momento da operação",
'choices' => self::$INDPRES_OPTS,
'attr' => array('class' => "chosen_find", 'style' => "width:400px")
))
->add('procEmi', 'choice', array(
'label' => "Código de identificação do processo de emissão",
'choices' => self::$PROCEMI_OPTS,
'attr' => array('class' => "chosen_find", 'style' => "width:400px")
))
->add('verProc', 'hidden', array('data' => "4.0.43"))
;
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array());
}
/**
* @return string
*/
public function getName()
{
return 'labone_bundle_orderbundle_nfe_idetype';
}
private static $CUF_OPTS = array(
'12' => "ACRE",
'27' => "ALAGOAS",
'16' => "AMAPÁ",
'13' => "AMAZONAS",
'29' => "BAHIA",
'23' => "CEARÁ",
'53' => "DISTRITO FEDERAL",
'32' => "ESPÍRITO SANTO",
'52' => "GOIÁS",
'21' => "MARANHÃO",
'51' => "MATO GROSSO",
'50' => "MATO GROSSO DO SUL",
'31' => "MINAS GERAIS",
'15' => "PARÁ",
'25' => "PARAÍBA",
'41' => "PARANÁ",
'26' => "PERNAMBUCO",
'22' => "PIAUÍ",
'33' => "RIO DE JANEIRO",
'24' => "RIO GRANDE DO NORTE",
'43' => "RIO GRANDE DO SUL (*)",
'11' => "RONDÔNIA",
'14' => "RORAIMA",
'42' => "SANTA CATARINA",
'35' => "SÃO PAULO",
'28' => "SERGIPE",
'17' => "TOCANTINS"
);
private static $NATOPE_OPTS = array(
"VENDA" => "VENDA",
"COMPRA" => "COMPRA",
"TRANSFERÊNCIA" => "TRANSFERÊNCIA",
"DEVOLUÇÃO" => "DEVOLUÇÃO",
"IMPORTAÇÃO" => "IMPORTAÇÃO",
"CONSIGNAÇÃO" => "CONSIGNAÇÃO",
"REMESSA" => "REMESSA"
);
private static $INDPAG_OPTS = array(
'0' => "PAGAMENTO À VISTA",
'1' => "PAGAMENTO À PRAZO",
'2' => "OUTROS"
);
private static $TPNF_OPTS = array(
'1' => "SAÍDA",
'0' => "ENTRADA"
);
private static $IDDEST_OPTS = array(
'1' => "OPERAÇÃO INTERNA",
'2' => "OPERAÇÃO INTERESTADUAL",
'3' => "OPERAÇÃO COM EXTERIOR"
);
private static $TPIMP_OPTS = array(
'1' => "DANFE NORMAL, RETRATO",
'0' => "SEM GERAÇÃO DE DANFE",
'2' => "DANFE NORMAL, PAISAGEM",
'3' => "DANFE SIMPLIFICADO",
'4' => "DANFE NFC-E",
'5' => "DANFE NFC-E EM MENSAGEM ELETRÔNICA"
);
private static $TPEMIS_OPTS = array(
'1' => "EMISSÃO NORMAL (NÃO EM CONTINGÊNCIA)",
'2' => "CONTINGÊNCIA FS-IA, COM IMPRESSÃO DO DANFE EM FORMULÁRIO DE SEGURANÇA",
'3' => "CONTINGÊNCIA SCAN (SISTEMA DE CONTINGÊNCIA DO AMBIENTE NACIONAL) DESATIVAÇÃO PREVISTA PARA 30/06/2014",
'4' => "CONTINGÊNCIA DPEC (DECLARAÇÃO PRÉVIA DA EMISSÃO EM CONTINGÊNCIA)",
'5' => "CONTINGÊNCIA FS-DA, COM IMPRESSÃO DO DANFE EM FORMULÁRIO DE SEGURANÇA",
'6' => "CONTINGÊNCIA SVC-AN (SEFAZ VIRTUAL DE CONTINGÊNCIA DO AN)",
'7' => "CONTINGÊNCIA SVC-RS (SEFAZ VIRTUAL DE CONTINGÊNCIA DO RS)",
'9' => "CONTINGÊNCIA OFF-LINE DA NFC-E"
);
private static $FINNFE_OPTS = array(
'1' => "NF-E NORMAL",
'2' => "NF-E COMPLEMENTAR",
'3' => "NF-E DE AJUSTE",
'4' => "DEVOLUÇÃO",
);
private static $INDFINAL_OPTS = array(
'0' => "NÃO",
'1' => "CONSUMIDOR FINAL"
);
private static $INDPRES_OPTS = array(
'0' => "NÃO SE APLICA (POR EXEMPLO, NOTA FISCAL COMPLEMENTAR OU DE AJUSTE)",
'1' => "OPERAÇÃO PRESENCIAL",
'2' => "OPERAÇÃO NÃO PRESENCIAL, PELA INTERNET",
'3' => "OPERAÇÃO NÃO PRESENCIAL, TELEATENDIMENTO",
'4' => "NFC-E EM OPERAÇÃO COM ENTREGA A DOMICÍLIO",
'9' => "OPERAÇÃO NÃO PRESENCIAL, OUTROS"
);
private static $PROCEMI_OPTS = array(
'0' => "EMISSÃO DE NF-E COM APLICATIVO DO CONTRIBUINTE",
'1' => "EMISSÃO DE NF-E AVULSA PELO FISCO",
'2' => "EMISSÃO DE NF-E AVULSA, PELO CONTRIBUINTE COM SEU CERTIFICADO DIGITAL, ATRAVÉS DO SITE DO FISCO",
'3' => "EMISSÃO NF-E PELO CONTRIBUINTE COM APLICATIVO FORNECIDO PELO FISCO"
);
}
class NfeProdType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('cProd', null, array('label' => "Código do produto"))
->add('cEAN', null, array(
'label' => "cEAN",
'required' => false,
'attr' => array('placeholder' => "- opcional - ")
))
->add('xProd', null, array('label' => "Nome do produto"))
->add('NCM', 'text', array('label' => "NCM"))
->add('EXTIPI', null, array(
'label' => "EXTIPI",
'required' => false,
'attr' => array('placeholder' => "- opcional - ")
))
->add('CFOP', 'choice', array(
'label' => "CFOP",
'empty_value' => '- SELECIONE - ',
'empty_data' => null,
'choices' => self::$CFOP_OPTS,
'attr' => array('class' => "chosen_find")
))
->add('uCom', 'choice', array(
'label' => "Unidade comercial",
'choices' => self::$UNITS_OPTS,
'attr' => array('class' => "chosen_find")
))
->add('qCom', 'number', array(
'label' => "Quantidade comercial",
'grouping' => true,
'attr' => array('class' => "spinner")
))
->add('vUnCom', 'number', array(
'label' => "Valor unitário comercial (R$)",
'grouping' => true,
'attr' => array('class' => "spinner")
))
->add('vProd', 'number', array(
'label' => "Valor do produto (R$)",
'grouping' => true,
'attr' => array('class' => "spinner")
))
->add('cEANTrib', null, array(
'label' => "cEANTrib",
'required' => false,
'attr' => array('placeholder' => "- opcional - ")
))
->add('uTrib', 'choice', array(
'label' => "Unidade tributária",
'choices' => self::$UNITS_OPTS,
'attr' => array('class' => "chosen_find")
))
->add('qTrib', 'number', array(
'label' => "Quantidade tributária",
'grouping' => true,
'attr' => array('class' => "spinner")
))
->add('vUnTrib', 'number', array(
'label' => "Valor unitário tributário (R$)",
'grouping' => true,
'attr' => array('class' => "spinner")
))
->add('vFrete', 'number', array(
'label' => "Valor do frete (R$)",
'grouping' => true,
'required' => false,
'attr' => array('class' => "spinner")
))
->add('vSeg', 'number', array(
'label' => "Valor do seguro (R$)",
'grouping' => true,
'required' => false,
'attr' => array('class' => "spinner")
))
->add('vDesc', 'number', array(
'label' => "Valor do desconto (R$)",
'grouping' => true,
'required' => false,
'attr' => array('class' => "spinner")
))
->add('vOutro', 'number', array(
'label' => "Outros valores (R$)",
'grouping' => true,
'required' => false,
'attr' => array('class' => "spinner")
))
->add('indTot', null, array(
'label' => "Valor do item compõe o valor total da nota?",
'data' => 1,
'helpBlock' => '1 => O valor do item (vProd) compõe o valor total da NF-e'
))
->add('xPed', null, array(
'label' => "xPed",
'required' => false,
'attr' => array('placeholder' => "- opcional - ")
))
->add('nItemPed', null, array(
'label' => "nItemPed",
'required' => false,
'attr' => array('placeholder' => "- opcional - ")
))
->add('nFCI', null, array(
'label' => "nFCI",
'required' => false,
'attr' => array('placeholder' => "- opcional - ")
))
->add('ICMS', new NfeProdICMSType(), array('label' => "ICMS"))
->add('PIS', new NfeProdPISType(), array('label' => "PIS"))
->add('COFINS', new NfeProdCOFINSType(), array('label' => "COFINS"))
;
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array());
}
/**
* @return string
*/
public function getName()
{
return 'labone_bundle_orderbundle_nfe_prodtype';
}
private static $UNITS_OPTS = array(
'cx' => "CX",
'kit' => "KIT",
'mil' => "MIL",
'pca' => "PCA",
'pct' => "PCT",
'jg' => "JG",
'und' => "UND",
'bb' => "BB"
);
private static $CFOP_OPTS = array(
'5101' => "PRODUTO FABRICADO / VENDIDO DENTRO DO ESTADO",
'5102' => "PRODUTO NÃO FABRICADO / VENDIDO DENTRO DO ESTADO",
'6101' => "PRODUTO FABRICADO / VENDIDO FORA DO ESTADO",
'6102' => "PRODUTO NÃO FABRICADO / VENDIDO FORA DO ESTADO"
);
}
class NfeProdICMSType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('orig', null, array(
'label' => "Origem",
'data' => '0',
'helpBlock' => '0 => NACIONAL'
))
->add('csosn', null, array(
'label' => "csosn",
'data' => '102',
'helpBlock' => '102 => TRIBUTADA SEM PERMISSÃO DE CRÉDITO'
))
->add('modBC', null, array(
'label' => "Modalidade de determinação da BC",
'data' => 3,
'helpBlock' => '3 => VALOR DA OPERAÇÃO'
))
->add('vBC', null, array('label' => "Valor da BC", 'required' => false, 'attr' => array('placeholder' => "- opcional - ")))
->add('pRedBC', null, array('label' => "Percentual da Redução de BC", 'required' => false, 'attr' => array('placeholder' => "- opcional - ")))
->add('pICMS', null, array('label' => "Alíquota", 'required' => false, 'attr' => array('placeholder' => "- opcional - ")))
->add('vICMS', null, array('label' => "Valor", 'required' => false, 'attr' => array('placeholder' => "- opcional - ")))
->add('pCredSN', null, array('label' => "pCredSN", 'required' => false, 'attr' => array('placeholder' => "- opcional - ")))
->add('vCredICMSSN', null, array('label' => "vCredICMSSN", 'required' => false, 'attr' => array('placeholder' => "- opcional - ")))
->add('modBCST', null, array('label' => "modBCST", 'required' => false, 'attr' => array('placeholder' => "- opcional - ")))
->add('pMVAST', null, array('label' => "pMVAST", 'required' => false, 'attr' => array('placeholder' => "- opcional - ")))
->add('pRedBCST', null, array('label' => "pRedBCST", 'required' => false, 'attr' => array('placeholder' => "- opcional - ")))
->add('vBCST', null, array('label' => "vBCST", 'required' => false, 'attr' => array('placeholder' => "- opcional - ")))
->add('pICMSST', null, array('label' => "pICMSST", 'required' => false, 'attr' => array('placeholder' => "- opcional - ")))
->add('vICMSST', null, array('label' => "vICMSST", 'required' => false, 'attr' => array('placeholder' => "- opcional - ")))
->add('vBCSTRet', null, array('label' => "vBCSTRet", 'required' => false, 'attr' => array('placeholder' => "- opcional - ")))
->add('vICMSSTRet', null, array('label' => "vICMSSTRet", 'required' => false, 'attr' => array('placeholder' => "- opcional - ")))
;
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array());
}
/**
* @return string
*/
public function getName()
{
return 'labone_bundle_orderbundle_nfe_prod_icmstype';
}
}
class NfeProdPISType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('cst', null, array(
'label' => "cst",
'data' => '07',
'helpBlock' => '07 => TRIBUTAÇÃO ISENTA DE CONTRIBUIÇÃO'
))
->add('vBC', null, array('label' => "vBC", 'required' => false, 'attr' => array('placeholder' => "- opcional - ")))
->add('pPIS', null, array('label' => "pPIS", 'required' => false, 'attr' => array('placeholder' => "- opcional - ")))
->add('vPIS', null, array('label' => "vPIS", 'required' => false, 'attr' => array('placeholder' => "- opcional - ")))
->add('qBCProd', null, array('label' => "qBCProd", 'required' => false, 'attr' => array('placeholder' => "- opcional - ")))
->add('vAliqProd', null, array('label' => "vAliqProd", 'required' => false, 'attr' => array('placeholder' => "- opcional - ")))
;
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array());
}
/**
* @return string
*/
public function getName()
{
return 'labone_bundle_orderbundle_nfe_prod_pistype';
}
}
class NfeProdCOFINSType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('cst', null, array(
'label' => "cst",
'data' => '07',
'helpBlock' => '07 => TRIBUTAÇÃO ISENTA DE CONTRIBUIÇÃO'
))
->add('vBC', null, array('label' => "vBC", 'required' => false, 'attr' => array('placeholder' => "- opcional - ")))
->add('pCOFINS', null, array('label' => "pCOFINS", 'required' => false, 'attr' => array('placeholder' => "- opcional - ")))
->add('vCOFINS', null, array('label' => "vCOFINS", 'required' => false, 'attr' => array('placeholder' => "- opcional - ")))
->add('qBCProd', null, array('label' => "qBCProd", 'required' => false, 'attr' => array('placeholder' => "- opcional - ")))
->add('vAliqProd', null, array('label' => "vAliqProd", 'required' => false, 'attr' => array('placeholder' => "- opcional - ")))
;
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array());
}
/**
* @return string
*/
public function getName()
{
return 'labone_bundle_orderbundle_nfe_prod_cofinstype';
}
}
@fmertins
Copy link

Olá, legal, obrigado por compartilhar. Uma dica (minha opinião), no NfeController.php linha 51, como no bloco IF você dá um return, sugiro não usar else, pois fica um bloco else gigante e desnecessário.

De forma geral eu procuro evitar lógica com IF..ELSE onde um dos dois é a lógica principal e daí no outro só tem uma linha, e na lógica principal é um bloco de código gigante, de várias e várias linhas. Facilita a depuração e evita um nível de indentação... :-)

Abraços!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment