',
+ `
`,
'',
'Guardada',
'
',
@@ -300,14 +300,30 @@
watch() {
return {
save: () => {
- document.querySelector(`button[data-index="${this.props.index}"]`).addEventListener('click', clickEvent => {
+ document.querySelector(`.guardar[data-index="${this.props.index}"]`).addEventListener('click', clickEvent => {
const index = clickEvent.currentTarget.getAttribute('data-index')
- facturas.save().factura(index)
+ facturas.venta.save().factura({index: index - 1})
})
}
}
}
+ validate() {
+ if (this.props.venta.id === null || typeof this.props.venta.id === 'undefined') {
+ return false
+ }
+ if (this.props.index === null || typeof this.props.index === 'undefined') {
+ return false
+ }
+ if (this.props.proporcion === null || typeof this.props.proporcion === 'undefined') {
+ return false
+ }
+ return !(this.props.receptor.rut === '' || this.props.receptor.nombre === '' || this.props.receptor.direccion === '' || this.props.receptor.comuna === '');
+
+ }
save() {
+ if (!this.validate()) {
+ return
+ }
let url = '{{$urls->api}}/ventas/facturas/add'
if (this.saved) {
url = `{{$urls->api}}/ventas/facturas/${this.props.id}/edit`
@@ -326,6 +342,7 @@
body.set('detalle', JSON.stringify(this.props.detalle))
body.set('total', JSON.stringify(this.props.total))
body.set('uf', JSON.stringify({fecha: [this.props.uf.fecha.getFullYear(), this.props.uf.fecha.getMonth()+1, this.props.uf.fecha.getDate()].join('-'), valor: this.props.uf.valor}))
+
return APIClient.fetch(url, {method, body}).then(response => {
if (!response) {
return
@@ -366,7 +383,7 @@
unidades.forEach(unidad => {
this.props.unidades.push({
unidad: unidad,
- descripcion: unidad.descripcion(this.props.proporcion),
+ descripcion: unidad.changeDescripcion(this.props.proporcion || 1),
precio: unidad.props.valor * this.props.uf.valor * this.props.proporcion,
prorrateo: unidad.props.prorrateo * this.props.proporcion
})
@@ -376,10 +393,10 @@
this.props.proporcion = propietario.props.proporcion
this.props.receptor = {
- rut: propietario.props.rut,
- nombre: propietario.props.nombre,
- direccion: propietario.props.direccion,
- comuna: propietario.comuna
+ rut: propietario.props.rut ?? '',
+ nombre: propietario.props.nombre ?? '',
+ direccion: propietario.props.direccion ?? '',
+ comuna: propietario.comuna ?? ''
}
}
}
diff --git a/app/resources/views/ventas/facturacion/show/propietario.blade.php b/app/resources/views/ventas/facturacion/show/propietario.blade.php
index f33fe56..03f076d 100644
--- a/app/resources/views/ventas/facturacion/show/propietario.blade.php
+++ b/app/resources/views/ventas/facturacion/show/propietario.blade.php
@@ -14,7 +14,11 @@
}
get comuna() {
- return $('#comuna_propietario'+this.props.index).dropdown('get text') ?? this.props.comuna
+ const comuna = $('#comuna_propietario'+this.props.index).dropdown('get text')
+ if (typeof comuna === 'string') {
+ return comuna
+ }
+ return this.props.comuna ?? ''
}
update() {
return {
diff --git a/app/resources/views/ventas/facturacion/show/unidad.blade.php b/app/resources/views/ventas/facturacion/show/unidad.blade.php
index c290796..af57b94 100644
--- a/app/resources/views/ventas/facturacion/show/unidad.blade.php
+++ b/app/resources/views/ventas/facturacion/show/unidad.blade.php
@@ -13,8 +13,8 @@
this.props = props
}
- descripcion(proporcion = 1) {
- return [this.props.tipo, this.props.descripcion, `[UF ${facturas.formatters.ufs.format(this.props.valor * proporcion)}]`].join(' ')
+ changeDescripcion(proporcion = 1) {
+ return this.descripcion = [this.props.tipo, this.props.descripcion, `[UF ${facturas.formatters.ufs.format(this.props.valor * proporcion)}]`].join(' ')
}
update() {
return {
diff --git a/app/resources/views/ventas/facturacion/show/venta.blade.php b/app/resources/views/ventas/facturacion/show/venta.blade.php
index bfb8f4a..e3638f5 100644
--- a/app/resources/views/ventas/facturacion/show/venta.blade.php
+++ b/app/resources/views/ventas/facturacion/show/venta.blade.php
@@ -252,6 +252,11 @@
this.props.propietarios.forEach(propietario => {
propietario.watch().propietario()
})
+ },
+ facturas: () => {
+ this.props.facturas.facturas.forEach(factura => {
+ factura.watch().save()
+ })
}
}
}
@@ -267,11 +272,11 @@
value: ufFormatter => {
return [
'
',
- '
',
- '
',
- 'Valor Venta: UF ' + ufFormatter.format(this.props.valor),
- '
',
- '
',
+ '
',
+ '
',
+ 'Valor Venta: UF ' + ufFormatter.format(this.props.valor),
+ '
',
+ '
',
'
'
].join("\n")
},
@@ -377,7 +382,7 @@
},
facturas: formatters => {
const output = []
- this.props.facturas.facturas.forEach((factura, index) => {
+ this.props.facturas.facturas.forEach(factura => {
output.push(factura.draw().factura({formatters}))
})
return output.join("\n")
@@ -405,10 +410,10 @@
comuna: this.props.inmobiliaria.comuna
},
receptor: {
- rut: '',
- nombre: '',
- direccion: '',
- comuna: ''
+ rut: propietario.props.rut ?? '',
+ nombre: propietario.props.nombre ?? '',
+ direccion: propietario.props.direccion ?? '',
+ comuna: propietario.props.comuna ?? ''
},
unidades: [],
detalle: {
diff --git a/app/src/Controller/API/Ventas/Facturas.php b/app/src/Controller/API/Ventas/Facturas.php
index 8757bcd..6a5d9a1 100644
--- a/app/src/Controller/API/Ventas/Facturas.php
+++ b/app/src/Controller/API/Ventas/Facturas.php
@@ -21,12 +21,13 @@ class Facturas extends Controller
'success' => false
];
try {
- foreach (['cliente', 'unidades', 'detalle', 'total', 'uf'] as $key) {
+ /*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['success'] = true;
} catch (Implement\Exception\EmptyResult) {
diff --git a/app/src/Model/Venta/Factura.php b/app/src/Model/Venta/Factura.php
index f3d4d1b..a4d2f55 100644
--- a/app/src/Model/Venta/Factura.php
+++ b/app/src/Model/Venta/Factura.php
@@ -13,11 +13,11 @@ class Factura extends Ideal\Model
public float $proporcion;
public Model\Persona $cliente;
- public DateTimeInterface $fecha;
- public array $unidades; // [[unidad, descripcion, precio, prorrateo]]
- public int $terreno;
- public object $uf; // [fecha, valor]
- public object $ipc; // [fecha, valor]
+ 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
@@ -28,23 +28,23 @@ class Factura extends Ideal\Model
return $this->estados ?? [];
}
- public function total(): int
+ public function total(): float
{
return $this->venta->valor * $this->uf->valor * $this->proporcion;
}
- public function bruto(): int
+ public function bruto(): float
{
return $this->total() - $this->terreno * $this->proporcion;
}
- public function iva(): int
+ public function iva(): float
{
return $this->neto() * .19;
}
- public function neto(): int
+ public function neto(): float
{
return $this->bruto() / 1.19;
}
- public function base(): int
+ public function base(): float
{
return $this->neto() + $this->terreno * $this->proporcion;
}
@@ -59,7 +59,7 @@ class Factura extends Ideal\Model
'total' => $this->total(),
'descuento' => array_reduce($this->unidades, function($sum, $unidad) {
return $sum + $unidad->prorrateo * $this->proporcion;
- })
+ }, 0)
];
}
public function totales(): array
@@ -89,18 +89,17 @@ class Factura extends Ideal\Model
'receptor' => [
'rut' => $this->cliente->rutCompleto(),
'nombre' => $this->cliente->nombreCompleto(),
- 'direccion' => $this->cliente->datos()->direccion->simple(),
- 'comuna' => $this->cliente->datos()->direccion->comuna->descripcion
+ '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' => $this->detalle(),
'total' => $this->totales(),
'uf' => [
- 'fecha' => $this->uf->fecha->format('Y-m-d'),
- 'valor' => $this->uf->valor
+ '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 97ee81c..d094ebd 100644
--- a/app/src/Repository/Venta/Factura.php
+++ b/app/src/Repository/Venta/Factura.php
@@ -9,10 +9,12 @@ use Incoviba\Common\Implement;
use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Model;
use Incoviba\Repository;
+use Incoviba\Service;
class Factura extends Ideal\Repository
{
public function __construct(Implement\Connection $connection, protected Repository\Venta $ventaRepository,
+ protected Service\Persona $personaService,
protected Repository\Persona $personaRepository, protected Unidad $unidadRepository)
{
parent::__construct($connection);
@@ -30,31 +32,67 @@ class Factura extends Ideal\Repository
->register('cliente_rut', (new Implement\Repository\Mapper())
->setProperty('cliente')
->setFunction(function($data) {
- return $this->personaRepository->fetchById($data['cliente_rut']);
+ return $this->personaService->getById($data['cliente_rut']);
}));
$factura = $this->parseData(new Model\Venta\Factura(), $data, $map);
- return $this->createDatos($factura);
+ return $this->createDatos($factura, $data);
}
- public function createDatos(Model\Venta\Factura &$factura): Model\Venta\Factura
+ public function createDatos(Model\Venta\Factura &$factura, ?array $data = null): Model\Venta\Factura
{
try {
$result = $this->getDatos($factura->venta->id);
- $factura->fecha = new DateTimeImmutable($result['fecha']);
- $factura->uf = json_decode($result['uf']);
- $factura->uf->fecha = new DateTimeImmutable($factura->uf->fecha);
- $factura->ipc = json_decode($result['ipc']);
- $factura->ipc->fecha = new DateTimeImmutable($factura->ipc->fecha);
- $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']));
- $factura->terreno = $result['terreno'];
- } catch (EmptyResult) {}
+ 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;
}
@@ -93,20 +131,27 @@ class Factura extends Ideal\Repository
$query = $this->connection->getQueryBuilder()
->insert()
->into('venta_datos_facturas')
+ ->columns([
+ 'venta_id',
+ 'fecha',
+ 'unidades',
+ 'terreno',
+ 'uf',
+ 'ipc'
+ ])
->values([
'venta_id' => $factura->venta->id,
- 'index' => $factura->index,
- 'proporcion' => $factura->proporcion,
- 'unidades' => json_encode(array_map(function($unidad) {
+ '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)),
- 'terreno' => $factura->terreno,
- 'uf' => json_encode($factura->uf),
- 'ipc' => json_encode($factura->ipc)
+ }, $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);
}
diff --git a/app/src/Service/Persona.php b/app/src/Service/Persona.php
index fabc9da..39733a6 100644
--- a/app/src/Service/Persona.php
+++ b/app/src/Service/Persona.php
@@ -11,7 +11,8 @@ class Persona extends Ideal\Service
{
public function __construct(LoggerInterface $logger,
protected Repository\Persona $personaRepository,
- protected Repository\Persona\Datos $datosPersonaRepository)
+ protected Repository\Persona\Datos $datosPersonaRepository,
+ protected Repository\Venta\Propietario $propietarioRepository)
{
parent::__construct($logger);
}
@@ -25,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 8f5bc4b..e5bcc84 100644
--- a/app/src/Service/Venta/Factura.php
+++ b/app/src/Service/Venta/Factura.php
@@ -64,7 +64,8 @@ class Factura extends Ideal\Service
$client = $this->personaService->add($data['cliente']);
$data['cliente_rut'] = $client->rut;
unset($data['cliente']);
- $factura = $this->facturaRepository->save($this->facturaRepository->create($data));
+ $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,