0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) {
$i--; $j--;
}
if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) {
$res = @include substr($tmp, 0, ($i + 1))."/main.inc.php";
}
if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) {
$res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php";
}
// Try main.inc.php using relative path
if (!$res && file_exists("../main.inc.php")) {
$res = @include "../main.inc.php";
}
if (!$res && file_exists("../../main.inc.php")) {
$res = @include "../../main.inc.php";
}
if (!$res && file_exists("../../../main.inc.php")) {
$res = @include "../../../main.inc.php";
}
if (!$res) {
die("Include of main fails");
}
global $user, $db, $conf;
error_reporting(0);
$zona_horaria = $conf->global->CFDIMX_HUSO_HORARIO;
date_default_timezone_set($zona_horaria);
dol_include_once('/cfdimx/lib/nusoap/lib/nusoap.php');
dol_include_once("/cfdimx/lib/phpqrcode/qrlib.php");
dol_include_once('/cfdimx/lib/numero_a_letra.php');
dol_include_once('/cfdimx/class/timbrado.class.php');
dol_include_once('/cfdimx/class/facturacfdimx.class.php');
dol_include_once('/cfdimx/class/complementos.class.php');
dol_include_once('/cfdimx/class/pagos.class.php');
dol_include_once('/cfdimx/class/cce.class.php');
require_once(DOL_DOCUMENT_ROOT . "/core/lib/company.lib.php");
require_once(DOL_DOCUMENT_ROOT . "/core/class/html.formfile.class.php");
require_once(DOL_DOCUMENT_ROOT . "/core/class/html.formother.class.php");
require_once(DOL_DOCUMENT_ROOT . '/core/class/html.formcompany.class.php');
require_once(DOL_DOCUMENT_ROOT . '/core/modules/facture/modules_facture.php');
require_once(DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php');
require_once(DOL_DOCUMENT_ROOT . '/core/class/discount.class.php');
require_once(DOL_DOCUMENT_ROOT . '/compta/paiement/class/paiement.class.php');
require_once(DOL_DOCUMENT_ROOT . "/core/lib/functions2.lib.php");
require_once(DOL_DOCUMENT_ROOT . '/core/lib/invoice.lib.php');
require_once(DOL_DOCUMENT_ROOT . "/core/lib/date.lib.php");
session_start();
if (@$conf->commande->enabled){
require_once(DOL_DOCUMENT_ROOT . '/commande/class/commande.class.php');
}
if (@$conf->projet->enabled) {
require_once(DOL_DOCUMENT_ROOT . '/projet/class/project.class.php');
require_once(DOL_DOCUMENT_ROOT . '/core/lib/project.lib.php');
}
$wscfdi = $conf->global->MAIN_MODULE_CFDIMX_WS;
$client = new nusoap_client($wscfdi, 'wsdl');
$result = $client->call('validaCliente', array("rfc" => $conf->global->MAIN_INFO_SIREN));
$status_clt = $result["return"]["status_cliente_id"];
$status_clt_desc = $result["return"]["status_cliente_desc"];
$folios_timbrados = $result["return"]["folios_timbrados"];
$folios_adquiridos = $result["return"]["folios_adquiridos"];
$folios_disponibles = $result["return"]["folios_disponibles"];
$ban_timbrado = 0;
if (@$_REQUEST["cfdi_commit"] == 1) {
$msg_cfdi_final = "El comprobante se ha generado de manera exitosa.";
$ban_timbrado = 1;
}else {
if (@$_REQUEST["cfdi_commit"] == 307) {
$msg_cfdi_final = "El comprobante se ha recuperado de manera exitosa.";
$ban_timbrado = 1;
}
}
$langs->load('bills');
$langs->load('companies');
$langs->load('products');
$langs->load('main');
if (GETPOST('mesg', 'int', 1) && isset($_SESSION['message']))
$mesg = $_SESSION['message'];
$sall = trim(GETPOST('sall'));
$projectid = (GETPOST('projectid') ? GETPOST('projectid', 'int') : 0);
$id = (GETPOST('id', 'int') ? GETPOST('id', 'int') : GETPOST('facid', 'int')); // For backward compatibility
$ref = GETPOST('ref', 'alpha');
$factemp = new Facture($db);
$factemp->fetch($id, $ref);
$id = $factemp->id;
@$_REQUEST["facid"] = $id;
$socid = GETPOST('socid', 'int');
$action = GETPOST('action', 'alpha');
$confirm = GETPOST('confirm', 'alpha');
$lineid = GETPOST('lineid', 'int');
$userid = GETPOST('userid', 'int');
$search_ref = GETPOST('sf_ref') ? GETPOST('sf_ref', 'alpha') : GETPOST('search_ref', 'alpha');
$search_societe = GETPOST('search_societe', 'alpha');
$search_montant_ht = GETPOST('search_montant_ht', 'alpha');
$search_montant_ttc = GETPOST('search_montant_ttc', 'alpha');
$dol_version = (int)DOL_VERSION;
$object = new Facture($db);
// Actions to send emails
if (empty($id)) $id=$facid;
$trigger_name='BILL_SENTBYMAIL';
$paramname='id';
$autocopy='MAIN_MAIL_AUTOCOPY_INVOICE_TO';
$trackid='inv'.$factemp->id;
include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php';
// Security check
$fieldid = (!empty($ref) ? 'ref' : 'rowid');
if($dol_version >= 14){
if ($user->socid)
$socid = $user->socid;
}else{
if ($user->societe_id)
$socid = $user->societe_id;
}
// Cargar object
if ($id > 0 || !empty($ref)) {
$ret = $object->fetch($id, $ref);
}
// $object->fetchObjectLinked();
// foreach ($object->linkedObjects as $objecttype => $objects) {
// $tplpath = $element = $subelement = $objecttype;
// print '
';
// print_r($objecttype);
// print ' ';
// print 'element: ' . $element.' ';
// }
#Datos del receptor
$sql = "SELECT * FROM " . MAIN_DB_PREFIX . "facture f, " . MAIN_DB_PREFIX . "societe s WHERE f.rowid = '" . $_REQUEST["facid"] . "' AND f.fk_soc = s.rowid";
$resql = $db->query($sql);
$tipo_domicilio = 0;
if ($resql) {
$soc_num = $db->num_rows($resql);
$i = 0;
if ($soc_num) {
while ($i < $soc_num) {
$obj = $db->fetch_object($resql);
if ($obj) {
$soc_rfc = $obj->siren;
$soc_id = $obj->rowid;
$soc_email = $obj->email;
$status = $obj->fk_statut;
$tipo_domicilio = 0;
}
$i++;
}
}
}
$objCCE = new CCE($db);
$object_complementos = new ComplementosCFDIMX($db, $id);
$objFacturaCFDI = new FacturaCFDI($db);
$objFacturaCFDI->entidad = $conf->entity;
$num_domicilio_fiscal = $objFacturaCFDI->getDomiciliosFiscalesCliente($object->socid);
$msj_error_domicilio_fiscal_40 = "";
$num_validaciones_cfdi_40 = 0;
if($num_domicilio_fiscal > 0 && strcmp($conf->global->CFDIMX_VERSION_SAT, "4.0") == 0){
$tipo_domicilio = 1;
for ($i=0; $i < count($objFacturaCFDI->lista_domicilios); $i++) {
$soc_rfc = $objFacturaCFDI->lista_domicilios[$i]->rfc;
break;
}
}else{
$tipo_domicilio = 1;
if($num_domicilio_fiscal < 1){
$msj_error_domicilio_fiscal_40 = "Error: Para el Timbrado de CFDI 4.0 se requiere llenar el apartado de Domicilio Fiscal en la Ficha del Cliente.";
}
}
#Datos de configuración del módulo
$sql = "SELECT * FROM " . MAIN_DB_PREFIX . "cfdimx_config WHERE emisor_rfc = '" . $conf->global->MAIN_INFO_SIREN . "' AND entity_id = " . $conf->entity;
$resql = $db->query($sql);
if ($resql) {
$conf_num = $db->num_rows($resql);
$i = 0;
if ($conf_num) {
while ($i < $conf_num) {
$obj = $db->fetch_object($resql);
if ($obj) {
$status_conf = $obj->status_conf;
$modo_timbrado = $obj->modo_timbrado;
$passwd_timbrado = $obj->password_timbrado_txt;
}
$i++;
}
}
}
#Datos de la factura cfdimx
$uuid = "";
$cfdi_cancela = "";
$totalpaye = "";
$sql = "SELECT * FROM " . MAIN_DB_PREFIX . "cfdimx WHERE fk_facture = " . $_REQUEST["facid"];
$resql = $db->query($sql);
if ($resql) {
$i = 0;
$cfdi_tot = $db->num_rows($resql);
if ($conf_num) {
while ($i < $conf_num) {
$obj = $db->fetch_object($resql);
if ($obj) {
$cfdi_cancela = $obj->cancelado;
$uuid = $obj->uuid;
$selloSAT = $obj->selloSAT;
$selloCFD = $obj->selloCFD;
$fechaTimbrado = $obj->fechaTimbrado;
$factura_id = $obj->factura_id;
$divisa = $obj->divisa;
}
$i++;
}
}
}
if (isset($conf->global->MAIN_MODULE_MULTICURRENCY)) {
$object->total_ht = $object->multicurrency_total_ht;
$object->total_tva = $object->multicurrency_total_tva;
$object->total_ttc = $object->multicurrency_total_ttc;
}
#Status del comprobante
if($uuid != ""){
$sql_verificar_estatus = "";
$sql_verificar_estatus = "SELECT * FROM ".MAIN_DB_PREFIX."cfdimx_estatus";
$sql_verificar_estatus .= " WHERE uuid = '".$uuid."'";
$sql_verificar_estatus .= " AND facid = ".$_REQUEST["facid"];
$sql_verificar_estatus .= " AND entity = ".$conf->entity;
$res_verificar_estatus = $db->query($sql_verificar_estatus);
$num_verificar_estatus = $db->num_rows($res_verificar_estatus);
if($num_verificar_estatus > 0){
$obj_verificar_estatus = $db->fetch_object($res_verificar_estatus);
$estado_cfdi = $obj_verificar_estatus->estado;
$estatus_cancelacion = $obj_verificar_estatus->escancelable;
$fecha_consulta_estatus = $obj_verificar_estatus->fecha." ".$obj_verificar_estatus->hora;
}
}else{
$estado_cfdi = "Sin timbrar";
$estatus_cancelacion = "";
$fecha_consulta_estatus = "";
}
/********************************************************************
* *
* Actions *
* *
*********************************************************************/
if ($action == 'guarda_tercero') {
$cambia_tercero = "UPDATE " . MAIN_DB_PREFIX . "facture SET fk_soc = ".$_REQUEST["socid"]." WHERE rowid = " . $_REQUEST["facid"];
$res_cambia_tercero = $db->query($cambia_tercero);
}
$form = new Form($db);
$htmlother = new FormOther($db);
$formfile = new FormFile($db);
// generaCFDI
if (isset($_REQUEST["action"]) && $_REQUEST["action"] == "generaCFDI") {
// if ($action == "confirm_generacfdi") {
foreach ($_REQUEST as $key => $value) {
//echo $key .'=>'. $value.' ';
$$key = $value;
}
include("cfdi.php");
}
if ($action == 'confirm_del_reten_man') {
$delete = "DELETE FROM " . MAIN_DB_PREFIX . "cfdimx_retenciones WHERE retenciones_id = " . $_REQUEST["del_retencion"];
$db->query($delete);
$rescomm = $db->commit();
if ($_REQUEST["tptre"] == "IVA") {
$delete = "DELETE FROM " . MAIN_DB_PREFIX . "cfdimx_retencionesdet WHERE impuesto='002' AND factura_id = " . $_REQUEST["facid"];
$db->query($delete);
}
if ($_REQUEST["tptre"] == "ISR") {
$delete = "DELETE FROM " . MAIN_DB_PREFIX . "cfdimx_retencionesdet WHERE impuesto='001' AND factura_id = " . $_REQUEST["facid"];
$db->query($delete);
}
print '';
}
if (isset($_REQUEST["del_retencion_local"]) && $_REQUEST["del_retencion_local"] != "") {
$delete = "DELETE FROM " . MAIN_DB_PREFIX . "cfdimx_retenciones_locales WHERE rowid = " . $_REQUEST["del_retencion_local"];
//print $delete;
$rescomm = $db->query($delete);
if ($rescomm) {
print '';
}
}
if ($action == 'add_reten_man') {
if ($_REQUEST["impuesto"] != "" && $_REQUEST["importe"] != "") {
$aplicar_ret_ind = $conf->global->CFDIMX_RET_INDIVIDUALES;
//Se obtiene el valor para determinar si las retenciones se hacen por concepto
//0 -> Se aplican retenciones a todos los conceptos
//1 -> Se aplican retenciones solo a los conceptos seleccionados
// print ''; print_r($object->lines); print ' ';
$importe_retencion = 0;
function truncateFloat($number, $digitos)
{
$raiz = 10;
$multiplicador = pow($raiz, $digitos);
$resultado = ((int) ($number * $multiplicador)) / $multiplicador;
return number_format($resultado, $digitos);
}
for($i=0; $i < sizeof($object->lines);$i++) {
// print ''; print_r($object->lines[$i]); print ' ';
$aplicar_retencion = ($object->lines[$i]->array_options["options_aplicar_ret_individual"] != "" ? $object->lines[$i]->array_options["options_aplicar_ret_individual"] : 0);
$total_ht_det = 0;
if ($conf->global->MAIN_MODULE_MULTICURRENCY) {
$total_ht_det = $object->lines[$i]->multicurrency_total_ht;
}else{
$total_ht_det = $object->lines[$i]->total_ht;
}
$importe_calculado = $total_ht_det * $_REQUEST["importe"];
$sql_retencion = "INSERT INTO " . MAIN_DB_PREFIX . "cfdimx_retencionesdet";
$sql_retencion .= " (factura_id, fk_facturedet, base, impuesto, tipo_factor, tasa, importe)";
$sql_retencion .= " VALUES";
$sql_retencion .= " (";
$sql_retencion .= $_REQUEST["facid"].",";
$sql_retencion .= $object->lines[$i]->id.",";
$sql_retencion .= "'".round($total_ht_det, 2)."',";
$sql_retencion .= "'".$_REQUEST["impuesto"]. "',";
$sql_retencion .= "'Tasa',";
$sql_retencion .= "'".$_REQUEST["importe"]."',";
$sql_retencion .= "'".str_replace(",", "", truncateFloat($importe_calculado, 2)) . "'";
$sql_retencion .= " )";
// print $sql_retencion;
if($aplicar_ret_ind == 1){
if($aplicar_retencion == 1){
$res_retencion_individual = $db->query($sql_retencion);
$importe_retencion += str_replace(",", "", truncateFloat($importe_calculado, 2));
}
}else{
$res_retencion_individual = $db->query($sql_retencion);
$importe_retencion += str_replace(",", "", truncateFloat($importe_calculado, 2));
}
}
$impuest_head_retencion = ($_REQUEST["impuesto"] == "002" ? "IVA" : "ISR");
$head_retencion = "INSERT INTO ".MAIN_DB_PREFIX."cfdimx_retenciones";
$head_retencion .= " (factura_id, fk_facture, impuesto, importe)";
$head_retencion .= " VALUES";
$head_retencion .= "(";
$head_retencion .= $_REQUEST["facid"].",";
$head_retencion .= $_REQUEST["facid"] . ",";
$head_retencion .= "'".$impuest_head_retencion."',";
$head_retencion .= round($importe_retencion, 2);
$head_retencion .=")";
$respuesta = 0;
if($importe_retencion != 0){
$respuesta = $db->query($head_retencion);
}
if ($respuesta == 1) {
echo '';
} else {
$msg_retenciones = "Error al registrar las Retenciones.";
if($importe_retencion == 0){
$msg_retenciones .= " Porque la suma de las Retenciones no es diferente de 0.";
}
}
}
}
if (isset($_REQUEST["envRetencionLocal"]) && $_REQUEST["envRetencionLocal"] != "") {
if ($_REQUEST["retlocal"] != "") {
$sqm = "SELECT rowid, cod,descripcion,tasa FROM " . MAIN_DB_PREFIX . "cfdimx_config_retenciones_locales
WHERE entity=" . $conf->entity . " AND rowid=" . $_REQUEST["retlocal"];
//print $sqm;
$rqs = $db->query($sqm);
$mrs = $db->fetch_object($rqs);
$importe = $object->total_ht * ($mrs->tasa / 100);
$insert = "
INSERT INTO " . MAIN_DB_PREFIX . "cfdimx_retenciones_locales (
fk_facture,codigo,tasa,importe
) VALUES (
'" . $_REQUEST["facid"] . "',
'" . $mrs->cod . "',
'" . $mrs->tasa . "',
'" . $importe . "'
)";
$db->query($insert);
$rescomm = $db->commit();
if ($rescomm == 1) {
echo '';
} else {
echo 'Error al insertar';
}
}
}
if ($action == "confirm_cancel" && GETPOST('confirm') == "yes") {
$foliosustitucion = (GETPOST("uuid_sustitucion") != '' ? GETPOST("uuid_sustitucion") : '');
$motivo = (GETPOST("motivo") != -1 ? GETPOST("motivo") : '');
$datos = array(
"timbrado_usuario" => GETPOST("rfc_emisor"),
"timbrado_password" => $passwd_timbrado,
"uuid" => GETPOST("uuid"),
"motivo" => $motivo,
"foliosustitucion" => $foliosustitucion
);
if($motivo != "" && $motivo != -1){
$validacion = 1;
if($motivo == "01"){
$validacion = ($motivo == "01" && $foliosustitucion != "" ? 1 : 0);
}
if($validacion == 1){
// Nuevo Esquema de Cancelación 2022
$resultado = $client->call("cancelar", $datos);
//Impresion de los arreglos que se mandan a timbrar
if($conf->global->CFDIMX_DEBUG_TIMBRADO == 1){
print ''; print_r($datos); print ' ';
print ''; print_r($resultado); print ' ';
}
if($resultado["return"] != ""){
if($resultado["return"]["httpStatusCode"] == 200){
//Se guarda el acuse de cancelación en un archivo
if(file_exists($conf->facture->dir_output."/".$object->ref)){
}else{
mkdir($conf->facture->dir_output."/".$object->ref,0700);
}
$fecha = date("Y-m-d")."_".date("H-i-s");
$archivo_acuse = "acuse_cancelacion_".$fecha."_".GETPOST("uuid").".xml";
$nombre_file_acuse = $conf->facture->dir_output."/".$object->ref."/".$archivo_acuse;
$file_acuse = fopen ($nombre_file_acuse, "w");
fwrite($file_acuse,utf8_encode($resultado["return"]["acuse"]));
fclose($file_acuse);
#Inicio para guardar la respuesta a la solicitud de Cancelacion
$sql_solicitud_canceacion = "";
$sql_solicitud_canceacion .= "INSERT INTO ".MAIN_DB_PREFIX."cfdimx_solicitud_cancelacion";
$sql_solicitud_canceacion .= " (fk_facture, httpStatusCode, acuse, status, uuid, uuidStatusCode, message, messageDetail, fecha, hora, archivo)";
$sql_solicitud_canceacion .= " VALUES";
$sql_solicitud_canceacion .= " (";
$sql_solicitud_canceacion .= "'".$_REQUEST["facid"]."',";
$sql_solicitud_canceacion .= "'".$db->escape(utf8_decode($resultado["return"]["httpStatusCode"]))."',";
$sql_solicitud_canceacion .= "'".$db->escape(utf8_decode($resultado["return"]["acuse"]))."',";
$sql_solicitud_canceacion .= "'".$db->escape(utf8_decode($resultado["return"]["status"]))."',";
$sql_solicitud_canceacion .= "'".$db->escape(utf8_decode($resultado["return"]["uuid"]))."',";
$sql_solicitud_canceacion .= "'".$db->escape(utf8_decode($resultado["return"]["uuidStatusCode"]))."',";
$sql_solicitud_canceacion .= "'".$db->escape(utf8_decode($resultado["return"]["message"]))."',";
$sql_solicitud_canceacion .= "'".$db->escape(utf8_decode($resultado["return"]["messageDetail"]))."',";
$sql_solicitud_canceacion .= " now(), now(),";
$sql_solicitud_canceacion .= "'".$db->escape(utf8_decode($archivo_acuse))."'";
$sql_solicitud_canceacion .= " )";
// print $sql_solicitud_canceacion;
$res_solicitud_canceacion = $db->query($sql_solicitud_canceacion);
#Termina para guardar la respuesta a la solicitud de Cancelacion
print '';
}else{
$msg_cfdi_final = "Error al Cancelar la Factura ";
if($resultado["return"]["message"] != "")
$msg_cfdi_final .= $resultado["return"]["message"]." ";
if($resultado["return"]["messageDetail"] != "")
$msg_cfdi_final .= $resultado["return"]["messageDetail"];
}
}else{
$msg_cfdi_final = "No hay respuesta para la cancelación con el SAT, favor de intentar mas tarde.";
}
}else{
$msg_cfdi_final = "Error 9001: El Folio de Sustitución esta vacío y es requerido cuando el Motivo es 01 - Comprobantes emitidos con errores con relación.";
}
}else{
$msg_cfdi_final = "Error 9002: El Motivo de Cancelación es obligatorio.";
}
}
if ($action == "confirm_clasificar_factura" && GETPOST('confirm') == "yes") {
// Classify "abandoned"
$object->fetch($id);
$close_code = GETPOST("close_code", 'restricthtml');
$close_note = GETPOST("close_note", 'restricthtml');
if ($close_code) {
if($dol_version > 13){
$result = $object->setCanceled($user, $close_code, $close_note);
}else{
$result = $object->set_canceled($user, $close_code, $close_note);
}
if ($result < 0) {
setEventMessages($object->error, $object->errors, 'errors');
}else{
$cancela_update = "UPDATE ".MAIN_DB_PREFIX."cfdimx SET cancelado = 1 WHERE fk_facture = " . $_REQUEST["facid"];
$rr = $db->query($cancela_update);
$sqlupd="UPDATE ".MAIN_DB_PREFIX."facture SET subtype = 1001 WHERE rowid = ".$_REQUEST["facid"];
$ass=$db->query($sqlupd);
}
} else {
setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Reason")), null, 'errors');
}
}
if ($action == "confirm_estatus" && GETPOST('confirm') == "yes") {
$sql_verificar_estatus = "";
$sql_verificar_estatus = "SELECT * FROM ".MAIN_DB_PREFIX."cfdimx_estatus";
$sql_verificar_estatus .= " WHERE uuid = '".$uuid."'";
$sql_verificar_estatus .= " AND facid = ".$_REQUEST["facid"];
$sql_verificar_estatus .= " AND entity = ".$conf->entity;
$res_verificar_estatus = $db->query($sql_verificar_estatus);
$num_verificar_estatus = $db->num_rows($res_verificar_estatus);
$datos = array(
"rfc_emisor" => $conf->global->MAIN_INFO_SIREN,
"rfc_receptor" => $soc_rfc,
"total" => $object->total_ttc,
"uuid" => $uuid
);
$result_status_factura = $client->call('getStatusFactura', $datos);
$escancelable = $result_status_factura["return"]["esCancelable"];
if($result_status_factura["return"]["estatusCancelacion"] != "" && !is_null($result_status_factura["return"]["estatusCancelacion"])){
$escancelable = $result_status_factura["return"]["estatusCancelacion"];
}
if($num_verificar_estatus > 0){
$obj_verificar_estatus = $db->fetch_object($res_verificar_estatus);
$update_estatus = "";
$update_estatus = "UPDATE ".MAIN_DB_PREFIX."cfdimx_estatus";
$update_estatus .= " SET ";
$update_estatus .= " estado = '".$db->escape(utf8_decode($result_status_factura["return"]["estado"]))."',";
$update_estatus .= " escancelable = '".$db->escape(utf8_decode($escancelable))."',";
$update_estatus .= " message = '".$db->escape(utf8_decode($result_status_factura["return"]["message"]))."',";
$update_estatus .= " fk_user = '".$user->id."',";
$update_estatus .= " fecha = now(), hora = now()";
$update_estatus .= " WHERE rowid = ".$obj_verificar_estatus->rowid;
if($obj_verificar_estatus->rowid > 0){
$res_update = $db->query($update_estatus);
print '';
}
}else{
$estado_cfdi = $result_status_factura["return"]["estado"];
$estatus_cancelacion = $result_status_factura["return"]["esCancelable"];
$fecha_consulta_estatus = date("Y-m-d")." ".date("H:i:s");
$sql_insert = "";
$sql_insert .= " INSERT INTO ".MAIN_DB_PREFIX."cfdimx_estatus";
$sql_insert .= " (";
$sql_insert .= " uuid, facid, entity, estado, escancelable, message, fk_user, fecha, hora";
$sql_insert .= " )";
$sql_insert .= " VALUES";
$sql_insert .= " (";
$sql_insert .= "'".$uuid."',";
$sql_insert .= "'".$_REQUEST["facid"]."',";
$sql_insert .= "'".$conf->entity."',";
$sql_insert .= "'".$db->escape(utf8_decode($result_status_factura["return"]["estado"]))."',";
$sql_insert .= "'".$db->escape(utf8_decode($escancelable))."',";
$sql_insert .= "'".$db->escape(utf8_decode($result_status_factura["return"]["message"]))."',";
$sql_insert .= "'".$user->id."',";
$sql_insert .= " now(), now()";
$sql_insert .= " )";
$res_insert = $db->query($sql_insert);
print '';
}
}
/*********************************************************************
* *
* Show object in view mode *
* *
*********************************************************************/
llxHeader('', "CFDI ".$conf->global->CFDIMX_VERSION_SAT." - ".$langs->trans('Bill'), 'EN:Customers_Invoices|FR:Factures_Clients|ES:Facturas_a_clientes');
$now = dol_now();
// print '';
// print_r($_SERVER);
// print ' ';
if ($id > 0 || !empty($ref)) {
if ($action == 'cancel') {
$lista_motivos = array(
'-1' => 'Selecciona el Motivo de Cancelación ',
'01' => '01 - Comprobantes emitidos con errores con relación.',
'02' => '02 - Comprobantes emitidos con errores sin relación.',
'03' => '03 - No se llevó a cabo la operación.',
'04' => '04 - Operación nominativa relacionada en una factura global.'
);
$titulo = "El Folio de Sustitución es obligatorio cuando el motivo es 01 . ";
$titulo .= "Nota: Se considera una solicitud de cancelación exitosa cuando regresa un valor de 200, sin embargo esto no asegura su cancelación.";
$pregunta = "¿Desea enviar la solicitud de Cancelación de este CFDI?";
$formquestion = array(
array('type' => 'hidden', 'name' => 'token', 'id'=>'token', 'value' => newToken()),
array('type' => 'hidden', 'name' => 'uuid_cancelar', 'id'=>'uuid_cancelar', 'value' => GETPOST("uuid")),
// array('type' => 'other', 'name' => 'titulo', 'id'=>'titulo', 'label' =>'¿Desea cancelar este CFDI?'),
array('type' => 'other', 'value' => ' '),
array('type' => 'select', 'name' => 'motivo', 'id'=>'motivo', 'label' => 'Motivo', 'values' => $lista_motivos, 'select_show_empty' => 0),
array('type' => 'text', 'name' => 'uuid_sustitucion', 'id'=>'uuid_sustitucion', 'label' =>'Folio de Sustitución', 'moreattr' => 'placeholder="d0645efd-4abb-4c24-a0d7-7986e82cfedf"', 'size' => 35),
array('type' => 'onecolumn', 'value' => $titulo)
);
$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id.'&rfc_emisor='.GETPOST("rfc_emisor").'&uuid='.GETPOST("uuid"), $pregunta, '', 'confirm_cancel', $formquestion, 0, 1, 330, 760);
print $formconfirm;
}
if ($action == 'regen_pdf') {
$formconfirm = $form->formconfirm('pdf_cfdi.php?facid=' . $object->id.'&uuid='.GETPOST("uuid").'&band=1&route=regenpdf', $langs->trans('Regenerar PDF'), $langs->trans('¿Desea regenerar el PDF de este CFDI?'), 'confirm_regen', '', 0, 1);
print $formconfirm;
}
// if ($action == 'preview_pdf2') {
// $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?facid=' . $object->id.'&route=regenpdf&previewpdf=previewpdf', $langs->trans('Previsualización PDF'), $langs->trans('Generar PDF previo de este CFDI?'), 'confirm_peview', '', 0, 1);
// print $formconfirm;
// }
if ($action == 'preview_pdf') {
$formconfirm = $form->formconfirm('pdf_previo.php?facid=' . $object->id.'&route=regenpdf&previewpdf=previewpdf', $langs->trans('Previsualización PDF'), $langs->trans('¿Desea generar un PDF previo de este CFDI?'), 'confirm_peview', '', 0, 1);
print $formconfirm;
}
if ($action == 'del_reten_man') {
$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id.'&del_retencion='.GETPOST('del_retencion').'&tptre='.GETPOST('tptre'), $langs->trans('Eliminar retención'), $langs->trans('¿Desea eliminar esta retención?'), 'confirm_del_reten_man', '', 0, 1);
print $formconfirm;
}
if ($action == 'consultar_estatus') {
// $titulo = "El Folio de Sustitución es obligatorio cuando el motivo es 01 . ";
$titulo = "Consultar Estatus CFDI";
$emisor = "Emisor: ".$conf->global->MAIN_INFO_SIREN;
$receptor = "Receptor: ".$soc_rfc;
$factura = "Factura: ".$object->ref;
$uuid = "UUID: ".$uuid;
$total = "Total: ".number_format($object->total_ttc, 2);
$pregunta = "¿Son correctos los Datos para la Consulta del Estatus de la Factura?";
$formquestion = array(
array('type' => 'onecolumn', 'value' => $emisor),
array('type' => 'onecolumn', 'value' => $receptor),
array('type' => 'onecolumn', 'value' => $factura),
array('type' => 'onecolumn', 'value' => $uuid),
array('type' => 'onecolumn', 'value' => $total),
array('type' => 'onecolumn', 'value' => $pregunta)
);
$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $titulo, '', 'confirm_estatus', $formquestion, 0, 1, 320, 600);
print $formconfirm;
}
if($action == 'clasificar_factura'){
$objectidnext = $object->getIdReplacingInvoice();
if ($objectidnext) {
$facturereplacement = new Facture($db);
$facturereplacement->fetch($objectidnext);
$statusreplacement = $facturereplacement->statut;
}
if ($objectidnext && $statusreplacement == 0) {
print ''.$langs->trans("ErrorCantCancelIfReplacementInvoiceNotValidated").'
';
} else {
// Code
$close[1]['code'] = 'badcustomer';
$close[2]['code'] = 'abandon';
// Help
$close[1]['label'] = $langs->trans("ConfirmClassifyPaidPartiallyReasonBadCustomerDesc");
$close[2]['label'] = $langs->trans("ConfirmClassifyAbandonReasonOtherDesc");
// Texte
$close[1]['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonBadCustomer", $object->ref), $close[1]['label'], 1);
$close[2]['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyAbandonReasonOther"), $close[2]['label'], 1);
// arrayreasons
$arrayreasons[$close[1]['code']] = $close[1]['reason'];
$arrayreasons[$close[2]['code']] = $close[2]['reason'];
// Cree un tableau formulaire
$formquestion = array(
'text' => $langs->trans("ConfirmCancelBillQuestion"),
array('type' => 'radio', 'name' => 'close_code', 'label' => $langs->trans("Reason"), 'values' => $arrayreasons),
array('type' => 'text', 'name' => 'close_note', 'label' => $langs->trans("Comment"), 'value' => 'CFDI Cancelado', 'morecss' => 'minwidth300')
);
$formconfirm = $form->formconfirm($_SERVER['PHP_SELF'].'?facid='.$object->id, $langs->trans('CancelBill'), $langs->trans('ConfirmCancelBill', $object->ref), 'confirm_clasificar_factura', $formquestion, "yes", 1, 250);
print $formconfirm;
}
}
$result = $object->fetch($id, $ref);
if(isset($conf->global->MAIN_MODULE_MULTICURRENCY)){
$object->total_ht = $object->multicurrency_total_ht;
$object->total_tva = $object->multicurrency_total_tva;
$object->total_ttc = $object->multicurrency_total_ttc;
}
if ($result > 0) {
if($dol_version >= 14){
if ($user->socid > 0 && $user->societe_id != $object->socid)
accessforbidden('', 0);
}else{
if ($user->societe_id > 0 && $user->societe_id != $object->socid)
accessforbidden('', 0);
}
$result = $object->fetch_thirdparty();
$soc = new Societe($db);
$soc->fetch($object->socid);
//Aquí comienza la vista
$head = facture_prepare_head($object);
print dol_get_fiche_head($head, "tabfactclient", 'CFDI', -1, 'bill');
$formconfirm = '';
if (isset($msg_cfdi_final) && $msg_cfdi_final != "") {
if($errores_factura != null){
$msg_cfdi_final .= "Validaciones del Comprobante ";
foreach ($errores_factura as $error_factura) {
$msg_cfdi_final .= $error_factura." ";
}
}
if($errores_conceptos != null){
$msg_cfdi_final .= "Validaciones de Conceptos ";
foreach ($errores_conceptos as $error_concepto) {
$msg_cfdi_final .= " ";
for ($i=0; $i < count($error_concepto); $i++) {
$msg_cfdi_final .= $error_concepto[$i]." ";
}
}
}
if($ban_timbrado == 1){
setEventMessage($msg_cfdi_final, 'mesgs');
}else{
dol_htmloutput_errors($msg_cfdi_final);
}
}
if(@$msg_retenciones != ""){
dol_htmloutput_errors($msg_retenciones);
}
$validacion_cfdimx = $objFacturaCFDI->validarVersionDoli($conf->global->CFDIMX_V_MIN_DOLI, $conf->global->CFDIMX_V_MAX_DOLI);
if($validacion_cfdimx != ""){
print '';
print $validacion_cfdimx;
print '
';
}
if($conf->global->CFDIMX_ALERTA_TIMBRES == 1 && $modo_timbrado == 1){
if($folios_disponibles <= $conf->global->CFDIMX_MIN_TIMBRES){
$url_config = 'Configuración ';
print '';
print ' ';
print ' ';
print 'Alerta de Timbres';
print ' ';
if($folios_disponibles == $conf->global->CFDIMX_MIN_TIMBRES){
print 'Actualmente tienes '.$folios_disponibles.' folios disponibles que es la cantidad ('.$conf->global->CFDIMX_MIN_TIMBRES.') minima establecida en la '.$url_config.'.';
}else{
print 'Actualmente tienes '.$folios_disponibles.' folios disponibles que es la cantidad ('.$conf->global->CFDIMX_MIN_TIMBRES.') minima por debajo de la establecida en la '.$url_config.'.';
}
print ' ';
print 'Contacta a tu Proveedor de Timbres para adquirir más.';
print '
';
}
}
?>
getSommePaiement();
$linkback = ''.$langs->trans("BackToList").' ';
$morehtmlref = '';
// Ref invoice
if ($object->status == $object::STATUS_DRAFT && !$mysoc->isInEEC() && !empty($conf->global->INVOICE_ALLOW_FREE_REF)) {
$morehtmlref .= $form->editfieldkey("Ref", 'ref', $object->ref, $object, '', 'string', '', 0, 1);
$morehtmlref .= $form->editfieldval("Ref", 'ref', $object->ref, $object, '', 'string', '', null, null, '', 1);
$morehtmlref .= '
';
}
// Ref customer
$morehtmlref .= $form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, '', 'string', '', 0, 1);
$morehtmlref .= $form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, '', 'string', '', null, null, '', 1);
// Thirdparty
$morehtmlref .= '
'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1, 'customer');
if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) {
$morehtmlref .= ' (
'.$langs->trans("OtherBills").' )';
}
// Project
if (!empty($conf->projet->enabled)) {
$langs->load("projects");
$morehtmlref .= '
'.$langs->trans('Project').' ';
if ($usercancreate) {
if ($action != 'classify') {
$morehtmlref .= '
'.img_edit($langs->transnoentitiesnoconv('SetProject')).' : ';
}
if ($action == 'classify') {
$morehtmlref .= '
';
} else {
$morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1);
}
} else {
if (!empty($object->fk_project)) {
$proj = new Project($db);
$proj->fetch($object->fk_project);
$morehtmlref .= '
';
$morehtmlref .= $proj->ref;
$morehtmlref .= ' ';
} else {
$morehtmlref .= '';
}
}
}
$morehtmlref .= '
';
$object->totalpaye = $totalpaye; // To give a chance to dol_banner_tab to use already paid amount to show correct status
dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref, '', 0, '', '');
print '';
print '
';
// Invoice content
print '
';
print '';
print '';
print '';
/*
print '';
print ' ';
print ' ';
print '';
print ' ';
print ' ';
print ' ';*/
print ' ';
print ' ';
print 'Datos del comprobante';
print ' ';
print ' ';
print ' ';
// print '';
print ' ';
if (GETPOST('tdocument') && GETPOST('edittp') == 1) {
// print GETPOST('tdocument');
// print 'enra ';
$sql = "UPDATE " . MAIN_DB_PREFIX . "cfdimx_type_document SET tipo_document=" . GETPOST('tdocument') . " WHERE fk_facture=" . $id;
//print $sql;
$rsq = $db->query($sql);
// $sql2 = "UPDATE " . MAIN_DB_PREFIX . "facture SET type=" . GETPOST('tdocument') . " WHERE rowid=" . $id;
// print $sql2;
// $rsq2 = $db->query($sql2);
$sql = "DELETE FROM " . MAIN_DB_PREFIX . "cfdimx_retenciones WHERE fk_facture=" . $id;
$rsq = $db->query($sql);
$sql = "DELETE FROM " . MAIN_DB_PREFIX . "cfdimx_retencionesdet WHERE factura_id=" . $id;
$rsq = $db->query($sql);
if ((GETPOST('tdocument') == 2 || GETPOST('tdocument') == 3)) {
$sql = "SELECT rowid,total_ht FROM " . MAIN_DB_PREFIX . "facturedet WHERE fk_facture=" . $id;
if ($conf->global->MAIN_MODULE_MULTICURRENCY) {
$sql = "SELECT rowid,multicurrency_total_ht as total_ht FROM " . MAIN_DB_PREFIX . "facturedet WHERE fk_facture=" . $id;
}
$retiva = 0;
$retisr = 0;
$resultset = $db->query($sql);
while ($rsqq = $db->fetch_object($resultset)) {
$isrprod = $rsqq->total_ht * 0.10;
$ivaprod = $rsqq->total_ht * 0.106667;
$sql = "INSERT INTO " . MAIN_DB_PREFIX . "cfdimx_retencionesdet(factura_id, fk_facturedet, base, impuesto, tipo_factor, tasa, importe) VALUES(" . $id . "," . $rsqq->rowid . ",'" . round($rsqq->total_ht, 2) . "','002','Tasa','0.106667','" . round($ivaprod, 2) . "')";
$rsq = $db->query($sql);
$sql = "INSERT INTO " . MAIN_DB_PREFIX . "cfdimx_retencionesdet(factura_id, fk_facturedet, base, impuesto, tipo_factor, tasa, importe) VALUES(" . $id . "," . $rsqq->rowid . ",'" . round($rsqq->total_ht, 2) . "','001','Tasa','0.10','" . round($isrprod, 2) . "')";
$rsq = $db->query($sql);
$retiva += $ivaprod;
$retisr += $isrprod;
}
$sql = "INSERT INTO " . MAIN_DB_PREFIX . "cfdimx_retenciones (factura_id,fk_facture,impuesto,importe) VALUES(" . $id . "," . $id . ",'IVA'," . round($retiva, 2) . ")";
$rsq = $db->query($sql);
$sql = "INSERT INTO " . MAIN_DB_PREFIX . "cfdimx_retenciones (factura_id,fk_facture,impuesto,importe) VALUES(" . $id . "," . $id . ",'ISR'," . round($retisr, 2) . ")";
$rsq = $db->query($sql);
print "";
}
if (GETPOST('tdocument') == 5) {
$sql = "SELECT rowid,total_ht FROM " . MAIN_DB_PREFIX . "facturedet WHERE fk_facture=" . $id;
if ($conf->global->MAIN_MODULE_MULTICURRENCY) {
$sql = "SELECT rowid,multicurrency_total_ht as total_ht FROM " . MAIN_DB_PREFIX . "facturedet WHERE fk_facture=" . $id;
}
$retiva = 0;
$resultset = $db->query($sql);
while ($rsqq = $db->fetch_object($resultset)) {
$ivaprod = $rsqq->total_ht * 0.04;
$sql = "INSERT INTO " . MAIN_DB_PREFIX . "cfdimx_retencionesdet(factura_id, fk_facturedet, base, impuesto, tipo_factor, tasa, importe) VALUES(" . $id . "," . $rsqq->rowid . ",'" . round($rsqq->total_ht, 2) . "','002','Tasa','0.04','" . round($ivaprod, 2) . "')";
$rsq = $db->query($sql);
$retiva += $ivaprod;
}
$sql = "INSERT INTO " . MAIN_DB_PREFIX . "cfdimx_retenciones (factura_id,fk_facture,impuesto,importe) VALUES(" . $id . "," . $id . ",'IVA'," . round($retiva, 2) . ")";
$rsq = $db->query($sql);
print "";
}
if (GETPOST('tdocument') == 9){
$objFacturaCFDI->correccionCCE($id);
$objCCE->createCCE($id);
print "";
}
}
if (GETPOST('tdocument') && GETPOST('edittp') == 2) {
$sql = "INSERT INTO " . MAIN_DB_PREFIX . "cfdimx_type_document (fk_facture,tipo_document) VALUES (" . $id . "," . GETPOST('tdocument') . ")";
$rs = $db->query($sql);
if (GETPOST('tdocument') == 2 || GETPOST('tdocument') == 3) {
$sql = "SELECT rowid,total_ht FROM " . MAIN_DB_PREFIX . "facturedet WHERE fk_facture=" . $id;
if ($conf->global->MAIN_MODULE_MULTICURRENCY) {
$sql = "SELECT rowid,multicurrency_total_ht as total_ht FROM " . MAIN_DB_PREFIX . "facturedet WHERE fk_facture=" . $id;
}
$retiva = 0;
$retisr = 0;
$resultset = $db->query($sql);
while ($rsqq = $db->fetch_object($resultset)) {
$isrprod = $rsqq->total_ht * 0.10;
$ivaprod = $rsqq->total_ht * 0.106667;
$sql = "INSERT INTO " . MAIN_DB_PREFIX . "cfdimx_retencionesdet(factura_id, fk_facturedet, base, impuesto, tipo_factor, tasa, importe) VALUES(" . $id . "," . $rsqq->rowid . ",'" . round($rsqq->total_ht, 2) . "','002','Tasa','0.106667','" . round($ivaprod, 2) . "')";
$rsq = $db->query($sql);
$sql = "INSERT INTO " . MAIN_DB_PREFIX . "cfdimx_retencionesdet(factura_id, fk_facturedet, base, impuesto, tipo_factor, tasa, importe) VALUES(" . $id . "," . $rsqq->rowid . ",'" . round($rsqq->total_ht, 2) . "','001','Tasa','0.10','" . round($isrprod, 2) . "')";
$rsq = $db->query($sql);
$retiva += $ivaprod;
$retisr += $isrprod;
}
$sql = "INSERT INTO " . MAIN_DB_PREFIX . "cfdimx_retenciones (factura_id,fk_facture,impuesto,importe) VALUES(" . $id . "," . $id . ",'IVA'," . round($retiva, 2) . ")";
$rsq = $db->query($sql);
$sql = "INSERT INTO " . MAIN_DB_PREFIX . "cfdimx_retenciones (factura_id,fk_facture,impuesto,importe) VALUES(" . $id . "," . $id . ",'ISR'," . round($retisr, 2) . ")";
$rsq = $db->query($sql);
print "";
}
if (GETPOST('tdocument') == 5) {
$sql = "SELECT rowid,total_ht FROM " . MAIN_DB_PREFIX . "facturedet WHERE fk_facture=" . $id;
if ($conf->global->MAIN_MODULE_MULTICURRENCY) {
$sql = "SELECT rowid,multicurrency_total_ht as total_ht FROM " . MAIN_DB_PREFIX . "facturedet WHERE fk_facture=" . $id;
}
$retiva = 0;
$resultset = $db->query($sql);
while ($rsqq = $db->fetch_object($resultset)) {
$ivaprod = $rsqq->total_ht * 0.04;
$sql = "INSERT INTO " . MAIN_DB_PREFIX . "cfdimx_retencionesdet(factura_id, fk_facturedet, base, impuesto, tipo_factor, tasa, importe) VALUES(" . $id . "," . $rsqq->rowid . ",'" . round($rsqq->total_ht, 2) . "','002','Tasa','0.04','" . round($ivaprod, 2) . "')";
$rsq = $db->query($sql);
$retiva += $ivaprod;
}
$sql = "INSERT INTO " . MAIN_DB_PREFIX . "cfdimx_retenciones (factura_id,fk_facture,impuesto,importe) VALUES(" . $id . "," . $id . ",'IVA'," . round($retiva, 2) . ")";
$rsq = $db->query($sql);
print "";
}
if (GETPOST('tdocument') == 9){
$objFacturaCFDI->correccionCCE($id);
$objCCE->createCCE($id);
print "";
}
}
$sql = "SELECT IFNULL(tipo_document,NULL) as tipo_document FROM " . MAIN_DB_PREFIX . "cfdimx_type_document WHERE fk_facture=" . $id;
$resp = $db->query($sql);
if($resp){
$respp = $db->fetch_object($resp);
if (@$respp->tipo_document == NULL) {
$sql = "SELECT type FROM " . MAIN_DB_PREFIX . "facture WHERE rowid=" . $id;
$resp = $db->query($sql);
$respp = $db->fetch_object($resp);
if ($respp->type == 2) {
$sql = "INSERT INTO " . MAIN_DB_PREFIX . "cfdimx_type_document (fk_facture,tipo_document) VALUES (" . $id . ",4)";
$resp = $db->query($sql);
}
}
}
// $val_cce = (file_exists('cce.php') ? 1 : 0);
$val_cce = 1;
if ($cfdi_tot > 0) {
print '';
print 'Tipo de Documento CFDI ';
$sql = "SELECT IFNULL(tipo_document,NULL) as tipo_document FROM " . MAIN_DB_PREFIX . "cfdimx_type_document WHERE fk_facture=" . $id;
$resp = $db->query($sql);
$respp = $db->fetch_object($resp);
print '';
if ($respp->tipo_document != NULL) {
if ($respp->tipo_document == 1) {
print "Factura Estándar";
}
if ($respp->tipo_document == 2) {
print "Recibo de Honorarios";
}
if ($respp->tipo_document == 3) {
print "Recibo de Arrendamiento";
}
if ($respp->tipo_document == 4) {
print "Nota de Crédito";
}
if ($respp->tipo_document == 5) {
print "Factura de Fletes";
}
if ($respp->tipo_document == 6) {
print "Factura RIF";
}
if ($respp->tipo_document == 7) {
print "Factura Traslado";
}
if ($respp->tipo_document == 8) {
print "Factura Global";
}
if ($respp->tipo_document == 9) {
print 'Factura CCE (Comercio Exterior)';
}
// if ($respp->tipo_document == 10) {
// print 'Factura CCE (Comercio Exterior)';
// }
} else {
$sql = "SELECT type FROM " . MAIN_DB_PREFIX . "facture WHERE rowid=" . $id;
$resp = $db->query($sql);
$respp = $db->fetch_object($resp);
if ($respp->type == 2) {
print "Nota de Crédito";
} else {
print "Factura Estándar";
}
}
print ' ';
print ' ';
} else {
print '';
$sql = "SELECT IFNULL(tipo_document,NULL) as tipo_document FROM " . MAIN_DB_PREFIX . "cfdimx_type_document WHERE fk_facture=" . $id;
$resp = $db->query($sql);
$respp = $db->fetch_object($resp);
if (@$respp->tipo_document != NULL) {
$edit_icon = '';
$edit_icon .= 'id . '&action=edit_type">'.img_edit($langs->trans('SetType'), 1).' ';
$edit_icon .= ' ';
}
print '
Tipo de Documento CFDI
'.@$edit_icon.'
';
if (@$respp->tipo_document != NULL) {
print '';
if ($action == 'edit_type') {
if ($respp->tipo_document != 4) {
print '';
}
}else {
if ($respp->tipo_document == 1) {
$label = "Factura Estándar";
}
if ($respp->tipo_document == 2) {
$label = "Recibo de Honorarios";
}
if ($respp->tipo_document == 3) {
$label = "Recibo de Arrendamiento";
}
if ($respp->tipo_document == 4) {
$label = "Nota de Crédito";
}
if ($respp->tipo_document == 5) {
$label = "Factura de Fletes";
}
if ($respp->tipo_document == 6) {
$label = "Factura RIF";
}
if ($respp->tipo_document == 7) {
$label = "Factura Traslado";
}
if ($respp->tipo_document == 8) {
$label = "Factura Global";
}
if($val_cce == 1){
if ($respp->tipo_document == 9) {
$label = "Factura CCE (Comercio Exterior)";
}
}
print $label;
}
print ' ';
}else {
print '';
print '';
print ' ';
}
print ' ';
}
// Date invoice
print '';
print '';
print '';
print ' ';
print '';
if ($object->type != 2) {
if ($action == 'editinvoicedate') {
$form->form_date($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $object->date, 'invoicedate');
} else {
print dol_print_date($object->date, 'daytext');
}
} else {
print dol_print_date($object->date, 'daytext');
}
print ' ';
print ' ';
// Date payment term
/*
print '';
print '';
print '';
print ' ';
print '';
if ($object->type != 2) {
if ($action == 'editpaymentterm') {
$form->form_date($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $object->date_lim_reglement, 'paymentterm');
} else {
print dol_print_date($object->date_lim_reglement, 'daytext');
if ($object->date_lim_reglement < ($now - $conf->facture->client->warning_delay) && !$object->paye && $object->statut == 1 && !$object->am)
print img_warning($langs->trans('Late'));
}
} else {
print ' ';
}
print ' ';
print ' ';
*/
// Mode de reglement
$pagos_detalles = new ComplementoPagos($db);
print '';
print '';
print '';
print '';
print '';
print 'Forma de Pago';
print ' ';
print ' ';
print '
';
print ' ';
print '';
print $pagos_detalles->obtener_catalogo($object->mode_reglement_code, 'formpago', 5, 1);
print ' ';
print ' ';
// Conditions de reglement
print '';
print '';
print '';
print ' ';
print '';
if ($object->type != 2) {
if ($action == 'editconditions') {
$form->form_conditions_reglement($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $object->cond_reglement_id, 'cond_reglement_id');
} else {
$form->form_conditions_reglement($_SERVER['PHP_SELF'] . '?facid=' . $object->id, $object->cond_reglement_id, 'none');
}
} else {
print ' ';
}
print ' ';
print ' ';
// Metodo de Pago
print '';
print '';
print '';
print '';
print '';
print 'Metodo de Pago';
print ' ';
print ' ';
print '
';
print ' ';
print '';
if($object->array_options["options_formpagcfdi"] != ''){
if($object->array_options["options_formpagcfdi"] == 'PUE'){
print 'PUE - Pago en una sola exhibición';
}else{
print 'PPD - Pago en parcialidades o diferido';
}
}else{
print ' ';
}
print ' ';
print ' ';
#Exportacion
if(strcmp($conf->global->CFDIMX_VERSION_SAT, "4.0") == 0){
print '';
print '';
print '';
print '';
print '';
print 'Exportación';
print ' ';
print ' ';
print '
';
print ' ';
print '';
print $pagos_detalles->obtener_catalogo($object->array_options["options_clave_expor"], 'exportacion', 6, 1);
// if($object->array_options["options_clave_expor"] != ''){
// print array_search($object->array_options["options_clave_expor"], array("01 - No Aplica" => "01", "02 - Definitiva" => "02", "03 - Temporal" => "03"));
// }else{
// print ' ';
// }
print ' ';
print ' ';
}
// Cuenta
// $sql = "SELECT * FROM " . MAIN_DB_PREFIX . "societe_rib WHERE default_rib=1 AND fk_soc = " . $soc->id;
// $resql = $db->query($sql);
// $nmc = $db->fetch_object($resql);
// print '';
// print 'Cuenta: ';
// if (DOL_VERSION < 8) {
// $desc = $form->textwithpicto($nmc->number, "Nota: El valor de este dato es el correspondiente al campo Número de Cuenta de Pago de la factura electrónica. No es obligatorio.", 1, 'help', '', 0, 3) . ' Modificar Valor ';
// print '' . $desc . ' ';
// } else {
// @$desc = $form->textwithpicto($nmc->number, "Nota: El valor de este dato es el correspondiente al campo Número de Cuenta de Pago de la factura electrónica. No es obligatorio.", 1, 'help', '', 0, 3) . ' Modificar Valor ';
// print '' . $desc . ' ';
// }
// print '';
//Divisa
print '';
print 'Divisa ';
print '';
if ($cfdi_tot > 0) {
if (!empty($divisa)) {
echo $divisa;
}
}else{
if (@$conf->global->MAIN_MODULE_MULTICURRENCY) {
$sql = "SELECT multicurrency_code AS divisa FROM " . MAIN_DB_PREFIX . "facture WHERE rowid=" . $id;
$ra = $db->query($sql);
$rb = $db->fetch_object($ra);
print $rb->divisa;
$conf->currency = $rb->divisa;
print ' ';
} else {
if (!empty($_REQUEST['osd'])) {
$osd = $_REQUEST['osd'];
} else {
$osd = $conf->currency;
}
print 'id . '&osd="+this.value>';
print '' . $osd . ' ';
print ' ';
print 'MXN ';
print 'USD ';
print ' ';
print ' ';
}
}
print ' ';
print ' ';
print '
';
print '
';
#Agregar Complemento
if ($object->statut == 1 || $object->statut == 2) {
// $complementos_cfdi = $objComplementos->complementosCFDI($object->id);
print '
';
print '';
print '';
if($uuid == ""){
print '';
print '';
print ' ';
print 'Agregar Complemento';
print ' ';
print ' ';
}else{
if($object_complementos->num_complementos > 0){
print '';
print ' ';
print 'Ver Complementos CFDI ';
print ' ';
}else{
print ' ';
print 'Complementos CFDI ';
}
}
print ' ';
print ' ';
if($uuid != ""){
if($object_complementos->num_complementos == 0){
print '';
print '';
print '';
echo "No se registraron complementos para esta factura";
print '
';
print ' ';
print ' ';
}else{
print '';
print '';
if($object_complementos->cfdi_rel == 1){
print '';
print '
';
print img_picto('CFDI Relacionados', 'switch_on');
print '
';
print '
';
print ' ';
print 'CFDI Relacionados';
print '
';
print '
';
}
if($object_complementos->fac_cce == 1){
print '';
print '
';
print img_picto('Comercio Exterior 1.1', 'switch_on');
print '
';
print '
';
print ' ';
print 'Comercio Exterior 1.1';
print '
';
print '
';
}
if($object_complementos->fac_cce20 == 1){
print '';
print '
';
print img_picto('Comercio Exterior 2.0', 'switch_on');
print '
';
print '
';
print ' ';
print 'Comercio Exterior 2.0';
print '
';
print '
';
}
if($object_complementos->fac_cp20 == 1){
print '';
print '
';
print img_picto('Carta Porte 2.0', 'switch_on');
print '
';
print '
';
print ' ';
print 'Carta Porte 2.0';
print '
';
print '
';
}
if($object_complementos->fac_cp30 == 1){
print '';
print '
';
print img_picto('Carta Porte 3.0', 'switch_on');
print '
';
print '
';
print ' ';
print 'Carta Porte 3.0';
print '
';
print '
';
}
print ' ';
print ' ';
}
}
print '
';
print '
';
}
$archivos_addendas = DOL_DOCUMENT_ROOT.'/cfdimx/addendas/index.php';
if (!is_null($uuid) && $uuid != "" && file_exists($archivos_addendas) == true) {
$addendas = null;
print '
';
}
if ($object->statut != 0) {
print '
';
#Datos de timbrado
if((int)DOL_VERSION == 10){
print '';
print '';
print ' ';
print 'Datos de Timbrado ';
print ' ';
print ' ';
}else{
print '';
print '';
print ' ';
print 'Datos de Timbrado ';
print ' ';
print ' ';
}
print '';
print '';
print '';
if($fecha_consulta_estatus != ""){
print '';
print 'Estado CFDI ';
print ''.$estado_cfdi.' ';
print ' ';
print '';
print 'Estatus de cancelación ';
print ''.$estatus_cancelacion.' ';
print ' ';
$titulo_consulta = "Consultar el Estatus de la Factura";
print '';
print 'Última Consulta de Estatus ';
print '';
print '';
print ' ';
print ' ';
}else{
if(strcmp("Sin timbrar", $estado_cfdi) == 0){
print '';
print 'Estado CFDI ';
print ''.$estado_cfdi.' ';
print ' ';
}else{
$titulo_consulta = "Consultar el Estatus de la Factura";
print '';
print 'Consultar Estatus ';
print '';
print '';
print ' ';
print ' ';
}
}
print '';
print 'UUID ';
print '' . $uuid . ' ';
print ' ';
$modo_timbrado_desc = ($modo_timbrado == 1) ? "Producción" : "Pruebas";
print '';
print 'Modo de Timbrado Activo ';
print '' . $modo_timbrado_desc . ' ';
print ' ';
print '';
print 'Versión de CFDI Activa ';
print '' . $conf->global->CFDIMX_VERSION_SAT . ' ';
print ' ';
print '';
print 'Folios Disponibles ';
print '' . $folios_disponibles . ' ';
print ' ';
print '';
print 'Folios Timbrados ';
print '' . $folios_timbrados . ' ';
print ' ';
print '
';
print ' ';
print ' ';
print '
';
print '
';
}
$sql_solicitud = "SELECT * FROM ".MAIN_DB_PREFIX."cfdimx_solicitud_cancelacion WHERE fk_facture = ".$object->id." ORDER BY rowid DESC LIMIT 1";
$res_solicitud = $db->query($sql_solicitud);
$num_solicitud = $db->num_rows($res_solicitud);
if($num_solicitud > 0){
print '
';
print '';
print '';
print ' ';
print ' ';
print 'Solicitud de Cancelación ';
print ' ';
print ' ';
$obj_cancelacion = $db->fetch_object($res_solicitud);
print '';
print 'UUID ';
print ''.$obj_cancelacion->uuid.' ';
print ' ';
print '';
print 'Estatus ';
print ''.$obj_cancelacion->uuidStatusCode.' ';
print ' ';
print '';
print 'Acuse ';
print '';
$ruta = DOL_URL_ROOT.'/document.php?modulepart=facture&file='.$object->ref.'/';
$ruta .= $obj_cancelacion->archivo;
print '';
print ' ';
print $obj_cancelacion->archivo;
print ' ';
print ' ';
print ' ';
print '';
print 'Fecha ';
print ''.$obj_cancelacion->fecha.' '.$obj_cancelacion->hora.' ';
print ' ';
print '
';
print '
';
}
print '
'; //Fiche left
print '
';
print '
';
print '';
print '';
print ' ';
print ' ';
print 'Montos del comprobante ';
print ' ';
print ' ';
//Descuentos
// Relative and absolute discounts
$addrelativediscount = 'id . '">' . $langs->trans("EditRelativeDiscounts") . ' ';
$addabsolutediscount = 'id . '">' . $langs->trans("EditGlobalDiscounts") . ' ';
$addcreditnote = 'id . '">' . $langs->trans("AddCreditNote") . ' ';
print '';
print '';
print $langs->trans('Discounts');
print ' ';
print '';
if($dol_version >= 14){
if ($soc->remise_percent)
print $langs->trans("CompanyHasRelativeDiscount", $soc->remise_percent);
else
print $langs->trans("CompanyHasNoRelativeDiscount");
}else{
if ($soc->remise_client)
print $langs->trans("CompanyHasRelativeDiscount", $soc->remise_client);
else
print $langs->trans("CompanyHasNoRelativeDiscount");
}
if (@$absolute_discount > 0) {
print '. ';
if ($object->statut > 0 || $object->type == 2 || $object->type == 3) {
if ($object->statut == 0) {
print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency));
print '. ';
} else {
if ($object->statut < 1 || $object->type == 2 || $object->type == 3) {
$text = $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency));
print ' ' . $text . '. ';
} else {
$text = $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->transnoentities("Currency" . $conf->currency));
$text2 = $langs->trans("AbsoluteDiscountUse");
print $form->textwithpicto($text, $text2);
}
}
} else {
// Remise dispo de type remise fixe (not credit note)
print ' ';
$form->form_remise_dispo($_SERVER["PHP_SELF"] . '?facid=' . $object->id, GETPOST('discountid'), 'remise_id', $soc->id, $absolute_discount, $filterabsolutediscount, $resteapayer, ' (' . $addabsolutediscount . ')');
}
} else {
if (@$absolute_creditnote > 0) // If not, link will be added later
{
if ($object->statut == 0 && $object->type != 2 && $object->type != 3)
print ' (' . $addabsolutediscount . ') ';
else
print '. ';
} else
print '. ';
}
if (@$absolute_creditnote > 0) {
// If validated, we show link "add credit note to payment"
if ($object->statut != 1 || $object->type == 2 || $object->type == 3) {
if ($object->statut == 0 && $object->type != 3) {
$text = $langs->trans("CompanyHasCreditNote", price($absolute_creditnote), $langs->transnoentities("Currency" . $conf->currency));
print $form->textwithpicto($text, $langs->trans("CreditNoteDepositUse"));
} else {
print $langs->trans("CompanyHasCreditNote", price($absolute_creditnote), $langs->transnoentities("Currency" . $conf->currency)) . '.';
}
} else {
// Remise dispo de type avoir
if (!$absolute_discount)
print ' ';
//$form->form_remise_dispo($_SERVER["PHP_SELF"].'?facid='.$object->id, 0, 'remise_id_for_payment', $soc->id, $absolute_creditnote, $filtercreditnote, $resteapayer);
$form->form_remise_dispo($_SERVER["PHP_SELF"] . '?facid=' . $object->id, 0, 'remise_id_for_payment', $soc->id, $absolute_creditnote, $filtercreditnote, 0); // We must allow credit not even if amount is higher
}
}
if (!@$absolute_discount && !@$absolute_creditnote) {
print $langs->trans("CompanyHasNoAbsoluteDiscount");
if ($object->statut == 0 && $object->type != 2 && $object->type != 3)
print ' (' . $addabsolutediscount . ') ';
else
print '. ';
}
print ' ';
print ' ';
//nueva val not credito
$total_ht = 0;
$total_tva = 0;
$total_ttc = 0;
if($object->total_ht == 0){
$total_ht = $object->lines[0]->total_ht;
}else{
$total_ht = $object->total_ht;
}
if($object->total_tva == 0){
$total_tva = $object->lines[0]->total_tva;
}else{
$total_tva = $object->total_tva;
}
if($object->total_ttc == 0){
$total_ttc = $object->lines[0]->total_ttc;
}else{
$total_ttc = $object->total_ttc;
}
// Amount
print '';
print '' . $langs->trans('AmountHT') . ' ';
print '';
print price($total_ht, 0, '', 1, -1, -1, $object->multicurrency_code);
print ' ';
print ' ';
print '';
print '' . $langs->trans('AmountVAT') . ' ';
print '';
print price($total_tva, 0, '', 1, -1, -1, $object->multicurrency_code);
print ' ';
print ' ';
// Amount Local Taxes
if($dol_version >= 14){
if ($mysoc->pays == 'ES') {
if ($mysoc->localtax1_assuj == "1") //Localtax1 RE
{
print '';
print '' . $langs->transcountry("AmountLT1", $mysoc->pays) . ' ';
print '';
print price($object->total_localtax1, 0, '', 1, -1, -1, $object->multicurrency_code);
print ' ';
print ' ';
}
if ($mysoc->localtax2_assuj == "1") //Localtax2 IRPF
{
print '';
print '' . $langs->transcountry("AmountLT2", $mysoc->pays) . ' ';
print '';
print price($object->total_localtax2, 0, '', 1, -1, -1, $object->multicurrency_code);
print ' ';
print ' ';
}
}
}else{
if ($mysoc->pays_code == 'ES') {
if ($mysoc->localtax1_assuj == "1") //Localtax1 RE
{
print '';
print '' . $langs->transcountry("AmountLT1", $mysoc->pays_code) . ' ';
print '';
print price($object->total_localtax1, 0, '', 1, -1, -1, $object->multicurrency_code);
print ' ';
print ' ';
}
if ($mysoc->localtax2_assuj == "1") //Localtax2 IRPF
{
print '';
print '' . $langs->transcountry("AmountLT2", $mysoc->pays_code) . ' ';
print '';
print price($object->total_localtax2, 0, '', 1, -1, -1, $object->multicurrency_code);
print ' ';
print ' ';
}
}
}
//Consulta Retenciones
$sqm = "SELECT COUNT(*) AS count FROM information_schema.tables WHERE table_schema = '" . $db->database_name . "' AND table_name = '" . MAIN_DB_PREFIX . "cfdimx_config_retenciones_locales'";
$rqm = $db->query($sqm);
$rqsm = $db->fetch_object($rqm);
if ($rqsm->count > 0) {
$sql = "SELECT * FROM " . MAIN_DB_PREFIX . "cfdimx_retenciones_locales WHERE fk_facture = " . $_REQUEST["facid"];
$resqm = $db->query($sql);
if ($resqm) {
$cfdi_m = $db->num_rows($resqm);
$i = 0;
if ($cfdi_m > 0) {
while ($i < $cfdi_m) {
$obm = $db->fetch_object($resqm);
if ($cfdi_tot < 1) {
print '';
print 'Ret. ' . $obm->codigo . ' ';
print '';
print price($obm->importe, 0, '', 1, -1, -1, $object->multicurrency_code);
print ' ';
print ' ';
$object->total_ttc = $object->total_ttc - $obm->importe;
$object->total_ttc = str_replace(",", "", number_format($object->total_ttc, 2));
} else {
print '';
print 'Ret. ' . $obm->codigo . ' ';
print '';
print price($obm->importe, 0, '', 1, -1, -1, $object->multicurrency_code);
print ' ';
print ' ';
}
$i++;
}
}
}
}
$sql = "SELECT count(*) as exist FROM " . MAIN_DB_PREFIX . "cfdimx_retenciones WHERE fk_facture=" . $id;
$rsq = $db->query($sql);
$rsqq = $db->fetch_object($rsq);
if ($rsqq->exist > 0) {
$sql = "SELECT impuesto,importe FROM " . MAIN_DB_PREFIX . "cfdimx_retenciones WHERE fk_facture=" . $id;
$rsq = $db->query($sql);
$restar = 0;
while ($rsqq = $db->fetch_object($rsq)) {
$restar = $restar + $rsqq->importe;
print '';
print 'Ret. de ' . $rsqq->impuesto . ' ';
print '';
print price($rsqq->importe, 0, '', 1, -1, -1, $object->multicurrency_code);
print ' ';
print ' ';
}
if ($cfdi_tot < 1) {
$total_res = $object->total_ttc - $restar;
print '';
print '' . $langs->trans('AmountTTC') . ' ';
print '';
print price($total_res, 0, '', 1, -1, -1, $object->multicurrency_code);
print ' ';
print ' ';
} else {
print '';
print '' . $langs->trans('AmountTTC') . ' ';
print '';
print price($object->total_ttc, 0, '', 1, -1, -1, $object->multicurrency_code);
print ' ';
print ' ';
}
} else {
print '';
print '' . $langs->trans('AmountTTC') . ' ';
print '';
print price($total_ttc, 0, '', 1, -1, -1, $object->multicurrency_code);
print ' ';
print ' ';
}
print '
';
print '
';
#Retenciones - Son como retenciones manuales (Inicio)
if ($object->statut != 0) {
print '
';
print '';
print '';
print ' ';
print ' ';
print 'Retenciones ';
print ' ';
print ' ';
print '';
print '';
if ($cfdi_tot < 1) {
print '';
print ' ';
$sql_ret = "SELECT * FROM " . MAIN_DB_PREFIX . "cfdimx_retenciones WHERE fk_facture = " . $_REQUEST["facid"];
$resql = $db->query($sql_ret);
if ($resql) {
$cfdi_tott = $db->num_rows($resql);
$i = 0;
if ($cfdi_tott > 0) {
print '';
print '';
print 'Impuesto ';
print 'Importe ';
print 'Acción ';
print ' ';
while ($i < $cfdi_tott) {
$obj = $db->fetch_object($resql);
print '';
print '' . $obj->impuesto . ' ';
print '';
print price($obj->importe, 0, '', 1, -1, -1, $object->multicurrency_code);
print ' ';
$url = '?facid=' . $_REQUEST["facid"] . '&del_retencion=' . $obj->retenciones_id . '&tptre=' . $obj->impuesto . '&action=del_reten_man';
if((int)DOL_VERSION > 15){
$url .= "&token=".newToken();
}
print '';
print '';
print img_delete('Eliminar Retención de '.$obj->impuesto);
print ' ';
print ' ';
print ' ';
$i++;
}
print '
';
}
}
} else {
$sql = "SELECT * FROM " . MAIN_DB_PREFIX . "cfdimx_retenciones WHERE fk_facture = " . $_REQUEST["facid"];
$resql = $db->query($sql);
if ($resql) {
$cfdi_tott = $db->num_rows($resql);
$i = 0;
if ($cfdi_tott > 0) {
print '';
print '';
print 'Impuesto ';
print 'Importe ';
print ' ';
while ($i < $cfdi_tott) {
$obj = $db->fetch_object($resql);
print '';
print '' . $obj->impuesto . ' ';
print '';
print price($obj->importe, 0, '', 1, -1, -1, $object->multicurrency_code);
print ' ';
print ' ';
$i++;
}
print '
';
}else{
print '';
echo "No se registraron retenciones para esta factura";
print '
';
}
}
}
print ' ';
print ' ';
print '
';
print '
';
}
#Retenciones - Son como retenciones manuales (Fin)
#Retenciones locales - Se agregan desde la configuración del módulo en Dolibarr (Inicio)
if($conf->global->CFDIMX_FAC_RET_LOCALES == 1){
if ($object->statut != 0) {
print '
';
print '';
print '';
print ' ';
print ' ';
print 'Retenciones Locales ';
print ' ';
print ' ';
$sqm = "SELECT rowid,cod,descripcion,tasa FROM " . MAIN_DB_PREFIX . "cfdimx_config_retenciones_locales WHERE entity=" . $conf->entity;
$rqm = $db->query($sqm);
$nrm = $db->num_rows($rqm);
if ($nrm > 0) {
print '';
print '';
if ($cfdi_tot < 1) {
print '';
print ' ';
$sql = "SELECT * FROM " . MAIN_DB_PREFIX . "cfdimx_retenciones_locales WHERE fk_facture = " . $_REQUEST["facid"];
$resql = $db->query($sql);
if ($resql) {
$cfdi_t = $db->num_rows($resql);
$i = 0;
if ($cfdi_t > 0) {
print '';
print '';
print '';
print 'Código ';
print 'Tasa ';
print 'Importe ';
print 'Acción ';
print ' ';
print ' ';
print '';
while ($i < $cfdi_t) {
$obj = $db->fetch_object($resql);
print '';
print ''.$obj->codigo.' ';
print ''.$obj->tasa.'% ';
print '';
print price($obj->importe, 0, '', 1, -1, -1, $object->multicurrency_code);
print ' ';
$url = '?facid=' . $_REQUEST["facid"] . '&del_retencion_local=' . $obj->rowid;
if((int)DOL_VERSION > 15){
$url .= "&token=".newToken();
}
print '';
print ''.img_delete('Eliminar la Retención '.$obj->codigo) . ' ';
print ' ';
print ' ';
$i++;
}
print ' ';
print '
';
}
}
} else {
$sql = "SELECT * FROM " . MAIN_DB_PREFIX . "cfdimx_retenciones_locales WHERE fk_facture = " . $_REQUEST["facid"];
$resql = $db->query($sql);
if ($resql) {
$cfdi_t = $db->num_rows($resql);
$i = 0;
if ($cfdi_t > 0) {
print '';
print '';
print '';
print 'Código ';
print 'Tasa ';
print 'Importe ';
print ' ';
print ' ';
print '';
while ($i < $cfdi_t) {
$obj = $db->fetch_object($resql);
// print 'Impuesto: ' . $obj->codigo . ' ' . $obj->tasa . '% Importe: ' . number_format($obj->importe, 2) . " ";
print '';
print ''.$obj->codigo.' ';
print ''.$obj->tasa.'% ';
print '';
print price($obj->importe, 0, '', 1, -1, -1, $object->multicurrency_code);
print ' ';
print ' ';
$i++;
}
print ' ';
print '
';
} else {
// echo "No se registraron retenciones para esta factura";
print '';
echo "No se registraron retenciones locales para esta factura";
print '
';
}
}
}
print ' ';
print ' ';
}else{
if($uuid == ""){
print '';
print '';
print '';
print ' ';
print ' ';
}else{
print '';
print '';
print '';
print "No se registraron retenciones locales para esta Factura.";
print '
';
print ' ';
print ' ';
}
}
print '
';
print '
';
}
}
#Retenciones locales - Se agregan desde la configuración del módulo en Dolibarr (Fin)
# Inicio ISH
if ($object->statut != 0) {
$sql = 'SHOW COLUMNS FROM ' . MAIN_DB_PREFIX . 'product_extrafields LIKE "prodcfish"';
$resql = $db->query($sql);
$existe_ish = $db->num_rows($resql);
$sql = 'SHOW COLUMNS FROM ' . MAIN_DB_PREFIX . 'facturedet_extrafields LIKE "prodcfish"';
$resql = $db->query($sql);
$existe_ish_extra = $db->num_rows($resql);
$totalish = 0;
if ($existe_ish > 0) {
if (isset($conf->global->MAIN_MODULE_MULTICURRENCY)){
$sql = "SELECT a.fk_product,a.multicurrency_total_ht as total_ht,b.prodcfish,((b.prodcfish/100)*a.multicurrency_total_ht) as impish,c.ref,c.label FROM " . MAIN_DB_PREFIX . "facturedet a, (SELECT fk_object,prodcfish FROM " . MAIN_DB_PREFIX . "product_extrafields WHERE prodcfish!=0 AND prodcfish IS NOT NULL) b, " . MAIN_DB_PREFIX . "product c WHERE a.fk_facture=" . $id . " AND a.fk_product =b.fk_object AND a.fk_product=c.rowid ORDER BY a.rowid";
}else {
$sql = "SELECT a.fk_product,a.total_ht,b.prodcfish,((b.prodcfish/100)*a.total_ht) as impish,c.ref,c.label FROM " . MAIN_DB_PREFIX . "facturedet a,(SELECT fk_object,prodcfish FROM " . MAIN_DB_PREFIX . "product_extrafields WHERE prodcfish!=0 AND prodcfish IS NOT NULL) b," . MAIN_DB_PREFIX . "product c WHERE a.fk_facture=" . $object->id . " AND a.fk_product =b.fk_object AND a.fk_product=c.rowid ORDER BY a.rowid";
}
// print $sql;
$ass = $db->query($sql);
$asf = $db->num_rows($ass);
if ($asf > 0) {
$currency = $langs->trans('Currency' . (isset($divisa) ? $divisa : $conf->currency));
print '
';
print '';
print '';
print '';
print ' ';
print ' ';
print 'Impuesto ISH ';
print ' ';
print ' ';
print ' ';
print '';
print 'Producto ';
print 'Importe Sin IVA ';
print 'Porcentaje ISH ';
print 'ISH ';
print ' ';
// $totalish = 0;
while ($asd = $db->fetch_object($ass)) {
print '';
print '' . $asd->ref . '-' . $asd->label . ' ';
print '';
print price($asd->total_ht, 0, '', 1, -1, -1, $object->multicurrency_code);
print ' ';
print '' . $asd->prodcfish . ' % ';
print '';
print price($asd->impish, 0, '', 1, -1, -1, $object->multicurrency_code);
print ' ';
print ' ';
$totalish = $totalish + $asd->impish;
}
if ($totalish > 0) {
$object->total_ttc = $object->total_ttc + $totalish;
$object->total_ttc = str_replace(",", "", number_format($object->total_ttc, 2));
}
if($existe_ish_extra == 0){
print '';
print '';
print 'Total Impuesto ISH: ';
print ' ';
print '';
print price($totalish, 0, '', 1, -1, -1, $object->multicurrency_code);
print ' ';
print ' ';
print '
';
}
}
}
if($existe_ish_extra > 0){
if (isset($conf->global->MAIN_MODULE_MULTICURRENCY)){
$sql = "
SELECT
a.fk_product,
a.multicurrency_total_ht AS total_ht,
b.prodcfish,
(
(b.prodcfish / 100) * a.multicurrency_total_ht
) AS impish,
a.label,
a.description
FROM
".MAIN_DB_PREFIX."facturedet a,
(
SELECT
fk_object,
prodcfish
FROM
".MAIN_DB_PREFIX."facturedet_extrafields
WHERE
prodcfish != 0 AND prodcfish IS NOT NULL
) b
WHERE
a.fk_facture = ".$object->id." AND a.rowid = b.fk_object
ORDER BY
a.rowid;
";
}else {
$sql = "
SELECT
a.fk_product,
a.total_ht,
b.prodcfish,
(
(b.prodcfish / 100) * a.total_ht
) AS impish,
a.label,
a.description
FROM
".MAIN_DB_PREFIX."facturedet a,
(
SELECT
fk_object,
prodcfish
FROM
".MAIN_DB_PREFIX."facturedet_extrafields
WHERE
prodcfish != 0 AND prodcfish IS NOT NULL
) b
WHERE
a.fk_facture = ".$object->id." AND a.rowid = b.fk_object
ORDER BY
a.rowid
";
}
// print $sql;
$ass = $db->query($sql);
$asf = $db->num_rows($ass);
if ($asf > 0) {
$currency = $langs->trans('Currency' . (isset($divisa) ? $divisa : $conf->currency));
if($totalish == 0){
print '
';
print '';
print '';
print '';
print ' ';
print ' ';
print 'Impuesto ISH ';
print ' ';
print ' ';
print ' ';
print '';
print 'Producto ';
print 'Importe Sin IVA ';
print 'Porcentaje ISH ';
print 'ISH ';
print ' ';
}
while ($asd = $db->fetch_object($ass)) {
print '';
print '' . $asd->description . ' ';
print '';
print price($asd->total_ht, 0, '', 1, -1, -1, $object->multicurrency_code);
print ' ';
print '' . $asd->prodcfish . ' % ';
print '';
print price($asd->impish, 0, '', 1, -1, -1, $object->multicurrency_code);
print ' ';
print ' ';
$totalish = $totalish + $asd->impish;
}
if ($totalish > 0) {
$object->total_ttc = $object->total_ttc + $totalish;
$object->total_ttc = str_replace(",", "", number_format($object->total_ttc, 2));
print '';
print '';
print 'Total Impuesto ISH: ';
print ' ';
print '';
print price($totalish, 0, '', 1, -1, -1, $object->multicurrency_code);
print ' ';
print ' ';
}
print '
';
}
}
print '
';
}
# Fin ISH
print '
'; //Fiche right
print '
'; //Fiche center
print '
';
dol_fiche_end();
if ($action == 'presend' || $action == 'send') {
include 'mail_form.php';
}
if ($action != 'presend' && $action != 'send'){
#Actions buttons
print '';
if ($object->statut == 1 || $object->statut == 2) {
if ($user->rights->cfdimx->create == 1 && $uuid == "") {
$filename2=DOL_DOCUMENT_ROOT.'/cfdimx/permisopdf.php';
if(file_exists($filename2) == true){
print '
';
}
print '
';
}
// Send by mail
if ($user->rights->cfdimx->send_mailsend && $uuid != "") {
print '
';
}
if ($user->rights->cfdimx->create == 1) {
$sql = 'SELECT * FROM '.MAIN_DB_PREFIX.'cfdimx WHERE fk_facture='.$object->id.' AND entity_id='. $conf->entity;
//echo $sql;
$resql = $db->query($sql);
//Si ya existe el registro en la BD de la factura seleccionada se puede regenerar el PDF
if ($db->num_rows($resql) > 0) {
print '
';
}
}
if ($user->rights->cfdimx->delete == 1) {
if($status_conf==1){
if( $cfdi_tot>0 ){
if($cfdi_cancela != 1) {
//Hay que agregar estos en cancelar
print '
';
}
}
}
$sql_solicitud_canceacion = "";
$sql_solicitud_canceacion .= "SELECT count(*) AS solicitudes FROM ".MAIN_DB_PREFIX."cfdimx_solicitud_cancelacion";
$sql_solicitud_canceacion .= " WHERE fk_facture = ".$object->id;
$res_solicitud_canceacion = $db->query($sql_solicitud_canceacion);
$num_solicitudes = 0;
if($res_solicitud_canceacion){
$obj_solicitud = $db->fetch_object($res_solicitud_canceacion);
$num_solicitudes = $obj_solicitud->solicitudes;
}
if($num_solicitudes > 0){
print '
';
}
}
if ($status_conf == 1) {
if ($cfdi_tot < 1) {
if ($soc_rfc != "") {
if ($user->rights->cfdimx->create == 1) {
if ($object->getLibStatut(1, $totalpaye) == 'Borrador' || $objFacturaCFDI->getLinkGeneraCFDI($status, $id) == 'Fuera de fecha de timbrado') {
if ($object->getLibStatut(1, $totalpaye) == 'Borrador') {
print '
';
print '
';
print 'No puede timbrar un borrador. ';
print '
';
print '
';
}
if ($objFacturaCFDI->getLinkGeneraCFDI($status, $id) == 'Fuera de fecha de timbrado') {
print '
';
print '
';
print 'Fuera de fecha de timbrado. ';
print '
';
print '
';
}
}else{
if ($modo_timbrado == 1){
if($folios_disponibles > 0) {
print '
';
}else{
print '
';
print '
';
print '
';
print 'No cuenta con Folios para realizar Facturas Electrónicas. ';
print '
';
print '
';
}
}else{
if ($modo_timbrado == 2) {
print '
';
}
}
}
}
}else{
$msj_validacion = "";
if(strcmp($conf->global->CFDIMX_VERSION_SAT, "4.0") == 0){
$msj_validacion = '
El Cliente (Receptor) no cuenta con un RFC asignado da Click aquí para completar. ';
}else{
$msj_validacion = '
El Cliente (Receptor) no cuenta con un RFC asignado da Click aquí para completar. ';
}
print '
';
print '
';
print '
';
print $msj_validacion;
print '
';
print '
';
}
}
}else {
$msj_validacion = '
Existen errores en la configuración';
$msj_validacion .= ' Click aquí para completar. ';
print '
';
print '
';
print '
';
print $msj_validacion;
print '
';
print '
';
}
}else {
if ($object->statut == 0) {
print '
';
print '
';
print '
';
print 'No es posible timbrar un borrador. ';
print '
';
print '
';
}
if ($object->statut == 3) {
print '
';
print '
';
print 'La factura esta abandonada, no es posible realizar acciones. ';
print '
';
print '
';
}
}
print '
';
print ''; //fichecenter 2 inicio
#Listado de archivos#
$filedir=$conf->facture->dir_output.'/'.$object->ref.'/';
$file_list=dol_dir_list($filedir,'files',0,'','\.meta$','date',SORT_DESC);
// Loop on each file found
if (is_array($file_list))
{
$out_files = "";
foreach($file_list as $file)
{
$aux_ext = explode(".", $file['name']);
$ext = $aux_ext[1];
if (in_array($ext, array("pdf"))){
$out_lupa = '
';
}else {
$out_lupa = "";
}
$out_files.= '
';
$out_files.='
'.$file['name'].'
'.$out_lupa.'
'.filesize($file['fullname']).' Bytes
'.dol_print_date($file['date'], "%H:%M %d/%m/%Y").'
';
$out_files.= ' ';
}
}
if($out_files != ""){
print '
';
print '
';
print '
';
print '
';
// print '
';
// print '
';
// print '';
// print '';
// print '';
// print 'Eventos CFDIMX sobre la Factura
';
// print ' ';
// print ' ';
// print ' ';
// print '
';
// print '
';
// print '
';
// print '
';
// print '
';
// include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php';
// $formactions = new FormActions($db);
// $somethingshown = $formactions->showactions($object, 'cfdimx', $soc_id, 1);
// print '
';
// print '
';
}
// print '
';
print '
'; //fichecenter 2 fin
}
}else {
dol_print_error($db, $object->error);
}
}
llxFooter();
$db->close();
?>