Merge branch 'dev/pedidos_v1' into 'main'

Dev/pedidos v1

See merge request jjimenez/safekat!273
This commit is contained in:
2024-06-16 00:10:32 +00:00
29 changed files with 2953 additions and 76 deletions

View File

@ -350,6 +350,7 @@ $routes->group('clientes', ['namespace' => 'App\Controllers\Clientes'], function
/* Cliente */
$routes->group('cliente', ['namespace' => 'App\Controllers\Clientes'], function ($routes) {
$routes->get('', 'Cliente::index', ['as' => 'clienteList']);
$routes->get('edit/(:num)', 'Cliente::edit/$1', ['as' => 'editarCliente']);
$routes->match(['get', 'post'], 'add', 'Cliente::add', ['as' => 'clienteAdd']);
$routes->match(['get', 'post'], 'edit/(:num)', 'Cliente::edit/$1', ['as' => 'clienteEdit']);
$routes->get('delete/(:num)', 'Cliente::delete/$1', ['as' => 'clienteDelete']);
@ -550,6 +551,7 @@ $routes->resource('clientedirecciones', ['namespace' => 'App\Controllers\Cliente
$routes->group('cosidotapablanda', ['namespace' => 'App\Controllers\Presupuestos'], function ($routes) {
$routes->get('list/(:num)', 'Cosidotapablanda::list/$1', ['as' => 'cosidotapablandaList']); // HOMOGENIZAR CON ARGS DINAMICOS!!!
$routes->get('add/(:num)', 'Cosidotapablanda::add/$1', ['as' => 'newCosidotapablanda']);
$routes->get('edit/(:any)', 'Cosidotapablanda::edit/$1', ['as' => 'editarPresupuesto']);
$routes->post('add/(:num)', 'Cosidotapablanda::add/$1', ['as' => 'createCosidotapablanda']);
$routes->post('create', 'Cosidotapablanda::create', ['as' => 'ajaxCreateCosidotapablanda']);
$routes->put('(:num)/update', 'Cosidotapablanda::update/$1', ['as' => 'ajaxUpdateCosidotapablanda']);
@ -567,6 +569,7 @@ $routes->group('presupuestocliente', ['namespace' => 'App\Controllers\Presupuest
$routes->get('add', 'Presupuestocliente::add', ['as' => 'nuevoPresupuestoCliente']);
$routes->post('add', 'Presupuestocliente::add', ['as' => 'crearPresupuestoCliente']);
$routes->post('edit/(:num)', 'Presupuestocliente::edit/$1', ['as' => 'editarPresupuestoCliente']);
$routes->get('edit/(:any)', 'Presupuestocliente::edit/$1', ['as' => 'editarPresupuestoCliente2']);
$routes->post('getgramaje', 'Presupuestocliente::getGramaje', ['as' => 'obtenerGramaje']);
$routes->post('presupuesto', 'Presupuestocliente::presupuesto', ['as' => 'presupuestoCliente']);
$routes->post('getDireccionesCliente', 'Presupuestocliente::getDireccionesCliente', ['as' => 'getDirecciones']);
@ -615,6 +618,35 @@ $routes->group('presupuestotiradasalternativas', ['namespace' => 'App\Controller
$routes->post('datatable_2', 'Presupuestotiradasalternativas::datatable_2', ['as' => 'getTiradaData']);
});
$routes->group('pedidos', ['namespace' => 'App\Controllers\Pedidos'], function ($routes) {
$routes->get('list', 'Pedido::todos', ['as' => 'listaPresupuestos']);
$routes->get('listActivos', 'Pedido::activos', ['as' => 'listaPresupuestosActivos']);
$routes->get('listFinalizados', 'Pedido::finalizados', ['as' => 'listaFinalizados']);
$routes->get('listCancelados', 'Pedido::cancelados', ['as' => 'listaCancelados']);
$routes->post('datatable', 'Pedido::datatable', ['as' => 'dataTableOfPedidos']);
$routes->get('add', 'Pedido::add', ['as' => 'nuevoPedido']);
$routes->post('add', 'Pedido::add', ['as' => 'crearPedido']);
$routes->get('edit/(:any)', 'Pedido::edit/$1', ['as' => 'editarPedido']);
$routes->post('getlineas', 'Pedido::getLineas', ['as' => 'tablaLineasPedido']);
$routes->post('cambiarestado', 'Pedido::cambiarEstado', ['as' => 'cambiarEstadoPedido']);
$routes->post('update/(:any)', 'Pedido::update/$1', ['as' => 'actualizarPedido']);
});
$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->resource('albaranes', ['namespace' => 'App\Controllers\Pedidos', 'controller' => 'Albaran', 'except' => 'show,new,create,update']);
$routes->group(

View File

@ -1,30 +0,0 @@
<?php
namespace App\Controllers\Facturacion;
use App\Controllers\BaseController;
class Albaran extends BaseController
{
function __construct()
{
}
public function index()
{
echo 'Albaran';
}
public function delete()
{
}
public function export()
{
}
}

View File

@ -0,0 +1,388 @@
<?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

@ -2,54 +2,301 @@
namespace App\Controllers\Pedidos;
use App\Controllers\BaseController;
use App\Entities\Pedidos\PedidoEntity;
use App\Models\Collection;
use App\Models\Pedidos\PedidoModel;
class Pedido extends BaseController
class Pedido extends \App\Controllers\BaseResourceController
{
function __construct()
{
protected $modelName = PedidoModel::class;
protected $format = 'json';
protected static $singularObjectNameCc = 'pedido';
protected static $singularObjectName = 'Pedido';
protected static $pluralObjectName = 'Pedidos';
protected static $controllerSlug = 'pedido';
protected static $viewPath = 'themes/vuexy/form/pedidos/';
protected $indexRoute = 'pedidoList';
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
$this->viewData['pageTitle'] = lang('Pedidos.moduleTitle');
// Se indica que este controlador trabaja con soft_delete
$this->viewData = ['usingServerSideDataTable' => true];
// Breadcrumbs
$this->viewData['breadcrumb'] = [
['title' => lang("App.menu_pedidos"), 'route' => "javascript:void(0);", 'active' => false],
];
parent::initController($request, $response, $logger);
}
public function index()
{
echo 'Pedidos';
$this->viewData['usingClientSideDataTable'] = true;
$this->viewData['pageSubTitle'] = lang('Basic.global.ManageAllRecords', [lang('Tarifaextra.tarifaextra')]);
parent::index();
}
public function activos()
{
echo 'Pedidos Activos';
$viewData = [
'currentModule' => static::$controllerSlug,
'pageSubTitle' => lang('Basic.global.ManageAllRecords', [lang('Pedidos.pedido')]),
'presupuestoEntity' => new PedidoEntity(),
'usingServerSideDataTable' => true,
'pageTitle' => lang('Pedidos.Pedidos'),
'estadoPedidos' => 'activo',
['title' => lang("App.menu_pedidos"), 'route' => site_url('pedidos/todos'), 'active' => true]
];
return view(static::$viewPath . 'viewPedidosList', $viewData);
}
public function finalizados()
{
echo 'Pedidos Finalizados';
$viewData = [
'currentModule' => static::$controllerSlug,
'pageSubTitle' => lang('Basic.global.ManageAllRecords', [lang('Pedidos.pedido')]),
'presupuestoEntity' => new PedidoEntity(),
'usingServerSideDataTable' => true,
'pageTitle' => lang('Pedidos.Pedidos'),
'estadoPedidos' => 'finalizado',
['title' => lang("App.menu_pedidos"), 'route' => site_url('pedidos/todos'), 'active' => true]
];
return view(static::$viewPath . 'viewPedidosList', $viewData);
}
public function cancelados()
{
echo 'Pedidos Cancelados';
$viewData = [
'currentModule' => static::$controllerSlug,
'pageSubTitle' => lang('Basic.global.ManageAllRecords', [lang('Pedidos.pedido')]),
'presupuestoEntity' => new PedidoEntity(),
'usingServerSideDataTable' => true,
'pageTitle' => lang('Pedidos.Pedidos'),
'estadoPedidos' => 'cancelado',
['title' => lang("App.menu_pedidos"), 'route' => site_url('pedidos/todos'), 'active' => true]
];
return view(static::$viewPath . 'viewPedidosList', $viewData);
}
public function manuales()
public function todos()
{
echo 'Pedidos Manuales';
$viewData = [
'currentModule' => static::$controllerSlug,
'pageSubTitle' => lang('Basic.global.ManageAllRecords', [lang('Pedidos.pedido')]),
'presupuestoEntity' => new PedidoEntity(),
'usingServerSideDataTable' => true,
'pageTitle' => lang('Pedidos.Pedidos'),
'estadoPedidos' => 'todos',
['title' => lang("App.menu_pedidos"), 'route' => site_url('pedidos/todos'), 'active' => true]
];
return view(static::$viewPath . 'viewPedidosList', $viewData);
}
// public function delete_files()
// {
//
// }
//
// public function pedidos_maquetacion()
// {
//
// }
//
// public function pedidos_prestashop()
// {
//
// }
public function cambiarEstado(){
if($this->request->isAJAX()){
$id = $this->request->getPost('id');
$estado = $this->request->getPost('estado');
$this->model->where('id', $id)->set(['estado' => $estado])->update();
return $this->respond(['status' => 'success', 'message' => lang('Basic.global.success')]);
}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);
$pedidoEntity = $this->model->find($id);
if ($pedidoEntity == false) :
$message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Pedidos.pedido')), $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;
$pedidoEntity->fill($sanitizedData);
endif;
if ($noException && $successfulResult) :
$id = $pedidoEntity->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 edit($id=null){
if ($id == null) :
return $this->redirect2listView();
endif;
$id = filter_var($id, FILTER_SANITIZE_URL);
$pedidoEntity = $this->model->find($id);
if ($pedidoEntity == false) :
$message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Pedidos.pedido')), $id]);
return $this->redirect2listView('sweet-error', $message);
endif;
$this->obtenerDatosFormulario($pedidoEntity);
$this->viewData['pedidoEntity'] = $pedidoEntity;
$this->viewData['boxTitle'] = lang('Basic.global.edit2') . ' ' . lang('Pedidos.moduleTitle') . ' ' . lang('Basic.global.edit3');
return $this->displayForm(__METHOD__, $id);
}
public function datatable(){
if ($this->request->isAJAX()) {
$reqData = $this->request->getPost();
if (!isset($reqData['draw']) || !isset($reqData['columns']) ) {
$errstr = 'No data available in response to this specific request.';
$response = $this->respond(Collection::datatable( [], 0, 0, $errstr ), 400, $errstr);
return $response;
}
$start = $reqData['start'] ?? 0;
$length = $reqData['length'] ?? 5;
$search = $reqData['search']['value'];
$requestedOrder = $reqData['order']['0']['column'] ?? 0;
$order = PedidoModel::SORTABLE_TODOS[$requestedOrder >= 0 ? $requestedOrder : 0];
$dir = $reqData['order']['0']['dir'] ?? 'asc';
$estado = $reqData['estado'] ?? 'todos';
if($estado == 'todos') $estado = '';
$model_linea = model('\App\Models\Pedidos\PedidoLineaModel');
$resourceData = $model_linea->getResource($search, $estado)->orderBy($order, $dir)->limit($length, $start)->get()->getResultObject();
return $this->respond(Collection::datatable(
$resourceData,
$model_linea->getResource("", $estado)->countAllResults(),
$model_linea->getResource($search, $estado)->countAllResults()
));
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function getlineas(){
if ($this->request->isAJAX()) {
$reqData = $this->request->getPost();
if (!isset($reqData['draw']) || !isset($reqData['columns']) ) {
$errstr = 'No data available in response to this specific request.';
$response = $this->respond(Collection::datatable( [], 0, 0, $errstr ), 400, $errstr);
return $response;
}
$id = $reqData['pedido_id'] ?? 0;
$resourceData = $this->model->obtenerLineasPedido($id);
return $this->respond(Collection::datatable(
$resourceData,
count($resourceData),
count($resourceData)
));
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
private function obtenerDatosFormulario(&$pedidoEntity){
$datos = $this->model->obtenerDatosForm($pedidoEntity->id);
$pedidoEntity->estadoText = lang('Pedidos.' . $pedidoEntity->estado);
if(count($datos) > 0){
$pedidoEntity->cliente = $datos[0]->cliente;
$pedidoEntity->cliente_id = $datos[0]->cliente_id;
$pedidoEntity->comercial = $datos[0]->comercial;
}
$pedidoEntity->fecha_entrega_real_text = $pedidoEntity->fecha_entrega_real ? date('d/m/Y', strtotime($pedidoEntity->fecha_entrega_real)) : '';
$pedidoEntity->fecha_impresion_text = $pedidoEntity->fecha_impresion ? date('d/m/Y', strtotime($pedidoEntity->fecha_impresion)) : '';
$pedidoEntity->fecha_encuadernado_text = $pedidoEntity->fecha_encuadernado ? date('d/m/Y', strtotime($pedidoEntity->fecha_encuadernado)) : '';
$pedidoEntity->fecha_entrega_externo_text = $pedidoEntity->fecha_entrega_externo ? date('d/m/Y', strtotime($pedidoEntity->fecha_entrega_externo)) : '';
}
}

View File

@ -20,6 +20,7 @@ use Exception;
use function PHPUnit\Framework\containsOnly;
class Presupuestocliente extends \App\Controllers\BaseResourceController
{
protected $modelName = "PresupuestoModel";
@ -787,6 +788,7 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
if ($confirmar) {
$model_presupuesto->confirmarPresupuesto($id);
$this->crearPedido($id);
}
return $this->respond([
@ -889,6 +891,44 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
* Funciones auxiliares
*
**********************/
public function crearPedido($presupuesto_id)
{
$model_pedido = model('App\Models\Pedidos\PedidoModel');
$model_pedido_linea = model('App\Models\Pedidos\PedidoLineaModel');
$model_cliente = model('App\Models\Clientes\ClienteModel');
$model_presupuesto = new PresupuestoModel();
$datos_presupuesto = $model_presupuesto->find($presupuesto_id);
$id_linea = 0;
$data_pedido = [
'total_precio' => $datos_presupuesto->total_aceptado,
'total_tirada' => $datos_presupuesto->tirada,
'estado' => $model_cliente->creditoDisponible($datos_presupuesto->cliente_id) ? "produccion" : "validacion",
'user_created_id' => auth()->user()->id,
'user_updated_id' => auth()->user()->id,
];
$pedido_id = $model_pedido->insert($data_pedido);
if($pedido_id){
$data_pedido_linea = [
"pedido_id" => $pedido_id,
"presupuesto_id" => $presupuesto_id,
"ubicacion_id" => 1, // safetak por defecto
"user_created_id" => auth()->user()->id,
"user_updated_id" => auth()->user()->id,
];
$id_linea = $model_pedido_linea->insert($data_pedido_linea);
}
if($id_linea != 0 && $pedido_id != 0){
return true;
}
return false;
}
protected function borrarRelacionesPresupuesto($id)
{
// Se borran las lineas de presupuesto

View File

@ -20,18 +20,11 @@ class Test extends BaseController
public function index()
{
helper('rbac');
//$user = auth()->user();
//generate_php_permissions_constant();
echo generate_php_permissions_matrix_constant();
//$user->syncGroups('admin');
//var_dump($user->can('token.menu'));
$model = new PresupuestoModel();
$data = $model->generarLineaPedido(123);
echo '<pre>';
var_dump($data);
echo '</pre>';
}

View File

@ -0,0 +1,46 @@
<?php
namespace App\Entities\Pedidos;
use CodeIgniter\Entity;
class AlbaranEntity extends \CodeIgniter\Entity\Entity
{
protected $attributes = [
'id' => null,
'pedido_id' => null,
'presupuesto_id' => null,
'presupuesto_direccion_id' => null,
'cliente_id' => null,
'serie_id' => null,
'numero_albaran' => null,
'mostrar_precios' => null,
'total' => null,
'direccion_albaran' => null,
'att_albaran' => null,
'user_created_id' => null,
'user_updated_id' => null,
'created_at' => null,
'updated_at' => null,
'deleted_at' => null,
];
protected $dates = ['created_at', 'updated_at', 'deleted_at'];
protected $casts = [
'id' => 'integer',
'pedido_id' => '?integer',
'presupuesto_id' => '?integer',
'presupuesto_direccion_id' => '?integer',
'cliente_id' => '?integer',
'serie_id' => '?integer',
'numero_albaran' => '?string',
'mostrar_precios' => '?boolean',
'total' => 'float',
'direccion_albaran' => '?string',
'att_albaran' => '?string',
'user_created_id' => 'integer',
'user_updated_id' => 'integer',
];
// Agrega tus métodos personalizados aquí
}

View File

@ -0,0 +1,40 @@
<?php
namespace App\Entities\Pedidos;
use CodeIgniter\Entity;
class AlbaranLineaEntity extends \CodeIgniter\Entity\Entity
{
protected $attributes = [
'id' => null,
'albaran_id' => null,
'titulo' => null,
'isbn' => null,
'ref_cliente' => null,
'cantidad' => null,
'cajas' => null,
'ejemplares_por_caja' => null,
'precio_unidad' => null,
'total' => null,
'user_created_id' => null,
'user_updated_id' => null,
'created_at' => null,
'updated_at' => null,
'deleted_at' => null,
];
protected $casts = [
'id' => 'integer',
'albaran_id' => '?integer',
'titulo' => 'string',
'isbn' => '?string',
'ref_cliente' => '?string',
'cantidad' => '?integer',
'cajas' => '?integer',
'ejemplares_por_caja' => '?integer',
'precio_unidad' => 'float',
'total' => 'float',
'user_created_id' => 'integer',
'user_updated_id' => 'integer',
];
}

View File

@ -0,0 +1,30 @@
<?php
namespace App\Entities\Pedidos;
use CodeIgniter\Entity;
class PedidoEntity extends \CodeIgniter\Entity\Entity
{
protected $attributes = [
"id" => null,
"total_precio" => null,
"total_tirada" => null,
"estado" => null,
"user_created_id" => null,
"user_updated_id" => null,
"user_validated_id" => null,
"fecha_entrega_real" => null,
"fecha_impresion" => null,
"fecha_encuadernado" => null,
"fecha_entrega_externo" => null,
"created_at" => null,
"updated_at" => null,
"validated_at" => null,
];
protected $casts = [
"total_precio" => "float",
"total_tirada" => "float",
];
}

View File

@ -0,0 +1,25 @@
<?php
namespace App\Entities\Pedidos;
use CodeIgniter\Entity;
class PedidoLineaEntity extends \CodeIgniter\Entity\Entity
{
protected $attributes = [
"id" => null,
"pedido_id" => null,
"presupuesto_id" => null,
"ubicacion_id" => null,
"user_created_id" => null,
"user_updated_id" => null,
"created_at" => null,
"updated_at" => null,
];
protected $casts = [
"pedido_id" => "int",
"presupuesto_id" => "int",
"ubicacion_id" => "int",
];
}

View File

@ -731,7 +731,7 @@ return [
"menu_pedidos_activos" => "Actives",
"menu_pedidos_finalizados" => "Finished",
"menu_pedidos_cancelados" => "Cancelled",
"menu_pedidos_manuales" => "Manual",
"menu_pedidos_todos" => "All",
"menu_presupuestos" => "Budgets",
"menu_presupuesto" => "Books",

View File

@ -0,0 +1,82 @@
<?php
return [
'id' => 'Number',
'fecha' => 'Date',
'fecha_entrega' => 'Delivery Date',
'cliente' => 'Client',
'comercial' => 'Commercial',
'titulo' => 'Title',
'ubicacion' => 'Location',
'inc_rei' => 'Inc/Rei', // This seems to be a specific term, left as is
'num_paginas' => 'Number of Pages',
'tiradas' => 'Print Runs',
'total_presupuesto' => 'Total Budget',
'estado' => 'Status',
'validacion' => 'Validation',
'produccion' => 'Production',
'finalizado' => 'Finished',
'enviado' => 'Sent',
'cancelado' => 'Cancelled',
'datosPedido' => 'Order Details',
'totales' => 'Totales',
'total_precio' => 'Total price',
"total_tirada" => 'Total print',
'fechas' => "Dates",
'fecha_entrega_real' => 'Actual Delivery Date',
'fecha_impresion' => 'Printing Date',
'fecha_encuadernado' => 'Binding Date',
'fecha_entrega_externo' => 'External Delivery Date',
'lineas' => 'Lines',
'unidades' => "Units",
'concepto' => "Concept",
'total' => "Total",
'presupuesto' => 'Budget',
'moduleTitle' => 'Orders',
'pedido' => 'Order',
'pedidos' => 'Orders',
'pedidosList' => 'Orders List',
'cancelar' => 'Cancel',
'finalizar' => 'Finish',
'unaCara' => '1 side',
'dosCaras' => '2 sides',
'lineasTemplates' =>[
'libro' => "[BUDGET %s] Printing of %s copies of %s pages.\nTitle: %s. Author: %s. ISBN: %s.Size: %smm.\n",
'libro_linea_interior' => "%s black pages on %s paper of %s grams",
'libro_linea_cubierta' => "\nCover printed on %s on %s paper of %s grams",
'libro_linea_sobrecubierta' => "\nDust jacket on %s paper of %s grams",
'libro_solapas' => " with flaps of %smm.",
'libro_encuadernacion' => "\nType of binding: %s"
],
'albaranes' => 'Delivery Notes',
'albaran' => 'Delivery Note',
'generarAlbaranes' => 'Generate delivery notes',
'borrarAlbaranes' => 'Delete delivery notes',
'att' => "Att",
'direccion' => 'Address',
'borrarAlbaran' => 'Delete delivery note',
'imprimirAlbaran' => 'Print',
'nuevaLinea' => 'New line',
'addIva' => "Add VAT",
'mostrarPrecios' => 'Show prices',
'iva4' => "4,00 % VAT",
'iva21' => "21,00 % VAT",
'facturas' => 'Invoices',
'validation' => [
],
];

View File

@ -739,7 +739,7 @@ return [
"menu_pedidos_activos" => "Activos",
"menu_pedidos_finalizados" => "Finalizados",
"menu_pedidos_cancelados" => "Cancelados",
"menu_pedidos_manuales" => "Manuales",
"menu_pedidos_todos" => "Todos",
"menu_presupuestos" => "Presupuestos",
"menu_presupuesto" => "Libros",

View File

@ -0,0 +1,84 @@
<?php
return [
'id' => 'Número',
'fecha' => 'Fecha',
'fecha_entrega' => 'Fecha <br>Entrega',
'cliente' => 'Cliente',
'comercial' => 'Comercial',
'titulo' => 'Título',
'ubicacion' => 'Ubicación',
'inc_rei' => 'Inc/Rei',
'num_paginas' => 'Nº Páginas',
'tiradas' => 'Tiradas',
'total_presupuesto' => 'Total',
'estado' => 'Estado',
'validacion' => 'Validación',
'produccion' => 'Producción',
'finalizado' => 'Finalizado',
'enviado' => 'Enviado',
'cancelado' => 'Cancelado',
'datosPedido' => 'Datos del pedido',
'totales' => 'Totales',
'total_precio' => 'Total precio',
"total_tirada" => 'Total tirada',
'fechas' => "Fechas",
'fecha_entrega_real' => "Fecha entrega real",
'fecha_impresion' => "Fecha impresion",
'fecha_encuadernado' => "Fecha encuadernado",
'fecha_entrega_externo' => "Fecha entrega externo",
'lineas' => 'Líneas pedido',
'unidades' => "Unidades",
'concepto' => "Concepto",
'total' => "Total",
'presupuesto' => 'Presupuesto',
'moduleTitle' => 'Pedidos',
'pedido' => 'Pedido',
'pedidos' => 'Pedidos',
'pedidosList' => 'Lista de Pedidos',
'cancelar' => 'Cancelar',
'finalizar' => 'Finalizar',
'unaCara' => '1 cara',
'dosCaras' => '2 caras',
'lineasTemplates' =>[
'libro' => "[PRESUPUESTO %s] Impresión de %s ejemplares de %s páginas.\nTítulo: %s. Autor: %s. ISBN: %s.Tamaño: %smm.\n",
'libro_linea_interior' => "%s páginas en negro sobre papel %s de %s gramos",
'libro_linea_cubierta' => "\nCubierta impresa a %s sobre papel %s de %s gramos",
'libro_linea_sobrecubierta' => "\nSobrecubierta sobre papel %s de %s gramos",
'libro_solapas' => " con solapas de %smm." ,
'libro_encuadernacion' => "\nTipo de encuadernación: %s"
],
'albaranes' => 'Albaranes',
'albaran' => 'Albarán',
'generarAlbaranes' => 'Generar albaranes',
'borrarAlbaranes' => 'Borrar albaranes',
'att' => "Att",
'direccion' => 'Direccion',
'borrarAlbaran' => 'Borrar albarán',
'imprimirAlbaran' => 'Imprimir',
'nuevaLinea' => 'Nueva línea',
'addIva' => "Añadir IVA",
'mostrarPrecios' => 'Mostrar precios',
'iva4' => "4,00 % IVA",
'iva21' => "21,00 % IVA",
'facturas' => 'Facturas',
'validation' => [
],
];

View File

@ -308,4 +308,11 @@ class ClienteModel extends \App\Models\BaseModel
->orLike("t7.nombre", $search)
->groupEnd();
}
/*
TO-DO: Implementar la lógica de negocio para el crédito disponible
*/
public function creditoDisponible($cliente_id){
return true;
}
}

View File

@ -0,0 +1,41 @@
<?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';
}

View File

@ -0,0 +1,113 @@
<?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){
// 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' => $envio->cantidad,
'cajas' => 1,
'ejemplares_por_caja' => $envio->cantidad,
'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;
}
}

View File

@ -0,0 +1,79 @@
<?php
namespace App\Models\Pedidos;
class PedidoLineaModel extends \App\Models\BaseModel
{
protected $table = "pedidos_linea";
/**
* Whether primary key uses auto increment.
*
* @var bool
*/
protected $useAutoIncrement = true;
const SORTABLE = [
0 => "t1.id",
1 => "t1.estado",
2 => "t1.total_precio",
3 => "t1.total_tirada",
];
protected $allowedFields = [
"pedido_id",
"presupuesto_id",
"ubicacion_id",
"user_created_id",
"user_updated_id",
"created_at",
"updated_at",
];
protected $returnType = "App\Entities\Pedidos\PedidoLineaEntity";
protected $useTimestamps = true;
protected $useSoftDeletes = false;
protected $createdField = "created_at";
protected $updatedField = "updated_at";
public static $labelField = "id";
public function getResource(string $search = "", $estado="")
{
$builder = $this->db
->table($this->table . " t1")
->select(
"t2.id AS id, t2.updated_at AS fecha, t2.fecha_entrega_real AS fecha_entrega,
t4.nombre AS cliente, CONCAT(t5.first_name, ' ', t5.last_name) AS comercial,
t3.titulo AS titulo, t6.nombre AS ubicacion, t3.inc_rei AS inc_rei,
t3.paginas AS paginas, t3.tirada AS tirada, t3.total_aceptado AS total_presupuesto,
t2.estado AS estado"
);
$builder->join("pedidos t2", "t2.id = t1.pedido_id", "left");
$builder->join("presupuestos t3", "t1.presupuesto_id = t3.id", "left");
$builder->join("clientes t4", "t4.id = t3.cliente_id", "left");
$builder->join("users t5", "t5.id = t4.comercial_id", "left");
$builder->join("ubicaciones t6", "t6.id = t1.ubicacion_id", "left");
if($estado != "") {
if($estado == "activo") {
$sql = "t2.estado = 'validacion' OR t2.estado = 'produccion'";
$builder->where($sql);
} else {
$builder->where("t2.estado", $estado);
}
}
// Falta implementar la busqueda por grupos
return empty($search)
? $builder
: $builder
->groupStart()
->like("t1.id", $search)
->orLike("t1.id", $search)
->groupEnd();
}
}

View File

@ -0,0 +1,88 @@
<?php
namespace App\Models\Pedidos;
class PedidoModel extends \App\Models\BaseModel
{
protected $table = "pedidos";
/**
* Whether primary key uses auto increment.
*
* @var bool
*/
protected $useAutoIncrement = true;
const SORTABLE_TODOS = [
0 => "t1.id",
1 => "t1.updated_at",
2 => "t1.fecha_entrega_real",
3 => "t4.nombre",
4 => "t5.first_name",
5 => "t3.titulo",
6 => "t6.ubicacion",
7 => "t3.inc_rei",
8 => "t3.paginas",
9 => "t3.tirada",
10 => "t3.total_aceptado",
11 => "t1.estado"
];
protected $allowedFields = [
"total_precio",
"total_tirada",
"estado",
"user_created_id",
"user_updated_id",
"user_validated_id",
"fecha_entrega_real",
"fecha_impresion",
"fecha_encuadernado",
"fecha_entrega_externo",
"created_at",
"updated_at",
"validated_at",
];
protected $returnType = "App\Entities\Pedidos\PedidoEntity";
protected $useTimestamps = true;
protected $useSoftDeletes = false;
protected $createdField = "created_at";
protected $updatedField = "updated_at";
public static $labelField = "id";
public function obtenerDatosForm($pedido_id){
$builder = $this->db
->table($this->table . " t1")
->select(
"t4.id AS cliente_id, t4.nombre AS cliente, CONCAT(t5.first_name, ' ', t5.last_name) AS comercial");
$builder->join("pedidos_linea t2", "t2.pedido_id = t1.id", "left");
$builder->join("presupuestos t3", "t2.presupuesto_id = t3.id", "left");
$builder->join("clientes t4", "t4.id = t3.cliente_id", "left");
$builder->join("users t5", "t5.id = t4.comercial_id", "left");
return $builder->get()->getResultObject();
}
public function obtenerLineasPedido($pedido_id){
$builder = $this->db
->table($this->table . " t1")
->select(
"t2.presupuesto_id"
);
$builder->where("t1.id", $pedido_id);
$builder->join("pedidos_linea t2", "t2.pedido_id = t1.id", "left");
$model_presupuesto = model("App\Models\Presupuestos\PresupuestoModel");
$lineasPresupuesto = [];
foreach($builder->get()->getResultObject() as $row){
array_push($lineasPresupuesto, $model_presupuesto->generarLineaPedido($row->presupuesto_id)[0]);
}
return $lineasPresupuesto;
}
}

View File

@ -538,5 +538,172 @@ class PresupuestoModel extends \App\Models\BaseModel
return $json;
}
public function generarLineaPedido($presupuesto_id)
{
$builder = $this->db
->table($this->table . " t1")
->select(
"t1.id AS numero, t1.tipo_impresion_id as tipo, t1.tirada AS unidades, t1.total_aceptado as total, t1.paginas AS paginas,
t1.titulo AS titulo, t1.autor AS autor, t1.isbn AS isbn,
t1.papel_formato_id AS papel_formato_id, t1.papel_formato_personalizado AS papel_formato_personalizado,
t1.papel_formato_ancho AS papel_formato_ancho, t1.papel_formato_alto AS papel_formato_alto,
CONCAT(CAST(t2.ancho AS INT), 'x', CAST(t2.alto AS INT)) AS tamanio,
t3.codigo AS codigo_encuadernacion,
t1.solapas AS solapas_cubierta, CAST(t1.solapas_ancho AS INT) AS solapas_ancho_cubierta,
t1.solapas_sobrecubierta AS solapas_sobrecubierta, CAST(t1.solapas_ancho_sobrecubierta AS INT) AS solapas_ancho_sobrecubierta,"
);
$builder->join("lg_papel_formato t2", "t1.papel_formato_id = t2.id", "left");
$builder->join("tipos_presupuestos t3", "t1.tipo_impresion_id = t3.id", "left");
$builder->where("t1.is_deleted", 0);
$builder->where("t1.id", $presupuesto_id);
$presupuesto = $builder->get()->getResultObject();
if(count($presupuesto) > 0){
$modelLinea = model('App\Models\Presupuestos\PresupuestoLineaModel');
$lineas = $modelLinea->where('presupuesto_id', $presupuesto_id)->findAll();
$presupuesto = $presupuesto[0];
// Libro
if($presupuesto->tipo < 10){
if($presupuesto->papel_formato_personalizado == 1){
$presupuesto->tamanio= $presupuesto->papel_formato_ancho . "x" . $presupuesto->papel_formato_alto;
}
$presupuesto->concepto = sprintf(lang('Pedidos.lineasTemplates.libro'),
$presupuesto->numero,
$presupuesto->unidades,
$presupuesto->paginas,
$presupuesto->titulo,
$presupuesto->autor,
$presupuesto->isbn,
$presupuesto->tamanio);
$presupuesto->concepto .= $this->generarConceptoLineasPresupuestoLibro($lineas, $presupuesto);
$presupuesto = (object)[
'numero' => $presupuesto->numero,
'unidades' => $presupuesto->unidades,
'total' => $presupuesto->total,
'concepto' => $presupuesto->concepto,
];
}
return [$presupuesto];
}
}
private function generarConceptoLineasPresupuestoLibro($lineas, $presupuesto){
$model_papel = model('App\Models\Configuracion\PapelImpresionModel');
$description_interior = "";
$description_cubierta = "";
$description_sobrecubierta = "";
$paginas_negro = 0;
$paginas_color = 0;
$papel_negro = "";
$papel_color = "";
$gramaje_negro = 0;
$gramaje_color = 0;
$lp_bn_lines = array_filter($lineas, function($linea) {
return strpos($linea->tipo, 'lp_bn') === 0;
});
$lp_color_lines = array_filter($lineas, function($linea) {
return strpos($linea->tipo, 'lp_color') === 0;
});
$lp_rot_bn = array_filter($lineas, function($linea) {
return strpos($linea->tipo, 'lp_rot_bn') === 0;
});
$lp_rot_color = array_filter($lineas, function($linea) {
return strpos($linea->tipo, 'lp_rot_color') === 0;
});
if(count($lp_bn_lines) > 0){
$lp_bn_lines = array_values($lp_bn_lines)[0];
$paginas_negro = $lp_bn_lines->paginas;
$gramaje_negro = $lp_bn_lines->gramaje;
$papel_negro = $model_papel->where('id', $lp_bn_lines->papel_impresion_id)->first()->nombre;
$description_interior .= sprintf(lang('Pedidos.lineasTemplates.libro_linea_interior'),
strval($paginas_negro),
$papel_negro,
strval($gramaje_negro)) . ". ";
}
if(count($lp_color_lines) > 0){
$lp_color_lines = array_values($lp_color_lines)[0];
$paginas_color = $lp_color_lines->paginas;
$gramaje_color = $lp_color_lines->gramaje;
$papel_color = $model_papel->where('id', $lp_color_lines->papel_impresion_id)->first()->nombre;
$description_interior .= sprintf(lang('Pedidos.lineasTemplates.libro_linea_interior'),
strval($paginas_color),
$papel_color,
strval($gramaje_color)) . ". ";
}
if(count($lp_rot_bn) > 0){
$lp_rot_bn = array_values($lp_rot_bn)[0];
$paginas_negro = $lp_rot_bn->paginas;
$gramaje_negro = $lp_rot_bn->gramaje;
$papel_negro = $model_papel->where('id', $lp_rot_bn->papel_impresion_id)->first()->nombre;
$description_interior .= sprintf(lang('Pedidos.lineasTemplates.libro_linea_interior'),
strval($paginas_negro),
$papel_negro,
strval($gramaje_negro)) . ". ";
}
if(count($lp_rot_color) > 0){
$lp_rot_color = array_values($lp_rot_color)[0];
$paginas_negro = intval($lp_rot_color->paginas)-intval($lp_rot_color->rotativa_pag_color);
$gramaje = $lp_rot_color->gramaje;
$papel = $model_papel->where('id', $lp_rot_color->papel_impresion_id)->first()->nombre;
if($paginas_negro > 0){
$description_interior .= sprintf(lang('Pedidos.lineasTemplates.libro_linea_interior'),
strval($paginas_negro),
$papel,
strval($gramaje)) . ". ";
}
$description_interior .= sprintf(lang('Pedidos.lineasTemplates.libro_linea_interior'),
strval($lp_rot_color->rotativa_pag_color),
$papel,
strval($gramaje)) . ". ";
}
$lp_cubierta = array_filter($lineas, function($linea) {
return strpos($linea->tipo, 'lp_cubierta') === 0;
});
$lp_sobrecubierta = array_filter($lineas, function($linea) {
return strpos($linea->tipo, 'lp_sobrecubierta') === 0;
});
if(count($lp_cubierta) > 0){
$lp_cubierta = array_values($lp_cubierta)[0];
if($lp_cubierta->paginas == 2){
$lp_cubierta->caras = lang('Pedidos.unaCara');
}
else{
$lp_cubierta->caras = lang('Pedidos.dosCaras');
}
$description_cubierta = sprintf(lang('Pedidos.lineasTemplates.libro_linea_cubierta'),
$lp_cubierta->caras,
$model_papel->where('id', $lp_cubierta->papel_impresion_id)->first()->nombre,
strval($lp_cubierta->gramaje));
$description_cubierta .= ($presupuesto->solapas_cubierta==1? sprintf(lang('Pedidos.lineasTemplates.libro_solapas'), $presupuesto->solapas_ancho_cubierta):". ");
}
if(count($lp_sobrecubierta) > 0){
$lp_sobrecubierta = array_values($lp_sobrecubierta)[0];
$description_sobrecubierta = sprintf(lang('Pedidos.lineasTemplates.libro_linea_sobrecubierta'),
$model_papel->where('id', $lp_sobrecubierta->papel_impresion_id)->first()->nombre,
strval($lp_sobrecubierta->gramaje));
$description_sobrecubierta .= ($presupuesto->solapas_sobrecubierta==1? sprintf(lang('Pedidos.lineasTemplates.libro_solapas'), $presupuesto->solapas_ancho_sobrecubierta):". ");
}
$acabado = sprintf(lang('Pedidos.lineasTemplates.libro_encuadernacion'),
lang('Presupuestos.' . $presupuesto->codigo_encuadernacion));
return $description_interior. $description_cubierta . $description_sobrecubierta . $acabado;
}
}

View File

@ -0,0 +1,709 @@
<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="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);
});
}
}
});
})
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' })
.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',
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);
}
},
footerCallback: function (row, data, start, end, display) {
/*
let api = this.api();
var numColumns = api.columns().count();
if(item.albaran.mostrar_precios == 1){
// Remove the formatting to get integer data for summation
let intVal = function (i) {
return typeof i === 'string'
? i.replace(/[\$,]/g, '') * 1
: typeof i === 'number'
? i
: 0;
};
// Total over all pages
total = api
.column(9)
.data()
.reduce((a, b) => intVal(a) + intVal(b), 0);
// Update footer
api.column(numColumns-1).footer().innerHTML =
'Total: ' + total.toFixed(2);
}
else{
api.column(numColumns-1).footer().innerHTML = '';
}
*/
},
});
// 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');
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 );
$.ajax({
url: url,
type: 'POST',
data: data,
success: function(response){
if('error' in response){
}
}
});
});
$(document).on('click', '#borrar_albaranes', function(){
// 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();
}
}
}
}
});
});
});
$(document).on('click', '.borrar-albaran', function(){
var albaran_id = $(this).attr('id').split('_').slice(-1)[0];
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();
}
}
}
}
});
});
$(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];
//NACHO AQUI
});
$.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);
});
}
}
});
<?=$this->endSection() ?>

