Editar Brokers y sus contratos

This commit is contained in:
Juan Pablo Vial
2025-03-11 17:41:11 -03:00
parent 510e05e5ca
commit 7c7c8315e2
13 changed files with 491 additions and 60 deletions

View File

@ -4,3 +4,6 @@ use Incoviba\Controller\Proyectos\Brokers;
$app->group('/brokers', function($app) {
$app->get('[/]', Brokers::class);
});
$app->group('/broker/{broker_rut}', function($app) {
$app->get('[/]', [Brokers::class, 'show']);
});

View File

@ -1,9 +1,9 @@
<head>
<meta charset="utf8" />
@hasSection('page_title')
<title>Incoviba - @yield('page_title')</title>
<title>Incoviba - @yield('page_title')</title>
@else
<title>Incoviba</title>
<title>Incoviba</title>
@endif
<link rel="icon" href="{{$urls->images}}/Isotipo 16.png" />
@include('layout.head.styles')

View File

@ -17,16 +17,20 @@
</thead>
@foreach($brokers as $broker)
<tr>
<td>{{$broker->rutFull()}}</td>
<td>
<span
@if ($broker->data()?->legalName !== '')
data-tooltip="{{ $broker->data()?->legalName }}" data-position="right center"
@if ($broker->data()?->legalName !== '')
data-tooltip="{{ $broker->data()?->legalName }}" data-position="right center"
@endif
>
{{$broker->name}}
{{$broker->rutFull()}}
</span>
</td>
<td>
<a href="{{ $urls->base }}/proyectos/broker/{{ $broker->rut }}">
{{$broker->name}}
</a>
</td>
<td>
<span
@if ($broker->data()?->representative?->email !== '' || $broker->data()?->representative?->phone !== '')
@ -40,7 +44,9 @@
<div class="ui list">
@foreach($broker->contracts() as $contract)
<div class="item">
<a href="{{$urls->base}}/proyecto/{{$contract->project->id}}">{{$contract->project->descripcion}} ({{$format->percent($contract->commission, 2, true)}})</a>
<a href="{{$urls->base}}/proyecto/{{$contract->project->id}}" data-tooltip="{{$contract->current()->date->format('d-m-Y')}}" data-position="right center">
{{$contract->project->descripcion}} ({{$format->percent($contract->commission, 2, true)}})
</a>
</div>
@endforeach
</div>
@ -57,10 +63,23 @@
@endforeach
</table>
@include('proyectos.brokers.add_modal')
@include('proyectos.brokers.edit_modal')
@endsection
@push('page_scripts')
<script>
function storeBrokers() {
localStorage.setItem('brokers', '{!! json_encode(array_map(function($broker) {
$arr = json_decode(json_encode($broker), true);
array_walk_recursive($arr, function(&$val, $key) {
if ($val === null) {
$val = '';
}
});
$arr['contracts'] = $broker->contracts();
return $arr;
}, $brokers)) !!}')
}
const brokersHandler = {
ids: {
buttons: {
@ -77,16 +96,19 @@
edit: ''
}
},
modals: {
add: null,
edit: null
},
events() {
return {
add: clickEvent => {
console.debug(clickEvent)
clickEvent.preventDefault()
brokersHandler.actions().add()
},
edit: clickEvent => {
clickEvent.preventDefault()
const broker_rut = clickEvent.currentTarget.dataset.index
const broker_rut = parseInt(clickEvent.currentTarget.dataset.index)
brokersHandler.actions().edit(broker_rut)
},
delete: clickEvent => {
@ -108,9 +130,23 @@
actions() {
return {
add: () => {
$(`#${brokersHandler.ids.modals.add}`).modal('show')
this.modals.add.show()
},
edit: broker_rut => {
const localData = JSON.parse(localStorage.getItem('brokers'))
const broker = localData.find(broker => broker.rut === broker_rut)
const data = {
rut: broker_rut,
name: broker.name,
legal_name: broker.data?.legal_name || '',
contact: broker.data?.representative?.name || '',
email: broker.data?.representative?.email || '',
phone: broker.data?.representative?.phone || '',
address: broker.data?.representative?.address || '',
contracts: broker.contracts
}
this.modals.edit.load(data)
},
edit: broker_rut => {},
delete: broker_rut => {
brokersHandler.execute().delete(broker_rut)
}
@ -150,31 +186,19 @@
setup(ids) {
brokersHandler.ids = ids
brokersHandler.buttonWatch()
$(`#${brokersHandler.ids.modals.add}`).modal('hide')
new AddModal(brokersHandler)
this.modals.add = new AddModal(brokersHandler)
this.modals.edit = new EditModal(brokersHandler)
}
}
$(document).ready(() => {
storeBrokers()
brokersHandler.setup({
buttons: {
add: 'add_button',
edit: 'edit_button',
remove: 'remove_button'
remove: 'remove_button',
},
modals: {
add: 'add_broker_modal',
edit: 'edit_broker_modal'
},
forms: {
add: {
base: 'add_broker_form',
digit: 'digit'
},
edit: {
base: 'edit_broker_form'
}
}
})
})
</script>

View File

@ -18,7 +18,7 @@
<label>Nombre</label>
<input type="text" name="name" placeholder="Nombre" required />
</div>
<div class="field">
<div class="six wide field">
<label>Razón Social</label>
<input type="text" name="legal_name" placeholder="Razón Social" required />
</div>
@ -55,19 +55,19 @@
@include('layout.body.scripts.rut')
@push('page_scripts')
<script>
class AddModal
{
class AddModal {
ids
modal
handler
constructor(handler)
{
constructor(handler) {
this.handler = handler
this.ids = {
modal: handler.ids.modals.add,
form: handler.ids.forms.add.base,
digit: handler.ids.forms.add.digit
modal: 'add_broker_modal',
form: 'add_broker_form',
digit: 'digit'
}
$(`#${this.ids.modal}`).modal({
this.modal = $(`#${this.ids.modal}`)
this.modal.modal({
onApprove: () => {
const form = document.getElementById(this.ids.form)
const data = {
@ -82,6 +82,7 @@
this.handler.execute().add(data)
}
})
this.modal.modal('hide')
const value = document.querySelector(`#${this.ids.form} input[name="rut"]`).value
this.update().digit(value)
this.watch().rut()
@ -105,6 +106,9 @@
}
}
}
show() {
this.modal.modal('show')
}
}
</script>
@endpush

View File

@ -1,15 +1,22 @@
@extends('layout.base')
@section('page_title')
Operadores
@hasSection('brokers_title')
- @yield('brokers_title')
Operadores - @yield('brokers_title')
@else
Operadores
@endif
@endsection
@section('page_content')
<div class="ui container">
<h2 class="ui header">Operadores</h2>
<h2 class="ui header">
@hasSection('brokers_header')
Operador - @yield('brokers_header')
@else
Operadores
@endif
</h2>
@yield('brokers_content')
</div>
@endsection

View File

@ -0,0 +1,111 @@
<div class="ui modal" id="edit_broker_modal">
<div class="header">
Editar Operador
</div>
<div class="content">
<form class="ui form" id="edit_broker_form">
<input type="hidden" name="broker_rut" value="" />
<div class="fields">
<div class="field">
<label>Rut</label>
<div class="ui right labeled input">
<input type="text" name="rut" placeholder="Rut" value="" disabled />
<div class="ui basic label">-<span id="edit_digit"></span></div>
</div>
</div>
</div>
<div class="fields">
<div class="field">
<label>Nombre</label>
<input type="text" name="name" placeholder="Nombre" value="" />
</div>
<div class="six wide field">
<label>Razón Social</label>
<input type="text" name="legal_name" placeholder="Razón Social" value="" />
</div>
</div>
<div class="fields">
<div class="field">
<label>Contacto</label>
<input type="text" name="contact" placeholder="Contacto" value="" />
</div>
</div>
<div class="fields">
<div class="field">
<label>Correo</label>
<input type="email" name="email" placeholder="Correo" value="" />
</div>
<div class="field">
<label>Teléfono</label>
<input type="text" name="phone" placeholder="Teléfono" value="" />
</div>
</div>
</form>
</div>
<div class="actions">
<div class="ui black deny button">
Cancelar
</div>
<div class="ui positive right labeled icon button">
Guardar
<i class="checkmark icon"></i>
</div>
</div>
</div>
@push('page_scripts')
<script>
class EditModal
{
ids
modal
handler
data
constructor(handler)
{
this.handler = handler
this.ids = {
modal: 'edit_broker_modal',
form: 'edit_broker_form',
digit: 'edit_digit',
}
this.modal = $(`#${this.ids.modal}`)
this.modal.modal({
onApprove: () => {
const form = document.getElementById(this.ids.form)
const broker_rut = form.querySelector('[name="broker_rut"]').value
const data = {
name: form.querySelector('[name="name"]').value,
legal_name: form.querySelector('[name="legal_name"]').value,
email: form.querySelector('[name="email"]').value || '',
phone: form.querySelector('[name="phone"]').value || ''
}
this.handler.execute().edit(broker_rut, data)
}
})
this.modal.modal('hide')
}
load(data) {
this.data = data
const form = document.getElementById(this.ids.form)
form.querySelector('input[name="broker_rut"]').value = data.rut
form.querySelector('input[name="rut"]').value = data.rut
form.querySelector('input[name="name"]').value = data.name
form.querySelector('input[name="legal_name"]').value = data.legal_name
form.querySelector('input[name="contact"]').value = data.contact
form.querySelector('input[name="email"]').value = data.email
form.querySelector('input[name="phone"]').value = data.phone
this.update().digit(data.rut)
this.modal.modal('show')
}
update() {
return {
digit: value => {
document.getElementById(this.ids.digit).textContent = Rut.digitoVerificador(value)
},
}
}
}
</script>
@endpush

View File

@ -0,0 +1,165 @@
@extends('proyectos.brokers.base')
@section('brokers_title')
{{ $broker->name }}
@endsection
@section('brokers_header')
{{ $broker->name }}
@endsection
@section('brokers_content')
<div class="ui compact segment">
<b>RUT:</b> {{ $broker->rutFull() }} <br />
<b>Razón Social:</b> {{ $broker->data()?->legalName }}
</div>
@if ($broker->data()?->representative->name !== null)
<div class="ui card">
<div class="content">
<div class="header">
Contacto
</div>
<div class="description">
Nombre: {{ $broker->data()?->representative?->name }}<br />
Email: {{ $broker->data()?->representative?->email }}<br />
Teléfono: {{ $broker->data()?->representative?->phone }}<br />
Dirección: {{ $broker->data()?->representative?->address }}
</div>
</div>
</div>
@endif
<table class="ui table">
<thead>
<tr>
<th>Proyecto</th>
<th>Comisión</th>
<th>Fecha Inicio</th>
<th class="right aligned">
<button type="button" class="ui small tertiary green icon button" id="add_contract_button">
<i class="plus icon"></i>
</button>
</th>
</tr>
</thead>
<tbody id="contracts">
@foreach($broker->contracts() as $contract)
<tr>
<td>{{ $contract->project->descripcion }}</td>
<td>{{ $format->percent($contract->commission, 2, true) }}</td>
<td>{{ $contract->current()->date->format('d-m-Y') }}</td>
<td class="right aligned">
<button type="button" class="ui small tertiary red icon button remove_button" data-index="{{$contract->id}}">
<i class="remove icon"></i>
</button>
</td>
</tr>
@endforeach
</tbody>
</table>
@include('proyectos.brokers.show.add_modal')
@endsection
@include('layout.body.scripts.datatables')
@push('page_scripts')
<script>
const brokerHandler = {
ids: {
buttons: {
add: '',
remove: ''
}
},
modals: {
add: null,
},
execute() {
return {
add: data => {
const url = '{{ $urls->api }}/proyectos/broker/{{ $broker->rut }}/contracts/add'
const method = 'post'
const body = new FormData()
body.set('contracts[]', JSON.stringify(data))
return APIClient.fetch(url, {method, body}).then(response => {
if (!response) {
console.error(response.errors)
alert('No se pudo agregar contrato.')
return
}
return response.json().then(json => {
if (!json.success) {
console.error(json.errors)
alert('No se pudo agregar contrato.')
return
}
window.location.reload()
})
})
},
remove: index => {
const url = `{{ $urls->api }}/proyectos/brokers/contract/${index}`
const method = 'delete'
return APIClient.fetch(url, {method}).then(response => {
if (!response) {
console.error(response.errors)
alert('No se pudo eliminar contrato.')
return
}
return response.json().then(json => {
if (!json.success) {
console.error(json.errors)
alert('No se pudo eliminar contrato.')
return
}
window.location.reload()
})
})
}
}
},
events() {
return {
add: clickEvent => {
clickEvent.preventDefault()
brokerHandler.modals.add.show()
},
remove: clickEvent => {
clickEvent.preventDefault()
const index = $(clickEvent.currentTarget).data('index')
brokerHandler.execute().remove(index)
}
}
},
buttonWatch() {
document.getElementById(brokerHandler.ids.buttons.add).addEventListener('click', brokerHandler.events().add)
Array.from(document.getElementsByClassName(brokerHandler.ids.buttons.remove)).forEach(button => {
button.addEventListener('click', brokerHandler.events().remove)
})
},
setup(ids) {
brokerHandler.ids = ids
brokerHandler.buttonWatch()
this.modals.add = new AddModal(brokerHandler)
const dto = structuredClone(datatables_defaults)
dto.order = [[0, 'asc']]
dto.columnDefs = [
{
targets: 3,
orderable: false
}
]
$('#contracts').parent().DataTable(dto)
}
}
$(document).ready(() => {
brokerHandler.setup({
buttons: {
add: 'add_contract_button',
remove: 'remove_button'
}
})
})
</script>
@endpush

View File

@ -0,0 +1,96 @@
<div class="ui modal" id="add_contract_modal">
<div class="header">
Agregar Contrato
</div>
<div class="content">
<form class="ui form" id="add_contract_form">
<input type="hidden" name="broker_rut" value="{{$broker->rut}}" />
<div class="fields">
<div class="six wide field">
<label>Proyecto</label>
<div class="ui search selection dropdown" id="project">
<input type="hidden" name="project_id" />
<i class="dropdown icon"></i>
<div class="default text">Proyecto</div>
<div class="menu">
@foreach($projects as $project)
<div class="item" data-value="{{ $project->id }}">{{ $project->descripcion }}</div>
@endforeach
</div>
</div>
</div>
<div class="field">
<label>Comisión</label>
<div class="ui right labeled input">
<input type="text" name="commission" placeholder="Comisión" />
<div class="ui basic label">%</div>
</div>
</div>
</div>
<div class="fields">
<div class="field">
<label>Fecha Inicio</label>
<div class="ui calendar" id="add_fecha_inicio">
<div class="ui icon input">
<i class="calendar icon"></i>
<input type="text" name="date" />
</div>
</div>
</div>
</div>
</form>
</div>
<div class="actions">
<div class="ui deny button">
Cancelar
</div>
<div class="ui positive right labeled icon button">
Agregar
<i class="checkmark icon"></i>
</div>
</div>
</div>
@push('page_scripts')
<script>
class AddModal {
ids
modal
handler
constructor(handler) {
this.handler = handler
this.ids = {
modal: 'add_contract_modal',
form: 'add_contract_form',
proyecto: 'project',
date: 'add_fecha_inicio'
}
$(`#${this.ids.proyecto}`).dropdown()
const cdo = structuredClone(calendar_date_options)
cdo['initialDate'] = new Date()
$(`#${this.ids.date}`).calendar(cdo)
this.modal = $(`#${this.ids.modal}`)
this.modal.modal({
onApprove: () => {
const form = document.getElementById(this.ids.form)
let commission = parseFloat(form.querySelector('[name="commission"]').value)
if (commission > 1) {
commission /= 100
}
const date = $(`#${this.ids.date}`).calendar('get date')
const data = {
broker_rut: form.querySelector('[name="broker_rut"]').value,
project_id: form.querySelector('[name="project_id"]').value,
commission: commission,
date: [date.getFullYear(), date.getMonth() + 1, date.getDate()].join('-')
}
this.handler.execute().add(data)
}
})
}
show() {
this.modal.modal('show')
}
}
</script>
@endpush

View File

@ -1,23 +1,46 @@
<?php
namespace Incoviba\Controller\Proyectos;
use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Exception\ServiceAction\Read;
use Psr\Log\LoggerInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use Incoviba\Common\Alias\View;
use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Exception\ServiceAction\Read;
use Incoviba\Repository;
use Incoviba\Service;
use Psr\Log\LoggerInterface;
class Brokers
{
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, LoggerInterface $logger, Service\Proyecto\Broker $brokerService, View $view): ResponseInterface
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, LoggerInterface $logger,
Service\Proyecto\Broker $brokerService, Repository\Proyecto $proyectoRepository,
View $view): ResponseInterface
{
$brokers = [];
$projects = [];
try {
$brokers = $brokerService->getAll();
} catch (Read) {}
return $view->render($response, 'proyectos.brokers', compact('brokers'));
$projects = $proyectoRepository->fetchAll('descripcion');
} catch (EmptyResult $exception) {
$logger->error($exception);
}
$brokers = $brokerService->getAll();
return $view->render($response, 'proyectos.brokers', compact('brokers', 'projects'));
}
public function show(ServerRequestInterface $request, ResponseInterface $response, LoggerInterface $logger,
Service\Proyecto\Broker $brokerService, Repository\Proyecto $proyectoRepository,
View $view, int $broker_rut): ResponseInterface
{
$broker = null;
try {
$broker = $brokerService->get($broker_rut);
} catch (Read $exception) {
$logger->error($exception);
}
$projects = [];
try {
$projects = $proyectoRepository->fetchAll('descripcion');
} catch (EmptyResult $exception) {
$logger->error($exception);
}
return $view->render($response, 'proyectos.brokers.show', compact('broker', 'projects'));
}
}

View File

@ -9,9 +9,9 @@ class Contract extends Common\Ideal\Model
public Model\Proyecto $project;
public Model\Proyecto\Broker $broker;
public float $commission;
protected array $states = [];
protected ?array $states;
public function states(): array
public function states(): ?array
{
if (!isset($this->states) or count($this->states) === 0) {
$this->states = $this->runFactory('states');
@ -20,7 +20,7 @@ class Contract extends Common\Ideal\Model
}
protected ?Contract\State $current;
public function currentState(): ?Contract\State
public function current(): ?Contract\State
{
if (!isset($this->current)) {
try {
@ -39,7 +39,7 @@ class Contract extends Common\Ideal\Model
'broker_rut' => $this->broker->rut,
'commission' => $this->commission,
'states' => $this->states(),
'current' => $this->currentState(),
'current' => $this->current(),
];
}
}

View File

@ -6,12 +6,12 @@ use IntlDateFormatter;
class Format
{
public function localDate(string $valor, string $format, bool $print = false): string
public function localDate(string $valor, ?string $format = null, bool $print = false): string
{
$date = new DateTimeImmutable($valor);
$formatter = new IntlDateFormatter('es_ES');
if ($format == null) {
$format = 'DD [de] MMMM [de] YYYY';
$format = "dd 'de' MMMM 'de' YYYY";
}
$formatter->setPattern($format);
return $formatter->format($date);

View File

@ -17,7 +17,8 @@ class Broker extends Ideal\Service
protected Repository\Proyecto\Broker $brokerRepository,
protected Repository\Proyecto\Broker\Data $dataRepository,
protected Repository\Proyecto\Broker\Contact $contactRepository,
protected Repository\Proyecto\Broker\Contract $contractRepository)
protected Repository\Proyecto\Broker\Contract $contractRepository,
protected Service\Proyecto\Broker\Contract $contractService)
{
parent::__construct($logger);
}
@ -115,8 +116,8 @@ class Broker extends Ideal\Service
->setArgs(['broker_rut' => $broker->rut])
->setCallable([$this->dataRepository, 'fetchByBroker']))
->addFactory('contracts', (new Factory())
->setArgs(['brokerRut' => $broker->rut])
->setCallable([$this->contractRepository, 'fetchByBroker']));
->setArgs(['broker_rut' => $broker->rut])
->setCallable([$this->contractService, 'getByBroker']));
return $broker;
}

View File

@ -118,7 +118,7 @@ class Contract extends Ideal\Service
{
try {
$contract = $this->contractRepository->fetchById($id);
$this->contractRepository->remove($contract->id);
$this->contractRepository->remove($contract);
return $contract;
} catch (PDOException | Implement\Exception\EmptyResult $exception) {
throw new ServiceAction\Delete(__CLASS__, $exception);
@ -145,9 +145,6 @@ class Contract extends Ideal\Service
$contract->addFactory('states', (new Implement\Repository\Factory())
->setCallable([$this->stateRepository, 'fetchByContract'])
->setArgs(['contract_id' => $contract->id]));
/*$contract->addFactory('currentState', (new Implement\Repository\Factory())
->setCallable([$this->stateRepository, 'fetchActiveByContract'])
->setArgs(['contract_id' => $contract->id]));*/
return $contract;
}
}