Agregar datos propietario

This commit is contained in:
Juan Pablo Vial
2025-05-15 15:23:34 -04:00
parent e33edc4d7b
commit 03317b3aa5
10 changed files with 441 additions and 132 deletions

View File

@ -153,7 +153,7 @@
@include('layout.body.scripts.rut') @include('layout.body.scripts.rut')
@push('page_scripts') @push('page_scripts')
<script type="text/javascript"> <script>
const regiones = [ const regiones = [
@foreach ($regiones as $region) @foreach ($regiones as $region)
'<div class="item" data-value="{{$region->id}}">{{$region->descripcion}}</div>', '<div class="item" data-value="{{$region->id}}">{{$region->descripcion}}</div>',
@ -354,56 +354,65 @@
const lines = [ const lines = [
'<label for="rut">RUT</label>', '<label for="rut">RUT</label>',
'<div class="inline field">', '<div class="inline field">',
'<input type="text" id="rut" name="rut" placeholder="00000000-0" required />', '<input type="text" id="rut" name="rut" placeholder="00000000-0" required />',
'<span class="ui error message" id="alert_rut">', '<span class="ui error message" id="alert_rut">',
'<i class="exclamation triangle icon"></i>', '<i class="exclamation triangle icon"></i>',
'RUT Inválido', 'RUT Inválido',
'</span>', '</span>',
'</div>', '</div>',
'<label for="nombres">Nombre</label>', '<label for="nombres">Nombre</label>',
'<div class="inline fields">', '<div class="inline fields">',
'<div class="field">', '<div class="field">',
'<input type="text" name="nombres" id="nombres" placeholder="Nombre(s)" required />', '<input type="text" name="nombres" id="nombres" placeholder="Nombre(s)" required />',
'</div>', '</div>',
'<div class="field">', '<div class="field">',
'<input type="text" name="apellido_paterno" placeholder="Apellido Paterno" required />', '<input type="text" name="apellido_paterno" placeholder="Apellido Paterno" required />',
'</div>', '</div>',
'<div class="field">', '<div class="field">',
'<input type="text" name="apellido_materno" placeholder="Apellido Materno" required />', '<input type="text" name="apellido_materno" placeholder="Apellido Materno" required />',
'</div>', '</div>',
'</div>', '</div>',
'<label for="calle">Dirección</label>', '<label for="calle">Dirección</label>',
'<div class="inline fields">', '<div class="inline fields">',
'<div class="eight wide field">', '<div class="eight wide field">',
'<input type="text" name="calle" id="calle" size="16" placeholder="Calle" required />', '<input type="text" name="calle" id="calle" size="16" placeholder="Calle" required />',
'</div>', '</div>',
'<div class="field">', '<div class="field">',
'<input type="text" name="numero" size="5" placeholder="Número" required />', '<input type="text" name="numero" size="5" placeholder="Número" required />',
'</div>', '</div>',
'<div class="field">', '<div class="field">',
'<input type="text" name="extra" placeholder="Otros Detalles" />', '<input type="text" name="extra" placeholder="Otros Detalles" />',
'</div>', '</div>',
'</div>', '</div>',
'<div class="inline fields">', '<div class="inline fields">',
'<div class="two wide field"></div>', '<div class="two wide field"></div>',
'<div class="four wide field">', '<div class="four wide field">',
'<div class="ui fluid search selection dropdown" id="comuna">', '<div class="ui fluid search selection dropdown" id="comuna">',
'<input type="hidden" name="comuna" />', '<input type="hidden" name="comuna" />',
'<i class="dropdown icon"></i>', '<i class="dropdown icon"></i>',
'<div class="default text">Comuna</div>', '<div class="default text">Comuna</div>',
'<div class="menu"></div>', '<div class="menu"></div>',
'</div>', '</div>',
'</div>', '</div>',
'<div class="six wide field">', '<div class="six wide field">',
'<div class="ui fluid search selection dropdown" id="region">', '<div class="ui fluid search selection dropdown" id="region">',
'<input type="hidden" name="region" />', '<input type="hidden" name="region" />',
'<i class="dropdown icon"></i>', '<i class="dropdown icon"></i>',
'<div class="default text">Región</div>', '<div class="default text">Región</div>',
'<div class="menu">', '<div class="menu">',
...regiones, ...regiones,
'</div>', '</div>',
'</div>', '</div>',
'</div>',
'</div>', '</div>',
'<label>Otros Datos</label>',
'<div class="inline fields">',
'<div class="four wide field">',
'<input type="email" name="email" placeholder="Email" />',
'</div>',
'<div class="field">',
'<input type="text" name="telefono" placeholder="Teléfono" />',
'</div>',
'</div>' '</div>'
] ]
return lines.join("\n") return lines.join("\n")
@ -467,8 +476,10 @@
'</div>', '</div>',
'</div>', '</div>',
'<div>Representante Legal</div>', '<div>Representante Legal</div>',
'<div class="ui divider"></div>',
this.persona.draw()
] ]
return [lines.join("\n"), this.persona.draw()].join("\n") return lines.join("\n")
} }
activate() { activate() {
new RutHandler({id: '#rut_sociedad', alert_id: '#alert_rut_sociedad'}) new RutHandler({id: '#rut_sociedad', alert_id: '#alert_rut_sociedad'})
@ -486,6 +497,7 @@
draw() { draw() {
let lines = [ let lines = [
this.persona.draw(), this.persona.draw(),
'<div class="ui divider"></div>',
'<label for="rut">RUT Otro</label>', '<label for="rut">RUT Otro</label>',
'<div class="inline field">', '<div class="inline field">',
'<input type="text" id="rut_otro" name="rut_otro" required />', '<input type="text" id="rut_otro" name="rut_otro" required />',
@ -538,6 +550,15 @@
'</div>', '</div>',
'</div>', '</div>',
'</div>', '</div>',
'</div>',
'<label>Otros Datos para Otro</label>',
'<div class="inline fields">',
'<div class="four wide field">',
'<input type="email" name="email_otro" placeholder="Email" />',
'</div>',
'<div class="field">',
'<input type="text" name="telefono_otro" placeholder="Teléfono" />',
'</div>',
'</div>' '</div>'
] ]
return lines.join("\n") return lines.join("\n")
@ -607,6 +628,8 @@
parent.find("[name='extra']").val(data.propietario.direccion.extra) parent.find("[name='extra']").val(data.propietario.direccion.extra)
parent.find('#region').dropdown('set selected', data.propietario.direccion.comuna.provincia.region.id) parent.find('#region').dropdown('set selected', data.propietario.direccion.comuna.provincia.region.id)
parent.find('#comuna').dropdown('set selected', data.propietario.direccion.comuna.id) parent.find('#comuna').dropdown('set selected', data.propietario.direccion.comuna.id)
parent.find("[name='email']").val(data.propietario.email)
parent.find("[name='telefono']").val(data.propietario.telefono)
if (data.propietario.representante !== '') { if (data.propietario.representante !== '') {
document.getElementById(this.ids.tipo).trigger('check') document.getElementById(this.ids.tipo).trigger('check')

View File

@ -58,7 +58,17 @@ Editar Propietario
<select class="ui search selection dropdown" name="comuna" id="comunas"></select> <select class="ui search selection dropdown" name="comuna" id="comunas"></select>
</div> </div>
</div> </div>
<button class="ui button" id="guardar_button">Guardar</button> <div class="fields">
<div class="four wide field">
<label>Email</label>
<input type="email" name="email" value="{{$propietario->datos?->email}}" />
</div>
<div class="field">
<label>Teléfono</label>
<input type="text" name="telefono" value="{{$propietario->datos?->telefono}}" />
</div>
</div>
<button type="button" class="ui button" id="guardar_button">Guardar</button>
</form> </form>
</div> </div>
@endsection @endsection
@ -66,10 +76,10 @@ Editar Propietario
@include('layout.body.scripts.rut') @include('layout.body.scripts.rut')
@push('page_scripts') @push('page_scripts')
<script type="text/javascript"> <script>
class Propietario { class Propietario {
props props
constructor({rut, digito, nombres, apellidos: {paterno, materno}, direccion: {calle, numero, extra, comuna, region}}) { constructor({rut, digito, nombres, apellidos: {paterno, materno}, direccion: {calle, numero, extra, comuna, region}, email, telefono}) {
this.props = { this.props = {
rut, rut,
digito, digito,
@ -85,6 +95,8 @@ Editar Propietario
comuna, comuna,
region region
}, },
email,
telefono
} }
} }
@ -128,6 +140,12 @@ Editar Propietario
this.props.direccion.region = region this.props.direccion.region = region
} }
} }
},
email: email => {
this.props.email = email
},
telefono: telefono => {
this.props.telefono = telefono
} }
} }
} }
@ -145,7 +163,9 @@ Editar Propietario
numero: '{{$propietario->datos->direccion->numero}}', numero: '{{$propietario->datos->direccion->numero}}',
extra: '{{trim($propietario->datos->direccion->extra)}}', extra: '{{trim($propietario->datos->direccion->extra)}}',
comuna: '{{$propietario->datos->direccion->comuna->id}}' comuna: '{{$propietario->datos->direccion->comuna->id}}'
} },
email: '{{trim($propietario->datos?->email)}}',
telefono: '{{trim($propietario->datos?->telefono)}}'
} }
const data = {} const data = {}
const collator = new Intl.Collator('es') const collator = new Intl.Collator('es')
@ -299,6 +319,16 @@ Editar Propietario
propietario.props.data.update().direccion().comuna(comuna_id) propietario.props.data.update().direccion().comuna(comuna_id)
}) })
} }
static email() {
$("[name='email']").change(event => {
propietario.props.data.update().email(event.currentTarget.value)
})
}
static telefono() {
$("[name='telefono']").change(event => {
propietario.props.data.update().telefono($(event.currentTarget).val())
})
}
static run() { static run() {
Watcher.rut() Watcher.rut()
@ -307,6 +337,8 @@ Editar Propietario
Watcher.direccion() Watcher.direccion()
Watcher.region() Watcher.region()
Watcher.comuna() Watcher.comuna()
Watcher.email()
Watcher.telefono()
} }
} }
class EventHandler { class EventHandler {
@ -381,6 +413,8 @@ Editar Propietario
$("[name='numero']").val(this.props.data.props.direccion.numero) $("[name='numero']").val(this.props.data.props.direccion.numero)
$("[name='extra']").val(this.props.data.props.direccion.extra) $("[name='extra']").val(this.props.data.props.direccion.extra)
$('#region').val(this.props.data.props.direccion.region) $('#region').val(this.props.data.props.direccion.region)
$("[name='email']").val(this.props.data.props.email)
$("[name='telefono']").val(this.props.data.props.telefono)
this.update().region() this.update().region()
}, },
region: () => { region: () => {
@ -422,6 +456,8 @@ Editar Propietario
this.props.data.update().direccion().extra(data.propietario.direccion.extra) this.props.data.update().direccion().extra(data.propietario.direccion.extra)
this.props.data.update().direccion().comuna(data.propietario.direccion.comuna.id) this.props.data.update().direccion().comuna(data.propietario.direccion.comuna.id)
this.props.data.update().direccion().region(data.propietario.direccion.comuna.provincia.region.id) this.props.data.update().direccion().region(data.propietario.direccion.comuna.provincia.region.id)
this.props.data.update().email(data.propietario.email)
this.props.data.update().telefono(data.propietario.telefono)
this.update().propietario() this.update().propietario()
}) })
}) })
@ -476,6 +512,8 @@ Editar Propietario
$("[name='calle']").val('') $("[name='calle']").val('')
$("[name='numero']").val('') $("[name='numero']").val('')
$("[name='extra']").val('') $("[name='extra']").val('')
$("[name='email']").val('')
$("[name='telefono']").val('')
} }
} }
}, },
@ -498,7 +536,8 @@ Editar Propietario
}) })
this.update().region() this.update().region()
$(this.props.ids.forms.edit).submit(Form.submit) document.getElementById(this.props.ids.forms.edit.replace('#', '')).addEventListener('submit', Form.submit)
document.getElementById(this.props.ids.buttons.guardar.replace('#', '')).addEventListener('click', Form.submit)
Watcher.run() Watcher.run()
} }
} }
@ -529,7 +568,9 @@ Editar Propietario
extra: '{{$propietario->datos->direccion->extra}}', extra: '{{$propietario->datos->direccion->extra}}',
comuna: '{{$propietario->datos->direccion->comuna->id}}', comuna: '{{$propietario->datos->direccion->comuna->id}}',
region: '{{$propietario->datos->direccion->comuna->provincia->region->id}}', region: '{{$propietario->datos->direccion->comuna->provincia->region->id}}',
} },
email: '{{$propietario->datos?->email}}',
telefono: '{{$propietario->datos?->telefono}}'
}) })
}) })
}) })

