Guardar factura

This commit is contained in:
Juan Pablo Vial
2025-02-03 22:17:57 -03:00
parent 71615050f3
commit 59a28a353b
11 changed files with 296 additions and 122 deletions

View File

@ -41,13 +41,18 @@
}, },
facturas: () => { facturas: () => {
document.getElementById(this.ids.facturas).innerHTML = this.venta.draw().facturas(this.formatters) document.getElementById(this.ids.facturas).innerHTML = this.venta.draw().facturas(this.formatters)
$('button.guardar').click(clickEvent => { this.venta.watch().facturas()
const index = clickEvent.currentTarget.getAttribute('data-index')
facturas.venta.save().factura({index: index-1})
})
} }
} }
}, },
proporcion() {
if (this.venta.props.facturas.facturas.length === 0) {
return 1
}
return this.venta.props.facturas.facturas.reduce((sum, factura) => {
return sum + factura.props.proporcion
}, 0)
},
setup({ids}) { setup({ids}) {
this.ids = ids this.ids = ids
this.venta = new Venta({ this.venta = new Venta({
@ -77,7 +82,7 @@
new Unidad({ new Unidad({
id: {{$unidad->id}}, id: {{$unidad->id}},
tipo: '{{ucwords($unidad->proyectoTipoUnidad->tipoUnidad->descripcion)}}', tipo: '{{ucwords($unidad->proyectoTipoUnidad->tipoUnidad->descripcion)}}',
descripcion: '{{$unidad->descripcion}}', descripcion: '{{ucwords($unidad->proyectoTipoUnidad->tipoUnidad->descripcion)}} {{ $unidad->descripcion }} (UF {{ number_format($unidad->precio($venta->currentEstado()->fecha)->valor, 2) }})',
prorrateo: {{$unidad->prorrateo}}, prorrateo: {{$unidad->prorrateo}},
propiedad_unidad_id: {{$unidad->pu_id}}, propiedad_unidad_id: {{$unidad->pu_id}},
valor: {{($unidad->valor > 0) ? $unidad->valor : $unidad->precio($venta->currentEstado()->fecha)->valor}} valor: {{($unidad->valor > 0) ? $unidad->valor : $unidad->precio($venta->currentEstado()->fecha)->valor}}
@ -98,23 +103,100 @@
}) })
@if (count($facturas) > 0) @if (count($facturas) > 0)
this.venta.props.uf = { this.venta.props.uf = {
fecha: new Date('{{$facturas[0]->fechaUF->format('Y-m-d')}}'), fecha: new Date('{{$facturas[0]->uf->fecha->format('Y-m-d')}}'),
valor: {{$facturas[0]->valorUF}} valor: {{$facturas[0]->uf->valor}}
} }
@foreach ($facturas as $factura) @foreach ($facturas as $factura)
this.venta.props.facturas[{{$factura->index-1}}] = new Factura(JSON.parse('{!! json_encode($factura) !!}')) this.venta.props.facturas.facturas[{{$factura->index - 1}}] = new Factura({
this.venta.props.facturas[{{$factura->index-1}}].props.saved = true id: {{ $factura->id }},
this.venta.props.propietarios[{{$factura->index-1}}] = new Propietario({ venta: this.venta.props,
index: {{$factura->index}},
fecha: new Date('{{$factura->fecha->format('Y-m-d')}}'),
proporcion: {{$factura->proporcion}},
emisor: {
rut: '{{$factura->venta->proyecto()->inmobiliaria()->rut}}',
nombre: '{{$factura->venta->proyecto()->inmobiliaria()->razon}}',
direccion: '{{$factura->venta->proyecto()->direccion()->simple()}}',
comuna: '{{$factura->venta->proyecto()->direccion()->comuna->id}}',
},
receptor: {
rut: '{{$factura->cliente->rutCompleto()}}',
nombre: '{{$factura->cliente->nombreCompleto()}}',
direccion: '{{$factura->cliente->datos()->direccion->simple()}}',
comuna: '{{$factura->cliente->datos()->direccion->comuna->id}}',
},
terreno: {
@if ($terreno->fecha != null) fecha: new Date('{{$terreno->fecha->add(new DateInterval('P1D'))->format('Y-m-d')}}'),
@else fecha: null,
@endif
valor: {{ $factura->terreno}}
},
unidades: [
@foreach ($factura->unidades as $unidad)
{
unidad: new Unidad({
id: {{$unidad->unidad->id}},
tipo: '{{ucwords($unidad->unidad->proyectoTipoUnidad->tipoUnidad->descripcion)}}',
descripcion: '{{ucwords($unidad->unidad->proyectoTipoUnidad->tipoUnidad->descripcion)}} {{ $unidad->unidad->descripcion }} (UF {{ number_format(array_values(array_filter($venta->propiedad()->unidades, function($uni) use ($unidad, $factura) {return $uni->id === $unidad->unidad->id;}))[0]->precio($venta->currentEstado()->fecha)->valor * $factura->proporcion, 2) }})',
prorrateo: {{$unidad->prorrateo}},
propiedad_unidad_id: {{ array_values(array_filter($venta->propiedad()->unidades, function($uni) use ($unidad) {return $uni->id === $unidad->unidad->id;}))[0]->pu_id }},
valor: {{$unidad->precio}}
}),
descripcion: '{{ucwords($unidad->unidad->proyectoTipoUnidad->tipoUnidad->descripcion)}} {{ $unidad->unidad->descripcion }} (UF {{ number_format(array_values(array_filter($venta->propiedad()->unidades, function($uni) use ($unidad, $factura) {return $uni->id === $unidad->unidad->id;}))[0]->precio($venta->currentEstado()->fecha)->valor * $factura->proporcion, 2) }})',
precio: {{ $unidad->precio }},
prorrateo: {{ $unidad->prorrateo }},
},
@endforeach
],
detalle: {
base: {{ $factura->base() }},
terreno: {{ $factura->terreno * $factura->proporcion }},
neto: {{ $factura->neto() }},
iva: {{ $factura->iva() }},
bruto: {{ $factura->bruto() }},
total: {{ $factura->total() }},
descuento: {{ array_reduce($factura->unidades, function($sum, $unidad) use ($factura) { return $sum + $unidad->prorrateo * $factura->proporcion; }, 0) }}
},
total: {
neto: {{ array_reduce($factura->unidades, function($sum, $unidad) {return $sum + $unidad->precio * $factura->proporcion;}, 0) }},
exento: {{ $factura->terreno * $factura->proporcion }},
iva: {{ $factura->iva() }},
total: {{ $factura->total() }}
},
saved: true,
uf: {
fecha: new Date('{{$factura->uf->fecha->format('Y-m-d')}}'),
valor: {{$factura->uf->valor}}
}
})
this.venta.props.facturas.facturas[{{$factura->index - 1}}].props.saved = true
this.venta.props.propietarios[{{$factura->index - 1}}] = new Propietario({
index: {{$factura->index}}, index: {{$factura->index}},
proporcion: {{$factura->proporcion}}, proporcion: {{$factura->proporcion}},
rut: '{{$factura->receptorRut}}', rut: '{{$factura->cliente->rutCompleto()}}',
nombre: '{{$factura->receptorNombre}}', nombre: '{{$factura->cliente->nombreCompleto()}}',
direccion: '{{$factura->receptorDireccion}}', direccion: '{{$factura->cliente->datos()->direccion->simple()}}',
comuna: '{{$factura->receptorComuna}}', comuna: '{{$factura->cliente->datos()->direccion->comuna->id}}',
fecha: new Date('{{$factura->fecha->format('Y-m-d')}}'), fecha: new Date('{{$factura->fecha->format('Y-m-d')}}'),
}) })
@endforeach @endforeach
@else this.draw().venta()
if (this.proporcion() < 1) {
const p = 1 - this.proporcion()
const propietario = this.venta.add().propietario({
rut: '',
nombre: '',
proporcion: (p*100).toFixed(0)/100,
direccion: '',
comuna: '0'
})
document.getElementById('propietarios').innerHTML = this.venta.draw().propietarios()
document.getElementById('cantidad_propietarios').value = this.venta.props.propietarios.length
this.venta.add().factura(propietario)
this.draw().facturas()
}
@else
const propietario = this.venta.add().propietario({ const propietario = this.venta.add().propietario({
proporcion: 1, proporcion: 1,
rut: '{{$venta->propietario()->rut()}}', rut: '{{$venta->propietario()->rut()}}',
@ -122,11 +204,11 @@
direccion: '{{$venta->propietario()->datos->direccion->simple()}}', direccion: '{{$venta->propietario()->datos->direccion->simple()}}',
comuna: '{{$venta->propietario()->datos->direccion->comuna->id}}' comuna: '{{$venta->propietario()->datos->direccion->comuna->id}}'
}) })
this.draw().venta()
if (typeof propietario !== 'undefined') {
this.venta.add().factura(propietario)
}
@endif @endif
this.draw().venta()
if (typeof propietario !== 'undefined') {
this.venta.add().factura(propietario)
}
this.draw().facturas() this.draw().facturas()
} }
} }

View File

@ -89,11 +89,11 @@
rut: () => { rut: () => {
return [ return [
'<div class="four wide column">', '<div class="four wide column">',
'<div class="ui center aligned red segment">', '<div class="ui center aligned orange segment">',
'<strong>', '<strong>',
`RUT:${this.props.emisor.rut.toUpperCase()}<br/>`, `RUT:${this.props.emisor.rut.toUpperCase()}<br/>`,
'FACTURA ELECTRÓNICA<br/>', 'FACTURA ELECTRÓNICA<br/>',
`N° #${this.props.venta.id}${this.props.index}`, `<span class="ui red text">N° ${this.props.venta.id}${this.props.index}</span>`,
'</strong>', '</strong>',
'</div>', '</div>',
'</div>' '</div>'
@ -128,34 +128,34 @@
table: ({formatters}) => { table: ({formatters}) => {
return [ return [
'<div class="row">', '<div class="row">',
'<table class="ui celled table">', '<table class="ui celled table">',
'<thead>', '<thead>',
'<tr class="grey">', '<tr class="grey">',
'<th class="center aligned" colspan="6">DETALLES</th>', '<th class="center aligned" colspan="6">DETALLES</th>',
'</tr>', '</tr>',
'<tr class="grey">', '<tr class="grey">',
'<th>N°</th>', '<th>N°</th>',
'<th class="center aligned">Descripción</th>', '<th class="center aligned">Descripción</th>',
'<th class="center aligned">Cant/Unidad</th>', '<th class="center aligned">Cant/Unidad</th>',
'<th class="center aligned">Prec. Unit.</th>', '<th class="center aligned">Prec. Unit.</th>',
'<th class="center aligned">Ind</th>', '<th class="center aligned">Ind</th>',
'<th class="center aligned">Total</th>', '<th class="center aligned">Total</th>',
'</tr>', '</tr>',
'</thead>', '</thead>',
'<tbody>', '<tbody>',
this.draw().unidades({formatters}), this.draw().unidades({formatters}),
'</tbody>', '</tbody>',
'<tfoot>', '<tfoot>',
'<tr>', '<tr>',
'<td colspan="6">', '<td colspan="6">',
'<br />', '<br />',
'<br />', '<br />',
'<br />', '<br />',
'<br />', '<br />',
'</td>', '</td>',
'</tr>', '</tr>',
'</tfoot>', '</tfoot>',
'</table>', '</table>',
'</div>' '</div>'
].join("\n") ].join("\n")
}, },
@ -279,7 +279,7 @@
'<div class="row">', '<div class="row">',
'<div class="fourteen wide column"></div>', '<div class="fourteen wide column"></div>',
'<div class="two wide center aligned column">', '<div class="two wide center aligned column">',
'<div class="ui green message">', `<div class="ui green message guardar" data-index="${this.props.index}">`,
'<i class="check icon"></i>', '<i class="check icon"></i>',
'Guardada', 'Guardada',
'</div>', '</div>',
@ -300,14 +300,30 @@
watch() { watch() {
return { return {
save: () => { 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') 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() { save() {
if (!this.validate()) {
return
}
let url = '{{$urls->api}}/ventas/facturas/add' let url = '{{$urls->api}}/ventas/facturas/add'
if (this.saved) { if (this.saved) {
url = `{{$urls->api}}/ventas/facturas/${this.props.id}/edit` url = `{{$urls->api}}/ventas/facturas/${this.props.id}/edit`
@ -326,6 +342,7 @@
body.set('detalle', JSON.stringify(this.props.detalle)) body.set('detalle', JSON.stringify(this.props.detalle))
body.set('total', JSON.stringify(this.props.total)) 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})) 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 => { return APIClient.fetch(url, {method, body}).then(response => {
if (!response) { if (!response) {
return return
@ -366,7 +383,7 @@
unidades.forEach(unidad => { unidades.forEach(unidad => {
this.props.unidades.push({ this.props.unidades.push({
unidad: unidad, 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, precio: unidad.props.valor * this.props.uf.valor * this.props.proporcion,
prorrateo: unidad.props.prorrateo * this.props.proporcion prorrateo: unidad.props.prorrateo * this.props.proporcion
}) })
@ -376,10 +393,10 @@
this.props.proporcion = propietario.props.proporcion this.props.proporcion = propietario.props.proporcion
this.props.receptor = { this.props.receptor = {
rut: propietario.props.rut, rut: propietario.props.rut ?? '',
nombre: propietario.props.nombre, nombre: propietario.props.nombre ?? '',
direccion: propietario.props.direccion, direccion: propietario.props.direccion ?? '',
comuna: propietario.comuna comuna: propietario.comuna ?? ''
} }
} }
} }

View File

@ -14,7 +14,11 @@
} }
get comuna() { 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() { update() {
return { return {

View File

@ -13,8 +13,8 @@
this.props = props this.props = props
} }
descripcion(proporcion = 1) { changeDescripcion(proporcion = 1) {
return [this.props.tipo, this.props.descripcion, `[UF ${facturas.formatters.ufs.format(this.props.valor * proporcion)}]`].join(' ') return this.descripcion = [this.props.tipo, this.props.descripcion, `[UF ${facturas.formatters.ufs.format(this.props.valor * proporcion)}]`].join(' ')
} }
update() { update() {
return { return {

View File

@ -252,6 +252,11 @@
this.props.propietarios.forEach(propietario => { this.props.propietarios.forEach(propietario => {
propietario.watch().propietario() propietario.watch().propietario()
}) })
},
facturas: () => {
this.props.facturas.facturas.forEach(factura => {
factura.watch().save()
})
} }
} }
} }
@ -267,11 +272,11 @@
value: ufFormatter => { value: ufFormatter => {
return [ return [
'<div class="ui grid">', '<div class="ui grid">',
'<div class="three wide column">', '<div class="three wide column">',
'<div class="ui very segment">', '<div class="ui very segment">',
'Valor Venta: UF ' + ufFormatter.format(this.props.valor), 'Valor Venta: UF ' + ufFormatter.format(this.props.valor),
'</div>', '</div>',
'</div>', '</div>',
'</div>' '</div>'
].join("\n") ].join("\n")
}, },
@ -377,7 +382,7 @@
}, },
facturas: formatters => { facturas: formatters => {
const output = [] const output = []
this.props.facturas.facturas.forEach((factura, index) => { this.props.facturas.facturas.forEach(factura => {
output.push(factura.draw().factura({formatters})) output.push(factura.draw().factura({formatters}))
}) })
return output.join("\n") return output.join("\n")
@ -405,10 +410,10 @@
comuna: this.props.inmobiliaria.comuna comuna: this.props.inmobiliaria.comuna
}, },
receptor: { receptor: {
rut: '', rut: propietario.props.rut ?? '',
nombre: '', nombre: propietario.props.nombre ?? '',
direccion: '', direccion: propietario.props.direccion ?? '',
comuna: '' comuna: propietario.props.comuna ?? ''
}, },
unidades: [], unidades: [],
detalle: { detalle: {

View File

@ -21,12 +21,13 @@ class Facturas extends Controller
'success' => false 'success' => false
]; ];
try { 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])) { if (!isset($data[$key]) or empty($data[$key])) {
continue; continue;
} }
$data[$key] = json_decode($data[$key], true); $data[$key] = json_decode($data[$key], true);
} }*/
$data['cliente'] = json_decode($data['cliente'], true);
$output['factura'] = $facturaService->add($data); $output['factura'] = $facturaService->add($data);
$output['success'] = true; $output['success'] = true;
} catch (Implement\Exception\EmptyResult) { } catch (Implement\Exception\EmptyResult) {

View File

@ -13,11 +13,11 @@ class Factura extends Ideal\Model
public float $proporcion; public float $proporcion;
public Model\Persona $cliente; public Model\Persona $cliente;
public DateTimeInterface $fecha; public ?DateTimeInterface $fecha = null;
public array $unidades; // [[unidad, descripcion, precio, prorrateo]] public ?array $unidades = null; // [[unidad, descripcion, precio, prorrateo]]
public int $terreno; public ?int $terreno = null;
public object $uf; // [fecha, valor] public ?object $uf = null; // [fecha, valor]
public object $ipc; // [fecha, valor] public ?object $ipc = null; // [fecha, valor]
protected array $estados; protected array $estados;
public function estados(): array public function estados(): array
@ -28,23 +28,23 @@ class Factura extends Ideal\Model
return $this->estados ?? []; return $this->estados ?? [];
} }
public function total(): int public function total(): float
{ {
return $this->venta->valor * $this->uf->valor * $this->proporcion; return $this->venta->valor * $this->uf->valor * $this->proporcion;
} }
public function bruto(): int public function bruto(): float
{ {
return $this->total() - $this->terreno * $this->proporcion; return $this->total() - $this->terreno * $this->proporcion;
} }
public function iva(): int public function iva(): float
{ {
return $this->neto() * .19; return $this->neto() * .19;
} }
public function neto(): int public function neto(): float
{ {
return $this->bruto() / 1.19; return $this->bruto() / 1.19;
} }
public function base(): int public function base(): float
{ {
return $this->neto() + $this->terreno * $this->proporcion; return $this->neto() + $this->terreno * $this->proporcion;
} }
@ -59,7 +59,7 @@ class Factura extends Ideal\Model
'total' => $this->total(), 'total' => $this->total(),
'descuento' => array_reduce($this->unidades, function($sum, $unidad) { 'descuento' => array_reduce($this->unidades, function($sum, $unidad) {
return $sum + $unidad->prorrateo * $this->proporcion; return $sum + $unidad->prorrateo * $this->proporcion;
}) }, 0)
]; ];
} }
public function totales(): array public function totales(): array
@ -89,18 +89,17 @@ class Factura extends Ideal\Model
'receptor' => [ 'receptor' => [
'rut' => $this->cliente->rutCompleto(), 'rut' => $this->cliente->rutCompleto(),
'nombre' => $this->cliente->nombreCompleto(), 'nombre' => $this->cliente->nombreCompleto(),
'direccion' => $this->cliente->datos()->direccion->simple(), 'direccion' => $this->cliente->datos()->direccion?->simple(),
'comuna' => $this->cliente->datos()->direccion->comuna->descripcion 'comuna' => $this->cliente->datos()->direccion?->comuna->descripcion
], ],
'fecha' => $this->fecha->format('Y-m-d'), 'fecha' => $this->fecha?->format('Y-m-d'),
'unidades' => $this->unidades, 'unidades' => $this->unidades,
'detalle' => $this->detalle(), 'detalle' => $this->detalle(),
'total' => $this->totales(), 'total' => $this->totales(),
'uf' => [ 'uf' => [
'fecha' => $this->uf->fecha->format('Y-m-d'), 'fecha' => $this->uf?->fecha->format('Y-m-d'),
'valor' => $this->uf->valor 'valor' => $this->uf?->valor
], ],
'estados' => $this->estados()
]); ]);
} }

