<commit_before><?php
/**
 * Este archivo contiene toda la logica de acceso a datos asociada a las facturas.
 *
 * PHP versions 5
 *
 * @filesource
 * @copyright       Copyright 2007-2009, Pragmatia
 * @link            http://www.pragmatia.com
 * @package         pragtico
 * @subpackage      app.models
 * @since           Pragtico v 1.0.0
 * @version         $Revision$
 * @modifiedby      $LastChangedBy$
 * @lastmodified    $Date$
 * @author          <NAME> <<EMAIL>>
 */
/**
 * La clase encapsula la logica de acceso a datos asociada a las facturas.
 *
 * @package     pragtico
 * @subpackage  app.models
 */
class Factura extends AppModel {


	var $hasMany = array(	'Liquidacion',
							'FacturasDetalle' =>
                        array('dependent'   => true));

	var $belongsTo = array('Empleador', 'Area');



	function __preSave($employerId, $receiptIds, $areaId, $saveDatailsTmp, $conditions) {
		$total = 0;
		foreach ($saveDatailsTmp as $tmp) {
			$saveDatails[] = $tmp;
			$total += $tmp['total'];
		}
		
		$saveMaster['empleador_id'] = $employerId;
		$saveMaster['area_id'] = $areaId;
		$saveMaster['fecha'] = date('d/m/Y');
		$saveMaster['estado'] = 'Sin Confirmar';
		$saveMaster['total'] = $total;
		$saveMaster['confirmable'] = 'No';
		if ($conditions['Liquidacion.estado'] === 'Confirmada') {
			$saveMaster['confirmable'] = 'Si';
		}
		$saveMaster['ano'] = $conditions['Liquidacion.ano'];
		$saveMaster['mes'] = $conditions['Liquidacion.mes'];
		$saveMaster['periodo'] = 'M';
		if (!empty($conditions['Liquidacion.periodo like'])) {
			$saveMaster['periodo'] = str_replace('%', '', $conditions['Liquidacion.periodo like']);
		}
		$saveMaster['tipo'] = Inflector::humanize($conditions['Liquidacion.tipo']);

		$save = array_merge(array('Factura' => $saveMaster), array('FacturasDetalle' => $saveDatails));
		$this->create($save);
		if ($this->saveAll($save)) {
			return $this->Liquidacion->updateAll(array('Liquidacion.factura_id' => $this->id), array('Liquidacion.id' => $receiptIds));
		} else {
			return false;
		}
	}

    /** Must update receipts */
	function beforeDelete($casacade = true) {
        $this->recursive = -1;
        $invoice = $this->findById($this->id);
        if ($invoice['Factura']['estado'] === 'Sin Confirmar') {
            return $this->Liquidacion->updateAll(array('Liquidacion.factura_id' => null), array('Liquidacion.factura_id' => $this->id));
        }
        return false;
    }
    