View File

@ -0,0 +1,304 @@
<div class="accordion accordion-bordered mt-3" id="cabeceraPedido">
<div class="card accordion-item active">
<h2 class="accordion-header" id="headingPedido">
<button type="button" class="accordion-button" data-bs-toggle="collapse" data-bs-target="#accordionPedidoTip" aria-expanded="false" aria-controls="accordionPedidoTip">
<h3><?= lang("Pedidos.datosPedido") ?></h3>
</button>
</h2>
<div id="accordionPedidoTip" class="accordion-collapse collapse show" data-bs-parent="#accordioPedido">
<div class="accordion-body">
<div class="row">
<div class="col-md-12 col-lg-2 px-4">
<div class="mb-1">
<label for="id" class="form-label">
<?= lang('Pedidos.id') ?>
</label>
<input readonly id="id" name="id" tabindex="1" maxLength="11" class="form-control" value="<?= old('id', $pedidoEntity->id) ?>" >
</div>
</div><!--//.mb-3 -->
<div class="col-md-12 col-lg-4 px-4">
<div class="mb-1">
<label for="cliente" class="form-label">
<?= lang('Pedidos.cliente') ?>
<div class="btn-group btn-group-sm">
<a href="<?= route_to('editarCliente', $pedidoEntity->cliente_id); ?>" target="_blank" ><i class="ti ti-file-search ti-sm btn-edit mx-2" data-id="${data.id}"></i></a>
</div>
</label>
<input readonly id="cliente" name="cliente" tabindex="2" maxLength="11" class="form-control" value="<?= old('cliente', $pedidoEntity->cliente) ?>" >
</div>
</div><!--//.mb-3 -->
<div class="col-md-12 col-lg-3 px-4">
<div class="mb-1">
<label for="comercial" class="form-label">
<?= lang('Pedidos.comercial') ?>
</label>
<input readonly id="comercial" name="comercial" tabindex="1" maxLength="11" class="form-control" value="<?= old('comercial', $pedidoEntity->comercial) ?>" >
</div>
</div><!--//.mb-3 -->
<div class="col-md-12 col-lg-3 px-4">
<div class="mb-1">
<label for="estadoText" class="form-label">
<?= lang('Pedidos.estado') ?>
</label>
<input readonly id="estadoText" name="estadoText" tabindex="1" maxLength="11" class="form-control" value="<?= old('estadoText', $pedidoEntity->estadoText) ?>" >
</div>
</div><!--//.mb-3 -->
<div class="accordion accordion mt-3 accordion-without-arrow" id="FechasPedido">
<div class="card accordion-item active mt-3 mx-2">
<h2 class="accordion-header" id="headingFechas">
<button type="button" class="accordion-button collapsed" data-bs-toggle="collapse" data-bs-target="#accordionIcon-1" aria-controls="accordionIcon-1">
<i class="ti ti-businessplan ti-sm mx-2"></i><?= lang('Pedidos.totales') ?>
</button>
</h2>
<div id="accordionFechasTip" class="accordion show" data-bs-parent="#accordioFechas">
<div class="accordion-body">
<div class="row">
<div class="col-md-12 col-lg-3 px-4">
<div class="mb-1">
<label for="total_precio" class="form-label">
<?= lang('Pedidos.total_precio') ?>
</label>
<input readonly id="total_precio" name="total_precio" tabindex="1" maxLength="11" class="form-control" value="<?= old('total_precio', $pedidoEntity->total_precio) ?>" >
</div>
</div><!--//.mb-3 -->
<div class="col-md-12 col-lg-3 px-4">
<div class="mb-1">
<label for="total_tirada" class="form-label">
<?= lang('Pedidos.total_tirada') ?>
</label>
<input readonly id="total_tirada" name="total_tirada" tabindex="1" maxLength="11" class="form-control" value="<?= old('total_tirada', $pedidoEntity->total_tirada ) ?>" >
</div>
</div><!--//.mb-3 -->
</div>
</div> <!--//accordion-body -->
</div> <!--//accordionFechasTip-->
</div> <!--//card-->
</div>
<div class="accordion accordion mt-3 accordion-without-arrow" id="FechasPedido">
<div class="card accordion-item active mt-3 mx-2">
<h2 class="accordion-header" id="headingFechas">
<button type="button" class="accordion-button collapsed" data-bs-toggle="collapse" data-bs-target="#accordionIcon-1" aria-controls="accordionIcon-1">
<i class="ti ti-calendar ti-sm mx-2"></i><?= lang("Pedidos.fechas") ?>
</button>
</h2>
<div id="accordionFechasTip" class="accordion show" data-bs-parent="#accordioFechas">
<div class="accordion-body">
<div class="row">
<div class="col-md-12 col-lg-3 px-4">
<div class="mb-1">
<label for="fecha_entrega_real" class="fecha-pedido form-label">
<?= lang('Pedidos.fecha_entrega_real') ?>
</label>
<input type="text" value="" id="fecha_entrega_real" name="fecha_entrega_real" tabindex="1" maxLength="11" class="form-control" value="<?= old('fecha_entrega_real', $pedidoEntity->fecha_entrega_real) ?>" >
</div>
</div>
<div class="col-md-12 col-lg-3 px-4">
<div class="mb-1">
<label for="fecha_impresion" class="form-label">
<?= lang('Pedidos.fecha_impresion') ?>
</label>
<input type="text" id="fecha_impresion" name="fecha_impresion" tabindex="1" maxLength="11" class="fecha-pedido form-control" value="<?= old('fecha_impresion', $pedidoEntity->fecha_impresion) ?>" >
</div>
</div>
<div class="col-md-12 col-lg-3 px-4">
<div class="mb-1">
<label for="fecha_encuadernado" class="form-label">
<?= lang('Pedidos.fecha_encuadernado') ?>
</label>
<input type="text" id="fecha_encuadernado" name="fecha_encuadernado" tabindex="1" maxLength="11" class="fecha-pedido form-control" value="<?= old('fecha_encuadernado', $pedidoEntity->fecha_encuadernado) ?>" >
</div>
</div>
<div class="col-md-12 col-lg-3 px-4">
<div class="mb-1">
<label for="fecha_entrega_externo" class="form-label">
<?= lang('Pedidos.fecha_entrega_externo') ?>
</label>
<input type="text" id="fecha_entrega_externo" name="fecha_entrega_externo" tabindex="1" maxLength="11" class="fecha-pedido form-control" value="<?= old('fecha_entrega_externo', $pedidoEntity->fecha_entrega_externo) ?>" >
</div>
</div>
</div>
</div>
</div> <!--//accordionFechasTip-->
</div> <!--//card-->
</div>
<?php if ($pedidoEntity->estado !== 'finalizado' && $pedidoEntity->estado !== 'cancelado'): ?>
<div class="col-12 d-flex flex-row-reverse mt-4 gap-2">
<div id="pedido_finalizado" class="buton-estado 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.finalizar') ?></span>
<i class="ti ti-hourglass-empty ti-xs"></i>
</div>
<div id="pedido_cancelado" class="buton-estado 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.cancelar') ?></span>
<i class="ti ti-circle-x ti-xs"></i>
</div>
</div>
<?php endif; ?>
</div>
</div>
</div>
</div>
<?=$this->section('additionalInlineJs') ?>
$("#fecha_entrega_real").flatpickr({
defaultDate: <?= $pedidoEntity->fecha_entrega_real_text ? "'".$pedidoEntity->fecha_entrega_real_text."'" : 'null' ?>,
dateFormat: "d/m/Y",
locale: {
firstDayOfWeek: 1,
weekdays: {
shorthand: ['Do', 'Lu', 'Ma', 'Mi', 'Ju', 'Vi', 'Sa'],
longhand: ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'],
},
months: {
shorthand: ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Оct', 'Nov', 'Dic'],
longhand: ['Enero', 'Febreo', 'Мarzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'],
},
},
onChange: function(selectedDates, dateStr, instance) {
<?php if ($pedidoEntity->estado !== 'finalizado' && $pedidoEntity->estado !== 'cancelado'): ?>
updateDate('fecha_entrega_real', dateStr);
<?php endif; ?>
}
});
$("#fecha_impresion").flatpickr({
defaultDate: <?= $pedidoEntity->fecha_impresion_text ? "'".$pedidoEntity->fecha_impresion_text."'" : 'null' ?>,
dateFormat: "d/m/Y",
locale: {
firstDayOfWeek: 1,
weekdays: {
shorthand: ['Do', 'Lu', 'Ma', 'Mi', 'Ju', 'Vi', 'Sa'],
longhand: ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'],
},
months: {
shorthand: ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Оct', 'Nov', 'Dic'],
longhand: ['Enero', 'Febreo', 'Мarzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'],
},
},
onChange: function(selectedDates, dateStr, instance) {
<?php if ($pedidoEntity->estado !== 'finalizado' && $pedidoEntity->estado !== 'cancelado'): ?>
updateDate('fecha_impresion', dateStr);
<?php endif; ?>
}
});
$("#fecha_encuadernado").flatpickr({
defaultDate: <?= $pedidoEntity->fecha_encuadernado_text ? "'".$pedidoEntity->fecha_encuadernado_text."'" : 'null' ?>,
dateFormat: "d/m/Y",
locale: {
firstDayOfWeek: 1,
weekdays: {
shorthand: ['Do', 'Lu', 'Ma', 'Mi', 'Ju', 'Vi', 'Sa'],
longhand: ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'],
},
months: {
shorthand: ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Оct', 'Nov', 'Dic'],
longhand: ['Enero', 'Febreo', 'Мarzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'],
},
},
onChange: function(selectedDates, dateStr, instance) {
<?php if ($pedidoEntity->estado !== 'finalizado' && $pedidoEntity->estado !== 'cancelado'): ?>
updateDate('fecha_encuadernado', dateStr);
<?php endif; ?>
}
});
$("#fecha_entrega_externo").flatpickr({
defaultDate: <?= $pedidoEntity->fecha_entrega_externo_text ? "'".$pedidoEntity->fecha_entrega_externo_text."'" : 'null' ?>,
dateFormat: "d/m/Y",
locale: {
firstDayOfWeek: 1,
weekdays: {
shorthand: ['Do', 'Lu', 'Ma', 'Mi', 'Ju', 'Vi', 'Sa'],
longhand: ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'],
},
months: {
shorthand: ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Оct', 'Nov', 'Dic'],
longhand: ['Enero', 'Febreo', 'Мarzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'],
},
},
onChange: function(selectedDates, dateStr, instance) {
<?php if ($pedidoEntity->estado !== 'finalizado' && $pedidoEntity->estado !== 'cancelado'): ?>
updateDate('fecha_entrega_externo', dateStr);
<?php endif; ?>
}
});
<?php if ($pedidoEntity->estado !== 'finalizado' && $pedidoEntity->estado !== 'cancelado'): ?>
$('.buton-estado').on('click', function() {
var id = <?=$pedidoEntity->id ?>;
var estado = $(this).attr('id').split('_')[1];
var url = '<?= route_to('cambiarEstadoPedido') ?>';
var data = {
id: id,
estado: estado
};
$.ajax({
url: url,
type: 'POST',
data: data,
success: function(response) {
try{
if (response.status=="success") {
location.reload();
}
}
catch(e){
console.log(e);
}
}
});
});
<?php endif; ?>
function updateDate(elementId, dateStr) {
var id = <?=$pedidoEntity->id ?>;
data = {
<?= csrf_token() ?? "token" ?>: <?= csrf_token() ?>v,
};
var parts = dateStr.split('/');
var newFormat = parts[2] + '-' + parts[1] + '-' + parts[0]; // Asume dateStr en formato d/m/Y.
data[elementId] = newFormat;
var url = '<?= route_to('actualizarPedido', ':id') ?>';
url = url.replace(':id', id );
$.ajax({
url: url,
type: 'POST',
data: data,
success: function(response){
if('error' in response){
}
}
});
}
<?=$this->endSection() ?>

