This commit is contained in:
amazuecos
2025-03-26 23:31:31 +01:00
14 changed files with 600 additions and 49 deletions

View File

@ -277,6 +277,13 @@ class Pedido extends \App\Controllers\BaseResourceController
$this->viewData['pedidoEntity'] = $pedidoEntity;
if($pedidoEntity->estado == 'validacion'){
$clienteModel = model('App\Models\Clientes\ClienteModel');
$pendiente = $clienteModel->getPendienteCobro($pedidoEntity->cliente_id);
$pendiente = $pendiente[0] + $pendiente[1];
$this->viewData['importePendiente'] = $pendiente;
}
$this->viewData['boxTitle'] = lang('Basic.global.edit2') . ' ' . lang('Pedidos.moduleTitle') . ' ' . lang('Basic.global.edit3');
return $this->displayForm(__METHOD__, $id);
@ -471,11 +478,12 @@ class Pedido extends \App\Controllers\BaseResourceController
$pedido = $this->model->find($pedido_id);
$serviceProduction->setPedido($pedido);
if($pedido->orden_trabajo()){
return $this->response->setJSON(["data"=>$pedido->orden_trabajo(),"message" => "Ya existe una orden de trabajo para este pedido"]);
return $this->response->setJSON(["status"=>false,"data"=>$pedido->orden_trabajo(),"message" => "Ya existe una orden de trabajo para este pedido"]);
}else{
$r = $serviceProduction->createOrdenTrabajo();
return $this->response->setJSON(["data"=>$r,"message" => "Orden trabajo creada correctamente"]);
$this->model->set(['estado' => 'produccion'])->where('id', $pedido_id)->update();
return $this->response->setJSON(["status"=>true, "data"=>$r,"message" => "Orden trabajo creada correctamente"]);
}
}

View File

@ -31,7 +31,8 @@ class Test extends BaseController
public function index()
{
$this->sendMail('prueba', 'Esto es una prueba', ['jaimejimenezortega@gmail.com','jaime0jimenez0ortega@gmail.com']);
$modelCliente = model('App\Models\Clientes\ClienteModel');
var_dump($modelCliente->getPendienteCobro(1284));
}
private function sendMail($subject, $body, $recipient)

View File