	function getInvoice($conditions = null) {

		if (empty($conditions)) {
			return false;
		}

        /*
		$conditions = array_merge($conditions,
			array(	'OR' => array(
				'Liquidacion.factura_id' 	=> null,
					array(	'Factura.estado' 				=> 'Sin Confirmar',
							'Liquidacion.factura_id !=' 	=> null))));
		*/
        $conditions = array_merge($conditions, array('Liquidacion.factura_id' => null));
        $data = $this->Liquidacion->find('all',
			array(	'conditions' 	=> $conditions,
					'order' 		=> array('Liquidacion.empleador_id', 'Liquidacion.relacion_area_id'),
				 	'contain'		=> array('Empleador', 'LiquidacionesDetalle', 'Factura')));

		if (!empty($data)) {
			
			$saveMaster = $saveDatails = null;
			$employerId = null;
			$areaId = null;
			$receiptIds = null;
            $count = count($data) - 1;
			foreach ($data as $k => $receipt) {

				foreach ($receipt['LiquidacionesDetalle'] as $detail) {
					if ($detail['coeficiente_tipo'] !== 'No Facturable' && ($detail['concepto_imprimir'] === 'Si' || ($detail['concepto_imprimir'] === 'Solo con valor') && abs($detail['valor']) > 0)) {
						if (!isset($saveDatails[$detail['coeficiente_nombre']])) {
							$saveDatails[$detail['coeficiente_nombre']]['coeficiente_id'] = $detail['coeficiente_id'];
							$saveDatails[$detail['coeficiente_nombre']]['coeficiente_nombre'] = $detail['coeficiente_nombre'];
							$saveDatails[$detail['coeficiente_nombre']]['coeficiente_tipo'] = $detail['coeficiente_tipo'];
							$saveDatails[$detail['coeficiente_nombre']]['coeficiente_valor'] = $detail['coeficiente_valor'];
							$saveDatails[$detail['coeficiente_nombre']]['subtotal'] = $detail['valor'];
							$saveDatails[$detail['coeficiente_nombre']]['total'] = $detail['valor'] * $detail['coeficiente_valor'];
						} else {
							$saveDatails[$detail['coeficiente_nombre']]['subtotal'] += $detail['valor'];
							$saveDatails[$detail['coeficiente_nombre']]['total'] += $detail['valor'] * $detail['coeficiente_valor'];
						}
					}
				}
				
                if ($receipt['Empleador']['facturar_por_area'] === 'No'
                    && $employerId !== $receipt['Liquidacion']['empleador_id']) {
					$employerId = $receipt['Liquidacion']['empleador_id'];
					$areaId = null;
                    if ($k > 0) {
						$this->__preSave($employerId, $receiptIds, $areaId, $saveDatails, $conditions);
						$saveMaster = $saveDatails = $receiptIds = null;;
					}
				} else if ($receipt['Empleador']['facturar_por_area'] === 'Si'
                    && $areaId !== $receipt['Liquidacion']['relacion_area_id']) {
                    if ($areaId !== null && !empty($saveDatails)) {
                        $this->__preSave($employerId, $receiptIds, $areaId, $saveDatails, $conditions);
                        $saveMaster = $saveDatails = $receiptIds = null;;
                    }
                    $employerId = $receipt['Liquidacion']['empleador_id'];
                    $areaId = $receipt['Liquidacion']['relacion_area_id'];
                } elseif ($count === $k) {
                    $receiptIds[] = $receipt['Liquidacion']['id'];
                    $this->__preSave($employerId, $receiptIds, $areaId, $saveDatails, $conditions);
                }
                $receiptIds[] = $receipt['Liquidacion']['id'];
            }
			return true;
		} else {
			return false;
		}
	}
	
	<commit_msg>Minor bugfix updating receipt when just one record<commit_after><?php
/**
 * Este archivo contiene toda la logica de acceso a datos asociada a las facturas.
 *
 * PHP versions 5
 *
 * @filesource
 * @copyright       Copyright 2007-2009, Pragmatia
 * @link            http://www.pragmatia.com
 * @package         pragtico
 * @subpackage      app.models
 * @since           Pragtico v 1.0.0
 * @version         $Revision$
 * @modifiedby      $LastChangedBy$
 * @lastmodified    $Date$
 * @author          <NAME> <<EMAIL>>
 */
/**
 * La clase encapsula la logica de acceso a datos asociada a las facturas.
 *
 * @package     pragtico
 * @subpackage  app.models
 */
class Factura extends AppModel {


	var $hasMany = array(	'Liquidacion',
							'FacturasDetalle' =>
                        array('dependent'   => true));

	var $belongsTo = array('Empleador', 'Area');



	function __preSave($employerId, $receiptIds, $areaId, $saveDatailsTmp, $conditions) {
		$total = 0;
		foreach ($saveDatailsTmp as $tmp) {
			$saveDatails[] = $tmp;
			$total += $tmp['total'];
		}
		
		$saveMaster['empleador_id'] = $employerId;
		$saveMaster['area_id'] = $areaId;
		$saveMaster['fecha'] = date('d/m/Y');
		$saveMaster['estado'] = 'Sin Confirmar';
		$saveMaster['total'] = $total;
		$saveMaster['confirmable'] = 'No';
		if ($conditions['Liquidacion.estado'] === 'Confirmada') {
			$saveMaster['confirmable'] = 'Si';
		}
		$saveMaster['ano'] = $conditions['Liquidacion.ano'];
		$saveMaster['mes'] = $conditions['Liquidacion.mes'];
		$saveMaster['periodo'] = 'M';
		if (!empty($conditions['Liquidacion.periodo like'])) {
			$saveMaster['periodo'] = str_replace('%', '', $conditions['Liquidacion.periodo like']);
		}
		$saveMaster['tipo'] = Inflector::humanize($conditions['Liquidacion.tipo']);

		$save = array_merge(array('Factura' => $saveMaster), array('FacturasDetalle' => $saveDatails));
		$this->create($save);
		if ($this->saveAll($save)) {
			return $this->Liquidacion->updateAll(array('Liquidacion.factura_id' => $this->id), array('Liquidacion.id' => $receiptIds));
		} else {
			return false;
		}
	}