View File

@ -0,0 +1,24 @@
<div class="accordion accordion-bordered mt-3" id="accordioFacturas">
<div class="card accordion-item active">
<h2 class="accordion-header" id="headingFacturas">
<button type="button" class="accordion-button" data-bs-toggle="collapse" data-bs-target="#accordionFacturasTip" aria-expanded="false" aria-controls="accordionFacturasTip">
<h3><?= lang("Pedidos.facturas") ?></h3>
</button>
</h2>
<div id="accordionFacturasTip" class="accordion-collapse collapse show" data-bs-parent="#accordioFacturas">
<div class="accordion-body">
</div> <!-- /.accordion-body -->
</div>
</div>
</div>
<?=$this->section('additionalInlineJs') ?>
<?=$this->endSection() ?>

View File

@ -0,0 +1,140 @@
<div class="accordion accordion-bordered mt-3" id="accordioLineas">
<div class="card accordion-item active">
<h2 class="accordion-header" id="headingLineas">
<button type="button" class="accordion-button" data-bs-toggle="collapse" data-bs-target="#accordionLineasTip" aria-expanded="false" aria-controls="accordionLineasTip">
<h3><?= lang("Pedidos.lineas") ?></h3>
</button>
</h2>
<div id="accordionLineasTip" class="accordion-collapse collapse show" data-bs-parent="#accordioLineas">
<div class="accordion-body">
<table id="tableOfLineasPedido" class="table table-striped table-hover" style="width: 100%;">
<thead>
<tr>
<th></th>
<th><?= lang('Pedidos.presupuesto') ?></th>
<th><?= lang('Pedidos.unidades')?></th>
<th><?= lang('Pedidos.concepto') ?></th>
<th><?= lang('Pedidos.total') ?></th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<th colspan="5" style="text-align:right">Total:</th>
</tr>
</tfoot>
</table>
</div> <!-- /.accordion-body -->
</div>
</div>
</div>
<?=$this->section('additionalInlineJs') ?>
const viewPresupuestoBtns = 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-file-search ti-sm btn-view mx-2" data-id="${data.numero}"></i></a>
</div>
</td>`;
};
var tableOfLineasPedido = new DataTable('#tableOfLineasPedido',{
processing: true,
serverSide: true,
autoWidth: true,
responsive: true,
scrollX: true,
searchable: false,
info: false,
dom: 't',
language: {
url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json"
},
ajax : $.fn.dataTable.pipeline( {
url: '<?= route_to('tablaLineasPedido') ?>',
data: function ( d ) {
d.pedido_id = <?= $pedidoEntity->id ?>;
},
method: 'POST',
headers: {'X-Requested-With': 'XMLHttpRequest'},
async: true,
}),
columns: [
{data: 'numero'},
{
data: viewPresupuestoBtns,
className: 'dt-center'
},
{data: 'unidades'},
{data: 'concepto'},
{data: 'total'},
],
columnDefs: [
{
targets: 0,
visible: false,
orderable: false,
searchable: false
},
{
targets: 1,
orderable: false,
data: null,
defaultContent: ''
},
{
targets: [2,3,4],
orderable: false,
},
],
footerCallback: function (row, data, start, end, display) {
let api = this.api();
// Remove the formatting to get integer data for summation
let intVal = function (i) {
return typeof i === 'string'
? i.replace(/[\$,]/g, '') * 1
: typeof i === 'number'
? i
: 0;
};
// Total over all pages
total = api
.column(4)
.data()
.reduce((a, b) => intVal(a) + intVal(b), 0);
// Update footer
api.column(4).footer().innerHTML =
'Total: ' + total;
},
});
$(document).on('click', '.btn-view', function(e) {
<?php if (auth()->user()->inGroup('admin') || auth()->user()->inGroup('beta')): ?>
var url = '<?= route_to('editarPresupuesto', ':id') ?>';
<?php else: ?>
var url = '<?= route_to('editarPresupuestoCliente2', ':id') ?>';
<?php endif; ?>
url = url.replace(':id', `${$(this).attr('data-id')}` );
console.log(url);
window.open(
url,
'_blank' // <- This is what makes it open in a new window.
);
});
<?=$this->endSection() ?>

View File

@ -0,0 +1,50 @@
<?= $this->include("themes/_commonPartialsBs/datatables") ?>
<?= $this->include("themes/_commonPartialsBs/select2bs5") ?>
<?= $this->include("themes/_commonPartialsBs/sweetalert") ?>
<?=$this->extend('themes/vuexy/main/defaultlayout') ?>
<?= $this->section("content") ?>
<div class="row">
<div class="col-12">
<div class="card card-info">
<div class="card-header">
<h3 class="card-title"><?= $boxTitle ?? $pageTitle ?></h3>
</div><!--//.card-header -->
<form id="pedidoForm" method="post" class="card-body" action="<?= $formAction ?>">
<?= csrf_field() ?>
<div class="card-body">
<?= view("themes/_commonPartialsBs/_alertBoxes") ?>
<?= !empty($validation->getErrors()) ? $validation->listErrors("bootstrap_style") : "" ?>
<?= view("themes/vuexy/form/pedidos/_cabeceraItems") ?>
<?= view("themes/vuexy/form/pedidos/_lineasItems") ?>
<?= view("themes/vuexy/form/pedidos/_albaranesItems") ?>
<?= view("themes/vuexy/form/pedidos/_facturasItems") ?>
</div><!-- /.card-body -->
<div class="pt-4">
<?= anchor(route_to("listaPresupuestos"), lang("Basic.global.Cancel"), ["class" => "btn btn-secondary float-start"]) ?>
</div><!-- /.card-footer -->
</form>
</div><!-- //.card -->
</div><!--//.col -->
</div><!--//.row -->
<?= $this->endSection() ?>
<?=$this->section('css') ?>
<link rel="stylesheet" href="<?= site_url("/themes/vuexy/vendor/libs/flatpickr/flatpickr.css") ?>">
<link rel="stylesheet" href="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/buttons.bootstrap5.min.css") ?>">
<link rel="stylesheet" href="<?= site_url('themes/vuexy/css/sk-datatables.css') ?>">
<?=$this->endSection() ?>
<?= $this->section('additionalExternalJs') ?>
<script src="<?= site_url("/themes/vuexy/vendor/libs/flatpickr/flatpickr.js") ?>"></script>
<script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/dataTables.buttons.min.js") ?>"></script>
<script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/buttons.bootstrap5.min.js") ?>"></script>
<script src="<?= site_url("themes/vuexy/vendor/libs/datatables-sk/plugins/select/dataTables.select.min.js") ?>"></script>
<script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/buttons.html5.min.js") ?>"></script>
<script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/buttons.print.min.js") ?>"></script>
<script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/jszip/jszip.min.js") ?>"></script>
<script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/pdfmake/pdfmake.min.js") ?>" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/pdfmake/vfs_fonts.js") ?>"></script>
<?=$this->endSection() ?>

View File

@ -0,0 +1,178 @@
<?=$this->include('themes/_commonPartialsBs/datatables') ?>
<?= $this->include('themes/_commonPartialsBs/_confirm2delete') ?>
<?=$this->extend('themes/vuexy/main/defaultlayout') ?>
<?=$this->section('content'); ?>
<div class="row">
<div class="col-md-12">
<div class="card card-info">
<div class="card-header">
<h3 class="card-title"><?=lang('Pedidos.pedidosList') ?></h3>
</div><!--//.card-header -->
<div class="card-body">
<?= view('themes/_commonPartialsBs/_alertBoxes'); ?>
<table id="tableOfPedidos" class="table table-striped table-hover" style="width: 100%;">
<thead>
<tr>
<th><?= lang('Pedidos.id') ?></th>
<th><?= lang('Pedidos.fecha') ?></th>
<th><?= lang('Pedidos.fecha_entrega') ?></th>
<th><?= lang('Pedidos.cliente') ?></th>
<th><?= lang('Pedidos.comercial') ?></th>
<th><?= lang('Pedidos.titulo') ?></th>
<th><?= lang('Pedidos.ubicacion') ?></th>
<th><?= lang('Pedidos.inc_rei') ?></th>
<th><?= lang('Pedidos.num_paginas') ?></th>
<th><?= lang('Pedidos.tiradas') ?></th>
<th><?= lang('Pedidos.total_presupuesto') ?></th>
<th><?= lang('Pedidos.estado') ?></th>
<th class="text-nowrap"><?= lang('Basic.global.Action') ?></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div><!--//.card-body -->
<div class="card-footer">
</div><!--//.card-footer -->
</div><!--//.card -->
</div><!--//.col -->
</div><!--//.row -->
<?=$this->endSection() ?>
<?=$this->section('additionalInlineJs') ?>
const lastColNr = $('#tableOfPedidos').find("tr:first th").length - 1;
const actionBtns = 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-eye ti-sm btn-edit mx-2" data-id="${data.id}"></i></a>
</div>
</td>`;
};
theTable = $('#tableOfPedidos').DataTable({
processing: true,
serverSide: true,
autoWidth: true,
responsive: true,
scrollX: true,
lengthMenu: [ 5, 10, 25, 50, 75, 100, 250, 500, 1000, 2500 ],
pageLength: 50,
lengthChange: true,
"dom": 'lfBrtip',
"buttons": [
'copy', 'csv', 'excel', 'print', {
extend: 'pdfHtml5',
orientation: 'landscape',
pageSize: 'A4'
}
],
stateSave: true,
order: [[0, 'asc']],
language: {
url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json"
},
ajax : $.fn.dataTable.pipeline( {
url: '<?= route_to('dataTableOfPedidos') ?>',
method: 'POST',
data: {
estado: "<?= $estadoPedidos ?>",
},
headers: {'X-Requested-With': 'XMLHttpRequest'},
async: true,
}),
columnDefs: [
{
orderable: false,
searchable: false,
targets: [lastColNr]
}
],
columns : [
{ 'data': 'id' },
{ 'data': 'fecha' },
{ 'data': 'fecha_entrega' },
{ 'data': 'cliente' },
{ 'data': 'comercial' },
{ 'data': 'titulo' },
{ 'data': 'ubicacion' },
{ 'data': 'inc_rei' },
{ 'data': 'paginas' },
{ 'data': 'tirada' },
{ 'data': 'total_presupuesto' },
{ 'data': 'estado',
render: function(data, type, row, meta) {
switch(data){
case "validacion":
return '<?= lang('Pedidos.validacion') ?>';
break;
case "produccion":
return '<?= lang('Pedidos.produccion') ?>';
break;
case "finalizado":
return '<?= lang('Pedidos.finalizado') ?>';
break;
case "enviado":
return '<?= lang('Pedidos.enviado') ?>';
break;
case "cancelado":
return '<?= lang('Pedidos.cancelado') ?>';
break;
default:
return data; // Debug
break;
}
}
},
{ 'data': actionBtns }
]
});
theTable.on( 'draw.dt', function () {
const boolCols = [];
for (let coln of boolCols) {
theTable.column(coln, { page: 'current' }).nodes().each( function (cell, i) {
cell.innerHTML = cell.innerHTML == '1' ? '<i class="ti ti-check"></i>' : '';
});
}
});
$(document).on('click', '.btn-edit', function(e) {
var url = '<?= route_to('editarPedido', ':id') ?>';
url = url.replace(':id', `${$(this).attr('data-id')}` );
window.location.href = url;
});
<?=$this->endSection() ?>
<?=$this->section('css') ?>
<link rel="stylesheet" href="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/buttons.bootstrap5.min.css") ?>">
<?=$this->endSection() ?>
<?= $this->section('additionalExternalJs') ?>
<script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/dataTables.buttons.min.js") ?>"></script>
<script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/buttons.bootstrap5.min.js") ?>"></script>
<script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/buttons.html5.min.js") ?>"></script>
<script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/buttons.print.min.js") ?>"></script>
<script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/jszip/jszip.min.js") ?>"></script>
<script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/pdfmake/pdfmake.min.js") ?>" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/pdfmake/vfs_fonts.js") ?>"></script>
<?=$this->endSection() ?>

