Merge branch 'add/view_logistica_principal' into 'main'

Add/view logistica principal

See merge request jjimenez/safekat!725
This commit is contained in:
2025-04-22 08:26:52 +00:00
40 changed files with 4022 additions and 1584 deletions

View File

@ -512,15 +512,16 @@ $routes->group('pedidos', ['namespace' => 'App\Controllers\Pedidos'], function (
$routes->resource('pedidos', ['namespace' => 'App\Controllers\Pedidos', 'controller' => 'Pedido', 'except' => 'show,new,create,update']);
$routes->group('albaranes', ['namespace' => 'App\Controllers\Pedidos'], function ($routes) {
$routes->post('add', 'Albaran::add', ['as' => 'crearAlbaranesPedido']);
$routes->post('update/(:any)', 'Albaran::update/$1', ['as' => 'actualizarAlbaran']);
$routes->post('updateLinea/(:any)', 'Albaran::updateLinea/$1', ['as' => 'actualizarLineaAlbaran']);
$routes->post('deletelinea', 'Albaran::borrarlinea', ['as' => 'borrarAlbaranLinea']);
$routes->get('delete/(:any)', 'Albaran::delete/$1', ['as' => 'borrarAlbaran']);
$routes->get('getalbaranes/(:any)', 'Albaran::getAlbaranes/$1', ['as' => 'getAlbaranes']);
$routes->get('nuevalinea/(:any)', 'Albaran::addLinea/$1', ['as' => 'addAlbaranLinea']);
$routes->post('nuevalinea/(:any)', 'Albaran::addLinea/$1', ['as' => 'addIVA']);
$routes->group('albaranes', ['namespace' => 'App\Controllers\Albaranes'], function ($routes) {
$routes->post('generarAlbaran', 'Albaran::generateAlbaran', ['as' => 'generarAlbaran']);
$routes->get('albaranesEnvio', 'Albaran::getAlbaranes');
$routes->get('datatablesAlbaranLinea', 'Albaran::datatablesLineasAlbaran');
$routes->post('updateAlbaran', 'Albaran::updateAlbaran');
$routes->post('borrarAlbaranLinea', 'Albaran::borrarLinea');
$routes->post('borrarAlbaran', 'Albaran::borrarAlbaran');
$routes->post('updateAlbaranLinea', 'Albaran::updateAlbaranLinea');
$routes->post('addIvaAlbaran', 'Albaran::addLineasIva');
$routes->post('nuevaLineaAlbaran', 'Albaran::addBlankLineaAlbaran');
});
$routes->resource('albaranes', ['namespace' => 'App\Controllers\Pedidos', 'controller' => 'Albaran', 'except' => 'show,new,create,update']);
@ -789,6 +790,19 @@ $routes->group('produccion', ['namespace' => 'App\Controllers\Produccion'], func
$routes->group('logistica', ['namespace' => 'App\Controllers\Logistica'], function ($routes) {
$routes->get('print/label/test', 'LogisticaController::print_test_label');
$routes->get('panel', 'LogisticaController::panel', ['as' => 'LogisticaPanel']);
$routes->get('selectEnvios/(:any)', 'LogisticaController::selectorEnvios/$1', ['as' => 'selectEnvios']);
$routes->get('buscar/(:any)', 'LogisticaController::searchPedidoOrISBN/$1', ['as' => 'buscarPedidoOrISBN']);
$routes->get('datatableEnvios', 'LogisticaController::datatable_envios');
$routes->get('datatableLineasEnvios/(:num)', 'LogisticaController::datatable_enviosEdit/$1');
$routes->get('envio/(:num)', 'LogisticaController::editEnvio/$1');
$routes->get('selectAddLinea', 'LogisticaController::selectAddEnvioLinea');
$routes->get('addLineaEnvio', 'LogisticaController::addEnvioLinea');
$routes->post('updateCajaLinea', 'LogisticaController::setCajaLinea');
$routes->post('deleteLineasEnvio', 'LogisticaController::deleteLineas');
$routes->post('updateLineaEnvio', 'LogisticaController::updateLineaEnvio');
$routes->post('updateComentariosEnvio', 'LogisticaController::saveComments');
$routes->post('updateCajasEnvio', 'LogisticaController::updateCajasEnvio');
});
/*

View File

@ -0,0 +1,560 @@
<?php
namespace App\Controllers\Albaranes;
use App\Entities\Albaranes\AlbaranEntity;
use App\Models\Albaranes\AlbaranModel;
use Hermawan\DataTables\DataTable;
class Albaran extends \App\Controllers\BaseResourceController
{
protected $modelName = AlbaranModel::class;
protected $format = 'json';
protected static $singularObjectNameCc = 'albaran';
protected static $singularObjectName = 'Albaran';
protected static $pluralObjectName = 'Albaranes';
protected static $controllerSlug = 'albaran';
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
}
public function index()
{
}
public function delete($id = null)
{
if ($this->request->isAJAX()) {
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$model_linea = model('App\Models\Albaranes\AlbaranLineaModel');
$model_linea->where('albaran_id', $id)->delete();
$this->model->where('id', $id)->delete();
$data = [
'error' => 0,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function addLinea($albaran_id)
{
if ($this->request->isAJAX()) {
$model_linea = model('App\Models\Albaranes\AlbaranLineaModel');
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
// si es un post, es el iva
if ($this->request->getPost()) {
$reqData = $this->request->getPost();
$albaran_id = $reqData['albaran_id'] ?? 0;
$albaran = $this->model->find($albaran_id);
if ($albaran == false) {
$data = [
'error' => 'Albaran no encontrado',
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
}
$presupuesto_model = model('App\Models\Presupuestos\PresupuestoModel');
$presupuesto = $presupuesto_model->find($albaran->presupuesto_id);
if ($presupuesto == false) {
$data = [
'error' => 'Presupuesto no encontrado',
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
}
$iva_reducido = $presupuesto->iva_reducido;
$lineas = $model_linea->where('albaran_id', $albaran_id)->findAll();
$total = 0;
foreach ($lineas as $linea) {
$total += $linea->total;
}
$iva = $iva_reducido ? $total * 4.0 / 100 : $total * 21.0 / 100;
$data_linea = [
'albaran_id' => $albaran_id,
'titulo' => $iva_reducido ? lang('Pedidos.iva4') : lang('Pedidos.iva21'),
'cantidad' => 1,
'precio_unidad' => round($iva, 2),
'total' => round($iva, 2),
'user_created_id' => auth()->user()->id,
'user_updated_id' => auth()->user()->id
];
$id_linea = $model_linea->insert($data_linea);
$linea = $model_linea->find($id_linea);
$data = [
'error' => 0,
'data' => $linea,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
} else {
$linea = [
'albaran_id' => $albaran_id,
'user_created_id' => auth()->user()->id,
'user_updated_id' => auth()->user()->id
];
$id_linea = $model_linea->insert($linea);
$data = $model_linea->find($id_linea);
$data = [
'error' => 0,
'data' => $data,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
}
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function add()
{
if ($this->request->isAJAX()) {
$user = auth()->user()->id;
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$reqData = $this->request->getPost();
$pedido_id = $reqData['pedido_id'] ?? 0;
$presupuestos_id = $reqData['presupuestos_id'] ?? 0;
$return_data = $this->model->generarAlbaranes($pedido_id, $presupuestos_id, $user);
$data = [
'data' => $return_data,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function updateAlbaran()
{
if ($this->request->isAJAX()) {
$fieldName = $this->request->getPost('fieldName');
$fieldValue = $this->request->getPost('fieldValue');
$id = $this->request->getPost('albaranId');
if ($id == null) {
$data = [
'success' => false,
'message' => lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Pedidos.albaran')), $id]),
];
return $this->respond($data);
}
$albaranEntity = $this->model->find($id);
if ($albaranEntity == false) {
$data = [
'success' => false,
'message' => lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Pedidos.albaran')), $id]),
];
return $this->respond($data);
}
if($fieldName == 'fecha_albaran'){
if($fieldValue == null || $fieldValue == '')
$fieldValue = null;
else
$fieldValue = date('Y-m-d H:i:s', strtotime($fieldValue));
}
$albaranEntity->fill([
$fieldName => $fieldValue,
'user_updated_id' => auth()->user()->id,
]);
$successfulResult = $this->model->skipValidation(true)->update($id, $albaranEntity);
if ($successfulResult) {
$data = [
'success' => true,
'message' => lang('Basic.global.updateSuccess', [lang('Basic.global.record')]) . '.',
];
} else {
$data = [
'success' => false,
'message' => lang('Basic.global.updateError', [lang('Basic.global.record')]) . '.',
];
}
return $this->respond($data);
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function updateLinea($id = null)
{
if ($this->request->isAJAX()) {
$model_linea = model('App\Models\Albaranes\AlbaranLineaModel');
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
if ($id == null):
$data = [
'error' => 2,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
endif;
$id = filter_var($id, FILTER_SANITIZE_URL);
$albaranEntity = $model_linea->find($id);
if ($albaranEntity == false):
$message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Pedidos.albaran')), $id]);
$data = [
'error' => $message,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
endif;
if ($this->request->getPost()):
$nullIfEmpty = true; // !(phpversion() >= '8.1');
$postData = $this->request->getPost();
$sanitizedData = $this->sanitized($postData, $nullIfEmpty);
// JJO
$sanitizedData['user_updated_id'] = auth()->user()->id;
$noException = true;
if ($successfulResult = $this->canValidate()): // if ($successfulResult = $this->validate($this->formValidationRules) ) :
if ($this->canValidate()):
try {
$successfulResult = $model_linea->skipValidation(true)->update($id, $sanitizedData);
} catch (\Exception $e) {
$noException = false;
$this->dealWithException($e);
}
else:
$this->viewData['warningMessage'] = lang('Basic.global.formErr1', [mb_strtolower(lang('Pedidos.albaran'))]);
$this->session->setFlashdata('formErrors', $model_linea->errors());
endif;
$albaranEntity->fill($sanitizedData);
endif;
if ($noException && $successfulResult):
$id = $albaranEntity->id ?? $id;
$message = lang('Basic.global.updateSuccess', [lang('Basic.global.record')]) . '.';
$data = [
'error' => 0,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
endif; // $noException && $successfulResult
endif; // ($requestMethod === 'post')
$data = [
'error' => 1,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function getAlbaranes()
{
if ($this->request->isAJAX()) {
$envio_id = $this->request->getGet('envio_id');
$albaranes = $this->model->getAlbaranesEnvio($envio_id);
$data = [
'status' => true,
'data' => $albaranes,
];
return $this->respond($data);
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function generateAlbaran()
{
if ($this->request->isAJAX()) {
$reqData = $this->request->getPost();
$envio_id = $reqData['envio_id'] ?? 0;
$envio_lineas = $reqData['envio_lineas'] ?? [];
$cajas = $reqData['cajas'] ?? 0;
$response = $this->model->generarAlbaranes($envio_id, $envio_lineas, $cajas);
return $this->respond($response);
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function datatablesLineasAlbaran()
{
$albaranId = $this->request->getGet('albaranId');
$model = model('App\Models\Albaranes\AlbaranLineaModel');
$q = $model->getDatatableQuery($albaranId);
$result = DataTable::of($q)
->add(
"action",
callback: function ($q) {
return '
<div class="btn-group btn-group-sm">
<a href="javascript:void(0);"><i class="ti ti-trash ti-sm btn-delete-albaran-lineas mx-2" data-id="' . $q->id . '"></i></a>
</div>
';
}
)
->edit('pedido', function ($q) {
return '<a href="' . base_url('pedidos/edit/' . $q->pedido) . '" target="_blank">' . $q->pedido . '</a>';
})
->edit('unidades', function ($q) {
if(str_contains($q->titulo, 'IVA'))
return null;
else
return '<input type="number" class="form-control form-control-sm input-albaran-linea text-center"
value="' . $q->unidades . '" data-id="' . $q->id . '" data-field="cantidad" />';
})
->edit('titulo', function ($q) {
return '<input type="text" class="form-control form-control-sm input-albaran-linea" value="' . $q->titulo .
'" data-id="' . $q->id . '" data-field="titulo" />';
})
->edit('total', function ($q) {
return '<input class="form-control autonumeric-2 input-albaran-linea
form-control-sm text-center" value="' . $q->total . '" data-id="' . $q->id . '" data-field="total" />';
})
->edit('precio_unidad', function ($q) {
if(str_contains($q->titulo, 'IVA'))
return null;
else
return '<input class="form-control autonumeric-4 form-control-sm text-center input-albaran-linea" value="' .
number_format((float) $q->precio_unidad, 4, ',', '') .
'" data-id="' . $q->id . '" data-field="precio_unidad" />';
});
return $result->toJson(returnAsObject: true);
}
public function updateAlbaranLinea(){
if ($this->request->isAJAX()) {
$model_linea = model('App\Models\Albaranes\AlbaranLineaModel');
$fieldName = $this->request->getPost('fieldName');
$fieldValue = $this->request->getPost('fieldValue');
$id = $this->request->getPost('lineaId');
$linea = $model_linea->find($id);
if ($linea == false) {
$data = [
'success' => false,
'message' => lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Pedidos.albaran')), $id]),
];
return $this->respond($data);
}
if($fieldName == 'cantidad') {
$linea->total = round($linea->precio_unidad * intval($fieldValue), 4);
$linea->cantidad = intval($fieldValue);
}
else if($fieldName == 'precio_unidad') {
$fieldValue2 = str_replace(',', '.', $fieldValue);
$linea->total = round(round(floatval($fieldValue2), 4) * intval($linea->cantidad), 2);
$linea->precio_unidad = round(floatval($fieldValue2), 4);
}
else if($fieldName == 'total') {
$linea->total = round(floatval($fieldValue), 2);
$linea->precio_unidad = round(floatval($fieldValue) / intval($linea->cantidad), 4);
}
else{
$linea->$fieldName = $fieldValue;
}
$linea->user_updated_id = auth()->user()->id;
$linea->updated_at = date('Y-m-d H:i:s');
$model_linea->update($id, $linea->toArray());
$data = [
'success' => true,
'message' => lang('Basic.global.updateSuccess', [lang('Basic.global.record')]) . '.',
];
return $this->respond($data);
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function addLineasIva(){
if ($this->request->isAJAX()) {
$albaran_id = $this->request->getPost('albaranId');
$model_linea = model('App\Models\Albaranes\AlbaranLineaModel');
$lineas_albaran = $model_linea->where('albaran_id', $albaran_id)->findAll();
$iva_reducido = 0;
$iva_no_reducido = 0;
foreach ($lineas_albaran as $linea) {
if($linea->iva_reducido == 1) {
$iva_reducido += round(floatval($linea->total)*0.04, 2);
} else {
$iva_no_reducido += round(floatval($linea->total)*0.21, 2);
}
}
$iva_reducido = round($iva_reducido, 2);
$iva_no_reducido = round($iva_no_reducido, 2);
if($iva_reducido > 0) {
$linea = [
'albaran_id' => $albaran_id,
'titulo' => lang('Albaran.iva4'),
'total' => round($iva_reducido, 2),
'user_created_id' => auth()->user()->id,
'user_updated_id' => auth()->user()->id
];
$model_linea->insert($linea);
}
if($iva_no_reducido > 0) {
$linea = [
'albaran_id' => $albaran_id,
'titulo' => lang('Albaran.iva21'),
'total' => round($iva_no_reducido, 2),
'user_created_id' => auth()->user()->id,
'user_updated_id' => auth()->user()->id
];
$model_linea->insert($linea);
}
$data = [
'success' => true,
'message' => lang('Basic.global.updateSuccess', [lang('Basic.global.record')]) . '.',
];
return $this->respond($data);
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function addBlankLineaAlbaran(){
if ($this->request->isAJAX()) {
$albaran_id = $this->request->getPost('albaranId');
$model_linea = model('App\Models\Albaranes\AlbaranLineaModel');
$linea = [
'albaran_id' => $albaran_id,
'user_created_id' => auth()->user()->id,
'user_updated_id' => auth()->user()->id
];
$id_linea = $model_linea->insert($linea);
$data = $model_linea->find($id_linea);
$data = [
'success' => true,
];
return $this->respond($data);
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function borrarLinea()
{
if ($this->request->isAJAX()) {
$model_linea = model('App\Models\Albaranes\AlbaranLineaModel');
$reqData = $this->request->getPost();
$id = $reqData['linea'] ?? 0;
$id = filter_var($id, FILTER_SANITIZE_URL);
$albaranLineaEntity = $model_linea->find($id);
if ($albaranLineaEntity == false):
$message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Pedidos.albaran')), $id]);
$data = [
'success' => false,
'error' => $message,
];
return $this->respond($data);
endif;
$successfulResult = $model_linea->skipValidation(true)->update($id, ['deleted_at' => date('Y-m-d H:i:s')]);
if ($successfulResult):
$data = [
'success' => true,
];
else:
$data = [
'success' => false,
'error' => lang('Basic.global.deleteError', [lang('Basic.global.record')]) . '.',
];
endif;
return $this->respond($data);
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function borrarAlbaran()
{
if ($this->request->isAJAX()) {
$id = $this->request->getPost('albaranId');
$model_linea = model('App\Models\Albaranes\AlbaranLineaModel');
$model_linea->where('albaran_id', $id)->delete();
$this->model->where('id', $id)->delete();
$data = [
'success' => true
];
return $this->respond($data);
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
}

View File

@ -4,9 +4,11 @@ namespace App\Controllers\Logistica;
use App\Controllers\BaseController;
use App\Services\ImpresoraEtiquetaService;
use App\Services\LogisticaService;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
use Hermawan\DataTables\DataTable;
class LogisticaController extends BaseController
{
@ -15,11 +17,22 @@ class LogisticaController extends BaseController
protected string $locale;
protected array $viewData;
protected static $controllerSlug = 'logistica';
protected static $viewPath = 'themes/vuexy/form/logistica/';
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
$this->impresoraEtiquetaService = service('impresora_etiqueta');
$this->locale = session()->get('lang');
$this->viewData['pageTitle'] = lang('Logistica.logistica');
// Breadcrumbs
$this->viewData['breadcrumb'] = [
['title' => lang("App.menu_logistica"), 'route' => "javascript:void(0);", 'active' => false],
];
parent::initController($request, $response, $logger);
}
public function print_test_label()
@ -28,4 +41,282 @@ class LogisticaController extends BaseController
$responseMessage = $etiquetaData["status"] ? "OK" : "ERROR";
return $this->response->setJSON(["message" => $responseMessage, "data" => $etiquetaData, "status" => $etiquetaData["status"]]);
}
public function panel()
{
$viewData = [
'currentModule' => static::$controllerSlug,
'boxTitle' => lang('Logistica.panel'),
'pageSubTitle' => 'Panel',
'usingServerSideDataTable' => true,
];
$viewData = array_merge($this->viewData, $viewData); // merge any possible values from the parent controller class
return view(static::$viewPath . 'viewPanelLogistica', $viewData);
}
public function selectorEnvios($tipoEnvio = null)
{
$viewData = [
'currentModule' => static::$controllerSlug,
'boxTitle' => lang('Logistica.envioSimpleMultiple'),
'usingServerSideDataTable' => true,
'tipoEnvio' => $tipoEnvio,
];
$viewData = array_merge($this->viewData, $viewData); // merge any possible values from the parent controller class
return view(static::$viewPath . 'viewLogisticaSelectEnvios', $viewData);
}
public function searchPedidoOrISBN($search = "", $envio_id = null)
{
if (empty($search)) {
$result = [
'status' => false,
'message' => lang('Logistica.errors.noDataToFind'),
];
return $this->response->setJSON($result);
}
$result = LogisticaService::findPedidoOrISBN($search);
return $this->response->setJSON($result);
}
public function selectAddEnvioLinea()
{
if ($this->request->isAJAX()) {
$query = LogisticaService::findLineaEnvioPorEnvio($this->request->getGet('envio'));
if ($this->request->getGet("q")) {
$query->groupStart()
->orLike("p.id", $this->request->getGet("q"))
->orLike("pr.titulo", $this->request->getGet("q"))
->groupEnd();
}
$result = $query->orderBy("name", "asc")->get()->getResultObject();
return $this->response->setJSON($result);
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function addEnvioLinea()
{
if ($this->request->isAJAX()) {
$pedido_id = $this->request->getGet('pedido_id');
$envio_id = $this->request->getGet('envio_id');
$envioModel = model('App\Models\Logistica\EnvioModel');
$direccion = $envioModel->find($envio_id)->direccion;
$result = LogisticaService::addLineaEnvio($envio_id, $pedido_id, $direccion);
return $this->response->setJSON($result);
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function datatable_envios()
{
$model = model('App\Models\Logistica\EnvioModel');
$q = $model->getDatatableQuery();
$result = DataTable::of($q)
->edit(
"finalizado",
function ($row, $meta) {
if ($row->finalizado == 1)
return '<i class="ti ti-check"></i>';
else
return '<i class="ti ti-x"></i>';
}
)
->add("action", callback: function ($q) {
return '
<div class="btn-group btn-group-sm">
<a href="javascript:void(0);"><i class="ti ti-eye ti-sm btn-edit mx-2" data-id="' . $q->id . '"></i></a>
</div>
';
});
return $result->toJson(returnAsObject: true);
}
public function editEnvio($id = null)
{
if (empty($id)) {
return redirect()->to(base_url('logistica/selectEnvios/simple'))->with('error', lang('Logistica.errors.noEnvio'));
}
$model = model('App\Models\Logistica\EnvioModel');
$envioEntity = $model->select('envios.*, lg_paises.nombre as pais')
->join('lg_paises', 'lg_paises.id = envios.pais_id', 'left')
->where('envios.id', $id)
->first();
if (empty($envioEntity)) {
return redirect()->to(base_url('logistica/selectEnvios/simple'))->with('error', lang('Logistica.errors.noEnvio'));
}
$viewData = [
'currentModule' => static::$controllerSlug,
'boxTitle' => '<i class="ti ti-truck ti-xl"></i>' . ' ' . lang('Logistica.envio') . ' [' . $envioEntity->id . ']: ' . $envioEntity->direccion,
'usingServerSideDataTable' => true,
'envioEntity' => $envioEntity,
];
$viewData = array_merge($this->viewData, $viewData); // merge any possible values from the parent controller class
return view(static::$viewPath . 'viewEnvioEditForm', $viewData);
}
public function updateCajasEnvio()
{
if ($this->request->isAJAX()) {
$id = $this->request->getPost('id');
$cajas = $this->request->getPost('cajas');
$model = model('App\Models\Logistica\EnvioModel');
$result = $model->update($id, [
'cajas' => $cajas,
]);
return $this->response->setJSON([
"status" => $result,
]);
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function datatable_enviosEdit($idEnvio)
{
$model = model('App\Models\Logistica\EnvioLineaModel');
$q = $model->getDatatableQuery($idEnvio);
$result = DataTable::of($q)
->add(
"rowSelected",
callback: function ($q) {
return '<input type="checkbox" class="form-check-input checkbox-linea-envio" name="row_selected[]" value="' . $q->id . '">';
}
)
->edit(
"pedido",
function ($row, $meta) {
return '<a href="' . base_url('pedidos/edit/' . $row->pedido) . '" target="_blank">' . $row->pedido . '</a>';
}
)
->edit(
"presupuesto",
function ($row, $meta) {
return '<a href="' . base_url('presupuestoadmin/edit/' . $row->presupuesto) . '" target="_blank">' . $row->presupuesto . '</a>';
}
)
->edit(
"cajas",
function ($row, $meta) {
return '<input type="number" class="form-control input-lineas input-cajas text-center"
data-id="'. $row->id.'" data-name="cajas" value="' . $row->cajas . '">';
}
)->edit(
"unidadesEnvio",
function ($row, $meta) {
return '<input type="number" class="form-control input-lineas input-unidades text-center"
data-id="'. $row->id.'" data-name="unidades_envio" value="' . $row->unidadesEnvio . '">';
}
)
->edit('cajasRaw', function ($row) {
return is_null($row->cajas) ? '__SIN__ASIGNAR__' : $row->cajas;
});
return $result->toJson(returnAsObject: true);
}
public function setCajaLinea()
{
if ($this->request->isAJAX()) {
$id = $this->request->getPost('id');
$caja = $this->request->getPost('caja');
$model = model('App\Models\Logistica\EnvioLineaModel');
$result = $model->update($id, [
'cajas' => $caja,
]);
return $this->response->setJSON([
"status" => $result,
]);
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function deleteLineas()
{
if ($this->request->isAJAX()) {
$ids = $this->request->getPost('ids');
$model = model('App\Models\Logistica\EnvioLineaModel');
$result = $model->delete($ids);
return $this->response->setJSON([
"status" => $result,
]);
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function updateLineaEnvio()
{
$id = $this->request->getPost('id');
$fieldName = $this->request->getPost('name');
$fieldValue = $this->request->getPost('value');
if (!$id || !$fieldName || ($fieldName=='unidades_envio' && !$fieldValue)) {
return $this->response->setJSON([
'status' => false,
'message' => 'Datos inválidos'
]);
}
$model = model('App\Models\Logistica\EnvioLineaModel');
$updated = $model->update($id, [
"" . $fieldName => $fieldValue==""? null: $fieldValue,
]);
return $this->response->setJSON([
'status' => $updated,
'message' => $updated ? 'Actualizado' : 'Error al actualizar'
]);
}
public function saveComments()
{
$id = $this->request->getPost('id');
$comments = $this->request->getPost('comentarios');
if (!$id || !$comments) {
return $this->response->setJSON([
'status' => false,
'message' => 'Datos inválidos'
]);
}
$model = model('App\Models\Logistica\EnvioModel');
$updated = $model->update($id, [
'comentarios' => $comments,
]);
return $this->response->setJSON([
'status' => $updated,
'message' => $updated ? 'Actualizado' : 'Error al actualizar'
]);
}
}

View File

@ -11,8 +11,8 @@ class PrintAlbaranes extends BaseController
public function index($albaran_id)
{
$albaranModel = model('App\Models\Pedidos\AlbaranModel');
$lineasAlbaranModel = model('App\Models\Pedidos\AlbaranLineaModel');
$albaranModel = model('App\Models\Albaranes\AlbaranModel');
$lineasAlbaranModel = model('App\Models\Albaranes\AlbaranLineaModel');
$data['albaran'] = $albaranModel->getResourceForPdf($albaran_id)->get()->getRow();
$data['albaranLineas'] = $lineasAlbaranModel->getResourceForPdf($albaran_id)->get()->getResultObject();
@ -25,14 +25,22 @@ class PrintAlbaranes extends BaseController
{
// Cargar modelos
$albaranModel = model('App\Models\Pedidos\AlbaranModel');
$lineasAlbaranModel = model('App\Models\Pedidos\AlbaranLineaModel');
$albaranModel = model('App\Models\Albaranes\AlbaranModel');
$lineasAlbaranModel = model('App\Models\Albaranes\AlbaranLineaModel');
// Informacion del presupuesto
$data['albaran'] = $albaranModel->getResourceForPdf($albaran_id)->get()->getRow();
$data['albaranLineas'] = $lineasAlbaranModel->getResourceForPdf($albaran_id)->get()->getResultObject();
// Obtener contenido HTML de la vista
$html = view(getenv('theme.path') . 'pdfs/albaran', $data);
// Cargar CSS desde archivo local
$css = file_get_contents(FCPATH . 'themes/vuexy/css/pdf.albaran.css');
// Combinar CSS y HTML
$html_con_css = "<style>$css</style>" . $html;
// Crear una instancia de Dompdf
$options = new \Dompdf\Options();
$options->set('isHtml5ParserEnabled', true);
@ -41,7 +49,7 @@ class PrintAlbaranes extends BaseController
$dompdf = new \Dompdf\Dompdf($options);
// Contenido HTML del documento
$dompdf->loadHtml(view(getenv('theme.path').'pdfs/albaran', $data));
$dompdf->loadHtml($html_con_css);
// Establecer el tamaño del papel
$dompdf->setPaper('A4', 'portrait');

View File

@ -1,388 +0,0 @@
<?php
namespace App\Controllers\Pedidos;
use App\Entities\Pedidos\AlbaranEntity;
use App\Models\Pedidos\AlbaranModel;
class Albaran extends \App\Controllers\BaseResourceController
{
protected $modelName = AlbaranModel::class;
protected $format = 'json';
protected static $singularObjectNameCc = 'albaran';
protected static $singularObjectName = 'Albaran';
protected static $pluralObjectName = 'Albaranes';
protected static $controllerSlug = 'albaran';
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
}
public function index()
{
}
public function delete($id = null)
{
if ($this->request->isAJAX()) {
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$model_linea = model('App\Models\Pedidos\AlbaranLineaModel');
$model_linea->where('albaran_id', $id)->delete();
$this->model->where('id', $id)->delete();
$data = [
'error' => 0,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
}
else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function addLinea($albaran_id){
if ($this->request->isAJAX()) {
$model_linea = model('App\Models\Pedidos\AlbaranLineaModel');
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
// si es un post, es el iva
if($this->request->getPost()){
$reqData = $this->request->getPost();
$albaran_id = $reqData['albaran_id'] ?? 0;
$albaran = $this->model->find($albaran_id);
if($albaran == false){
$data = [
'error' => 'Albaran no encontrado',
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
}
$presupuesto_model = model('App\Models\Presupuestos\PresupuestoModel');
$presupuesto = $presupuesto_model->find($albaran->presupuesto_id);
if($presupuesto == false){
$data = [
'error' => 'Presupuesto no encontrado',
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
}
$iva_reducido = $presupuesto->iva_reducido;
$lineas = $model_linea->where('albaran_id', $albaran_id)->findAll();
$total = 0;
foreach($lineas as $linea){
$total += $linea->total;
}
$iva = $iva_reducido? $total * 4.0 / 100: $total * 21.0 / 100;
$data_linea= [
'albaran_id' => $albaran_id,
'titulo' => $iva_reducido?lang('Pedidos.iva4'):lang('Pedidos.iva21'),
'cantidad' => 1,
'precio_unidad' => round($iva,2),
'total' => round($iva,2),
'user_created_id' => auth()->user()->id,
'user_updated_id' => auth()->user()->id
];
$id_linea = $model_linea->insert($data_linea);
$linea = $model_linea->find($id_linea);
$data = [
'error' => 0,
'data' => $linea,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
}
else{
$linea = [
'albaran_id' => $albaran_id,
'user_created_id' => auth()->user()->id,
'user_updated_id' => auth()->user()->id
];
$id_linea = $model_linea->insert($linea);
$data = $model_linea->find($id_linea);
$data = [
'error' => 0,
'data' => $data,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
}
}
else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function add()
{
if ($this->request->isAJAX()) {
$user = auth()->user()->id;
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$reqData = $this->request->getPost();
$pedido_id = $reqData['pedido_id'] ?? 0;
$presupuestos_id = $reqData['presupuestos_id'] ?? 0;
$return_data = $this->model->generarAlbaranes($pedido_id, $presupuestos_id, $user);
$data = [
'data' => $return_data,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
}
else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function update($id = null){
if ($this->request->isAJAX()) {
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
if ($id == null) :
$data = [
'error' => 2,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
endif;
$id = filter_var($id, FILTER_SANITIZE_URL);
$albaranEntity = $this->model->find($id);
if ($albaranEntity == false) :
$message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Pedidos.albaran')), $id]);
$data = [
'error' => $message,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
endif;
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');
$postData = $this->request->getPost();
$sanitizedData = $this->sanitized($postData, $nullIfEmpty);
// JJO
$sanitizedData['user_updated_id'] = auth()->user()->id;
$noException = true;
if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) :
if ($this->canValidate()) :
try {
$successfulResult = $this->model->skipValidation(true)->update($id, $sanitizedData);
} catch (\Exception $e) {
$noException = false;
$this->dealWithException($e);
}
else:
$this->viewData['warningMessage'] = lang('Basic.global.formErr1', [mb_strtolower(lang('Pedidos.albaran'))]);
$this->session->setFlashdata('formErrors', $this->model->errors());
endif;
$albaranEntity->fill($sanitizedData);
endif;
if ($noException && $successfulResult) :
$id = $albaranEntity->id ?? $id;
$message = lang('Basic.global.updateSuccess', [lang('Basic.global.record')]) . '.';
$data = [
'error' => 0,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
endif; // $noException && $successfulResult
endif; // ($requestMethod === 'post')
$data = [
'error' => 1,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
}
else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function updateLinea($id = null){
if ($this->request->isAJAX()) {
$model_linea = model('App\Models\Pedidos\AlbaranLineaModel');
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
if ($id == null) :
$data = [
'error' => 2,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
endif;
$id = filter_var($id, FILTER_SANITIZE_URL);
$albaranEntity = $model_linea->find($id);
if ($albaranEntity == false) :
$message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Pedidos.albaran')), $id]);
$data = [
'error' => $message,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
endif;
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');
$postData = $this->request->getPost();
$sanitizedData = $this->sanitized($postData, $nullIfEmpty);
// JJO
$sanitizedData['user_updated_id'] = auth()->user()->id;
$noException = true;
if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) :
if ($this->canValidate()) :
try {
$successfulResult = $model_linea->skipValidation(true)->update($id, $sanitizedData);
} catch (\Exception $e) {
$noException = false;
$this->dealWithException($e);
}
else:
$this->viewData['warningMessage'] = lang('Basic.global.formErr1', [mb_strtolower(lang('Pedidos.albaran'))]);
$this->session->setFlashdata('formErrors', $model_linea->errors());
endif;
$albaranEntity->fill($sanitizedData);
endif;
if ($noException && $successfulResult) :
$id = $albaranEntity->id ?? $id;
$message = lang('Basic.global.updateSuccess', [lang('Basic.global.record')]) . '.';
$data = [
'error' => 0,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
endif; // $noException && $successfulResult
endif; // ($requestMethod === 'post')
$data = [
'error' => 1,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
}
else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function borrarLinea(){
if ($this->request->isAJAX()) {
$model_linea = model('App\Models\Pedidos\AlbaranLineaModel');
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$reqData = $this->request->getPost();
$id = $reqData['id'] ?? 0;
$id = filter_var($id, FILTER_SANITIZE_URL);
$albaranLineaEntity = $model_linea->find($id);
if ($albaranLineaEntity == false) :
$message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Pedidos.albaran')), $id]);
$message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Pedidos.albaran')), $id]);
$data = [
'error' => $message,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
endif;
$successfulResult = $model_linea->skipValidation(true)->update($id, ['deleted_at' => date('Y-m-d H:i:s')]);
if ($successfulResult) :
$data = [
'error' => 0,
$csrfTokenName => $newTokenHash
];
else:
$data = [
'error' => 1,
$csrfTokenName => $newTokenHash
];
endif;
return $this->respond($data);
}
else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function getAlbaranes($pedido_id = null){
if ($this->request->isAJAX()) {
$model_linea = model('App\Models\Pedidos\AlbaranLineaModel');
$newTokenHash = csrf_hash();
$csrfTokenName = csrf_token();
$returnData = [];
$albaranes = $this->model->asArray()->where('pedido_id', $pedido_id)->findAll();
foreach($albaranes as $albaran){
$albaran['fecha_albaran'] = $albaran['updated_at'];
array_push($returnData,
[
'albaran' => $albaran,
'lineas' => $model_linea->asArray()->where('albaran_id', $albaran['id'])->findAll()]
);
}
$data = [
'data' => $returnData,
$csrfTokenName => $newTokenHash
];
return $this->respond($data);
}
else {
return $this->failUnauthorized('Invalid request', 403);
}
}
}

View File

@ -382,6 +382,16 @@ class Presupuestoadmin extends \App\Controllers\BaseResourceController
'descripcion' => $linea_pedido->concepto
]);
// se actualiza el totalizador del pedido
$total_tirada = $pedidoModel
->selectSum('cantidad')
->where('pedido_id', $idPedido)
->first()->cantidad;
$pedidoModel = model('App\Models\Pedidos\PedidoModel');
$pedidoModel->update($idPedido, [
'total_tirada' => $total_tirada
]);
// se actualiza la factura
$linea_pedido = $this->model->generarLineaPedido($id, true, $idPedido)[0];
$facturaLineaModel = model('App\Models\Facturas\FacturaLineaModel');

View File

@ -0,0 +1,104 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class CreateEnviosTable extends Migration
{
public function up()
{
$this->forge->addField([
'id' => [
'type' => 'INT',
'unsigned' => true,
'auto_increment' => true,
],
'finalizado' => [
'type' => 'TINYINT',
'constraint' => 1,
'default' => 0,
],
'codigo_seguimiento' => [
'type' => 'VARCHAR',
'constraint' => 100,
'null' => true,
],
'proveedor_id' => [
'type' => 'INT',
'unsigned' => true,
'null' => true,
],
'comentarios' => [
'type' => 'TEXT',
'null' => true,
],
'att' => [
'type' => 'VARCHAR',
'constraint' => 100,
'null' => true,
],
'direccion' => [
'type' => 'VARCHAR',
'constraint' => 300,
'null' => true,
],
'ciudad' => [
'type' => 'VARCHAR',
'constraint' => 100,
'null' => true,
],
'cp' => [
'type' => 'VARCHAR',
'constraint' => 10,
'null' => true,
],
'email' => [
'type' => 'VARCHAR',
'constraint' => 150,
'null' => true,
],
'telefono' => [
'type' => 'VARCHAR',
'constraint' => 60,
'null' => true,
],
'pais_id' => [
'type' => 'INT',
'unsigned' => true,
'null' => true,
],
'mostrar_precios' => [
'type' => 'TINYINT',
'constraint' => 1,
'default' => 0,
],
'mostrar_iva' => [
'type' => 'TINYINT',
'constraint' => 1,
'default' => 0,
],
'created_at' => [
'type' => 'TIMESTAMP',
'null' => false,
'default' => '0000-00-00 00:00:00',
],
'updated_at' => [
'type' => 'TIMESTAMP',
'null' => false,
'default' => '0000-00-00 00:00:00',
],
]);
$this->forge->addKey('id', true);
$this->forge->addForeignKey('proveedor_id', 'lg_proveedores', 'id', 'SET NULL', 'SET NULL');
$this->forge->addForeignKey('pais_id', 'lg_paises', 'id', 'SET NULL', 'SET NULL');
$this->forge->createTable('envios');
}
public function down()
{
$this->forge->dropTable('envios');
}
}

View File

@ -0,0 +1,29 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
use CodeIgniter\Database\RawSql;
class AddMEnvioColumns extends Migration
{
public function up()
{
$this->forge->addColumn("envios",
["multienvio" => [
"type" => "TINYINT",
"unsigned" => true,
"null" => false,
"default" => 0,
]]
);
}
public function down()
{
$this->forge->dropColumn("envios", ['multienvio']);
}
}

View File

@ -0,0 +1,41 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class AddEnviosLineas extends Migration
{
public function up()
{
$this->forge->addField([
'id' => ['type' => 'INT', 'auto_increment' => true],
'envio_id' => ['type' => 'INT', 'unsigned' => true],
'pedido_id' => ['type' => 'INT', 'unsigned' => true],
'presupuesto_id' => ['type' => 'INT', 'unsigned' => true],
'unidades_envio' => ['type' => 'INT', 'default' => 0],
'unidades_total' => ['type' => 'INT', 'default' => 0],
'cajas' => ['type' => 'INT', 'default' => 0],
'unidades_cajas' => ['type' => 'INT', 'default' => 0],
'created_at' => ['type' => 'DATETIME', 'null' => true],
'updated_at' => ['type' => 'DATETIME', 'null' => true],
'created_by' => ['type' => 'INT', 'unsigned' => true, 'null' => true],
'updated_by' => ['type' => 'INT', 'unsigned' => true, 'null' => true],
]);
$this->forge->addKey('id', true); // Primary Key
// Foreign Keys
$this->forge->addForeignKey('presupuesto_id', 'presupuestos', 'id', 'CASCADE', 'CASCADE');
$this->forge->addForeignKey('pedido_id', 'pedidos', 'id', 'CASCADE', 'CASCADE');
$this->forge->addForeignKey('created_by', 'users', 'id', 'SET NULL', 'CASCADE');
$this->forge->addForeignKey('updated_by', 'users', 'id', 'SET NULL', 'CASCADE');
$this->forge->createTable('envios_lineas');
}
public function down()
{
$this->forge->dropTable('envios_lineas');
}
}

View File

@ -0,0 +1,98 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class ModifyAlbaranesAndAlbaranesLineas extends Migration
{
public function up()
{
// --- Tabla albaranes ---
$this->forge->dropColumn('albaranes', [
'pedido_id',
'presupuesto_id',
'presupuesto_direccion_id',
'total'
]);
$this->forge->addColumn('albaranes', [
'fecha_albaran' => [
'type' => 'DATE',
'null' => true,
'after' => 'numero_albaran'
],
'envio_id' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => true,
'null' => true,
'after' => 'fecha_albaran'
]
]);
// Añadir foreign key a envios con ON DELETE SET NULL
$this->db->query('ALTER TABLE `albaranes`
ADD CONSTRAINT `fk_albaranes_envio_id` FOREIGN KEY (`envio_id`)
REFERENCES `envios`(`id`) ON DELETE SET NULL ON UPDATE CASCADE');
// --- Tabla albaranes_lineas ---
$this->forge->dropColumn('albaranes_lineas', ['cajas', 'ejemplares_por_caja']);
$this->forge->addColumn('albaranes_lineas', [
'iva_reducido' => [
'type' => 'TINYINT',
'constraint' => 1,
'default' => 0,
'null' => false,
'after' => 'precio_unidad'
]
]);
}
public function down()
{
// Deshacer cambios tabla albaranes
$this->forge->dropForeignKey('albaranes', 'fk_albaranes_envio_id');
$this->forge->dropColumn('albaranes', ['envio_id', 'fecha_albaran']);
$this->forge->addColumn('albaranes', [
'pedido_id' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => true,
'null' => true,
],
'presupuesto_id' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => true,
'null' => true,
],
'presupuesto_direccion_id' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => true,
'null' => true,
],
'total' => [
'type' => 'DOUBLE',
'null' => true,
],
]);
// Deshacer cambios tabla albaranes_lineas
$this->forge->dropColumn('albaranes_lineas', ['iva_reducido']);
$this->forge->addColumn('albaranes_lineas', [
'cajas' => [
'type' => 'INT',
'null' => true,
],
'ejemplares_por_caja' => [
'type' => 'INT',
'null' => true,
],
]);
}
}

View File

@ -0,0 +1,29 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class AddClienteIdToEnvios extends Migration
{
public function up()
{
$this->forge->addColumn('envios', [
'cliente_id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true, // IMPORTANTE
'null' => true,
'after' => 'id',
],
]);
$this->db->query('ALTER TABLE envios ADD CONSTRAINT fk_envios_cliente FOREIGN KEY (cliente_id) REFERENCES clientes(id) ON DELETE SET NULL ON UPDATE CASCADE');
}
public function down()
{
$this->db->query('ALTER TABLE envios DROP FOREIGN KEY fk_envios_cliente');
$this->forge->dropColumn('envios', 'cliente_id');
}
}

View File

@ -0,0 +1,32 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class RenameCajasNullable extends Migration
{
public function up()
{
$this->forge->modifyColumn('envios_lineas', [
'cajas' => [
'type' => 'INT',
'constraint' => 11,
'null' => true,
'default' => null,
],
]);
}
public function down()
{
$this->forge->modifyColumn('envios_lineas', [
'cajas' => [
'type' => 'INT',
'constraint' => 11,
'null' => false,
'default' => 0,
],
]);
}
}

View File

@ -0,0 +1,90 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class UpdateEnviosAlbaranes extends Migration
{
public function up()
{
// 1. Quitar columnas de envios_lineas
$this->forge->dropColumn('envios_lineas', ['cajas', 'unidades_cajas']);
// 2. Añadir columna 'cajas' en envios
$this->forge->addColumn('envios', [
'cajas' => [
'type' => 'INT',
'constraint' => 11,
'default' => 0,
'after' => 'comentarios'
]
]);
// 2. Quitar columna multienvio de envios
$this->forge->dropColumn('envios', 'multienvio');
// 3. Añadir columna 'cajas' en albaranes
$this->forge->addColumn('albaranes', [
'cajas' => [
'type' => 'INT',
'constraint' => 11,
'default' => 0,
'after' => 'envio_id'
]
]);
// 4. Añadir columna 'pedido_linea_id' a albaranes_lineas
$this->forge->addColumn('albaranes_lineas', [
'pedido_linea_id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
'null' => true,
'after' => 'albaran_id'
]
]);
// 5. Foreign key a pedidos_lineas
$this->db->query("
ALTER TABLE albaranes_lineas
ADD CONSTRAINT fk_albaranes_lineas_pedido_linea
FOREIGN KEY (pedido_linea_id) REFERENCES pedidos_linea(id)
ON DELETE SET NULL ON UPDATE CASCADE
");
}
public function down()
{
// Revertir cajas en envios_lineas
$this->forge->addColumn('envios_lineas', [
'cajas' => [
'type' => 'INT',
'constraint' => 11,
'null' => true,
],
'unidades_cajas' => [
'type' => 'INT',
'constraint' => 11,
'null' => true,
]
]);
$this->forge->addColumn('envios', [
'multienvio' => [
'type' => 'TINYINT',
'constraint' => 3,
'unsigned' => true,
'default' => 0
]
]);
// Quitar columnas añadidas
$this->forge->dropColumn('envios', 'cajas');
$this->forge->dropColumn('albaranes', 'cajas');
// Quitar foreign y columna pedido_linea_id
$this->db->query("ALTER TABLE albaranes_lineas DROP FOREIGN KEY fk_albaranes_lineas_pedido_linea");
$this->forge->dropColumn('albaranes_lineas', 'pedido_linea_id');
}
}

View File

@ -0,0 +1,28 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class FixDeletedAtToDatetime extends Migration
{
public function up()
{
// Cambia los tipos de deleted_at a DATETIME NULL si existen
$tablas = ['albaranes', 'albaranes_lineas', 'envios', 'envios_lineas'];
foreach ($tablas as $tabla) {
$this->db->query("ALTER TABLE {$tabla} MODIFY COLUMN deleted_at DATETIME NULL");
}
}
public function down()
{
// Opcional: puedes restaurar como TIMESTAMP NULL si lo deseas
$tablas = ['albaranes', 'albaranes_lineas', 'envios', 'envios_lineas'];
foreach ($tablas as $tabla) {
$this->db->query("ALTER TABLE {$tabla} MODIFY COLUMN deleted_at TIMESTAMP NULL");
}
}
}

View File

@ -1,5 +1,5 @@
<?php
namespace App\Entities\Pedidos;
namespace App\Entities\Albaranes;
use CodeIgniter\Entity;
@ -7,28 +7,27 @@ class AlbaranEntity extends \CodeIgniter\Entity\Entity
{
protected $attributes = [
'id' => null,
'pedido_id' => null,
'presupuesto_id' => null,
'presupuesto_direccion_id' => null,
'envio_id' => null,
'cliente_id' => null,
'serie_id' => null,
'numero_albaran' => null,
'mostrar_precios' => null,
'total' => null,
'direccion_albaran' => null,
'att_albaran' => null,
'fecha_albaran' => null,
'user_created_id' => null,
'user_updated_id' => null,
'created_at' => null,
'updated_at' => null,
'deleted_at' => null,
'cajas' => null,
];
protected $dates = ['created_at', 'updated_at', 'deleted_at'];
protected $casts = [
'id' => 'integer',
'pedido_id' => '?integer',
'envio_id' => '?integer',
'presupuesto_id' => '?integer',
'presupuesto_direccion_id' => '?integer',
'cliente_id' => '?integer',
@ -40,6 +39,7 @@ class AlbaranEntity extends \CodeIgniter\Entity\Entity
'att_albaran' => '?string',
'user_created_id' => 'integer',
'user_updated_id' => 'integer',
'fecha_albaran' => '?datetime',
];
// Agrega tus métodos personalizados aquí

View File

@ -1,5 +1,5 @@
<?php
namespace App\Entities\Pedidos;
namespace App\Entities\Albaranes;
use CodeIgniter\Entity;
@ -8,14 +8,14 @@ class AlbaranLineaEntity extends \CodeIgniter\Entity\Entity
protected $attributes = [
'id' => null,
'albaran_id' => null,
'pedido_linea_id' => null,
'titulo' => null,
'isbn' => null,
'ref_cliente' => null,
'cantidad' => null,
'cajas' => null,
'ejemplares_por_caja' => null,
'precio_unidad' => null,
'total' => null,
'iva_reducido' => null,
'user_created_id' => null,
'user_updated_id' => null,
'created_at' => null,
@ -26,14 +26,14 @@ class AlbaranLineaEntity extends \CodeIgniter\Entity\Entity
protected $casts = [
'id' => 'integer',
'albaran_id' => '?integer',
'pedido_linea_id' => '?integer',
'titulo' => 'string',
'isbn' => '?string',
'ref_cliente' => '?string',
'cantidad' => '?integer',
'cajas' => '?integer',
'ejemplares_por_caja' => '?integer',
'precio_unidad' => 'float',
'total' => 'float',
'iva_reducido' => '?boolean',
'user_created_id' => 'integer',
'user_updated_id' => 'integer',
];

View File

@ -0,0 +1,35 @@
<?php
namespace App\Entities\Logistica;
use CodeIgniter\Entity\Entity;
class EnvioEntity extends Entity
{
protected $attributes = [
'finalizado' => 0,
'mostrar_precios' => 0,
'mostrar_iva' => 0,
];
protected $casts = [
'id' => 'int',
'finalizado' => 'boolean',
'codigo_seguimiento'=> 'string',
'proveedor_id' => 'int',
'cliente_id' => 'int',
'comentarios' => 'string',
'att' => 'string',
'direccion' => 'string',
'ciudad' => 'string',
'cp' => 'string',
'email' => 'string',
'telefono' => 'string',
'pais_id' => 'int',
'mostrar_precios' => 'boolean',
'mostrar_iva' => 'boolean',
'created_at' => 'datetime',
'updated_at' => 'datetime',
'cajas' => 'int',
];
}

View File

@ -0,0 +1,21 @@
<?php
namespace App\Entities\Logistica;
use CodeIgniter\Entity\Entity;
class EnvioLineaEntity extends Entity
{
protected $casts = [
'id' => 'int',
'envio_id' => 'int',
'pedido_id' => 'int',
'presupuesto_id' => 'int',
'unidades_envio' => 'int',
'unidades_total' => 'int',
'created_by' => 'int',
'updated_by' => 'int',
'created_at' => 'datetime',
'updated_at' => 'datetime',
];
}

View File

@ -0,0 +1,31 @@
<?php
return [
'fechaCreacion' => 'Fecha de creación',
"fechaAlbaran" => 'Fecha de albarán',
'numEnvio' => 'Número de envío',
'cliente' => 'Cliente',
'albaran' => 'Albarán',
'att' => 'Att',
'direccion' => 'Dirección',
'cajas' => 'Cajas',
'unidades' => 'Unidades',
'titulo' => 'Título',
'ISBN' => 'ISBN',
'refCliente' => 'Ref. cliente',
'precioU' => 'Precio/Unidad',
'subtotal' => 'Subtotal',
'pedido' => 'Pedido',
'mostrarPrecios' => 'Mostrar precios',
'addIva' => 'Añadir IVA',
'nuevaLinea' => 'Nueva línea',
'imprimirAlbaran' => 'Imprimir albarán',
'borrarAlbaran' => 'Borrar albarán',
'borrarAlbaranConfirm' => '¿Está seguro de que desea borrar el albarán?',
'borrar' => 'Borrar',
'cancelar' => 'Cancelar',
'iva4' => 'IVA 4%',
'iva21' => 'IVA 21%',
];

View File

@ -9,4 +9,60 @@ return [
'etiquetasEnvio' => 'Etiquetas de envío',
'envioFerros' => 'Envío de ferros',
'cerrarOTauto' => 'Cerrar OT automáticamente',
'envioSimpleMultiple' => 'Envío simple/múltiple',
'nuevoEnvio' => 'Nuevo envío',
'buscadorPedidosTitle' => 'Código Pedido o ISBN',
'buscadorPedidosTitle2' => 'Código Pedido o título',
'listadoEnvios' => 'Listado de envíos',
'idEnvio' => 'ID Envío',
'numeroPedidos' => 'Nº Pedidos',
'numeroLineas' => 'Nº Líneas',
'att' => 'Att',
'direccion' => 'Dirección',
'ciudad' => 'Ciudad',
'pais' => 'País',
'cp' => 'CP',
'email' => 'Email',
'telefono' => 'Teléfono',
'finalizado' => 'Finalizado',
'acciones' => 'Acciones',
'backToPanel' => 'Volver al panel',
'no' => 'No',
'si' => 'Sí',
'envio' => 'Envío',
'addLineasEnvio' => 'Añadir líneas al envío',
'addLineasText'=> 'La siguiente lista muestra los envíos del cliente a la misma dirección de envío. Si desea añadir líneas a un envío existente, seleccione el envío y haga clic en "Añadir líneas al envío". Si desea crear un nuevo envío, haga clic en "Añadir".',
'add' => 'Añadir',
'datosEnvio' => 'Datos del envío',
'lineasEnvio' => 'Líneas del envío',
'comentariosEnvio' => 'Comentarios del envío',
'guardar' => 'Guardar',
'totales' => 'Totales',
'cajas' => 'Cajas',
'pedido' => 'Pedido',
'presupuesto' => 'Presupuesto',
'unidadesEnvio' => 'Unidades envío',
'unidadesEnviadas' => 'Unidades enviadas',
'titulo' => 'Título',
'unidadesTotales' => 'Total unidades',
'eliminar' => 'Eliminar',
'generarAlbaran' => 'Generar albarán',
'imprimirEtiquetas' => 'Imprimir etiquetas',
'buttonsActions' => 'Acciones sobre las filas seleccionadas',
'addCaja' => 'Añadir caja',
'numCaja' => 'Número de caja',
'selectAll' => 'Seleccionar todo',
'peso' => 'Peso (kg): ',
'unidadesTotalesFooter' => 'Unidades:',
'errors' => [
'noEnvio' => 'No se ha encontrado el envio',
'noDataToFind' => 'No se ha introducido ningún dato para buscar',
'notFound' => 'No se encuentra el pedido o ISBN, el pedido aún no se ha finalizado o no tiene envíos pendientes',
'noAddresses' => 'El pedido no tiene direcciones de envío',
],
];

View File

@ -0,0 +1,85 @@
<?php
namespace App\Models\Albaranes;
class AlbaranLineaModel extends \App\Models\BaseModel
{
protected $table = "albaranes_lineas";
/**
* Whether primary key uses auto increment.
*
* @var bool
*/
protected $useAutoIncrement = true;
protected $primaryKey = 'id';
protected $returnType = 'App\Entities\Albaranes\AlbaranLineaEntity';
protected $allowedFields = [
'albaran_id',
'pedido_linea_id',
'titulo',
'isbn',
'ref_cliente',
'cantidad',
'precio_unidad',
'total',
'iva_reducido',
'user_created_id',
'user_updated_id',
'created_at',
'updated_at',
'deleted_at',
];
protected $useSoftDeletes = true;
protected $useTimestamps = true;
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
protected $deletedField = 'deleted_at';
/**
* Get resource data for creating PDFs.
*
* @param string $search
*
* @return \CodeIgniter\Database\BaseBuilder
*/
public function getResourceForPdf($albaran_id = -1)
{
$builder = $this->db
->table($this->table . " t1")
->select(
"t1.id, t1.titulo as titulo, t1.isbn as isbn, t1.ref_cliente as ref_cliente,
t1.cantidad as unidades, t1.precio_unidad as precio_unidad, t1.iva_reducido as iva_reducido,
t1.total as total, pedidos.id AS pedido"
)
->join("pedidos_linea", "t1.pedido_linea_id = pedidos_linea.id", "left")
->join("pedidos", "pedidos_linea.pedido_id = pedidos.id", "left");
$builder->where("t1.deleted_at IS NULL");
$builder->where("t1.albaran_id", $albaran_id);
return $builder;
}
public function getDatatableQuery($albaran_id = null)
{
$builder = $this->db
->table($this->table . " t1")
->select(
"t1.id, t1.titulo as titulo, t1.isbn as isbn, t1.ref_cliente as ref_cliente,
t1.cantidad as unidades, t1.precio_unidad as precio_unidad, t1.iva_reducido as iva_reducido,
t1.total as total, pedidos.id AS pedido"
)
->join("pedidos_linea", "t1.pedido_linea_id = pedidos_linea.id", "left")
->join("pedidos", "pedidos_linea.pedido_id = pedidos.id", "left");
$builder->where("t1.deleted_at IS NULL");
$builder->where("t1.albaran_id", $albaran_id);
return $builder;
}
}

View File

@ -0,0 +1,206 @@
<?php
namespace App\Models\Albaranes;
class AlbaranModel extends \App\Models\BaseModel
{
protected $table = "albaranes";
/**
* Whether primary key uses auto increment.
*
* @var bool
*/
protected $useAutoIncrement = true;
protected $primaryKey = 'id';
protected $returnType = 'App\Entities\Albaranes\AlbaranEntity';
protected $allowedFields = [
'envio_id',
'cliente_id',
'serie_id',
'numero_albaran',
'mostrar_precios',
'direccion_albaran',
'fecha_albaran',
'att_albaran',
'user_created_id',
'user_updated_id',
'created_at',
'updated_at',
'deleted_at',
'cajas',
];
protected $useSoftDeletes = true;
protected $useTimestamps = true;
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
protected $deletedField = 'deleted_at';
public function generarAlbaranes($envio_id, $envio_lineas, $cajas)
{
$user_id = auth()->user()->id;
if (!$envio_id || !$envio_lineas) {
return [
'status' => false
];
}
// el albaran es para el mismo cliente, por lo que se obtiene el cliente_id de la primera_linea
$cliente_id = $this->db->table('envios_lineas')
->select('presupuestos.cliente_id')
->join('presupuestos', 'presupuestos.id = envios_lineas.presupuesto_id')
->where('envios_lineas.id', $envio_lineas[0])
->get()
->getRow()->cliente_id;
// se genera el numero de albaran
$model_series = model('App\Models\Configuracion\SeriesFacturasModel');
$serie = $model_series->find(11);
$numero_albaran = str_replace('{number}', $serie->next, $serie->formato);
$numero_albaran = str_replace('{year}', date("Y"), $numero_albaran);
$serie->next = $serie->next + 1;
$model_series->save($serie);
// Se genera el albaran con los datos del envio
$model_envio = model('App\Models\Logistica\EnvioModel');
$envio = $model_envio->find($envio_id);
$data = [
'envio_id' => $envio->id,
'cliente_id' => $cliente_id,
'serie_id' => 11, // Serie de albaranes
'numero_albaran' => $numero_albaran,
'mostrar_precios' => 0,
'direccion_albaran' => $envio->direccion,
'att_albaran' => $envio->att,
'user_created_id' => $user_id,
'cajas' => $cajas,
];
$id_albaran = $this->insert($data);
if(!$id_albaran) {
return [
'status' => false
];
}
// Se generan las lineas del albaran
$model_albaran_linea = model('App\Models\Albaranes\AlbaranLineaModel');
$albaran_linea = [];
foreach ($envio_lineas as $linea) {
$modelLineaEnvio = model('App\Models\Logistica\EnvioLineaModel');
$datosLinea = $this->db->table('envios_lineas')
->select('presupuestos.titulo as titulo, presupuestos.isbn as isbn, presupuestos.referencia_cliente as ref_cliente,
envios_lineas.unidades_envio as cantidad, presupuestos.total_precio_unidad as precio_unidad, presupuestos.iva_reducido as iva_reducido,
ROUND(envios_lineas.unidades_envio * presupuestos.total_precio_unidad, 2) as total, pedidos_linea.id as pedido_linea_id')
->join('presupuestos', 'presupuestos.id = envios_lineas.presupuesto_id')
->join('pedidos', 'pedidos.id = envios_lineas.pedido_id')
->join('pedidos_linea', 'pedidos_linea.pedido_id = pedidos.id')
->where('envios_lineas.id', $linea)
->get()
->getRow();
$linea = $modelLineaEnvio->find($linea);
if (!$linea) {
continue;
}
$albaran_linea = [
'albaran_id' => $id_albaran,
'titulo' => $datosLinea->titulo,
'isbn' => $datosLinea->isbn,
'ref_cliente' => $datosLinea->ref_cliente,
'cantidad' => $datosLinea->cantidad,
'precio_unidad' => $datosLinea->precio_unidad,
'iva_reducido' => $datosLinea->iva_reducido,
'total' => $datosLinea->total,
'user_created_id' => $user_id,
'user_updated_id' => $user_id,
'pedido_linea_id' => $datosLinea->pedido_linea_id,
];
$model_albaran_linea->insert($albaran_linea);
}
$albaran_data = $this->db->table('albaranes t1')
->select("
t1.id,
t1.att_albaran AS att,
t1.direccion_albaran AS direccion,
t1.envio_id,
t1.numero_albaran AS numero_albaran,
DATE_FORMAT(t1.created_at, '%d/%m/%Y') AS fecha_creacion,
DATE_FORMAT(t1.fecha_albaran, '%d/%m/%Y') AS fecha_albaran,
t1.mostrar_precios AS mostrar_precios,
t1.cajas AS cajas,
")
->where('t1.id', $id_albaran)
->get()
->getResultObject();
$modelCliente = model('App\Models\Clientes\ClienteModel');
$cliente = $modelCliente->find($cliente_id);
$albaran_data[0]->cliente = $cliente->nombre;
return [
'status' => true,
'albaran' => $albaran_data[0],
];
}
public function getAlbaranesEnvio($envio_id=null){
if (!$envio_id) {
return [];
}
$albaran_data = $this->db->table('albaranes t1')
->select("
t1.id,
t1.att_albaran AS att,
t1.direccion_albaran AS direccion,
t1.envio_id,
t1.numero_albaran AS numero_albaran,
DATE_FORMAT(t1.created_at, '%d/%m/%Y') AS fecha_creacion,
DATE_FORMAT(t1.fecha_albaran, '%d/%m/%Y') AS fecha_albaran,
t1.mostrar_precios AS mostrar_precios,
t2.nombre AS cliente,
t1.cajas AS cajas
")
->join('clientes t2', 't1.cliente_id = t2.id', 'left')
->where('t1.envio_id', $envio_id)
->where('t1.deleted_at IS NULL')
->get()
->getResultObject();
return $albaran_data;
}
/**
* Get resource data for creating PDFs.
*
* @param string $search
*
* @return \CodeIgniter\Database\BaseBuilder
*/
public function getResourceForPdf($albaran_id = -1)
{
$builder = $this->db
->table($this->table . " t1")
->select("
t1.id,
t1.att_albaran AS att,
t1.direccion_albaran AS direccion,
t1.envio_id,
t1.numero_albaran AS numero_albaran,
DATE_FORMAT(t1.created_at, '%d/%m/%Y') AS fecha_creacion,
DATE_FORMAT(t1.fecha_albaran, '%d/%m/%Y') AS fecha_albaran,
t1.mostrar_precios AS mostrar_precios,
t2.nombre AS cliente,
t1.cajas AS cajas
") ;
$builder->join("clientes t2", "t1.cliente_id = t2.id", "left");
$builder->where("t1.deleted_at IS NULL");
$builder->where("t1.id", $albaran_id);
return $builder;
}
}

View File

@ -0,0 +1,64 @@
<?php
namespace App\Models\Logistica;
use CodeIgniter\Model;
use CodeIgniter\Database\BaseBuilder;
class EnvioLineaModel extends Model
{
protected $table = 'envios_lineas';
protected $primaryKey = 'id';
protected $useAutoIncrement = true;
protected $returnType = \App\Entities\Logistica\EnvioLineaEntity::class;
protected $useSoftDeletes = false;
protected $allowedFields = [
'envio_id',
'pedido_id',
'unidades_envio',
'unidades_total',
'created_at',
'updated_at',
'created_by',
'updated_by',
'presupuesto_id',
];
protected $useTimestamps = true;
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
public function getDatatableQuery($envio_id = null): BaseBuilder
{
$builder = $this->db
->table($this->table . " t1")
->select(
"t1.id, t1.pedido_id as pedido, t3.id as presupuesto,
t3.titulo as titulo, t1.unidades_envio as unidadesEnvio, t1.unidades_envio as unidadesEnvioRaw,
t1.unidades_total as unidadesTotal,
IFNULL((
SELECT SUM(t_sub.unidades_envio)
FROM " . $this->table . " t_sub
JOIN envios e ON e.id = t_sub.envio_id
JOIN presupuesto_direcciones d ON d.presupuesto_id = t_sub.presupuesto_id
WHERE e.finalizado = 1
AND t_sub.pedido_id = t1.pedido_id
AND e.direccion = d.direccion COLLATE utf8mb3_general_ci
), 0) as unidadesEnviadas,
IFNULL((
SELECT ROUND(SUM(peso) / 1000, 1)
FROM presupuesto_linea
WHERE presupuesto_id = t3.id
), 0) AS pesoUnidad"
);
$builder->join("presupuestos t3", "t1.presupuesto_id = t3.id", "left");
$builder->where("t1.envio_id", $envio_id);
return $builder;
}
}

View File

@ -0,0 +1,56 @@
<?php
namespace App\Models\Logistica;
use CodeIgniter\Database\BaseBuilder;
use CodeIgniter\Model;
class EnvioModel extends Model
{
protected $table = 'envios';
protected $primaryKey = 'id';
protected $useAutoIncrement = true;
protected $returnType = \App\Entities\Logistica\EnvioEntity::class;
protected $useSoftDeletes = false;
protected $allowedFields = [
'finalizado',
'codigo_seguimiento',
'proveedor_id',
'comentarios',
'cliente_id',
'att',
'direccion',
'ciudad',
'cp',
'email',
'telefono',
'pais_id',
'mostrar_precios',
'mostrar_iva',
'created_at',
'updated_at',
'cajas',
];
protected $useTimestamps = true;
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
public function getDatatableQuery(): BaseBuilder
{
$builder = $this->db
->table($this->table . " t1")
->select(
"t1.id, GROUP_CONCAT(DISTINCT t2.pedido_id) AS pedidos,
COUNT(t2.id) AS num_lineas,
t1.att, t1.direccion, t1.ciudad, t3.nombre as pais, t1.cp, t1.email, t1.telefono, t1.finalizado"
);
$builder->join("envios_lineas t2", "t2.envio_id = t1.id", "left");
$builder->join("lg_paises t3", "t3.id = t1.pais_id", "left");
$builder->groupBy("t1.id");
return $builder;
}
}

View File

@ -1,66 +0,0 @@
<?php
namespace App\Models\Pedidos;
class AlbaranLineaModel extends \App\Models\BaseModel
{
protected $table = "albaranes_lineas";
/**
* Whether primary key uses auto increment.
*
* @var bool
*/
protected $useAutoIncrement = true;
protected $primaryKey = 'id';
protected $returnType = 'App\Entities\Pedidos\AlbaranLineaEntity';
protected $allowedFields = [
'albaran_id',
'titulo',
'isbn',
'ref_cliente',
'cantidad',
'cajas',
'ejemplares_por_caja',
'precio_unidad',
'total',
'user_created_id',
'user_updated_id',
'created_at',
'updated_at',
'deleted_at',
];
protected $useSoftDeletes = true;
protected $useTimestamps = true;
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
protected $deletedField = 'deleted_at';
/**
* Get resource data for creating PDFs.
*
* @param string $search
*
* @return \CodeIgniter\Database\BaseBuilder
*/
public function getResourceForPdf($albaran_id = -1)
{
$builder = $this->db
->table($this->table . " t1")
->select(
"t1.id AS id, t1.albaran_id AS albaran_id, t1.titulo AS titulo, t1.isbn AS isbn,
t1.ref_cliente AS ref_cliente, t1.cantidad AS cantidad, t1.cajas AS cajas,
t1.ejemplares_por_caja AS ejemplares_por_caja, t1.precio_unidad AS precio_unidad,
t1.total AS total"
);
$builder->where("t1.deleted_at IS NULL");
$builder->where("t1.albaran_id", $albaran_id);
return $builder;
}
}

View File

@ -1,161 +0,0 @@
<?php
namespace App\Models\Pedidos;
class AlbaranModel extends \App\Models\BaseModel
{
protected $table = "albaranes";
/**
* Whether primary key uses auto increment.
*
* @var bool
*/
protected $useAutoIncrement = true;
protected $primaryKey = 'id';
protected $returnType = 'App\Entities\Pedidos\AlbaranEntity';
protected $allowedFields = [
'pedido_id',
'presupuesto_id',
'presupuesto_direccion_id',
'cliente_id',
'serie_id',
'numero_albaran',
'mostrar_precios',
'total',
'direccion_albaran',
'att_albaran',
'user_created_id',
'user_updated_id',
'created_at',
'updated_at',
'deleted_at',
];
protected $useSoftDeletes = true;
protected $useTimestamps = true;
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
protected $deletedField = 'deleted_at';
public function generarAlbaranes($pedido_id, $presupuestos_id, $user_id){
$model_presupuesto = model('App\Models\Presupuestos\PresupuestoModel');
$model_presupuesto_direcciones = model('App\Models\Presupuestos\PresupuestoDireccionesModel');
$model_series = model('App\Models\Configuracion\SeriesFacturasModel');
$presupuestos = $model_presupuesto->find($presupuestos_id);
$return_data = [];
foreach ($presupuestos as $presupuesto) {
$envios = $model_presupuesto_direcciones->where('presupuesto_id', $presupuesto->id)->findAll();
foreach($envios as $envio){
// se buscan los albaranes en este presupuesto con la misma direccion y con el mismo presupuesto_id en albaran
// en albaran linea para obtener la cantidad total enviada
$model_albaran = model('App\Models\Pedidos\AlbaranModel');
$model_albaran_linea = model('App\Models\Pedidos\AlbaranLineaModel');
$albaranes = $model_albaran->where('presupuesto_id', $presupuesto->id)
->where('presupuesto_direccion_id', $envio->id)->findAll();
// se suman las cantidades de los albaranes
$cantidad_enviada = 0;
foreach($albaranes as $albaran){
$lineas = $model_albaran_linea->where('albaran_id', $albaran->id)->findAll();
foreach($lineas as $linea){
$cantidad_enviada += $linea->cantidad;
}
}
if($cantidad_enviada >= intval($envio->cantidad)){
continue;
}
// calculo precio_unidad
$precio_unidad = $presupuesto->total_aceptado/$presupuesto->tirada;
$albaran_linea = [];
$albaran_linea = [
'titulo' => $presupuesto->titulo,
'isbn' => $presupuesto->isbn,
'ref_cliente' => $presupuesto->ref_cliente,
'cantidad' => intval($envio->cantidad)-$cantidad_enviada,
'cajas' => 1,
'ejemplares_por_caja' => intval($envio->cantidad)-$cantidad_enviada,
'precio_unidad' => $precio_unidad,
'total' => $precio_unidad * $envio->cantidad,
'user_created_id' => $user_id,
'user_updated_id' => $user_id,
];
$serie = $model_series->find(11);
$numero_albaran = str_replace('{number}', $serie->next, $serie->formato);
$numero_albaran = str_replace( '{year}', date("Y"), $numero_albaran);
$serie->next = $serie->next + 1;
$model_series->save($serie);
$albaran = [
'pedido_id' => $pedido_id,
'presupuesto_id' => $presupuesto->id,
'presupuesto_direccion_id' => $envio->id,
'cliente_id' => $presupuesto->cliente_id,
'serie_id' => 11, // Serie de albaranes
'numero_albaran' => $numero_albaran,
'mostrar_precios' => 0,
'total' => $albaran_linea['total'],
'direccion_albaran' => $envio->direccion,
'att_albaran' => $envio->att,
'user_created_id' => $user_id,
'user_updated_id' => $user_id,
'fecha_albaran' => date('d/m/Y'),
];
$id_albaran = $this->insert($albaran);
$model_albaran_linea = model('App\Models\Pedidos\AlbaranLineaModel');
$albaran['id'] = $id_albaran;
$albaran_linea['albaran_id'] = $id_albaran;
$id_albaran_linea =$model_albaran_linea->insert($albaran_linea);
$albaran_linea['id'] = $id_albaran_linea;
array_push($return_data, ["albaran"=>$albaran, "lineas" =>[$albaran_linea]]);
}
}
return $return_data;
}
/**
* Get resource data for creating PDFs.
*
* @param string $search
*
* @return \CodeIgniter\Database\BaseBuilder
*/
public function getResourceForPdf($albaran_id = -1)
{
$builder = $this->db
->table($this->table . " t1")
->select(
"t1.id AS id, t1.pedido_id AS pedido_id, t1.presupuesto_id AS presupuesto_id,
t1.presupuesto_direccion_id AS presupuesto_direccion_id, t1.cliente_id AS cliente_id,
t1.serie_id AS serie_id, t1.numero_albaran AS numero_albaran, t1.mostrar_precios AS mostrar_precios,
t1.total AS total, t1.direccion_albaran AS direccion_albaran, t1.att_albaran AS att_albaran,
t1.user_created_id AS user_created_id, t1.user_updated_id AS user_updated_id,
t1.created_at AS created_at, t1.updated_at AS updated_at,
t2.nombre AS cliente"
);
$builder->join("clientes t2", "t1.cliente_id = t2.id", "left");
$builder->where("t1.deleted_at IS NULL");
$builder->where("t1.id", $albaran_id);
return $builder;
}
}

View File

@ -0,0 +1,287 @@
<?php
namespace App\Services;
use Config\Services;
class LogisticaService
{
public static function findPedidoOrISBN($search)
{
$multienvio = false;
$modelPedido = model('App\Models\Pedidos\PedidoModel');
$search = trim($search);
$searchClean = str_replace('-', '', $search);
$modelPedido = model('App\Models\Pedidos\PedidoModel');
$builder = $modelPedido->builder();
$builder->select([
'pedidos.id as pedido_id',
'pedidos_linea.id as linea_id',
'pedidos_linea.cantidad as cantidad_linea',
'presupuestos.id as presupuesto_id',
]);
$builder->join('pedidos_linea', 'pedidos_linea.pedido_id = pedidos.id', 'left');
$builder->join('presupuestos', 'presupuestos.id = pedidos_linea.presupuesto_id', 'left');
$builder->join('envios_lineas', 'envios_lineas.pedido_id = pedidos_linea.pedido_id', 'left');
$builder->groupStart()
->where('pedidos.id', $search)
->whereIn('pedidos.estado', ['finalizado'])
->orWhere("REPLACE(presupuestos.isbn, '-', '')", $searchClean)
->groupEnd();
$builder->groupBy('pedidos_linea.id');
$builder->having('IFNULL(SUM(envios_lineas.unidades_envio), 0) < cantidad_linea', null, false);
$result = $builder->get()->getResult();
if (empty($result)) {
$response = [
'status' => false,
'message' => lang('Logistica.errors.notFound'),
];
return $response;
}
$PresupuestoDireccionesModel = model('App\Models\Presupuestos\PresupuestoDireccionesModel');
$numDirecciones = $PresupuestoDireccionesModel->where('presupuesto_id', $result[0]->presupuesto_id)
->countAllResults();
if ($numDirecciones == 0) {
$response = [
'status' => false,
'message' => lang('Logistica.errors.noAddresses'),
];
return $response;
} else if ($numDirecciones > 1) {
$multienvio = true;
}
$response = [
'status' => true,
'data' => $result[0],
];
$response_envio = LogisticaService::generateEnvio($result[0]->pedido_id, $multienvio);
if ($response_envio['status'] == false) {
$response = [
'status' => false,
'message' => $response_envio['message'],
];
return $response;
} else {
$response['data']->id_envio = $response_envio['data']['id_envio'];
$response['data']->multienvio = $response_envio['data']['multienvio'];
}
return $response;
}
public static function findLineaEnvioPorEnvio(int $envio_id)
{
$db = \Config\Database::connect();
$subCliente = $db->table('envios')
->select('cliente_id')
->where('id', $envio_id)
->getCompiledSelect();
$builder = $db->table('envios e_main');
$builder->select("
CONCAT('[', p.id, '] - ', pr.titulo) AS name,
pl.id AS id,
pl.cantidad,
(
SELECT IFNULL(SUM(el.unidades_envio), 0)
FROM envios_lineas el
JOIN envios e ON e.id = el.envio_id
WHERE el.pedido_id = p.id
AND e.direccion = e_main.direccion
AND pr.cliente_id = ($subCliente)
) AS unidades_enviadas,
(
pl.cantidad - (
SELECT IFNULL(SUM(el2.unidades_envio), 0)
FROM envios_lineas el2
JOIN envios e2 ON e2.id = el2.envio_id
WHERE el2.pedido_id = p.id
AND e2.direccion = e_main.direccion
AND pr.cliente_id = ($subCliente)
)
) AS unidades_pendientes
");
$builder->join('pedidos_linea pl', '1=1'); // para incluir líneas sin envío aún
$builder->join('pedidos p', 'p.id = pl.pedido_id');
$builder->join('presupuestos pr', 'pr.id = pl.presupuesto_id');
$builder->where('e_main.id', $envio_id);
$builder->where('p.estado', 'finalizado');
$builder->where("pr.cliente_id = ($subCliente)", null, false);
$builder->having('unidades_pendientes >', 0);
$builder->orderBy('name', 'ASC');
return $builder;
}
public static function addLineaEnvio($envio_id = null, $pedido_id = null, $direccion = null)
{
$modelPedido = model('App\Models\Pedidos\PedidoModel');
$builder = $modelPedido->builder();
$builder->select("
pedidos.id as pedido_id,
pedidos_linea.id as linea_id,
pedidos_linea.cantidad as total_unidades,
(
SELECT IFNULL(SUM(el.unidades_envio), 0)
FROM envios_lineas el
JOIN envios e ON e.id = el.envio_id
WHERE el.pedido_id = pedidos.id
AND e.finalizado = 1
AND TRIM(e.direccion) = '" . addslashes(trim($direccion)) . "'
) as unidades_enviadas,
pedidos_linea.cantidad - IFNULL(SUM(envios_lineas.unidades_envio), 0) as unidades_envio,
presupuestos.id as presupuesto_id
");
$builder->join('pedidos_linea', 'pedidos_linea.pedido_id = pedidos.id', 'left');
$builder->join('presupuestos', 'presupuestos.id = pedidos_linea.presupuesto_id', 'left');
$builder->join('envios_lineas', 'envios_lineas.pedido_id = pedidos_linea.pedido_id', 'left');
$builder->groupBy('pedidos_linea.id');
$builder->having('IFNULL(SUM(envios_lineas.unidades_envio), 0) < pedidos_linea.cantidad', null, false);
$builder->where('pedidos.estado', 'finalizado');
$builder->where('pedidos.id', $pedido_id);
$result = $builder->get()->getResultObject();
if (empty($result)) {
return [
'status' => false,
'message' => lang('Logistica.errors.notFound'),
];
} else {
$EnvioLineasModel = model('App\Models\Logistica\EnvioLineaModel');
$EnvioLineasModel->save([
'envio_id' => $envio_id,
'pedido_id' => $result[0]->pedido_id,
'unidades_envio' => $result[0]->unidades_envio,
'unidades_total' => $result[0]->total_unidades,
'cajas' => null,
'unidades_cajas' => 1,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s'),
'created_by' => auth()->user()->id,
'updated_by' => auth()->user()->id,
'presupuesto_id' => $result[0]->presupuesto_id,
]);
}
return [
'status' => true,
'data' => [
'unidades_envio' => $result[0]->unidades_envio,
'unidades_enviadas' => $result[0]->unidades_enviadas,
'total_unidades' => $result[0]->total_unidades,
]
];
}
private static function generateEnvio($pedido_id, $multienvio = false)
{
$presupuestoDireccionesModel = model('App\Models\Presupuestos\PresupuestoDireccionesModel');
if (!$multienvio) {
// solo hay una dirección, se obtiene de los albaranes
$datosEnvio = $presupuestoDireccionesModel
->select('
presupuestos.id as presupuesto_id,
presupuesto_direcciones.att,
presupuesto_direcciones.direccion,
presupuesto_direcciones.provincia as ciudad,
presupuesto_direcciones.cp,
presupuesto_direcciones.telefono,
presupuesto_direcciones.email,
presupuesto_direcciones.pais_id,
presupuesto_direcciones.cantidad - IFNULL(SUM(envios_lineas.unidades_envio), 0) as cantidad,
presupuesto_direcciones.cantidad as cantidad_total,
presupuestos.cliente_id as cliente_id
')
->join('pedidos_linea', 'pedidos_linea.presupuesto_id = presupuesto_direcciones.presupuesto_id')
->join('pedidos', 'pedidos.id = pedidos_linea.pedido_id')
->join('presupuestos', 'pedidos_linea.presupuesto_id = presupuestos.id')
->join('envios_lineas', 'envios_lineas.pedido_id = pedidos.id', 'left')
->join('envios', 'envios.id = envios_lineas.envio_id', 'left')
->where('pedidos.id', $pedido_id)
->groupBy('presupuesto_direcciones.id') // Necesario por el uso de SUM
->first();
// se genera un nuevo envio con estos datos
$EnvioModel = model('App\Models\Logistica\EnvioModel');
$EnvioModel->set('cliente_id', $datosEnvio->cliente_id);
$EnvioModel->set('att', $datosEnvio->att);
$EnvioModel->set('direccion', $datosEnvio->direccion);
$EnvioModel->set('ciudad', $datosEnvio->ciudad);
$EnvioModel->set('cp', $datosEnvio->cp);
$EnvioModel->set('telefono', $datosEnvio->telefono);
$EnvioModel->set('email', $datosEnvio->email);
$EnvioModel->set('pais_id', $datosEnvio->pais_id);
$EnvioModel->set('cantidad', $datosEnvio->cantidad);
$EnvioModel->set('cajas', 1);
$EnvioModel->set('multienvio', $multienvio ? 1 : 0);
$EnvioModel->set('created_at', date('Y-m-d H:i:s'));
$EnvioModel->set('updated_at', date('Y-m-d H:i:s'));
$EnvioModel->insert();
$idEnvio = $EnvioModel->insertID();
// se genera la linea de envio
$EnvioLineasModel = model('App\Models\Logistica\EnvioLineaModel');
$EnvioLineasModel->save([
'envio_id' => $idEnvio,
'pedido_id' => $pedido_id,
'unidades_envio' => $datosEnvio->cantidad,
'unidades_total' => $datosEnvio->cantidad_total,
'cajas' => 1,
'unidades_cajas' => 1,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s'),
'created_by' => auth()->user()->id,
'updated_by' => auth()->user()->id,
'presupuesto_id' => (int) $datosEnvio->presupuesto_id
]);
return [
'status' => true,
'data' => [
'id_envio' => $idEnvio,
'multienvio' => false,
],
];
}
if (empty($datosEnvio)) {
return [
'status' => false,
'message' => lang('Logistica.errors.noAddresses'),
];
}
}
}

View File

@ -0,0 +1,295 @@
<?= $this->include("themes/_commonPartialsBs/sweetalert") ?>
<?= $this->include('themes/_commonPartialsBs/datatables') ?>
<?= $this->include("themes/_commonPartialsBs/select2bs5") ?>
<?= $this->extend('themes/vuexy/main/defaultlayout') ?>
<?= $this->section('content'); ?>
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header">
<h4><?= $boxTitle ?></h4>
</div>
<div class="card-body">
<?= view("themes/_commonPartialsBs/_alertBoxes") ?>
<input type="hidden" id="id" name="id" value="<?= $envioEntity->id ?>">
<input type="hidden" id="nextCaja" name="next_caja" value="<?= $envioEntity->nextCaja ?>">
<div class="accordion accordion-bordered">
<div class="card accordion-item active mb-5">
<h4 class="accordion-header px-4 py-3">
<?= lang("Logistica.datosEnvio") ?>
</h4>
<div id="accordionDatosEnvioTip" class="accordion-collapse collapse show">
<div class="accordion-body px-4 py-3">
<div class="d-flex flex-row mb-3">
<div class="col-sm-4 px-3">
<label for="att" class="form-label">
<?= lang("Logistica.att") ?>
</label>
<input readonly id="att" name="att" tabindex="1" maxlength="50"
class="form-control" value="<?= old('att', $envioEntity->att) ?>">
</div>
<div class="col-sm-6 px-3">
<label for="direccion" class="form-label">
<?= lang("Logistica.direccion") ?>
</label>
<input readonly id="direccion" name="direccion" tabindex="1" maxlength="50"
class="form-control"
value="<?= old('direccion', $envioEntity->direccion) ?>">
</div>
<div class="col-sm-2 px-3">
<label for="ciudad" class="form-label">
<?= lang("Logistica.ciudad") ?>
</label>
<input readonly id="ciudad" name="ciudad" tabindex="1" maxlength="50"
class="form-control" value="<?= old('ciudad', $envioEntity->ciudad) ?>">
</div>
</div>
<div class="d-flex flex-row mb-3">
<div class="col-sm-3 px-3">
<label for="cp" class="form-label">
<?= lang("Logistica.cp") ?>
</label>
<input readonly id="cp" name="cp" tabindex="1" maxlength="50"
class="form-control" value="<?= old('cp', $envioEntity->cp) ?>">
</div>
<div class="col-sm-3 px-3">
<label for="pais" class="form-label">
<?= lang("Logistica.pais") ?>
</label>
<input readonly id="pais" name="pais" tabindex="1" maxlength="50"
class="form-control" value="<?= old('pais', $envioEntity->pais) ?>">
</div>
<div class="col-sm-3 px-3">
<label for="email" class="form-label">
<?= lang("Logistica.email") ?>
</label>
<input readonly id="email" name="email" tabindex="1" maxlength="50"
class="form-control" value="<?= old('email', $envioEntity->email) ?>">
</div>
<div class="col-sm-3 px-3">
<label for="telefono" class="form-label">
<?= lang("Logistica.telefono") ?>
</label>
<input readonly id="telefono" name="telefono" tabindex="1" maxlength="50"
class="form-control" value="<?= old('telefono', $envioEntity->telefono) ?>">
</div>
</div>
<div class="d-flex flex-row mb-3">
<div class="col-sm-9 px-3">
<label for="comentarios" class="form-label">
<?= lang("Logistica.comentariosEnvio") ?>
</label>
<input id="comentarios" name="comentarios" tabindex="1" maxlength="50"
class="form-control"
value="<?= old('comentarios', $envioEntity->comentarios) ?>">
</div>
<div class="col-sm-3 px-3">
<button id="guardarComentarios" name="guardar_comentarios" tabindex="1"
class="btn btn-primary mt-4 w-100">
<?= lang("Logistica.guardar") ?>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="accordion accordion-bordered">
<div class="card accordion-item active mb-5">
<h4 class="accordion-header px-4 py-3">
<?= lang("Logistica.addLineasEnvio") ?>
</h4>
<div id="accordionaddLineasEnvioTip" class="accordion-collapse collapse show">
<div class="d-flex flex-row mb-3">
<div class="col-sm-12 px-3">
<p><?= lang('Logistica.addLineasText') ?></p>
</div>
</div>
<div class="d-flex flex-row mb-3">
<div class="col-sm-6 px-3">
<label for="buscadorPedidos" class="form-label">
<?= lang("Logistica.buscadorPedidosTitle2") ?>
</label>
<select id="buscadorPedidos" name="buscador_pedidos" tabindex="1" maxlength="50"
class="form-control select2bs2" style="width: 100%;">
</select>
</div>
<div class="col-sm-2 px-3">
<button id="btnAddLinea" name="btnBuscar" tabindex="1"
class="btn btn-primary mt-4 w-100">
<?= lang("Logistica.add") ?>
<ti class="ti ti-circle-plus"></ti>
</button>
</div>
</div>
</div>
</div>
</div>
<div class="accordion accordion-bordered">
<div class="card accordion-item active mb-5">
<h4 class="accordion-header px-4 py-3">
<?= lang("Logistica.lineasEnvio") ?>
</h4>
<div id="accordionDatosEnvioTip" class="accordion-collapse collapse show">
<div class="accordion-body px-4 py-3">
<div class="d-flex flex-row">
<p><?= lang('Logistica.buttonsActions') ?></p>
</div>
<div class="d-flex flex-row mb-3">
<div class="col-sm-2 px-3">
<button id="btnSelectAll" name="btnSelectAll" tabindex="1"
class="btn btn-primary w-100">
<?= lang("Logistica.selectAll") ?>
<i class="ti ti-select"></i>
</button>
</div>
<div class="col-sm-2 px-3">
<button id="btnEliminarLineas" name="btnEliminarLineas" tabindex="1"
class="btn btn-danger w-100">
<?= lang("Logistica.eliminar") ?>
<i class="ti ti-trash"></i>
</button>
</div>
<div class="col-sm-2 px-3">
<button id="btnGenerarAlbaran" name="btnGenerarAlbaran" tabindex="1"
class="btn btn-success w-100">
<?= lang("Logistica.generarAlbaran") ?>
<i class="ti ti-file-check"></i>
</button>
</div>
<div class="col-sm-2 px-3">
<button id="btnImprimirEtiquetas" name="btnImprimirEtiquetas" tabindex="1"
class="btn btn-info w-100">
<?= lang("Logistica.imprimirEtiquetas") ?>
<i class="ti ti-printer"></i>
</button>
</div>
</div>
<div class="row mb-3">
<table id="tableLineasEnvio" class="table table-striped table-hover w-100">
<thead>
<tr>
<th></th>
<th><?= lang("Logistica.pedido") ?></th>
<th><?= lang("Logistica.presupuesto") ?></th>
<th><?= lang("Logistica.titulo") ?></th>
<th class="text-center" style="width: 10%;">
<?= lang("Logistica.unidadesEnvio") ?>
</th>
<th class="text-center" style="width: 10%;">
<?= lang("Logistica.unidadesEnviadas") ?>
</th>
<th class="text-center" style="width: 10%;">
<?= lang("Logistica.unidadesTotales") ?>
</th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<th colspan="10">
<div class="text-end">
<?= lang("Logistica.unidadesTotalesFooter") ?>
<span id="footer-unidades-envio"></span>
</div>
</th>
</tr>
<tr>
<th colspan="10">
<div class="text-end">
<?= lang("Logistica.peso") ?>
<span id="footer-peso"></span>
</div>
</th>
</tr>
</tfoot>
</table>
<div class="col-sm-2 px-3">
<label for="cajas" class="form-label">
<?= lang("Logistica.cajas") ?>
</label>
<input type="number" id="cajas" name="cajas" tabindex="1" maxlength="50"
class="form-control" value="<?= old('cajas', $envioEntity->cajas) ?>">
</div>
</div>
</div>
</div>
</div>
<div class="accordion accordion-bordered mt-3" id="accordioAlbaranes">
<div class="card accordion-item active">
<h2 class="accordion-header" id="headingAlbaranes">
<button type="button" class="accordion-button" data-bs-toggle="collapse"
data-bs-target="#accordionAlbaranesTip" aria-expanded="false"
aria-controls="accordionAlbaranesTip">
<h3><?= lang("Pedidos.albaranes") ?></h3>
</button>
</h2>
<div id="accordionAlbaranesTip" class="accordion-collapse collapse show"
data-bs-parent="#accordioAlbaranes">
<div id="contenedorAlbaranes" class="accordion-body">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<?= $this->endSection() ?>
<?= $this->section('css') ?>
<link rel="stylesheet" href="<?= site_url('themes/vuexy/vendor/libs/sweetalert2/sweetalert2.css') ?>" />
<link rel="stylesheet" href="https://cdn.datatables.net/rowreorder/1.4.1/css/rowReorder.dataTables.min.css">
<link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
<link rel="stylesheet" href="<?= site_url("/themes/vuexy/vendor/libs/flatpickr/flatpickr.css") ?>">
<?= $this->endSection() ?>
<?= $this->section('additionalExternalJs') ?>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>
<script src="<?= site_url('themes/vuexy/vendor/libs/sweetalert2/sweetalert2.js') ?>"></script>
<script src="https://cdn.datatables.net/rowgroup/1.3.1/js/dataTables.rowGroup.min.js"></script>
<script type="module" src="<?= site_url("assets/js/safekat/pages/logistica/envioEdit.js") ?>"></script>
<?= $this->endSection() ?>

View File

@ -0,0 +1,97 @@
<?= $this->include("themes/_commonPartialsBs/sweetalert") ?>
<?= $this->include('themes/_commonPartialsBs/datatables') ?>
<?= $this->extend('themes/vuexy/main/defaultlayout') ?>
<?= $this->section('content'); ?>
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header">
<h4><?= $boxTitle ?></h4>
</div>
<div class="card-body">
<?= view("themes/_commonPartialsBs/_alertBoxes") ?>
<div class="card accordion-item active mb-5">
<h4 class="accordion-header px-4 py-3">
<?= lang("Logistica.nuevoEnvio") ?>
</h4>
<div id="accordionNuevoEnvioTip" class="accordion-collapse collapse show">
<div class="accordion-body px-4 py-3">
<div class="row">
<div class="mb-1 col-sm-4">
<label for="buscadorPedidos" class="form-label">
<?= lang("Logistica.buscadorPedidosTitle") ?>
</label>
<input id="buscadorPedidos" name="buscador_pedidos" tabindex="1" maxlength="50"
class="form-control" value="">
</div>
</div>
</div>
</div>
</div>
<div class="card accordion-item active">
<h4 class="accordion-header px-4 py-3">
<?= lang("Logistica.listadoEnvios") ?>
</h4>
<div id="accordionListadoEnviosTip" class="accordion-collapse collapse show">
<div class="accordion-body px-4 py-3">
<div class="row">
<table id="tableOfEnvios" class="table table-striped table-hover w-100">
<thead>
<tr>
<th><?= lang('Logistica.idEnvio') ?? 'ID Envío' ?></th>
<th><?= lang('Logistica.numeroPedidos') ?? 'Nº Pedidos' ?></th>
<th><?= lang('Logistica.numeroLineas') ?? 'Nº Líneas' ?></th>
<th><?= lang('Logistica.att') ?? 'Att' ?></th>
<th><?= lang('Logistica.direccion') ?? 'Dirección' ?></th>
<th><?= lang('Logistica.ciudad') ?? 'Ciudad' ?></th>
<th><?= lang('Logistica.pais') ?? 'País' ?></th>
<th><?= lang('Logistica.cp') ?? 'CP' ?></th>
<th><?= lang('Logistica.email') ?? 'Email' ?></th>
<th><?= lang('Logistica.telefono') ?? 'Teléfono' ?></th>
<th><?= lang('Logistica.finalizado') ?? 'Finalizado' ?></th>
<th><?= lang('Logistica.acciones') ?? 'Acciones' ?></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
<div class="mt-3">
<button type="button" class="btn btn-secondary" id="btnImprimirEtiquetas"
onclick="window.location.href='<?= route_to('LogisticaPanel') ?>'">
<?= lang('Logistica.backToPanel') ?>
</button>
</div>
</div>
</div>
</div>
</div>
<?= $this->endSection() ?>
<?= $this->section('css') ?>
<link rel="stylesheet" href="<?= site_url('themes/vuexy/vendor/libs/sweetalert2/sweetalert2.css') ?>" />
<?= $this->endSection() ?>
<?= $this->section('additionalExternalJs') ?>
<script src="<?= site_url('themes/vuexy/vendor/libs/sweetalert2/sweetalert2.js') ?>"></script>
<script type="module" src="<?= site_url("assets/js/safekat/pages/logistica/envio.js") ?>"></script>
<?= $this->endSection() ?>

View File

@ -0,0 +1,96 @@
<?= $this->include("themes/_commonPartialsBs/sweetalert") ?>
<?= $this->include('themes/_commonPartialsBs/datatables') ?>
<?= $this->extend('themes/vuexy/main/defaultlayout') ?>
<?= $this->section('content'); ?>
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header">
<h4><?= $boxTitle ?></h4>
</div>
<div class="card-body">
<?= view("themes/_commonPartialsBs/_alertBoxes") ?>
<div class="card accordion-item active mb-5">
<h4 class="accordion-header px-4 py-3">
<?= lang("Logistica.nuevoEnvio") ?>
</h4>
<div id="accordionNuevoEnvioTip" class="accordion-collapse collapse show">
<div class="accordion-body px-4 py-3">
<div class="row">
<div class="mb-1 col-sm-4">
<label for="buscadorPedidos" class="form-label">
<?= lang("Logistica.buscadorPedidosTitle") ?>
</label>
<input id="buscadorPedidos" name="buscador_pedidos" tabindex="1" maxlength="50"
class="form-control" value="">
</div>
</div>
</div>
</div>
</div>
<div class="card accordion-item active">
<h4 class="accordion-header px-4 py-3">
<?= lang("Logistica.listadoEnvios") ?>
</h4>
<div id="accordionListadoEnviosTip" class="accordion-collapse collapse show">
<div class="accordion-body px-4 py-3">
<div class="row">
<table id="tableOfEnvios" class="table table-striped table-hover w-100">
<thead>
<tr>
<th><?= lang('Logistica.idEnvio') ?? 'ID Envío' ?></th>
<th><?= lang('Logistica.numeroPedidos') ?? 'Nº Pedidos' ?></th>
<th><?= lang('Logistica.numeroLineas') ?? 'Nº Líneas' ?></th>
<th><?= lang('Logistica.att') ?? 'Att' ?></th>
<th><?= lang('Logistica.direccion') ?? 'Dirección' ?></th>
<th><?= lang('Logistica.ciudad') ?? 'Ciudad' ?></th>
<th><?= lang('Logistica.pais') ?? 'País' ?></th>
<th><?= lang('Logistica.cp') ?? 'CP' ?></th>
<th><?= lang('Logistica.email') ?? 'Email' ?></th>
<th><?= lang('Logistica.telefono') ?? 'Teléfono' ?></th>
<th><?= lang('Logistica.finalizado') ?? 'Finalizado' ?></th>
<th><?= lang('Logistica.acciones') ?? 'Acciones' ?></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
<div class="mt-3">
<button type="button" class="btn btn-secondary" id="btnImprimirEtiquetas"
onclick="window.location.href='<?= route_to('LogisticaPanel') ?>'">
<?= lang('Logistica.backToPanel') ?>
</button>
</div>
</div>
</div>
</div>
<?= $this->endSection() ?>
<?= $this->section('css') ?>
<link rel="stylesheet" href="<?= site_url('themes/vuexy/vendor/libs/sweetalert2/sweetalert2.css') ?>" />
<?= $this->endSection() ?>
<?= $this->section('additionalExternalJs') ?>
<script src="<?= site_url('themes/vuexy/vendor/libs/sweetalert2/sweetalert2.js') ?>"></script>
<script type="module" src="<?= site_url("assets/js/safekat/pages/logistica/envio.js") ?>"></script>
<?= $this->endSection() ?>

View File

@ -14,41 +14,43 @@
<div class="row mb-3">
<div class="col-4">
<button type="button" style="height: 80px;" class="btn btn-primary w-100 " data-toggle="modal" data-target="#modalCreate">
<button type="button" style="height: 80px;" class="btn btn-primary w-100 "
onclick="window.location.href='<?= route_to('selectEnvios', 'simple') ?>'"
>
<?= lang('Logistica.envioSimple') ?>
</button>
</div>
<div class="col-4">
<button type="button" style="height: 80px;" class="btn btn-primary w-100 " data-toggle="modal" data-target="#modalCreate">
<button type="button" style="height: 80px;" class="btn btn-primary w-100 " >
<?= lang('Logistica.envioMultiple') ?>
</button>
</div>
<div class="col-4">
<button type="button" style="height: 80px;" class="btn btn-primary w-100 " data-toggle="modal" data-target="#modalCreate">
<button type="button" style="height: 80px;" class="btn btn-primary w-100 " >
<?= lang('Logistica.envioConjunto') ?>
</button>
</div>
</div>
<div class="row mb-3">
<div class="col-4">
<button type="button" style="height: 80px;" class="btn btn-primary w-100 " data-toggle="modal" data-target="#modalCreate">
<button type="button" style="height: 80px;" class="btn btn-primary w-100 " >
<?= lang('Logistica.etiquetasTitulos') ?>
</button>
</div>
<div class="col-4">
<button type="button" style="height: 80px;" class="btn btn-primary w-100 " data-toggle="modal" data-target="#modalCreate">
<button type="button" style="height: 80px;" class="btn btn-primary w-100 " >
<?= lang('Logistica.etiquetasEnvio') ?>
</button>
</div>
<div class="col-4">
<button type="button" style="height: 80px;" class="btn btn-primary w-100 " data-toggle="modal" data-target="#modalCreate">
<button type="button" style="height: 80px;" class="btn btn-primary w-100 " >
<?= lang('Logistica.envioFerros') ?>
</button>
</div>
</div>
<div class="row">
<div class="col-4">
<button type="button" style="height: 80px;" class="btn btn-primary w-100 " data-toggle="modal" data-target="#modalCreate">
<button type="button" style="height: 80px;" class="btn btn-primary w-100 " >
<?= lang('Logistica.cerrarOTauto') ?>
</button>
</div>

View File

@ -1,787 +0,0 @@
<div class="accordion accordion-bordered mt-3" id="accordioAlbaranes">
<div class="card accordion-item active">
<h2 class="accordion-header" id="headingAlbaranes">
<button type="button" class="accordion-button" data-bs-toggle="collapse" data-bs-target="#accordionAlbaranesTip" aria-expanded="false" aria-controls="accordionAlbaranesTip">
<h3><?= lang("Pedidos.albaranes") ?></h3>
</button>
</h2>
<div id="accordionAlbaranesTip" class="accordion-collapse collapse show" data-bs-parent="#accordioAlbaranes">
<div class="accordion-body">
<div id='alert-albaranes' class="alert alert-warning d-flex align-items-baseline d-none" role="alert">
<div class="d-flex flex-column ps-1">
<h5 id='error-albaranes' class="alert-heading mb-2"></h5>
</div>
</div>
<div id="bonotes_albaranes" class="col-12 d-flex flex-row-reverse mt-4 gap-2">
<div id="generar_albaranes" class="btn mt-3 btn-success waves-effect waves-light ml-2">
<span class="align-middle d-sm-inline-block d-none me-sm-1"><?= lang('Pedidos.generarAlbaranes') ?></span>
<i class="ti ti-player-play ti-xs"></i>
</div>
<div id="borrar_albaranes" class="btn mt-3 btn-danger waves-effect waves-light ml-2">
<span class="align-middle d-sm-inline-block d-none me-sm-1"><?= lang('Pedidos.borrarAlbaranes') ?></span>
<i class="ti ti-trash ti-xs"></i>
</div>
</div>
</div> <!-- /.accordion-body -->
</div>
</div>
</div>
<?=$this->section('additionalInlineJs') ?>
$('#generar_albaranes').on('click', function(){
var lineasPedido = $('#tableOfLineasPedido').DataTable();
var presupuestos = lineasPedido.column(0).data().unique().toArray();
$.ajax({
url: '<?= route_to('crearAlbaranesPedido') ?>',
type: 'POST',
data: {
pedido_id: <?= $pedidoEntity->id ?>,
presupuestos_id: presupuestos,
<?= csrf_token() ?? "token" ?>: <?= csrf_token() ?>v,
},
success: function(response){
if(response.data.length > 0){
Object.values(response.data).forEach(function(item){
generarAlbaran(item);
});
}
cambios_cantidad_albaranes();
}
});
})
const deleteLineaBtns = function(data) {
return `
<td class="text-right py-0 align-middle">
<div class="btn-group btn-group-sm">
<a href="javascript:void(0);"><i class="ti ti-trash ti-sm btn-delete-linea mx-2" data-id="${data.id}"></i></a>
</div>
</td>`;
};
function generarAlbaran(item){
// Crear los elementos necesarios
const accordion = $('<div>', {
class: 'accordion accordion-bordered mt-3 accordion-albaran',
id: 'accordioAlbaran' + item.albaran.id,
albaran: item.albaran.id
});
const card = $('<div>', {
class: 'card accordion-item active'
});
const header = $('<h2>', {
class: 'accordion-header',
id: 'headingAlbaran' + item.albaran.id
});
const button = $('<button>', {
type: 'button',
class: 'accordion-button collapsed',
'data-bs-toggle': 'collapse',
'data-bs-target': '#accordionAlbaranTip' + item.albaran.id,
'aria-expanded': 'false',
'aria-controls': 'accordionAlbaranTip' + item.albaran.id,
'albaran': item.albaran.id,
}).css({
'background-color': '#F0F8FF'
});
const h3 = $('<h5>').html(item.albaran.numero_albaran);
const collapseDiv = $('<div>', {
id: 'accordionAlbaranTip' + item.albaran.id,
class: 'accordion-collapse collapse',
'data-bs-parent': '#accordioAlbaran' + item.albaran.id
});
const body = $('<div>', {
class: 'accordion-body'
});
const cabecera =
`
<div class="col-12 d-flex justify-content-between mb-3">
<div class="col-6 d-flex flex-row">
<div class="col-2">
<label><?= lang('Pedidos.fecha') ?>:</label>
</div>
<div class="col-2">
<label>${item.albaran.fecha_albaran}</label>
</div>
</div>
<div class="col-6 d-flex flex-row-reverse">
<div class="col-2">
<label style="text-align: right; display:block">${item.albaran.pedido_id}</label>
</div>
<div class="col-2">
<label style="text-align: right"><?= lang('Pedidos.pedido') ?>:</label>
</div>
</div>
</div>
<div class="col-12 d-flex justify-content-between mb-3">
<div class="col-6 d-flex flex-row">
<div class="col-2">
<label><?= lang('Pedidos.cliente') ?>:</label>
</div>
<div class="col-4">
<label>${$('#cliente').val()}</label>
</div>
</div>
<div class="col-6 d-flex flex-row-reverse">
<div class="col-2">
<label style="text-align: right; display:block">${item.albaran.numero_albaran}</label>
</div>
<div class="col-2">
<label style="text-align: right"><?= lang('Pedidos.albaran') ?>:</label>
</div>
</div>
</div>
<div class="col-12 d-flex justify-content-between mb-3">
<div class="col-1">
<label><?= lang('Pedidos.att') ?>:</label>
</div>
<div class="col-11">
<input id="att_${item.albaran.id}" class="cambios-albaran form-control" albaran_id=${item.albaran.id} value="${item.albaran.att_albaran}" class="form-control"></input>
</div>
</div>
<div class="col-12 d-flex justify-content-between mb-3">
<div class="col-1">
<label><?= lang('Pedidos.direccion') ?>:</label>
</div>
<div class="col-11">
<input id="direccion_${item.albaran.id}" albaran_id=${item.albaran.id} value="${item.albaran.direccion_albaran}" class="cambios-albaran form-control"></input>
</div>
</div>
`;
const table = $('<table>',
{ id: 'tablaAlbaran' + item.albaran.id, width:'100%', class: 'table table-responsive table-striped table-hover table-albaran' })
.css({
'width': '100%',
}).append(
$('<thead>').append(
$('<tr>').append(
$('<th>').css({'max-width':'20px'}),
$('<th>'),
$('<th>', { class:'lp-header', scope: 'col' }).css({'font-size':'smaller'}).text('Unidades'),
$('<th>', { class:'lp-header',scope: 'col' }).css({'font-size':'smaller'}).text('Título'),
$('<th>', { class:'lp-header',scope: 'col' }).css({'font-size':'smaller'}).text('ISBN'),
$('<th>', { class:'lp-header',scope: 'col' }).css({'font-size':'smaller'}).text('Ref. Cliente'),
$('<th>', { class:'lp-header',scope: 'col' }).css({'font-size':'smaller'}).text('Cajas'),
$('<th>', { class:'lp-header',scope: 'col' }).css({'font-size':'smaller'}).text('Ej./Cajas'),
$('<th>', { class:'lp-header',scope: 'col' }).css({'font-size':'smaller'}).text('€/u'),
$('<th>', { class:'lp-header',scope: 'col' }).css({'font-size':'smaller'}).text('Subtotal')
)
),
$('<tbody>'),
$('<tfoot>').append(
$('<tr>').append(
$('<th>', { colspan: '9', style: 'text-align:right' }).text('')
)
),
);
let isChecked = item.albaran.mostrar_precios == 1 ? 'checked' : '';
const botones_albaran =
`
<div class="row mt-1">
<div id="div_mostrar_precios_${item.albaran.id}" class="col-2 d-flex flex-row gap-2">
<div class="d-flex align-items-center">
<label><?= lang('Pedidos.mostrarPrecios') ?>:</label>
</div>
<div class="d-flex align-items-center">
<input type="checkbox" id="mostrar_precios" name="mostrar_precios" albaran_id=${item.albaran.id} class="mostrar-precios custom-control-input" ${isChecked} >
</div>
</div>
<div id="bonotes_albaran_${item.albaran.id}" class="col-10 d-flex flex-row-reverse gap-2">
<div id="borrar_albaran_${item.albaran.id}" class="borrar-albaran btn mt-3 button-albaran btn-label-danger waves-effect waves-light ml-2">
<span class="align-middle d-sm-inline-block d-none me-sm-1"><?= lang('Pedidos.borrarAlbaran') ?></span>
<i class="ti ti-trash ti-xs"></i>
</div>
<div id="imprimir_albaran_${item.albaran.id}" class="imprimir-albaran btn mt-3 btn-label-secondary button-albaran waves-effect waves-light ml-2">
<span class="align-middle d-sm-inline-block d-none me-sm-1"><?= lang('Pedidos.imprimirAlbaran') ?></span>
<i class="ti ti-printer ti-xs"></i>
</div>
<div id="nueva_linea_albaran_${item.albaran.id}" class="nueva-linea-albaran btn mt-3 btn-label-secondary button-albaran waves-effect waves-light ml-2">
<span class="align-middle d-sm-inline-block d-none me-sm-1"><?= lang('Pedidos.nuevaLinea') ?></span>
<i class="ti ti-plus ti-xs"></i>
</div>
<div id="add_iva_albaran_${item.albaran.id}" class="add-iva-albaran btn mt-3 btn-label-secondary button-albaran waves-effect waves-light ml-2">
<span class="align-middle d-sm-inline-block d-none me-sm-1"><?= lang('Pedidos.addIva') ?></span>
<i class="ti ti-plus ti-xs"></i>
</div>
</div>
</div>
`;
// Armar la estructura
button.append(h3);
header.append(button);
card.append(header);
collapseDiv.append(body);
body.append(cabecera);
body.append(table);
body.append(botones_albaran);
card.append(collapseDiv);
accordion.append(card);
// Agregar el elemento al accordioAlbaranes
$('#bonotes_albaranes').before(accordion);
const datatableAlbaran = new DataTable('#tablaAlbaran' + item.albaran.id,{
scrollX: true,
searching: false,
paging: false,
info: false,
ordering: false,
responsive: true,
select: false,
dom: 't',
language: {
url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json"
},
columns: [
{ data: 'id'},
{
data: deleteLineaBtns,
className: 'dt-center'
},
{
data: 'cantidad',
render: function ( data, type, row, meta ) {
var input = $('<input>', {
id: 'cantidad_' + row.id,
name: 'cantidad_' + row.id,
class: 'lp-cell lp-input albaran_linea cantidad-albaran',
albaran: item.albaran.numero_albaran,
type: 'text',
value: data,
linea: row.id
}).css({
'text-align': 'center',
'font-size': 'smaller',
'max-width': '50px'
});
return input.prop('outerHTML');
}
},
{
data: 'titulo',
render: function ( data, type, row, meta ) {
var input = $('<input>', {
id: 'titulo_' + row.id,
name: 'titulo_' + row.id,
class: 'lp-cell lp-input albaran_linea',
albaran: item.albaran.numero_albaran,
type: 'text',
value: data,
linea: row.id
}).css({
'text-align': 'center',
'font-size': 'smaller',
'min-width': '300px'
});
return input.prop('outerHTML');
}
},
{
data: 'isbn',
render: function ( data, type, row, meta ) {
var input = $('<input>', {
id: 'isbn_' + row.id,
name: 'isbn_' + row.id,
class: 'lp-cell lp-input albaran_linea',
albaran: item.albaran.numero_albaran,
type: 'text',
value: data,
linea: row.id
}).css({
'text-align': 'center',
'font-size': 'smaller'
});
return input.prop('outerHTML');
}
},
{
data: 'ref_cliente',
render: function ( data, type, row, meta ) {
var input = $('<input>', {
id: 'ref_cliente_' + row.id,
name: 'ref_cliente_' + row.id,
class: 'lp-cell lp-input albaran_linea',
albaran: item.albaran.numero_albaran,
type: 'text',
value: data,
linea: row.id
}).css({
'text-align': 'center',
'font-size': 'smaller'
});
return input.prop('outerHTML');
}
},
{
data: 'cajas',
render: function ( data, type, row, meta ) {
var input = $('<input>', {
id: 'cajas_' + row.id,
name: 'cajas_' + row.id,
class: 'lp-cell lp-input albaran_linea',
albaran: item.albaran.numero_albaran,
type: 'text',
value: data,
linea: row.id
}).css({
'text-align': 'center',
'font-size': 'smaller',
'max-width': '50px'
});
return input.prop('outerHTML');
}
},
{
data: 'ejemplares_por_caja',
render: function ( data, type, row, meta ) {
var input = $('<input>', {
id: 'ejemplares_por_caja_' + row.id,
name: 'ejemplares_por_caja_' + row.id,
class: 'lp-cell lp-input albaran_linea',
albaran: item.albaran.numero_albaran,
type: 'text',
value: data,
linea: row.id
}).css({
'text-align': 'center',
'font-size': 'smaller',
'max-width': '50px'
});
return input.prop('outerHTML');
}
},
{
data: 'precio_unidad',
render: function ( data, type, row, meta ) {
value = parseFloat(data).toFixed(4);
var input = $('<input>', {
id: 'precio_unidad_' + row.id,
name: 'precio_unidad_' + row.id,
class: 'lp-cell lp-input albaran_linea',
albaran: item.albaran.numero_albaran,
type: 'text',
value: value,
linea: row.id
}).css({
'text-align': 'center',
'font-size': 'smaller',
'max-width': '50px'
});
return input.prop('outerHTML');
}
},
{
data: 'total',
render: function ( data, type, row, meta ) {
var input = $('<input>', {
id: 'total_' + row.id,
name: 'total_' + row.id,
class: 'lp-cell lp-input albaran_linea',
albaran: item.albaran.numero_albaran,
type: 'text',
value: data,
linea: row.id
}).css({
'text-align': 'center',
'font-size': 'smaller',
'max-width': '50px'
});
return input.prop('outerHTML');
}
}
],
columnDefs: [
{ targets: [0], visible: false, searchable: false },
{ targets: [1], orderable: false },
{ targets: [2, 3, 4, 5, 6, 7, 8, 9], className: 'dt-center' }
],
initComplete: function(settings){
var numColumns = this.api().columns().count();
if(item.albaran.mostrar_precios == 0){
this.api().column(numColumns - 1).visible(false);
this.api().column(numColumns - 2).visible(false);
} else {
this.api().column(numColumns - 1).visible(true);
this.api().column(numColumns - 2).visible(true);
}
},
});
// Añadir la nueva fila a la tabla
if(Array.isArray(item.lineas)) {
item.lineas.forEach(function(linea) {
datatableAlbaran.row.add(linea).draw();
});
}
}
$(document).on('click', '.accordion-button', function(){
var albaran_id = $(this).attr('albaran');
var table = $('#tablaAlbaran' + albaran_id).DataTable();
table.columns.adjust();
});
$(document).on('change', '.cambios-albaran', function(){
var elementId = $(this).attr('id');
data = {
<?= csrf_token() ?? "token" ?>: <?= csrf_token() ?>v,
};
data[elementId.split('_')[0] + '_albaran'] = $(this).val();
var albaran_id = $(this).attr('albaran_id');
var url = '<?= route_to('actualizarAlbaran', ':id') ?>';
url = url.replace(':id', albaran_id );
$.ajax({
url: url,
type: 'POST',
data: data,
success: function(response){
if('error' in response){
}
}
});
});
$(document).on('change', '.mostrar-precios', function(){
var checked = $(this).prop('checked');
var albaran_id = $(this).attr('albaran_id');
var table = $('#tablaAlbaran' + albaran_id).DataTable();
var url = '<?= route_to('actualizarAlbaran', ':id') ?>';
url = url.replace(':id', albaran_id );
$.ajax({
url: url,
type: 'POST',
data: {
mostrar_precios: checked?1:0,
<?= csrf_token() ?? "token" ?>: <?= csrf_token() ?>v,
},
success: function(response){
if('error' in response){
if(response.error == 0){
if(checked){
table.column(9).visible(true);
table.column(8).visible(true);
} else {
table.column(9).visible(false);
table.column(8).visible(false);
}
}
}
}
});
});
$(document).on('click', '.btn-delete-linea', function(){
var elementId = $(this).attr('id');
var domTable = $(this).closest('table');
var table = domTable.DataTable();
const row = $(this).closest('tr');
var url = '<?= route_to('borrarAlbaranLinea') ?>';
$.ajax({
url: url,
type: 'POST',
data: {
id: $(this).attr('data-id'),
<?= csrf_token() ?? "token" ?>: <?= csrf_token() ?>v,
},
success: function(response){
if('error' in response){
if(response.error == 0){
table.row($(row)).remove().draw();
}
}
}
});
});
$(document).on('change', '.albaran_linea', function(){
var elementId = $(this).attr('id');
if(elementId.includes('cantidad')){
const item_id = elementId.split('_').slice(-1)[0];
let table = $(this).closest('table').DataTable(); // Obtiene la tabla DataTable
let row = $(this).closest('tr'); // Encuentra la fila actual
let rowIndex = table.row(row).index(); // Obtiene el índice de la fila
const previousValue = table.cell(rowIndex, 2).data();
const newValue = parseInt($(this).val()); // Obtiene el nuevo valor del input
let cantidad = calcular_cantidad_albaranes();
if(cantidad-previousValue+newValue <= parseInt($('#total_tirada').val()) ){
// Actualiza el DataTable
table.cell(rowIndex, 2).data(newValue);
const cajas = parseInt(table.cell(rowIndex, 6).data());
table.cell(rowIndex, 7).data(parseInt(newValue/cajas));
table.cell(rowIndex, 9).data(parseFloat(parseFloat(table.cell(rowIndex, 8).data()) * newValue).toFixed(2));
$('#ejemplares_por_caja_' + item_id).val(parseInt(newValue/cajas)).trigger('change');
$('#total_' + item_id).val(parseFloat((table.cell(rowIndex, 8).data()) * newValue).toFixed(2)).trigger('change');
cambios_cantidad_albaranes();
table.draw();
}
else{
$(this).val(previousValue);
table.cell(rowIndex, 7).data(previousValue);
table.draw();
}
}
data = {
<?= csrf_token() ?? "token" ?>: <?= csrf_token() ?>v,
};
data[elementId.split('_').slice(0, -1).join('_')] = $(this).val();
var linea_id = $(this).attr('linea');
var url = '<?= route_to('actualizarLineaAlbaran', ':id') ?>';
url = url.replace(':id', linea_id );
if(elementId.includes('cajas')){
var cajas = $(this).val();
var linea_id = elementId.split('_').slice(-1)[0];
$('#ejemplares_por_caja_' + linea_id).val(parseInt($('#cantidad_' + linea_id).val()/cajas)).trigger('change');
}
$.ajax({
url: url,
type: 'POST',
data: data,
success: function(response){
if('error' in response){
}
}
});
});
$(document).on('click', '#borrar_albaranes', function(){
asyncConfirmDialogWithParams(
"Borrar albaranes",
"¿Está seguro de borrar los albaranes? Esta acción no se puede deshacer.",
borrar_albaranes, function(){}, [])
});
function borrar_albaranes(){
// seleccionan todos los accordion dentro del body del accordion accordioAlbaranes
$('.accordion-albaran').each(function() {
// Aquí puedes trabajar con cada acordeón interno encontrado
var albaran_id = $(this).attr('albaran');
var url = '<?= route_to('borrarAlbaran', ':id') ?>';
url = url.replace(':id', albaran_id );
$.ajax({
url: url,
type: 'GET',
success: function(response){
if(response){
if('error' in response){
if(response.error == 0){
$('#accordioAlbaran' + albaran_id).remove();
}
}
}
cambios_cantidad_albaranes();
}
});
});
}
function borrar_albaran(albaran_id){
var url = '<?= route_to('borrarAlbaran', ':id') ?>';
url = url.replace(':id', albaran_id );
$.ajax({
url: url,
type: 'GET',
success: function(response){
if(response){
if('error' in response){
if(response.error == 0){
$('#accordioAlbaran' + albaran_id).remove();
}
}
cambios_cantidad_albaranes();
}
}
});
}
$(document).on('click', '.borrar-albaran', function(){
var albaran_id = $(this).attr('id').split('_').slice(-1)[0];
asyncConfirmDialogWithParams(
"Borrar albarán",
"¿Está seguro de borrar el albarán? Esta acción no se puede deshacer.",
borrar_albaran, function(){}, [albaran_id])
});
$(document).on('click', '.nueva-linea-albaran', function(){
var albaran_id = $(this).attr('id').split('_').slice(-1)[0];
var url = '<?= route_to('addAlbaranLinea', ':id') ?>';
url = url.replace(':id', albaran_id );
$.ajax({
url: url,
type: 'GET',
success: function(response){
if(response){
if('error' in response){
if(response.error == 0){
var table = $('#tablaAlbaran' + albaran_id).DataTable();
table.row.add(response.data).draw();
}
}
}
}
});
});
$(document).on('click', '.add-iva-albaran', function(){
var albaran_id = $(this).attr('id').split('_').slice(-1)[0];
var url = '<?= route_to('addIVA', ':id') ?>';
url = url.replace(':id', albaran_id );
data = {
albaran_id: albaran_id,
<?= csrf_token() ?? "token" ?>: <?= csrf_token() ?>v,
};
$.ajax({
url: url,
type: 'POST',
data: data,
success: function(response){
if(response){
if('error' in response){
if(response.error == 0){
var table = $('#tablaAlbaran' + albaran_id).DataTable();
table.row.add(response.data).draw();
}
}
}
}
});
});
$(document).on('click', '.imprimir-albaran', function(){
var albaran_id = $(this).attr('id').split('_').slice(-1)[0];
window.open('<?= site_url('print-albaran/generar/') ?>' + albaran_id, '_blank');
});
$.ajax({
url: '<?= route_to('getAlbaranes', $pedidoEntity->id) ?>',
type: 'GET',
success: function(response){
if(response.data.length > 0){
Object.values(response.data).forEach(function(item){
generarAlbaran(item);
});
cambios_cantidad_albaranes();
}
}
});
function calcular_cantidad_albaranes(){
let cantidad_albaranes = 0;
const tablas = $('.table.table-albaran');
const tabla_pedido = $('#tableOfLineasPedido').DataTable();
const titulo = tabla_pedido.column(3).data().toArray()[0];
for(var i = 0; i < tablas.length; i++){
var table = $(tablas[i]).DataTable();
table.rows().every(function(){
if(titulo && titulo.length >0 && this.data() && titulo.includes(this.data().titulo)){
cantidad_albaranes += parseInt(this.data().cantidad) || 0;
}
});
}
return cantidad_albaranes;
}
function cambios_cantidad_albaranes(){
const cantidad_albaranes = calcular_cantidad_albaranes();
check_cantidad_albaranes(cantidad_albaranes);
}
function check_cantidad_albaranes(unidades_albaranes){
if(unidades_albaranes != parseInt($('#total_tirada').val()) ){
$('#alert-albaranes').removeClass('d-none');
$('#error-albaranes').
html('<?= lang('Pedidos.validation.errorCantidadAlbaranes') ?>'
.replace('{0}', unidades_albaranes)
.replace('{1}', $('#total_tirada').val()));
$('#generar_albaranes').removeClass('d-none');
}
else{
$('#alert-albaranes').addClass('d-none');
$('#error-albaranes').html('');
$('#generar_albaranes').addClass('d-none');
}
}
<?=$this->endSection() ?>

View File

@ -99,7 +99,7 @@ var tableOfLineasPedido = new DataTable('#tableOfLineasPedido',{
drawCallback: function(){
$(this.api().table().container()).find('table').css('width', '100%');
this.api().columns.adjust();
cambios_cantidad_albaranes();
//cambios_cantidad_albaranes();
},
footerCallback: function (row, data, start, end, display) {
let api = this.api();

View File

@ -29,9 +29,6 @@
<?php endif; ?>
<?= view("themes/vuexy/form/pedidos/_cabeceraItems") ?>
<?= view("themes/vuexy/form/pedidos/_lineasItems") ?>
<?php if (!(auth()->user()->inGroup('cliente-admin') || auth()->user()->inGroup('cliente-editor'))) : ?>
<?= view("themes/vuexy/form/pedidos/_albaranesItems") ?>
<?php endif; ?>
<?= view("themes/vuexy/form/pedidos/_facturasItems") ?>
<?= view("themes/vuexy/components/chat_internal_pedido", data: ["modelId" => $pedidoEntity->id, "type" => "pedido"]) ?>
</div><!-- /.card-body -->

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,632 @@
import DatePicker from "./datepicker.js";
class AlbaranComponent {
constructor(item) {
this.item = item;
this.id = item.id;
this.numero = item.numero_albaran;
this.cliente = item.cliente;
this.att = item.att;
this.direccion = item.direccion;
this.envio_id = item.envio_id;
this.fecha = null;
if(this.item.fecha_albaran != null){
const [dia, mes, anio] = item.fecha_albaran.split('/');
this.fecha = `${anio}-${mes.padStart(2, '0')}-${dia.padStart(2, '0')}`;
}
this.selectorTabla = `#tablaAlbaran${this.id}`;
this.table = null;
this.fechaAlbaran = null;
}
mount(selector) {
const dom = this.render();
$(selector).append(dom);
requestAnimationFrame(() => this.init());
}
render() {
const { id, numero } = this;
const accordion = $('<div>', {
class: 'accordion accordion-bordered mt-3 accordion-albaran',
id: 'accordioAlbaran' + id,
albaran: id
});
const card = $('<div>', { class: 'card accordion-item active' });
const header = $('<h2>', {
class: 'accordion-header',
id: 'headingAlbaran' + id
});
const button = $('<button>', {
type: 'button',
class: 'accordion-button collapsed',
'data-bs-toggle': 'collapse',
'data-bs-target': '#accordionAlbaranTip' + id,
'aria-expanded': 'false',
'aria-controls': 'accordionAlbaranTip' + id,
'albaran': id,
}).css({ 'background-color': '#F0F8FF' }).append($('<h5>').html(numero));
const collapseDiv = $('<div>', {
id: 'accordionAlbaranTip' + id,
class: 'accordion-collapse collapse',
'data-bs-parent': '#accordioAlbaran' + id
});
const body = $('<div>', { class: 'accordion-body' });
// Cabecera HTML
const cabecera = this._buildCabecera();
const tableWrapper = $('<div>', {
class: 'table-responsive'
}).append(this._buildTable());
const botones = this._buildBotonera();
header.append(button);
card.append(header);
collapseDiv.append(body);
body.append(cabecera, tableWrapper, botones);
card.append(collapseDiv);
accordion.append(card);
return accordion;
}
_buildCabecera() {
return $(`
<div class="col-12 d-flex justify-content-between align-items-center my-3">
<!-- Fechas a la izquierda pegadas -->
<div class="d-flex align-items-center">
<div class="d-flex align-items-center me-3">
<label class="me-2 mb-0 white-space-nowrap">${window.language.Albaran.fechaCreacion}:</label>
<label class="mb-0">${this.item.fecha_creacion}</label>
</div>
<div class="d-flex align-items-center ml-5">
<label class="me-2 mb-0 white-space-nowrap">${window.language.Albaran.fechaAlbaran}:</label>
<input id="fecha_albaran_${this.id}" class="cambios-albaran form-control form-control-sm"
style="max-width: 130px;" albaran_id=${this.id} value="${this.item.fecha_albaran == null ? '' : this.item.fecha_albaran}">
</div>
</div>
<!-- Envío a la derecha -->
<div class="d-flex align-items-center ms-auto">
<label class="me-1 mb-0">${window.language.Albaran.numEnvio}:</label>
<label class="mb-0">${this.envio_id}</label>
</div>
</div>
<div class="col-12 d-flex justify-content-between align-items-center mb-3">
<!-- Cliente a la izquierda -->
<div class="d-flex align-items-center">
<label class="me-2 mb-0">${window.language.Albaran.cliente}:</label>
<label class="mb-0 text-left">${this.cliente}</label>
</div>
<!-- Nº Albarán a la derecha -->
<div class="d-flex align-items-center ms-auto">
<label class="me-2 mb-0">${window.language.Albaran.albaran}:</label>
<label class="mb-0 text-end">${this.item.numero_albaran}</label>
</div>
</div>
<div class="col-12 d-flex justify-content-between mb-3">
<div class="col-1">
<label>${window.language.Albaran.att}:</label>
</div>
<div class="col-11">
<input id="att_${this.item.id}" class="cambios-albaran form-control" data-albaranId=${this.item.id} value="${this.att}">
</div>
</div>
<div class="col-12 d-flex justify-content-between mb-3">
<div class="col-1">
<label>${window.language.Albaran.direccion}:</label>
</div>
<div class="col-11">
<input id="direccion_${this.item.id}" class="cambios-albaran form-control" data-albaranId=${this.item.id} value="${this.direccion}">
</div>
</div>
`);
}
_buildTable() {
return $('<table>', {
id: 'tablaAlbaran' + this.id,
width: '100%',
class: 'table table-responsive table-striped table-hover table-albaran'
}).append(
$('<thead>').append(
$('<tr>').append(
$('<th>').css({ 'max-width': '20px' }),
$('<th>'),
$('<th>', { class: 'lp-header', scope: 'col' }).css({ 'font-size': 'smaller', 'max-width':'8%' }).text(window.language.Albaran.pedido),
$('<th>', { class: 'lp-header', scope: 'col' }).css({ 'font-size': 'smaller', 'max-width':'8%' }).text(window.language.Albaran.unidades),
$('<th>', { class: 'lp-header', scope: 'col' }).css({ 'font-size': 'smaller' }).text(window.language.Albaran.titulo),
$('<th>', { class: 'lp-header', scope: 'col' }).css({ 'font-size': 'smaller', 'max-width':'15%' }).text(window.language.Albaran.ISBN),
$('<th>', { class: 'lp-header', scope: 'col' }).css({ 'font-size': 'smaller', 'max-width':'15%' }).text(window.language.Albaran.refCliente),
$('<th>', { class: 'lp-header', scope: 'col' }).css({ 'font-size': 'smaller', 'max-width':'8%' }).text(window.language.Albaran.precioU),
$('<th>', { class: 'lp-header', scope: 'col' }).css({ 'font-size': 'smaller', 'max-width':'8%' }).text(window.language.Albaran.subtotal),
$('<th>'),
)
),
$('<tbody>')
);
}
_buildBotonera() {
const id = this.id;
const mostrarPreciosChecked = this.item.mostrar_precios == 1 ? 'checked' : '';
return $(`
<div class="row mt-5">
<div class="col-12 d-flex align-items-center">
<div class="d-flex align-items-center">
<label for="mostrar_precios_${id}" class="me-2 mb-0">${window.language.Albaran.mostrarPrecios}:</label>
<input type="checkbox" id="mostrar_precios_${id}" class="form-check-input mostrar-precios" albaran_id="${id}" ${mostrarPreciosChecked}>
</div>
<div class="d-flex align-items-center mx-5">
<label for="cajas_albaran_${id}" class="me-2 mb-0">${window.language.Albaran.cajas}:</label>
<input type="number" id="cajas_albaran_${id}" class="form-control" albaran_id="${id}" value="${this.item.cajas}" min="0" max="200" step="1">
</div>
<!-- Botones alineados a la derecha -->
<div class="ms-auto d-flex gap-2 flex-wrap justify-content-end">
<button id="add_iva_albaran_${id}" class="add-iva-albaran btn btn-sm btn-light" type="button">
${window.language.Albaran.addIva} <i class="ti ti-plus"></i>
</button>
<button id="nueva_linea_albaran_${id}" class="nueva-linea-albaran btn btn-sm btn-light" type="button">
${window.language.Albaran.nuevaLinea} <i class="ti ti-plus"></i>
</button>
<button id="imprimir_albaran_${id}" class="imprimir-albaran btn btn-sm btn-light" type="button">
${window.language.Albaran.imprimirAlbaran} <i class="ti ti-printer"></i>
</button>
<button id="borrar_albaran_${id}" class="borrar-albaran btn btn-sm btn-danger" type="button">
${window.language.Albaran.borrarAlbaran} <i class="ti ti-trash"></i>
</button>
</div>
</div>
</div>
`);
}
init() {
this.table = $('#tablaAlbaran' + this.id).DataTable({
processing: true,
serverSide: true,
autoWidth: true,
responsive: true,
scrollX: true,
order: [[1, 'asc']],
orderable: false,
lengthMenu: [5, 10, 25, 50, 75, 100, 250, 500, 1000, 2500],
pageLength: 50,
dom: 'lrtip',
ajax: {
url: "/albaranes/datatablesAlbaranLinea?albaranId",
data: {
albaranId: this.id
},
type: 'GET',
},
language: {
url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json"
},
columns: [
{ data: "action" },
{ data: "id", visible: false },
{ data: "pedido"},
{ data: "unidades" },
{ data: "titulo" },
{ data: "isbn" },
{ data: "ref_cliente" },
{ data: "precio_unidad" },
{ data: "total" },
{ data: "iva_reducido", visible: false },
],
columnDefs: [
{
orderable: false,
searchable: false,
targets: [0]
}
],
drawCallback: (settings) => {
if ($('#mostrar_precios_' + this.id).is(':checked')) {
this.table
.column(7).visible(true)
.column(8).visible(true);
}
else {
this.table
.column(7).visible(false)
.column(8).visible(false);
}
requestAnimationFrame(() => {
this._initAutoNumericInputs();
});
}
});
$('#accordionAlbaranTip' + this.id).on('shown.bs.collapse', () => {
if (this.table) {
this.table.columns.adjust().draw(false);
}
});
const option = {
altInput: true,
altFormat: "d/m/Y",
dateFormat: "Y-m-d",
allowInput: true,
}
this.fechaAlbaran = new DatePicker($('#fecha_albaran_' + this.id), option);
this.fechaAlbaran.setDate(this.fecha);
$('#tablaAlbaran' + this.id).on('click', '.btn-delete-albaran-lineas', (e) => {
e.preventDefault();
const table = $('#tablaAlbaran' + this.id).DataTable();
const id = $(e.currentTarget).attr('data-id');
const url = `/albaranes/borrarAlbaranLinea`;
const data = { linea: id };
$.ajax({
url: url,
type: 'POST',
data: data,
success: (response) => {
if (response.success) {
table.draw(false);
} else {
Swal.fire({
title: 'Error',
text: 'No se ha podido borrar la línea del albarán',
icon: 'error',
showCancelButton: false,
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
table.draw(false);
}
},
error: (xhr, status, error) => {
console.error(error);
}
});
});
$('#mostrar_precios_' + this.id).on('change', (e) => {
const checked = $(e.currentTarget).is(':checked');
if (checked) {
this.table
.column(7).visible(true)
.column(8).visible(true);
} else {
this.table
.column(7).visible(false)
.column(8).visible(false);
}
$.post('/albaranes/updateAlbaran', {
albaranId: this.id,
fieldName: 'mostrar_precios',
fieldValue: checked ? 1 : 0
}, (response) => {
if (response.success) {
this.table.ajax.reload(null, false);
} else {
Swal.fire({
title: 'Error',
text: 'No se ha podido actualizar el albarán',
icon: 'error',
showCancelButton: false,
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
}
}
)
});
$('#direccion_' + this.item.id).on('change', (e) => {
const value = $(e.currentTarget).val();
const albaranId = $(e.currentTarget).attr('data-albaranId');
$.post('/albaranes/updateAlbaran', {
albaranId: albaranId,
fieldName: 'direccion_albaran',
fieldValue: value
}, (response) => {
if (response.success) {
this.table.ajax.reload(null, false);
} else {
Swal.fire({
title: 'Error',
text: 'No se ha podido actualizar el albarán',
icon: 'error',
showCancelButton: false,
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
}
});
});
$('#att_' + this.item.id).on('change', (e) => {
const value = $(e.currentTarget).val();
const albaranId = $(e.currentTarget).attr('data-albaranId');
$.post('/albaranes/updateAlbaran', {
albaranId: albaranId,
fieldName: 'att_albaran',
fieldValue: value
}, (response) => {
if (response.success) {
this.table.ajax.reload(null, false);
} else {
Swal.fire({
title: 'Error',
text: 'No se ha podido actualizar el albarán',
icon: 'error',
showCancelButton: false,
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
}
});
});
$('#fecha_albaran_' + this.item.id).on('change', (e) => {
const value = $(e.currentTarget).val();
const albaranId = this.id;
$.post('/albaranes/updateAlbaran', {
albaranId: albaranId,
fieldName: 'fecha_albaran',
fieldValue: value
}, (response) => {
if (response.success) {
this.table.ajax.reload(null, false);
} else {
Swal.fire({
title: 'Error',
text: 'No se ha podido actualizar el albarán',
icon: 'error',
showCancelButton: false,
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
}
});
});
$("#borrar_albaran_" + this.item.id).on('click', (e) => {
e.preventDefault();
const albaranId = this.id;
const url = `/albaranes/borrarAlbaran`;
const data = { albaranId: albaranId };
Swal.fire({
title: window.language.Albaran.borrarAlbaran,
text: window.language.Albaran.borrarAlbaranConfirm,
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: window.language.Albaran.borrar,
cancelButtonText: window.language.Albaran.cancelar,
customClass: {
confirmButton: 'btn btn-primary me-1',
cancelButton: 'btn btn-outline-secondary'
},
buttonsStyling: false
}).then((result) => {
$.ajax({
url: url,
type: 'POST',
data: data,
success: (response) => {
if (response.success) {
// quitar del dom el albarán
$(`#accordioAlbaran${albaranId}`).remove();
} else {
Swal.fire({
title: 'Error',
text: 'No se ha podido borrar el albarán',
icon: 'error',
showCancelButton: false,
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
}
},
error: (xhr, status, error) => {
console.error(error);
}
});
});
});
$('#tablaAlbaran' + this.id).on('change', '.input-albaran-linea', (e) => {
const fieldName = $(e.currentTarget).attr('data-field');
const fieldValue = $(e.currentTarget).val();
const albaranId = this.id;
const lineaId = $(e.currentTarget).attr('data-id');
$.post('/albaranes/updateAlbaranLinea', {
fieldName: fieldName,
fieldValue: fieldValue,
lineaId: lineaId
}, (response) => {
if (response.success) {
this.table.ajax.reload(null, false);
} else {
Swal.fire({
title: 'Error',
text: 'No se ha podido actualizar el albarán',
icon: 'error',
showCancelButton: false,
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
}
});
});
$('#add_iva_albaran_' + this.id).on('click', (e) => {
e.preventDefault();
const albaranId = this.id;
const url = `/albaranes/addIvaAlbaran`;
const data = { albaranId: albaranId };
$.ajax({
url: url,
type: 'POST',
data: data,
success: (response) => {
if (response.success) {
this.table.ajax.reload(null, false);
} else {
Swal.fire({
title: 'Error',
text: 'No se ha podido añadir el IVA al albarán',
icon: 'error',
showCancelButton: false,
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
}
},
error: (xhr, status, error) => {
console.error(error);
}
});
});
$('#nueva_linea_albaran_' + this.id).on('click', (e) => {
e.preventDefault();
const albaranId = this.id;
const url = `/albaranes/nuevaLineaAlbaran`;
const data = { albaranId: albaranId };
$.ajax({
url: url,
type: 'POST',
data: data,
success: (response) => {
if (response.success) {
this.table.ajax.reload(null, false);
} else {
Swal.fire({
title: 'Error',
text: 'No se ha podido añadir la línea al albarán',
icon: 'error',
showCancelButton: false,
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
}
},
error: (xhr, status, error) => {
console.error(error);
}
});
});
$('#imprimir_albaran_' + this.id).on('click', (e) => {
var albaran_id = this.id;
window.open('/print-albaran/generar/'+ albaran_id , '_blank');
});
}
_initAutoNumericInputs() {
const config_2 = {
decimalPlaces: 2,
digitGroupSeparator: '.',
decimalCharacter: ',',
unformatOnSubmit: true,
decimalPlacesShownOnFocus: 2,
decimalPlacesShownOnBlur: 2,
watchExternalChanges: true
};
const config_4 = {
decimalPlaces: 4,
digitGroupSeparator: '.',
decimalCharacter: ',',
unformatOnSubmit: true,
decimalPlacesShownOnFocus: 4,
decimalPlacesShownOnBlur: 4,
watchExternalChanges: true
};
// 🔥 Forzar limpieza completa de instancias anteriores
document.querySelectorAll('.autonumeric-2, .autonumeric-4').forEach(el => {
if (AutoNumeric.getAutoNumericElement(el)) {
AutoNumeric.getAutoNumericElement(el).remove();
}
});
// Inicializar nuevos
AutoNumeric.multiple('.autonumeric-2', config_2);
AutoNumeric.multiple('.autonumeric-4', config_4);
}
}
export default AlbaranComponent;

View File

@ -0,0 +1,82 @@
import Ajax from '../../components/ajax.js';
$(()=>{
$('#buscadorPedidos').on('keydown', function(e) {
if (e.key === 'Enter' || e.keyCode === 13) {
e.preventDefault(); // Evita el submit si está dentro de un form
let search = $(this).val().trim();
new Ajax(
'/logistica/buscar/'+search,
{},
{},
function(response) {
if(!response.status){
popErrorAlert(response.message);
}
if(response.data){
window.open(`${window.location.origin}/logistica/envio/${response.data.id_envio}`);
}
},
function(xhr, status, error) {
if(status == 'error' && typeof(error)== 'string')
popErrorAlert(error);
else
popErrorAlert(error.responseJSON.message);
}
).get();
}
});
const tableEnvios = $('#tableOfEnvios').DataTable({
processing: true,
serverSide: true,
autoWidth: true,
responsive: true,
scrollX: true,
orderCellsTop: true,
lengthMenu: [5, 10, 25, 50, 75, 100, 250, 500, 1000, 2500],
pageLength: 50,
"dom": 'lBrtip',
"ajax": {
"url": "/logistica/datatableEnvios",
},
"columns": [
{ "data": "id" },
{ "data": "pedidos" },
{ "data": "num_lineas" },
{ "data": "att" },
{ "data": "direccion" },
{ "data": "ciudad" },
{ "data": "pais" },
{ "data": "cp" },
{ "data": "email" },
{ "data": "telefono" },
{
"data": "finalizado",
"className": "text-center",
},
{ "data": "action" }
],
"language": {
url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json"
},
"columnDefs": [
{
orderable: false,
searchable: false,
targets: [11]
},
],
"order": [[0, "desc"]],
});
$(document).on('click', '.btn-edit', function (e) {
window.location.href = '/logistica/envio/' + $(this).attr('data-id');
});
});

View File

@ -0,0 +1,452 @@
import ClassSelect from '../../components/select2.js';
import Ajax from '../../components/ajax.js';
import AlbaranComponent from '../../components/albaranComponent.js';
class EnvioEdit {
constructor() {
this.tableCols = [
{ data: "rowSelected" },
{ data: "pedido" },
{ data: "presupuesto" },
{ data: "titulo" },
{ data: "unidadesEnvio" },
{ data: "unidadesEnviadas" },
{ data: "unidadesTotal" },
{ data: "id" },
{ data: "pesoUnidad" },
{ data: "unidadesEnvioRaw" }
];
this.table = null;
this.buscarPedidos = new ClassSelect($("#buscadorPedidos"), '/logistica/selectAddLinea', "", true, { 'envio': $("#id").val() });
this.btnAddLinea = $("#btnAddLinea");
this.btnDeleteLinea = $("#btnEliminarLineas");
this.btnGuardarComentarios = $("#guardarComentarios");
this.btnGenerarAlbaran = $("#btnGenerarAlbaran");
this.btnbtnSelectAll = $("#btnSelectAll");
this.cajas = $("#cajas");
}
init() {
this.table = $('#tableLineasEnvio').DataTable({
processing: true,
serverSide: true,
autoWidth: true,
responsive: true,
scrollX: true,
orderCellsTop: true,
orderable: false,
order: [[7, 'asc']],
lengthMenu: [5, 10, 25, 50, 75, 100, 250, 500, 1000, 2500],
pageLength: 50,
"dom": 'lrtip',
"ajax": {
"url": "/logistica/datatableLineasEnvios/" + $('#id').val(),
},
"columns": this.tableCols,
"language": {
url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json"
},
footerCallback: function (row, data, start, end, display) {
let totalUnidades = 0;
let totalPeso = 0;
data.forEach(row => {
const unidades = parseFloat(row.unidadesEnvioRaw) || 0;
const pesoUnidad = parseFloat(row.pesoUnidad) || 0;
totalUnidades += unidades;
totalPeso += unidades * pesoUnidad;
});
// Mostrar en spans personalizados del <tfoot>
$('#footer-unidades-envio').text(totalUnidades);
$('#footer-peso').text(totalPeso.toFixed(2));
},
"columnDefs": [
{
"targets": [0],
"className": "text-center",
"orderable": false,
"searchable": false,
},
{
"targets": [1, 2, 4, 5, 6],
"className": "text-center",
},
{
targets: [7, 8, 9],
visible: false
}
]
});
this.cajas.on('change', (e) => {
const value = $(e.currentTarget).val();
if (value < 0) {
Swal.fire({
title: 'Atención!',
text: 'El número de cajas no puede ser negativo.',
icon: 'info',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
$(e.currentTarget).val(0);
return;
}
$.post('/logistica/updateCajasEnvio', {
id: $('#id').val(),
cajas: value
}, function (response) {
if (!response.status) {
Swal.fire({
title: 'Error',
text: response.message,
icon: 'error',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
$(e.currentTarget).val(0);
}
}).fail(() => {
Swal.fire({
title: 'Error',
text: 'No se pudo actualizar el número de cajas.',
icon: 'error',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
$(e.currentTarget).val(0);
});
});
$(document).on('change', '.input-lineas', (e) => {
const table = this.table;
const row = table.row($(e.currentTarget).closest('tr'));
const rowData = row.data();
const fieldName = $(e.currentTarget).data('name');
const fieldValue = $(e.currentTarget).val();
$.post('/logistica/updateLineaEnvio', {
id: rowData.id,
"name": fieldName,
'value': fieldValue
}, function (response) {
if (response.status) {
table.draw(false);
} else {
Swal.fire({
title: 'Error',
text: response.message,
icon: 'error',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
table.draw(false);
}
}).fail(() => {
Swal.fire({
title: 'Error',
text: 'No se pudo actualizar el dato.',
icon: 'error',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
table.draw(false);
});
});
this.buscarPedidos.init();
if (this.btnAddLinea.length) this.btnAddLinea.on('click', this._addEnvioLinea.bind(this));
if (this.btnDeleteLinea.length) this.btnDeleteLinea.on('click', this._deleteLineas.bind(this));
if (this.btnGenerarAlbaran.length) this.btnGenerarAlbaran.on('click', this._generarAlbaran.bind(this));
if (this.btnGuardarComentarios.length) {
this.btnGuardarComentarios.on('click', () => {
$.post('/logistica/updateComentariosEnvio', {
id: $('#id').val(),
comentarios: $('#comentarios').val()
}, function (response) {
if (response.status) {
popSuccessAlert('Comentarios guardados correctamente');
} else {
popErrorAlert(response.message);
}
}).fail((error) => {
popErrorAlert(error.responseJSON.message);
});
});
}
this.btnbtnSelectAll.on('click', () => {
const checkboxes = this.table.$('input[type="checkbox"]');
const allChecked = checkboxes.length === checkboxes.filter(':checked').length;
checkboxes.prop('checked', !allChecked);
}
);
this._getAlbaranes();
}
_getAlbaranes() {
$.get('/albaranes/albaranesEnvio', {
envio_id: $('#id').val(),
}, function (response) {
if (response.status && response.data) {
for (let i = 0; i < response.data.length; i++) {
const albaran = response.data[i];
new AlbaranComponent(albaran).mount('#contenedorAlbaranes');
}
} else {
Swal.fire({
title: 'Error',
text: response.message,
icon: 'error',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
}
}).fail(() => {
Swal.fire({
title: 'Error',
text: 'No se han podido obtener los albaranes.',
icon: 'error',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
});
}
_generarAlbaran() {
const table = this.table;
const selectedRows = table.rows({ page: 'current' }).nodes().filter((node) => {
const checkbox = $(node).find('.checkbox-linea-envio');
return checkbox.is(':checked');
});
const ids = selectedRows.map((node) => {
const rowData = table.row(node).data();
return rowData.id;
}).toArray();
if (ids.length <= 0) {
Swal.fire({
title: 'Atención!',
text: 'Debe seleccionar al menos una línea de envío para generar el albarán.',
icon: 'info',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
return;
}
const idEnvio = $('#id').val();
$.post('/albaranes/generarAlbaran', {
envio_id: idEnvio,
envio_lineas: ids,
cajas: this.cajas.val()
}, function (response) {
if (response.status && response.albaran) {
new AlbaranComponent(response.albaran).mount('#contenedorAlbaranes');
} else {
Swal.fire({
title: 'Error',
text: response.message,
icon: 'error',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
}
}).fail(() => {
Swal.fire({
title: 'Error',
text: 'No se pudo generar el albarán.',
icon: 'error',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
});
}
_deleteLineas() {
const table = this.table;
const selectedRows = table.rows({ page: 'current' }).nodes().filter((node) => {
const checkbox = $(node).find('.checkbox-linea-envio');
return checkbox.is(':checked');
});
const ids = selectedRows.map((node) => {
const rowData = table.row(node).data();
return rowData.id;
}).toArray();
if (ids.length > 0) {
Swal.fire({
title: 'Eliminar líneas de envío',
text: '¿Está seguro de que desea eliminar las líneas seleccionadas?',
icon: 'warning',
showCancelButton: true,
confirmButtonText: 'Sí',
cancelButtonText: 'Cancelar',
customClass: {
confirmButton: 'btn btn-danger me-1',
cancelButton: 'btn btn-secondary'
},
buttonsStyling: false
}).then((result) => {
if (result.isConfirmed) {
$.post('/logistica/deleteLineasEnvio', {
ids: ids
}, function (response) {
if (response.status) {
table.draw(false);
} else {
Swal.fire({
title: 'Error',
text: response.message,
icon: 'error',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
table.ajax.reload();
}
}).fail(() => {
Swal.fire({
title: 'Error',
text: 'No se pudo eliminar la línea de envío.',
icon: 'error',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
table.ajax.reload();
});
}
});
} else {
Swal.fire({
title: 'Sin filas seleccionadas',
text: 'Marca al menos una línea para eliminarla.',
icon: 'info',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
}
}
_addEnvioLinea() {
if (!this.buscarPedidos.getVal()) {
Swal.fire({
title: 'Atención!',
text: 'Debe seleccionar un pedido antes de añadir una línea de envío.',
icon: 'info',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
return;
}
new Ajax('/logistica/addLineaEnvio', {
'envio_id': $('#id').val(),
'pedido_id': this.buscarPedidos.getVal(),
'direccion': $("#direccion").val()
}, {},
(response) => {
if (response.status) {
this.table.draw();
this.buscarPedidos.empty();
} else {
Swal.fire({
title: 'Atención!',
text: response.message,
icon: 'info',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Ok',
customClass: {
confirmButton: 'btn btn-primary me-1',
},
buttonsStyling: false
});
}
}, (error) => {
console.error(error);
}).get();
}
}
document.addEventListener('DOMContentLoaded', function () {
const dropdown = document.querySelector(".dropdown-language");
const activeItem = dropdown.querySelector(".dropdown-menu .dropdown-item");
let locale = 'es';
if (activeItem) {
locale = activeItem.getAttribute("data-language");
}
new Ajax('/translate/getTranslation', { locale: locale, translationFile: ['Albaran'] }, {},
function (translations) {
window.language = JSON.parse(translations);
new EnvioEdit().init();
},
function (error) {
console.log("Error getting translations:", error);
}
).post();
});
export default EnvioEdit;

View File

@ -129,8 +129,10 @@ class PresupuestoAdminEdit {
let totalCostes = AutoNumeric.getAutoNumericElement($('#totalCostes')[0]);
let envio_base = AutoNumeric.getAutoNumericElement($('#precioEnvios')[0]);
let autoTotalAceptado = AutoNumeric.getAutoNumericElement($('#total_aceptado_revisado')[0]);
let totalMargenes = AutoNumeric.getAutoNumericElement($('#totalMargenes')[0]);
let total_aceptado_revisado = autoTotalAceptado.getNumber();
if (total_aceptado_revisado && total_aceptado_revisado != 0) {
const nuevoTotal = totalCostes.getNumber() + envio_base.getNumber();
@ -140,7 +142,7 @@ class PresupuestoAdminEdit {
total_aceptado_revisado = nuevoTotal;
}
totalMargenes = total_aceptado_revisado - nuevoTotal;
totalMargenes.set(total_aceptado_revisado - nuevoTotal);
}
}.bind(this));

View File

@ -130,4 +130,9 @@
.beta {
color: orangered !important;
}
.dtrg-group.ui-droppable-hover {
background-color: #d1ecf1 !important;
cursor: move;
}