View File

@ -9,10 +9,12 @@ use Incoviba\Common\Implement;
use Incoviba\Common\Implement\Exception\EmptyResult; use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Model; use Incoviba\Model;
use Incoviba\Repository; use Incoviba\Repository;
use Incoviba\Service;
class Factura extends Ideal\Repository class Factura extends Ideal\Repository
{ {
public function __construct(Implement\Connection $connection, protected Repository\Venta $ventaRepository, public function __construct(Implement\Connection $connection, protected Repository\Venta $ventaRepository,
protected Service\Persona $personaService,
protected Repository\Persona $personaRepository, protected Unidad $unidadRepository) protected Repository\Persona $personaRepository, protected Unidad $unidadRepository)
{ {
parent::__construct($connection); parent::__construct($connection);
@ -30,31 +32,67 @@ class Factura extends Ideal\Repository
->register('cliente_rut', (new Implement\Repository\Mapper()) ->register('cliente_rut', (new Implement\Repository\Mapper())
->setProperty('cliente') ->setProperty('cliente')
->setFunction(function($data) { ->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); $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 { try {
$result = $this->getDatos($factura->venta->id); $result = $this->getDatos($factura->venta->id);
$factura->fecha = new DateTimeImmutable($result['fecha']); if ($result['fecha'] !== null) {
$factura->uf = json_decode($result['uf']); $factura->fecha = new DateTimeImmutable($result['fecha']);
$factura->uf->fecha = new DateTimeImmutable($factura->uf->fecha); }
$factura->ipc = json_decode($result['ipc']); if ($result['uf'] !== null) {
$factura->ipc->fecha = new DateTimeImmutable($factura->ipc->fecha); $factura->uf = json_decode($result['uf']);
$factura->unidades = array_map(function($datos) use ($factura) { $factura->uf->fecha = new DateTimeImmutable($factura->uf->fecha);
$unidad = $this->unidadRepository->fetchById($datos->unidad_id); }
return (object) [ if ($result['ipc'] !== null) {
'unidad' => $unidad, $factura->ipc = json_decode($result['ipc']);
'descripcion' => implode(' ', [ucwords($unidad->proyectoTipoUnidad->tipoUnidad->descripcion), $unidad->descripcion]), $factura->ipc->fecha = new DateTimeImmutable($factura->ipc->fecha);
'precio' => $datos->precio, }
'prorrateo' => $datos->prorrateo if ($result['unidades'] !== null) {
]; $factura->unidades = array_map(function($datos) use ($factura) {
}, json_decode($result['unidades'])); $unidad = $this->unidadRepository->fetchById($datos->unidad_id);
$factura->terreno = $result['terreno']; return (object) [
} catch (EmptyResult) {} '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; return $factura;
} }
@ -93,20 +131,27 @@ class Factura extends Ideal\Repository
$query = $this->connection->getQueryBuilder() $query = $this->connection->getQueryBuilder()
->insert() ->insert()
->into('venta_datos_facturas') ->into('venta_datos_facturas')
->columns([
'venta_id',
'fecha',
'unidades',
'terreno',
'uf',
'ipc'
])
->values([ ->values([
'venta_id' => $factura->venta->id, 'venta_id' => $factura->venta->id,
'index' => $factura->index, 'fecha' => $factura->fecha?->format('Y-m-d'),
'proporcion' => $factura->proporcion, 'unidades' => (isset($factura->unidades)) ? json_encode(array_map(function($unidad) {
'unidades' => json_encode(array_map(function($unidad) {
return [ return [
'unidad_id' => $unidad->unidad->id, 'unidad_id' => $unidad->unidad->id,
'precio' => $unidad->precio, 'precio' => $unidad->precio,
'prorrateo' => $unidad->prorrateo 'prorrateo' => $unidad->prorrateo
]; ];
}, $factura->unidades)), }, $factura?->unidades)) : null,
'terreno' => $factura->terreno, 'terreno' => $factura?->terreno,
'uf' => json_encode($factura->uf), 'uf' => (isset($factura->uf)) ? json_encode(['fecha' => $factura->uf?->fecha->format('Y-m-d'), 'valor' => $factura->uf?->valor]) : null,
'ipc' => json_encode($factura->ipc) 'ipc' => (isset($factura->ipc)) ? json_encode(['fecha' => $factura->ipc?->fecha->format('Y-m-d'), 'valor' => $factura->ipc?->valor]) : null
]); ]);
$this->connection->execute($query); $this->connection->execute($query);
} }

View File

@ -11,7 +11,8 @@ class Persona extends Ideal\Service
{ {
public function __construct(LoggerInterface $logger, public function __construct(LoggerInterface $logger,
protected Repository\Persona $personaRepository, protected Repository\Persona $personaRepository,
protected Repository\Persona\Datos $datosPersonaRepository) protected Repository\Persona\Datos $datosPersonaRepository,
protected Repository\Venta\Propietario $propietarioRepository)
{ {
parent::__construct($logger); parent::__construct($logger);
} }
@ -25,11 +26,21 @@ class Persona extends Ideal\Service
try { try {
$persona = $this->personaRepository->fetchById($data['rut']); $persona = $this->personaRepository->fetchById($data['rut']);
} catch (Implement\Exception\EmptyResult) { } 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->create($data);
$persona = $this->personaRepository->save($persona); $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]; $datosData = ['persona_rut' => $persona->rut];
if (isset($data['direccion_id'])) {
$datosData['direccion_id'] = $data['direccion_id'];
}
if (isset($data['email'])) { if (isset($data['email'])) {
$datosData['email'] = $data['email']; $datosData['email'] = $data['email'];
} }

View File

@ -3,6 +3,7 @@ namespace Incoviba\Service;
use Predis\ClientInterface; use Predis\ClientInterface;
use Incoviba\Common\Implement\Exception\EmptyRedis; use Incoviba\Common\Implement\Exception\EmptyRedis;
use Predis\Connection\ConnectionException;
class Redis class Redis
{ {
@ -10,13 +11,21 @@ class Redis
public function get(string $name): mixed public function get(string $name): mixed
{ {
if (!$this->client->exists($name)) { try {
throw new EmptyRedis($name); 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 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;
}
} }
} }

View File

@ -64,7 +64,8 @@ class Factura extends Ideal\Service
$client = $this->personaService->add($data['cliente']); $client = $this->personaService->add($data['cliente']);
$data['cliente_rut'] = $client->rut; $data['cliente_rut'] = $client->rut;
unset($data['cliente']); 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'); $tipo = $this->tipoRepository->fetchByDescripcion('generada');
$this->estadoRepository->save($this->estadoRepository->create([ $this->estadoRepository->save($this->estadoRepository->create([
'factura_id' => $factura->id, 'factura_id' => $factura->id,