Lançado Adianti Framework 7.6!
Clique aqui para saber mais
Pegar dados do Item via Array Boa noite pessoal. Gostaria de uma ajuda, estou precisando pegar os dados de um Mestre Detalhe para complementar Nota Fiscal, já consigo pegar os dados do Mestre, mas não consigo pegar os itens, ocorre sempre o mesmo erro. Segue o código: ...
CM
Pegar dados do Item via Array  
Boa noite pessoal.

Gostaria de uma ajuda, estou precisando pegar os dados de um Mestre Detalhe para complementar Nota Fiscal, já consigo pegar os dados do Mestre, mas não consigo pegar os itens, ocorre sempre o mesmo erro.

Segue o código:

  1. <?php
  2. TTransaction::open('ourorio');              
  3.             $items  ComprasSub::where('compra_id''='$key)->load(); // O ERRO OCORRE SEMPRE NESTA LINHA, SEI QUE FALTA ALGO, MAS NÃO CONSEGUI IDENTIFICAR.
  4.             
  5.             foreach($items as $key => $itemCompra) {
  6.                 $item = array(
  7.                     "numero_item" => strval($key 1),
  8.                     "codigo_produto" => $itemCompra->codigo,
  9.                     "descricao" => $itemCompra->descricao,
  10.                     "codigo_ncm" => $item->codigo_ncm,
  11.                     "cfop" => $item->cfop,
  12.                     "unidade_comercial" =>  $item->unidade,
  13.                     "quantidade_comercial" =>  $item->quantidade,
  14.                     "valor_unitario_comercial" =>  $item->valor_unit,
  15.                     "valor_bruto" =>  $item->subtotal,
  16.                     "unidade_tributavel" => $item->unidade,
  17.                     "quantidade_tributavel" => $item->quantidade,
  18.                     "valor_unitario_tributavel" => $item->valor_unit,
  19.                     "origem" => "0",
  20.                     "inclui_no_total" => "1",
  21.                     "imposto" => array(
  22.                         "valor_total_tributos" => 0,
  23.                         "icms" => array(
  24.                             "situacao_tributaria" => "102",  // meio fixo, ver com o contador
  25.                             "aliquota_credito_simples" => "0",
  26.                             "valor_credito_simples" => "0",
  27.                             "modalidade_base_calculo" => "3",
  28.                             "valor_base_calculo" => "0.00",
  29.                             "modalidade_base_calculo_st" => "4",
  30.                             "aliquota_reducao_base_calculo" => "0.00",
  31.                             "aliquota" => "0.00",
  32.                             "aliquota_final" => "0.00",
  33.                             "valor" => "0.00",
  34.                             "aliquota_margem_valor_adicionado_st" => "0.00",
  35.                             "aliquota_reducao_base_calculo_st" => "0.00",
  36.                             "aliquota_base_calculo_st" => "0.00",
  37.                             "aliquota_st" => "0.00",
  38.                             "valor_st" => "0.00"
  39.                         ),
  40. ?>

Curso completo Meu Negócio Pronto
Use para si, ou transforme em um negócio: Inclui aulas e códigos-fontes
Gestor de conteúdo (SITE) + Loja Virtual (E-Commerce) + Emissor de Notas para infoprodutos


Meu negócio pronto Quero me inscrever agora!

Comentários (4)


NR

Qual o erro?
CM

Desculpe Nataniel, não postei o erro.
Vou postar o código completo e informar o erro pra ficar mais fácil entender.
Obrigado

Este é o erro:
  1. <?php 
  2. Notice:  Undefined variablekey in C:\xampp\htdocs\adianti\ourorio\app\control\ourorio\ComprasFormMaster.php on line 950
  3. array(1) {
  4.   [0]=>
  5.   object(stdClass)#17 (4) {
  6.     ["campo"]=>
  7.     string(5"itens"
  8.     ["erro"]=>
  9.     string(40"[] - A propriedade itens é obrigatório"
  10.     ["descricao"]=>
  11.     string(0""
  12.     ["detalhes"]=>
  13.     string(0""
  14.   }
  15. }
  16. ?>


Aqui o código completo.
  1. <?php 
  2. class ComprasFormMaster extends TPage
  3. {
  4.     protected $form// form
  5.     protected $detail_list;
  6.     
  7.     public function __construct()
  8.     {
  9.         parent::__construct();
  10.    
  11.         TButton::disableField('form_Compras''btn_recibo_compra');
  12.         // creates the form
  13.         $this->form = new BootstrapFormBuilder('form_Compras');
  14.         $this->form->setFormTitle('REGISTRO COMPRA');
  15.         $this->form->setFieldSizes('100%');
  16.         // master fields
  17.         $id_compra         = new TEntry('id_compra');
  18.         $data_compra       = new TDate('data_compra');
  19.         $tipo_compra_txt   = new TEntry('tipo_compra_txt');
  20.         $finalizada        = new THidden('finalizada');
  21.        
  22.         $criteria = new TCriteria;
  23.         $criteria->setProperty('order''nome_cliente');
  24.         $cliente_id = new  ">TDBSeekButton('cliente_id''ourorio''form_Compras''Clientes''nome_cliente''cliente_id''cliente_txt'$criteria);
  25.         $cliente_txt = new TEntry('cliente_txt');
  26.         $cliente_txt->setEditable(FALSE);
  27.         
  28.        // define ação de saída do campo
  29.         $cliente_id->setExitAction(new TAction(array($this'onExitCliente')));
  30.         
  31.         $cliente_cep                = new THidden('cliente_cep');
  32.         $cliente_endereco_tipo      = new THidden('cliente_endereco_tipo');
  33.         $cliente_endereco           = new THidden('cliente_endereco');
  34.         $cliente_endereco_numero    = new THidden('cliente_endereco_numero');
  35.         $cliente_endereco_complem   = new THidden('cliente_endereco_complem');
  36.         $cliente_bairro             = new THidden('cliente_bairro');
  37.         $cliente_cidade             = new THidden('cliente_cidade');
  38.         $cliente_codigo_municipio   = new THidden('cliente_codigo_municipio');
  39.         $cliente_estado             = new THidden('cliente_estado');
  40.         $cliente_telefone           = new THidden('cliente_telefone');
  41.         $cliente_nascimento         = new THidden('cliente_nascimento');
  42.         $cliente_identidade         = new THidden('cliente_identidade');
  43.         $cliente_email              = new THidden('cliente_email');
  44.         $cliente_cpf                = new THidden('cliente_cpf');
  45.         $anexo_nf_joia_cliente      = new TMultiFile('anexo_nf_joia_cliente');
  46.         $vendedor_txt               = new TEntry('vendedor_txt');
  47.         $vendedor_id                = new THidden('vendedor_id');
  48.         $loja_id                    = new TEntry('loja_id');
  49.         $loja_id                    = new THidden('loja_id');
  50.         $loja_txt                   = new TEntry('loja_txt');
  51.         $loja_cnpj                  = new TEntry('loja_cnpj');
  52.         $loja_cnpj                  = new THidden('loja_cnpj');
  53.         $movimento_fechado          = new TEntry('movimento_fechado');
  54.         $movimento_fechado_em       = new TDate('movimento_fechado_em');
  55.         $valor_total                = new TEntry('valor_total');
  56.         
  57.        //Campos Obrigatórios
  58.         $cliente_id->addValidation('Id do Cliente', new TRequiredValidator);
  59.         $cliente_txt->addValidation('Nome do Cliente', new TRequiredValidator);
  60.         $data_compra->addValidation('Data da Compra', new TRequiredValidator);
  61.         $valor_total->addValidation('Valor da Compra', new TRequiredValidator);
  62.     
  63.         // máscara Master
  64.         $data_compra ->setDatabaseMask('yyyy-mm-dd');
  65.         $data_compra ->setMask('dd/mm/yyyy');
  66.         $data_compra->setValue(date("Y-m-d"));
  67.         $loja_id->setEditable(FALSE);
  68.         $loja_txt->setEditable(FALSE);
  69.         $vendedor_txt->setEditable(FALSE);
  70.         $finalizada->setValue(0);
  71.         $loja_id->setValue(TSession::getValue('userunitid')) ; //id da unidade
  72.         $loja_txt->setValue(TSession::getValue('userunitname')); //nome da unidade
  73.         $loja_cnpj->setValue(TSession::getValue('loja_cnpj')); //cnpj da unidade
  74.         $vendedor_txt->setValue(TSession::getValue('username')); //nome do usuário
  75.         $vendedor_id->setValue(TSession::getValue('userid'));//id usua
  76.         // set sizes Master
  77.         $cliente_id->setSize('100%');
  78.         $cliente_txt->setSize('100%');
  79.         $vendedor_txt->setSize('100%');
  80.         $loja_txt->setSize('100%');
  81.         // detail fields
  82.         $detail_uniqid            = new THidden('detail_uniqid');
  83.         $detail_id_automatico     = new THidden('detail_id_automatico');
  84.         $detail_data_compra_sub   = new THidden('detail_data_compra_sub');
  85.         $detail_loja_sub_id       = new THidden('detail_loja_sub_id');
  86.         $detail_loja_sub_txt      = new THidden('detail_loja_sub_txt');
  87.         $detail_vendedor_sub_id   = new THidden('detail_vendedor_sub_id');
  88.         $detail_vendedor_sub_txt  = new THidden('detail_vendedor_sub_txt');
  89.         $detail_quantidade        = new TEntry('detail_quantidade');
  90.         $detail_quantidade        = new TNumeric('detail_quantidade'2''''true);
  91.         $detail_unidade           = new TEntry('detail_unidade');
  92.         $detail_descricao         = new TEntry('detail_descricao');
  93.         $detail_valor_unit        = new TEntry('detail_valor_unit');
  94.         $detail_subtotal          = new TEntry('detail_subtotal');
  95.         $detail_tipo_compra_id    = new TDBCombo('detail_tipo_compra_id''ourorio''ComprasTipo''id_tipo_compra''descricao','descricao');
  96.         $detail_tipo_compra_txt   = new TEntry('detail_tipo_compra_txt');
  97.         $detail_tipo_compra_txt   = new THidden('detail_tipo_compra_txt');
  98.         $detail_kilate_id         = new TDBCombo('detail_kilate_id''ourorio''ComprasKilate''id_kilate''descricao_kilate','descricao_kilate');
  99.         $detail_kilate_txt        = new TEntry('detail_kilate_txt');
  100.         $cfop                     = new THidden('cfop');
  101.         $codigo_ncm               = new THidden('codigo_ncm');
  102.         $cest                     = new THidden('cest');
  103.         $origem                   = new THidden('origem');
  104.         $detail_subtotal->setEditable(FALSE);
  105.         // define ação ao Sair doo Campo
  106.         $detail_quantidade->setExitAction(new TAction(array($this'onUpdateTotal')));
  107.         $detail_valor_unit->setExitAction(new TAction(array($this'onUpdateTotal')));
  108.         // define ação ao alterar a Combo
  109.         $detail_tipo_compra_id->setChangeAction(new TAction(array($this'onChangeTipoCompra')));
  110.         $detail_kilate_id->setChangeAction(new TAction(array($this'onChangeKilate')));
  111.                
  112.         // mascara detalhes
  113.         $detail_descricao->forceUpperCase();
  114.         $detail_unidade->forceUpperCase();
  115.         $detail_unidade->setValue('GR');
  116.         $detail_quantidade->setNumericMask(2',''.'truetrue);
  117.         $detail_valor_unit->setNumericMask(2',''.'true);
  118.         $detail_subtotal->setNumericMask(2',''.'true);
  119.         $detail_data_compra_sub->setValue(date("Y-m-d"));
  120.         $detail_loja_sub_id->setValue($loja_id);
  121.         $detail_loja_sub_txt->setValue($loja_txt);
  122.         $detail_vendedor_sub_id->setValue($vendedor_id);
  123.         $detail_vendedor_sub_txt->setValue($vendedor_txt);
  124.         if (!empty($id_compra))
  125.         {
  126.             $id_compra->setEditable(FALSE);
  127.         } else {
  128.             $finalizada 0;
  129.         }
  130.         // master fields
  131.         $row $this->form->addFields ([new TLabel('Código')], [$id_compra] ,
  132.                                        [new TLabel('Data')], [$data_compra] ,
  133.                                        [new TLabel('Oper.')], [$vendedor_txt],
  134.                                        [new THidden('Loja')], [$loja_txt],
  135.                                        [new THidden('CNPJ')], [$loja_cnpj]);
  136.         $row->layout = ['col-sm-1','col-sm-2','col-sm-1','col-sm-2','col-sm-1','col-2','col-sm-0','col-3','col-sm-0','col-0'];
  137.         
  138.         $row $this->form->addFields( [new TLabel('Anexo N.F. Joia')], [$anexo_nf_joia_cliente],
  139.                                        [new TLabel('ID')], [$cliente_id],
  140.                                        [new TLabel('Cliente')], [$cliente_txt]);
  141.         $row->layout = ['col-sm-1''col-sm-2','col-sm-1''col-sm-2','col-sm-1''col-sm-5'];
  142.         
  143.                                         
  144.         $row $this->form->addFields([new THidden('CEP')], [$cliente_cep],
  145.                                       [new THidden('Tipo')], [$cliente_endereco_tipo],
  146.                                       [new THidden('Endereço')], [$cliente_endereco],
  147.                                       [new THidden('Compl')], [$cliente_endereco_complem],
  148.                                       [new THidden('Numero')], [$cliente_endereco_numero],
  149.                                       [new THidden('Bairro')], [$cliente_bairro],
  150.                                       [new THidden('Cidade')], [$cliente_cidade],
  151.                                       [new THidden('Cód. Mun.')], [$cliente_codigo_municipio],
  152.                                       [new THidden('Estado')], [$cliente_estado],
  153.                                       [new THidden('Telefone')], [$cliente_telefone],
  154.                                       [new THidden('Nasc')], [$cliente_nascimento],
  155.                                       [new THidden('Identidade')], [$cliente_identidade],
  156.                                       [new THidden('Email')], [$cliente_email],
  157.                                       [new THidden('CPF')], [$cliente_cpf] );
  158.         $row->layout = ['col-sm-1','col-sm-1','col-sm-1','col-sm-1','col-sm-1','col-sm-1','col-sm-1','col-sm-1','col-sm-1','col-sm-1','col-sm-1','col-sm-1','col-sm-1','col-sm-1''col-sm-2''col-sm-1','col-sm-2''col-sm-1','col-sm-2''col-sm-1','col-sm-2''col-sm-1','col-sm-2''col-sm-1','col-sm-2''col-sm-1','col-sm-2','col-sm-1','col-sm-2'];
  159.         
  160.         $row $this->form->addFields([new THidden('ID')], [$loja_id] );
  161.         $row->layout = ['col-sm-1''col-sm-3','col-sm-1''col-sm-3','col-sm-1','col-sm-3'];
  162.         
  163.         // detail fields
  164.         $this->form->addContent( ['<h4>Item(s) da Compra</h4><hr>'] );
  165.         $this->form->addFields( [$detail_uniqid] );
  166.         $this->form->addFields( [$detail_id_automatico] );
  167.         
  168.         $row $this->form->addFields( [new TLabel('Tipo')], [$detail_tipo_compra_id],
  169.                                        [new TLabel('Kilate')], [$detail_kilate_id],
  170.                                        [new TLabel('Quant')], [$detail_quantidade],
  171.                                        [new TLabel('Unidade')], [$detail_unidade] );
  172.         $row->layout = ['col-sm-1''col-sm-2','col-sm-1','col-sm-2','col-sm-1','col-sm-2','col-sm-1','col-sm-2'];
  173.         
  174.         $row $this->form->addFields([new THidden('TipoTxt')], [$detail_tipo_compra_txt],
  175.                                       [new THidden('KilateTxt')], [$detail_kilate_txt],
  176.                                       [new THidden('Data Compra')], [$detail_data_compra_sub]);
  177.         $row->layout = ['col-sm-1''col-sm-2','col-sm-1','col-sm-2','col-sm-1','col-sm-2'];
  178.         
  179.         
  180.         $row $this->form->addFields( [new TLabel('Produto')], [$detail_descricao],
  181.                                        [new TLabel('Valor')], [$detail_valor_unit],                                  
  182.                                        [new TLabel('Subtotal')], [$detail_subtotal]);
  183.         $row->layout = ['col-sm-1''col-sm-5','col-sm-1','col-sm-2','col-sm-1','col-sm-2'];
  184.     
  185.         $btn_add TButton::create('add', [$this'onDetailAdd'], 'Lança Produto''fa:plus-circle green');
  186.         $btn_add->getAction()->setParameter('static','1');
  187.         $this->form->addFields( [], [$btn_add] );
  188.         
  189.         
  190.         $this->detail_list = new BootstrapDatagridWrapper(new TDataGrid);
  191.         $this->detail_list->setId('ComprasSub_list');
  192.         $this->detail_list->generateHiddenFields();
  193.         $this->detail_list->style "min-width: 700px; width:100%;margin-bottom: 10px";
  194.         
  195.         // items
  196.         $this->detail_list->addColumn( new TDataGridColumn('uniqid''Uniqid''center') )->setVisibility(false);
  197.         $this->detail_list->addColumn( new TDataGridColumn('id_automatico''Id''center') )->setVisibility(false);
  198.         $quant $this->detail_list->addColumn( new TDataGridColumn('quantidade''Quant''right'50) );
  199.         $this->detail_list->addColumn( new TDataGridColumn('unidade''Unid''center'50) );
  200.        
  201.         $this->detail_list->addColumn( new TDataGridColumn('descricao''Descrição''left'100) );
  202.         $this->detail_list->addColumn( new TDataGridColumn('tipo_compra_txt''Tipo''left'50) );
  203.         $this->detail_list->addColumn( new TDataGridColumn('kilate_txt''Kilate''left'50) );
  204.         $vlr_unit $this->detail_list->addColumn( new TDataGridColumn('valor_unit''Valor Unit''right'50) );
  205.         $this->detail_list->addColumn( new TDataGridColumn('loja_sub_id''Loja Id''left'100) )->setVisibility(false);
  206.         $this->detail_list->addColumn( new TDataGridColumn('loja_sub_txt''Loja txt''left'100) )->setVisibility(false);
  207.         $this->detail_list->addColumn( new TDataGridColumn('vendedor_sub_id''Vendedor id''left'100) )->setVisibility(false);
  208.         $this->detail_list->addColumn( new TDataGridColumn('vendedor_sub_txt''Vendedor txt''left'100) )->setVisibility(false);
  209.         $this->detail_list->addColumn( new TDataGridColumn('tipo_compra_id''Tipo Compra Id''left'50))->setVisibility(false);
  210.         $this->detail_list->addColumn( new TDataGridColumn('kilate_id''Kilate Id''left'50) )->setVisibility(false);
  211.         $this->detail_list->addColumn( new TDataGridColumn('data_compra_sub''Data Compra''left'50) )->setVisibility(false);
  212.  
  213.         $formula '={quantidade} * {valor_unit}';
  214.         $st $this->detail_list->addColumn( new TDataGridColumn($formula'SubTotal''right'100) );
  215.         
  216.         // definir o método do transformador sobre o Valor
  217.         $format_value = function($value) {
  218.             if (is_numeric($value))
  219.             {
  220.                 return ' ' number_format($value2',''.');
  221.             }
  222.             return $value;
  223.             };
  224.         $st->setTransformer($format_value);
  225.         $vlr_unit->setTransformer($format_value);
  226.         $quant->setTransformer($format_value);
  227.         
  228.         
  229.         // detail actions
  230.         $btn_edita_item = new TDataGridAction([$this'onDetailEdit'] );
  231.         //$btn_edita_item->setDisplayCondition( array($this, 'mostrar') );
  232.         $btn_edita_item->setFields( ['uniqid''*'] );    
  233.         
  234.         
  235.         $btn_deleta_item = new TDataGridAction([$this'onDetailDelete']);
  236.         //$btn_deleta_item->setDisplayCondition( array($this, 'mostrar') );
  237.         $btn_deleta_item->setField('uniqid');
  238.         
  239.         // add the actions to the datagrid
  240.         $this->detail_list->addAction($btn_edita_item_t('Edit'), 'fa:edit blue');
  241.         $this->detail_list->addAction($btn_deleta_item_t('Delete'), 'far:trash-alt red');
  242.        
  243.         
  244.         $this->detail_list->createModel();
  245.         
  246.         $panel = new TPanelGroup;
  247.         $panel->add($this->detail_list);
  248.         $panel->getBody()->style 'overflow-x:auto';
  249.         $this->form->addContent( [$panel] );
  250.         
  251.         $btn_gravar $this->form->addAction'SALVAR',  new TAction([$this'onSave'], ['static'=>'1']), 'fa:save white');
  252.         $btn_gravar->class 'btn btn-sm btn-primary';
  253.         
  254.         $btn_voltar $this->form->addAction('VOLTAR',new TAction(array('ComprasList','onReload')),'far:arrow-alt-circle-left white');
  255.         $btn_voltar->class 'btn btn-sm btn-danger';
  256.         
  257.         Tbutton::disablefield('form_Compras','btn_print');
  258.         //BOTÃO PARA GERAR PDF
  259.         $btn_print $this->form->addAction('RECIBO COMPRA', new TAction(array($this'OnPDF')),'fa:print white');
  260.         $btn_print->class 'btn btn-sm btn-secondary';
  261.    
  262.         $btn_nfe $this->form->addAction('GERAR NFe', new TAction(array($this'OnNfe')),'fa:print white');
  263.         $btn_nfe->class 'btn btn-sm btn-success';
  264.         $btn_cancelar_nfe $this->form->addAction('CANCELAR NFe', new TAction(array($this'OnCancelarNfe')),'fa:print white');
  265.         $btn_cancelar_nfe->class 'btn btn-sm btn-danger';
  266.         //BOTÃO FINALIZAR
  267.         //$btn_finaliza = $this->form->addAction('FINALIZA', new TAction(array($this, 'onConfirma')),'far:arrow-alt-circle-left white');
  268.         //$btn_finaliza->class = 'btn btn-sm btn-secondary';
  269.         //Tbutton::disablefield('form_Compras','btn_finaliza');
  270.         // create the page container
  271.         $container = new TVBox;
  272.         $container->style 'width: 100%';
  273.         // $container->add(new TXMLBreadCrumb('menu.xml', __CLASS__));
  274.         $container->add(TBreadCrumb::create(['COMPRAS''REGISTRO DE COMPRA']));
  275.         $container->add($this->form);
  276.         parent::add($container);
  277.     }
  278.     
  279.         
  280.     /**
  281.      * Clear form
  282.      * @param $param URL parameters
  283.      */
  284.     public function onClear($param)
  285.     {
  286.         $this->form->clear(TRUE);
  287.     }
  288.     
  289.     /**
  290.      * Add detail item
  291.      * @param $param URL parameters
  292.      */
  293.     public function onDetailAdd$param )
  294.     {
  295.         try
  296.         {
  297.             $this->form->validate();
  298.             $data $this->form->getData();
  299.         
  300.             (new TRequiredValidator)->validate("Tipo de Compra"$data->detail_tipo_compra_id);
  301.             (new TRequiredValidator)->validate("Kilate do Produto"$data->detail_kilate_id);
  302.             (new TRequiredValidator)->validate("Quantidade"$data->detail_quantidade);
  303.             (new TRequiredValidator)->validate("Unidade"$data->detail_unidade);
  304.             (new TRequiredValidator)->validate("Produto"$data->detail_descricao);
  305.             
  306.             $uniqid = !empty($data->detail_uniqid) ? $data->detail_uniqid uniqid();
  307.             
  308.             $grid_data = [];
  309.             $grid_data['uniqid']            = $uniqid;
  310.             $grid_data['id_automatico']     = $data->detail_id_automatico;
  311.             $grid_data['data_compra_sub']   = $data->detail_data_compra_sub;
  312.             $grid_data['quantidade']        = $data->detail_quantidade;
  313.             $grid_data['descricao']         = $data->detail_descricao;
  314.             $grid_data['unidade']           = $data->detail_unidade;
  315.             $grid_data['valor_unit']        = $data->detail_valor_unit;
  316.             $grid_data['subtotal']          = $data->detail_subtotal;
  317.             $grid_data['tipo_compra_id']    = $data->detail_tipo_compra_id;
  318.             $grid_data['tipo_compra_txt']   = $data->detail_tipo_compra_txt;
  319.             $grid_data['kilate_id']         = $data->detail_kilate_id;
  320.             $grid_data['kilate_txt']        = $data->detail_kilate_txt;
  321.             $grid_data['cfop']              = $data->cfop;
  322.             $grid_data['codigo_ncm']        = $data->codigo_ncm;
  323.             $grid_data['cest']              = $data->cest;
  324.             $grid_data['origem']            = $data->origem;
  325.             
  326.             $grid_data['data_compra_sub']   = $data->data_compra;
  327.             $grid_data['loja_sub_id']       = $data->loja_id;
  328.             $grid_data['loja_sub_txt']      = $data->loja_txt;
  329.             $grid_data['vendedor_sub_id']   = $data->vendedor_id;
  330.             $grid_data['vendedor_sub_txt']  = $data->vendedor_txt;
  331.         
  332.             // insert row dynamically
  333.             $row $this->detail_list->addItem( (object) $grid_data );
  334.             $row->id $uniqid;
  335.             
  336.             TDataGrid::replaceRowById('ComprasSub_list'$uniqid$row);
  337.             
  338.             // clear detail form fields
  339.             $data->detail_uniqid '';
  340.             $data->detail_id_automatico '';
  341.             $data->detail_data_compra_sub '';
  342.             $data->detail_quantidade '';
  343.             $data->detail_descricao '';
  344.             $data->detail_unidade '';
  345.             $data->detail_valor_unit '';
  346.             $data->detail_subtotal '';
  347.             $data->detail_tipo_compra_id '';
  348.             $data->detail_tipo_compra_txt '';
  349.             $data->detail_kilate_id '';
  350.             $data->detail_kilate_txt '';
  351.             $data->detail_cfop '';
  352.             $data->detail_codigo_ncm '';
  353.             $data->detail_cest '';
  354.             $data->detail_origem '';
  355.             $data->detail_loja_sub_id '';
  356.             $data->detail_loja_sub_txt '';
  357.             $data->detail_vendedor_sub_id '';
  358.             $data->detail_vendedor_sub_txt '';
  359.             
  360.             // send data, do not fire change/exit events
  361.             TForm::sendData'form_Compras'$datafalsefalse );
  362.         }
  363.         catch (Exception $e)
  364.         {
  365.             $this->form->setData$this->form->getData());
  366.             new TMessage('error'$e->getMessage());
  367.         }
  368.     }
  369.     
  370.     /**
  371.      * Edit detail item
  372.      * @param $param URL parameters
  373.      */
  374.     public static function onDetailEdit$param )
  375.     {
  376.         $data = new stdClass;
  377.         $data->detail_uniqid             $param['uniqid'];
  378.         $data->detail_id_automatico      $param['id_automatico'];
  379.         $data->detail_quantidade         number_format($param['quantidade'],2,',','.');
  380.         $data->detail_descricao          utf8_decode($param['descricao']);
  381.         $data->detail_unidade            utf8_decode($param['unidade']);
  382.         $data->detail_valor_unit         number_format($param['valor_unit'],2,',','.');
  383.         $data->detail_subtotal           number_format($param['subtotal'],2,',','.');
  384.         $data->detail_tipo_compra_id     $param['tipo_compra_id'];
  385.         $data->detail_tipo_compra_txt    utf8_decode($param['tipo_compra_txt']);
  386.         $data->detail_kilate_id          $param['kilate_id'];
  387.         $data->detail_kilate_txt         utf8_decode($param['kilate_txt']);
  388.         $data->detail_loja_sub_id        $param['loja_sub_id'];
  389.         $data->detail_loja_sub_txt       utf8_decode($param['loja_sub_txt']);
  390.         $data->detail_vendedor_sub_id    $param['vendedor_sub_id'];
  391.         $data->detail_vendedor_sub_txt   utf8_decode($param['vendedor_sub_txt']);
  392.         
  393.         // send data, do not fire change/exit events
  394.         TForm::sendData'form_Compras'$datafalsefalse );
  395.         
  396.     }
  397.     
  398.     /**
  399.      * Delete detail item
  400.      * @param $param URL parameters
  401.      */
  402.     public static function onDetailDelete$param )
  403.     {
  404.         // clear detail form fields
  405.         $data = new stdClass;
  406.         $data->detail_uniqid '';
  407.         $data->detail_id_automatico '';
  408.         $data->detail_data_compra_sub '';
  409.         $data->detail_quantidade '';
  410.         $data->detail_descricao '';
  411.         $data->detail_unidade '';
  412.         $data->detail_valor_unit '';
  413.         $data->detail_subtotal '';
  414.         $data->detail_tipo_compra_id '';
  415.         $data->detail_tipo_compra_txt '';
  416.         $data->detail_kilate_id '';
  417.         $data->detail_kilate_txt '';
  418.         $data->detail_cfop '';
  419.         $data->detail_codigo_ncm '';
  420.         $data->detail_cest '';
  421.         $data->detail_origemt '';
  422.         $data->detail_loja_sub_id '';
  423.         $data->detail_loja_sub_txt '';
  424.         $data->detail_vendedor_sub_id '';
  425.         $data->detail_vendedor_sub_txt '';
  426.         
  427.         // send data, do not fire change/exit events
  428.         TForm::sendData'form_Compras'$datafalsefalse );
  429.         
  430.         // remove row
  431.         TDataGrid::removeRowById('ComprasSub_list'$param['uniqid']);
  432.     }
  433.     
  434.    
  435.     public function onEdit($param)
  436.     {
  437.         try
  438.         {
  439.             TTransaction::open('ourorio');
  440.                
  441.             if (isset($param['key']))
  442.             {
  443.                 $key $param['key'];
  444.                 
  445.                 $object = new Compras($key);
  446.                 
  447.                  //Bloquear campos de acordo com o Status
  448.                 if ($object->finalizada == 0
  449.                   { 
  450.                    TDate::enableField('form_Compras''data_compra');
  451.                    TDBCombo::enableField('form_Compras''cliente_id');
  452.                     ">TDBSeekButton::enableField('form_Compras''cliente_id');
  453.                    TButton::enableField('form_Compras''btn_limpar');
  454.                    TButton::enableField('form_Compras''btn_salvar'); 
  455.                    TButton::disableField('form_Compras''btn_recibo_compra');
  456.                   }
  457.                if ($object->finalizada== 1
  458.                   { 
  459.                    TDate::disableField('form_Compras''data_compra');
  460.                    TDBCombo::disableField('form_Compras''cliente_id');
  461.                    TButton::disableField('form_Compras''btn_limpar');
  462.                    TButton::disableField('form_Compras''btn_salvar'); 
  463.                    TButton::enableField('form_Compras''btn_recibo_compra');
  464.                   }
  465.                    
  466.                 
  467.                 $items  ComprasSub::where('compra_id''='$key)->load();
  468.                 
  469.                 foreach( $items as $item )
  470.                 {
  471.                     $item->uniqid uniqid();
  472.                     $row $this->detail_list->addItem$item );
  473.                     $row->id $item->uniqid;
  474.                 }
  475.                 $this->form->setData($object);
  476.                 TTransaction::close();
  477.             }
  478.             else
  479.             {
  480.                 $this->form->clear(TRUE);
  481.             }
  482.         }
  483.         catch (Exception $e// in case of exception
  484.         {
  485.             new TMessage('error'$e->getMessage());
  486.             TTransaction::rollback();
  487.         }
  488.     }
  489.     
  490.    
  491.     public function onSave($param)
  492.     {
  493.         try
  494.         {
  495.             // open a transaction with database
  496.             TTransaction::open('ourorio');
  497.             
  498.             $data $this->form->getData();
  499.             $this->form->validate();
  500.             $master = new Compras;
  501.             $master->fromArray( (array) $data);
  502.             $master->store(); 
  503.             ComprasSub::where('compra_id''='$master->id_compra)->delete();
  504.             if( $param['ComprasSub_list_quantidade'] )
  505.             {
  506.                 foreach( $param['ComprasSub_list_quantidade'] as $key => $item_id )
  507.                 {
  508.                     $detail = new ComprasSub;
  509.                     $detail->quantidade       $param['ComprasSub_list_quantidade'][$key];
  510.                     $detail->data_compra_sub  $param['ComprasSub_list_data_compra_sub'][$key];
  511.                     $detail->descricao        utf8_decode($param['ComprasSub_list_descricao'][$key]);
  512.                     $detail->unidade          utf8_decode($param['ComprasSub_list_unidade'][$key]);
  513.                     $detail->valor_unit       $param['ComprasSub_list_valor_unit'][$key];
  514.                     $detail->tipo_compra_id   $param['ComprasSub_list_tipo_compra_id'][$key];
  515.                     $detail->tipo_compra_txt  utf8_decode($param['ComprasSub_list_tipo_compra_txt'][$key]);
  516.                     $detail->kilate_id        $param['ComprasSub_list_kilate_id'][$key];
  517.                     $detail->kilate_txt       utf8_decode($param['ComprasSub_list_kilate_txt'][$key]);
  518.                     $detail->cfop             utf8_decode($param['ComprasSub_list_cfop'][$key]);
  519.                     $detail->codigo_ncm       utf8_decode($param['ComprasSub_list_codigo_ncm'][$key]);
  520.                     $detail->cest             utf8_decode($param['ComprasSub_list_cest'][$key]);
  521.                     $detail->origem           utf8_decode($param['ComprasSub_list_origem'][$key]);
  522.                     $detail->loja_sub_id      $param['ComprasSub_list_loja_sub_id'][$key];
  523.                     $detail->loja_sub_txt     utf8_decode($param['ComprasSub_list_loja_sub_txt'][$key]);
  524.                     $detail->vendedor_sub_id  $param['ComprasSub_list_vendedor_sub_id'][$key];
  525.                     $detail->vendedor_sub_txt utf8_decode($param['ComprasSub_list_vendedor_sub_txt'][$key]);
  526.                     $detail->compra_id       $master->id_compra;
  527.                     
  528.                     $detail->subtotal = ($detail->quantidade $detail->valor_unit);
  529.                     
  530.                     $master->valor_total += $detail->subtotal;
  531.                     $detail->store();
  532.                 }
  533.             }
  534.                     //FINALIZAR A VENDA
  535.                     $master->finalizada 1;
  536.                     $master->loja_id TSession::getValue('userunitid') ; //id da unidade
  537.                     $master->loja_txt =TSession::getValue('userunitname'); //nome da unidade
  538.                     $master->vendedor_txt =TSession::getValue('username'); //nome do usuário
  539.                     $master->vendedor_id =TSession::getValue('userid');//id usuario
  540.                     $master->store();
  541.             TTransaction::close(); // close the transaction
  542.             
  543.             TForm::sendData('form_Compras', (object) ['id' => $master->id_compra]);
  544.      
  545.             TToast::show('show','COMPRA GRAVADA COM SUCESSO!''center''fas fa-check');
  546.             AdiantiCoreApplication::loadPage'ComprasList' );
  547.             exit;
  548.             //$param["id_compra"]=$master->id_compra;
  549.             //$this->OnPDF($param);
  550.         }
  551.         catch (Exception $e// in case of exception
  552.         {
  553.             new TMessage('error'$e->getMessage());
  554.             $this->form->setData$this->form->getData() ); // keep form data
  555.             TTransaction::rollback();
  556.         }
  557.     }
  558.     
  559.      public function OnPDF($param)
  560.     {
  561.     
  562.      // open a transaction with database 'samples'
  563.       TTransaction::open('ourorio');
  564.     
  565.      
  566.      // load all customers
  567.      $repository = new TRepository('ComprasSub');
  568.      $criteria = new TCriteria;
  569.      $ComprasSub $repository->load($criteria);
  570.     setlocale(LC_TIME'portuguese');
  571.     date_default_timezone_set('America/Sao_Paulo');
  572.     $data_atual strftime("%A, %d de %B de %Y"strtotime(date("Y-m-d")));
  573.      $data $this->form->getData('ComprasSub');
  574.      $this->form->validate();
  575.   
  576.      $pdf = new TPDFDesigner;
  577.      $pdf->fromXml('app/reports/recibo_compra_cliente.pdf.xml');
  578.    
  579.    // cabeçalho
  580.      $pdf->replace('{id_compra}',$data->id_compra);
  581.      $pdf->replace('{data_compra}',DateTime::createFromFormat('Y-m-d'$data->data_compra)->format'd/m/Y' ));
  582.      $pdf->replace('{cliente_txt}',utf8_decode($data->cliente_txt));
  583.      $pdf->replace('{endereco_tipo}',utf8_decode($data->cliente_endereco_tipo), 00'L');
  584.      $pdf->replace('{endereco_numero}',utf8_decode($data->cliente_endereco_numero), 00'L');
  585.      $pdf->replace('{endereco}',utf8_decode($data->cliente_endereco), 00'L');
  586.      $pdf->replace('{bairro}',utf8_decode($data->cliente_bairro), 00'L');
  587.   
  588.      $pdf->replace('{cpf}',utf8_decode($data->cliente_cpf), 00'L');
  589.      $pdf->replace('{identidade}',utf8_decode($data->cliente_identidade), 00'L');
  590.      $pdf->replace('{telefone}',utf8_decode($data->cliente_telefone), 00'L');
  591.      $pdf->replace('{nascimento}',DateTime::createFromFormat('Y-m-d'$data->cliente_nascimento)->format'd/m/Y' ));
  592.      $pdf->replace('{cidade}',utf8_decode($data->cliente_cidade), 00'L');
  593.      $pdf->replace('{estado}',utf8_decode($data->cliente_estado), 00'L');
  594.      $pdf->replace('{email}',utf8_decode($data->cliente_email), 00'L');
  595.    
  596.      $pdf->replace('{vendedor_txt}',utf8_decode($data->vendedor_txt));
  597.      $pdf->replace('{loja_txt}',utf8_decode($data->loja_txt));
  598.      $pdf->replace('{loja_id}',utf8_decode($data->loja_id));
  599.     
  600.      $pdf->generate();
  601.      $fill TRUE
  602.      // Itens do Pedido
  603.              $tot 0;  // acrescentei aqui
  604.              
  605.              
  606.              foreach ($ComprasSub as $pedido_list)
  607.                  {
  608.                  if($pedido_list->compra_id == $data->id_compra)  // alterei aqui para testar
  609.                  {
  610.                     $pdf->gotoAnchorX('detalhes');
  611.                     $pdf->Ln(20);
  612.                     $pdf->Cell(5012number_format((double)$pedido_list->quantidade2',''.'), 00'R');
  613.                     $pdf->Cell(2512utf8_decode($pedido_list->unidade), 00'R');
  614.                     $pdf->Cell(10012utf8_decode($pedido_list->descricao), 00'L');
  615.                     $pdf->Cell(18012utf8_decode($pedido_list->kilate_txt), 00'R');
  616.                     $pdf->Cell(8012utf8_decode($pedido_list->tipo_compra_txt), 00'L');
  617.                     $pdf->Cell(7512number_format((double)$pedido_list->valor_unit2',''.'), 00'R');
  618.                     $pdf->Cell(7012number_format((double)$pedido_list->subtotal2',''.'), 00'R');
  619.                     
  620.                     $tot $tot $pedido_list->subtotal;  // acrescentei aqui
  621.                     
  622.                     // grid background
  623.                     $fill = !$fill;
  624.                }
  625.             }      
  626.     
  627.      $pdf->Ln(4);
  628.      $pdf->SetX(18); 
  629.      $pdf->Cell(57014utf8_decode(""),'B','R'$fill);
  630.        
  631.      $pdf->Ln(20);
  632.      $pdf->SetX(50);
  633.      $pdf->Cell(53014utf8_decode("Total R$ "number_format((double)$tot2',''.')),0,0,'R');   // acrescentei aqui
  634.      
  635.      $pdf->Ln(50);
  636.      $pdf->SetX(18); 
  637.      $pdf->MultiCell(56014utf8_decode("      Eu, ".$data->cliente_txt", declaro, para todos os fins, de direito e sob as penas da Lei 12.683 de 9 de julho de 2012 e  artigos 155, 156 e 157 todos do Código Penal Brasileiro, em todas as esferas, em juízo ou fora dele, ser o(a) legítimo(a) Proprietário(a) do(s) objeto(s) e/ou ouro velho que, no presente ato vendo a OuroRio Quiosques & Comércio de Metais Ltda, declarando ainda que não transfiro em caráter absoluto nenhuma de minhas responsabilidades a referida empresa quanto a procedência, descrição e autenticidade do(s) objeto(s) e/ou ouro velho o(s) qual(is) foi(ram) por mim legalmente adquirido(s) e está(ão) livre(s) e desembaraçada(s) de quaisquer ônus ou pendência(s).
  638.       Respondo sempre e, em quaisquer circunstâncias, pelos termos desta Declaração a qual assino em via única."),0,'J'$fill);
  639.      
  640.      $pdf->Ln(200);
  641.      $pdf->SetX(20);
  642.      $pdf->Cell(56014,$data_atual);  
  643.      
  644.    
  645.     // inicio do rodapé
  646.      $pdf->SetY(-25);
  647.      $pdf->SetFont('Arial'''8);
  648.      $pdf->setFontColorRGB'#000000' );
  649.      $pdf->Cell(59010utf8_decode('Pág. ').$pdf->PageNo().' de {nb}',0,0,'R');
  650.      $pdf->SetY(-25);
  651.      $pdf->Cell(14010utf8_decode('Sistema Gestor OuroRio © '.date("Y"."")),0,0,'R');
  652.      $pdf->SetY(-25);
  653.      $pdf->Cell(340,10,utf8_decode("Impresso em ".date("d/m/Y H:i:s"."")),0,1,'R');
  654.      $pdf->SetY(-25);
  655.      $pdf->Cell(460,10,utf8_decode(" Por ".TSession::getValue('username')),0,1,'R'); //nome do usuário 
  656.      // fim do rodapé
  657.     
  658.    
  659.      $file="app/output/Recibo - ".$data->loja_txt.".pdf"
  660.     
  661.      if (!file_exists($file) OR is_writable($file))
  662.      {
  663.      $pdf->save($file);
  664.    
  665.      //Abrir PDF em Janela Modal dentro do Sistema
  666.      $window TWindow::create($data->loja_txt0.80.8);
  667.                 $object = new TElement('object');
  668.                 $object->data  $file;
  669.                 $object->type  'application/pdf';
  670.                 $object->style "width: 100%; height:calc(100% - 10px)";
  671.                 $window->add($object);
  672.                 $window->show();
  673.                 
  674.      }
  675.      else
  676.      {
  677.      throw new Exception(_t('Permission denied') . ': ' $file);
  678.      } 
  679.     
  680.      TForm::sendData('form_Compras',$data);
  681.      TToast::show('success','RECIBO GERADO COM SUCESSO!''top left''fas fa-check');
  682.      TTransaction::close();
  683.      AdiantiCoreApplication::loadPage'ComprasList' );
  684.      exit;
  685.     
  686.     
  687.      }
  688.     // CÓDIGO PARA PASSAR DADOS DO CLIENTE AOS CAMPOS
  689.     public static function onExitCliente($param)
  690.     {
  691.         $cliente_id $param['cliente_id']; // get the product code
  692.         try
  693.         {
  694.             TTransaction::open('ourorio');
  695.             $cliente = new Clientes($cliente_id); // reads the product
  696.             
  697.             $obj = new StdClass;
  698.             $obj->cliente_cep               = ($cliente->cep);
  699.             $obj->cliente_endereco_tipo     = ($cliente->endereco_tipo);
  700.             $obj->cliente_endereco          = ($cliente->endereco);
  701.             $obj->cliente_endereco_numero   = ($cliente->endereco_numero);
  702.             $obj->cliente_bairro            = ($cliente->bairro);
  703.             $obj->cliente_cidade            = ($cliente->cidade);
  704.             $obj->cliente_codigo_municipio  = ($cliente->codigo_municipio);
  705.             $obj->cliente_estado            = ($cliente->estado);
  706.             $obj->cliente_telefone          = ($cliente->telefone);
  707.             $obj->cliente_nascimento        = ($cliente->data_nascimento);
  708.             $obj->cliente_identidade        = ($cliente->identidade);
  709.             $obj->cliente_email             = ($cliente->email);
  710.             $obj->cliente_cpf               = ($cliente->cpf);
  711.                      
  712.             TTransaction::close();
  713.             TForm::sendData('form_Compras'$obj);
  714.         }
  715.         catch (Exception $e)
  716.         {
  717.             new TMessage('error'$e->getMessage());
  718.             $this->form->setData$this->form->getData() ); // keep form data
  719.             TTransaction::rollback();
  720.         }
  721.     }
  722.      // CÓDIGO PARA PASSAR VALORES DO COMBO KILATE AO CAMPO VALOR UNITÁRIO E DESCRIÇÃO
  723.     public static function onChangeKilate($param)
  724.     {
  725.         $detail_kilate_id $param['detail_kilate_id']; // get the product code
  726.  
  727.         try
  728.         {
  729.             TTransaction::open('ourorio');
  730.             $kilate = new ComprasKilate($detail_kilate_id); // reads the product
  731.       
  732.             $obj = new StdClass;
  733.             $obj->detail_valor_unit  number_format($kilate->valor_unit2',''.');
  734.             $obj->detail_kilate_txt  utf8_decode($kilate->descricao_kilate);
  735.             
  736.             // CÁLCULO DO PRODUTO
  737.             
  738.             $detail_quantidade     = (double) str_replace(['.'','], ['''.'], $param['detail_quantidade']);
  739.             $obj->detail_subtotal  number_format($kilate->valor_unit $detail_quantidade2',''.'); 
  740.                   
  741.             TScript::create('setTimeout(function() { $("input[name=\'detail_quantidade\']").focus() }, 200);');
  742.             
  743.             TTransaction::close();
  744.             TForm::sendData('form_Compras'$obj);
  745.         }
  746.         catch (Exception $e)
  747.         {
  748.             new TMessage('error'$e->getMessage());
  749.             $this->form->setData$this->form->getData() ); // keep form data
  750.             TTransaction::rollback();
  751.         }
  752.     }
  753.  // CÓDIGO PARA CALCULAR VALOR TOTAL DOS PRODUTOS
  754.     public static function onUpdateTotal($param)
  755.     {
  756.         $detail_valor_unit = (double) str_replace(['.'','], ['''.'], $param['detail_valor_unit']);
  757.         $detail_quantidade     = (double) str_replace(['.'','], ['''.'], $param['detail_quantidade']);
  758.         $obj = new StdClass;    
  759.         $obj->detail_subtotal number_format( ($detail_valor_unit $detail_quantidade), 2',''.');
  760.         TForm::sendData('form_Compras'$obj);
  761.     }
  762.   
  763.   
  764.   // CÓDIGO PARA PASSAR VALORES DO COMBO TIPO DE COMPRA AO CAMPO DO DETALHE
  765.     public static function onChangeTipoCompra($param)
  766.     {
  767.         $detail_tipo_compra_id $param['detail_tipo_compra_id']; // get the product code
  768.         try
  769.         {
  770.             TTransaction::open('ourorio');
  771.             $tipo_compraId     = new ComprasTipo($detail_tipo_compra_id); // reads the product
  772.       
  773.             $obj = new StdClass;
  774.             $obj->detail_tipo_compra_txt  utf8_decode($tipo_compraId->descricao);
  775.             
  776.             TScript::create('setTimeout(function() { $("input[name=\'detail_kilate_id\']").focus() }, 200);');
  777.            
  778.             TTransaction::close();
  779.             TForm::sendData('form_Compras'$obj);
  780.         }
  781.         catch (Exception $e)
  782.         {
  783.             new TMessage('error'$e->getMessage());
  784.             $this->form->setData$this->form->getData() ); // keep form data
  785.             TTransaction::rollback();
  786.         }
  787.     }
  788.     
  789.     public static function onConfirma($param)
  790.     {
  791.     $action = new TAction(array(__CLASS__'ConfirmarCompra'));
  792.     $action->setParameters($param);
  793.     
  794.     new TQuestion('Confirma os Dados da Compra ?'$action);
  795.     } 
  796.     
  797.     public static function ConfirmarCompra$param )
  798.     {
  799.     try
  800.     {
  801.     
  802.     $nome_loja TSession::getValue('userunitname');;
  803.     TPage::openFile("app/output/Recibo - ".$nome_loja.".pdf");
  804.     TToast::show('show','COMPRA REGISTRADA COM SUCESSO!''center''fas fa-check');
  805.     
  806.     
  807.     TTransaction::close();
  808.     }
  809.     catch (Exception $e)
  810.     {
  811.     new TMessage('error''Error ' $e->getMessage());
  812.     TTransaction::rollback();
  813.     }
  814.     } 
  815.     public static function enviaAPI($ambiente$endpoint$method$token$data)
  816.     {
  817.         $url "https://hom.api.cloud-dfe.com.br/v1";
  818.         if ($ambiente == 1) {
  819.             $url "https://api.cloud-dfe.com.br/v1";
  820.         }
  821.         $ch curl_init("{$url}/{$endpoint}");
  822.         curl_setopt($chCURLOPT_TIMEOUT30);
  823.         curl_setopt($chCURLOPT_PORT443);
  824.         curl_setopt($chCURLOPT_CUSTOMREQUEST$method);
  825.         curl_setopt($chCURLOPT_POSTFIELDSjson_encode($data));
  826.         curl_setopt($chCURLOPT_HTTPHEADER, [
  827.             "Authorization: {$token}",
  828.             "Content-Type: application/json"
  829.         ]);
  830.         curl_setopt($chCURLOPT_FOLLOWLOCATION1);
  831.         curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  832.         curl_setopt($chCURLOPT_SSL_VERIFYHOST2);
  833.         curl_setopt($chCURLOPT_SSL_VERIFYPEER0);
  834.         $resp curl_exec($ch);
  835.         return json_decode($resp);
  836.     }
  837.     public static function OnNfe$param )
  838.     {
  839.         try
  840.         {
  841.             TTransaction::open('ourorio');
  842.             
  843.             $data = array(
  844.                 "natureza_operacao" => "VENDA DENTRO DO ESTADO",  // fixo
  845.                 "serie" => "18",
  846.                 "numero" => "1111225",
  847.                 "data_emissao" => "2021-09-17T13:00:00-03:00",
  848.                 "data_entrada_saida" => "2021-09-17T13:00:00-03:00",
  849.                 "tipo_operacao" => "0"// fixo, 0 = ENTRADA, 1 = SAÍDA
  850.                 "finalidade_emissao" => "1"// fixo, 1 - Nota normal, 2 - Nota complementar, 3 - Nota de ajuste, 4 - Devolução de mercadoria
  851.                 "consumidor_final" => "1"// fixo, 0 - Normal, 1 - Consumidor final
  852.                 "presenca_comprador" => "1"// fixo
  853.                 "intermediario" => array(
  854.                     "indicador" => "0"  // fixo
  855.                 ),
  856.                 "destinatario" => array(
  857.                     "cpf" => $param['cliente_cpf'],
  858.                     "nome" => $param['cliente_txt'],
  859.                     "indicador_inscricao_estadual" => "9",
  860.                     "inscricao_estadual" => null,
  861.                     "endereco" => array(
  862.                         "logradouro" => $param['cliente_endereco'],
  863.                         "numero" => $param['cliente_endereco_numero'],
  864.                         "bairro" => $param['cliente_bairro'],
  865.                         "complemento" => $param['cliente_endereco_complem'],
  866.                         "codigo_municipio" => $param['cliente_codigo_municipio'],
  867.                         "nome_municipio" => $param['cliente_cidade'],
  868.                         "uf" => $param['cliente_estado'],
  869.                         "cep" => $param['cliente_cep'],
  870.                         "codigo_pais" => "1058",
  871.                         "nome_pais" => "BRASIL",
  872.                         "telefone" => $param['cliente_telefone']
  873.                     )
  874.                 ),
  875.                 "itens" => array(),
  876.                 "frete" => array(
  877.                     "modalidade_frete" => "0"  // fixo
  878.                 ),
  879.                 "pagamento" => array(
  880.                     "formas_pagamento" => array(
  881.                         array(
  882.                             "meio_pagamento" => "01"// 01 - Dinheiro
  883.                             "valor" => "224.50"
  884.                         )
  885.                     )
  886.                 )
  887.             );
  888.            
  889.             TTransaction::open('ourorio');              
  890.             $items  ComprasSub::where('compra_id''='$key)->load();
  891.             
  892.             foreach($items as $key => $itemCompra) {
  893.                 $item = array(
  894.                     "numero_item" => strval($key 1),
  895.                     "codigo_produto" => $itemCompra->codigo,
  896.                     "descricao" => $itemCompra->descricao,
  897.                     "codigo_ncm" => $item->codigo_ncm,
  898.                     "cfop" => $item->cfop,
  899.                     "unidade_comercial" =>  $item->unidade,
  900.                     "quantidade_comercial" =>  $item->quantidade,
  901.                     "valor_unitario_comercial" =>  $item->valor_unit,
  902.                     "valor_bruto" =>  $item->subtotal,
  903.                     "unidade_tributavel" => $item->unidade,
  904.                     "quantidade_tributavel" => $item->quantidade,
  905.                     "valor_unitario_tributavel" => $item->valor_unit,
  906.                     "origem" => "0",
  907.                     "inclui_no_total" => "1",
  908.                     "imposto" => array(
  909.                         "valor_total_tributos" => 0,
  910.                         "icms" => array(
  911.                             "situacao_tributaria" => "102",  // meio fixo, ver com o contador
  912.                             "aliquota_credito_simples" => "0",
  913.                             "valor_credito_simples" => "0",
  914.                             "modalidade_base_calculo" => "3",
  915.                             "valor_base_calculo" => "0.00",
  916.                             "modalidade_base_calculo_st" => "4",
  917.                             "aliquota_reducao_base_calculo" => "0.00",
  918.                             "aliquota" => "0.00",
  919.                             "aliquota_final" => "0.00",
  920.                             "valor" => "0.00",
  921.                             "aliquota_margem_valor_adicionado_st" => "0.00",
  922.                             "aliquota_reducao_base_calculo_st" => "0.00",
  923.                             "aliquota_base_calculo_st" => "0.00",
  924.                             "aliquota_st" => "0.00",
  925.                             "valor_st" => "0.00"
  926.                         ),
  927.                         "pis" => array(
  928.                             "situacao_tributaria" => "99",
  929.                             "valor_base_calculo" => 0,
  930.                             "aliquota" => "0",
  931.                             "valor" => "0"
  932.                         ),
  933.                         "cofins" => array(
  934.                             "situacao_tributaria" => "99",
  935.                             "valor_base_calculo" => 0,
  936.                             "aliquota" => "0",
  937.                             "valor" => "0"
  938.                         )
  939.                     ),
  940.                     "valor_desconto" => 0,
  941.                     "valor_frete" => 0,
  942.                     "valor_seguro" => 0,
  943.                     "valor_outras_despesas" => 0
  944.                 );
  945.                 $data["itens"][] = $item;
  946.             }
  947.             $ambiente 2// 1 = producao, 2 = homologação
  948.             //$token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJlbXAiOjQ1LCJ1c3IiOjE5LCJ0cCI6MiwiaWF0IjoxNTkyODI1MDkwfQ.SmZhXytS1jgYab4BoCOHglFutn-VobYd9693c4pE2Yk";
  949.             $token "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJlbXAiOjMwMywidXNyIjoxNTIsInRwIjoyLCJpYXQiOjE2MzIwMDQ2NDd9.AItuUuMVTu5yuN37ayUWljyF-E0RvKzwtFUE_ZkYhbE";
  950.            
  951.             $resp self::enviaAPI($ambiente"nfe""POST"$token$data);
  952.             if ($resp->sucesso) {
  953.                 sleep(5);
  954.                 $chave $resp->chave;
  955.                 if ($resp->codigo == 5023) {
  956.                     /**
  957.                      * Em alguns casos a SEFAZ pode demorar mais do que esperado pela api
  958.                      * para processar o lote, devido a trafego na rede ou sobrecarga de processamento
  959.                      * então nesse caso quando vir codigo 5023 é necessario buscar a NFe pela chave de acesso
  960.                      */
  961.                     $tentativa 1;
  962.                     while ($tentativa <= 5) {
  963.                         $resp self::enviaAPI($ambiente"nfe/{$chave}""GET"$token, array());
  964.                         if ($resp->codigo != 5023) {
  965.                             if ($resp->sucesso) {
  966.                                 // autorizado
  967.                                 var_dump($resp);
  968.                                 $pdf base64_decode($resp->pdf);
  969.                                 $xml base64_decode($resp->xml);
  970.                                 break;
  971.                             } else {
  972.                                 // rejeição
  973.                                 var_dump($resp);
  974.                                 break;
  975.                             }
  976.                         }
  977.                         $tentativa++;
  978.                         sleep(10);
  979.                     }
  980.                 } else {
  981.                     // autorizado
  982.                     var_dump($resp);
  983.                 }
  984.             } else if (in_array($resp->codigo, array(50015002))) {
  985.                 // erro nos campos
  986.                 var_dump($resp->erros);
  987.             } else if ($resp->codigo >= 7000) {
  988.                 // erro de timout ou de conexão
  989.                 var_dump($resp);
  990.                 // recomendamos fazer a consulta pela chave para sincronizar o documento
  991.                 $resp self::enviaAPI($ambiente"nfe/{$resp->chave}""GET"$token, array());
  992.                 if ($resp->sucesso) {
  993.                     // autorizado
  994.                     var_dump($resp);
  995.                 } else {
  996.                     // rejeição
  997.                     var_dump($resp);
  998.                 }
  999.             } else {
  1000.                 // rejeição
  1001.                 var_dump($resp);
  1002.             }
  1003.             
  1004.             TTransaction::close();
  1005.         }
  1006.         catch (Exception $e)
  1007.         {
  1008.             new TMessage('error''Error ' $e->getMessage());
  1009.             TTransaction::rollback();
  1010.         }
  1011.     } 
  1012.     public static function OnCancelarNfe$param )
  1013.     {
  1014.         try
  1015.         {
  1016.             TTransaction::open('ourorio');
  1017.             $ambiente 2;
  1018.             $token "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJlbXAiOjQ1LCJ1c3IiOjE5LCJ0cCI6MiwiaWF0IjoxNTkyODI1MDkwfQ.SmZhXytS1jgYab4BoCOHglFutn-VobYd9693c4pE2Yk";
  1019.             $data =  array(
  1020.                 "chave" => "41210922545265000108550180011112251837890220",
  1021.                 "justificativa" => "Teste de carta de correcao"
  1022.             );
  1023.             $resp self::enviaAPI($ambiente"nfe/cancela""POST"$token$data);
  1024.             if ($resp->sucesso) {
  1025.                 // cancelou com sucesso
  1026.                 var_dump($resp);
  1027.                 $pdf base64_decode($resp->pdf);
  1028.                 $xml base64_decode($resp->xml);
  1029.             } else {
  1030.                 // rejeição
  1031.                 var_dump($resp);
  1032.             }
  1033.             TTransaction::close();
  1034.         }
  1035.         catch (Exception $e)
  1036.         {
  1037.             new TMessage('error''Error ' $e->getMessage());
  1038.             TTransaction::rollback();
  1039.         }
  1040.     }
  1041. }
  1042. ?>
NR

"Undefined variable: key" - Você está usando uma variável que não existe, $key não tem valor nenhum. Não seria "$param['id_compra']"?
CM

Desculpe a demora.
Obrigado Nataniel, resolvido.
Abraço irmão.