View File

@ -10,6 +10,8 @@ use Incoviba\Common\Implement\Exception\EmptyRedis;
use Incoviba\Common\Implement\Exception\EmptyResult; use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Controller\withRedis; use Incoviba\Controller\withRedis;
use Incoviba\Exception\ServiceAction\Read; use Incoviba\Exception\ServiceAction\Read;
use Incoviba\Exception\ServiceAction\Create;
use Incoviba\Exception\ServiceAction\Update;
use Incoviba\Model; use Incoviba\Model;
use Incoviba\Repository; use Incoviba\Repository;
use Incoviba\Service; use Incoviba\Service;
@ -334,7 +336,7 @@ class Ventas extends Controller
$propietario = $propietarioService->edit($propietario, $data); $propietario = $propietarioService->edit($propietario, $data);
} }
$output['edited'] = true; $output['edited'] = true;
} catch (EmptyResult) {} } catch (EmptyResult|Read|Create|Update) {}
return $this->withJson($response, $output); return $this->withJson($response, $output);
} }

View File

@ -63,24 +63,31 @@ class Propietario extends Ideal\Repository
return $data['otro'] !== 0; return $data['otro'] !== 0;
}) })
->setDefault(null)); ->setDefault(null));
return $this->parseData(new Model\Venta\Propietario(), $data, $map); $model = $this->parseData(new Model\Venta\Propietario(), $data, $map);
if (array_key_exists('email', $data)) {
$model->datos->email = $data['email'];
}
if (array_key_exists('telefono', $data)) {
$model->datos->telefono = $data['telefono'];
}
return $model;
} }
public function save(Define\Model $model): Define\Model public function save(Define\Model $model): Define\Model
{ {
$this->saveNew( $this->saveNew(
['rut', 'dv', 'nombres', 'apellido_paterno', 'apellido_materno', 'direccion', 'otro', 'representante'], ['rut', 'dv', 'nombres', 'apellido_paterno', 'apellido_materno', 'direccion', 'email', 'telefono', 'otro', 'representante'],
[$model->rut, $model->dv, $model->nombres, $model->apellidos['paterno'], $model->apellidos['materno'], $model->datos->direccion->id, $model->otro->rut ?? 0, $model->contacto->rut ?? 0] [$model->rut, $model->dv, $model->nombres, $model->apellidos['paterno'], $model->apellidos['materno'], $model->datos?->direccion->id, $model->datos?->email, $model->datos?->telefono, $model->otro->rut ?? 0, $model->contacto->rut ?? 0]
); );
return $model; return $model;
} }
public function edit(Define\Model $model, array $new_data): Define\Model public function edit(Define\Model $model, array $new_data): Define\Model
{ {
return $this->update($model, ['dv', 'nombres', 'apellido_paterno', 'apellido_materno', 'direccion', 'otro', 'representante'], $new_data); return $this->update($model, ['dv', 'nombres', 'apellido_paterno', 'apellido_materno', 'direccion', 'email', 'telefono', 'otro', 'representante'], $new_data);
} }
public function filterData(array $data): array public function filterData(array $data): array
{ {
return array_intersect_key($data, array_flip(['rut', 'dv', 'nombres', 'apellido_paterno', 'apellido_materno', 'direccion', 'representante'])); return array_intersect_key($data, array_flip(['rut', 'dv', 'nombres', 'apellido_paterno', 'apellido_materno', 'direccion', 'email', 'telefono', 'otro', 'representante']));
} }
} }

