Maestro-Detalle / Factura Compra en Yii – Parte II

| 2014-01-16 | 0 Comments

fac-compraContinuamos con el tutorial, nos falta la parte del controlador y también las vistas!!!

Link para crear la factura compra: http://localhost/proyecto/index.php?r=cabcompra/create esto es en mi caso, deben de reemplazar con sus respectivos datos.

Controlador CabCompra.php (solamente se necesita un controlador):

El controlador es la parte más tediosa ya que ahí es donde se procede a hacer todos los cálculos y luego el guardado de los datos una vez validado.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
<?php
 
class CabCompraController extends Controller
{
 
public $detallecompra;
 public $layout='//layouts/column1';
 
 public function filters()
 {
 
 }
 
 public function actionView($id)
 {
 $this->layout='//layouts/column2';
 $this->render('view',array(
 'model'=>$this->loadModel((int)$id),
 ));
 }
 
 public function actionGetPrecioTotal() {
 //Imprimimos el resumen
 echo Compra::getTotal();
 }
 
 private function borrarTodo()
 {
 Compra::setContenidoCompra(array());
 Compra::setProveedor(null);
 Compra::setPago(null);
 Compra::setDoc(null);
 Compra::setContenidoCheque(array());
 }
 
 public function actionUpdateCantidad()
 {
 //Abrimos el contenido
 $compra= Compra::getContenidoCompra();
 
foreach($_GET as $key => $value)
 {
 if(substr($key, 0, 9) == 'cantidad_')
 {
 if (!is_numeric($value) || $value <= 0 || $value == ' ')
 throw new CException('Cantidad Invalida');
 $position = explode('_', $key);
 $position = $position[1];
 //Si existe cantidad
 if(isset($compra[$position]['cantidad']))
 $compra[$position]['cantidad'] = $value;
 $precio=$compra[$position]['precio']-(($compra[$position]['precio']*$compra[$position]['dcto'])/100);
 //$model = Productos::model()->findByPk($compra[$position]['id_producto']);
 //$resultado=ProductoProveedor::getProductoProveedor($compra[$position]['id_producto']);
 echo $value*$precio;
 //Guardamos el contenido
 return Compra::setContenidoCompra($compra);
 }
 }
 }
 
 public function actionUpdatePrecio()
 {
 //Para actualizar precio
 $compra= Compra::getContenidoCompra();
 
foreach($_GET as $key => $value)
 {
 if(substr($key, 0, 7) == 'precio_')
 {
 if (!is_numeric($value) || $value <= 0 || $value == ' ')
 throw new CException('Precio Invalido');
 $position = explode('_', $key);
 $position = $position[1];
 if(isset($compra[$position]['precio']))
 $compra[$position]['precio'] = $value;
 $precio=$compra[$position]['precio']-(($compra[$position]['precio']*$compra[$position]['dcto'])/100);
 echo $precio*$compra[$position]['cantidad'];
 return Compra::setContenidoCompra($compra);
 }
 }
 }
 
 public function actionAddItem()
 {
 //Definimos c como null para comprobación
 $c=null;
 //Abrimos el contenido
 $compra=Compra::getContenidoCompra();
 
 //Eliminamos los atributos POST innecesarios
 if(isset($_POST['yt0']))
 unset($_POST['yt0']);
 if(isset($_POST['yt1']))
 unset($_POST['yt1']);
 if(isset($_POST['nombre_producto']))
 unset($_POST['nombre_producto']);
 
//Consultamos si el existe producto para aumentar la cantidad
 if($_POST['id_producto']>0)
 {
 if($compra)
 foreach ($compra as $position => $product)
 {
 if($product['id_producto']==$_POST['id_producto'])
 {
 $compra[$position]['cantidad']+=$_POST['cantidad'];
 $c=1;
 }
 }
 //Si no existe producto repetido, se asigna lo mandado por POST
 if($c==null)
 {
 $model = Productos::model()->findByPk($_POST['id_producto']);
 $_POST['desc']= $model->descripcion;
 $_POST['precio']= $model->precio_compra;
 $_POST['dcto']= $model->descuento;
 //Iva en forma manual, se puede cargar de la DB si se desea
 $_POST['iva']= '10';
 $compra[] = $_POST;
 }
 //Guardamos el contenido
 Compra::setContenidoCompra($compra);
 
 }
 $this->redirect(array('/cabcompra/create'));
 }
 
