Gerar relatorio PDF e imprimi-lo A principio eu criei um formulário mestre/detalhe para cadastrar Vendas (mestre) e ItensVenda (detalhes , até então tudo certo. Agora preciso de um página que liste todas as despesas com seus respectivos itens e com opção para gerar um relatório em PDF e impressão. ...
JP
Gerar relatorio PDF e imprimi-lo  
A principio eu criei um formulário mestre/detalhe para cadastrar Vendas (mestre) e ItensVenda (detalhes , até então tudo certo. Agora preciso de um página que liste todas as despesas com seus respectivos itens e com opção para gerar um relatório em PDF e impressão.

 
  1. <?php
  2. /**
  3. * VendaForm Master/Detail
  4. * @author <your name here>
  5. */
  6. class VendaForm extends TPage
  7. {
  8. protected $form; // form
  9. protected $detail_list;
  10. /**
  11. * Page constructor
  12. */
  13. public function __construct()
  14. {
  15. parent::__construct();
  16. // creates the form
  17. $this->form = new BootstrapFormBuilder('form_Venda');
  18. $this->form->setFormTitle('Venda');
  19. // master fields
  20. $ven_cod = new TEntry('ven_cod');
  21. $cliente = new TEntry('cliente');
  22. $cli_cod_fk = new TDBUniqueSearch('cli_cod_fk', 'bd_venda', 'Cliente', 'cli_cod', 'cli_nome');
  23. // detail fields
  24. $detail_itv_cod = new THidden('detail_itv_cod');
  25. $detail_cod_prod = new TDBUniqueSearch('detail_cod_prod', 'bd_venda', 'Produto', 'pro_cod', 'pro_nome');
  26. $detail_preco_venda = new TEntry('detail_preco_venda');
  27. $detail_quantidade = new TEntry('detail_quantidade');
  28. $detail_cod_prod->setChangeAction( new TAction([$this, 'onProductChange']));
  29. if (!empty($ven_cod))
  30. {
  31. $ven_cod->setEditable(FALSE);
  32. }
  33. // master fields
  34. $this->form->addFields( [new TLabel('Código')], [$ven_cod] );
  35. $this->form->addFields( [new TLabel('Cliente')], [$cliente] );
  36. $this->form->addFields( [new TLabel('Cliente Fidelizado')], [$cli_cod_fk] );
  37. // detail fields
  38. $this->form->addContent( ['<h4>Detalhes da Venda</h4><hr>'] );
  39. $this->form->addFields( [$detail_itv_cod] );
  40. $this->form->addFields( [new TLabel('Produto')], [$detail_cod_prod] );
  41. $this->form->addFields( [new TLabel('Preço ')], [$detail_preco_venda] );
  42. $this->form->addFields( [new TLabel('Quantidade')], [$detail_quantidade] );
  43. $add = TButton::create('add', [$this, 'onSaveDetail'], 'Register', 'fa:save');
  44. $this->form->addFields( [], [$add] )->style = 'background: whitesmoke; padding: 5px; margin: 1px;';
  45. $this->detail_list = new BootstrapDatagridWrapper(new TQuickGrid);
  46. $this->detail_list->style = "min-width: 700px; width:100%;margin-bottom: 10px";
  47. $this->detail_list->setId('Venda_list');
  48. // items
  49. $prod= $this->detail_list->addQuickColumn('Produto', 'cod_prod', 'left', 50);
  50. $preco= $this->detail_list->addQuickColumn('Preço ', 'preco_venda', 'left', 30);
  51. $this->detail_list->addQuickColumn('Quantidade', 'quantidade', 'left', 30);
  52. //Calcula o total da datagrid
  53. $subtotal = $this->detail_list->addQuickColumn('Subtotal', '={quantidade} * {preco_venda}', 'right', 50);
  54. //Converte o valor numerico em milhares
  55. $format_value = function($value){
  56. if (is_numeric($value))
  57. {
  58. return 'Kz ' . number_format ($value, 2, ' , ' , ' . ');
  59. }
  60. return $value;
  61. };
  62. $subtotal->setTransformer($format_value);
  63. $preco->setTransformer($format_value);
  64. $subtotal->setTotalFunction(function($values){
  65. return array_sum((array) $values);
  66. });
  67. $prod-> setTransformer( function ($value) {
  68. return Produto :: findInTransaction ( 'bd_venda' , $value )->pro_nome;
  69. });
  70. // detail actions
  71. $this->detail_list->addQuickAction( 'Edit', new TDataGridAction([$this, 'onEditDetail']), 'itv_cod', 'fa:edit blue');
  72. $this->detail_list->addQuickAction( 'Delete', new TDataGridAction([$this, 'onDeleteDetail']), 'itv_cod', 'fa:trash red');
  73. $this->detail_list->createModel();
  74. $panel = new TPanelGroup;
  75. $panel->add($this->detail_list);
  76. $panel->getBody()->style = 'overflow-x:auto';
  77. $this->form->addContent( [$panel] );
  78. $btn = $this->form->addAction( _t('Save'), new TAction([$this, 'onSave']), 'fa:save');
  79. $btn->class = 'btn btn-sm btn-primary';
  80. $this->form->addAction( _t('Clear'), new TAction([$this, 'onClear']), 'fa:eraser red');
  81. // create the page container
  82. $container = new TVBox;
  83. $container->style = 'width: 100%';
  84. // $container->add(new TXMLBreadCrumb('menu.xml', __CLASS__));
  85. $container->add($this->form);
  86. parent::add($container);
  87. }
  88. //METODO QUE BUSCA O PREÇO DO ITEM
  89. public static function onProductChange( $params )
  90. {
  91. if(!empty($params['detail_cod_prod']))
  92. {
  93. try
  94. {
  95. TTransaction :: open('bd_venda');
  96. $produto = Produto :: find($params['detail_cod_prod']);
  97. $fill_data = new StdClass;
  98. $fill_data->detail_preco_venda = $produto->pro_preco;
  99. TForm :: sendData ('form_Venda', $fill_data);
  100. TTransaction::close();
  101. }
  102. catch(Exception $e)
  103. {
  104. new TMessage('error', $e->getMessage());
  105. TTransaction::rollback();
  106. }
  107. }
  108. }
  109. /**
  110. * Clear form
  111. * @param $param URL parameters
  112. */
  113. public function onClear($param)
  114. {
  115. $this->form->clear(TRUE);
  116. TSession::setValue(__CLASS__.'_items', array());
  117. $this->onReload( $param );
  118. }
  119. /**
  120. * Save an item from form to session list
  121. * @param $param URL parameters
  122. */
  123. public function onSaveDetail( $param )
  124. {
  125. try
  126. {
  127. TTransaction::open('bd_venda');
  128. $data = $this->form->getData();
  129. /** validation sample
  130. if (empty($data->fieldX))
  131. {
  132. throw new Exception('The field fieldX is required');
  133. }
  134. **/
  135. $items = TSession::getValue(__CLASS__.'_items');
  136. $key = empty($data->detail_itv_cod) ? 'X'.mt_rand(1000000000, 1999999999) : $data->detail_itv_cod;
  137. $items[ $key ] = array();
  138. $items[ $key ]['itv_cod'] = $key;
  139. $items[ $key ]['cod_prod'] = $data->detail_cod_prod;
  140. $items[ $key ]['preco_venda'] = $data->detail_preco_venda;
  141. $items[ $key ]['quantidade'] = $data->detail_quantidade;
  142. TSession::setValue(__CLASS__.'_items', $items);
  143. // clear detail form fields
  144. $data->detail_itv_cod = '';
  145. $data->detail_cod_prod = '';
  146. $data->detail_preco_venda = '';
  147. $data->detail_quantidade = '';
  148. TTransaction::close();
  149. $this->form->setData($data);
  150. $this->onReload( $param ); // reload the items
  151. }
  152. catch (Exception $e)
  153. {
  154. $this->form->setData( $this->form->getData());
  155. new TMessage('error', $e->getMessage());
  156. }
  157. $this->form->clear(TRUE); //Para Limpar os campos do formulario Mestre
  158. }
  159. /**
  160. * Load an item from session list to detail form
  161. * @param $param URL parameters
  162. */
  163. public static function onEditDetail( $param )
  164. {
  165. // read session items
  166. $items = TSession::getValue(__CLASS__.'_items');
  167. // get the session item
  168. $item = $items[ $param['key'] ];
  169. $data = new stdClass;
  170. $data->detail_itv_cod = $item['itv_cod'];
  171. $data->detail_cod_prod = $item['cod_prod'];
  172. $data->detail_preco_venda = $item['preco_venda'];
  173. $data->detail_quantidade = $item['quantidade'];
  174. // fill detail fields
  175. TForm::sendData( 'form_Venda', $data );
  176. }
  177. /**
  178. * Delete an item from session list
  179. * @param $param URL parameters
  180. */
  181. public static function onDeleteDetail( $param )
  182. {
  183. // reset items
  184. $data = new stdClass;
  185. $data->detail_cod_prod = '';
  186. $data->detail_preco_venda = '';
  187. $data->detail_quantidade = '';
  188. // clear form data
  189. TForm::sendData('form_Venda', $data );
  190. // read session items
  191. $items = TSession::getValue(__CLASS__.'_items');
  192. // get detail id
  193. $detail_id = $param['key'];
  194. // delete the item from session
  195. unset($items[ $detail_id ] );
  196. // rewrite session items
  197. TSession::setValue(__CLASS__.'_items', $items);
  198. // delete item from screen
  199. TScript::create("ttable_remove_row_by_id('Venda_list', '{$detail_id}')");
  200. }
  201. /**
  202. * Load the items list from session
  203. * @param $param URL parameters
  204. */
  205. public function onReload($param)
  206. {
  207. // read session items
  208. $items = TSession::getValue(__CLASS__.'_items');
  209. $this->detail_list->clear(); // clear detail list
  210. if ($items)
  211. {
  212. foreach ($items as $list_item)
  213. {
  214. $item = (object) $list_item;
  215. $row = $this->detail_list->addItem( $item );
  216. $row->id = $list_item['itv_cod'];
  217. }
  218. }
  219. $this->loaded = TRUE;
  220. }
  221. /**
  222. * Load Master/Detail data from database to form/session
  223. */
  224. public function onEdit($param)
  225. {
  226. try
  227. {
  228. TTransaction::open('bd_venda');
  229. if (isset($param['key']))
  230. {
  231. $key = $param['key'];
  232. $object = new Venda($key);
  233. $items = Itensvenda::where('cod_venda', '=', $key)->load();
  234. $session_items = array();
  235. foreach( $items as $item )
  236. {
  237. $item_key = $item->itv_cod;
  238. $session_items[$item_key] = $item->toArray();
  239. $session_items[$item_key]['itv_cod'] = $item->itv_cod;
  240. $session_items[$item_key]['cod_prod'] = $item->cod_prod;
  241. $session_items[$item_key]['preco_venda'] = $item->preco_venda;
  242. $session_items[$item_key]['quantidade'] = $item->quantidade;
  243. // $session_items[$item_key]['desconto'] = $item->desconto;
  244. }
  245. TSession::setValue(__CLASS__.'_items', $session_items);
  246. $this->form->setData($object); // fill the form with the active record data
  247. $this->onReload( $param ); // reload items list
  248. TTransaction::close(); // close transaction
  249. }
  250. else
  251. {
  252. $this->form->clear(TRUE);
  253. TSession::setValue(__CLASS__.'_items', null);
  254. $this->onReload( $param );
  255. }
  256. }
  257. catch (Exception $e) // in case of exception
  258. {
  259. new TMessage('error', $e->getMessage());
  260. TTransaction::rollback();
  261. }
  262. }
  263. /**
  264. * Save the Master/Detail data from form/session to database
  265. */
  266. public function onSave()
  267. {
  268. try
  269. {
  270. // open a transaction with database
  271. TTransaction::open('bd_venda');
  272. $data = $this->form->getData();
  273. $master = new Venda;
  274. $master->fromArray( (array) $data);
  275. $this->form->validate(); // Valida a data do formulario
  276. $master->store(); // save master object
  277. // delete details
  278. $old_items = Itensvenda::where('cod_venda', '=', $master->ven_cod)->load();
  279. $keep_items = array();
  280. // get session items
  281. $items = TSession::getValue(__CLASS__.'_items');
  282. if( $items )
  283. {
  284. foreach( $items as $item )
  285. {
  286. if (substr($item['itv_cod'],0,1) == 'X' ) // new record
  287. {
  288. $detail = new Itensvenda;
  289. }
  290. else
  291. {
  292. $detail = Itensvenda::find($item['itv_cod']);
  293. }
  294. $detail->cod_prod = $item['cod_prod'];
  295. $detail->preco_venda = $item['preco_venda'];
  296. $detail->quantidade = $item['quantidade'];
  297. $detail->cod_venda = $master->ven_cod;
  298. // Criamos um Campo ven_total para guardar o total da venda
  299. $detail->ven_total = ($detail->quantidade * ($detail->preco_venda));
  300. $detail->store(); // Guarda os itens dos detalhes
  301. $this->form->setData($data); // Preencha a Data no Formulário
  302. $master->ven_total += $detail->ven_total;
  303. $master->venda_data = date('Y-m-d H:m:s');
  304. $keep_items[] = $detail->itv_cod;
  305. }
  306. $master->store();
  307. }
  308. if ($old_items)
  309. {
  310. foreach ($old_items as $old_item)
  311. {
  312. if (!in_array( $old_item->itv_cod, $keep_items))
  313. {
  314. $old_item->delete();
  315. }
  316. }
  317. }
  318. TTransaction::close(); // close the transaction
  319. // reload form and session items
  320. $this->onEdit(array('key'=>$master->ven_cod));
  321. new TMessage('info', TAdiantiCoreTranslator::translate('Record saved'));
  322. }
  323. catch (Exception $e) // in case of exception
  324. {
  325. new TMessage('error', $e->getMessage());
  326. $this->form->setData( $this->form->getData() ); // keep form data
  327. TTransaction::rollback();
  328. }
  329. $this->form->clear(TRUE); //Para Limpar os campos do formulario Mestre
  330. }
  331. /**
  332. * Show the page
  333. */
  334. public function show()
  335. {
  336. // check if the datagrid is already loaded
  337. if (!$this->loaded AND (!isset($_GET['method']) OR $_GET['method'] !== 'onReload') )
  338. {
  339. $this->onReload( func_get_arg(0) );
  340. }
  341. parent::show();
  342. }
  343. }

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 (1)