diff --git a/app/resources/database/migrations/20141101080037_create_factura_venta.php b/app/resources/database/migrations/20141101080037_create_factura_venta.php
deleted file mode 100644
index 1556250..0000000
--- a/app/resources/database/migrations/20141101080037_create_factura_venta.php
+++ /dev/null
@@ -1,22 +0,0 @@
-execute('SET unique_checks=0; SET foreign_key_checks=0;');
- $this->execute("ALTER DATABASE CHARACTER SET 'utf8mb4';");
- $this->execute("ALTER DATABASE COLLATE='utf8mb4_general_ci';");
-
- $this->table('factura_venta')
- ->addColumn('factura_id', 'integer', ['length' => 10, 'null' => false, 'signed' => false])
- ->addColumn('venta_id', 'integer', ['length' => 10, 'null' => false, 'signed' => false])
- ->addColumn('valor', 'double', ['null' => false])
- ->addForeignKey('factura_id', 'factura_proyecto_operador', 'id', ['delete' => 'cascade', 'update' => 'cascade'])
- ->addForeignKey('venta_id', 'venta', 'id', ['delete' => 'cascade', 'update' => 'cascade'])
- ->create();
- $this->execute('SET unique_checks=1; SET foreign_key_checks=1;');
- }
-}
diff --git a/app/resources/database/migrations/20141101080037_create_venta_datos_facturas.php b/app/resources/database/migrations/20141101080037_create_venta_datos_facturas.php
new file mode 100644
index 0000000..cea37ba
--- /dev/null
+++ b/app/resources/database/migrations/20141101080037_create_venta_datos_facturas.php
@@ -0,0 +1,24 @@
+execute('SET unique_checks=0; SET foreign_key_checks=0;');
+ $this->execute("ALTER DATABASE CHARACTER SET 'utf8mb4';");
+ $this->execute("ALTER DATABASE COLLATE='utf8mb4_general_ci';");
+
+ $this->table('venta_datos_facturas')
+ ->addColumn('venta_id', 'integer', ['length' => 10, 'signed' => false])
+ ->addColumn('fecha', 'date')
+ ->addColumn('uf', 'string', ['length' => 50]) // fecha, valor
+ ->addColumn('ipc', 'string', ['length' => 50]) // fecha, valor
+ ->addColumn('terreno', 'integer', ['signed' => false])
+ ->addColumn('unidades', 'text') // id, precios, prorrateo
+ ->addForeignKey('venta_id', 'venta', 'id', ['delete' => 'cascade', 'update' => 'cascade'])
+ ->create();
+ $this->execute('SET unique_checks=1; SET foreign_key_checks=1;');
+ }
+}
diff --git a/app/resources/database/migrations/20141101080038_create_facturas.php b/app/resources/database/migrations/20141101080038_create_facturas.php
index 0cd4c00..3938e9b 100644
--- a/app/resources/database/migrations/20141101080038_create_facturas.php
+++ b/app/resources/database/migrations/20141101080038_create_facturas.php
@@ -11,11 +11,12 @@ class CreateFacturas extends Phinx\Migration\AbstractMigration
$this->execute("ALTER DATABASE COLLATE='utf8mb4_general_ci';");
$this->table('facturas')
- ->addColumn('venta_id', 'integer', ['length' => 10, 'null' => false, 'signed' => false])
- ->addColumn('index', 'integer', ['length' => 10, 'null' => false, 'signed' => false])
- ->addColumn('proporcion', 'double', ['null' => false, 'signed' => false])
- ->addColumn('data', 'text', ['null' => false])
+ ->addColumn('venta_id', 'integer', ['length' => 10, 'signed' => false])
+ ->addColumn('index', 'integer', ['signed' => false])
+ ->addColumn('proporcion', 'double', ['signed' => false]) // %
+ ->addColumn('cliente_rut', 'integer', ['length' => 10, 'signed' => false])
->addForeignKey('venta_id', 'venta', 'id', ['delete' => 'cascade', 'update' => 'cascade'])
+ ->addForeignKey('cliente_rut', 'personas', 'rut', ['delete' => 'cascade', 'update' => 'cascade'])
->create();
$this->execute('SET unique_checks=1; SET foreign_key_checks=1;');
}
diff --git a/app/resources/routes/api/ventas/facturas.php b/app/resources/routes/api/ventas/facturas.php
index 697f1b0..fb97561 100644
--- a/app/resources/routes/api/ventas/facturas.php
+++ b/app/resources/routes/api/ventas/facturas.php
@@ -4,3 +4,6 @@ use Incoviba\Controller\API\Ventas\Facturas;
$app->group('/facturas', function($app) {
$app->post('/add[/]', [Facturas::class, 'add']);
});
+$app->group('/facturas/{factura_id}', function($app) {
+ $app->post('/edit[/]', [Facturas::class, 'edit']);
+});
diff --git a/app/resources/views/ventas/facturacion/show.blade.php b/app/resources/views/ventas/facturacion/show.blade.php
index b2146d9..d9bcaba 100644
--- a/app/resources/views/ventas/facturacion/show.blade.php
+++ b/app/resources/views/ventas/facturacion/show.blade.php
@@ -19,1015 +19,11 @@
@endsection
@push('page_scripts')
+ @include('ventas.facturacion.show.factura')
+ @include('ventas.facturacion.show.propietario')
+ @include('ventas.facturacion.show.unidad')
+ @include('ventas.facturacion.show.venta')
diff --git a/app/resources/views/ventas/facturacion/show/propietario.blade.php b/app/resources/views/ventas/facturacion/show/propietario.blade.php
new file mode 100644
index 0000000..03f076d
--- /dev/null
+++ b/app/resources/views/ventas/facturacion/show/propietario.blade.php
@@ -0,0 +1,193 @@
+
diff --git a/app/resources/views/ventas/facturacion/show/unidad.blade.php b/app/resources/views/ventas/facturacion/show/unidad.blade.php
new file mode 100644
index 0000000..af57b94
--- /dev/null
+++ b/app/resources/views/ventas/facturacion/show/unidad.blade.php
@@ -0,0 +1,125 @@
+
diff --git a/app/resources/views/ventas/facturacion/show/venta.blade.php b/app/resources/views/ventas/facturacion/show/venta.blade.php
new file mode 100644
index 0000000..e3638f5
--- /dev/null
+++ b/app/resources/views/ventas/facturacion/show/venta.blade.php
@@ -0,0 +1,472 @@
+
diff --git a/app/src/Controller/API/Ventas/Facturas.php b/app/src/Controller/API/Ventas/Facturas.php
index 19c4ff2..6a5d9a1 100644
--- a/app/src/Controller/API/Ventas/Facturas.php
+++ b/app/src/Controller/API/Ventas/Facturas.php
@@ -18,11 +18,18 @@ class Facturas extends Controller
$output = [
'input' => $data,
'factura' => null,
- 'saved' => false
+ 'success' => false
];
try {
+ /*foreach (['cliente', 'unidades', 'detalle', 'total', 'uf'] as $key) {
+ if (!isset($data[$key]) or empty($data[$key])) {
+ continue;
+ }
+ $data[$key] = json_decode($data[$key], true);
+ }*/
+ $data['cliente'] = json_decode($data['cliente'], true);
$output['factura'] = $facturaService->add($data);
- $output['saved'] = true;
+ $output['success'] = true;
} catch (Implement\Exception\EmptyResult) {
$output['error'] = 'No se pudo agregar la factura';
return $this->withJson($response, $output, 400);
diff --git a/app/src/Controller/API/withJson.php b/app/src/Controller/API/withJson.php
index 1a6e2f4..cc4c051 100644
--- a/app/src/Controller/API/withJson.php
+++ b/app/src/Controller/API/withJson.php
@@ -5,9 +5,9 @@ use Psr\Http\Message\ResponseInterface;
trait withJson
{
- public function withJson(ResponseInterface $response, array|object $data = []): ResponseInterface
+ public function withJson(ResponseInterface $response, array|object $data = [], int $statusCode = 200): ResponseInterface
{
$response->getBody()->write(json_encode($data));
- return $response->withHeader('Content-Type', 'application/json');
+ return $response->withStatus($statusCode)->withHeader('Content-Type', 'application/json');
}
}
diff --git a/app/src/Controller/Ventas/Facturacion.php b/app/src/Controller/Ventas/Facturacion.php
index 39ccccb..1563277 100644
--- a/app/src/Controller/Ventas/Facturacion.php
+++ b/app/src/Controller/Ventas/Facturacion.php
@@ -8,6 +8,7 @@ use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Incoviba\Common\Alias\View;
use Incoviba\Common\Ideal;
+use Incoviba\Repository;
use Incoviba\Service;
class Facturacion extends Ideal\Controller
@@ -29,6 +30,7 @@ class Facturacion extends Ideal\Controller
Service\Venta $ventaService, Service\Proyecto\Terreno $terrenoService,
Service\IPC $ipcService, Service\UF $ufService,
Service\Venta\Factura $facturasService,
+ Repository\Comuna $comunaRepository,
int $venta_id): ResponseInterface
{
$venta = $ventaService->getById($venta_id);
@@ -48,7 +50,8 @@ class Facturacion extends Ideal\Controller
}
}
$facturas = $facturasService->getByVenta($venta->id);
+ $comunas = $comunaRepository->fetchAll('descripcion');
- return $view->render($response, 'ventas.facturacion.show', compact('venta', 'terreno', 'uf', 'ipc', 'facturas'));
+ return $view->render($response, 'ventas.facturacion.show', compact('venta', 'terreno', 'uf', 'ipc', 'facturas', 'comunas'));
}
}
diff --git a/app/src/Model/Venta/Factura.php b/app/src/Model/Venta/Factura.php
index cb0b259..a4d2f55 100644
--- a/app/src/Model/Venta/Factura.php
+++ b/app/src/Model/Venta/Factura.php
@@ -8,30 +8,16 @@ use Incoviba\Model;
class Factura extends Ideal\Model
{
public Model\Venta $venta;
+
public int $index;
public float $proporcion;
- public string $emisorRut;
- public string $emisorNombre;
- public string $emisorDireccion;
- public string $receptorRut;
- public string $receptorNombre;
- public string $receptorDireccion;
- public string $receptorComuna;
- public DateTimeInterface $fecha;
- public array $unidades;
- public int $detalleBase;
- public int $detalleTerreno;
- public int $detalleNeto;
- public int $detalleIva;
- public int $detalleBruto;
- public float $detalleDescuento;
- public int $detalleTotal;
- public int $totalNeto;
- public int $totalExento;
- public int $totalIva;
- public int $totalTotal;
- public DateTimeInterface $fechaUF;
- public float $valorUF;
+ public Model\Persona $cliente;
+
+ public ?DateTimeInterface $fecha = null;
+ public ?array $unidades = null; // [[unidad, descripcion, precio, prorrateo]]
+ public ?int $terreno = null;
+ public ?object $uf = null; // [fecha, valor]
+ public ?object $ipc = null; // [fecha, valor]
protected array $estados;
public function estados(): array
@@ -42,6 +28,52 @@ class Factura extends Ideal\Model
return $this->estados ?? [];
}
+ public function total(): float
+ {
+ return $this->venta->valor * $this->uf->valor * $this->proporcion;
+ }
+ public function bruto(): float
+ {
+ return $this->total() - $this->terreno * $this->proporcion;
+ }
+ public function iva(): float
+ {
+ return $this->neto() * .19;
+ }
+ public function neto(): float
+ {
+ return $this->bruto() / 1.19;
+ }
+ public function base(): float
+ {
+ return $this->neto() + $this->terreno * $this->proporcion;
+ }
+ public function detalle(): array
+ {
+ return [
+ 'base' => $this->base(),
+ 'terreno' => $this->terreno * $this->proporcion,
+ 'neto' => $this->neto(),
+ 'iva' => $this->iva(),
+ 'bruto' => $this->bruto(),
+ 'total' => $this->total(),
+ 'descuento' => array_reduce($this->unidades, function($sum, $unidad) {
+ return $sum + $unidad->prorrateo * $this->proporcion;
+ }, 0)
+ ];
+ }
+ public function totales(): array
+ {
+ return [
+ 'neto' => array_reduce($this->unidades, function($sum, $unidad) {
+ return $sum + $unidad->precio * $this->proporcion;
+ }),
+ 'exento' => $this->terreno * $this->proporcion,
+ 'iva' => $this->iva(),
+ 'total' => $this->total()
+ ];
+ }
+
public function jsonSerialize(): mixed
{
return array_merge(parent::jsonSerialize(), [
@@ -49,38 +81,26 @@ class Factura extends Ideal\Model
'index' => $this->index,
'proporcion' => $this->proporcion,
'emisor' => [
- 'rut' => $this->emisorRut,
- 'nombre' => $this->emisorNombre,
- 'direccion' => $this->emisorDireccion
+ 'rut' => $this->venta->proyecto()->inmobiliaria()->rut(),
+ 'nombre' => $this->venta->proyecto()->inmobiliaria()->nombreCompleto(),
+ 'direccion' => $this->venta->proyecto()->direccion()->simple(),
+ 'comuna' => $this->venta->proyecto()->direccion()->comuna->descripcion
],
'receptor' => [
- 'rut' => $this->receptorRut,
- 'nombre' => $this->receptorNombre,
- 'direccion' => $this->receptorDireccion,
- 'comuna' => $this->receptorComuna
+ 'rut' => $this->cliente->rutCompleto(),
+ 'nombre' => $this->cliente->nombreCompleto(),
+ 'direccion' => $this->cliente->datos()->direccion?->simple(),
+ 'comuna' => $this->cliente->datos()->direccion?->comuna->descripcion
],
- 'fecha' => $this->fecha->format('Y-m-d'),
+ 'fecha' => $this->fecha?->format('Y-m-d'),
'unidades' => $this->unidades,
- 'detalle' => [
- 'base' => $this->detalleBase,
- 'terreno' => $this->detalleTerreno,
- 'neto' => $this->detalleNeto,
- 'iva' => $this->detalleIva,
- 'bruto' => $this->detalleBruto,
- 'descuento' => $this->detalleDescuento,
- 'total' => $this->detalleTotal
- ],
- 'total' => [
- 'neto' => $this->totalNeto,
- 'exento' => $this->totalExento,
- 'iva' => $this->totalIva,
- 'total' => $this->totalTotal
- ],
+ 'detalle' => $this->detalle(),
+ 'total' => $this->totales(),
'uf' => [
- 'fecha' => $this->fechaUF->format('Y-m-d'),
- 'valor' => $this->valorUF
+ 'fecha' => $this->uf?->fecha->format('Y-m-d'),
+ 'valor' => $this->uf?->valor
],
- 'estados' => $this->estados()
]);
}
+
}
diff --git a/app/src/Repository/Venta/Factura.php b/app/src/Repository/Venta/Factura.php
index 0bd8716..d094ebd 100644
--- a/app/src/Repository/Venta/Factura.php
+++ b/app/src/Repository/Venta/Factura.php
@@ -1,6 +1,7 @@
setTable('facturas');
@@ -19,89 +23,175 @@ class Factura extends Ideal\Repository
public function create(?array $data = null): Model\Venta\Factura
{
- $map = (new Implement\Repository\MapperParser(['index']))
+ $map = (new Implement\Repository\MapperParser(['index', 'proporcion']))
->register('venta_id', (new Implement\Repository\Mapper())
->setProperty('venta')
->setFunction(function($data) {
return $this->ventaRepository->fetchById($data['venta_id']);
+ }))
+ ->register('cliente_rut', (new Implement\Repository\Mapper())
+ ->setProperty('cliente')
+ ->setFunction(function($data) {
+ return $this->personaService->getById($data['cliente_rut']);
}));
$factura = $this->parseData(new Model\Venta\Factura(), $data, $map);
- $json = json_decode($data['data']);
- $factura->proporcion = $json->proporcion;
- $factura->emisorRut = $json->emisor->rut;
- $factura->emisorNombre = $json->emisor->nombre;
- $factura->emisorDireccion = $json->emisor->direccion;
- $factura->receptorRut = $json->receptor->rut;
- $factura->receptorNombre = $json->receptor->nombre;
- $factura->receptorDireccion = $json->receptor->direccion;
- $factura->receptorComuna = $json->receptor->comuna;
- $factura->fecha = new DateTimeImmutable($json->fecha);
- $factura->unidades = $json->unidades;
- $factura->detalleBase = $json->detalle->base;
- $factura->detalleTerreno = $json->detalle->terreno;
- $factura->detalleNeto = $json->detalle->neto;
- $factura->detalleIva = $json->detalle->iva;
- $factura->detalleBruto = $json->detalle->bruto;
- $factura->detalleDescuento = $json->detalle->descuento;
- $factura->detalleTotal = $json->detalle->total;
- $factura->totalNeto = $json->total->neto;
- $factura->totalExento = $json->total->exento;
- $factura->totalIva = $json->total->iva;
- $factura->totalTotal = $json->total->total;
- $factura->fechaUF = new DateTimeImmutable($json->uf->fecha);
- $factura->valorUF = $json->uf->valor;
+ return $this->createDatos($factura, $data);
+ }
+ public function createDatos(Model\Venta\Factura &$factura, ?array $data = null): Model\Venta\Factura
+ {
+ try {
+ $result = $this->getDatos($factura->venta->id);
+ if ($result['fecha'] !== null) {
+ $factura->fecha = new DateTimeImmutable($result['fecha']);
+ }
+ if ($result['uf'] !== null) {
+ $factura->uf = json_decode($result['uf']);
+ $factura->uf->fecha = new DateTimeImmutable($factura->uf->fecha);
+ }
+ if ($result['ipc'] !== null) {
+ $factura->ipc = json_decode($result['ipc']);
+ $factura->ipc->fecha = new DateTimeImmutable($factura->ipc->fecha);
+ }
+ if ($result['unidades'] !== null) {
+ $factura->unidades = array_map(function($datos) use ($factura) {
+ $unidad = $this->unidadRepository->fetchById($datos->unidad_id);
+ return (object) [
+ 'unidad' => $unidad,
+ 'descripcion' => implode(' ', [ucwords($unidad->proyectoTipoUnidad->tipoUnidad->descripcion), $unidad->descripcion]),
+ 'precio' => $datos->precio,
+ 'prorrateo' => $datos->prorrateo
+ ];
+ }, json_decode($result['unidades']));
+ }
+ if ($result['terreno'] !== null) {
+ $factura->terreno = $result['terreno'];
+ }
+ } catch (EmptyResult) {
+ if (isset($data['fecha'])) {
+ $factura->fecha = new DateTimeImmutable($data['fecha']);
+ }
+ if (isset($data['uf'])) {
+ $factura->uf = json_decode($data['uf']);
+ $factura->uf->fecha = new DateTimeImmutable($factura->uf->fecha);
+ }
+ if (isset($data['ipc'])) {
+ $factura->ipc = json_decode($data['ipc']);
+ $factura->ipc->fecha = new DateTimeImmutable($factura->ipc->fecha);
+ }
+ if (isset($data['unidades'])) {
+ $factura->unidades = array_map(function($datos) use ($factura) {
+ $unidad = $this->unidadRepository->fetchById($datos->unidad_id);
+ return (object) [
+ 'unidad' => $unidad,
+ 'descripcion' => implode(' ', [ucwords($unidad->proyectoTipoUnidad->tipoUnidad->descripcion), $unidad->descripcion]),
+ 'precio' => $datos->precio,
+ 'prorrateo' => $datos->prorrateo
+ ];
+ }, json_decode($data['unidades']));
+ }
+ if (isset($data['terreno'])) {
+ $factura->terreno = (int) $data['terreno'];
+ }
+ }
+
return $factura;
}
+ protected function getDatos(int $venta_id): array
+ {
+ $query = $this->connection->getQueryBuilder()
+ ->select()
+ ->from('venta_datos_facturas')
+ ->where('venta_id = :venta_id');
+ $result = $this->connection->execute($query, ['venta_id' => $venta_id])->fetch(PDO::FETCH_ASSOC);
+ if ($result === false) {
+ throw new EmptyResult($query);
+ }
+ return $result;
+ }
public function save(Define\Model $model): Model\Venta\Factura
{
$model->id = $this->saveNew([
'venta_id',
'index',
- 'data'
+ 'proporcion',
+ 'cliente_rut'
], [
$model->venta->id,
$model->index,
- json_encode([
- 'proporcion' => $model->proporcion,
- 'emisor' => [
- 'rut' => $model->emisorRut,
- 'nombre' => $model->emisorNombre,
- 'direccion' => $model->emisorDireccion
- ],
- 'receptor' => [
- 'rut' => $model->receptorRut,
- 'nombre' => $model->receptorNombre,
- 'direccion' => $model->receptorDireccion,
- 'comuna' => $model->receptorComuna
- ],
- 'fecha' => $model->fecha->format('Y-m-d'),
- 'unidades' => $model->unidades,
- 'detalle' => [
- 'base' => $model->detalleBase,
- 'terreno' => $model->detalleTerreno,
- 'neto' => $model->detalleNeto,
- 'iva' => $model->detalleIva,
- 'bruto' => $model->detalleBruto,
- 'descuento' => $model->detalleDescuento,
- 'total' => $model->detalleTotal
- ],
- 'total' => [
- 'neto' => $model->totalNeto,
- 'exento' => $model->totalExento,
- 'iva' => $model->totalIva,
- 'total' => $model->totalTotal
- ],
- 'uf' => [
- 'fecha' => $model->fechaUF->format('Y-m-d'),
- 'valor' => $model->valorUF
- ]
- ])
+ $model->proporcion,
+ $model->cliente->rut
]);
- return $model;
+ return $this->saveDatos($model);
+ }
+ protected function saveDatos(Model\Venta\Factura $factura): Model\Venta\Factura
+ {
+ try {
+ $this->getDatos($factura->venta->id);
+ } catch (EmptyResult) {
+ $query = $this->connection->getQueryBuilder()
+ ->insert()
+ ->into('venta_datos_facturas')
+ ->columns([
+ 'venta_id',
+ 'fecha',
+ 'unidades',
+ 'terreno',
+ 'uf',
+ 'ipc'
+ ])
+ ->values([
+ 'venta_id' => $factura->venta->id,
+ 'fecha' => $factura->fecha?->format('Y-m-d'),
+ 'unidades' => (isset($factura->unidades)) ? json_encode(array_map(function($unidad) {
+ return [
+ 'unidad_id' => $unidad->unidad->id,
+ 'precio' => $unidad->precio,
+ 'prorrateo' => $unidad->prorrateo
+ ];
+ }, $factura?->unidades)) : null,
+ 'terreno' => $factura?->terreno,
+ 'uf' => (isset($factura->uf)) ? json_encode(['fecha' => $factura->uf?->fecha->format('Y-m-d'), 'valor' => $factura->uf?->valor]) : null,
+ 'ipc' => (isset($factura->ipc)) ? json_encode(['fecha' => $factura->ipc?->fecha->format('Y-m-d'), 'valor' => $factura->ipc?->valor]) : null
+ ]);
+ $this->connection->execute($query);
+ }
+
+ return $factura;
}
public function edit(Define\Model $model, array $new_data): Model\Venta\Factura
{
- return $this->update($model, ['venta_id', 'index', 'data'], $new_data);
+ $model = $this->editDatos($model, $new_data);
+ return $this->update($model, ['venta_id', 'index', 'proporcion', 'cliente_rut'], $new_data);
+ }
+ protected function editDatos(Model\Venta\Factura $factura, array $new_data): Model\Venta\Factura
+ {
+ $dataFields = [
+ 'fecha',
+ 'unidades',
+ 'terreno',
+ 'uf',
+ 'ipc'
+ ];
+ $fields = [];
+ $values = [];
+ foreach ($dataFields as $field) {
+ if (isset($new_data[$field])) {
+ $fields[] = "{$field} = ?";
+ $values[] = is_array($new_data[$field]) ? json_encode($new_data[$field]) : $new_data[$field];
+ }
+ }
+ if (count($fields) === 0) {
+ return $factura;
+ }
+
+ $query = $this->connection->getQueryBuilder()
+ ->update('venta_datos_facturas')
+ ->set($fields)
+ ->where('venta_id = ?')
+ ->limit(1);
+ $this->connection->execute($query, array_merge($values, [$factura->venta->id]));
+
+ return $this->fetchById($factura->id);
}
/**
@@ -123,7 +213,7 @@ class Factura extends Ideal\Repository
$query = $this->connection->getQueryBuilder()
->select()
->from($this->getTable())
- ->where('venta_id = :venta_id AND index = :index');
+ ->where('venta_id = :venta_id AND `index` = :index');
return $this->fetchOne($query, ['venta_id' => $venta_id, 'index' => $index]);
}
}
diff --git a/app/src/Service/Persona.php b/app/src/Service/Persona.php
index 5e8244e..39733a6 100644
--- a/app/src/Service/Persona.php
+++ b/app/src/Service/Persona.php
@@ -9,8 +9,10 @@ use Psr\Log\LoggerInterface;
class Persona extends Ideal\Service
{
- public function __construct(LoggerInterface $logger, protected Repository\Persona $personaRepository,
- protected Repository\Persona\Datos $datosPersonaRepository)
+ public function __construct(LoggerInterface $logger,
+ protected Repository\Persona $personaRepository,
+ protected Repository\Persona\Datos $datosPersonaRepository,
+ protected Repository\Venta\Propietario $propietarioRepository)
{
parent::__construct($logger);
}
@@ -24,11 +26,21 @@ class Persona extends Ideal\Service
try {
$persona = $this->personaRepository->fetchById($data['rut']);
} catch (Implement\Exception\EmptyResult) {
+ try {
+ $propietario = $this->propietarioRepository->fetchById($data['rut']);
+ $data['nombres'] = $propietario->nombres;
+ $data['apellido_paterno'] = $propietario->apellidos['paterno'];
+ $data['apellido_materno'] = $propietario->apellidos['materno'];
+ $data['direccion_id'] = $propietario->datos->direccion->id;
+ } catch (Implement\Exception\EmptyResult) {}
$persona = $this->personaRepository->create($data);
$persona = $this->personaRepository->save($persona);
}
- if (isset($data['email']) or isset($data['telefono'])) {
+ if (isset($data['direccion_id']) or isset($data['email']) or isset($data['telefono'])) {
$datosData = ['persona_rut' => $persona->rut];
+ if (isset($data['direccion_id'])) {
+ $datosData['direccion_id'] = $data['direccion_id'];
+ }
if (isset($data['email'])) {
$datosData['email'] = $data['email'];
}
diff --git a/app/src/Service/Redis.php b/app/src/Service/Redis.php
index 5f85f0e..6b14761 100644
--- a/app/src/Service/Redis.php
+++ b/app/src/Service/Redis.php
@@ -3,6 +3,7 @@ namespace Incoviba\Service;
use Predis\ClientInterface;
use Incoviba\Common\Implement\Exception\EmptyRedis;
+use Predis\Connection\ConnectionException;
class Redis
{
@@ -10,13 +11,21 @@ class Redis
public function get(string $name): mixed
{
- if (!$this->client->exists($name)) {
- throw new EmptyRedis($name);
+ try {
+ if (!$this->client->exists($name)) {
+ throw new EmptyRedis($name);
+ }
+ return $this->client->get($name);
+ } catch (ConnectionException $exception) {
+ throw new EmptyRedis($name, $exception);
}
- return $this->client->get($name);
}
public function set(string $name, mixed $value, int $expirationTTL = 60 * 60 * 24): void
{
- $this->client->set($name, $value, 'EX', $expirationTTL);
+ try {
+ $this->client->set($name, $value, 'EX', $expirationTTL);
+ } catch (ConnectionException) {
+ return;
+ }
}
}
diff --git a/app/src/Service/Venta/Factura.php b/app/src/Service/Venta/Factura.php
index 7715810..e5bcc84 100644
--- a/app/src/Service/Venta/Factura.php
+++ b/app/src/Service/Venta/Factura.php
@@ -7,13 +7,15 @@ use Incoviba\Common\Ideal;
use Incoviba\Common\Implement;
use Incoviba\Model;
use Incoviba\Repository;
+use Incoviba\Service;
class Factura extends Ideal\Service
{
public function __construct(LoggerInterface $logger,
protected Repository\Venta\Factura $facturaRepository,
protected Repository\Venta\Factura\Estado $estadoRepository,
- protected Repository\Venta\Factura\Estado\Tipo $tipoRepository)
+ protected Repository\Venta\Factura\Estado\Tipo $tipoRepository,
+ protected Service\Persona $personaService)
{
parent::__construct($logger);
}
@@ -57,7 +59,13 @@ class Factura extends Ideal\Service
if ($factura !== null) {
return $factura;
}
- $factura = $this->facturaRepository->save($this->facturaRepository->create($data));
+ list($data['cliente']['rut'], $data['cliente']['digito']) = explode('-', $data['cliente']['rut']);
+ $data['cliente']['rut'] = (int) str_replace('.', '', $data['cliente']['rut']);
+ $client = $this->personaService->add($data['cliente']);
+ $data['cliente_rut'] = $client->rut;
+ unset($data['cliente']);
+ $factura = $this->facturaRepository->create($data);
+ $factura = $this->facturaRepository->save($factura);
$tipo = $this->tipoRepository->fetchByDescripcion('generada');
$this->estadoRepository->save($this->estadoRepository->create([
'factura_id' => $factura->id,