Conheça as melhorias da versão 8.0, 8.1, 8.2!
Clique aqui para saber mais
Checkboxes com seleção de valores de ids intermitentes Boa noite a todos, Estou tendo uma certa dificuldade com uma tela que estou criando. Eu tenho um datagrid com checkboxes que podem selecionar todos ou 1 por vez. Acontece que o comportamento está intermitente e nem sempre retorna os valores ids corretos dos checkboxes selecionados. A versão do framework que utilizo é a 7.4 minha classe. Método onSelecionados e o JavaScript no final do...
LS
Checkboxes com seleção de valores de ids intermitentes  
Boa noite a todos,

Estou tendo uma certa dificuldade com uma tela que estou criando. Eu tenho um datagrid com checkboxes que podem selecionar todos ou 1 por vez. Acontece que o comportamento está intermitente e nem sempre retorna os valores ids corretos dos checkboxes selecionados.

A versão do framework que utilizo é a 7.4

minha classe. Método onSelecionados e o JavaScript no final do construtor.


 
  1. <?php
  2. require 'vendor/autoload.php';
  3. use Dompdf\Dompdf;
  4. use Dompdf\Options;
  5. /**
  6. * OrdemPagamentoPortobayConsulta Listing
  7. * @author <your name here>
  8. */
  9. class OrdemPagamentoPortobayConsulta extends TStandardList
  10. {
  11. protected $form; // registration form
  12. protected $datagrid; // listing
  13. protected $pageNavigation;
  14. protected $formgrid;
  15. protected $deleteButton;
  16. protected $transformCallback;
  17. const FORM_NUMBER = 9;
  18. private static $formName = 'form_search_OrdemPagamentoPortobayConsulta';
  19. /**
  20. * Class constructor
  21. * Creates the page, the form and the listing
  22. */
  23. public function __construct()
  24. {
  25. parent::__construct();
  26. parent::setDatabase('permission');
  27. parent::setActiveRecord('OrdemPagamentoPortobay'); // defines the active record
  28. parent::setDefaultOrder('id', 'desc'); // defines the default order
  29. $userid = TSession::getValue('userid');
  30. TTransaction::open('permission');
  31. // creates the form
  32. $this->form = new BootstrapFormBuilder(self::$formName);
  33. $this->form->setFormTitle('Consulta - Ordem de Pagamento Portobay');
  34. // create the form fields
  35. $id = new TEntry('id');
  36. $flagCheck = new THidden('flagCheck');
  37. $razao_social = new TEntry('razao_social');
  38. $cnpj = new TEntry('cnpj');
  39. $cnpj->placeholder = '99.999.999/9999-99';
  40. $cnpj->setMask('99.999.999/9999-99');
  41. $cpf = new TEntry('cpf');
  42. $cpf->placeholder = '999.999.999-99';
  43. $cpf->setMask('999.999.999-99');
  44. $centro_de_custo = new TEntry('centro_de_custo');
  45. $conta_contabil = new TEntry('conta_contabil');
  46. $numero_nf = new TEntry('numero_nf');
  47. $data_vencimento_ini = new TDate('data_vencimento_ini');
  48. $data_vencimento_ini->setMask('dd/mm/yyyy');
  49. $data_vencimento_fim = new TDate('data_vencimento_fim');
  50. $data_vencimento_fim->setMask('dd/mm/yyyy');
  51. $valor_ini = new TEntry('valor_ini');
  52. $valor_ini->setNumericMask(2, ',', '.', true);
  53. $valor_fim = new TEntry('valor_fim');
  54. $valor_fim->setNumericMask(2, ',', '.', true);
  55. $etapa = new TCombo('etapa');
  56. $etapa->addItems(HomeSolicitacao::getStatusList(self::FORM_NUMBER, $userid));
  57. $etapa->enableSearch();
  58. $data_cadastro_ini = new TDate('data_cadastro_ini');
  59. $data_cadastro_ini->setMask('dd/mm/yyyy');
  60. $data_cadastro_fim = new TDate('data_cadastro_fim');
  61. $data_cadastro_fim->setMask('dd/mm/yyyy');
  62. $fk_id_emissor = new TDBMultiSearch('fk_id_emissor', 'permission', 'SystemUser', 'id', 'name');
  63. $fk_id_emissor->setMinLength(0);
  64. $fk_id_emissor->setMask('{name}');
  65. $fk_id_emissor->setOperator('ilike');
  66. $criteria = new TCriteria;
  67. $criteria->add(new TFilter('fk_id_formulario', '=', self::FORM_NUMBER));
  68. $fk_id_cadastro = new TDBMultiSearch('fk_id_cadastro', 'permission', 'CadastroEtapa', 'id', 'nome', 'nome', $criteria);
  69. $fk_id_cadastro->setMinLength(0);
  70. $fk_id_cadastro->setMask('{nome}');
  71. $fk_id_cadastro->setOperator('ilike');
  72. $id->setSize('100%');
  73. $flagCheck->setSize('100%');
  74. $razao_social->setSize('100%');
  75. $cnpj->setSize('100%');
  76. $cpf->setSize('100%');
  77. $centro_de_custo->setSize('100%');
  78. $conta_contabil->setSize('100%');
  79. $numero_nf->setSize('100%');
  80. $data_vencimento_ini->setSize('120');
  81. $data_vencimento_fim->setSize('120');
  82. $valor_ini->setSize('120');
  83. $valor_fim->setSize('120');
  84. $etapa->setSize('100%');
  85. $data_cadastro_ini->setSize('120');
  86. $data_cadastro_fim->setSize('120');
  87. $fk_id_emissor->setSize('100%', 30);
  88. $fk_id_cadastro->setSize('100%', 30);
  89. // add the fields
  90. $row = $this->form->addFields(
  91. [new TLabel("N° Ordem Pagamento", '', '14px', 'b', '100%'), $id],
  92. [new TLabel("Razão Social", '', '14px', 'b', '100%'), $razao_social]
  93. );
  94. $row->layout = ['col-sm-3', 'col-sm-9'];
  95. $row = $this->form->addFields(
  96. [new TLabel("CPF", "", '14px', 'b', '100%'), $cpf],
  97. [new TLabel("CNPJ", "", '14px', 'b', '100%'), $cnpj],
  98. [new TLabel("Centro de Custo", '', '14px', 'b', '100%'), $centro_de_custo]
  99. );
  100. $row->layout = ['col-sm-3', 'col-sm-3', 'col-sm-6'];
  101. $row = $this->form->addFields(
  102. [new TLabel("Conta Contábil", '', '14px', 'b', '100%'), $conta_contabil],
  103. [new TLabel("Número da Nota", '', '14px', 'b', '100%'), $numero_nf],
  104. [new TLabel("Status", '', '14px', 'b', '100%'), $etapa]
  105. );
  106. $row->layout = ['col-sm-3', 'col-sm-3', 'col-sm-6'];
  107. $row = $this->form->addFields(
  108. [new TLabel("Data Cadastro", '', '14px', 'b', '100%'), $data_cadastro_ini, 'à', $data_cadastro_fim],
  109. [new TLabel("Data Vencimento", '', '14px', 'b', '100%'), $data_vencimento_ini, 'à', $data_vencimento_fim],
  110. [new TLabel("Valor", '', '14px', 'b', '100%'), $valor_ini, 'à', $valor_fim]
  111. );
  112. $row->layout = ['col-sm-4', 'col-sm-4', 'col-sm-4'];
  113. $hasCreatePermission = HomeSolicitacao::checkPermissions(self::FORM_NUMBER, $userid, -2);
  114. if ($hasCreatePermission) {
  115. $row = $this->form->addFields(
  116. [new TLabel("Emissor", '', '14px', 'b', '100%'), $fk_id_emissor],
  117. [new TLabel("Módulo", '', '14px', 'b', '100%'), $fk_id_cadastro]
  118. );
  119. $row->layout = ['col-sm-6', 'col-sm-6'];
  120. } else {
  121. $row = $this->form->addFields([new TLabel("Módulo", '', '14px', 'b', '100%'), $fk_id_cadastro]);
  122. $row->layout = ['col-sm-12'];
  123. }
  124. $this->form->addFields([$flagCheck]);
  125. // keep the form filled during navigation with session data
  126. $this->form->setData(TSession::getValue('OrdemPagamentoPortobayConsulta_filter_data'));
  127. $this->form->addAction(_t('Find'), new TAction(array($this, 'onSearch')), 'fa:search')->class = 'btn btn-sm btn-primary';
  128. $this->form->addAction(_t('Clear'), new TAction(array($this, 'onClear')), 'fa:eraser red');
  129. $isFinanceiro = SystemUserGroup::where('system_user_id', '=', $userid)->where('system_group_id', 'IN', "(SELECT id FROM permission.system_group WHERE name ILIKE '%Financeiro%Portobay%')")->count() > 0;
  130. if ($isFinanceiro) {
  131. $this->form->addAction(('Marcar como nota pendente'), new TAction(array($this, 'onMarkAsPending')), 'fa:file-invoice-dollar red');
  132. $this->form->addAction(('Marcar como nota enviada'), new TAction(array($this, 'onMarkAsSent')), 'fa:file-invoice-dollar green');
  133. }
  134. TTransaction::close();
  135. $this->form->addAction(('Gerar PDF Selecionados'), new TAction(array($this, 'onGenerateMultiple')), 'fa:check-square green');
  136. // creates a Datagrid
  137. $this->datagrid = new BootstrapDatagridWrapper(new TDataGrid);
  138. $this->datagrid->datatable = 'true';
  139. $this->datagrid->id = 'datagrid_list'; // Adiciona um ID à datagrid
  140. $this->datagrid->style = 'width: 100%';
  141. $this->datagrid->setHeight(320);
  142. $checkall = new TElement('input');
  143. $checkall->id = 'checkbox_all';
  144. $checkall->type = 'checkbox';
  145. $checkall->title = 'Marcar/desmarcar todos';
  146. $checkall->style = 'height: 20px; width: 20px; background-color: transparent; border: 6px solid #5a5a5a;';
  147. //$checkall->onclick = "selectAll(this);";
  148. // creates the datagrid columns
  149. $col_select = new TDataGridColumn('select', $checkall, 'center');
  150. $column_id = new TDataGridColumn('id', 'N° OP', 'center');
  151. $column_razao_social = new TDataGridColumn('razao_social', 'Razão Social', 'center');
  152. $column_tipo_pessoa = new TDataGridColumn('tipo_pessoa', 'Tipo Pessoa', 'center');
  153. $column_cpf_cnpj = new TDataGridColumn('cnpj', 'CPF/CNPJ', 'center');
  154. $column_numero_nf = new TDataGridColumn('numero_nf', 'Nota Fiscal', 'center');
  155. $column_data_vencimento = new TDataGridColumn('data_vencimento', 'Data de Vencimento', 'center');
  156. $column_valor = new TDataGridColumn('valor', 'Valor', 'center');
  157. $column_fk_id_emissor = new TDataGridColumn('fk_id_emissor', 'Emissor', 'center');
  158. $column_data_cadastro = new TDataGridColumn('data_cadastro', 'Cadastrado em', 'center');
  159. $column_etapa = new TDataGridColumn('etapa', 'Status', 'center');
  160. $column_tipo = new TDataGridColumn('tipo', 'Módulo', 'center');
  161. $column_nota_enviada = new TDataGridColumn('nota_enviada', 'Status Nota', 'center');
  162. // add the columns to the Datagrid
  163. $this->datagrid->addColumn($col_select);
  164. $this->datagrid->addColumn($column_id, new TAction([$this, 'onReload'], ['column' => 'id']));
  165. $this->datagrid->addColumn($column_razao_social, new TAction([$this, 'onReload'], ['column' => 'razao_social']));
  166. $this->datagrid->addColumn($column_tipo_pessoa, new TAction([$this, 'onReload'], ['column' => 'tipo_pessoa']));
  167. $this->datagrid->addColumn($column_cpf_cnpj, new TAction([$this, 'onReload'], ['column' => 'cnpj']));
  168. $this->datagrid->addColumn($column_numero_nf, new TAction([$this, 'onReload'], ['column' => 'numero_nf']));
  169. $this->datagrid->addColumn($column_data_vencimento, new TAction([$this, 'onReload'], ['column' => 'data_vencimento']));
  170. $this->datagrid->addColumn($column_valor, new TAction([$this, 'onReload'], ['column' => 'valor']));
  171. $this->datagrid->addColumn($column_tipo);
  172. $this->datagrid->addColumn($column_etapa);
  173. $this->datagrid->addColumn($column_nota_enviada);
  174. $this->datagrid->addColumn($column_fk_id_emissor, new TAction([$this, 'onReload'], ['column' => 'fk_id_emissor']));
  175. $this->datagrid->addColumn($column_data_cadastro, new TAction([$this, 'onReload'], ['column' => 'data_cadastro']));
  176. // define format function
  177. $format_value = function ($value) {
  178. if (is_numeric($value)) {
  179. return number_format($value, 2, ',', '.') . ' R$';
  180. }
  181. return $value;
  182. };
  183. $column_valor->setTransformer($format_value);
  184. $column_valor->setTotalFunction(function ($values) {
  185. return array_sum((array) $values);
  186. });
  187. $this->datagrid->disableDefaultClick();
  188. // create EDIT action
  189. $action_edit = new TDataGridAction(array('OrdemPagamentoPortobayForm', 'onEdit'));
  190. $action_edit->setButtonClass('btn btn-default');
  191. $action_edit->setLabel('Editar');
  192. $action_edit->setImage('far:edit fa-lg blue');
  193. $action_edit->setField('id');
  194. $action_edit->setDisplayCondition(array($this, 'enableEdit'));
  195. $action_edit_financeiro = new TDataGridAction(array('OrdemPagamentoPortobayForm', 'onEditFinanceiro'));
  196. $action_edit_financeiro->setButtonClass('btn btn-default');
  197. $action_edit_financeiro->setLabel('Editar (Financeiro)');
  198. $action_edit_financeiro->setImage('far:edit fa-lg blue');
  199. $action_edit_financeiro->setField('id');
  200. $action_edit_financeiro->setDisplayCondition(array($this, 'enableEditFinanceiro'));
  201. $action_view = new TDataGridAction(array('OrdemPagamentoPortobayView', 'onViewFromConsulta'));
  202. $action_view->setButtonClass('btn btn-default');
  203. $action_view->setLabel('Visualizar');
  204. $action_view->setImage('fa:eye fa-lg purple');
  205. $action_view->setField('id');
  206. $action_files = new TDataGridAction(array('OrdemPagamentoPortobayAnexosView', 'onView'));
  207. $action_files->setButtonClass('btn btn-default');
  208. $action_files->setLabel('Anexos');
  209. $action_files->setImage('fa:paperclip grey fa-lg');
  210. $action_files->setField('id');
  211. $action_pdf = new TDataGridAction(array($this, 'onGenerateSingle'));
  212. $action_pdf->setButtonClass('btn btn-default');
  213. $action_pdf->setLabel(('Vizualizar PDF'));
  214. $action_pdf->setImage('fa:file-pdf red fa-lg');
  215. $action_pdf->setField('id');
  216. $action_del = new TDataGridAction(array($this, 'onDelete'));
  217. $action_del->setButtonClass('btn btn-default');
  218. $action_del->setLabel('Remover');
  219. $action_del->setImage('fa:trash fa-lg red');
  220. $action_del->setField('id');
  221. $action_del->setDisplayCondition(array($this, 'enableDelete'));
  222. $action_group = new TDataGridActionGroup('Ações ', 'fa:th');
  223. $action_group->addHeader('Opções');
  224. $action_group->addAction($action_edit);
  225. $action_group->addAction($action_edit_financeiro);
  226. //$action_group->addAction($action_pdf);
  227. $action_group->addAction($action_view);
  228. $action_group->addAction($action_files);
  229. //$action_group->addAction($action_del);
  230. // add the actions to the datagrid
  231. $this->datagrid->addActionGroup($action_group);
  232. // create the datagrid model
  233. $this->datagrid->createModel();
  234. // create the page navigation
  235. $this->pageNavigation = new TPageNavigation;
  236. $this->pageNavigation->setAction(new TAction(array($this, 'onReload')));
  237. $this->pageNavigation->setWidth($this->datagrid->getWidth());
  238. $panel = new TPanelGroup;
  239. $panel->add($this->datagrid);
  240. $panel->addFooter($this->pageNavigation);
  241. // header actions
  242. $dropdown = new TDropDown(TSession::getValue('OrdemPagamentoPortobayConsulta_limit') ?? '20', '');
  243. $dropdown->style = 'height:37px';
  244. $dropdown->setPullSide('right');
  245. $dropdown->setButtonClass('btn btn-default waves-effect dropdown-toggle');
  246. foreach ([10, 20, 50, 100, 500] as $qty) {
  247. $dropdown->addAction(
  248. $qty,
  249. new TAction(
  250. [$this, 'onChangeLimit'],
  251. [
  252. 'register_state' => 'false',
  253. 'static' => '1',
  254. 'limit' => "{$qty}"
  255. ]
  256. )
  257. );
  258. }
  259. $panel->addHeaderWidget(new TLabel('Listar &nbsp;'));
  260. $panel->addHeaderWidget($dropdown);
  261. $panel->addHeaderWidget(new TLabel('&nbsp; / página'));
  262. $panel->addHeaderWidget(new TLabel('&nbsp;&nbsp;'));
  263. $dropdown = new TDropDown(_t('Export'), 'fa:list');
  264. $dropdown->setPullSide('right');
  265. $dropdown->setButtonClass('btn btn-default waves-effect dropdown-toggle');
  266. $dropdown->addAction(_t('Save as CSV'), new TAction([$this, 'onExportCSV'], ['register_state' => 'false', 'static' => '1']), 'fa:table fa-fw blue');
  267. $dropdown->addAction(_t('Save as PDF'), new TAction([$this, 'onGenerateMultiple2'], ['register_state' => 'false', 'static' => '1']), 'far:file-pdf fa-fw red');
  268. $panel->addHeaderWidget($dropdown);
  269. // vertical box container
  270. $container = new TVBox;
  271. $container->style = 'width: 100%';
  272. $container->add(new TXMLBreadCrumb('menu.xml', 'OrdemPagamentoPortobayConsulta2'));
  273. $container->add($this->form);
  274. $container->add($panel);
  275. parent::add($container);
  276. TScript::create("
  277. let checkboxStates = {};
  278. document.getElementById('checkbox_all').addEventListener('change', function () {
  279. const isChecked = this.checked;
  280. $('input[name^=\"check_select_\"]').each(function () {
  281. const key = $(this).val();
  282. $(this).prop('checked', isChecked);
  283. sendAjaxRequest(key, isChecked);
  284. console.log('atualização individual:', key);
  285. });
  286. console.log('Status do checkbox all:', isChecked);
  287. });
  288. $(document).on('change', 'input[name^=\"check_select_\"]', function () {
  289. const key = $(this).val();
  290. const isChecked = this.checked;
  291. sendAjaxRequest(key, isChecked);
  292. console.log('Status do checkbox individual:', key);
  293. const allChecked = $('input[name^=\"check_select_\"]').length === $('input[name^=\"check_select_\"]:checked').length;
  294. $('#checkbox_all').prop('checked', allChecked);
  295. });
  296. function sendAjaxRequest(key, isChecked) {
  297. if (checkboxStates[key] !== isChecked) {
  298. console.log('Enviando AJAX para a chave:', key, 'Com flagCheck:', !isChecked);
  299. __adianti_ajax_exec('class=OrdemPagamentoPortobayConsulta&method=onSelecionados&key=' + key + '&flagCheck=' + !isChecked);
  300. console.log('Chamada AJAX enviada.');
  301. checkboxStates[key] = isChecked;
  302. }
  303. }
  304. $(document).ready(function(){
  305. $('#datagrid_list').parent().parent().addClass('margin_bottom_120');
  306. });
  307. ");
  308. }
  309. public function enableEdit($object)
  310. {
  311. return $object->can_edit;
  312. }
  313. public function enableEditFinanceiro($object)
  314. {
  315. return $object->can_edit_financeiro;
  316. }
  317. public function enableDelete($object)
  318. {
  319. return $object->can_delete;
  320. }
  321. public static function onChangeLimit($param)
  322. {
  323. TSession::setValue('OrdemPagamentoPortobayConsulta_limit', $param['limit']);
  324. AdiantiCoreApplication::loadPage(__CLASS__, 'onReload');
  325. }
  326. public function onEnter()
  327. {
  328. TSession::setValue('solicitacoes_selecionadas', []);
  329. $this->onReload();
  330. }
  331. public static function onSelecionados($param)
  332. {
  333. // Obtém a lista de documentos selecionados da sessão ou inicializa como um array vazio
  334. $documentosSelecionados = TSession::getValue('solicitacoes_selecionadas') ?? [];
  335. // Obter a chave e o estado do checkbox (flagCheck)
  336. $key = $param['key'] ?? null;
  337. $flagCheck = isset($param['flagCheck']) ? filter_var($param['flagCheck'], FILTER_VALIDATE_BOOLEAN) : null;
  338. // Exibir o estado do flagCheck para depuração
  339. echo "Flag Check: " . ($flagCheck ? 'true' : 'false') . "\n";
  340. echo "<pre>"; print_r($param); echo "</pre>";
  341. echo "Flag Check: " . ($flagCheck ? 'true' : 'false') . "<br>";
  342. // Manipula a lista de documentos com base no estado do checkbox
  343. if ($flagCheck)
  344. {
  345. // Remove o item se o flagCheck for true (marcado)
  346. $documentosSelecionados = array_diff($documentosSelecionados, [$key]);
  347. }
  348. else
  349. {
  350. // Adiciona o item se o flagCheck for false (não marcado) e não estiver presente
  351. if (!in_array($key, $documentosSelecionados, true))
  352. {
  353. $documentosSelecionados[] = $key;
  354. }
  355. }
  356. // Atualiza a sessão com os itens selecionados
  357. TSession::setValue('solicitacoes_selecionadas', array_values($documentosSelecionados));
  358. // Exibir o array atualizado para depuração
  359. echo "<pre>"; print_r($documentosSelecionados); echo "</pre>";
  360. // Envia dados do formulário
  361. TForm::sendData(self::$formName, $param);
  362. }
  363. public static function onGenerateMultiple($param)
  364. {
  365. $ordens = TSession::getValue('solicitacoes_selecionadas');
  366. if (empty($ordens)) {
  367. new TMessage('error', 'Favor Selecionar algum item na lista!');
  368. } else {
  369. try {
  370. TTransaction::open('permission');
  371. $files = [];
  372. foreach ($ordens as $ordemId) {
  373. $files[] = "D:/htdocs/qualydocs/" . self::createPDF($ordemId);
  374. }
  375. $files = implode(" ", $files);
  376. $output_file = 'app/output/multiples_' . date('Y_m_d_H_i_s') . "_" . rand(0, 99999) . ".pdf";
  377. $fullpath = 'D:/htdocs/qualydocs/' . $output_file;
  378. $command = "D:/htdocs/qualydocs/gs/gswin32c.exe -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOUTPUTFILE=$fullpath $files 2>&1";
  379. $result = shell_exec($command);
  380. TScript::create("console.log('$command');");
  381. TScript::create("console.log('$result');");
  382. if (file_exists($output_file)) {
  383. // open window to show pdf
  384. $window = TWindow::create('Ordem de Pagamento', 0.8, 0.8);
  385. $object = new TElement('object');
  386. $object->data = $output_file;
  387. $object->type = 'application/pdf';
  388. $object->style = "width: 100%; height:calc(100% - 10px)";
  389. $window->add($object);
  390. $window->show();
  391. } else {
  392. new TMessage('error', 'Erro ao gerar pdf!');
  393. }
  394. TTransaction::close();
  395. } catch (Exception $e) {
  396. new TMessage('error', $e->getMessage());
  397. TTransaction::rollback();
  398. }
  399. }
  400. TSession::setValue('solicitacoes_selecionadas', []);
  401. }
  402. public static function onGenerateSingle($param)
  403. {
  404. try {
  405. TTransaction::open('permission');
  406. $output_file = self::createPDF($param['id']);
  407. if (file_exists($output_file)) {
  408. // open window to show pdf
  409. $window = TWindow::create('Ordem de Pagamento', 0.8, 0.8);
  410. $object = new TElement('object');
  411. $object->data = $output_file;
  412. $object->type = 'application/pdf';
  413. $object->style = "width: 100%; height:calc(100% - 10px)";
  414. $window->add($object);
  415. $window->show();
  416. } else {
  417. new TMessage('error', 'Erro ao gerar pdf!');
  418. }
  419. TTransaction::close();
  420. } catch (Exception $e) {
  421. new TMessage('error', $e->getMessage());
  422. TTransaction::rollback();
  423. }
  424. }
  425. public static function createPDF($id)
  426. {
  427. $ordem_pagamento = new OrdemPagamentoPortobay($id);
  428. // replace the main section variables
  429. $html = new THtmlRenderer('app/reports/relatorio.html');
  430. $unidade_monetaria = array(1 => 'R$', 2 => '$', 3 => '€', 4 => '£');
  431. $data_vencimento = !empty($ordem_pagamento->data_vencimento) ? date('d/m/Y', strtotime($ordem_pagamento->data_vencimento)) : '';
  432. $data_emissao_nf = !empty($ordem_pagamento->data_emissao_nf) ? date('d/m/Y', strtotime($ordem_pagamento->data_emissao_nf)) : '';
  433. $data_cadastro = !empty($ordem_pagamento->data_cadastro) ? date('d/m/Y', strtotime($ordem_pagamento->data_cadastro)) : '';
  434. $ordem_pagamento->inss_label = number_format($ordem_pagamento->inss_label, 2, ',', '.') . '%';
  435. $ordem_pagamento->irrf_label = number_format($ordem_pagamento->irrf_label, 2, ',', '.') . '%';
  436. $ordem_pagamento->irrf_2_label = number_format($ordem_pagamento->irrf_2_label, 2, ',', '.') . '%';
  437. $ordem_pagamento->iss_label = number_format($ordem_pagamento->iss_label, 2, ',', '.') . '%';
  438. $ordem_pagamento->pis_cofins_cssl_label = number_format($ordem_pagamento->pis_cofins_cssl_label, 2, ',', '.') . '%';
  439. $unidade_monetaria = !empty($ordem_pagamento->unidade_monetaria) ? $unidade_monetaria[$ordem_pagamento->unidade_monetaria] . " " : "";
  440. $replace = [];
  441. $replace['data_vencimento'] = $data_vencimento;
  442. $replace['data_emissao_nf'] = $data_emissao_nf;
  443. $replace['valor'] = "{$unidade_monetaria}" . number_format($ordem_pagamento->valor ?? '0', 2, ',', '.');
  444. $replace['numero_nf'] = $ordem_pagamento->numero_nf;
  445. $replace['razao_social'] = $ordem_pagamento->razao_social;
  446. if ($ordem_pagamento->tipo_pessoa == 1 && !empty($ordem_pagamento->cpf)) {
  447. $ordem_pagamento->cnpj = $ordem_pagamento->cpf;
  448. } else if ($ordem_pagamento->tipo_pessoa == 2 && !empty($ordem_pagamento->cnpj)) {
  449. $ordem_pagamento->cnpj = $ordem_pagamento->cnpj;
  450. }
  451. $replace['cnpj'] = $ordem_pagamento->cnpj;
  452. $replace['telefone'] = $ordem_pagamento->telefone;
  453. $replace['descricao_servico'] = $ordem_pagamento->descricao_servico;
  454. $replace['op1'] = "[ ] BOLETO";
  455. $replace['op2'] = "[ ] DEPÓSITO";
  456. $replace['op3'] = "[ ] CÂMBIO";
  457. $replace['op4'] = "[ ] OUTROS";
  458. switch ($ordem_pagamento->forma_pagamento) {
  459. case 'BOLETO':
  460. $replace['op1'] = "[ X ] BOLETO";
  461. break;
  462. case 'DEPOSITO':
  463. $replace['op2'] = "[ X ] DEPÓSITO";
  464. break;
  465. case 'CAMBIO':
  466. $replace['op3'] = "[ X ] CÂMBIO";
  467. break;
  468. case 'OUTROS':
  469. $replace['op4'] = "[ X ] OUTROS";
  470. break;
  471. }
  472. $replace['credor'] = $ordem_pagamento->credor;
  473. $replace['banco'] = $ordem_pagamento->banco;
  474. $replace['agencia'] = $ordem_pagamento->agencia;
  475. $replace['conta_corrente'] = $ordem_pagamento->numero_conta;
  476. $replace['valor_bruto'] = "{$unidade_monetaria}" . number_format($ordem_pagamento->valor_bruto, 2, ',', '.');
  477. $replace['inss'] = 'R$ ' . number_format($ordem_pagamento->inss, 2, ',', '.');
  478. $replace['irrf'] = 'R$ ' . number_format($ordem_pagamento->irrf, 2, ',', '.');
  479. $replace['irrf_2'] = 'R$ ' . number_format($ordem_pagamento->irrf_2, 2, ',', '.');
  480. $replace['iss'] = 'R$ ' . number_format($ordem_pagamento->iss, 2, ',', '.');
  481. $replace['pis_cofins_cssl'] = 'R$ ' . number_format($ordem_pagamento->pis_cofins_cssl, 2, ',', '.');
  482. $replace['inss_label'] = strval(number_format(doubleval($ordem_pagamento->inss_label), 2, ',', '.')) . '%';
  483. $replace['irrf_label'] = strval(number_format(doubleval($ordem_pagamento->irrf_label), 2, ',', '.')) . '%';
  484. $replace['irrf_2_label'] = strval(number_format(doubleval($ordem_pagamento->irrf_2_label), 2, ',', '.')) . '%';
  485. $replace['iss_label'] = strval(number_format(doubleval($ordem_pagamento->iss_label), 2, ',', '.')) . '%';
  486. $replace['pis_cofins_cssl_label'] = strval(number_format(doubleval($ordem_pagamento->pis_cofins_cssl_label), 2, ',', '.')) . '%';
  487. $replace['descontos'] = 'R$ ' . number_format($ordem_pagamento->descontos, 2, ',', '.');
  488. $replace['valor_liquido'] = "{$unidade_monetaria}" . number_format($ordem_pagamento->valor_liquido, 2, ',', '.');
  489. $replace['centro_de_custo'] = $ordem_pagamento->centro_de_custo;
  490. $replace['conta_contabil'] = $ordem_pagamento->conta_contabil;
  491. if ($ordem_pagamento->fk_id_emissor != null) {
  492. $user = new SystemUser($ordem_pagamento->fk_id_emissor);
  493. $replace['fk_id_emissor'] = $user->name;
  494. $replace['data_emissor'] = $data_cadastro;
  495. $replace['emissor'] = $ordem_pagamento->emissor;
  496. }
  497. $tipos = array("contabilidade", "controller", "diretoria");
  498. foreach ($tipos as $tipo) {
  499. $replace['fk_id_' . $tipo] = '';
  500. $replace['data_' . $tipo] = '';
  501. $replace[$tipo] = '';
  502. if (!empty($ordem_pagamento->{"fk_id_{$tipo}"})) {
  503. $user = new SystemUser($ordem_pagamento->{"fk_id_{$tipo}"});
  504. $replace['fk_id_' . $tipo] = $user->name;
  505. $replace['data_' . $tipo] = !empty($ordem_pagamento->{"data_{$tipo}"}) ? date('d/m/Y H:i:s', strtotime($ordem_pagamento->{"data_{$tipo}"})) : '';
  506. $replace[$tipo] = $ordem_pagamento->contabilidade;
  507. }
  508. }
  509. $html->enableSection('main', $replace);
  510. $contents = $html->getContents();
  511. // converts the HTML template into PDF
  512. $dompdf = new \Dompdf\Dompdf();
  513. $dompdf->loadHtml($contents);
  514. $dompdf->setPaper('A3', 'portrait');
  515. $dompdf->render();
  516. // write and open file
  517. $docName = date('Y_m_d_H_i_s') . "_" . rand(1, 9999) . ".pdf";
  518. file_put_contents('app/output/' . $docName, $dompdf->output());
  519. $files = ['D:/htdocs/qualydocs/app/output/first_' . $docName];
  520. $pdf = new PDFMerger;
  521. $pdf->addPDF('app/output/' . $docName, '1');
  522. $pdf->merge('file', 'app/output/first_' . $docName);
  523. $criterio = new TCriteria;
  524. $criterio->add(new TFilter('fk_id_ordem_pagamento', '=', $ordem_pagamento->id));
  525. $anexos = OrdemPagamentoPortobayArquivo::getObjects($criterio);
  526. $domPdfPath = realpath('vendor/dompdf/dompdf');
  527. \PhpOffice\PhpWord\Settings::setPdfRendererPath($domPdfPath);
  528. \PhpOffice\PhpWord\Settings::setPdfRendererName('DomPDF');
  529. foreach ($anexos as $anexo) {
  530. if (file_exists($anexo->documento) && is_file($anexo->documento)) {
  531. $ext = mb_strtolower(pathinfo($anexo->documento, PATHINFO_EXTENSION));
  532. if ($ext == 'pdf') {
  533. $files[] = 'D:/htdocs/qualydocs/' . $anexo->documento;
  534. } elseif ($ext == 'txt') {
  535. $temp_txt = file_get_contents($anexo->documento);
  536. $html = new THtmlRenderer('app/reports/texto.html');
  537. $replace = [];
  538. $replace['texto'] = $temp_txt;
  539. $html->enableSection('main', $replace);
  540. // converts the HTML template into PDF
  541. $dompdf = new \Dompdf\Dompdf();
  542. $dompdf->loadHtml($html->getContents());
  543. $dompdf->setPaper('A3', 'portrait');
  544. $dompdf->render();
  545. // write and open file
  546. $f = "app/output/doc_" . date('Y_m_d_H_i_s') . "_" . rand(0, 99999) . ".pdf";
  547. file_put_contents($f, $dompdf->output());
  548. if (file_exists($f) && is_file($f)) {
  549. $files[] = 'D:/htdocs/qualydocs/' . $f;
  550. }
  551. } elseif (in_array($ext, array('doc', 'docx'))) {
  552. $f = "app/output/doc_" . date('Y_m_d_H_i_s') . "_" . rand(0, 99999) . ".pdf";
  553. $phpWord = \PhpOffice\PhpWord\IOFactory::load($anexo->documento);
  554. $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, "PDF");
  555. $objWriter->save($f);
  556. if (file_exists($f) && is_file($f)) {
  557. $files[] = 'D:/htdocs/qualydocs/' . $f;
  558. }
  559. } elseif (in_array($ext, array('xls', 'xlsx'))) {
  560. $f = "app/output/doc_" . date('Y_m_d_H_i_s') . "_" . rand(0, 99999) . ".pdf";
  561. $phpExcel = \PhpOffice\PhpSpreadsheet\IOFactory::load($anexo->documento);
  562. $objWriter = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($phpExcel, 'Dompdf');
  563. $objWriter->save($f);
  564. if (file_exists($f) && is_file($f)) {
  565. $files[] = 'D:/htdocs/qualydocs/' . $f;
  566. }
  567. }
  568. }
  569. }
  570. $files = implode(" ", $files);
  571. $output_file = 'D:/htdocs/qualydocs/app/output/full_' . $docName;
  572. $command = "D:/htdocs/qualydocs/gs/gswin32c.exe -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOUTPUTFILE=$output_file $files 2>&1";
  573. $result = shell_exec($command);
  574. TScript::create("console.log('$command');");
  575. TScript::create("console.log('$result');");
  576. return 'app/output/full_' . $docName;
  577. }
  578. private static function prepareDataHeader()
  579. {
  580. return [
  581. 'title' => "PATHFINDER EMPREENDIMENTOS E PARTICIPACOES LTDA",
  582. 'subtitle' => "Pagamentos em Aberto",
  583. 'subtitle2' => "Total de Solicitações",
  584. ];
  585. }
  586. private static function prepareData($ordem)
  587. {
  588. $unidade_monetaria = [1 => 'R$', 2 => '$', 3 => '€', 4 => '£'];
  589. $data_vencimento = !empty($ordem->data_vencimento)
  590. ? date('d/m/Y', strtotime($ordem->data_vencimento))
  591. : '';
  592. $unidade_monetaria = $unidade_monetaria[$ordem->unidade_monetaria] ?? '';
  593. return [
  594. 'razao_social' => htmlspecialchars($ordem->razao_social ?? ''),
  595. 'cnpj' => htmlspecialchars($ordem->cnpj ?? ''),
  596. 'data_vencimento' => htmlspecialchars($data_vencimento),
  597. 'numero_nf' => htmlspecialchars($ordem->numero_nf ?? ''),
  598. 'valor' => "{$unidade_monetaria} " . number_format(htmlspecialchars($ordem->valor ?? '0'), 2, ',', '.'),
  599. 'etapa' => htmlspecialchars($ordem->etapa ?? ''),
  600. 'fk_id_emissor' => $ordem->fk_id_emissor ? htmlspecialchars((new SystemUser($ordem->fk_id_emissor))->name ?? '') : '',
  601. ];
  602. }
  603. private static function generateTableRows($ordens)
  604. {
  605. $rows = "";
  606. foreach ($ordens as $ordem)
  607. {
  608. $data = self::prepareData($ordem);
  609. $rows .= "
  610. <tr>
  611. <td>{$data['razao_social']}</td>
  612. <td>{$data['cnpj']}</td>
  613. <td>{$data['data_vencimento']}</td>
  614. <td>{$data['numero_nf']}</td>
  615. <td>{$data['valor']}</td>
  616. <td>{$data['etapa']}</td>
  617. <td>{$data['fk_id_emissor']}</td>
  618. </tr>";
  619. }
  620. return $rows;
  621. }
  622. private static function generateSummary($total)
  623. {
  624. return "
  625. <section class='footer'>
  626. <ul class='summary-list'>
  627. <li>
  628. <span class='label'>Nº Total de Solicitações:</span>
  629. <span class='value'>{$total}</span>
  630. </li> </ul>
  631. </section>
  632. ";
  633. }
  634. private static function ImageToDataUrl($filename)
  635. {
  636. if(!file_exists($filename))
  637. throw new Exception('File not found.');
  638. $mime = mime_content_type($filename);
  639. if($mime === false)
  640. throw new Exception('Illegal MIME type.');
  641. $raw_data = file_get_contents($filename);
  642. if(empty($raw_data))
  643. throw new Exception('File not readable or empty.');
  644. return "data:{$mime};base64," . base64_encode($raw_data);
  645. }
  646. public static function generateHtml($ordens)
  647. {
  648. // Carrega o template HTML de um arquivo local.
  649. $template = file_get_contents('app/reports/relatorio2.html');
  650. // Prepara os dados do cabeçalho e substitui os placeholders no template.
  651. $headerData = self::prepareDataHeader();
  652. $placeholders = ['{$title}', '{$subtitle}', '{$subtitle2}'];
  653. $headerValues = [$headerData['title'], $headerData['subtitle'], $headerData['subtitle2']];
  654. $template = str_replace($placeholders, $headerValues, $template);
  655. // Gera as linhas da tabela com os dados das ordens e insere no template.
  656. $items = self::generateTableRows($ordens);
  657. $template = str_replace('<!-- [items] -->', $items, $template);
  658. // Conta o total de ordens e gera um resumo, inserindo-o no template.
  659. $total = count($ordens);
  660. $summary = self::generateSummary($total);
  661. $template = str_replace('<!-- [summary] -->', $summary, $template);
  662. $template = str_replace('LOGO', self::ImageToDataUrl("app/images/portobay.png"), $template);
  663. return $template;
  664. }
  665. public static function generatePdf($ordens)
  666. {
  667. $options = new Options();
  668. $options->set('isHtml5ParserEnabled', true);
  669. $options->set('isRemoteEnabled', true);
  670. $dompdf = new Dompdf($options);
  671. $total = count($ordens);
  672. $htmlContent = "";
  673. $htmlContent .= self::generateHtml($ordens);
  674. $dompdf->loadHtml($htmlContent);
  675. $dompdf->setPaper('A4', 'portrait');
  676. $dompdf->render();
  677. if (!is_dir('app/output/'))
  678. {
  679. mkdir('app/output/', 0777, true);
  680. }
  681. $fileName = 'app/output/ordens_pagamento_' . date('Y_m_d_H_i_s') . '.pdf';
  682. file_put_contents($fileName, $dompdf->output());
  683. return $fileName;
  684. }
  685. private static function showPdf2($filePath)
  686. {
  687. $window = TWindow::create('Ordem de Pagamento', 0.8, 0.8);
  688. $object = new TElement('object');
  689. $object->data = $filePath;
  690. $object->type = 'application/pdf';
  691. $object->style = "width: 100%; height:calc(100% - 10px)";
  692. $window->add($object);
  693. $window->show();
  694. }
  695. /**
  696. * Cria os critérios de filtro e ordenação.
  697. */
  698. private static function createCriteria($filters, $orderColumn, $orderDirection, $limit, $userid, $param)
  699. {
  700. $criteria = new TCriteria;
  701. $criteria->setProperties($param);
  702. $criteria->setProperty('order', $orderColumn);
  703. $criteria->setProperty('direction', $orderDirection);
  704. $criteria->setProperty('limit', $limit);
  705. // Adiciona filtros da sessão, se houver
  706. if ($filters)
  707. {
  708. foreach ($filters as $filter)
  709. {
  710. $criteria->add($filter);
  711. }
  712. }
  713. // Adiciona critérios de acesso e workflow
  714. $criteria->add(HomeSolicitacao::getAccessCriteria($userid, self::FORM_NUMBER - 1));
  715. $criteria->add(HomeSolicitacao::getWorkflowCriteria(self::FORM_NUMBER, $userid));
  716. return $criteria;
  717. }
  718. public static function onGenerateMultiple2($param)
  719. {
  720. $userid = TSession::getValue('userid');
  721. $filters = TSession::getValue('OrdemPagamentoPortobayConsulta_filters');
  722. $limit = TSession::getValue('OrdemPagamentoPortobayConsulta_limit') ?? 10;
  723. // Parâmetros de ordenação
  724. $orderColumn = $param['column'] ?? 'id';
  725. $orderDirection = $param['direction'] ?? 'desc';
  726. try
  727. {
  728. // Inicia a transação com o banco de dados
  729. TTransaction::open('permission');
  730. $param = $param ?? [];
  731. // Repositório e critério
  732. $repository = new TRepository('OrdemPagamentoPortobay');
  733. $criteria = self::createCriteria($filters, $orderColumn, $orderDirection, $limit, $userid, $param);
  734. // Carrega os objetos de acordo com o critério
  735. $ordens = $repository->load($criteria);
  736. if (!$ordens)
  737. {
  738. throw new Exception('Nenhum registro encontrado.');
  739. }
  740. // Verifica se há solicitações selecionadas
  741. $ordensSelecionadasIds = TSession::getValue('solicitacoes_selecionadas');
  742. // Se a sessão estiver vazia ou for um array vazio, usa os 10 registros carregados na página
  743. if (empty($ordensSelecionadasIds))
  744. {
  745. $ordensSelecionadas = $ordens; // Usa os registros carregados
  746. }
  747. else
  748. {
  749. // Converte IDs para objetos, pois ele recebe IDs
  750. $ordensSelecionadas = [];
  751. foreach ($ordensSelecionadasIds as $id)
  752. {
  753. //pega a instância do objeto OrdemPagamentoPortoBayo necessário
  754. $ordem = new OrdemPagamentoPortobay($id);
  755. if (!empty($ordem))
  756. {
  757. $ordensSelecionadas[] = $ordem; // pega o objeto fora do array
  758. }
  759. }
  760. }
  761. // Cria o PDF com todas as ordens selecionadas
  762. $fileName = self::generatePdf($ordensSelecionadas);
  763. // Exibe o PDF gerado
  764. self::showPdf2($fileName);
  765. // Finaliza a transação
  766. TTransaction::close();
  767. }
  768. catch (Exception $e)
  769. {
  770. new TMessage('error', $e->getMessage());
  771. TTransaction::rollback();
  772. }
  773. // Limpa as solicitações selecionadas
  774. TSession::setValue('solicitacoes_selecionadas', []);
  775. TScript::create("
  776. $('input[name^=\"check_select_\"]').each(function () {
  777. const key = $(this).val();
  778. $(this).prop('checked', false);
  779. console.log('desmarcando checkbox:', key);
  780. });
  781. ");
  782. }
  783. /**
  784. * Export datagrid as PDF
  785. */
  786. public function onExportPDF($param)
  787. {
  788. try {
  789. $output = 'app/output/' . uniqid() . '.pdf';
  790. $this->exportToPDF($output);
  791. $window = TWindow::create('Export', 0.8, 0.8);
  792. $object = new TElement('object');
  793. $object->{'data'} = $output;
  794. $object->{'type'} = 'application/pdf';
  795. $object->{'style'} = "width: 100%; height:calc(100% - 10px)";
  796. $window->add($object);
  797. $window->show();
  798. } catch (Exception $e) {
  799. new TMessage('error', $e->getMessage());
  800. }
  801. }
  802. /**
  803. * Export to PDF
  804. * @param $output Output file
  805. */
  806. public function exportToPDF($output)
  807. {
  808. if ((!file_exists($output) && is_writable(dirname($output))) or is_writable($output)) {
  809. $this->limit = 0;
  810. $this->datagrid->prepareForPrinting();
  811. $this->onReload();
  812. // string with HTML contents
  813. $html = clone $this->datagrid;
  814. $contents = file_get_contents('app/resources/styles-print.html') . $html->getContents();
  815. $options = new \Dompdf\Options();
  816. $options->setChroot(getcwd());
  817. // converts the HTML template into PDF
  818. $dompdf = new \Dompdf\Dompdf($options);
  819. $dompdf->loadHtml($contents);
  820. $dompdf->setPaper('A4', 'landscape');
  821. $dompdf->render();
  822. // write and open file
  823. file_put_contents($output, $dompdf->output());
  824. } else {
  825. throw new Exception(AdiantiCoreTranslator::translate('Permission denied') . ': ' . $output);
  826. }
  827. }
  828. /**
  829. * Export to CSV
  830. */
  831. public function onExportCSV($param)
  832. {
  833. try {
  834. $output = 'app/output/' . uniqid() . '.csv';
  835. $this->exportToCSV($output);
  836. TPage::openFile($output);
  837. } catch (Exception $e) {
  838. return new TMessage('error', $e->getMessage());
  839. }
  840. }
  841. /**
  842. * Export to CSV
  843. * @param $output Output file
  844. */
  845. public function exportToCSV($output)
  846. {
  847. if ((!file_exists($output) && is_writable(dirname($output))) or is_writable($output)) {
  848. TTransaction::openFake($this->database);
  849. // creates a criteria
  850. $criteria = new TCriteria;
  851. $userid = TSession::getValue('userid');
  852. $filters = TSession::getValue('OrdemPagamentoPortobayConsulta_filters');
  853. if ($filters != null) {
  854. foreach ($filters as $filtro) {
  855. $criteria->add($filtro);
  856. }
  857. }
  858. $criteria->add(HomeSolicitacao::getAccessCriteria($userid, self::FORM_NUMBER - 1));
  859. // creates a repository for DadosDB
  860. $repository = new TRepository('OrdemPagamentoPortobay');
  861. // load the objects according to criteria
  862. $objects = $repository->load($criteria, false);
  863. $handler = fopen($output, 'w');
  864. $header = [
  865. 'N° OP',
  866. 'Razão Social',
  867. 'Tipo Pessoa',
  868. 'CPF/CNPJ',
  869. 'Nota Fiscal',
  870. 'Data de Vencimento',
  871. 'Valor',
  872. 'Módulo',
  873. 'Status',
  874. 'Status Nota',
  875. 'Emissor',
  876. 'Cadastrado em',
  877. ];
  878. fputcsv($handler, $header);
  879. if ($objects) {
  880. $status = [1000 => 'Concluído', 1001 => 'Reprovado', 1002 => 'Reprovado'];
  881. $tipoPessoa = [1 => 'Física', 2 => 'Jurídica'];
  882. foreach ($objects as $object) {
  883. $fluxo = HomeSolicitacao::getFluxoByFormAndUser(
  884. self::FORM_NUMBER,
  885. $object->fluxo,
  886. $object->fk_id_emissor
  887. );
  888. $document = "";
  889. if ($object->tipo_pessoa == 1 && !empty($object->cpf)) {
  890. $document = $object->cpf;
  891. } elseif ($object->tipo_pessoa == 2 && !empty($object->cnpj)) {
  892. $document = $object->cnpj;
  893. }
  894. $emissor = new SystemUser($object->fk_id_emissor);
  895. $row = [
  896. $object->id,
  897. $object->razao_social,
  898. $tipoPessoa[$object->tipo_pessoa],
  899. $document,
  900. $object->numero_nf,
  901. !empty($object->data_vencimento) ? date('d/m/Y', strtotime($object->data_vencimento)) : '',
  902. number_format($object->valor, 2, ',', '.') . ' R$',
  903. $fluxo->nome,
  904. $status[$object->etapa_atual] ?? HomeSolicitacao::getCurrentStepLabel($fluxo, $object->etapa_atual),
  905. $object->nota_enviada ? 'Enviada' : 'Pendente',
  906. $emissor->name,
  907. !empty($object->data_cadastro) ? date('d/m/Y', strtotime($object->data_cadastro)) : '',
  908. ];
  909. fputcsv($handler, $row);
  910. }
  911. }
  912. fclose($handler);
  913. TTransaction::close();
  914. } else {
  915. throw new Exception(AdiantiCoreTranslator::translate('Permission denied') . ': ' . $output);
  916. }
  917. }
  918. /**
  919. * Delete a record
  920. */
  921. public function Delete($param)
  922. {
  923. try {
  924. $key = $param['key']; // get the parameter $key
  925. TTransaction::open('permission'); // open a transaction with database
  926. $object = new OrdemPagamentoPortobay($key); // instantiates the Active Record
  927. if ($object->fk_id_emissor != TSession::getValue('userid')) {
  928. TApplication::loadPage('OrdemPagamentoPortobayConsulta', 'showNotAllowed');
  929. return;
  930. }
  931. $anexos = OrdemPagamentoPortobayArquivo::where('fk_id_ordem_pagamento', '=', $object->id)
  932. ->orderBy('id')->load();
  933. if (!empty($anexos)) {
  934. foreach ($anexos as $documento) {
  935. if (file_exists($documento->documento) && is_file($documento->documento)) {
  936. unlink($documento->documento);
  937. }
  938. $documento->delete();
  939. }
  940. }
  941. $caminho = "files/ordem_pagamento_portobay/" . $object->id;
  942. if (file_exists($caminho) && is_dir($caminho)) {
  943. rmdir($caminho);
  944. }
  945. $object->delete();
  946. TTransaction::close(); // close the transaction
  947. new TMessage('info', AdiantiCoreTranslator::translate('Record deleted')); // success message
  948. $this->onReload($param); // reload the listing
  949. } catch (Exception $e) {
  950. new TMessage('error', $e->getMessage()); // shows the exception error message
  951. TTransaction::rollback(); // undo all pending operations
  952. }
  953. }
  954. public static function onMarkAsPending()
  955. {
  956. $solicitacoes = TSession::getValue('solicitacoes_selecionadas');
  957. if (!empty($solicitacoes)) {
  958. try {
  959. TTransaction::open('permission');
  960. $userid = TSession::getValue('userid');
  961. $dataAprovacao = date('d/m/y H:i:s');
  962. foreach ($solicitacoes as $id) {
  963. OrdemPagamentoPortobay::where('id', '=', $id)
  964. ->set('nota_enviada', 'f')
  965. ->set('status_nota_modificado_por', $userid)
  966. ->set('status_nota_modificado_em', $dataAprovacao)
  967. ->update();
  968. }
  969. TSession::setValue('solicitacoes_selecionadas', []);
  970. TTransaction::close();
  971. AdiantiCoreApplication::loadPage('OrdemPagamentoPortobayConsulta', 'showMessagePendingReceipt');
  972. } catch (Exception $e) {
  973. new TMessage('error', $e->getMessage());
  974. TTransaction::rollback();
  975. }
  976. } else {
  977. new TMessage('error', 'Favor selecionar algum item na lista!');
  978. }
  979. }
  980. public static function onMarkAsSent()
  981. {
  982. $solicitacoes = TSession::getValue('solicitacoes_selecionadas');
  983. if (!empty($solicitacoes)) {
  984. try {
  985. TTransaction::open('permission');
  986. $userid = TSession::getValue('userid');
  987. $dataAprovacao = date('d/m/y H:i:s');
  988. foreach ($solicitacoes as $id) {
  989. OrdemPagamentoPortobay::where('id', '=', $id)
  990. ->set('nota_enviada', 't')
  991. ->set('status_nota_modificado_por', $userid)
  992. ->set('status_nota_modificado_em', $dataAprovacao)
  993. ->update();
  994. }
  995. TSession::setValue('solicitacoes_selecionadas', []);
  996. TTransaction::close();
  997. AdiantiCoreApplication::loadPage('OrdemPagamentoPortobayConsulta', 'showMessageSentReceipt');
  998. } catch (Exception $e) {
  999. new TMessage('error', $e->getMessage());
  1000. TTransaction::rollback();
  1001. }
  1002. } else {
  1003. new TMessage('error', 'Favor selecionar algum item na lista!');
  1004. }
  1005. }
  1006. function onClear()
  1007. {
  1008. // get the search form data
  1009. $data = $this->form->getData();
  1010. TSession::setValue('OrdemPagamentoPortobayConsulta_filters', null);
  1011. TSession::setValue('solicitacoes_selecionadas', []);
  1012. $data->id = '';
  1013. $data->razao_social = '';
  1014. $data->cnpj = '';
  1015. $data->cpf = '';
  1016. $data->centro_de_custo = '';
  1017. $data->conta_contabil = '';
  1018. $data->numero_nf = '';
  1019. $data->data_vencimento_ini = '';
  1020. $data->data_vencimento_fim = '';
  1021. $data->valor_ini = '';
  1022. $data->valor_fim = '';
  1023. $data->data_cadastro_ini = '';
  1024. $data->data_cadastro_fim = '';
  1025. $data->fk_id_emissor = '';
  1026. $data->etapa = '';
  1027. $data->fk_id_cadastro = '';
  1028. // fill the form with data again
  1029. $this->form->setData($data);
  1030. TSession::setValue('OrdemPagamentoPortobayConsulta_filter_data', $data);
  1031. $param = [];
  1032. $param['offset'] = 0;
  1033. $param['first_page'] = 1;
  1034. $this->onReload($param);
  1035. }
  1036. /**
  1037. * Função auxiliar para criar o filtro de etapa
  1038. */
  1039. private function createEtapaFilter($etapa)
  1040. {
  1041. if (strpos($etapa, '-') !== false)
  1042. {
  1043. $parts = explode('-', $etapa);
  1044. $criteria = new TCriteria;
  1045. $criteria->add(new TFilter('fluxo', '=', $parts[0]));
  1046. $criteria->add(new TFilter('etapa_atual', '=', $parts[1]));
  1047. return $criteria;
  1048. }
  1049. else
  1050. {
  1051. return new TFilter('etapa_atual', '=', "{$etapa}");
  1052. }
  1053. }
  1054. /**
  1055. * Register the filter in the session
  1056. */
  1057. public function onSearch($param = NULL)
  1058. {
  1059. // Obtém os dados do formulário de busca
  1060. $data = $this->form->getData();
  1061. // Limpa os filtros de sessão
  1062. TSession::setValue('OrdemPagamentoPortobayConsulta_filters', NULL);
  1063. $filters = [];
  1064. // Mapeamento de campos e seus operadores
  1065. $fields = [
  1066. 'id' => ['field' => 'id', 'operator' => '=', 'value' => $data->id],
  1067. 'razao_social' => ['field' => 'razao_social', 'operator' => 'ilike', 'value' => $data->razao_social],
  1068. 'cnpj' => ['field' => 'cnpj', 'operator' => 'ilike', 'value' => $data->cnpj],
  1069. 'cpf' => ['field' => 'cpf', 'operator' => 'ilike', 'value' => $data->cpf],
  1070. 'centro_de_custo' => ['field' => 'centro_de_custo', 'operator' => 'ilike', 'value' => $data->centro_de_custo],
  1071. 'conta_contabil' => ['field' => 'conta_contabil', 'operator' => '=', 'value' => $data->conta_contabil],
  1072. 'numero_nf' => ['field' => 'numero_nf', 'operator' => '=', 'value' => $data->numero_nf],
  1073. 'data_vencimento_ini' => ['field' => 'data_vencimento', 'operator' => '>=', 'value' => $data->data_vencimento_ini],
  1074. 'data_vencimento_fim' => ['field' => 'data_vencimento', 'operator' => '<=', 'value' => $data->data_vencimento_fim],
  1075. 'valor_ini' => ['field' => 'valor', 'operator' => '>=', 'value' => $data->valor_ini],
  1076. 'valor_fim' => ['field' => 'valor', 'operator' => '<=', 'value' => $data->valor_fim],
  1077. 'data_cadastro_ini' => ['field' => 'data_cadastro', 'operator' => '>=', 'value' => $data->data_cadastro_ini],
  1078. 'data_cadastro_fim' => ['field' => 'data_cadastro', 'operator' => '<=', 'value' => $data->data_cadastro_fim],
  1079. ];
  1080. // Adiciona filtros a partir do array de campos
  1081. foreach ($fields as $field => $config)
  1082. {
  1083. if (isset($config['value']) && $config['value'] !== '')
  1084. {
  1085. $value = $config['operator'] == 'ilike' ? "%{$config['value']}%" : "{$config['value']}";
  1086. $filters[] = new TFilter($config['field'], $config['operator'], $value);
  1087. }
  1088. }
  1089. // Filtro de etapa
  1090. if (isset($data->etapa) && strlen(trim($data->etapa)) > 0)
  1091. {
  1092. $filters[] = $this->createEtapaFilter($data->etapa);
  1093. }
  1094. // Filtros com valores múltiplos
  1095. if (!empty($data->fk_id_emissor))
  1096. {
  1097. $filters[] = new TFilter('fk_id_emissor', 'IN', $data->fk_id_emissor);
  1098. }
  1099. if (!empty($data->fk_id_cadastro))
  1100. {
  1101. $modulos = implode(',', $data->fk_id_cadastro);
  1102. $filters[] = new TFilter('fluxo', 'IN', "(SELECT fluxo FROM solicitacao.cadastro_etapas WHERE id IN ({$modulos}))");
  1103. }
  1104. // Define os filtros na sessão
  1105. TSession::setValue('OrdemPagamentoPortobayConsulta_filters', $filters);
  1106. // Preenche novamente o formulário com os dados
  1107. $this->form->setData($data);
  1108. // Armazena os dados de busca na sessão
  1109. TSession::setValue('OrdemPagamentoPortobayConsulta_filter_data', $data);
  1110. // Recarrega a lista com os novos parâmetros
  1111. $param = [];
  1112. $param['offset'] = 0;
  1113. $param['first_page'] = 1;
  1114. $this->onReload($param);
  1115. }
  1116. /**
  1117. * Load the datagrid with data
  1118. */
  1119. public function onReload($param = NULL)
  1120. {
  1121. $userid = TSession::getValue('userid');
  1122. $filters = TSession::getValue('OrdemPagamentoPortobayConsulta_filters');
  1123. $limit = TSession::getValue('OrdemPagamentoPortobayConsulta_limit') ?? 10;
  1124. // Parâmetros de ordenação
  1125. $orderColumn = $param['column'] ?? 'id';
  1126. $orderDirection = $param['direction'] ?? 'desc';
  1127. try
  1128. {
  1129. // Inicia uma transação com o banco de dados 'permission'
  1130. TTransaction::open('permission');
  1131. $documentosSelecionados = TSession::getValue('solicitacoes_selecionadas');
  1132. $param = $param ?? [];
  1133. // Cria um repositório para OrdemPagamentoPortobay
  1134. $repository = new TRepository('OrdemPagamentoPortobay');
  1135. // Cria os critérios de pesquisa
  1136. $criteria = self::createCriteria($filters, $orderColumn, $orderDirection, $limit, $userid, $param);
  1137. // Carrega os objetos de acordo com os critérios
  1138. $objects = $repository->load($criteria, false);
  1139. if (is_callable($this->transformCallback))
  1140. {
  1141. call_user_func($this->transformCallback, $objects, $param);
  1142. }
  1143. $this->datagrid->clear();
  1144. if ($objects)
  1145. {
  1146. // Verifica se o usuário tem permissão no grupo Financeiro
  1147. $isFinanceiro = SystemUserGroup::where('system_user_id', '=', $userid)
  1148. ->where('system_group_id', 'IN', "(SELECT id FROM permission.system_group WHERE name ILIKE '%Financeiro%Master%Portobay%')")
  1149. ->count() > 0;
  1150. $status = [1000 => 'Concluído', 1001 => 'Reprovado', 1002 => 'Reprovado'];
  1151. $label = [1000 => 'success', 1001 => 'danger', 1002 => 'danger'];
  1152. $data = new stdClass;
  1153. // Itera sobre a coleção de registros
  1154. foreach ($objects as $object)
  1155. {
  1156. $fluxo = HomeSolicitacao::getFluxoByFormAndUser(
  1157. self::FORM_NUMBER,
  1158. $object->fluxo,
  1159. $object->fk_id_emissor
  1160. );
  1161. $idSelected = $object->id;
  1162. $chave_select = "validado_{$idSelected}";
  1163. $id_checkGroup = "check_select_{$idSelected}";
  1164. // Cria o grupo de checkboxes
  1165. $object->select = new TCheckGroup($id_checkGroup);
  1166. // A linha abaixo foi removida para evitar a atribuição manual de IDs duplicados
  1167. //$object->select->id = $chave_select;
  1168. $object->select->addItems(array($idSelected => ''));
  1169. $object->select->setChangeAction(new TAction([$this, 'onSelecionados']));
  1170. $this->form->addField($object->select);
  1171. if (!empty($documentosSelecionados) && in_array($object->id, $documentosSelecionados))
  1172. {
  1173. $data->{$id_checkGroup} = [$idSelected];
  1174. }
  1175. // Ajusta o CNPJ/CPF dependendo do tipo de pessoa
  1176. $object->cnpj = ($object->tipo_pessoa == 1 && !empty($object->cpf)) ? $object->cpf : $object->cnpj;
  1177. $emissor = new SystemUser($object->fk_id_emissor);
  1178. $object->can_edit = $object->etapa_atual == 1001 && $userid == $object->fk_id_emissor;
  1179. $object->can_edit_financeiro = $isFinanceiro;
  1180. $object->can_generate = $object->etapa_atual == 1000;
  1181. $object->can_delete = $userid == $object->fk_id_emissor;
  1182. // Cria os links para exibição
  1183. $tipoPessoa = [1 => 'Física', 2 => 'Jurídica'];
  1184. $object->razao_social = self::createLink($object->razao_social, $object->id);
  1185. $object->cnpj = self::createLink(empty($object->cnpj) ? '-' : $object->cnpj, $object->id);
  1186. $object->numero_nf = self::createLink($object->numero_nf, $object->id);
  1187. $object->data_vencimento = self::createLink(!empty($object->data_vencimento) ? date('d/m/Y', strtotime($object->data_vencimento)) : '', $object->id);
  1188. $object->fk_id_emissor = self::createLink($emissor->name, $object->id);
  1189. $object->data_cadastro = self::createLink(!empty($object->data_cadastro) ? date('d/m/Y', strtotime($object->data_cadastro)) : '', $object->id);
  1190. $object->tipo = self::createLink($fluxo->nome, $object->id);
  1191. $object->tipo_pessoa = self::createLink(!empty($object->tipo_pessoa) ? $tipoPessoa[$object->tipo_pessoa] : 'Indefinido', $object->id);
  1192. // Adiciona os labels de status e nota enviada
  1193. $div = new TElement('span');
  1194. $div->class = "label label-" . ($label[$object->etapa_atual] ?? "info");
  1195. $div->style = "text-shadow:none; font-size:12px";
  1196. $div->add($status[$object->etapa_atual] ?? HomeSolicitacao::getCurrentStepLabel($fluxo, $object->etapa_atual));
  1197. $object->etapa = $div;
  1198. $div = new TElement('span');
  1199. $div->class = "label label-" . ($object->nota_enviada ? 'success' : 'danger');
  1200. $div->style = "text-shadow:none; font-size:12px; font-weight:lighter";
  1201. $div->add($object->nota_enviada ? 'Enviada' : 'Pendente');
  1202. $object->nota_enviada = $div;
  1203. // Adiciona o objeto ao datagrid
  1204. $this->datagrid->addItem($object);
  1205. }
  1206. $this->form->setData($data);
  1207. }
  1208. // Conta os registros
  1209. $criteria->resetProperties();
  1210. $count = $repository->count($criteria);
  1211. $this->pageNavigation->setCount($count);
  1212. $this->pageNavigation->setProperties($param);
  1213. $this->pageNavigation->setLimit($limit);
  1214. // Fecha a transação
  1215. TTransaction::close();
  1216. $this->loaded = true;
  1217. }
  1218. catch (Exception $e)
  1219. {
  1220. // Mostra a mensagem de erro
  1221. new TMessage('error', $e->getMessage());
  1222. // Desfaz as operações pendentes
  1223. TTransaction::rollback();
  1224. }
  1225. }
  1226. public static function createLink($text, $id)
  1227. {
  1228. return TElement::tag(
  1229. 'a',
  1230. $text,
  1231. [
  1232. 'href ' => (new TAction(['OrdemPagamentoPortobayView', 'onViewFromConsulta'], ['id' => $id, 'key' => $id]))->serialize(),
  1233. 'generator' => 'adianti',
  1234. 'style' => 'color: #212529;'
  1235. ]
  1236. );
  1237. }
  1238. /**
  1239. * method show()
  1240. * Shows the page
  1241. */
  1242. public function show()
  1243. {
  1244. // check if the datagrid is already loaded
  1245. if (!$this->loaded and (!isset($_GET['method']) or !(in_array($_GET['method'], array('onEnter', 'onReload', 'onSearch', 'onClear', 'Delete', 'showMessageReenviado', 'showNotAllowed', 'showNotFound', 'showNotAllowedCreate', 'showMessagePendingReceipt', 'showMessageSentReceipt'))))) {
  1246. if (func_num_args() > 0) {
  1247. $this->onReload(func_get_arg(0));
  1248. } else {
  1249. $this->onReload();
  1250. }
  1251. }
  1252. $this->loaded = true;
  1253. parent::show();
  1254. }
  1255. function showMessageEnviado()
  1256. {
  1257. new TMessage('info', 'Ordem de pagamento Portobay foi enviada!');
  1258. TSession::setValue('propostas_selecionadas', []);
  1259. $this->onReload();
  1260. }
  1261. function showMessageReenviado()
  1262. {
  1263. new TMessage('info', 'Ordem de pagamento Portobay foi reenviada!');
  1264. TSession::setValue('propostas_selecionadas', []);
  1265. $this->onReload();
  1266. }
  1267. function showMessagePendingReceipt()
  1268. {
  1269. new TMessage('info', 'Ordens de Pagamento Portobay atualizadas como pendente nota com sucesso!');
  1270. $this->onReload();
  1271. }
  1272. function showMessageSentReceipt()
  1273. {
  1274. new TMessage('info', 'Ordens de Pagamento Portobay atualizadas como nota enviada com sucesso!');
  1275. $this->onReload();
  1276. }
  1277. function showNotAllowed()
  1278. {
  1279. new TMessage('error', 'Você não tem permissão para editar/remover esta proposta!');
  1280. $this->onReload();
  1281. }
  1282. function showNotAllowedCreate()
  1283. {
  1284. new TMessage('error', 'Você não tem permissão para abrir propostas!');
  1285. $this->onReload();
  1286. }
  1287. function showNotFound()
  1288. {
  1289. new TMessage('error', 'Proposta não encontrada!');
  1290. $this->onReload();
  1291. }
  1292. }
  1293. ?>


Curso Dominando o Adianti Framework

O material mais completo de treinamento do Framework.
Curso em vídeo aulas + Livro completo + Códigos fontes do projeto ERPHouse.
Conteúdo Atualizado!


Dominando o Adianti Framework Quero me inscrever agora!

Comentários (2)


LS

Antes eu estava fazendo a chamada do JS dessa maneira
 
  1. <?php
  2. TScript::create("
  3. function selectAll(el) {
  4. $('input[name^=\"check_select_\"]').each(function () {
  5. $(this).prop('checked', !el.checked);
  6. $(this).click();
  7. });
  8. }
  9. $(document).ready(function(){
  10. $('#datagrid_list').parent().parent().addClass('margin_bottom_120');
  11. });
  12. ");
  13. public static function onSelecionados($param)
  14. {
  15. $documentosSelecionados = TSession::getValue('solicitacoes_selecionadas');
  16. if (empty($documentosSelecionados)) {
  17. $documentosSelecionados = [];
  18. }
  19. $key = $param['key'];
  20. $chave = array_search($key, $documentosSelecionados);
  21. if ($chave !== false)
  22. {
  23. unset($documentosSelecionados[$chave]);
  24. }
  25. else
  26. {
  27. $documentosSelecionados[] = $key;
  28. }
  29. echo "<pre>"; print_r($documentosSelecionados); echo "</pre>";
  30. TSession::setValue('solicitacoes_selecionadas', $documentosSelecionados);
  31. }
  32. ?>


O problema era quando clicava no botão para selecionar todos e ele nunca retornava os valores corretos.
Se algum de vocês puderem me ajudar
PD

Lucas,

Evita postar tanto código. Dificilmente alguém irá conseguir ajudar por que não irá conseguir simular (rodar o mesmo código) localmente. Foque as dúvidas relativas ao Framework, não à código javascript em si, visto que este espaço é exclusivo para dúvidas do framework.