View File

@ -4,7 +4,8 @@ namespace Incoviba\Service;
use Exception; use Exception;
use DateTimeImmutable; use DateTimeImmutable;
use DateMalformedStringException; use DateMalformedStringException;
use Incoviba\Exception\ServiceAction\{Read, Update}; use Incoviba\Exception\ServiceAction\{Create, Read, Update};
use PDOException;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use Incoviba\Common\Ideal\Service; use Incoviba\Common\Ideal\Service;
use Incoviba\Common\Implement; use Incoviba\Common\Implement;
@ -225,15 +226,24 @@ class Venta extends Service
} }
/** /**
* @throws Exception * @throws Create|Update
*/ */
public function add(array $data): Model\Venta public function add(array $data): Model\Venta
{ {
$fecha = new DateTimeImmutable($data['fecha_venta']); try {
$fecha = new DateTimeImmutable($data['fecha_venta']);
} catch (DateMalformedStringException $exception) {
throw new Create(__CLASS__, $exception);
}
$data['uf'] = $this->ufService->get($fecha); $data['uf'] = $this->ufService->get($fecha);
$propietario = $this->addPropietario($data); $propietario = $this->addPropietario($data);
$propiedad = $this->addPropiedad($data); $propiedad = $this->addPropiedad($data);
$formaPago = $this->addFormaPago($data);
try {
$formaPago = $this->addFormaPago($data);
} catch (Create) {}
$venta_data = [ $venta_data = [
'propietario' => $propietario->rut, 'propietario' => $propietario->rut,
'propiedad' => $propiedad->id, 'propiedad' => $propiedad->id,
@ -242,31 +252,46 @@ class Venta extends Service
'fecha_ingreso' => (new DateTimeImmutable())->format('Y-m-d'), 'fecha_ingreso' => (new DateTimeImmutable())->format('Y-m-d'),
'uf' => $data['uf'] 'uf' => $data['uf']
]; ];
$map = ['pie', 'subsidio', 'credito', 'bono_pie'];
foreach ($map as $field) { if (isset($formaPago)) {
$name = lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', $field)))); $map = ['pie', 'subsidio', 'credito', 'bono_pie'];
if (isset($formaPago->{$name})) { foreach ($map as $field) {
$venta_data[$field] = $formaPago->{$name}->id; $name = lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', $field))));
if (isset($formaPago->{$name})) {
$venta_data[$field] = $formaPago->{$name}->id;
}
} }
} }
try { try {
return $this->ventaRepository->fetchByPropietarioAndPropiedad($propietario->rut, $propiedad->id); return $this->ventaRepository->fetchByPropietarioAndPropiedad($propietario->rut, $propiedad->id);
} catch (Implement\Exception\EmptyResult) { } catch (Implement\Exception\EmptyResult) {
$venta = $this->ventaRepository->create($venta_data); $venta = $this->ventaRepository->create($venta_data);
$venta->setFormaPago($formaPago); if (isset($formaPago)) {
$venta->setFormaPago($formaPago);
}
$venta = $this->ventaRepository->save($venta); $venta = $this->ventaRepository->save($venta);
$tipoEstado = $this->tipoEstadoVentaRepository->fetchByDescripcion('vigente'); try {
$estado = $this->estadoVentaRepository->create([ $tipoEstado = $this->tipoEstadoVentaRepository->fetchByDescripcion('vigente');
'venta' => $venta->id, try {
'estado' => $tipoEstado->id, $estado = $this->estadoVentaRepository->create([
'fecha' => $venta->fecha->format('Y-m-d') 'venta' => $venta->id,
]); 'estado' => $tipoEstado->id,
$this->estadoVentaRepository->save($estado); 'fecha' => $venta->fecha->format('Y-m-d')
]);
$this->estadoVentaRepository->save($estado);
} catch (PDOException) {}
} catch (Implement\Exception\EmptyResult) {}
return $venta; return $venta;
} }
} }
/**
* @param array $data
* @return Model\Venta\Propietario
* @throws Create|Update
*/
protected function addPropietario(array $data): Model\Venta\Propietario protected function addPropietario(array $data): Model\Venta\Propietario
{ {
if (isset($data['natural_uno'])) { if (isset($data['natural_uno'])) {
@ -277,9 +302,15 @@ class Venta extends Service
} }
return $this->addSociedad($data); return $this->addSociedad($data);
} }
/**
* @param array $data
* @return Model\Venta\Propietario
* @throws Create
*/
protected function addUnPropietario(array $data): Model\Venta\Propietario protected function addUnPropietario(array $data): Model\Venta\Propietario
{ {
$fields = array_fill_keys([ $fields = array_flip([
'rut', 'rut',
'nombres', 'nombres',
'apellido_paterno', 'apellido_paterno',
@ -287,14 +318,22 @@ class Venta extends Service
'calle', 'calle',
'numero', 'numero',
'extra', 'extra',
'comuna' 'comuna',
], 0); 'email',
'telefono'
]);
$filtered_data = array_intersect_key($data, $fields); $filtered_data = array_intersect_key($data, $fields);
return $this->propietarioService->addPropietario($filtered_data); return $this->propietarioService->addPropietario($filtered_data);
} }
/**
* @param array $data
* @return Model\Venta\Propietario
* @throws Create
*/
protected function addDosPropietarios(array $data): Model\Venta\Propietario protected function addDosPropietarios(array $data): Model\Venta\Propietario
{ {
$fields = array_fill_keys([ $fields = array_flip([
'rut_otro', 'rut_otro',
'nombres_otro', 'nombres_otro',
'apellido_paterno_otro', 'apellido_paterno_otro',
@ -302,8 +341,10 @@ class Venta extends Service
'calle_otro', 'calle_otro',
'numero_otro', 'numero_otro',
'extra_otro', 'extra_otro',
'comuna_otro' 'comuna_otro',
], 0); 'email_otro',
'telefono_otro'
]);
$filtered_data = array_intersect_key($data, $fields); $filtered_data = array_intersect_key($data, $fields);
$mapped_data = array_combine([ $mapped_data = array_combine([
'rut', 'rut',
@ -313,12 +354,14 @@ class Venta extends Service
'calle', 'calle',
'numero', 'numero',
'extra', 'extra',
'comuna' 'comuna',
'email',
'telefono'
], $filtered_data); ], $filtered_data);
$otro = $this->propietarioService->addPropietario($mapped_data); $otro = $this->propietarioService->addPropietario($mapped_data);
$data['otro'] = $otro->rut; $data['otro'] = $otro->rut;
$fields = array_fill_keys([ $fields = array_flip([
'rut', 'rut',
'nombres', 'nombres',
'apellido_paterno', 'apellido_paterno',
@ -327,17 +370,26 @@ class Venta extends Service
'numero', 'numero',
'extra', 'extra',
'comuna', 'comuna',
'otro' 'otro',
], 0); 'email',
'telefono'
]);
$filtered_data = array_intersect_key($data, $fields); $filtered_data = array_intersect_key($data, $fields);
return $this->propietarioService->addPropietario($filtered_data); return $this->propietarioService->addPropietario($filtered_data);
} }
/**
* @param array $data
* @return Model\Venta\Propietario
* @throws Create
* @throws Update
*/
protected function addSociedad(array $data): Model\Venta\Propietario protected function addSociedad(array $data): Model\Venta\Propietario
{ {
$representante = $this->addUnPropietario($data); $representante = $this->addUnPropietario($data);
$data['representante'] = $representante->rut; $data['representante'] = $representante->rut;
$fields = array_fill_keys([ $fields = array_flip([
'rut_sociedad', 'rut_sociedad',
'razon_social', 'razon_social',
'calle_comercial', 'calle_comercial',
@ -345,7 +397,7 @@ class Venta extends Service
'extra_comercial', 'extra_comercial',
'comuna_comercial', 'comuna_comercial',
'representante' 'representante'
], 0); ]);
$filtered_data = array_intersect_key($data, $fields); $filtered_data = array_intersect_key($data, $fields);
$mapped_data = array_combine([ $mapped_data = array_combine([
'rut', 'rut',
@ -358,6 +410,12 @@ class Venta extends Service
], $filtered_data); ], $filtered_data);
return $this->propietarioService->addSociedad($mapped_data); return $this->propietarioService->addSociedad($mapped_data);
} }
/**
* @param array $data
* @return Model\Venta\Propiedad
* @throws Create
*/
protected function addPropiedad(array $data): Model\Venta\Propiedad protected function addPropiedad(array $data): Model\Venta\Propiedad
{ {
$ids = array_filter($data, function($key) { $ids = array_filter($data, function($key) {
@ -366,6 +424,12 @@ class Venta extends Service
return $this->propiedadService->addPropiedad($ids); return $this->propiedadService->addPropiedad($ids);
} }
/**
* @param array $data
* @return Model\Venta\FormaPago
* @throws Create
*/
protected function addFormaPago(array $data): Model\Venta\FormaPago protected function addFormaPago(array $data): Model\Venta\FormaPago
{ {
return $this->formaPagoService->add($data); return $this->formaPagoService->add($data);

View File

@ -1,12 +1,15 @@
<?php <?php
namespace Incoviba\Service\Venta; namespace Incoviba\Service\Venta;
use DateMalformedStringException;
use Exception; use Exception;
use DateTimeImmutable; use DateTimeImmutable;
use Incoviba\Common\Implement\Exception\EmptyResult; use PDOException;
use Incoviba\Exception\ServiceAction\Read;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use Incoviba\Common\Ideal; use Incoviba\Common\Ideal;
use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Exception\ServiceAction\Create;
use Incoviba\Exception\ServiceAction\Read;
use Incoviba\Repository; use Incoviba\Repository;
use Incoviba\Model; use Incoviba\Model;
use Incoviba\Service; use Incoviba\Service;
@ -41,13 +44,23 @@ class Credito extends Ideal\Service
} }
/** /**
* @throws Exception * @param array $data
* @return Model\Venta\Credito
* @throws Create
*/ */
public function add(array $data): Model\Venta\Credito public function add(array $data): Model\Venta\Credito
{ {
$fecha = new DateTimeImmutable($data['fecha']); try {
$fecha = new DateTimeImmutable($data['fecha']);
} catch (DateMalformedStringException) {
$fecha = new DateTimeImmutable();
}
$uf = $this->valorService->clean($data['uf']) ?? $this->moneyService->getUF($fecha); $uf = $this->valorService->clean($data['uf']) ?? $this->moneyService->getUF($fecha);
$tipoPago = $this->tipoPagoRepository->fetchByDescripcion('carta de resguardo'); try {
$tipoPago = $this->tipoPagoRepository->fetchByDescripcion('carta de resguardo');
} catch (EmptyResult $exception) {
throw new Create(__CLASS__, $exception);
}
$valor = $this->valorService->clean($data['valor']); $valor = $this->valorService->clean($data['valor']);
$pago = $this->pagoService->add([ $pago = $this->pagoService->add([
'fecha' => $fecha->format('Y-m-d'), 'fecha' => $fecha->format('Y-m-d'),
@ -55,12 +68,20 @@ class Credito extends Ideal\Service
'uf' => $uf, 'uf' => $uf,
'tipo' => $tipoPago->id 'tipo' => $tipoPago->id
]); ]);
$credito = $this->creditoRepository->create([ try {
'valor' => $valor, $credito = $this->creditoRepository->create([
'fecha' => $fecha->format('Y-m-d'), 'valor' => $valor,
'pago' => $pago->id 'fecha' => $fecha->format('Y-m-d'),
]); 'pago' => $pago->id
return $this->creditoRepository->save($credito); ]);
} catch (EmptyResult $exception) {
throw new Create(__CLASS__, $exception);
}
try {
return $this->creditoRepository->save($credito);
} catch (PDOException $exception) {
throw new Create(__CLASS__, $exception);
}
} }
/** /**

View File

@ -2,10 +2,12 @@
namespace Incoviba\Service\Venta; namespace Incoviba\Service\Venta;
use Error; use Error;
use Incoviba\Exception\ServiceAction\Read; use Exception;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use Incoviba\Common\Implement; use Incoviba\Common\Implement;
use Incoviba\Common\Ideal; use Incoviba\Common\Ideal;
use Incoviba\Exception\ServiceAction\Create;
use Incoviba\Exception\ServiceAction\Read;
use Incoviba\Model; use Incoviba\Model;
use Incoviba\Repository; use Incoviba\Repository;
use Incoviba\Service\Valor; use Incoviba\Service\Valor;
@ -53,6 +55,10 @@ class FormaPago extends Ideal\Service
return $formaPago; return $formaPago;
} }
/**
* @param array $data
* @return Model\Venta\FormaPago
*/
public function add(array $data): Model\Venta\FormaPago public function add(array $data): Model\Venta\FormaPago
{ {
$fields = [ $fields = [
@ -68,6 +74,9 @@ class FormaPago extends Ideal\Service
$method = 'add' . str_replace(' ', '', ucwords(str_replace('_', ' ', $name))); $method = 'add' . str_replace(' ', '', ucwords(str_replace('_', ' ', $name)));
$obj = $this->{$method}($data); $obj = $this->{$method}($data);
$forma_pago->{$name} = $obj; $forma_pago->{$name} = $obj;
} catch (Create $exception) {
$this->logger->warning($exception);
continue;
} catch (Error $error) { } catch (Error $error) {
$this->logger->critical($error); $this->logger->critical($error);
} }
@ -76,14 +85,19 @@ class FormaPago extends Ideal\Service
return $forma_pago; return $forma_pago;
} }
/**
* @param array $data
* @return Model\Venta\Pie
* @throws Create
*/
protected function addPie(array $data): Model\Venta\Pie protected function addPie(array $data): Model\Venta\Pie
{ {
$fields = array_fill_keys([ $fields = array_flip([
'fecha_venta', 'fecha_venta',
'pie', 'pie',
'cuotas', 'cuotas',
'uf' 'uf'
], 0); ]);
$filtered_data = array_intersect_key($data, $fields); $filtered_data = array_intersect_key($data, $fields);
$mapped_data = array_combine([ $mapped_data = array_combine([
'fecha', 'fecha',
@ -94,14 +108,20 @@ class FormaPago extends Ideal\Service
$mapped_data['valor'] = $this->valorService->clean($mapped_data['valor']); $mapped_data['valor'] = $this->valorService->clean($mapped_data['valor']);
return $this->pieService->add($mapped_data); return $this->pieService->add($mapped_data);
} }
/**
* @param array $data
* @return Model\Venta\Subsidio
* @throws Create
*/
protected function addSubsidio(array $data): Model\Venta\Subsidio protected function addSubsidio(array $data): Model\Venta\Subsidio
{ {
$fields = array_fill_keys([ $fields = array_flip([
'fecha_venta', 'fecha_venta',
'ahorro', 'ahorro',
'subsidio', 'subsidio',
'uf' 'uf'
], 0); ]);
$filtered_data = array_intersect_key($data, $fields); $filtered_data = array_intersect_key($data, $fields);
$mapped_data = array_combine([ $mapped_data = array_combine([
'fecha', 'fecha',
@ -113,13 +133,19 @@ class FormaPago extends Ideal\Service
$mapped_data['subsidio'] = $this->valorService->clean($mapped_data['subsidio']); $mapped_data['subsidio'] = $this->valorService->clean($mapped_data['subsidio']);
return $this->subsidioService->add($mapped_data); return $this->subsidioService->add($mapped_data);
} }
/**
* @param array $data
* @return Model\Venta\Credito
* @throws Create
*/
protected function addCredito(array $data): Model\Venta\Credito protected function addCredito(array $data): Model\Venta\Credito
{ {
$fields = array_fill_keys([ $fields = array_flip([
'fecha_venta', 'fecha_venta',
'credito', 'credito',
'uf' 'uf'
], 0); ]);
$filtered_data = array_intersect_key($data, $fields); $filtered_data = array_intersect_key($data, $fields);
$mapped_data = array_combine([ $mapped_data = array_combine([
'fecha', 'fecha',
@ -129,12 +155,18 @@ class FormaPago extends Ideal\Service
$mapped_data['valor'] = $this->valorService->clean($mapped_data['valor']); $mapped_data['valor'] = $this->valorService->clean($mapped_data['valor']);
return $this->creditoService->add($mapped_data); return $this->creditoService->add($mapped_data);
} }
/**
* @param array $data
* @return Model\Venta\BonoPie
* @throws Create
*/
protected function addBonoPie(array $data): Model\Venta\BonoPie protected function addBonoPie(array $data): Model\Venta\BonoPie
{ {
$fields = array_fill_keys([ $fields = array_flip([
'fecha_venta', 'fecha_venta',
'bono_pie' 'bono_pie'
], 0); ]);
$filtered_data = array_intersect_key($data, $fields); $filtered_data = array_intersect_key($data, $fields);
$mapped_data = array_combine([ $mapped_data = array_combine([
'fecha', 'fecha',

View File

@ -49,11 +49,21 @@ class Propiedad extends Service
throw new Exception\ServiceAction\Read(__CLASS__, $exception); throw new Exception\ServiceAction\Read(__CLASS__, $exception);
} }
} }
/**
* @param array $ids
* @return Model\Venta\Propiedad
* @throws Exception\ServiceAction\Create
*/
public function addPropiedad(array $ids): Model\Venta\Propiedad public function addPropiedad(array $ids): Model\Venta\Propiedad
{ {
$unidades = []; $unidades = [];
foreach ($ids as $unidad_id) { foreach ($ids as $unidad_id) {
$unidades []= $this->unidadRepository->fetchById($unidad_id); try {
$unidades []= $this->unidadRepository->fetchById($unidad_id);
} catch (EmptyResult $exception) {
$this->logger->warning($exception);
}
} }
usort($unidades, function(Model\Venta\Unidad $a, Model\Venta\Unidad $b) { usort($unidades, function(Model\Venta\Unidad $a, Model\Venta\Unidad $b) {
$t = $a->proyectoTipoUnidad->tipoUnidad->orden - $b->proyectoTipoUnidad->tipoUnidad->orden; $t = $a->proyectoTipoUnidad->tipoUnidad->orden - $b->proyectoTipoUnidad->tipoUnidad->orden;
@ -70,13 +80,25 @@ class Propiedad extends Service
'unidad_principal' => $unidades[0]->id, 'unidad_principal' => $unidades[0]->id,
'estado' => 1 'estado' => 1
]); ]);
$propiedad = $this->propiedadRepository->save($propiedad); try {
$propiedad = $this->propiedadRepository->save($propiedad);
} catch (PDOException $exception) {
throw new Exception\ServiceAction\Create(__CLASS__, $exception);
}
} }
$this->addUnidades($propiedad, $unidades); $this->addUnidades($propiedad, $unidades);
$this->cleanUpUnidades($propiedad, $unidades); try {
$this->cleanUpUnidades($propiedad, $unidades);
} catch (Exception\ServiceAction\Read|Exception\ServiceAction\Delete) {}
return $propiedad; return $propiedad;
} }
/**
* @param Model\Venta\Propiedad $propiedad
* @param array $unidades
* @return void
*/
protected function addUnidades(Model\Venta\Propiedad $propiedad, array $unidades): void protected function addUnidades(Model\Venta\Propiedad $propiedad, array $unidades): void
{ {
$query = "SELECT 1 FROM `propiedad_unidad` WHERE `propiedad` = ? AND `unidad` = ?"; $query = "SELECT 1 FROM `propiedad_unidad` WHERE `propiedad` = ? AND `unidad` = ?";
@ -91,19 +113,33 @@ class Propiedad extends Service
throw new EmptyResult($query); throw new EmptyResult($query);
} }
} catch (PDOException|EmptyResult) { } catch (PDOException|EmptyResult) {
$insert->execute([$propiedad->id, $unidad->id, ($ix === 0) ? 1 : 0]); try {
$insert->execute([$propiedad->id, $unidad->id, ($ix === 0) ? 1 : 0]);
} catch (PDOException) {}
} }
} }
} }
/**
* @param Model\Venta\Propiedad $propiedad
* @param array $unidades
* @return void
* @throws Exception\ServiceAction\Delete
* @throws Exception\ServiceAction\Read
*/
protected function cleanUpUnidades(Model\Venta\Propiedad $propiedad, array $unidades): void protected function cleanUpUnidades(Model\Venta\Propiedad $propiedad, array $unidades): void
{ {
$query = "SELECT `unidad` FROM `propiedad_unidad` WHERE `propiedad` = ?"; $query = "SELECT `unidad` FROM `propiedad_unidad` WHERE `propiedad` = ?";
$statement = $this->connection->prepare($query); try {
$statement->execute([$propiedad->id]); $statement = $this->connection->prepare($query);
$results = $statement->fetchAll(PDO::FETCH_ASSOC); $statement->execute([$propiedad->id]);
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $exception) {
throw new Exception\ServiceAction\Read(__CLASS__, $exception);
}
if (!$results) { if (!$results) {
return; throw new Exception\ServiceAction\Read(__CLASS__);
} }
$all_ids = array_map(function($row) {return $row['unidad'];}, $results); $all_ids = array_map(function($row) {return $row['unidad'];}, $results);
@ -113,9 +149,15 @@ class Propiedad extends Service
return; return;
} }
$query = "DELETE FROM `propiedad_unidad` WHERE `propiedad` = ? AND `unidad` = ?"; $query = "DELETE FROM `propiedad_unidad` WHERE `propiedad` = ? AND `unidad` = ?";
$statement = $this->connection->prepare($query); try {
$statement = $this->connection->prepare($query);
} catch (PDOException $exception) {
throw new Exception\ServiceAction\Delete(__CLASS__, $exception);
}
foreach ($diff as $id) { foreach ($diff as $id) {
$statement->execute([$propiedad->id, $id]); try {
$statement->execute([$propiedad->id, $id]);
} catch (PDOException) {}
} }
} }
protected function process(Model\Venta\Propiedad $propiedad): Model\Venta\Propiedad protected function process(Model\Venta\Propiedad $propiedad): Model\Venta\Propiedad

View File

@ -3,8 +3,12 @@ namespace Incoviba\Service\Venta;
use Incoviba\Common\Ideal\Service; use Incoviba\Common\Ideal\Service;
use Incoviba\Common\Implement\Exception\EmptyResult; use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Exception\ServiceAction\Create;
use Incoviba\Exception\ServiceAction\Read;
use Incoviba\Exception\ServiceAction\Update;
use Incoviba\Repository; use Incoviba\Repository;
use Incoviba\Model; use Incoviba\Model;
use PDOException;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
class Propietario extends Service class Propietario extends Service
@ -17,10 +21,27 @@ class Propietario extends Service
parent::__construct($logger); parent::__construct($logger);
} }
/**
* @param int $rut
* @return Model\Venta\Propietario
* @throws Read
*/
public function getByRut(int $rut): Model\Venta\Propietario public function getByRut(int $rut): Model\Venta\Propietario
{ {
return $this->propietarioRepository->fetchById($rut); try {
return $this->propietarioRepository->fetchById($rut);
} catch (EmptyResult $exception) {
throw new Read(__CLASS__, $exception);
}
} }
/**
* @param Model\Venta\Propietario $propietario
* @param array $data
* @return Model\Venta\Propietario
* @throws Create
* @throws Update
*/
public function edit(Model\Venta\Propietario $propietario, array $data): Model\Venta\Propietario public function edit(Model\Venta\Propietario $propietario, array $data): Model\Venta\Propietario
{ {
if (isset($data['calle']) or isset($data['numero']) or isset($data['extra']) or isset($data['comuna'])) { if (isset($data['calle']) or isset($data['numero']) or isset($data['extra']) or isset($data['comuna'])) {
@ -28,8 +49,18 @@ class Propietario extends Service
$data['direccion'] = $direccion->id; $data['direccion'] = $direccion->id;
} }
$filteredData = $this->propietarioRepository->filterData($data); $filteredData = $this->propietarioRepository->filterData($data);
return $this->propietarioRepository->edit($propietario, $filteredData); try {
return $this->propietarioRepository->edit($propietario, $filteredData);
} catch (PDOException | EmptyResult $exception) {
throw new Update(__CLASS__, $exception);
}
} }
/**
* @param array $data
* @return Model\Venta\Propietario
* @throws Create
*/
public function addPropietario(array $data): Model\Venta\Propietario public function addPropietario(array $data): Model\Venta\Propietario
{ {
$direccion = $this->addDireccion($data); $direccion = $this->addDireccion($data);
@ -42,14 +73,16 @@ class Propietario extends Service
$data['dv'] = $dv; $data['dv'] = $dv;
} }
$fields = array_fill_keys([ $fields = array_flip([
'rut', 'rut',
'dv', 'dv',
'nombres', 'nombres',
'apellido_paterno', 'apellido_paterno',
'apellido_materno', 'apellido_materno',
'direccion' 'direccion',
], 0); 'email',
'telefono'
]);
$filtered_data = array_intersect_key($data, $fields); $filtered_data = array_intersect_key($data, $fields);
try { try {
@ -60,11 +93,22 @@ class Propietario extends Service
} }
$propietario = $this->propietarioRepository->edit($propietario, $edits); $propietario = $this->propietarioRepository->edit($propietario, $edits);
} catch (EmptyResult) { } catch (EmptyResult) {
$propietario = $this->propietarioRepository->create($filtered_data); try {
$propietario = $this->propietarioRepository->save($propietario); $propietario = $this->propietarioRepository->create($filtered_data);
$propietario = $this->propietarioRepository->save($propietario);
} catch (PDOException $exception) {
throw new Create(__CLASS__, $exception);
}
} }
return $propietario; return $propietario;
} }
/**
* @param array $data
* @return Model\Venta\Propietario
* @throws Create
* @throws Update
*/
public function addSociedad(array $data): Model\Venta\Propietario public function addSociedad(array $data): Model\Venta\Propietario
{ {
$direccion = $this->addDireccion($data); $direccion = $this->addDireccion($data);
@ -74,12 +118,12 @@ class Propietario extends Service
$data['rut'] = explode('-', $data['rut'])[0]; $data['rut'] = explode('-', $data['rut'])[0];
} }
$fields = array_fill_keys([ $fields = array_flip([
'rut', 'rut',
'razon_social', 'razon_social',
'direccion', 'direccion',
'representante' 'representante'
], 0); ]);
$filtered_data = array_intersect_key($data, $fields); $filtered_data = array_intersect_key($data, $fields);
$mapped_data = array_combine([ $mapped_data = array_combine([
'rut', 'rut',
@ -97,27 +141,45 @@ class Propietario extends Service
if ($sociedad->contacto->rut !== $mapped_data['representante']) { if ($sociedad->contacto->rut !== $mapped_data['representante']) {
$edits['representante'] = $mapped_data['representante']; $edits['representante'] = $mapped_data['representante'];
} }
$sociedad = $this->propietarioRepository->edit($sociedad, $edits); try {
$sociedad = $this->propietarioRepository->edit($sociedad, $edits);
} catch (PDOException $exception) {
throw new Update(__CLASS__, $exception);
}
} catch (EmptyResult) { } catch (EmptyResult) {
$sociedad = $this->propietarioRepository->create($mapped_data); try {
$sociedad = $this->propietarioRepository->save($sociedad); $sociedad = $this->propietarioRepository->create($mapped_data);
$sociedad = $this->propietarioRepository->save($sociedad);
} catch (PDOException $exception) {
throw new Create(__CLASS__, $exception);
}
} }
return $sociedad; return $sociedad;
} }
/**
* @param array $data
* @return Model\Direccion
* @throws Create
*/
protected function addDireccion(array $data): Model\Direccion protected function addDireccion(array $data): Model\Direccion
{ {
$fields = array_fill_keys([ $fields = array_flip([
'calle', 'calle',
'numero', 'numero',
'extra', 'extra',
'comuna' 'comuna'
], 0); ]);
$filtered_data = array_intersect_key($data, $fields); $filtered_data = array_intersect_key($data, $fields);
try { try {
$direccion = $this->direccionRepository->fetchByCalleAndNumeroAndExtraAndComuna($filtered_data['calle'], $filtered_data['numero'], $filtered_data['extra'], $filtered_data['comuna']); $direccion = $this->direccionRepository->fetchByCalleAndNumeroAndExtraAndComuna($filtered_data['calle'], $filtered_data['numero'], $filtered_data['extra'], $filtered_data['comuna']);
} catch (EmptyResult) { } catch (EmptyResult) {
$direccion = $this->direccionRepository->create($filtered_data); try {
$direccion = $this->direccionRepository->save($direccion); $direccion = $this->direccionRepository->create($filtered_data);
$direccion = $this->direccionRepository->save($direccion);
} catch (PDOException $exception) {
throw new Create(__CLASS__, $exception);
}
} }
return $direccion; return $direccion;
} }

View File

@ -3,7 +3,9 @@ namespace Incoviba\Service\Venta;
use DateTimeImmutable; use DateTimeImmutable;
use DateMalformedStringException; use DateMalformedStringException;
use PDOException;
use Incoviba\Common\Implement\Exception\EmptyResult; use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Exception\ServiceAction\Create;
use Incoviba\Exception\ServiceAction\Read; use Incoviba\Exception\ServiceAction\Read;
use Incoviba\Repository; use Incoviba\Repository;
use Incoviba\Model; use Incoviba\Model;
@ -35,6 +37,11 @@ class Subsidio
} }
} }
/**
* @param array $data
* @return Model\Venta\Subsidio
* @throws Create
*/
public function add(array $data): Model\Venta\Subsidio public function add(array $data): Model\Venta\Subsidio
{ {
$fecha = new DateTimeImmutable(); $fecha = new DateTimeImmutable();
@ -42,10 +49,18 @@ class Subsidio
$fecha = new DateTimeImmutable($data['fecha']); $fecha = new DateTimeImmutable($data['fecha']);
} catch (DateMalformedStringException) {} } catch (DateMalformedStringException) {}
$uf = $data['uf'] ?? $this->moneyService->getUF($fecha); $uf = $data['uf'] ?? $this->moneyService->getUF($fecha);
$tipoPago = $this->tipoPagoRepository->fetchByDescripcion('vale vista'); try {
$tipoPago = $this->tipoPagoRepository->fetchByDescripcion('vale vista');
} catch (EmptyResult $exception) {
throw new Create(__CLASS__, $exception);
}
$ahorro = $this->pagoService->add(['fecha' => $fecha->format('Y-m-d'), 'valor' => $this->valorService->clean($data['ahorro']) * $uf, 'uf' => $uf, 'tipo' => $tipoPago->id]); $ahorro = $this->pagoService->add(['fecha' => $fecha->format('Y-m-d'), 'valor' => $this->valorService->clean($data['ahorro']) * $uf, 'uf' => $uf, 'tipo' => $tipoPago->id]);
$subsidioPago = $this->pagoService->add(['fecha' => $fecha->format('Y-m-d'), 'valor' => $this->valorService->clean($data['subsidio']) * $uf, 'uf' => $uf, 'tipo' => $tipoPago->id]); $subsidioPago = $this->pagoService->add(['fecha' => $fecha->format('Y-m-d'), 'valor' => $this->valorService->clean($data['subsidio']) * $uf, 'uf' => $uf, 'tipo' => $tipoPago->id]);
$subsidio = $this->subsidioRepository->create(['pago' => $ahorro->id, 'subsidio' => $subsidioPago->id]); $subsidio = $this->subsidioRepository->create(['pago' => $ahorro->id, 'subsidio' => $subsidioPago->id]);
return $this->subsidioRepository->save($subsidio); try {
return $this->subsidioRepository->save($subsidio);
} catch (PDOException $exception) {
throw new Create(__CLASS__, $exception);
}
} }
} }