View File

@ -117,10 +117,10 @@
</a>
</li>
<?php endif; ?>
<?php if (count(getArrayItem($temp, 'methods', 'manuales', true)) > 0): ?>
<?php if (count(getArrayItem($temp, 'methods', 'todos', true)) > 0): ?>
<li class="menu-item">
<a href="<?= site_url("pedidos/pedido/manuales") ?>" class="menu-link">
<div data-i18n="<?= lang("App.menu_pedidos_manuales") ?>"><?= lang("App.menu_pedidos_manuales") ?></div>
<a href="<?= site_url("pedidos/pedido/todos") ?>" class="menu-link">
<div data-i18n="<?= lang("App.menu_pedidos_todos") ?>"><?= lang("App.menu_pedidos_todos") ?></div>
</a>
</li>
<?php endif; ?>

View File

@ -138,10 +138,10 @@
</a>
</li>
<?php endif; ?>
<?php if (count(getArrayItem($temp, 'methods', 'manuales', true)) > 0): ?>
<?php if (count(getArrayItem($temp, 'methods', 'todos', true)) > 0): ?>
<li class="menu-item">
<a href="<?= site_url("pedidos/pedido/manuales") ?>" class="menu-link">
<div data-i18n="<?= lang("App.menu_pedidos_manuales") ?>"><?= lang("App.menu_pedidos_manuales") ?></div>
<a href="<?= site_url("pedidos/pedido/todos") ?>" class="menu-link">
<div data-i18n="<?= lang("App.menu_pedidos_todos") ?>"><?= lang("App.menu_pedidos_todos") ?></div>
</a>
</li>
<?php endif; ?>

View File

@ -27,8 +27,8 @@ if (auth()->user()->inGroup('beta')) {
</a>
</li>
<li class="menu-item">
<a href="<?= site_url("pedidos/pedido/manuales") ?>" class="menu-link">
<?= lang("App.menu_pedidos_manuales") ?>
<a href="<?= site_url("pedidos/pedido/todos") ?>" class="menu-link">
<?= lang("App.menu_pedidos_todos") ?>
</a>
</li>
</ul>