    /** Must update receipts */
	function beforeDelete($casacade = true) {
        $this->recursive = -1;
        $invoice = $this->findById($this->id);
        if ($invoice['Factura']['estado'] === 'Sin Confirmar') {
            return $this->Liquidacion->updateAll(array('Liquidacion.factura_id' => null), array('Liquidacion.factura_id' => $this->id));
        }
        return false;
    }
    
	function getInvoice($conditions = null) {

		if (empty($conditions)) {
			return false;
		}

        /*
		$conditions = array_merge($conditions,
			array(	'OR' => array(
				'Liquidacion.factura_id' 	=> null,
					array(	'Factura.estado' 				=> 'Sin Confirmar',
							'Liquidacion.factura_id !=' 	=> null))));
		*/
        $conditions = array_merge($conditions, array('Liquidacion.factura_id' => null));
        $data = $this->Liquidacion->find('all',
			array(	'conditions' 	=> $conditions,
					'order' 		=> array('Liquidacion.empleador_id', 'Liquidacion.relacion_area_id'),
				 	'contain'		=> array('Empleador', 'LiquidacionesDetalle', 'Factura')));

		if (!empty($data)) {
			
			$saveMaster = $saveDatails = null;
			$employerId = null;
			$areaId = null;
			$receiptIds = null;
            $count = count($data) - 1;
			foreach ($data as $k => $receipt) {

				foreach ($receipt['LiquidacionesDetalle'] as $detail) {
					if ($detail['coeficiente_tipo'] !== 'No Facturable' && ($detail['concepto_imprimir'] === 'Si' || ($detail['concepto_imprimir'] === 'Solo con valor') && abs($detail['valor']) > 0)) {
						if (!isset($saveDatails[$detail['coeficiente_nombre']])) {
							$saveDatails[$detail['coeficiente_nombre']]['coeficiente_id'] = $detail['coeficiente_id'];
							$saveDatails[$detail['coeficiente_nombre']]['coeficiente_nombre'] = $detail['coeficiente_nombre'];
							$saveDatails[$detail['coeficiente_nombre']]['coeficiente_tipo'] = $detail['coeficiente_tipo'];
							$saveDatails[$detail['coeficiente_nombre']]['coeficiente_valor'] = $detail['coeficiente_valor'];
							$saveDatails[$detail['coeficiente_nombre']]['subtotal'] = $detail['valor'];
							$saveDatails[$detail['coeficiente_nombre']]['total'] = $detail['valor'] * $detail['coeficiente_valor'];
						} else {
							$saveDatails[$detail['coeficiente_nombre']]['subtotal'] += $detail['valor'];
							$saveDatails[$detail['coeficiente_nombre']]['total'] += $detail['valor'] * $detail['coeficiente_valor'];
						}
					}
				}
				
                $receiptIds[] = $receipt['Liquidacion']['id'];
                if ($receipt['Empleador']['facturar_por_area'] === 'No'
                    && $employerId !== $receipt['Liquidacion']['empleador_id']) {
					$employerId = $receipt['Liquidacion']['empleador_id'];
					$areaId = null;
                    if ($k > 0) {
						$this->__preSave($employerId, $receiptIds, $areaId, $saveDatails, $conditions);
						$saveMaster = $saveDatails = $receiptIds = null;;
					}
				} else if ($receipt['Empleador']['facturar_por_area'] === 'Si'
                    && $areaId !== $receipt['Liquidacion']['relacion_area_id']) {
                    if ($areaId !== null && !empty($saveDatails)) {
                        $this->__preSave($employerId, $receiptIds, $areaId, $saveDatails, $conditions);
                        $saveMaster = $saveDatails = $receiptIds = null;;
                    }
                    $employerId = $receipt['Liquidacion']['empleador_id'];
                    $areaId = $receipt['Liquidacion']['relacion_area_id'];
                } elseif ($count === $k) {
                    $receiptIds[] = $receipt['Liquidacion']['id'];
                    $this->__preSave($employerId, $receiptIds, $areaId, $saveDatails, $conditions);
                }
            }
			return true;
		} else {
			return false;
		}
	}
	
	
{'fraction_non_alphanumeric': 0.1835318310341873, 'fraction_numerical': 0.002913203667209322, 'mean_word_length': 3.2817314746881876, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 79, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1741023', 'n_tokens_mistral': 4507, 'n_tokens_neox': 3937, 'n_words': 633}