 public function actionAddProveedor()
 {
 if($_POST['id_proveedor']>0)
 {
 //Guardamos el contenido
 Compra::setProveedor((int)$_POST['id_proveedor']);
 }
 $this->redirect(array('/cabcompra/create'));
 }
 
 public function actionAddPago()
 {
 if(isset($_POST['id_formapago']) && $_POST['id_formapago']>0)
 {
 //Guardamos el contenido
 Compra::setPago((int)$_POST['id_formapago']);
 }
 
 if(isset($_POST['tipo_cheque']) && $_POST['tipo_cheque']>0)
 {
 $registro=new RegistroCheque();
 $registro->attributes=array(
 'tipo_cheque_id_tipo_cheque'=>$_POST['tipo_cheque'],
 'bancos_id_banco'=>$_POST['banco'],
 'nro_cheque'=>$_POST['cheque'],
 'titural_cheque'=>$_POST['titular'],
 'importe_cheque'=>10000,
 'fecha_emision'=>$_POST['fecha_emision'],
 'fecha_cobro'=>$_POST['fecha_cobro'],
 );
 if ($registro->validate()) {
 if(isset($_POST['yt0']))
 unset($_POST['yt0']);
 $cheque[0] = $_POST;
 Compra::setContenidoCheque($cheque);
 }
 else{
 $error='';
 foreach ($registro->getErrors() as $position => $er)
 $error.=$er[0].'<br/>';
 Yii::app()->user->setFlash('danger',$error);
 }
 }
 $this->redirect(array('/cabcompra/create'));
 }
 
 public function actionAddDoc()
 {
 if($_POST['id_doc']>0)
 {
 //Guardamos el contenido
 Compra::setDoc((int)$_POST['id_doc']);
 }
 $this->redirect(array('/cabcompra/create'));
 }
 
 public function actionCreate()
 {
 $this->render('create',array(
 ));
 }
 
