Skip to content

Commit 7be9683

Browse files
committed
Merge branch 'produccion' of https://github.com/PiruloDev/Proyecto into produccion
2 parents 0d33e4e + 0e615b1 commit 7be9683

9 files changed

Lines changed: 539 additions & 138 deletions

File tree

Frontend/app/Http/Controllers/Productos/ProductoController.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -203,4 +203,18 @@ public function destroy($id)
203203
->with('error', 'Error de conexión: ' . $e->getMessage());
204204
}
205205
}
206+
207+
// Añade esto a ProductoController.php
208+
public function getProductosJson()
209+
{
210+
try {
211+
$response = Http::timeout(10)->get($this->apiUrl);
212+
if ($response->successful()) {
213+
return response()->json($response->json());
214+
}
215+
return response()->json(['error' => 'API no disponible'], 500);
216+
} catch (\Exception $e) {
217+
return response()->json(['error' => $e->getMessage()], 500);
218+
}
219+
}
206220
}

Frontend/app/Services/Pedidos/EstadoPedidoService.php

Lines changed: 58 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -7,82 +7,98 @@
77

88
class EstadoPedidoService
99
{
10-
// Asumimos que tu API de Java usa el endpoint /estadosPedidos
11-
protected $baseUrl = 'http://localhost:8080/estadosPedidos';
10+
protected $baseUrl;
11+
12+
public function __construct()
13+
{
14+
// Usamos la IP elástica configurada en el .env, o la IP directa si no está definida
15+
$apiHost = env('API_BASE_URL', 'http://32.193.167.191:8080');
16+
$this->baseUrl = "{$apiHost}/estadosPedidos";
17+
}
1218

1319
public function obtenerEstados()
1420
{
15-
$response = Http::get($this->baseUrl);
21+
try {
22+
$response = Http::get($this->baseUrl);
1623

17-
if ($response->successful()) {
18-
return $response->json();
19-
}
24+
if ($response->successful()) {
25+
return $response->json();
26+
}
2027

21-
// Si la API devuelve un error, lanzamos una excepción
22-
throw new Exception("Error al obtener estados: " . $response->body());
28+
throw new Exception("Error al obtener estados: " . $response->body());
29+
} catch (Exception $e) {
30+
throw new Exception("No se pudo conectar con la API de estados: " . $e->getMessage());
31+
}
2332
}
2433

2534
/**
2635
* Solución de emergencia para el error 405 Method Not Allowed en Java.
27-
* En lugar de llamar a /estadosPedidos/{id} (que falla),
28-
* llama a /estadosPedidos (lista completa) y busca el ID en PHP.
2936
*/
3037
public function obtenerEstadoPorId($id)
3138
{
32-
// Paso 1: Llamamos al endpoint que sabemos que funciona (la lista completa)
33-
$response = Http::get($this->baseUrl);
39+
try {
40+
$response = Http::get($this->baseUrl);
3441

35-
if ($response->successful()) {
36-
$todosLosEstados = $response->json();
42+
if ($response->successful()) {
43+
$todosLosEstados = $response->json();
3744

38-
// Paso 2: Buscamos el estado por ID dentro de la lista en Laravel
39-
foreach ($todosLosEstados as $estado) {
40-
// Buscamos el estado cuyo 'id_ESTADO_PEDIDO' coincide
41-
if (isset($estado['id_ESTADO_PEDIDO']) && $estado['id_ESTADO_PEDIDO'] == $id) {
42-
return $estado; // Devolvemos solo el estado encontrado
45+
foreach ($todosLosEstados as $estado) {
46+
if (isset($estado['id_ESTADO_PEDIDO']) && $estado['id_ESTADO_PEDIDO'] == $id) {
47+
return $estado;
48+
}
4349
}
50+
51+
throw new Exception("Estado de pedido ID {$id} no encontrado en la lista.");
4452
}
45-
46-
// Si no lo encontramos después de recorrer la lista
47-
throw new Exception("Estado de pedido ID {$id} no encontrado en la lista.");
48-
}
4953

50-
// Si la llamada a la lista falló por completo
51-
throw new Exception("Error al obtener lista de estados: " . $response->body());
54+
throw new Exception("Error al obtener lista de estados: " . $response->body());
55+
} catch (Exception $e) {
56+
throw new Exception($e->getMessage());
57+
}
5258
}
5359

5460
public function crearEstado(array $data)
5561
{
56-
// Enviamos los datos mapeados (NOMBRE_ESTADO)
57-
$response = Http::post($this->baseUrl, $data);
62+
try {
63+
$response = Http::post($this->baseUrl, $data);
5864

59-
if ($response->successful()) {
60-
return $response->json();
61-
}
65+
if ($response->successful()) {
66+
return $response->json();
67+
}
6268

63-
throw new Exception("Error al crear estado: " . $response->body());
69+
throw new Exception("Error al crear estado: " . $response->body());
70+
} catch (Exception $e) {
71+
throw new Exception("Error de conexión al crear estado: " . $e->getMessage());
72+
}
6473
}
6574

6675
public function actualizarEstado($id, array $data)
6776
{
68-
// Enviamos los datos mapeados (NOMBRE_ESTADO)
69-
$response = Http::put("{$this->baseUrl}/{$id}", $data);
77+
try {
78+
$response = Http::put("{$this->baseUrl}/{$id}", $data);
7079

71-
if ($response->successful()) {
72-
return $response->json();
73-
}
80+
if ($response->successful()) {
81+
return $response->json();
82+
}
7483

75-
throw new Exception("Error al actualizar estado: " . $response->body());
84+
throw new Exception("Error al actualizar estado: " . $response->body());
85+
} catch (Exception $e) {
86+
throw new Exception("Error de conexión al actualizar estado: " . $e->getMessage());
87+
}
7688
}
7789

7890
public function eliminarEstado($id)
7991
{
80-
$response = Http::delete("{$this->baseUrl}/{$id}");
92+
try {
93+
$response = Http::delete("{$this->baseUrl}/{$id}");
8194

82-
if ($response->successful()) {
83-
return true;
84-
}
95+
if ($response->successful()) {
96+
return true;
97+
}
8598

86-
throw new Exception("Error al eliminar estado: " . $response->body());
99+
throw new Exception("Error al eliminar estado: " . $response->body());
100+
} catch (Exception $e) {
101+
throw new Exception("Error de conexión al eliminar estado: " . $e->getMessage());
102+
}
87103
}
88104
}

Frontend/app/Services/Pedidos/PedidosApiService.php

Lines changed: 78 additions & 82 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,19 @@
77

88
class PedidosApiService
99
{
10-
protected $baseUrl = 'http://localhost:8080/pedidos';
11-
protected $productosUrl = 'http://localhost:8080/productos';
10+
protected $baseUrl;
11+
protected $productosUrl;
12+
protected $detallesUrl;
13+
14+
public function __construct()
15+
{
16+
// Usamos la variable de entorno, si no existe, usa la IP de tu instancia
17+
$apiHost = env('API_BASE_URL', 'http://32.193.167.191:8080');
18+
19+
$this->baseUrl = "{$apiHost}/pedidos";
20+
$this->productosUrl = "{$apiHost}/productos";
21+
$this->detallesUrl = "{$apiHost}/detalles-pedidos";
22+
}
1223

1324
/* =========================
1425
PRODUCTOS
@@ -19,15 +30,12 @@ public function obtenerProductos()
1930
try {
2031
$response = Http::get($this->productosUrl);
2132
$response->throw();
22-
2333
$productosResponse = $response->json();
2434

2535
if (isset($productosResponse['content']) && is_array($productosResponse['content'])) {
2636
return $productosResponse['content'];
2737
}
28-
2938
return $productosResponse;
30-
3139
} catch (Exception $e) {
3240
throw new Exception("Error al obtener productos de la API.");
3341
}
@@ -68,27 +76,22 @@ public function crearPedido($data)
6876
}
6977
}
7078

71-
public function actualizarPedido($id, $data)
72-
{
73-
try {
74-
// Agregamos logging para ver qué estamos enviando exactamente a Java
75-
\Log::info("Enviando actualización a API Java para Pedido #{$id}:", $data);
76-
77-
$response = Http::put("{$this->baseUrl}/{$id}", $data);
78-
79-
if ($response->failed()) {
80-
// Esto imprimirá en storage/logs/laravel.log el error real de Java
81-
\Log::error("Error desde API Java (Pedido #{$id}): " . $response->body());
82-
83-
$mensajeError = $response->json('message') ?? "Error servidor Java: " . $response->status();
84-
throw new Exception($mensajeError);
85-
}
79+
public function actualizarPedido($id, $data)
80+
{
81+
try {
82+
\Log::info("Enviando actualización a API Java para Pedido #{$id}:", $data);
83+
$response = Http::put("{$this->baseUrl}/{$id}", $data);
8684

87-
return $response->json();
88-
} catch (Exception $e) {
89-
throw new Exception($e->getMessage());
85+
if ($response->failed()) {
86+
\Log::error("Error desde API Java (Pedido #{$id}): " . $response->body());
87+
$mensajeError = $response->json('message') ?? "Error servidor Java: " . $response->status();
88+
throw new Exception($mensajeError);
89+
}
90+
return $response->json();
91+
} catch (Exception $e) {
92+
throw new Exception($e->getMessage());
93+
}
9094
}
91-
}
9295

9396
public function eliminarPedido($id)
9497
{
@@ -100,24 +103,25 @@ public function eliminarPedido($id)
100103
}
101104

102105
/* =========================
103-
CHECKOUT (CLAVE)
106+
CHECKOUT
104107
========================= */
105108

106109
public function crearPedidoCheckout(array $payload)
107-
{
108-
try {
109-
return Http::withHeaders([
110-
'Content-Type' => 'application/json',
111-
'Accept' => 'application/json',
112-
])
113-
->asJson()
114-
->post($this->baseUrl, $payload)
115-
->throw()
116-
->json();
117-
} catch (\Exception $e) {
118-
throw new Exception("Error API: " . ($e->response?->body() ?? $e->getMessage()));
110+
{
111+
try {
112+
return Http::withHeaders([
113+
'Content-Type' => 'application/json',
114+
'Accept' => 'application/json',
115+
])
116+
->asJson()
117+
->post($this->baseUrl, $payload)
118+
->throw()
119+
->json();
120+
} catch (\Exception $e) {
121+
throw new Exception("Error API: " . ($e->response?->body() ?? $e->getMessage()));
122+
}
119123
}
120-
}
124+
121125
/* =========================
122126
DASHBOARD CLIENTE
123127
========================= */
@@ -133,55 +137,47 @@ public function obtenerPedidosPorCliente($clienteId)
133137
}
134138
}
135139

136-
protected $detallesUrl = 'http://localhost:8080/detalles-pedidos'; // URL de tu nuevo Controller en Java
137-
138-
public function obtenerTodosLosDetalles()
139-
{
140-
try {
141-
$data = Http::get($this->detallesUrl)->throw()->json();
142-
\Log::info("Detalles desde API Java:", $data); // Esto te dirá exactamente cómo se llaman las llaves
143-
return $data;
144-
} catch (Exception $e) { }
145-
}
146-
147-
public function obtenerTodosLosPedidos()
148-
{
149-
try {
150-
// Usamos la baseUrl (http://localhost:8080/pedidos) que ya tienes definida
151-
return Http::get($this->baseUrl)->throw()->json();
152-
} catch (Exception $e) {
153-
throw new Exception("Error al obtener el listado global de pedidos de la API.");
140+
public function obtenerTodosLosDetalles()
141+
{
142+
try {
143+
$data = Http::get($this->detallesUrl)->throw()->json();
144+
return $data;
145+
} catch (Exception $e) {
146+
return [];
147+
}
154148
}
155-
}
156149

157-
/* =========================
158-
CATÁLOGOS PARA MODALES
159-
========================= */
150+
/* =========================
151+
CATÁLOGOS (CORREGIDOS)
152+
========================= */
160153

161-
public function obtenerEstados()
162-
{
163-
try {
164-
return Http::get("http://localhost:8080/estadosPedidos")->throw()->json();
165-
} catch (Exception $e) {
166-
return []; // Retorna array vacío si falla
154+
public function obtenerEstados()
155+
{
156+
$apiHost = env('API_BASE_URL', 'http://32.193.167.191:8080');
157+
try {
158+
return Http::get("{$apiHost}/estadosPedidos")->throw()->json();
159+
} catch (Exception $e) {
160+
return [];
161+
}
167162
}
168-
}
169163

170-
public function obtenerClientes()
171-
{
172-
try {
173-
return Http::get("http://localhost:8080/detalle/cliente")->throw()->json();
174-
} catch (Exception $e) {
175-
return [];
164+
public function obtenerClientes()
165+
{
166+
$apiHost = env('API_BASE_URL', 'http://32.193.167.191:8080');
167+
try {
168+
return Http::get("{$apiHost}/detalle/cliente")->throw()->json();
169+
} catch (Exception $e) {
170+
return [];
171+
}
176172
}
177-
}
178173

179-
public function obtenerEmpleados()
180-
{
181-
try {
182-
return Http::get("http://localhost:8080/detalle/empleado")->throw()->json();
183-
} catch (Exception $e) {
184-
return [];
174+
public function obtenerEmpleados()
175+
{
176+
$apiHost = env('API_BASE_URL', 'http://32.193.167.191:8080');
177+
try {
178+
return Http::get("{$apiHost}/detalle/empleado")->throw()->json();
179+
} catch (Exception $e) {
180+
return [];
181+
}
185182
}
186-
}
187-
}
183+
}

Frontend/resources/views/pedidosviews/PedidosClientes/create.blade.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@
9292
9393
async function cargarProductos() {
9494
try {
95-
const response = await fetch('http://localhost:8080/productos');
95+
const response = await fetch("{{ route('api.productos.lista') }}");
9696
const data = await response.json();
9797
listaProductosGlobal = data.map(p => ({
9898
id: p.id_PRODUCTO || p.idProducto || p["Id Producto:"],

Frontend/resources/views/pedidosviews/PedidosClientes/edit.blade.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,7 @@
129129
async function inicializarVista() {
130130
try {
131131
console.log("Iniciando carga de productos desde Java...");
132-
const response = await fetch('http://localhost:8080/productos');
132+
const response = await fetch("{{ route('api.productos.lista') }}");
133133
if (!response.ok) throw new Error("Fallo al conectar con Java");
134134
135135
const data = await response.json();

0 commit comments

Comments
 (0)