Merge branch 'main' of https://github.com/AduanaSoft/IMPORTADORES
This commit is contained in:
363
app/controllers/productos_frecuentes.php
Normal file
363
app/controllers/productos_frecuentes.php
Normal file
@@ -0,0 +1,363 @@
|
||||
<?php
|
||||
// app/controllers/productos_frecuentes.php
|
||||
|
||||
|
||||
|
||||
require_once __DIR__ . '/../helpers/session.php';
|
||||
require_once __DIR__ . '/../../config/database.php';
|
||||
// 1) Composer autoload (phpdotenv y demás libs)
|
||||
require_once __DIR__ . '/../../vendor/autoload.php';
|
||||
// 2) Carga nuestro helper de entorno y dispara la carga de .env
|
||||
require_once __DIR__ . '/../helpers/env.php';
|
||||
loadEnv();
|
||||
|
||||
/** GET /IMPORTADORES/productos_frecuentes
|
||||
* Muestra el listado **/
|
||||
function index()
|
||||
{
|
||||
lista();
|
||||
}
|
||||
|
||||
function ajax_paises()
|
||||
{
|
||||
|
||||
|
||||
// Sólo importadores pueden usarlo
|
||||
if (empty($_SESSION['usuario_id']) || $_SESSION['tipo_usuario'] !== 'importador') {
|
||||
http_response_code(401);
|
||||
echo json_encode(['results' => []]);
|
||||
exit;
|
||||
}
|
||||
|
||||
$conn = getConnection();
|
||||
$sql = "SELECT id_pais AS id, nombre AS text
|
||||
FROM dbo.paises
|
||||
ORDER BY nombre";
|
||||
$stmt = sqlsrv_query($conn, $sql);
|
||||
|
||||
$out = ['results' => []];
|
||||
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
|
||||
$out['results'][] = [
|
||||
'id' => $row['id'],
|
||||
'text' => $row['text'],
|
||||
];
|
||||
}
|
||||
|
||||
echo json_encode($out);
|
||||
exit;
|
||||
}
|
||||
|
||||
|
||||
|
||||
function ajax_proveedores()
|
||||
{
|
||||
// 1) Asegura que la respuesta sea JSON
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
|
||||
// 2) Obtén o renueva tu token (usa tu función existente)
|
||||
$token = getApiToken();
|
||||
if (!$token) {
|
||||
echo json_encode(['results' => []]);
|
||||
return;
|
||||
}
|
||||
|
||||
// 3) Llama al endpoint de la API de proveedores
|
||||
$apiBase = rtrim($_ENV['API_URL'] ?? '', '/');
|
||||
$url = $apiBase . '/proveedores';
|
||||
|
||||
$ch = curl_init($url);
|
||||
curl_setopt_array($ch, [
|
||||
CURLOPT_HTTPHEADER => ["Authorization: $token", 'Accept: application/json'],
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_TIMEOUT => 5,
|
||||
]);
|
||||
$resp = curl_exec($ch);
|
||||
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
curl_close($ch);
|
||||
|
||||
// 4) Parsear y transformar al formato { results: [ {id,text}, … ] }
|
||||
$out = ['results' => []];
|
||||
if ($status === 200 && ($json = json_decode($resp, true)) && is_array($json)) {
|
||||
foreach ($json as $p) {
|
||||
$clave = $p['Clave'] ?? '';
|
||||
$nombre = $p['Nombre'] ?? '';
|
||||
$out['results'][] = [
|
||||
'id' => $clave,
|
||||
'text' => "[$clave] - $nombre"
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
// 5) Devolver JSON
|
||||
echo json_encode($out);
|
||||
exit;
|
||||
}
|
||||
|
||||
|
||||
function lista()
|
||||
{
|
||||
|
||||
if (empty($_SESSION['usuario_id'])) {
|
||||
header('Location: /IMPORTADORES/login');
|
||||
exit;
|
||||
}
|
||||
include __DIR__ . '/../../views/productos_frecuentes/lista.php';
|
||||
}
|
||||
|
||||
/** GET /IMPORTADORES/productos_frecuentes/alta
|
||||
* Muestra el formulario de creación **/
|
||||
function alta()
|
||||
{
|
||||
|
||||
if (empty($_SESSION['usuario_id'])) {
|
||||
header('Location: /IMPORTADORES/login');
|
||||
exit;
|
||||
}
|
||||
include __DIR__ . '/../../views/productos_frecuentes/alta.php';
|
||||
}
|
||||
|
||||
/** POST /IMPORTADORES/productos_frecuentes/guardar
|
||||
* Procesa alta de producto frecuente **/
|
||||
function guardar()
|
||||
{
|
||||
|
||||
if (empty($_SESSION['usuario_id'])) {
|
||||
header('Location: /IMPORTADORES/login');
|
||||
exit;
|
||||
}
|
||||
|
||||
$conn = getConnection();
|
||||
|
||||
// Recoger y sanear
|
||||
$sinonimo = trim($_POST['sinonimo'] ?? '');
|
||||
$fraccion = trim($_POST['fraccion'] ?? '');
|
||||
$nico = trim($_POST['nico'] ?? '');
|
||||
$numero_parte = trim($_POST['numero_parte'] ?? null);
|
||||
$descripcion = trim($_POST['descripcion'] ?? null);
|
||||
$umc_id = intval($_POST['umc_id'] ?? 0);
|
||||
$pais_origen_destino = trim($_POST['pais_origen_destino'] ?? null);
|
||||
$pais_comprador_vendedor = trim($_POST['pais_comprador_vendedor'] ?? null);
|
||||
$uso_mercancia = trim($_POST['uso_mercancia'] ?? null);
|
||||
$estado_mercancia = trim($_POST['estado_mercancia'] ?? null);
|
||||
$vinculacion = trim($_POST['vinculacion'] ?? null);
|
||||
$observaciones = trim($_POST['observaciones'] ?? null);
|
||||
$preferencia = trim($_POST['preferencia'] ?? null);
|
||||
$criterio_preferencia = trim($_POST['criterio_preferencia'] ?? null);
|
||||
$uso_producto = trim($_POST['uso_producto'] ?? null);
|
||||
$descripcion_producto = trim($_POST['descripcion_producto'] ?? null);
|
||||
$certificado_origen = isset($_POST['certificado_origen']) ? 1 : 0;
|
||||
$tipo_mercancia = trim($_POST['tipo_mercancia'] ?? null);
|
||||
$documento_en_original = isset($_POST['documento_en_original']) ? 1 : 0;
|
||||
$proveedor = trim($_POST['proveedor'] ?? null);
|
||||
$id_importador = intval($_SESSION['usuario_id']);
|
||||
$status = 1;
|
||||
$frecuencia_uso = intval($_POST['frecuencia_uso'] ?? 1);
|
||||
|
||||
// Validación mínima
|
||||
if ($sinonimo === '' || $fraccion === '' || $nico === '' || $umc_id <= 0) {
|
||||
$_SESSION['flash_error'] = 'Sinónimo, Fracción, NICO y Unidad de Medida son obligatorios.';
|
||||
header('Location: /IMPORTADORES/productos_frecuentes/alta');
|
||||
exit;
|
||||
}
|
||||
|
||||
// INSERT
|
||||
$sql = "
|
||||
INSERT INTO dbo.productos_frecuentes (
|
||||
sinonimo, fraccion, nico, numero_parte,
|
||||
descripcion, umc_id,
|
||||
pais_origen_destino, pais_comprador_vendedor,
|
||||
uso_mercancia, estado_mercancia, vinculacion,
|
||||
observaciones, preferencia, criterio_preferencia,
|
||||
uso_producto, descripcion_producto,
|
||||
certificado_origen, tipo_mercancia,
|
||||
documento_en_original, proveedor,
|
||||
id_importador, fecha_alta, status, frecuencia_uso
|
||||
) VALUES (
|
||||
?,?,?,?,
|
||||
?,?,
|
||||
?,?,
|
||||
?,?,?,
|
||||
?,?,?,
|
||||
?,?,
|
||||
?,?,
|
||||
?,?,
|
||||
?,GETDATE(),?,?
|
||||
)
|
||||
";
|
||||
$params = [
|
||||
$sinonimo, $fraccion, $nico, $numero_parte,
|
||||
$descripcion, $umc_id,
|
||||
$pais_origen_destino, $pais_comprador_vendedor,
|
||||
$uso_mercancia, $estado_mercancia, $vinculacion,
|
||||
$observaciones, $preferencia, $criterio_preferencia,
|
||||
$uso_producto, $descripcion_producto,
|
||||
$certificado_origen, $tipo_mercancia,
|
||||
$documento_en_original, $proveedor,
|
||||
$id_importador, $status, $frecuencia_uso
|
||||
];
|
||||
$stmt = sqlsrv_query($conn, $sql, $params);
|
||||
|
||||
if ($stmt === false) {
|
||||
$_SESSION['flash_error'] = 'Error al guardar el producto frecuente.';
|
||||
header('Location: /IMPORTADORES/productos_frecuentes/alta');
|
||||
exit;
|
||||
}
|
||||
|
||||
$_SESSION['flash_success'] = 'Producto frecuente registrado correctamente.';
|
||||
header('Location: /IMPORTADORES/productos_frecuentes');
|
||||
exit;
|
||||
}
|
||||
|
||||
/** GET /IMPORTADORES/productos_frecuentes/editar?id=XX
|
||||
* Muestra el formulario de edición **/
|
||||
function editar()
|
||||
{
|
||||
|
||||
if (empty($_SESSION['usuario_id'])) {
|
||||
header('Location: /IMPORTADORES/login');
|
||||
exit;
|
||||
}
|
||||
|
||||
$id = intval($_GET['id'] ?? 0);
|
||||
if ($id <= 0) {
|
||||
header('Location: /IMPORTADORES/productos_frecuentes');
|
||||
exit;
|
||||
}
|
||||
|
||||
$conn = getConnection();
|
||||
$sql = "SELECT * FROM dbo.productos_frecuentes WHERE id_producto_frecuente = ?";
|
||||
$stmt = sqlsrv_query($conn, $sql, [$id]);
|
||||
if ($stmt === false || ($producto = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) === null) {
|
||||
$_SESSION['flash_error'] = 'Producto frecuente no encontrado.';
|
||||
header('Location: /IMPORTADORES/productos_frecuentes');
|
||||
exit;
|
||||
}
|
||||
|
||||
include __DIR__ . '/../../views/productos_frecuentes/editar.php';
|
||||
}
|
||||
|
||||
/** POST /IMPORTADORES/productos_frecuentes/actualizar
|
||||
* Procesa la actualización **/
|
||||
function actualizar()
|
||||
{
|
||||
session_start();
|
||||
if (empty($_SESSION['usuario_id'])) {
|
||||
header('Location: /IMPORTADORES/login');
|
||||
exit;
|
||||
}
|
||||
|
||||
$id = intval($_POST['id_producto_frecuente'] ?? 0);
|
||||
$sinonimo = trim($_POST['sinonimo'] ?? '');
|
||||
// ... (resto de campos idénticos a guardar)
|
||||
// Validaciones similares...
|
||||
// UPDATE ...
|
||||
$conn = getConnection();
|
||||
$sql = "
|
||||
UPDATE dbo.productos_frecuentes SET
|
||||
sinonimo = ?, fraccion = ?, nico = ?, numero_parte = ?,
|
||||
descripcion = ?, umc_id = ?,
|
||||
pais_origen_destino = ?, pais_comprador_vendedor = ?,
|
||||
uso_mercancia = ?, estado_mercancia = ?, vinculacion = ?,
|
||||
observaciones = ?, preferencia = ?, criterio_preferencia = ?,
|
||||
uso_producto = ?, descripcion_producto = ?,
|
||||
certificado_origen = ?, tipo_mercancia = ?,
|
||||
documento_en_original = ?, proveedor = ?
|
||||
WHERE id_producto_frecuente = ?
|
||||
";
|
||||
$params = [
|
||||
$sinonimo, $fraccion, $nico, $numero_parte,
|
||||
$descripcion, $umc_id,
|
||||
$pais_origen_destino, $pais_comprador_vendedor,
|
||||
$uso_mercancia, $estado_mercancia, $vinculacion,
|
||||
$observaciones, $preferencia, $criterio_preferencia,
|
||||
$uso_producto, $descripcion_producto,
|
||||
$certificado_origen, $tipo_mercancia,
|
||||
$documento_en_original, $proveedor,
|
||||
$id
|
||||
];
|
||||
$stmt = sqlsrv_query($conn, $sql, $params);
|
||||
|
||||
if ($stmt === false) {
|
||||
$_SESSION['flash_error'] = 'Error al actualizar el producto frecuente.';
|
||||
} else {
|
||||
$_SESSION['flash_success'] = 'Producto frecuente actualizado correctamente.';
|
||||
}
|
||||
header('Location: /IMPORTADORES/productos_frecuentes');
|
||||
exit;
|
||||
}
|
||||
|
||||
/** GET /IMPORTADORES/productos_frecuentes/importacion_csv
|
||||
* Muestra formulario de importación masiva **/
|
||||
function importacion_csv()
|
||||
{
|
||||
session_start();
|
||||
if (empty($_SESSION['usuario_id'])) {
|
||||
header('Location: /IMPORTADORES/login');
|
||||
exit;
|
||||
}
|
||||
include __DIR__ . '/../../views/productos_frecuentes/importacion_csv.php';
|
||||
}
|
||||
|
||||
function ajax_unidades()
|
||||
{
|
||||
|
||||
|
||||
if (empty($_SESSION['usuario_id']) || $_SESSION['tipo_usuario'] !== 'importador') {
|
||||
http_response_code(401);
|
||||
echo json_encode(['results' => []]);
|
||||
exit;
|
||||
}
|
||||
|
||||
$conn = getConnection();
|
||||
$sql = "SELECT id, descripcion FROM dbo.unidades_medida_apendice7 ORDER BY descripcion";
|
||||
$stmt = sqlsrv_query($conn, $sql);
|
||||
|
||||
$out = ['results' => []];
|
||||
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
|
||||
$out['results'][] = [
|
||||
'id' => $row['id'],
|
||||
'text' => $row['descripcion']
|
||||
];
|
||||
}
|
||||
|
||||
echo json_encode($out);
|
||||
exit;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/** POST /IMPORTADORES/productos_frecuentes/procesar_csv
|
||||
* Procesa el upload y la inserción de CSV **/
|
||||
function procesar_csv()
|
||||
{
|
||||
session_start();
|
||||
if (empty($_SESSION['usuario_id'])) {
|
||||
header('Location: /IMPORTADORES/login');
|
||||
exit;
|
||||
}
|
||||
|
||||
if (empty($_FILES['csv_file']['tmp_name'])) {
|
||||
$_SESSION['flash_error'] = 'No se subió ningún archivo.';
|
||||
header('Location: /IMPORTADORES/productos_frecuentes/importacion_csv');
|
||||
exit;
|
||||
}
|
||||
|
||||
$file = fopen($_FILES['csv_file']['tmp_name'], 'r');
|
||||
$conn = getConnection();
|
||||
$row = 0;
|
||||
while (($data = fgetcsv($file, 0, ',')) !== false) {
|
||||
$row++;
|
||||
if ($row === 1) continue; // suponemos encabezado
|
||||
// mapear columnas CSV a variables…
|
||||
list(
|
||||
$sinonimo, $fraccion, $nico, /* etc. */
|
||||
) = $data;
|
||||
// INSERT similar a guardar()
|
||||
// …
|
||||
}
|
||||
fclose($file);
|
||||
|
||||
$_SESSION['flash_success'] = 'Importación completada.';
|
||||
header('Location: /IMPORTADORES/productos_frecuentes');
|
||||
exit;
|
||||
}
|
||||
Reference in New Issue
Block a user