Agregar Proveedor

This commit is contained in:
Juan Pablo Vial
2024-12-03 16:45:20 -03:00
parent 5b44260245
commit 42e1dcdff7
19 changed files with 473 additions and 283 deletions

View File

@ -34,7 +34,7 @@ abstract class Repository implements Define\Repository
$query = $this->connection->getQueryBuilder()
->delete()->from($this->getTable())
->where("{$this->getKey()} = ?");
$this->connection->execute($query, [$model->id]);
$this->connection->execute($query, [$model->{$this->getKey()}]);
}
/**

View File

@ -1,11 +1,12 @@
<?php
use Incoviba\Controller\API\Inmobiliarias\Agentes;
use Incoviba\Controller\API\Inmobiliarias\Proveedores;
$app->group('/proveedores', function($app) {
$app->post('/add[/]', [Agentes::class, 'add']);
$app->post('/register[/]', [Agentes::class, 'register']);
$app->get('[/]', Agentes::class);
$app->post('/add[/]', [Proveedores::class, 'add']);
//$app->post('/register[/]', [Proveedores::class, 'register']);
$app->get('[/]', Proveedores::class);
});
$app->group('/proveedor/{agente_id}', function($app) {
$app->post('/edit[/]', [Agentes::class, 'edit']);
$app->group('/proveedor/{proveedor_rut:[0-9]+}', function($app) {
$app->post('/edit[/]', [Proveedores::class, 'edit']);
$app->delete('/delete[/]', [Proveedores::class, 'delete']);
});

View File

@ -8,7 +8,7 @@
<th>Nombre</th>
<th>Contacto</th>
<th class="right aligned">
<button class="ui green icon button" id="add_button">
<button class="ui tertiary green icon button" id="add_button">
<i class="plus icon"></i>
</button>
</th>
@ -20,10 +20,10 @@
<td>{{$proveedor->nombre}}</td>
<td>{{$proveedor->contacto->nombreCompleto()}}</td>
<td class="right aligned">
<button class="ui icon button" data-sociedad="{{$proveedor->rut}}">
<button class="ui tertiary icon button" data-proveedor="{{$proveedor->rut}}">
<i class="edit icon"></i>
</button>
<button class="ui red icon button" data-sociedad="{{$proveedor->rut}}">
<button class="ui tertiary red icon button" data-proveedor="{{$proveedor->rut}}">
<i class="remove icon"></i>
</button>
</td>
@ -32,74 +32,16 @@
</tbody>
</table>
</div>
<div class="ui modal" id="add_modal">
<div class="content">
<form class="ui form">
<div class="three wide field">
<label for="rut">RUT</label>
<div class="ui right labeled input">
<input class="right aligned" type="text" id="rut" name="rut" placeholder="RUT" maxlength="10"
required/>
<div class="ui basic label">-<span id="dv"></span></div>
</div>
</div>
<div class="five wide field">
<label for="nombre">Nombre</label>
<input type="text" id="nombre" name="nombre" placeholder="Nombre" required/>
</div>
<div class="field">
<label for="razon">Razón Social</label>
<input type="text" id="razon" name="razon" placeholder="Razón Social" required/>
</div>
<div class="ui divider">Contacto</div>
<div class="three wide field">
<label for="rut_contacto">RUT</label>
<div class="ui right labeled input">
<input type="text" id="rut_contacto" name="rut_contacto" placeholder="RUT" maxlength="10"
required/>
<div class="ui basic label">-<span id="dv_contacto"></span></div>
</div>
</div>
<div class="fields">
<div class="five wide field">
<label for="nombre_contacto">Nombre</label>
<input type="text" id="nombre_contacto" name="nombre_contacto" placeholder="Nombre" required/>
</div>
<div class="field">
<label for="apellido_paterno_contacto">Apellido Paterno</label>
<input type="text" id="apellido_paterno_contacto" name="apellido_paterno_contacto"
placeholder="Apellido Paterno" required/>
</div>
<div class="field">
<label for="apellido_materno_contacto">Apellido Materno</label>
<input type="text" id="apellido_materno_contacto" name="apellido_materno_contacto"
placeholder="Apellido Materno"/>
</div>
</div>
<div class="field">
<label for="email_contacto">Email</label>
<input type="email" id="email_contacto" name="email_contacto" placeholder="Email"/>
</div>
<div class="field">
<label for="telefono_contacto">Teléfono</label>
<div class="ui left labeled input">
<div class="ui basic label">+56</div>
<input type="text" id="telefono_contacto" name="telefono_contacto" placeholder="Teléfono"/>
</div>
</div>
</form>
</div>
<div class="actions">
<button class="ui green approve button">Guardar</button>
</div>
</div>
@include('inmobiliarias.proveedores.add_modal')
@endsection
@include('layout.body.scripts.rut')
@push('page_scripts')
<script>
const proveedores = {
ids: {
modal: '',
buttons: {
add: '',
edit: '',
@ -111,7 +53,6 @@
dv: '',
nombre: '',
razon: '',
tipo: '',
contacto: {
rut: '',
dv: '',
@ -125,69 +66,18 @@
proveedores: ''
},
data: JSON.parse('{!! json_encode($proveedores) !!}'),
add() {
return {
sociedad: () => {
const data = {
rut: $(this.ids.add.rut).val().replace(/\D/g, ''),
digito: $(this.ids.add.dv).text(),
nombre: $(this.ids.add.nombre).val(),
razon: $(this.ids.add.razon).val(),
tipo_sociedad_id: $(this.ids.add.tipo).dropdown('get value'),
contacto: {
rut: $(this.ids.add.contacto.rut).val().replace(/\D/g, ''),
digito: $(this.ids.add.contacto.dv).text(),
nombres: $(this.ids.add.contacto.nombre).val(),
apellido_paterno: $(this.ids.add.contacto.apellido_paterno).val(),
apellido_materno: $(this.ids.add.contacto.apellido_materno).val(),
email: $(this.ids.add.contacto.email).val(),
telefono: $(this.ids.add.contacto.telefono).val().replace(/\D/g, ''),
}
}
const body = new FormData()
body.append('sociedades[]', JSON.stringify(data))
const url = '{{$urls->api}}/sociedades/add'
const method = 'post'
fetchAPI(url, {method, body})
.then(response => (response) ? response.json() : null)
.then(data => {
if (data.sociedades !== null) {
data.sociedades.forEach(sociedad => {
const exists = this.data.find(s => s.rut === sociedad.rut)
if (typeof exists !== 'undefined') {
return
}
this.data.push(sociedad)
})
this.draw().sociedades()
$(this.ids.modal).find('form.form').trigger('reset')
}
})
}
}
},
edit() {
},
remove() {
return {
sociedad: rut => {
const body = new FormData()
body.append('sociedades_ruts[]', rut)
const url = '{{$urls->api}}/sociedades/delete'
const method = 'post'
fetchAPI(url, {method, body})
proveedor: rut => {
const url = `{{$urls->api}}/inmobiliarias/proveedor/${rut}/delete`
const method = 'delete'
APIClient.fetch(url, {method})
.then(response => (response) ? response.json() : null)
.then(data => {
if (data.sociedades !== null) {
data.sociedades.forEach(sociedad => {
if (sociedad.sociedad.rut !== rut) {
return
}
if (!sociedad.deleted) {
return
}
$(this.ids.proveedores).find(`button[data-sociedad="${rut}"]`).closest('tr').remove()
})
if (data.success) {
window.location.reload()
}
})
@ -196,18 +86,18 @@
},
draw() {
return {
sociedades: () => {
proveedores: () => {
$(this.ids.proveedores).empty()
this.data.forEach(sociedad => {
this.data.forEach(proveedor => {
$(this.ids.proveedores).append(`
<tr>
<td>${sociedad.nombre}</td>
<td>${sociedad.contacto.nombreCompleto}</td>
<td>${proveedor.nombre}</td>
<td>${proveedor.contacto.nombreCompleto}</td>
<td class="right aligned">
<button class="ui icon button" data-sociedad="${sociedad.rut}">
<button class="ui icon button" data-proveedor="${proveedor.rut}">
<i class="edit icon"></i>
</button>
<button class="ui red icon button" data-sociedad="${sociedad.rut}">
<button class="ui red icon button" data-proveedor="${proveedor.rut}">
<i class="remove icon"></i>
</button>
</td>
@ -215,7 +105,7 @@
`)
})
$(this.ids.buttons.remove).click((e) => {
this.remove().sociedad($(e.target).data('sociedad'))
this.remove().proveedor($(e.target).data('proveedor'))
})
}
}
@ -223,11 +113,7 @@
formatters() {
return {
rut: value => {
const rut = value.replace(/[^0-9]/g, '')
if (rut.length <= 1) {
return rut
}
return rut.replace(/\B(?=(\d{3})+(?!\d))/g, '.')
return Rut.format(value)
},
telefono: value => {
const phone = value.replace(/[^0-9]/g, '')
@ -238,77 +124,35 @@
}
}
},
digitoVerificador(value) {
let rut = value.replace(/[^0-9kK]/g, '')
if (rut.length < 1) {
return ''
}
let suma = 0
let mul = 2
for (let i = rut.length - 1; i >= 0; i--) {
suma += parseInt(rut[i]) * mul
mul = (mul + 1) % 8 || 2
}
const dv = 11 - suma % 11
return dv === 10 ? 'K' : (dv === 11 ? '0' : dv.toString())
},
setup(ids) {
this.ids = ids
const addModal = new AddModal(this.ids.add, this.formatters())
$(this.ids.buttons.add).click(() => {
$(this.ids.modal).modal('show')
})
$(this.ids.add.rut).on('input', (e) => {
e.target.value = this.formatters().rut(e.target.value)
$(this.ids.add.dv).text(this.digitoVerificador(e.target.value))
})
if ($(this.ids.add.rut).val().length > 0) {
$(this.ids.add.rut).val(this.formatters().rut($(this.ids.add.rut).val()))
$(this.ids.add.dv).text(this.digitoVerificador($(this.ids.add.rut).val()))
}
$(this.ids.tipo).dropdown()
$(this.ids.add.contacto.rut).on('input', (e) => {
e.target.value = this.formatters().rut(e.target.value)
$(this.ids.add.contacto.dv).text(this.digitoVerificador(e.target.value))
})
if ($(this.ids.add.contacto.rut).val().length > 0) {
$(this.ids.add.contacto.rut).val(this.formatters().rut($(this.ids.add.contacto.rut).val()))
$(this.ids.add.contacto.dv).text(this.digitoVerificador($(this.ids.add.contacto.rut).val()))
}
$(this.ids.add.contacto.telefono).on('input', (e) => {
e.target.value = this.formatters().telefono(e.target.value)
})
if ($(this.ids.add.contacto.telefono).val().length > 0) {
$(this.ids.add.contacto.telefono).val(this.formatters().telefono($(this.ids.add.contacto.telefono).val()))
}
$(this.ids.modal).modal({
onApprove: () => {
this.add().sociedad()
}
addModal.show()
})
$(this.ids.buttons.remove).click((e) => {
this.remove().sociedad($(e.target).data('sociedad'))
this.remove().proveedor(e.currentTarget.parentNode.dataset.proveedor)
})
}
}
$(document).ready(() => {
proveedores.setup({
modal: '#add_modal',
buttons: {
add: '#add_button',
edit: '.edit',
remove: '.remove'
},
add: {
form: '#add_modal form.form',
modal: '#add_modal',
form: 'add_form',
rut: '#rut',
dv: '#dv',
digito: '#dv',
nombre: '#nombre',
razon: '#razon',
tipo: '#tipo',
contacto: {
rut: '#rut_contacto',
dv: '#dv_contacto',
nombre: '#nombre_contacto',
digito: '#dv_contacto',
nombres: '#nombre_contacto',
apellido_paterno: '#apellido_paterno_contacto',
apellido_materno: '#apellido_materno_contacto',
email: '#email_contacto',

View File

@ -0,0 +1,137 @@
<div class="ui modal" id="add_modal">
<div class="content">
<form class="ui form" id="add_form">
<div class="three wide field">
<label for="rut">RUT</label>
<div class="ui right labeled input">
<input class="right aligned" type="text" id="rut" name="rut" placeholder="RUT" maxlength="10"
required/>
<div class="ui basic label">-<span id="dv"></span></div>
</div>
</div>
<div class="five wide field">
<label for="nombre">Nombre</label>
<input type="text" id="nombre" name="nombre" placeholder="Nombre" required/>
</div>
<div class="field">
<label for="razon">Razón Social</label>
<input type="text" id="razon" name="razon" placeholder="Razón Social" required/>
</div>
<div class="ui divider">Contacto</div>
<div class="three wide field">
<label for="rut_contacto">RUT</label>
<div class="ui right labeled input">
<input type="text" id="rut_contacto" name="rut_contacto" placeholder="RUT" maxlength="10"
required/>
<div class="ui basic label">-<span id="dv_contacto"></span></div>
</div>
</div>
<div class="fields">
<div class="five wide field">
<label for="nombre_contacto">Nombre</label>
<input type="text" id="nombre_contacto" name="nombre_contacto" placeholder="Nombre" required/>
</div>
<div class="field">
<label for="apellido_paterno_contacto">Apellido Paterno</label>
<input type="text" id="apellido_paterno_contacto" name="apellido_paterno_contacto"
placeholder="Apellido Paterno" required/>
</div>
<div class="field">
<label for="apellido_materno_contacto">Apellido Materno</label>
<input type="text" id="apellido_materno_contacto" name="apellido_materno_contacto"
placeholder="Apellido Materno"/>
</div>
</div>
<div class="field">
<label for="email_contacto">Email</label>
<input type="email" id="email_contacto" name="email_contacto" placeholder="Email"/>
</div>
<div class="field">
<label for="telefono_contacto">Teléfono</label>
<div class="ui left labeled input">
<div class="ui basic label">+56</div>
<input type="text" id="telefono_contacto" name="telefono_contacto" placeholder="Teléfono"/>
</div>
</div>
</form>
</div>
<div class="actions">
<button class="ui green approve button">Guardar</button>
</div>
</div>
@push('page_scripts')
<script>
class AddModal {
props
constructor(props, formatters) {
this.props = props
this.setup(formatters)
}
show() {
$(this.props.modal).modal('show')
}
add() {
const form = document.getElementById(this.props.form)
const data = {
rut: form.querySelector(this.props.rut).value.replace(/\D/g, ''),
digito: form.querySelector(this.props.digito).textContent,
nombre: form.querySelector(this.props.nombre).value,
razon: form.querySelector(this.props.razon).value,
contacto: {
rut: form.querySelector(this.props.contacto.rut).value.replace(/\D/g, ''),
digito: form.querySelector(this.props.contacto.digito).textContent,
nombres: form.querySelector(this.props.contacto.nombres).value,
apellido_paterno: form.querySelector(this.props.contacto.apellido_paterno).value,
apellido_materno: form.querySelector(this.props.contacto.apellido_materno).value,
email: form.querySelector(this.props.contacto.email).value,
telefono: form.querySelector(this.props.contacto.telefono).value.replace(/\D/g, ''),
}
}
const body = new FormData()
body.append('proveedores[]', JSON.stringify(data))
const url = '{{$urls->api}}/inmobiliarias/proveedores/add'
const method = 'post'
APIClient.fetch(url, {method, body})
.then(response => (response) ? response.json() : null)
.then(data => {
if (data.success.filter(s => s).length > 0) {
window.location.reload()
}
})
}
setup(formatters) {
$(this.props.modal).modal({
onApprove: () => {
this.add()
}
})
const form = document.getElementById(this.props.form)
form.querySelector(this.props.rut).addEventListener('input', (e) => {
e.currentTarget.value = formatters.rut(e.currentTarget.value)
form.querySelector(this.props.digito).textContent = Rut.digitoVerificador(e.currentTarget.value)
})
if (form.querySelector(this.props.rut).value.length > 0) {
form.querySelector(this.props.rut).value = formatters.rut(form.querySelector(this.props.rut).value)
form.querySelector(this.props.digito).textContent = Rut.digitoVerificador(form.querySelector(this.props.rut).value)
}
form.querySelector(this.props.contacto.rut).addEventListener('input', (e) => {
e.currentTarget.value = formatters.rut(e.currentTarget.value)
form.querySelector(this.props.contacto.digito).textContent = Rut.digitoVerificador(e.currentTarget.value)
})
if (form.querySelector(this.props.contacto.rut).value.length > 0) {
form.querySelector(this.props.contacto.rut).value = formatters.rut(form.querySelector(this.props.contacto.rut).value)
form.querySelector(this.props.contacto.digito).textContent = Rut.digitoVerificador(form.querySelector(this.props.contacto.rut).value)
}
form.querySelector(this.props.contacto.telefono).addEventListener('input', (e) => {
e.currentTarget.value = formatters.telefono(e.currentTarget.value)
})
if (form.querySelector(this.props.contacto.telefono).value.length > 0) {
form.querySelector(this.props.contacto.telefono).value = formatters.telefono(form.querySelector(this.props.contacto.telefono).value)
}
}
}
</script>
@endpush

View File

@ -2,6 +2,9 @@
<script>
class Rut {
static digitoVerificador(rut) {
if (!(typeof rut === 'string' || rut instanceof String)) {
rut = rut.toString()
}
if (rut.length === 0) {
return ''
}
@ -12,6 +15,9 @@
return S ? S - 1 : 'K'
}
static format(rut) {
if (!(typeof rut === 'string' || rut instanceof String)) {
rut = rut.toString()
}
if (rut.length === 0) {
return ''
}
@ -19,6 +25,9 @@
return rut.replace(/^(\d{1,2})(\d{3})(\d{3})$/, '$1.$2.$3')
}
static validar(rut, digito) {
if (!(typeof digito === 'string' || digito instanceof String)) {
digito = digito.toString()
}
return Rut.digitoVerificador(rut) === digito
}
}

View File

@ -0,0 +1,79 @@
<?php
namespace Incoviba\Controller\API\Inmobiliarias;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Incoviba\Common\Implement;
use Incoviba\Controller\API\withJson;
use Incoviba\Common\Ideal;
use Incoviba\Repository;
use Incoviba\Service;
class Proveedores extends Ideal\Controller
{
use withJson;
public function __invoke(ServerRequestInterface $request, ResponseInterface $response,
Service\Inmobiliaria\Proveedor $proveedorService): ResponseInterface
{
$output = ['proveedores' => []];
try {
$output['proveedores'] = $proveedorService->getAll('nombre');
} catch (Implement\Exception\EmptyResult) {}
return $this->withJson($response, $output);
}
public function add(ServerRequestInterface $request, ResponseInterface $response,
Service\Inmobiliaria\Proveedor $proveedorService): ResponseInterface
{
$input = $request->getParsedBody();
$output = [
'input' => $input,
'proveedores' => [],
'success' => [],
];
foreach ($input['proveedores'] as $json) {
$data = json_decode($json, true);
try {
$output['proveedores'] []= $proveedorService->add($data);
$output['success'] []= true;
} catch (Implement\Exception\EmptyResult) {
$output['success'] []= false;
}
}
return $this->withJson($response, $output);
}
public function edit(ServerRequestInterface $request, ResponseInterface $response,
Service\Inmobiliaria\Proveedor $proveedorService): ResponseInterface
{
$input = $request->getParsedBody();
$output = [
'input' => $input,
'proveedores' => [],
'success' => [],
];
foreach ($input['proveedores'] as $json) {
$data = json_decode($json, true);
try {
$output['proveedores'] []= $proveedorService->edit($data);
$output['success'] []= true;
} catch (Implement\Exception\EmptyResult) {
$output['success'] []= false;
}
}
return $this->withJson($response, $output);
}
public function delete(ServerRequestInterface $request, ResponseInterface $response,
Service\Inmobiliaria\Proveedor $proveedorService, int $proveedor_rut): ResponseInterface
{
$output = [
'proveedor_rut' => $proveedor_rut,
'proveedor' => null,
'success' => false
];
try {
$output['proveedor'] = $proveedorService->getById($proveedor_rut);
$output['success'] = $proveedorService->delete($output['proveedor']);
} catch (Implement\Exception\EmptyResult) {}
return $this->withJson($response, $output);
}
}

View File

@ -11,8 +11,7 @@ use Incoviba\Service;
class Proveedores
{
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, View $view,
Service\Inmobiliaria\Proveedor $proveedorService,
Repository\Inmobiliaria\TipoSociedad $tipoSociedad): ResponseInterface
Service\Inmobiliaria\Proveedor $proveedorService): ResponseInterface
{
$proveedores = [];
try {

View File

@ -1,32 +0,0 @@
<?php
namespace Incoviba\Model;
use DateTimeInterface;
use Incoviba\Common\Ideal;
class DatosPersona extends Ideal\Model
{
public Persona $persona;
public ?Direccion $direccion;
public ?int $telefono;
public ?string $email;
public ?DateTimeInterface $fechaNacimiento;
public ?string $sexo;
public ?string $estadoCivil;
public ?string $nacionalidad;
public ?string $ocupacion;
public function jsonSerialize(): mixed
{
return [
'direccion' => $this->direccion,
'telefono' => $this->telefono,
'email' => $this->email,
'fechaNacimiento' => $this->fechaNacimiento,
'sexo' => $this->sexo,
'estadoCivil' => $this->estadoCivil,
'nacionalidad' => $this->nacionalidad,
'profesion' => $this->ocupacion,
];
}
}

View File

@ -2,7 +2,9 @@
namespace Incoviba\Model\Inmobiliaria;
use Incoviba\Common\Ideal;
use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Model;
use Incoviba\Model\Inmobiliaria\Proveedor\Datos;
class Proveedor extends Ideal\Model
{
@ -10,18 +12,30 @@ class Proveedor extends Ideal\Model
public string $digito;
public string $nombre;
public ?string $razon;
public ?DatosProveedor $datos;
public ?Model\Persona $contacto;
public ?Datos $datos;
public function datos(): ?Datos
{
if (!isset($this->datos)) {
$this->datos = $this->runFactory('datos');
}
return $this->datos;
}
public function jsonSerialize(): mixed
{
return [
$json = [
'rut' => $this->rut,
'digito' => $this->digito,
'nombre' => $this->nombre,
'razon' => $this->razon,
'datos' => $this->datos,
'datos' => null,
'contacto' => $this->contacto
];
try {
$json['datos'] = $this->datos();
} catch (EmptyResult) {}
return $json;
}
}

View File

@ -1,10 +1,11 @@
<?php
namespace Incoviba\Model\Inmobiliaria;
namespace Incoviba\Model\Inmobiliaria\Proveedor;
use Incoviba\Common\Ideal;
use Incoviba\Model\Direccion;
use Incoviba\Model\Inmobiliaria\Proveedor;
class DatosProveedor extends Ideal\Model
class Datos extends Ideal\Model
{
public Proveedor $proveedor;
public ?Direccion $direccion;

View File

@ -2,6 +2,7 @@
namespace Incoviba\Model;
use Incoviba\Common\Ideal;
use Incoviba\Model\Persona\Datos;
class Persona extends Ideal\Model
{
@ -21,8 +22,8 @@ class Persona extends Ideal\Model
return number_format($this->rut, 0, ',', '.') . '-' . $this->digito;
}
protected ?DatosPersona $datos;
public function datos(): ?DatosPersona
protected ?Datos $datos;
public function datos(): ?Datos
{
if (!isset($this->datos)) {
$this->datos = $this->runFactory('datos');
@ -40,7 +41,7 @@ class Persona extends Ideal\Model
'apellidoMaterno' => $this->apellidoMaterno,
'nombreCompleto' => $this->nombreCompleto(),
'rutCompleto' => $this->rutCompleto(),
'datos' => $this->datos(),
'datos' => $this->datos() ?? null,
];
}
}

View File

@ -0,0 +1,34 @@
<?php
namespace Incoviba\Model\Persona;
use DateTimeInterface;
use Incoviba\Common\Ideal;
use Incoviba\Model\Direccion;
use Incoviba\Model\Persona;
class Datos extends Ideal\Model
{
public Persona $persona;
public ?Direccion $direccion;
public ?int $telefono;
public ?string $email;
public ?DateTimeInterface $fechaNacimiento;
public ?string $sexo;
public ?string $estadoCivil;
public ?string $nacionalidad;
public ?string $ocupacion;
public function jsonSerialize(): mixed
{
return [
'direccion' => $this->direccion ?? null,
'telefono' => $this->telefono ?? null,
'email' => $this->email ?? null,
'fechaNacimiento' => $this->fechaNacimiento ?? null,
'sexo' => $this->sexo ?? null,
'estadoCivil' => $this->estadoCivil ?? null,
'nacionalidad' => $this->nacionalidad ?? null,
'ocupacion' => $this->ocupacion ?? null,
];
}
}

View File

@ -10,8 +10,8 @@ use Incoviba\Service;
class Proveedor extends Ideal\Repository
{
public function __construct(Define\Connection $connection, protected Repository\Inmobiliaria $inmobiliariaRepository,
protected Repository\Sociedad $sociedadRepository)
public function __construct(Define\Connection $connection,
protected Service\Persona $personaService)
{
parent::__construct($connection);
$this->setTable('proveedores');
@ -19,43 +19,40 @@ class Proveedor extends Ideal\Repository
public function create(?array $data = null): Model\Inmobiliaria\Proveedor
{
$map = (new Implement\Repository\MapperParser())
->register('inmobiliaria_rut', (new Implement\Repository\Mapper())
->setProperty('inmobiliaria')
->setFunction(function($data) {
return $this->inmobiliariaRepository->fetchById($data['inmobiliaria_rut']);
}))
->register('sociedad_rut', (new Implement\Repository\Mapper())
->setProperty('sociedad')
->setFunction(function($data) {
return $this->sociedadRepository->fetchById($data['sociedad_rut']);
}));
$map = (new Implement\Repository\MapperParser(['rut', 'digito', 'nombre', 'razon']))
->register('contacto_rut', (new Implement\Repository\Mapper())->setProperty('contacto')->setFunction(function($data) {
return $this->personaService->getById($data['contacto_rut']);
}));
return $this->parseData(new Model\Inmobiliaria\Proveedor(), $data, $map);
}
public function save(Define\Model $model): Model\Inmobiliaria\Proveedor
{
$model->id = $this->saveNew(['inmobiliaria_rut', 'sociedad_rut'], [$model->inmobiliaria->rut, $model->sociedad->rut]);
$this->saveNew(['rut', 'digito', 'nombre', 'razon', 'contacto_rut'], [
$model->rut, $model->digito, $model->nombre, $model->razon, $model->contacto->rut
]);
return $model;
}
public function edit(Define\Model $model, array $new_data): Model\Inmobiliaria\Proveedor
{
return $this->update($model, ['sociedad_id'], $new_data);
return $this->update($model, ['rut', 'digito', 'nombre', 'razon', 'contacto_rut'], $new_data);
}
public function fetchByInmobiliaria(int $inmobiliaria_rut): array
public function fetchByNombre(string $nombre): Model\Inmobiliaria\Proveedor
{
$query = $this->connection->getQueryBuilder()
->select()
->from($this->getTable())
->where('inmobiliaria_rut = :inmobiliaria_rut');
return array_map([$this, 'load'], $this->fetchMany($query, compact('inmobiliaria_rut')));
->where('nombre = :nombre');
return $this->fetchOne($query, compact('nombre'));
}
public function fetchBySociedad(int $sociedad_rut): array
public function filterData(array $data): array
{
$query = $this->connection->getQueryBuilder()
->select()
->from($this->getTable())
->where('sociedad_rut = :sociedad_rut');
return array_map([$this, 'load'], $this->fetchMany($query, compact('sociedad_rut')));
return array_intersect_key($data, array_flip(['rut', 'digito', 'nombre', 'razon', 'contacto_rut']));
}
protected function getKey(): string
{
return 'rut';
}
}

View File

@ -0,0 +1,52 @@
<?php
namespace Incoviba\Repository\Inmobiliaria\Proveedor;
use Incoviba\Common\Define;
use Incoviba\Common\Ideal;
use Incoviba\Common\Implement;
use Incoviba\Model;
use Incoviba\Repository;
use Incoviba\Service;
class Datos extends Ideal\Repository
{
public function __construct(Define\Connection $connection, protected Repository\Inmobiliaria\Proveedor $proveedorRepository,
protected Repository\Direccion $direccionRepository)
{
parent::__construct($connection);
$this->setTable('datos_proveedores');
}
public function create(?array $data = null): Model\Inmobiliaria\Proveedor\Datos
{
$map = (new Implement\Repository\MapperParser(['telefono', 'giro']))
->register('proveedor_rut', (new Implement\Repository\Mapper())->setProperty('proveedor')->setFunction(function($data) {
return $this->proveedorRepository->fetchById($data['proveedor_rut']);
}))
->register('direccion_id', (new Implement\Repository\Mapper())->setProperty('direccion')->setFunction(function($data) {
return $this->direccionRepository->fetchById($data['direccion_id']);
}));
return $this->parseData(new Model\Inmobiliaria\Proveedor\Datos(), $data, $map);
}
public function save(Define\Model $model): Model\Inmobiliaria\Proveedor\Datos
{
$model->id = $this->saveNew([
'proveedor_rut', 'direccion_id', 'telefono', 'giro'
], [
$model->proveedor->rut, $model->direccion->id, $model->telefono, $model->giro
]);
return $model;
}
public function edit(Define\Model $model, array $new_data): Model\Inmobiliaria\Proveedor\Datos
{
return $this->update($model, ['proveedor_rut', 'direccion_id', 'telefono', 'giro'], $new_data);
}
public function fetchByProveedor(int $proveedor_rut): Model\Inmobiliaria\Proveedor\Datos
{
$query = $this->connection->getQueryBuilder()
->select()
->from($this->getTable())
->where('proveedor_rut = :proveedor_rut');
return $this->fetchOne($query, compact('proveedor_rut'));
}
}

View File

@ -33,13 +33,18 @@ class Persona extends Ideal\Repository
return $this->update($model, $new_data, ['rut', 'digito', 'nombres', 'apellido_paterno', 'apellido_materno']);
}
public function fetchByRut(int $rut): Model\Persona
/*public function fetchById(int $rut): Model\Persona
{
$query = $this->connection->getQueryBuilder()
->select()
->from($this->getTable())
->where('rut = ?');
return $this->fetchOne($query, [$rut]);
}*/
public function filterData(array $data): array
{
return array_intersect_key($data, array_flip(['rut', 'digito', 'nombres', 'apellido_paterno', 'apellido_materno']));
}
protected function getKey(): string

