mirror of
https://git.imnavajas.es/jjimenez/safekat.git
synced 2025-07-25 22:52:08 +00:00
650 lines
26 KiB
PHP
Executable File
650 lines
26 KiB
PHP
Executable File
<?php
|
|
|
|
namespace App\Controllers\Pedidos;
|
|
use App\Controllers\BaseController;
|
|
use App\Controllers\Facturacion\Facturas;
|
|
use App\Entities\Pedidos\PedidoEntity;
|
|
use App\Models\Collection;
|
|
use App\Models\Pedidos\PedidoModel;
|
|
use App\Services\ProductionService;
|
|
use Hermawan\DataTables\DataTable;
|
|
use CodeIgniter\I18n\Time;
|
|
|
|
class Pedido extends \App\Controllers\BaseResourceController
|
|
{
|
|
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],
|
|
];
|
|
helper("time");
|
|
|
|
parent::initController($request, $response, $logger);
|
|
|
|
}
|
|
|
|
public function index()
|
|
{
|
|
|
|
if (auth()->user()->inGroup('cliente-admin') || auth()->user()->inGroup('cliente-editor')) {
|
|
// Se obtiene el cliente ID a partir del usuario de la sesion
|
|
$model_user = model('App\Models\Usuarios\UserModel');
|
|
$user = $model_user->find(auth()->user()->id);
|
|
$clienteId = $user->cliente_id;
|
|
} else {
|
|
$clienteId = -1;
|
|
}
|
|
|
|
$this->viewData['cliente_id'] = $clienteId;
|
|
|
|
$this->viewData['usingClientSideDataTable'] = true;
|
|
|
|
$this->viewData['pageSubTitle'] = lang('Basic.global.ManageAllRecords', [lang('Tarifaextra.tarifaextra')]);
|
|
parent::index();
|
|
|
|
}
|
|
|
|
public function activos()
|
|
{
|
|
$viewData = [
|
|
'currentModule' => static::$controllerSlug,
|
|
'pageSubTitle' => lang('Basic.global.ManageAllRecords', [lang('Pedidos.pedido')]),
|
|
'pedidoEntity' => new PedidoEntity(),
|
|
'usingServerSideDataTable' => true,
|
|
'pageTitle' => lang('Pedidos.Pedidos'),
|
|
'estadoPedidos' => 'produccion',
|
|
['title' => lang("App.menu_pedidos"), 'route' => site_url('pedidos/todos'), 'active' => true]
|
|
];
|
|
|
|
if (auth()->user()->inGroup('cliente-admin') || auth()->user()->inGroup('cliente-editor')) {
|
|
// Se obtiene el cliente ID a partir del usuario de la sesion
|
|
$model_user = model('App\Models\Usuarios\UserModel');
|
|
$user = $model_user->find(auth()->user()->id);
|
|
$clienteId = $user->cliente_id;
|
|
} else {
|
|
$clienteId = -1;
|
|
}
|
|
|
|
$viewData['cliente_id'] = $clienteId;
|
|
|
|
return view(static::$viewPath . 'viewPedidosList', $viewData);
|
|
}
|
|
|
|
public function finalizados()
|
|
{
|
|
$viewData = [
|
|
'currentModule' => static::$controllerSlug,
|
|
'pageSubTitle' => lang('Basic.global.ManageAllRecords', [lang('Pedidos.pedido')]),
|
|
'pedidoEntity' => new PedidoEntity(),
|
|
'usingServerSideDataTable' => true,
|
|
'pageTitle' => lang('Pedidos.Pedidos'),
|
|
'estadoPedidos' => 'finalizado',
|
|
['title' => lang("App.menu_pedidos"), 'route' => site_url('pedidos/todos'), 'active' => true]
|
|
];
|
|
|
|
if (auth()->user()->inGroup('cliente-admin') || auth()->user()->inGroup('cliente-editor')) {
|
|
// Se obtiene el cliente ID a partir del usuario de la sesion
|
|
$model_user = model('App\Models\Usuarios\UserModel');
|
|
$user = $model_user->find(auth()->user()->id);
|
|
$clienteId = $user->cliente_id;
|
|
} else {
|
|
$clienteId = -1;
|
|
}
|
|
|
|
$viewData['cliente_id'] = $clienteId;
|
|
|
|
return view(static::$viewPath . 'viewPedidosList', $viewData);
|
|
}
|
|
|
|
public function validacion()
|
|
{
|
|
$viewData = [
|
|
'currentModule' => static::$controllerSlug,
|
|
'pageSubTitle' => lang('Basic.global.ManageAllRecords', [lang('Pedidos.pedido')]),
|
|
'pedidoEntity' => new PedidoEntity(),
|
|
'usingServerSideDataTable' => true,
|
|
'pageTitle' => lang('Pedidos.Pedidos'),
|
|
'estadoPedidos' => 'validacion',
|
|
['title' => lang("App.menu_pedidos"), 'route' => site_url('pedidos/todos'), 'active' => true]
|
|
];
|
|
|
|
if (auth()->user()->inGroup('cliente-admin') || auth()->user()->inGroup('cliente-editor')) {
|
|
// Se obtiene el cliente ID a partir del usuario de la sesion
|
|
$model_user = model('App\Models\Usuarios\UserModel');
|
|
$user = $model_user->find(auth()->user()->id);
|
|
$clienteId = $user->cliente_id;
|
|
} else {
|
|
$clienteId = -1;
|
|
}
|
|
|
|
$viewData['cliente_id'] = $clienteId;
|
|
|
|
return view(static::$viewPath . 'viewPedidosList', $viewData);
|
|
}
|
|
|
|
public function cancelados()
|
|
{
|
|
$viewData = [
|
|
'currentModule' => static::$controllerSlug,
|
|
'pageSubTitle' => lang('Basic.global.ManageAllRecords', [lang('Pedidos.pedido')]),
|
|
'pedidoEntity' => new PedidoEntity(),
|
|
'usingServerSideDataTable' => true,
|
|
'pageTitle' => lang('Pedidos.Pedidos'),
|
|
'estadoPedidos' => 'cancelado',
|
|
['title' => lang("App.menu_pedidos"), 'route' => site_url('pedidos/todos'), 'active' => true]
|
|
];
|
|
|
|
if (auth()->user()->inGroup('cliente-admin') || auth()->user()->inGroup('cliente-editor')) {
|
|
// Se obtiene el cliente ID a partir del usuario de la sesion
|
|
$model_user = model('App\Models\Usuarios\UserModel');
|
|
$user = $model_user->find(auth()->user()->id);
|
|
$clienteId = $user->cliente_id;
|
|
} else {
|
|
$clienteId = -1;
|
|
}
|
|
|
|
$viewData['cliente_id'] = $clienteId;
|
|
|
|
return view(static::$viewPath . 'viewPedidosList', $viewData);
|
|
}
|
|
|
|
public function todos()
|
|
{
|
|
|
|
$viewData = [
|
|
'currentModule' => static::$controllerSlug,
|
|
'pageSubTitle' => lang('Basic.global.ManageAllRecords', [lang('Pedidos.pedido')]),
|
|
'pedidoEntity' => new PedidoEntity(),
|
|
'usingServerSideDataTable' => true,
|
|
'pageTitle' => lang('Pedidos.Pedidos'),
|
|
'estadoPedidos' => 'todos',
|
|
['title' => lang("App.menu_pedidos"), 'route' => site_url('pedidos/todos'), 'active' => true]
|
|
];
|
|
|
|
if (auth()->user()->inGroup('cliente-admin') || auth()->user()->inGroup('cliente-editor')) {
|
|
// Se obtiene el cliente ID a partir del usuario de la sesion
|
|
$model_user = model('App\Models\Usuarios\UserModel');
|
|
$user = $model_user->find(auth()->user()->id);
|
|
$clienteId = $user->cliente_id;
|
|
} else {
|
|
$clienteId = -1;
|
|
}
|
|
|
|
$viewData['cliente_id'] = $clienteId;
|
|
|
|
return view(static::$viewPath . 'viewPedidosList', $viewData);
|
|
|
|
}
|
|
|
|
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)
|
|
{
|
|
|
|
$data = [];
|
|
|
|
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);
|
|
|
|
foreach (array_keys($sanitizedData) as $key) {
|
|
if (str_starts_with($key, "fecha_")) {
|
|
$sanitizedData[$key . "_change_user_id"] =
|
|
auth()->user()->id;
|
|
$data[$key . "_change_user"] =
|
|
model('App\Models\Usuarios\UserModel')->getFullName(auth()->user()->id);
|
|
}
|
|
}
|
|
// 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;
|
|
$data[$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);
|
|
|
|
$pedidoEntity->fecha_entrega_real_change_user = $pedidoEntity->fecha_entrega_real_change_user_id ? model('App\Models\Usuarios\UserModel')->
|
|
getFullName($pedidoEntity->fecha_entrega_real_change_user_id) : "";
|
|
$pedidoEntity->fecha_impresion_change_user = $pedidoEntity->fecha_impresion_change_user_id ? model('App\Models\Usuarios\UserModel')->
|
|
getFullName($pedidoEntity->fecha_impresion_change_user_id) : "";
|
|
$pedidoEntity->fecha_encuadernado_change_user = $pedidoEntity->fecha_encuadernado_change_user_id ? model('App\Models\Usuarios\UserModel')->
|
|
getFullName($pedidoEntity->fecha_encuadernado_change_user_id) : "";
|
|
$pedidoEntity->fecha_entrega_change_externo_user = $pedidoEntity->fecha_entrega_change_externo_user_id ? model('App\Models\Usuarios\UserModel')->
|
|
getFullName($pedidoEntity->fecha_entrega_change_externo_user_id) : "";
|
|
|
|
$this->viewData['pedidoEntity'] = $pedidoEntity;
|
|
|
|
if ($pedidoEntity->estado == 'validacion') {
|
|
$clienteModel = model('App\Models\Clientes\ClienteModel');
|
|
$pendiente = $clienteModel->getPendienteCobro($pedidoEntity->cliente_id);
|
|
$pendiente = $pendiente[0] + $pendiente[1];
|
|
$this->viewData['importePendiente'] = $pendiente;
|
|
}
|
|
|
|
$modelOrden = new \App\Models\OrdenTrabajo\OrdenTrabajoModel();
|
|
$orden = $modelOrden->where('pedido_id', $pedidoEntity->id)->first();
|
|
if ($orden) {
|
|
$this->viewData['orden_id'] = $orden->id;
|
|
}
|
|
|
|
$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';
|
|
$cliente_id = $reqData['cliente_id'] ?? -1;
|
|
if ($estado == 'todos')
|
|
$estado = '';
|
|
|
|
$showTotal = $reqData['showTotal'] ?? false;
|
|
|
|
$searchValues = get_filter_datatables_columns($reqData);
|
|
|
|
$model_linea = model('\App\Models\Pedidos\PedidoLineaModel');
|
|
$resourceData = $model_linea->getResource($searchValues, $estado, $cliente_id)->orderBy($order, $dir)->limit($length, $start)->get()->getResultObject();
|
|
$totalTirada = $model_linea->getSumOfTirada($searchValues, $estado, $cliente_id, $start, $length);
|
|
$total = $model_linea->getSumOfTotalAceptado($searchValues, $estado, $cliente_id, $start, $length);
|
|
$extra_data['total_tirada'] = $totalTirada;
|
|
$extra_data['total'] = $total;
|
|
$total2 = 0;
|
|
if ($showTotal) {
|
|
$total2 = $model_linea->getTotalOfTotalAceptado($estado);
|
|
$tirada2 = $model_linea->getTotalTirada($estado);
|
|
$extra_data['total2'] = $total2;
|
|
$extra_data['total_tirada2'] = $tirada2;
|
|
}
|
|
|
|
return $this->respond(Collection::datatable(
|
|
$resourceData,
|
|
$model_linea->getResource("", $estado)->countAllResults(),
|
|
$model_linea->getResource($searchValues, $estado)->countAllResults(),
|
|
"",
|
|
$extra_data
|
|
));
|
|
} else {
|
|
return $this->failUnauthorized('Invalid request', 403);
|
|
}
|
|
}
|
|
|
|
public function tablaClienteForm()
|
|
{
|
|
|
|
$clienteId = $this->request->getGet('cliente_id') ?? -1;
|
|
|
|
$q = $this->model->getPedidosClienteForm($clienteId);
|
|
|
|
$searchValue = $this->request->getGet('fecha') ?? '';
|
|
if (!empty($searchValue)) {
|
|
// Extraer las fechas del formato "YYYY-MM-DD|YYYY-MM-DD"
|
|
$dates = explode('|', $searchValue);
|
|
if (count($dates) == 2) {
|
|
$q->where('p.created_at >=', $dates[0] . ' 00:00:00')
|
|
->where('p.created_at <=', $dates[1] . ' 23:59:59');
|
|
}
|
|
}
|
|
$searchValue = $this->request->getGet('fecha_entrega') ?? '';
|
|
if (!empty($searchValue)) {
|
|
// Extraer las fechas del formato "YYYY-MM-DD|YYYY-MM-DD"
|
|
$dates = explode('|', $searchValue);
|
|
if (count($dates) == 2) {
|
|
$q->where('p.fecha_entrega_real >=', $dates[0] . ' 00:00:00')
|
|
->where('p.fecha_entrega_real <=', $dates[1] . ' 23:59:59');
|
|
}
|
|
}
|
|
|
|
|
|
$result = DataTable::of($q)
|
|
->edit(
|
|
'fecha',
|
|
fn($q) => $q->fecha ? Time::createFromFormat("Y-m-d H:i:s", $q->fecha)->format("d/m/Y") : ""
|
|
)
|
|
->edit(
|
|
'fecha_entrega',
|
|
fn($q) => $q->fecha_entrega ? Time::createFromFormat("Y-m-d H:i:s", $q->fecha_entrega)->format("d/m/Y") : ""
|
|
)
|
|
->edit(
|
|
"estado",
|
|
function ($row, $meta) {
|
|
switch ($row->estado) {
|
|
case "validacion":
|
|
return lang('Pedidos.validacion');
|
|
case "produccion":
|
|
return lang('Pedidos.produccion');
|
|
case "finalizado":
|
|
return lang('Pedidos.finalizado');
|
|
case "enviado":
|
|
return lang('Pedidos.enviado');
|
|
case "cancelado":
|
|
return lang('Pedidos.cancelado');
|
|
default:
|
|
return '--'; // Debug
|
|
}
|
|
}
|
|
)
|
|
->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 obtenerTotalPedidosCliente($cliente_id)
|
|
{
|
|
|
|
$error = false;
|
|
$result = [
|
|
'total_impresion' => 0,
|
|
'total_maquetacion' => 0,
|
|
];
|
|
$data = $this->model
|
|
->where('presupuestos.cliente_id', $cliente_id)->whereNotIn('pedidos.estado', ['cancelado'])
|
|
->select('SUM(pedidos.total_precio) as total')
|
|
->join('pedidos_linea', 'pedidos_linea.pedido_id = pedidos.id')
|
|
->join('presupuestos', 'presupuestos.id = pedidos_linea.presupuesto_id')
|
|
->groupBy('presupuestos.cliente_id')->get()->getResultObject();
|
|
if (count($data) > 0) {
|
|
$result['total_impresion'] = round(floatval($data[0]->total), 2);
|
|
} else {
|
|
$error = true;
|
|
}
|
|
$result['total'] = $result['total_impresion'] + $result['total_maquetacion'];
|
|
return $this->respond(['status' => $error ? 'error' : 'success', 'totales' => $result]);
|
|
}
|
|
|
|
|
|
public function obtenerPedidosForFacturas()
|
|
{
|
|
if ($this->request->isAJAX()) {
|
|
$reqData = $this->request->getPost();
|
|
$start = $reqData['start'] ?? 0;
|
|
} 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);
|
|
}
|
|
}
|
|
|
|
|
|
public function addFactura()
|
|
{
|
|
|
|
if ($this->request->isAJAX()) {
|
|
|
|
|
|
$modelFactura = model('App\Models\Facturas\FacturaModel');
|
|
$modelFacturaLinea = model('App\Models\Facturas\FacturaLineaModel');
|
|
|
|
$pedido_id = $this->request->getPost('pedido_id');
|
|
$serie_id = $this->request->getPost('serie_id');
|
|
|
|
$datosFactura = $this->model->obtenerDatosForFactura($pedido_id);
|
|
|
|
if (count($datosFactura) == 0) {
|
|
return $this->respond(['status' => 'error', 'message' => 'Error obteniendo datos de factura']);
|
|
}
|
|
|
|
$datosFactura = $datosFactura[0];
|
|
|
|
$modelFactura->insert([
|
|
'cliente_id' => $datosFactura->cliente_id,
|
|
'serie_id' => $serie_id,
|
|
'estado' => 'borrador',
|
|
'estado_pago' => 'pendiente',
|
|
'fecha_factura_at' => date('Y-m-d'),
|
|
'cliente_nombre' => $datosFactura->cliente_nombre,
|
|
'cliente_cif' => $datosFactura->cliente_cif,
|
|
'cliente_pais' => $datosFactura->cliente_pais,
|
|
'cliente_address' => $datosFactura->cliente_direccion,
|
|
'cliente_cp' => $datosFactura->cliente_cp,
|
|
'cliente_cuidad' => $datosFactura->cliente_ciudad,
|
|
'cliente_provincia' => $datosFactura->cliente_provincia,
|
|
'user_created_id' => auth()->user()->id,
|
|
'user_updated_id' => auth()->user()->id
|
|
]);
|
|
|
|
$factura_id = $modelFactura->getInsertID();
|
|
|
|
if ($factura_id) {
|
|
|
|
$model_pedido_linea = model('\App\Models\Pedidos\PedidoLineaModel');
|
|
$lineas = $model_pedido_linea->where('pedido_id', $pedido_id)->first();
|
|
$facturas = new Facturas();
|
|
$result = $facturas->addLineaPedidoImpresion($factura_id, $lineas->id);
|
|
if ($result['error'] == 0) {
|
|
// Se actualiza el precio total de la factura obtenido de la linea añadida
|
|
$linea_added = $modelFacturaLinea->where('factura_id', $factura_id)->first();
|
|
$modelFactura->set([
|
|
'base' => $linea_added->base,
|
|
'total' => $linea_added->total,
|
|
'pendiente' => $linea_added->total,
|
|
])->where('id', $factura_id)->update();
|
|
return $this->respond(['status' => 'success', 'id' => $factura_id, 'message' => lang('Basic.global.success')]);
|
|
} else {
|
|
return $this->respond(['status' => 'error', 'message' => 'Error insertando lineas de factura']);
|
|
}
|
|
}
|
|
|
|
return $this->respond(['status' => 'error', 'message' => 'Error insertando factura']);
|
|
|
|
} 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)) : '';
|
|
|
|
$userModel = model('App\Models\Usuarios\UserModel');
|
|
$pedidoEntity->created_by = $userModel->getFullName($pedidoEntity->user_created_id);
|
|
$pedidoEntity->updated_by = $userModel->getFullName($pedidoEntity->user_updated_id);
|
|
$pedidoEntity->created_at_footer = $pedidoEntity->created_at ? date(' H:i d/m/Y', strtotime($pedidoEntity->created_at)) : '';
|
|
$pedidoEntity->updated_at_footer = $pedidoEntity->updated_at ? date(' H:i d/m/Y', strtotime($pedidoEntity->updated_at)) : '';
|
|
}
|
|
|
|
|
|
public function to_produccion($pedido_id)
|
|
{
|
|
$serviceProduction = service('production');
|
|
$pedido = $this->model->find($pedido_id);
|
|
$cliente = $pedido->presupuesto()->cliente_id;
|
|
$serviceProduction->setPedido($pedido);
|
|
if ($pedido->orden_trabajo()) {
|
|
return $this->response->setJSON(["status" => false, "data" => $pedido->orden_trabajo(), "message" => "Ya existe una orden de trabajo para este pedido"]);
|
|
|
|
} else {
|
|
$r = $serviceProduction->createOrdenTrabajo();
|
|
$this->model->set(['estado' => 'produccion'])->where('id', $pedido_id)->update();
|
|
$clienteModel = model('App\Models\Clientes\ClienteModel');
|
|
$cliente = $clienteModel->find($cliente);
|
|
if ($cliente) {
|
|
if ($cliente->tirada_flexible == 1) {
|
|
$ejemplares_tirada_flexible = intval($pedido->total_tirada * 0.05);
|
|
$comentario = lang('OrdenTrabajo.tiradaFlexible', [
|
|
'unidades' => $ejemplares_tirada_flexible
|
|
]) . "\n" . trim($cliente->comentarios_tirada_flexible);
|
|
|
|
$serviceProduction->init($r->id)->updateOrdenTrabajoData([
|
|
'name' => 'comment_logistica',
|
|
'comment_logistica' => $comentario
|
|
]);
|
|
}
|
|
}
|
|
return $this->response->setJSON(["status" => true, "data" => $r, "message" => "Orden trabajo creada correctamente"]);
|
|
}
|
|
}
|
|
|
|
}
|