@ -0,0 +1,222 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
use CodeIgniter\Database\RawSql;
class OrdenTrabajoUsersTable extends Migration
{
protected array $USER_COLUMNS = [
'id' => [
'type' => 'INT',
'unsigned' => true,
'auto_increment' => true,
],
"orden_trabajo_id" => [
"type" => "INT",
"unsigned" => true,
],
"user_created_id" => [
"type" => "INT",
"unsigned" => true,
"constraint" => 10,
"null" => true,
],
"user_update_id" => [
"type" => "INT",
"unsigned" => true,
"constraint" => 10,
"null" => true,
],
"inaplazable_revised_change_user_id" => [
"type" => "INT",
"unsigned" => true,
"constraint" => 10,
"null" => true,
],
"ferro_disponible_hecho_user_id" => [
"type" => "INT",
"unsigned" => true,
"constraint" => 10,
"null" => true,
],
"ferro_disponible_ok_user_id" => [
"type" => "INT",
"unsigned" => true,
"constraint" => 10,
"null" => true,
],
"ferro_entregado_user_id" => [
"type" => "INT",
"unsigned" => true,
"constraint" => 10,
"null" => true,
],
"pendiente_ferro_user_id" => [
"type" => "INT",
"unsigned" => true,
"constraint" => 10,
"null" => true,
],
"ferro_en_cliente_user_id" => [
"type" => "INT",
"unsigned" => true,
"constraint" => 10,
"null" => true,
],
"ferro_ok_user_id" => [
"type" => "INT",
"unsigned" => true,
"constraint" => 10,
"null" => true,
],
"interior_bn_user_id" => [
"type" => "INT",
"unsigned" => true,
"constraint" => 10,
"null" => true,
],
"interior_color_user_id" => [
"type" => "INT",
"unsigned" => true,
"constraint" => 10,
"null" => true,
],
"preparacion_interior_user_id" => [
"type" => "INT",
"unsigned" => true,
"constraint" => 10,
"null" => true,
],
"cubierta_user_id" => [
"type" => "INT",
"unsigned" => true,
"constraint" => 10,
"null" => true,
],
"plastificado_user_id" => [
"type" => "INT",
"unsigned" => true,
"constraint" => 10,
"null" => true,
],
"encuadernacion_user_id" => [
"type" => "INT",
"unsigned" => true,
"constraint" => 10,
"null" => true,
],
"corte_user_id" => [
"type" => "INT",
"unsigned" => true,
"constraint" => 10,
"null" => true,
],
"embalaje_user_id" => [
"type" => "INT",
"unsigned" => true,
"constraint" => 10,
"null" => true,
],
"envio_user_id" => [
"type" => "INT",
"unsigned" => true,
"constraint" => 10,
"null" => true,
],
"entrada_manipulado_user_id" => [
"type" => "INT",
"unsigned" => true,
"constraint" => 10,
"null" => true,
],
"pre_formato_user_id" => [
"type" => "INT",
"unsigned" => true,
"constraint" => 10,
"null" => true,
],
"pre_lomo_user_id" => [
"type" => "INT",
"unsigned" => true,
"constraint" => 10,
"null" => true,
],
"pre_solapa_user_id" => [
"type" => "INT",
"unsigned" => true,
"constraint" => 10,
"null" => true,
],
"pre_codbarras_user_id" => [
"type" => "INT",
"unsigned" => true,
"constraint" => 10,
"null" => true,
],
"pre_imposicion_user_id" => [
"type" => "INT",
"unsigned" => true,
"constraint" => 10,
"null" => true,
],
"pre_imprimir_user_id" => [
"type" => "INT",
"unsigned" => true,
"constraint" => 10,
"null" => true,
],
"pre_imprimir_user_id" => [
"type" => "INT",
"unsigned" => true,
"constraint" => 10,
"null" => true,
],
];
public function up()
{
$this->forge->dropTable('orden_trabajo_users',true);
$currenttime = new RawSql("CURRENT_TIMESTAMP");
$this->forge->addField($this->USER_COLUMNS);
$this->forge->addField([
"created_at" => [
"type" => "TIMESTAMP",
"default" => $currenttime,
],
"updated_at" => [
"type" => "TIMESTAMP",
"null" => true,
],
"deleted_at" => [
"type" => "TIMESTAMP",
"null" => true,
],
]);
$this->forge->addPrimaryKey('id');
$this->forge->addForeignKey("orden_trabajo_id", "ordenes_trabajo","id");
$this->forge->createTable("orden_trabajo_users");
}
public function down()
{
$this->forge->dropTable('orden_trabajo_users');
}
}

View File