View File

@ -1,12 +1,14 @@
<?php
namespace Incoviba\Repository;
namespace Incoviba\Repository\Persona;
use Incoviba\Common\Define;
use Incoviba\Common\Ideal;
use Incoviba\Common\Implement;
use Incoviba\Model;
use Incoviba\Repository\Direccion;
use Incoviba\Repository\Persona;
class DatosPersona extends Ideal\Repository
class Datos extends Ideal\Repository
{
public function __construct(Define\Connection $connection, protected Persona $personaRepository,
protected Direccion $direccionRepository)
@ -15,7 +17,7 @@ class DatosPersona extends Ideal\Repository
$this->setTable('datos_personas');
}
public function create(?array $data = null): Model\DatosPersona
public function create(?array $data = null): Model\Persona\Datos
{
$map = (new Implement\Repository\MapperParser())
->register('persona_rut', (new Implement\Repository\Mapper())
@ -46,31 +48,31 @@ class DatosPersona extends Ideal\Repository
->register('nacionalidad', (new Implement\Repository\Mapper())->setFunction(function($data) {
return $data['nacionalidad'];
})->setDefault(null))
->register('profesion', (new Implement\Repository\Mapper())->setFunction(function($data) {
return $data['profesion'];
->register('ocupacion', (new Implement\Repository\Mapper())->setFunction(function($data) {
return $data['ocupacion'];
})->setDefault(null));
return $this->parseData(new Model\DatosPersona(), $data, $map);
return $this->parseData(new Model\Persona\Datos(), $data, $map);
}
public function save(Define\Model $model): Model\DatosPersona
public function save(Define\Model $model): Model\Persona\Datos
{
$this->saveNew([
'persona_rut', 'direccion_id', 'telefono', 'email', 'fecha_nacimiento', 'sexo', 'estado_civil',
'nacionalidad', 'profesion'
'nacionalidad', 'ocupacion'
], [
$model->persona->rut, $model->direccion?->id, $model->telefono, $model->email, $model->fechaNacimiento,
$model->sexo, $model->estadoCivil, $model->nacionalidad, $model->ocupacion
]);
return $model;
}
public function edit(Define\Model $model, array $new_data): Model\DatosPersona
public function edit(Define\Model $model, array $new_data): Model\Persona\Datos
{
return $this->update($model, [
'direccion_id', 'telefono', 'email', 'fecha_nacimiento', 'sexo', 'estado_civil',
'nacionalidad', 'profesion'
'nacionalidad', 'ocupacion'
], $new_data);
}
public function fetchByPersona(int $persona_rut): Model\DatosPersona
public function fetchByPersona(int $persona_rut): Model\Persona\Datos
{
$query = $this->connection->getQueryBuilder()
->select()

View File

@ -31,7 +31,7 @@ class Sociedad extends Ideal\Repository
->register('contacto_rut', (new Implement\Repository\Mapper())
->setProperty('contacto')
->setFunction(function ($data) {
return $this->personaService->getByRut($data['contacto_rut']);
return $this->personaService->getById($data['contacto_rut']);
}));
return $this->parseData(new Model\Sociedad(), $data, $map);
}

View File

@ -1,16 +1,20 @@
<?php
namespace Incoviba\Service\Inmobiliaria;
use PDOException;
use Psr\Log\LoggerInterface;
use Incoviba\Common\Ideal;
use Incoviba\Common\Implement;
use Incoviba\Common\Define;
use Incoviba\Repository;
use Incoviba\Model;
use Incoviba\Repository;
use Incoviba\Service;
class Proveedor extends Ideal\Service
{
public function __construct(LoggerInterface $logger, protected Repository\Inmobiliaria\Proveedor $proveedorRepository)
public function __construct(LoggerInterface $logger,
protected Repository\Inmobiliaria\Proveedor $proveedorRepository,
protected Repository\Inmobiliaria\Proveedor\Datos $datosRepository,
protected Service\Persona $contactoService)
{
parent::__construct($logger);
}
@ -18,18 +22,61 @@ class Proveedor extends Ideal\Service
public function getAll(?string $orderBy = null): array
{
try {
return $this->proveedorRepository->fetchAll($orderBy);
return array_map([$this, 'process'], $this->proveedorRepository->fetchAll($orderBy));
} catch (Implement\Exception\EmptyResult) {
return [];
}
}
public function getByRut(int $proveedor_rut): ?Model\Inmobiliaria\Proveedor
public function getById(int $proveedor_rut): ?Model\Inmobiliaria\Proveedor
{
try {
return $this->proveedorRepository->fetchById($proveedor_rut);
return $this->process($this->proveedorRepository->fetchById($proveedor_rut));
} catch (Implement\Exception\EmptyResult) {
return null;
}
}
public function add(array $data): Model\Inmobiliaria\Proveedor
{
$filteredData = $this->proveedorRepository->filterData($data);
try {
$proveedor = $this->process($this->proveedorRepository->fetchByNombre($filteredData['nombre']));
if ($proveedor->contacto->rut !== $data['contacto']['rut']) {
$contacto = $this->contactoService->add($data['contacto']);
return $this->proveedorRepository->edit($proveedor, ['contacto_rut' => $contacto->rut]);
}
return $proveedor;
} catch (Implement\Exception\EmptyResult) {
$contacto = $this->contactoService->add($data['contacto']);
$filteredData['contacto_rut'] = $contacto->rut;
$proveedor = $this->proveedorRepository->create($filteredData);
return $this->process($this->proveedorRepository->save($proveedor));
}
}
/**
* @TODO Implement
* @param Model\Inmobiliaria\Proveedor $proveedor
* @param array $data
* @return Model\Inmobiliaria\Proveedor
*/
public function edit(Model\Inmobiliaria\Proveedor $proveedor, array $data): Model\Inmobiliaria\Proveedor
{
return $proveedor;
}
public function delete(Model\Inmobiliaria\Proveedor $proveedor): bool
{
try {
$this->proveedorRepository->remove($proveedor);
return true;
} catch (Implement\Exception\EmptyResult | PDOException) {
return false;
}
}
protected function process(Model\Inmobiliaria\Proveedor $proveedor): Model\Inmobiliaria\Proveedor
{
$proveedor->addFactory('datos', (new Implement\Repository\Factory())->setCallable([$this->datosRepository, 'fetchByProveedor'])->setArgs(['proveedor_rut' => $proveedor->rut]));
return $proveedor;
}
}

View File

@ -1,28 +1,28 @@
<?php
namespace Incoviba\Service;
use Psr\Log\LoggerInterface;
use Incoviba\Common\Ideal;
use Incoviba\Common\Implement;
use Incoviba\Model;
use Incoviba\Repository;
use Psr\Log\LoggerInterface;
class Persona extends Ideal\Service
{
public function __construct(LoggerInterface $logger, protected Repository\Persona $personaRepository,
protected Repository\DatosPersona $datosPersonaRepository)
public function __construct(LoggerInterface $logger, protected Repository\Persona $personaRepository,
protected Repository\Persona\Datos $datosPersonaRepository)
{
parent::__construct($logger);
}
public function getByRut(int $rut): Model\Persona
public function getById(int $rut): Model\Persona
{
return $this->process($this->personaRepository->fetchByRut($rut));
return $this->process($this->personaRepository->fetchById($rut));
}
public function add(array $data): Model\Persona
{
try {
$persona = $this->personaRepository->fetchByRut($data['rut']);
$persona = $this->personaRepository->fetchById($data['rut']);
} catch (Implement\Exception\EmptyResult) {
$persona = $this->personaRepository->create($data);
$persona = $this->personaRepository->save($persona);