 public function actionComplete()
 {
 //Para guardar todo
 if((@$pago = Compra::getPago()) && (@$doc = Compra::getDoc()) && (@$proveedor=Compra::getProveedor()) && (@$productos=Compra::getContenidoCompra()))
 {
 if($doc==1)
 {
 if($_POST['ref'])
 {
 $referencia=$_POST['ref'];
 $fecha_requerida=null;
 }
 else
 {
 Yii::app()->user->setFlash('danger', '<strong>Complete el numero de referencia.</strong>
 <br/>PD: El numero de referencia es el numero de la factura compra.');
 $this->redirect(array('/cabcompra/create'));
 }
 }
 else if($doc==2)
 {
 if($_POST['fecha_requerida']>=date('Y-m-d'))
 {
 $referencia=null;
 $fecha_requerida=$_POST['fecha_requerida'];
 }
 else
 {
 Yii::app()->user->setFlash('danger', '<strong>Complete la fecha requerida.</strong>
 <br/>PD: Debe ser mayor o igual a la fecha actual.');
 $this->redirect(array('/cabcompra/create'));
 }
 }
 
 if($pago==2 && !(@$cheque=Compra::getContenidoCheque()))
 {
 Yii::app()->user->setFlash('danger', '<strong>Complete correctamente los detalles del cheque.</strong>');
 $this->redirect(array('/cabcompra/create'));
 }
 
$CabCompra=new CabCompra();
 $resumen=Compra::getTotal(true);
 $CabCompra->attributes=array(
 'id_proveedor'=>$proveedor,
 'fecha_compra'=>date('Y-m-d'),
 'fecha_registro'=>$fecha_requerida,
 'nro_documento'=>$referencia,
 'user'=>Yii::app()->user->name,
 'id_tipo_pago'=>$pago,
 'id_tipo_documento'=>$doc,
 'obs'=>$_POST['obs'],
 //'sub_total'=>$resumen['subtotal'],
 'igv'=>$resumen['iva'],
 'total'=>$resumen['total'],
 'descuento_total'=>$resumen['dcto']
 );
 if ($CabCompra->validate()) {
 //Guardamos cabecera de compra
 if($CabCompra->save()){
 //Guardamos detalles de compra
 foreach($productos as $position => $product) {
 $position = new DetalleCompra();
 $position->id_compra = $CabCompra->id_compra;
 $position->id_producto = $product['id_producto'];
 $position->cantidad_producto = $product['cantidad'];
 $position->precio_unitario = $product['precio'];
 $position->descuento_producto = $product['dcto'];
 $position->subtotal_iva = $product['iva'];
 $position->subtotal_producto =(($product['precio']-(($product['precio']*$product['dcto'])/100))*$product['cantidad']);
 $position->save();
 }
 $this->borrarTodo();
 Yii::app()->user->setFlash('success', '<strong>Transaccion finalizada correctamente</strong>.');
 $this->redirect(array('/cabcompra/index'));
 }
 }
 else{
 $error='';
 foreach ($CabCompra->getErrors() as $position => $er)
 $error.=$er[0].'<br/>';
 Yii::app()->user->setFlash('danger',$error);
 $this->redirect(array('/cabcompra/create'));
 }
 }
 Yii::app()->user->setFlash('danger', '<strong>Complete correctamente todos los formularios.</strong>.');
 $this->redirect(array('/cabcompra/create'));
 }
 
 public function actionDeleteItem($id)
 {
 $id = (int) $id;
 //Descodificamos el array JSON
 $compra = CJSON::decode(Yii::app()->user->getState('compra'), true);
 //Eliminamos el atributo pasado por parámetro
 unset($compra[$id]);
 //Volvemos a codificar y guardar el contenido
 Yii::app()->user->setState('compra', CJSON::encode($compra));
 $this->redirect(array('/cabcompra/create'));
 }
 
 public function actionDeleteProveedor()
 {
 //Para borrar proveedor
 Compra::setProveedor(null);
 $this->redirect(array('/cabcompra/create'));
 }
 
 public function actionDeleteCheque()
 {
 //Para borrar cheque
 Compra::setContenidoCheque(array());
 $this->redirect(array('/cabcompra/create'));
 }
 
 public function actionDeletePago()
 {
 //Para borrar pago
 Compra::setPago(null);
 $this->redirect(array('/cabcompra/create'));
 }
 
 public function actionDeleteDoc()
 {
 //Para borrar tipo de doc
 Compra::setDoc(null);
 $this->redirect(array('/cabcompra/create'));
 }
 
 public function actionDeleteAll()
 {
 //Para borrar todo
 $this->borrarTodo();
 $this->redirect(array('/cabcompra/create'));
 }
 
 public function lookupdata()
 {
 $this->detallecompra=new DetalleCompra('search');
 $this->detallecompra->unsetAttributes(); // clear any default values
 if(isset($_GET['DetalleCompra']))
 $this->detallecompra->attributes=$_GET['DetalleCompra'];
 }
 
public function actionIndex()
 {
 $this->layout='//layouts/column2';
 $dataProvider=new CActiveDataProvider('CabCompra');
 $this->render('index',array(
 'dataProvider'=>$dataProvider,
 ));
 }
 
public function loadModel($id)
 {
 $model=CabCompra::model()->findByPk((int)$id);
 if($model===null)
 throw new CHttpException(404,'The requested page does not exist.');
 return $model;
 }
 
public function loadModeldetail($id)
 {
 $model=DetalleCompra::model()->findAll('id_compra=:id_compra', array(':id_compra'=>(int)$id));
 if($model===null)
 throw new CHttpException(404,'The requested page does not exist.');
 return $model;
 }
 protected function performAjaxValidation($model)
 {
 if(isset($_POST['ajax']) && $_POST['ajax']==='cabcompra-form')
 {
 echo CActiveForm::validate($model);
 Yii::app()->end();
 }
 if(isset($_POST['ajax']) && $_POST['ajax']==='detcompra-form')
 {
 echo CActiveForm::validate($model);
 Yii::app()->end();
 }
 }
 
}

Ahora las vistas (create.php y_form.php que es la vista que se utiliza para la creación).

Cabe destacar que en las vistas he utilizado JS y Ajax para realizar los cálculos de forma directa, deben de seguir todo muy minuciosamente para entender su funcionamiento, lo único que hice en su momento fue aplicar mis bases de PHP, JS y Ajax en Yii.

create.php (carpeta views y dentro del nombre del controlador y modelo que usen, en mi caso CabCompra)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
$this->breadcrumbs=array(
 'Compra'=>array('index'),
 'Crear',
);
 
$this->menu=array(
 array('label'=>'Administrar Compras','url'=>array('index')),
);
?>
 
<h4>Crear Orden de Compra / Registrar Factura Compra</h4>
 
<?php echo $this->renderPartial('_form', array(
));
?>

_form.php (Carpeta views y dentro del nombre del controlador y modelo que usen, en mi caso CabCompra):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
<?php Yii::app()->bootstrap->registerAssetCss('bootstrap-box.css'); ?>
<div class="row">
<div class="span3">
<?php $products = Compra::getContenidoCompra(); ?>
 <div class="bootstrap-widget">
 <h3>Proveedor</h3>
<div class="form-actions" id="yw3">
 <?php $form=$this->beginWidget('bootstrap.widgets.TbActiveForm',array(
 'id'=>'proveedor-form',
 'action'=>$this->createUrl('/cabcompra/addProveedor'),
 'enableAjaxValidation'=>false,
 'enableClientValidation'=>false,
 'clientOptions'=>array(
 'validateOnSubmit'=>false,
 )
)); ?>
 <?php
 if(@$proveedor = Compra::getProveedor())
 {
 if(@$model = Proveedores::model()->findByPk($proveedor))
 {
 echo "<b>Proveedor:</b> ".$model->nombre_proveedor."<br/>";
 echo CHtml::link('Eliminar', array(
 '/cabcompra/deleteproveedor'));
 }
 }
 else
 {
 echo CHtml::hiddenField('id_proveedor');
 echo "Seleccione Proveedor";
 $this->widget('zii.widgets.jui.CJuiAutoComplete', array(
 'name'=>'nombre_proveedor',
 'sourceUrl'=>$this->createUrl('/Proveedores/ListarProveedores'),
 'options'=>array(
 'minLength'=>'1',
 'showAnim'=>'fold',
 'select' => 'js:function(event, ui)
 { jQuery("#id_proveedor").val(ui.item["id"]); }',
 'search'=> 'js:function(event, ui)
 { jQuery("#id_proveedor").val(0); }'
 ),
 'htmlOptions'=>array(
 'class'=>'span2'
 ),
 ));
 $this->widget('bootstrap.widgets.TbButton', array(
 'type' =>'primary',
 'label'=>'Agregar',
 'buttonType' => 'submit',
 ));
 }
 ?>
 <?php $this->endWidget(); ?>
</div> <br/>
<h3>Forma de Pago</h3>
<div class="form-actions" id="yw3">
<?php if($products) : ?>
<?php $doc = Compra::getDoc() ?>
<?php $form=$this->beginWidget('bootstrap.widgets.TbActiveForm',array(
 'id'=>'pago-form',
 'action'=>$this->createUrl('/cabcompra/addPago'),
 'enableAjaxValidation'=>false,
 'enableClientValidation'=>false,
 'clientOptions'=>array(
 'validateOnSubmit'=>false,
 )
)); ?>
<?php
 if(@$pago = Compra::getPago())
 {
 if(@$model = FormasPago::model()->findByPk($pago))
 {
 echo "<b>Forma de Pago:</b> ".$model->desc_forma."<br/>";
 echo CHtml::link('Eliminar', array('/cabcompra/deletepago'));
 }
 if($pago==2 && $doc==1)
 {
 echo '<h4>Detalles del Cheque</h4>';
 if(@$cheque= Compra::getContenidoCheque())
 {
 echo '<b>Tipo de cheque:</b> '.TipoCheque::getCheque($cheque[0]['tipo_cheque'])."<br />";
 echo '<b>Banco:</b> '.Bancos::getBanco($cheque[0]['banco'])."<br />";
 echo '<b>Número de cheque:</b> '.$cheque[0]['cheque']."<br />";
 echo '<b>Titular: </b>'.$cheque[0]['titular']."<br />";
 echo '<b>Fecha de Emisión:</b> '.$cheque[0]['fecha_emision']."<br />";
 echo '<b>Fecha de Cobro:</b> '.$cheque[0]['fecha_cobro']."<br />";
 echo CHtml::link('Eliminar Detalles', array('/cabcompra/deletecheque'));
 }
 else{
 echo 'Tipo de cheque: <span class="required">*</span>';
 echo CHtml::dropDownList('tipo_cheque','',TipoCheque::getListCheques(),array('empty'=>'Seleccione Tipo','class'=>'span2'));
 
echo '<br />Banco: <span class="required">*</span><br />';
 echo CHtml::dropDownList('banco','',Bancos::getListBancos(),array('empty'=>'Seleccione Banco','class'=>'span2'));
 
echo '<br />Titular: <span class="required">*</span><br />';
 echo CHtml::TextField('titular','',array('class'=>'span2'));
 
echo '<br />Número de Cheque: <span class="required">*</span><br />';
 echo CHtml::TextField('cheque','',array('class'=>'span2'));
 
echo '<br />Fecha de Emision: <span class="required">*</span><br />';
 $this->widget('zii.widgets.jui.CJuiDatePicker',
 array(
 'name'=>'fecha_emision',
 'language' => 'es',
 'htmlOptions' => array('readonly'=>"readonly",'class'=>'span2'),
 'options'=>array(
 'autoSize'=>true,
 'dateFormat'=>'yy-mm-dd',
 'buttonImage'=>Yii::app()->baseUrl.'/images/calendar.png',
 'buttonImageOnly'=>true,
 'buttonText'=>'Fecha',
 'selectOtherMonths'=>true,
 'showAnim'=>'slide',
 'showButtonPanel'=>true,
 'showOn'=>'button',
 'showOtherMonths'=>true,
 'changeMonth' => 'true',
 'changeYear' => 'true',
 ),
 
 )
);
 echo '<br />Fecha de Cobro: <span class="required">*</span>';
 $this->widget('zii.widgets.jui.CJuiDatePicker',
 array(
 'name'=>'fecha_cobro',
 'language' => 'es',
 'htmlOptions' => array('readonly'=>"readonly",'class'=>'span2'),
 'options'=>array(
 'autoSize'=>true,
 'dateFormat'=>'yy-mm-dd',
 'buttonImage'=>Yii::app()->baseUrl.'/images/calendar.png',
 'buttonImageOnly'=>true,
 'buttonText'=>'Fecha',
 'selectOtherMonths'=>true,
 'showAnim'=>'slide',
 'showButtonPanel'=>true,
 'showOn'=>'button',
 'showOtherMonths'=>true,
 'changeMonth' => 'true',
 'changeYear' => 'true',
 ),
 
 )
);
 $this->widget('bootstrap.widgets.TbButton', array(
 'type' =>'primary',
 'label'=>'Agregar detalles',
 'buttonType' => 'submit',
 ));
 }
}
 }
 else
 {
 echo CHtml::dropDownList('id_formapago','',FormasPago::getListFormasPagos(),array('empty'=>'Seleccione forma de pago','class'=>'span2'));
 $this->widget('bootstrap.widgets.TbButton', array(
 'type' =>'primary',
 'label'=>'Agregar',
 'buttonType' => 'submit',
 ));
 }
?>
<?php $this->endWidget(); ?>
<?php endif ?>
</div><br/>
 
<?php if($products) : ?>
<h3>Tipo de Documento</h3>
<div class="form-actions" id="yw3">
<?php $form=$this->beginWidget('bootstrap.widgets.TbActiveForm',array(
 'id'=>'doc-form',
 'action'=>$this->createUrl('/cabcompra/addDoc'),
 'enableAjaxValidation'=>false,
 'enableClientValidation'=>false,
 'clientOptions'=>array(
 'validateOnSubmit'=>false,
 )
)); ?>
<?php
 if($doc)
 {
 if(@$documento = TiposDocumentos::model()->findByPk($doc))
 {
 echo "<b>Tipo de Documento:</b> ".$documento->desc."<br/>";
 echo CHtml::link('Eliminar', array(
 '/cabcompra/deletedoc'));
 }
 }
 else
 {
 echo CHtml::dropDownList('id_doc','',TiposDocumentos::getListDocumentos(),array('empty'=>'Seleccione documento','class'=>'span2'));
 $this->widget('bootstrap.widgets.TbButton', array(
 'type' =>'primary',
 'label'=>'Agregar',
 'buttonType' => 'submit',
 ));
 }
?>
<?php $this->endWidget(); ?>
</div><br/>
<h3>Transacción</h3>
<div class="form-actions" id="yw3">
<?php if($pago && $doc) { ?>
<?php $form=$this->beginWidget('bootstrap.widgets.TbActiveForm',array(
 'id'=>'final-form',
 'action'=>$this->createUrl('/cabcompra/complete'),
 'enableAjaxValidation'=>false,
 'enableClientValidation'=>false,
 'clientOptions'=>array(
 'validateOnSubmit'=>false,
 )
)); ?>
<?php
if($doc==1)
{
echo 'Número de referencia: <span class="required">*</span>';
echo CHtml::TextField('ref','',array('class'=>'span2'));
}
 
else if($doc==2)
{
echo 'Fecha requerida: <span class="required">*</span>';
$this->widget('zii.widgets.jui.CJuiDatePicker',
 array(
 'name'=>'fecha_requerida',
 'language' => 'es',
 'htmlOptions' => array('readonly'=>"readonly",'class'=>'span2'),
 'options'=>array(
 'autoSize'=>true,
 'dateFormat'=>'yy-mm-dd',
 'buttonImage'=>Yii::app()->baseUrl.'/images/calendar.png',
 'buttonImageOnly'=>true,
 'buttonText'=>'Fecha',
 'selectOtherMonths'=>true,
 'showAnim'=>'slide',
 'showButtonPanel'=>true,
 'showOn'=>'button',
 'showOtherMonths'=>true,
 'changeMonth' => 'true',
 'changeYear' => 'true',
 ),
 )
);
}
echo "Observación:";
echo CHtml::textArea('obs','',array('class'=>'span2'));
?>
<div class="form-actions">
<?php $this->widget('bootstrap.widgets.TbButton', array(
 'label'=>'Completar',
 'type'=>'success',
 'buttonType'=>'submit',
 ));
?>
</div>
<?php $this->endWidget(); } ?>
<div class="well">
<h4>¿Desea cancelar todas las transacciones?</h4>
<?php $this->widget('bootstrap.widgets.TbButton', array(
 'label'=>'Si',
 'type'=>'danger',
 'url'=>$this->createUrl('/cabcompra/deleteall'),
 ));
?>
</div>
</div>
<?php endif ?>
 
</div>
</div>
<div class="span9">
 <?php $this->widget('bootstrap.widgets.TbAlert', array(
 'alerts'=>array(
 'success'=>array('block'=>true, 'fade'=>true),
 'danger'=>array('block'=>true, 'fade'=>true),
 ),
 ));?>
 
<?php $form=$this->beginWidget('bootstrap.widgets.TbActiveForm',array(
 'id'=>'productos-form',
 'action'=>$this->createUrl('/cabcompra/addItem'),
 'enableAjaxValidation'=>false,
 'enableClientValidation'=>false,
 'clientOptions'=>array(
 'validateOnSubmit'=>false,
 )
)); ?>
<h4>Buscar Producto</h4>
<div class="">
<?php
 echo CHtml::hiddenField('id_producto',0);
 echo CHtml::hiddenField('cantidad',1);
 $this->widget('zii.widgets.jui.CJuiAutoComplete', array(
 'name'=>'nombre_producto',
 'sourceUrl'=>$this->createUrl('/Productos/ListarProductos'),
 'options'=>array(
 'minLength'=>'1',
 'showAnim'=>'fold',
 'select' => 'js:function(event, ui)
 { jQuery("#id_producto").val(ui.item["id"]); }',
 'search'=> 'js:function(event, ui)
 { jQuery("#id_producto").val(0); }'
 ),
 'htmlOptions'=>array(
 'class'=>'span2'
 ),
 ));
?>
<?php $this->widget('bootstrap.widgets.TbButton', array(
 'icon' => 'icon-plus',
 'label'=>'Agregar Producto',
 'type' => 'secundary',
 'buttonType' => 'submit',
 ));
?>
</div>
<?php
 echo '<div class="grid-view">';
 echo '<table class="items table table-striped">';
 echo '<thead>';
 printf('<tr><th>%s</th><th>%s</th><th>%s</th><th>%s</th><th>%s</th><th>%s</th><th class="actions button-column">&nbsp;</th></tr>',
 'CANTIDAD',
 'DESCRIPCION',
 'PRECIO UNITARIO',
 'DESC %',
 'IVA %',
 'TOTAL'
 );
 echo '</thead>';
if($products) {
 
?>
<?php
 echo '<tbody>';
 foreach($products as $position => $product) {
 printf('<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td class="textright total_'.$position.'">%s</td><td class="actions button-column">%s</td></tr>',
 CHtml::textField('cantidad_'.$position,
 $product['cantidad'], array(
 'class' => 'span1 cantidad_'.$position,
 )
 ),
 $product['desc'],
 CHtml::textField('precio_'.$position,
 $product['precio'], array(
 'class' => 'span2 precio_'.$position,
 )
 ),
 $product['dcto'],
 $product['iva'],
 (($product['precio']-(($product['precio']*$product['dcto'])/100))*$product['cantidad']),
 $this->widget('bootstrap.widgets.TbButton', array(
 'icon'=>'icon-trash',
 'type'=>'link',
 'url'=>$this->createUrl('/cabcompra/deleteitem',array('id' => $position)))
 ,true)
 );
 
 Yii::app()->clientScript->registerScript('cantidad_'.$position,"
 $('.cantidad_".$position."').keyup(function() {
 $.ajax({
 url:'".$this->createUrl('/cabcompra/updateCantidad')."',
 data: $('#cantidad_".$position."'),
 success: function(result) {
 $('.total_".$position."').html(result);
 $('.resumen').load('".$this->createUrl(
 '/cabcompra/getPrecioTotal')."');
 },
 error: function() {
 },
 
});
 });
 ");
 
Yii::app()->clientScript->registerScript('precio_'.$position,"
 $('.precio_".$position."').keyup(function() {
 $.ajax({
 url:'".$this->createUrl('/cabcompra/updatePrecio')."',
 data: $('#precio_".$position."'),
 success: function(result) {
 $('.total_".$position."').html(result);
 $('.resumen').load('".$this->createUrl(
 '/cabcompra/getPrecioTotal')."');
 },
 error: function() {
 },
 
});
 });
 ");
 
}
 
echo '</tbody>';
 
?>
 
&nbsp;
 
<?php
}
echo '</table><div class="well pull-right extended-summary resumen">';
echo Compra::getTotal();
echo '</div></div>';
?>
<br/><br/><br/><br/><br/><br/>
<br/><br/><br/><br/><br/><br/>
</div>
</div>
<?php $this->endWidget(); ?>

Reconozco que todo esto es bastante complejo y que les va a llevar tiempo para descifrar mis códigos ya que cuando los hice no comenté todas las partes por el apuro que tenía para entregar mi proyecto en la facultad. Cuando tenga más tiempo volveré a reeditar todo esto y a dar más detalles de todo lo que hice.

Les dejo el source code completo del proyecto Yii con la base de datos (Hacer clic en la imagen para ingresar y descargar el proyecto del repositorio):

github-logo

Acerca del autor: Rodrigo Paszniuk

Ingeniero Informático, amante de la tecnología, la música, el ciclismo y aprender cosas nuevas.

Posts Relacionados

  • Phalcon – Framework PHP – Extensión de C
  • Reportes gráficos en Yii
  • Backup en Yii
  • Manual intermedio de Yii framework (PHP)



SEGUÍNOS EN FACEBOOK


GITHUB