@ -0,0 +1,174 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
use CodeIgniter\Database\RawSql;
class OrdenTrabajoDatesTable extends Migration
{
protected array $COLUMNS = [
'id' => [
'type' => 'INT',
'unsigned' => true,
'auto_increment' => true,
],
"orden_trabajo_id" => [
"type" => "INT",
"unsigned" => true,
],
"fecha_entrada_at" => [
"type" => "DATE",
"null" => true,
],
"fecha_entrega_at" => [
"type" => "DATE",
"null" => true,
],
"fecha_entrega_change_at" => [
"type" => "DATE",
"null" => true,
],
"fecha_entrega_real_at" => [
"type" => "DATE",
"null" => true,
],
"fecha_impresion_at" => [
"type" => "DATE",
"null" => true,
],
"fecha_encuadernado_at" => [
"type" => "DATE",
"null" => true,
],
"fecha_entrega_externo" => [
"type" => "DATE",
"null" => true,
],
"pendiente_ferro_at" => [
"type" => "DATE",
"null" => true,
],
"ferro_en_cliente_at" => [
"type" => "DATE",
"null" => true,
],
"ferro_ok_at" => [
"type" => "DATE",
"null" => true,
],
"interior_bn_at" => [
"type" => "DATE",
"null" => true,
],
"interior_color_at" => [
"type" => "DATE",
"null" => true,
],
"preparacion_interiores_at" => [
"type" => "DATE",
"null" => true,
],
"cubierta_at" => [
"type" => "DATE",
"null" => true,
],
"plastificado_at" => [
"type" => "DATE",
"null" => true,
],
"encuadernacion_at" => [
"type" => "DATE",
"null" => true,
],
"corte_at" => [
"type" => "DATE",
"null" => true,
],
"embalaje_at" => [
"type" => "DATE",
"null" => true,
],
"envio_at" => [
"type" => "DATE",
"null" => true,
],
"entrada_manipulado_at" => [
"type" => "DATE",
"null" => true,
],
"ferro_disponible_hecho_at" => [
"type" => "DATE",
"null" => true,
],
"ferro_disponible_ok_at" => [
"type" => "DATE",
"null" => true,
],
"ferro_entregado_at" => [
"type" => "DATE",
"null" => true,
],
"pre_formato_at" => [
"type" => "DATE",
"null" => true,
],
"pre_lomo_at" => [
"type" => "DATE",
"null" => true,
],
"pre_solapa_at" => [
"type" => "DATE",
"null" => true,
],
"pre_codbarras_at" => [
"type" => "DATE",
"null" => true,
],
"pre_imposicion_at" => [
"type" => "DATE",
"null" => true,
],
];
public function up()
{
$this->forge->dropTable('orden_trabajo_dates',true);
$currenttime = new RawSql("CURRENT_TIMESTAMP");
$this->forge->addField($this->COLUMNS);
$this->forge->addField([
"created_at" => [
"type" => "TIMESTAMP",
"default" => $currenttime,
],
"updated_at" => [
"type" => "TIMESTAMP",
"null" => true,
],
"deleted_at" => [
"type" => "TIMESTAMP",
"null" => true,
],
]);
$this->forge->addPrimaryKey('id');
$this->forge->addForeignKey("orden_trabajo_id", "ordenes_trabajo","id");
$this->forge->createTable("orden_trabajo_dates");
}
public function down()
{
$this->forge->dropTable('orden_trabajo_dates');
}
}

View File

@ -7,8 +7,8 @@ use CodeIgniter\Entity\Entity;
class OrdenTrabajoDateEntity extends Entity
{
protected $attributes = [
"orden_trabajo_id" => null,
"fecha_entrada_at" => null,
"fecha_entrega_at" => null,
"fecha_entrega_change_at" => null,
"fecha_entrega_real_at" => null,
"fecha_entrega_real_warning" => null,
@ -33,10 +33,35 @@ class OrdenTrabajoDateEntity extends Entity
];
protected $datamap = [];
protected $dates = ['created_at', 'updated_at', 'deleted_at'];
protected $dates = [
'created_at',
'updated_at',
'deleted_at',
'fecha_entrega_at',
'fecha_entrega_change_at',
'fecha_entrega_real_at',
'fecha_entrega_real_warning',
'fecha_impresion_at',
'fecha_encuadernado_at',
'fecha_externo_at',
'fecha_entrega_warning',
'fecha_entrega_warning_revised',
'pendiente_ferro_at',
'ferro_en_cliente_at',
'ferro_ok_at',
'interior_bn_at',
'interior_color_at',
'preparacion_interiores_at',
'cubierta_at',
'plastificado_at',
'encuadernacion_at',
'corte_at',
'embalaje_at',
'envio_at',
'entrada_manipulado_at'
];
protected $casts = [
// "fecha_entrada_at" => "?datetime",
// "fecha_entrega_at" => "?datetime",
// "fecha_entrega_change_at" => "?datetime",
// "fecha_entrega_real_at" => "?datetime",
// "fecha_entrega_real_warning" => "?bool",

View File

@ -8,7 +8,33 @@ class OrdenTrabajoUserEntity extends Entity
{
protected $datamap = [];
protected $dates = ['created_at', 'updated_at', 'deleted_at'];
protected $casts = [];
protected array $casts = [
"orden_trabajo_id" => "integer",
"user_created_id" => "?integer",
"user_update_id" => "?integer",
"inaplazable_revised_change_user_id" => "?integer",
"ferro_disponible_hecho_user_id" => "?integer",
"ferro_disponible_ok_user_id" => "?integer",
"ferro_entregado_user_id" => "?integer",
"pendiente_ferro_user_id" => "?integer",
"ferro_en_cliente_user_id" => "?integer",
"ferro_ok_user_id" => "?integer",
"interior_bn_user_id" => "?integer",
"interior_color_user_id" => "?integer",
"preparacion_interior_user_id" => "?integer",
"cubierta_user_id" => "?integer",
"plastificado_user_id" => "?integer",
"encuadernacion_user_id" => "?integer",
"corte_user_id" => "?integer",
"embalaje_user_id" => "?integer",
"entrada_manipulado_user_id" => "?integer",
"pre_formato_user_id" => "?integer",
"pre_lomo_user_id" => "?integer",
"pre_solapa_user_id" => "?integer",
"pre_codbarras_user_id" => "?integer",
"pre_imposicion_user_id" => "?integer",
"pre_imprimir_user_id" => "?integer"
];
protected $attributes = [
"orden_trabajo_id"=> null,
"user_created_id"=> null,

View File

@ -14,6 +14,7 @@ return [
'tiradas' => 'Tiradas',
'total_presupuesto' => 'Total',
'estado' => 'Estado',
'importePendiente' => 'Importe Pendiente',
'validacion' => 'Validación',
'produccion' => 'Producción',

View File

@ -309,10 +309,27 @@ class ClienteModel extends \App\Models\BaseModel
/*
TO-DO: Implementar la lógica de negocio para el crédito disponible
*/
public function creditoDisponible($cliente_id)
public function creditoDisponible($cliente_id, $total_pedido = 0)
{
$builder = $this->db
->table($this->table . " t1")
->select(
"t1.limite_credito AS limite_credito"
)
->where("t1.is_deleted", 0)
->where("t1.id", $cliente_id);
$limite = $builder->get()->getResultObject();
if($limite){
$pendiente = $this->getPendienteCobro($cliente_id);
$credito_disponible = floatval($limite[0]->limite_credito) - $pendiente[0] - $pendiente[1] - floatval($total_pedido);
if($credito_disponible < 0)
return false;
return true;
}
return false;
}
public function getClienteDataFacturas($cliente_id)
{
@ -402,4 +419,83 @@ class ClienteModel extends \App\Models\BaseModel
->groupEnd()->get()->getResultObject();
}
public function getPendienteCobro($cliente_id = -1)
{
$pendiente_old = $this->getTotalPendienteOldERP($cliente_id);
// Subconsulta para verificar la existencia en facturas_lineas
$subquery_facturas = "(SELECT 1
FROM facturas_lineas fl
JOIN facturas f2 ON fl.factura_id = f2.id
WHERE (fl.pedido_linea_impresion_id = p.id OR fl.pedido_maquetacion_id = p.id)
AND f2.estado = 'validada')";
// Subconsulta para calcular el total de pedidos pendientes
$subquery_total_pedidos = $this->db->table('pedidos p')
->select('SUM(p.total_precio)', false)
->join('pedidos_linea pl', 'p.id = pl.pedido_id', 'left')
->join('presupuestos pr', 'pl.presupuesto_id = pr.id', 'left')
->where('pr.cliente_id', $cliente_id)
->whereIn('p.estado', ['produccion', 'finalizado', 'enviado'])
->where("NOT EXISTS $subquery_facturas", null, false) // Implementación manual de NOT EXISTS
->getCompiledSelect();
// Construcción de la consulta principal
$builder = $this->db->table('(SELECT DISTINCT cliente_id FROM presupuestos UNION SELECT DISTINCT cliente_id FROM facturas) c');
$builder->select('c.cliente_id');
$builder->select('COALESCE(SUM(f.pendiente), 0) AS total_facturas');
$builder->select("COALESCE(($subquery_total_pedidos), 0) AS total_pedidos", false);
$builder->select("COALESCE(SUM(f.pendiente), 0) + COALESCE(($subquery_total_pedidos), 0) AS total_pendiente", false);
$builder->join('facturas f', 'c.cliente_id = f.cliente_id AND f.deleted_at IS NULL AND f.estado = "validada"', 'left');
$builder->where('c.cliente_id', $cliente_id);
$builder->groupBy('c.cliente_id');
$query = $builder->get();
$valor = $query->getRow();
if ($valor) {
return [round(floatval($valor->total_pendiente), 2), round(floatval($pendiente_old), 2)];
} else {
return [0, round(floatval($pendiente_old), 2)];
}
}
private function getTotalPendienteOldERP($customer_id = -1)
{
$db = \Config\Database::connect('old_erp'); // Conectar a olderp
$builder = $db->table('safekat.facturas f');
$builder->select('f.customer_id');
$builder->select('SUM(f.pendiente) + COALESCE((
SELECT SUM(pl.total_raw)
FROM safekat.pedido_libro pl
WHERE pl.factura_id IS NULL
AND pl.estado IN ("aceptado", "finalizado", "validado")
AND pl.total_raw IS NOT NULL
AND pl.total_raw != 0
AND pl.inc_rei IS NULL
AND pl.customer_id = f.customer_id
), 0) AS total_pendiente');
$builder->where('f.deleted_at IS NULL');
$builder->where('f.estado', 'open');
$builder->where('f.customer_id', $customer_id);
$builder->groupBy('f.customer_id');
$query = $builder->get();
$valor = $query->getRow();
/*
$builder = $db->table('vista_importe_pendiente_cliente t1')
->select('*')
->where('t1.customer_id', $customer_id);
$query = $builder->get();
$valor = $query->getRow();*/
if ($valor) {
return $valor->total_pendiente;
} else {
return 0;
}
}
}

View File

@ -9,8 +9,8 @@ use CodeIgniter\Model;
class OrdenTrabajoDate extends Model
{
protected $table = 'orden_trabajo_dates';
protected $primaryKey = 'orden_trabajo_id';
protected $useAutoIncrement = false;
protected $primaryKey = 'id';
protected $useAutoIncrement = true;
protected $returnType = OrdenTrabajoDateEntity::class;
protected $useSoftDeletes = true;
protected $protectFields = true;
@ -62,8 +62,8 @@ class OrdenTrabajoDate extends Model
protected $allowCallbacks = true;
protected $beforeInsert = [];
protected $afterInsert = ["updateOrdenTrabajoUser"];
protected $beforeUpdate = ["updateOrdenTrabajoUser"];
protected $afterUpdate = [];
protected $beforeUpdate = [];
protected $afterUpdate = ["updateOrdenTrabajoUser"];
protected $beforeFind = [];
protected $afterFind = [];
protected $beforeDelete = [];
@ -106,7 +106,7 @@ class OrdenTrabajoDate extends Model
$mapping = [
"fecha_encuadernado_at" => "encuadernacion_user_id",
// "fecha_externo_at" => "null",
"fecha_impresion_at" => "null",
"fecha_impresion_at" => null,
"pendiente_ferro_at" => "pendiente_ferro_user_id",
"ferro_en_cliente_at" => "ferro_en_cliente_user_id",
"ferro_ok_at" => "ferro_ok_user_id",
@ -124,9 +124,12 @@ class OrdenTrabajoDate extends Model
foreach ($data as $key => $value) {
if(isset($mapping[$key])){
if($value){
$otUser->update($data["orden_trabajo_id"],[$mapping[$key] => $auth_user_id]);
$otUser->where('orden_trabajo_id',$data['orden_trabajo_id'])
->set([$mapping[$key] => $auth_user_id])
->update();
}
}
}
return $data;
}
}

View File

@ -9,8 +9,8 @@ use CodeIgniter\Model;
class OrdenTrabajoUser extends Model
{
protected $table = 'orden_trabajo_users';
protected $primaryKey = 'orden_trabajo_id';
protected $useAutoIncrement = false;
protected $primaryKey = 'id';
protected $useAutoIncrement = true;
protected $returnType = OrdenTrabajoUserEntity::class;
protected $useSoftDeletes = true;
protected $protectFields = true;
@ -46,31 +46,7 @@ class OrdenTrabajoUser extends Model
protected bool $updateOnlyChanged = true;
protected array $casts = [
"orden_trabajo_id" => "integer",
"user_created_id" => "?integer",
"user_update_id" => "?integer",
"inaplazable_revised_change_user_id" => "?integer",
"ferro_disponible_hecho_user_id" => "?integer",
"ferro_disponible_ok_user_id" => "?integer",
"ferro_entregado_user_id" => "?integer",
"pendiente_ferro_user_id" => "?integer",
"ferro_en_cliente_user_id" => "?integer",
"ferro_ok_user_id" => "?integer",
"interior_bn_user_id" => "?integer",
"interior_color_user_id" => "?integer",
"preparacion_interior_user_id" => "?integer",
"cubierta_user_id" => "?integer",
"plastificado_user_id" => "?integer",
"encuadernacion_user_id" => "?integer",
"corte_user_id" => "?integer",
"embalaje_user_id" => "?integer",
"entrada_manipulado_user_id" => "?integer",
"pre_formato_user_id" => "?integer",
"pre_lomo_user_id" => "?integer",
"pre_solapa_user_id" => "?integer",
"pre_codbarras_user_id" => "?integer",
"pre_imposicion_user_id" => "?integer",
"pre_imprimir_user_id" => "?integer"
];
protected array $castHandlers = [];

View File

@ -2,6 +2,7 @@
namespace App\Services;
use App\Controllers\Pedidos\Pedido;
use CodeIgniter\Config\BaseService;
use App\Models\Configuracion\MaquinasTarifasImpresionModel;
@ -1877,7 +1878,7 @@ class PresupuestoService extends BaseService
$data_pedido = [
'total_precio' => $datos_presupuesto->total_aceptado,
'total_tirada' => $datos_presupuesto->tirada,
'estado' => $model_cliente->creditoDisponible($datos_presupuesto->cliente_id) ? "produccion" : "validacion",
'estado' => $model_cliente->creditoDisponible($datos_presupuesto->cliente_id, $datos_presupuesto->total_aceptado) ? "produccion" : "validacion",
'user_created_id' => auth()->user()->id,
'user_updated_id' => auth()->user()->id,
];
@ -1896,6 +1897,9 @@ class PresupuestoService extends BaseService
}
if ($id_linea != 0 && $pedido_id != 0) {
if($data_pedido['estado'] == "produccion"){
$response = (new Pedido())->to_produccion($pedido_id);
}
return true;
}
return false;

View File

@ -121,10 +121,10 @@ class ProductionService extends BaseService
"total_tirada" => $this->pedido->total_tirada,
"total_precio" => $this->pedido->total_precio
];
$ot_id = $this->otModel->insert($data);
$this->init($ot_id);
// $this->storeOrdenTrabajoUsers();
// $this->storeOrdenTrabajoDates();
$id = $this->otModel->insert($data);
$this->init($id);
$this->storeOrdenTrabajoUsers();
$this->storeOrdenTrabajoDates();
$this->storeAllTareas();
return $this->ot;
}

View File

@ -56,6 +56,18 @@
</div>
</div><!--//.mb-3 -->
<?php if($pedidoEntity->estado == 'validacion' && (!(auth()->user()->inGroup('cliente-admin') || auth()->user()->inGroup('cliente-editor')))): ?>
<div class="col-md-12 col-lg-2 px-4"></div>
<div class="col-md-12 col-lg-4 px-4"></div>
<div class="col-md-12 col-lg-3 px-4"></div>
<div class="col-md-12 col-lg-3 px-4">
<label for="estadoText" class="form-label">
<?= lang('Pedidos.importePendiente') ?>
</label>
<input readonly id="importePendienteText" name="importePendienteText" tabindex="1" maxLength="11" class="form-control" value="<?= old('importePendienteText', $importePendiente) ?>" >
</div>
<?php endif; ?>
<?php if (!(auth()->user()->inGroup('cliente-admin') || auth()->user()->inGroup('cliente-editor'))) : ?>
<div class="accordion accordion mt-3 accordion-without-arrow" id="FechasPedido">

View File

@ -23,6 +23,9 @@ $(() => {
null,
null,
(response) => {
if(response.status){
location.reload()
}
Swal.fire({
title: response.message,
icon: 'success',