1 Commits

Author SHA1 Message Date
ad64ffa436 Import Precios 2025-08-27 19:27:18 -04:00
50 changed files with 1137 additions and 2258 deletions

View File

@ -2,9 +2,7 @@
namespace Incoviba\Common\Implement\Repository;
use Closure;
use Exception;
use Incoviba\Common\Define;
use Incoviba\Common\Implement\Exception\EmptyResult;
class Factory implements Define\Repository\Factory
{
@ -22,16 +20,8 @@ class Factory implements Define\Repository\Factory
return $this;
}
/**
* @return mixed
* @throws EmptyResult
*/
public function run(): mixed
{
try {
return call_user_func_array($this->callable, $this->args);
} catch (Exception $exception) {
throw new EmptyResult($exception->getMessage(), $exception);
}
return call_user_func_array($this->callable, $this->args);
}
}

View File

@ -4,7 +4,7 @@ declare(strict_types=1);
use Phinx\Migration\AbstractMigration;
final class CreateReservations extends AbstractMigration
final class CreateReservation extends AbstractMigration
{
/**
* Change Method.
@ -23,11 +23,9 @@ final class CreateReservations extends AbstractMigration
$this->execute("ALTER DATABASE CHARACTER SET 'utf8mb4';");
$this->execute("ALTER DATABASE COLLATE='utf8mb4_general_ci';");
$this->table('reservations')
->addColumn('project_id', 'integer', ['signed' => false, 'null' => false])
$this->table('reservation')
->addColumn('buyer_rut', 'integer', ['signed' => false, 'null' => false])
->addColumn('date', 'date', ['null' => false])
->addForeignKey('project_id', 'proyecto', 'id', ['delete' => 'cascade', 'update' => 'cascade'])
->addForeignKey('buyer_rut', 'personas', 'rut', ['delete' => 'cascade', 'update' => 'cascade'])
->create();

View File

@ -4,7 +4,7 @@ declare(strict_types=1);
use Phinx\Migration\AbstractMigration;
final class CreateReservationDetails extends AbstractMigration
final class CreateReservationDatas extends AbstractMigration
{
/**
* Change Method.
@ -23,13 +23,11 @@ final class CreateReservationDetails extends AbstractMigration
$this->execute("ALTER DATABASE CHARACTER SET 'utf8mb4';");
$this->execute("ALTER DATABASE COLLATE='utf8mb4_general_ci';");
$this->table('reservation_details')
$this->table('reservation_data')
->addColumn('reservation_id', 'integer', ['signed' => false, 'null' => false])
->addColumn('type', 'integer', ['length' => 1, 'signed' => false, 'null' => false])
->addColumn('reference_id', 'integer', ['signed' => false, 'null' => false])
->addColumn('value', 'decimal', ['precision' => 10, 'scale' => 2, 'signed' => false, 'default' => null, 'null' => true])
->addForeignKey('reservation_id', 'reservations', 'id', ['delete' => 'cascade', 'update' => 'cascade'])
->addIndex(['reservation_id', 'type', 'reference_id'], ['unique' => true, 'name' => 'idx_reservation_details'])
->addColumn('value', 'decimal', ['precision' => 10, 'scale' => 2, 'signed' => false, 'default' => 0.00, 'null' => true])
->create();
$this->execute('SET unique_checks=1; SET foreign_key_checks=1;');

View File

@ -27,7 +27,7 @@ final class CreateReservationStates extends AbstractMigration
->addColumn('reservation_id', 'integer', ['signed' => false, 'null' => false])
->addColumn('date', 'date', ['null' => false])
->addColumn('type', 'integer', ['length' => 3, 'null' => false, 'default' => 0])
->addForeignKey('reservation_id', 'reservations', 'id', ['delete' => 'cascade', 'update' => 'cascade'])
->addForeignKey('reservation_id', 'reservation', 'id', ['delete' => 'cascade', 'update' => 'cascade'])
->create();
$this->execute('SET unique_checks=1; SET foreign_key_checks=1;');

View File

@ -1,29 +0,0 @@
<?php
declare(strict_types=1);
use Phinx\Migration\AbstractMigration;
final class AddCommentsToEstadoCierre extends AbstractMigration
{
/**
* Change Method.
*
* Write your reversible migrations using this method.
*
* More information on writing migrations is available here:
* https://book.cakephp.org/phinx/0/en/migrations.html#the-change-method
*
* Remember to call "create()" or "update()" and NOT "save()" when working
* with the Table class.
*/
public function change(): void
{
$this->table('estado_cierre_comentarios')
->addColumn('estado_cierre_id', 'integer', ['signed' => false])
->addColumn('fecha', 'datetime', ['default' => 'CURRENT_TIMESTAMP'])
->addColumn('comments', 'text')
->addForeignKey('estado_cierre_id', 'estado_cierre', 'id', ['delete' => 'cascade', 'update' => 'cascade'])
->create();
}
}

View File

@ -1,7 +0,0 @@
<?php
use Incoviba\Controller\API\Personas;
//$app->group('/personas', function($app) {});
$app->group('/persona/{rut}', function($app) {
$app->get('[/]', [Personas::class, 'get']);
});

View File

@ -30,5 +30,4 @@ $app->group('/proyecto/{proyecto_id}', function($app) {
$app->post('/edit[/]', [Proyectos::class, 'terreno']);
});
$app->get('/brokers', [Proyectos::class, 'brokers']);
$app->get('/promotions', [Proyectos::class, 'promotions']);
});

View File

@ -2,6 +2,7 @@
use Incoviba\Controller\API\Ventas\Precios;
$app->group('/precios', function($app) {
$app->post('/import[/]', [Precios::class, 'import']);
$app->post('[/]', [Precios::class, 'proyecto']);
});
$app->group('/precio', function($app) {

View File

@ -3,11 +3,6 @@ use Incoviba\Controller\API\Ventas\Reservations;
$app->group('/reservations', function($app) {
$app->post('/add[/]', [Reservations::class, 'add']);
$app->group('/project/{project_id}', function($app) {
$app->get('/active[/]', [Reservations::class, 'active']);
$app->get('/pending[/]', [Reservations::class, 'pending']);
$app->get('/rejected[/]', [Reservations::class, 'rejected']);
});
$app->get('[/]', Reservations::class);
});
$app->group('/reservation/{reservation_id}', function($app) {

View File

@ -1,6 +1,5 @@
<?php
//use Incoviba\Controller\Ventas\Cierres;
use Incoviba\Controller\Ventas\Reservations as Cierres;
use Incoviba\Controller\Ventas\Cierres;
$app->group('/cierres', function($app) {
$app->get('[/]', Cierres::class);

View File

@ -2,5 +2,5 @@
use Incoviba\Controller\Ventas\Precios;
$app->group('/precios', function($app) {
$app->get('[/]', Precios::class);
$app->get('[/{project_id}[/]]', Precios::class);
});

View File

@ -24,6 +24,9 @@
<button class="ui tiny green icon button" id="add_button">
<i class="plus icon"></i>
</button>
<button class="ui tiny green icon button" id="import_button">
<i class="upload icon"></i>
</button>
</div>
</div>
</h4>
@ -31,6 +34,7 @@
<table class="ui table" id="list_data"></table>
</div>
</div>
@include('ventas.precios.modal.import')
<div class="ui modal" id="list_modal">
<div class="header">
Actualizar <span id="modal_title"></span>
@ -97,7 +101,8 @@
return this.precio / this.superficie
}
draw(formatter) {
const date = new Date(this.fecha)
const dateParts = this.fecha.split('-')
const date = new Date(dateParts[0], dateParts[1] - 1, dateParts[2])
const dateFormatter = new Intl.DateTimeFormat('es-CL')
return $('<tr></tr>').addClass('unidad').attr('data-linea', this.linea).append(
$('<td></td>').html(this.nombre)
@ -317,7 +322,8 @@
buttons: {
add: '',
up: '',
refresh: ''
refresh: '',
import: ''
}
},
data: {
@ -330,6 +336,11 @@
loading: {
precios: false
},
components: {
modals: {
import: null
}
},
get: function() {
return {
proyectos: () => {
@ -378,6 +389,24 @@
}
}
},
url() {
return {
proyectos: () => {
const currentUrl = window.location.href
const newUrl = `{{ $urls->base }}/ventas/precios`
if (newUrl !== currentUrl) {
window.history.replaceState(null, null, newUrl)
}
},
precios: proyecto_id => {
const currentUrl = window.location.href
const newUrl = `{{ $urls->base }}/ventas/precios/${proyecto_id}`
if (newUrl !== currentUrl) {
window.history.replaceState(null, null, newUrl)
}
}
}
},
add: function() {
return {
precio: data => {
@ -400,6 +429,7 @@
draw: function() {
return {
proyectos: () => {
this.url().proyectos()
const parent = $(this.ids.list)
const header = parent.find('#list_title')
const list = parent.find('.list')
@ -408,6 +438,7 @@
$(this.ids.buttons.add).hide()
$(this.ids.buttons.add).attr('data-id', '')
$(this.ids.buttons.add).attr('data-proyecto', '')
$(`#${this.ids.buttons.import}`).hide()
header.html('Proyectos')
table.hide()
@ -415,7 +446,8 @@
this.data.proyectos.forEach(proyecto => {
list.append(
$('<div></div>').addClass('item proyecto').attr('data-proyecto', proyecto.id).html(proyecto.descripcion).css('cursor', 'pointer')
$('<div></div>').addClass('item proyecto').attr('data-proyecto', proyecto.id)
.html(proyecto.descripcion).css('cursor', 'pointer')
)
})
list.show()
@ -431,6 +463,7 @@
})
},
precios: () => {
this.url().precios(this.data.id)
const parent = $(this.ids.list)
const header = parent.find('#list_title')
const list = parent.find('.list')
@ -440,6 +473,8 @@
$(this.ids.buttons.add).attr('data-proyecto', this.data.proyecto)
$(this.ids.buttons.add).show()
$(`#${this.ids.buttons.import}`).show()
header.html('Precios de ' + this.data.proyecto)
list.hide()
table.html('')
@ -581,18 +616,27 @@
}
}
},
import: event => {
event.preventDefault()
precios.components.modals.import.show(this.data.id)
return false
}
}
},
setup: function({list, proyectos, buttons_up, buttons_refresh, buttons_add}) {
setup: function({list, proyectos, buttons_up, buttons_refresh, buttons_add, buttons_import}) {
this.ids.list = list
this.ids.proyectos = proyectos
this.ids.buttons.up = buttons_up
this.ids.buttons.refresh = buttons_refresh
this.ids.buttons.add = buttons_add
this.ids.buttons.import = buttons_import
$(this.ids.buttons.up).click(this.actions().up)
$(this.ids.buttons.refresh).click(this.actions().refresh)
$(this.ids.buttons.add).click(this.actions().add().list)
document.getElementById(this.ids.buttons.import).addEventListener('click', this.actions().import)
this.components.modals.import = new ImportModal()
this.draw().proyectos()
}
@ -674,6 +718,10 @@
$(this.ids.button).click(this.actions().send)
}
}
function selectProject(projectId) {
const $project = $(`.item.proyecto[data-proyecto="${projectId}"]`)
$project.click()
}
$(document).ready(() => {
precios.setup({
@ -681,7 +729,8 @@
proyectos: '#proyectos',
buttons_up: '#up_button',
buttons_refresh: '#refresh_button',
buttons_add: '#add_button'
buttons_add: '#add_button',
buttons_import: 'import_button'
})
list_modal.setup({
modal: '#list_modal',
@ -692,6 +741,10 @@
fields_valor: '#valor',
button: '#send'
})
@if (isset($project_id))
selectProject({{$project_id}})
@endif
})
</script>
@endpush

View File

@ -0,0 +1,120 @@
<div class="ui modal" id="import_modal">
<div class="header">
Importar Precios
</div>
<div class="content">
<div class="ui form">
<input type="hidden" id="import_project_id" name="import_project_id" value="" />
<div class="three wide field">
<div class="ui calendar" id="import_date">
<div class="ui left icon input">
<i class="calendar icon"></i>
<input type="text" name="fecha" />
</div>
</div>
</div>
<input class="ui invisible file input" type="file" id="import_file" name="file" />
<label class="ui placeholder segment" for="import_file">
<div class="ui icon header">
<i class="upload icon"></i>
Archivo de Precios
</div>
</label>
</div>
</div>
<div class="actions">
<div class="ui red cancel icon button">
<i class="remove icon"></i>
</div>
<div class="ui green ok icon button">
<i class="checkmark icon"></i>
Importar
</div>
</div>
@push('page_scripts')
<script>
class ImportModal {
ids = {
modal: '',
project: '',
calendar: '',
file: ''
}
components = {
$modal: null,
form: null,
project: null,
$calendar: null,
file: null,
$file: null
}
constructor() {
this.ids.modal = 'import_modal'
this.ids.project = 'import_project_id'
this.ids.calendar = 'import_date'
this.ids.file = 'import_file'
this.setup()
}
show(project_id) {
this.components.project.value = project_id
this.components.$modal.modal('show')
}
dragDrop(event) {
event.preventDefault()
if (event.originalEvent.dataTransfer && event.originalEvent.dataTransfer.files.length > 0) {
this.components.file.files = event.originalEvent.dataTransfer.files
}
}
import() {
const url = '{{ $urls->api }}/ventas/precios/import'
const method = 'post'
const body = new FormData()
body.set('project_id', this.components.project.value)
const date = this.components.$calendar.calendar('get date')
body.set('date', [date.getFullYear(), date.getMonth() + 1, date.getDate()].join('-'))
body.set('file', this.components.file.files[0])
APIClient.fetch(url, {method, body}).then(response => response.json()).then(json => {
if (json.status === true) {
window.location.reload()
return
}
console.debug(json)
})
}
setup() {
this.components.$modal = $(`#${this.ids.modal}`)
this.components.$modal.modal({
onApprove: () => {
this.import()
}
})
this.components.form = this.components.$modal.find('form')
this.components.form.submit(event => {
event.preventDefault()
this.import()
return false
})
this.components.project = document.getElementById(this.ids.project)
this.components.$calendar = $(`#${this.ids.calendar}`)
const cdo = structuredClone(calendar_date_options)
cdo['maxDate'] = new Date()
this.components.$calendar.calendar(cdo)
this.components.file = document.getElementById(this.ids.file)
this.components.$file = $(this.components.file.parentNode.querySelector('label'))
this.components.$file.css('cursor', 'pointer')
this.components.$file.on('dragover', event => {
event.preventDefault()
event.stopPropagation()
})
this.components.$file.on('dragenter', event => {
event.preventDefault()
event.stopPropagation()
})
this.components.$file.on('drop', this.dragDrop.bind(this))
}
}
</script>
@endpush

View File

@ -1,554 +0,0 @@
@extends('layout.base')
@section('page_title')
Cierres -Reservas
@endsection
@section('page_content')
<div class="ui container">
<h2 class="ui header">Cierres - Reservas</h2>
<div class="ui compact segment" id="projects">
<div class="ui header">Proyectos</div>
@if (count($projects) == 0)
<div class="ui message">
No hay proyectos en venta.
</div>
@else
<div class="ui link list">
@foreach ($projects as $project)
<div class="item link" data-id="{{ $project->id }}">
{{ $project->descripcion }}
</div>
@endforeach
</div>
@endif
</div>
<div class="ui two column grid">
<div class="column">
<h3 class="ui header" id="project"></h3>
</div>
<div class="column">
<div class="ui active inline loader" id="loader"></div>
</div>
</div>
<div id="results">
<div class="ui right aligned top attached basic segment" id="controls">
<div class="ui tiny icon buttons">
<button class="ui button" id="up_button">
<i class="up arrow icon"></i>
</button>
<button class="ui button" id="refresh_button">
<i class="refresh icon"></i>
</button>
<button class="ui green icon button" id="add_button">
<i class="plus icon"></i>
</button>
</div>
</div>
<div class="ui top attached tabular menu" id="tabs">
<div class="yellow active item" data-tab="pending">Pendientes</div>
<div class="green item" data-tab="active">Activas</div>
<div class="red item" data-tab="rejected">Rechazadas</div>
</div>
<div class="ui bottom attached tab fitted segment active" data-tab="pending">
<table class="ui yellow striped table" id="pending_reservations">
<thead>
<tr>
<th>Unidades</th>
<th>Cliente</th>
<th>Fecha</th>
<th>Oferta</th>
<th>¿Valida?</th>
<th>Operador</th>
<th></th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<div class="ui bottom attached tab fitted segment" data-tab="active">
<table class="ui green striped table" id="active_reservations">
<thead>
<tr>
<th>Unidades</th>
<th>Cliente</th>
<th>Fecha</th>
<th>Oferta</th>
<th>Operador</th>
<th></th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<div class="ui bottom attached tab fitted segment" data-tab="rejected">
<table class="ui red striped table" id="rejected_reservations">
<thead>
<tr>
<th>Unidades</th>
<th>Cliente</th>
<th>Fecha</th>
<th>Oferta</th>
<th>Estado</th>
<th>Operador</th>
<th>Comentarios</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
</div>
@include('ventas.reservations.add_modal')
@endsection
@push('page_styles')
<style>
.item.link {
cursor: pointer;
text-decoration: underline;
}
</style>
@endpush
@push('page_scripts')
<script>
class Projects {
display = {
projects: '',
project: ''
}
component_id = ''
component = null
current_project = null;
title_id = ''
title_component = null
constructor({component_id, title_id}) {
this.component_id = component_id
this.component = document.getElementById(this.component_id)
this.display.projects = this.component.style.display
this.title_id = title_id
this.title_component = document.getElementById(this.title_id)
this.display.project = this.title_component.style.display
this.show()
this.watch()
}
select(event) {
event.preventDefault()
const project_id = event.currentTarget.dataset.id
reservations.show.results()
if (project_id === this.current_project) {
this.hide()
this.title_component.innerHTML = event.currentTarget.innerHTML
reservations.action.reservations()
return
}
this.current_project = project_id
reservations.get.reservations(project_id)
reservations.components.modals.add.load(project_id)
this.hide()
this.title_component.innerHTML = event.currentTarget.innerHTML
}
watch() {
this.component.querySelectorAll('.item.link').forEach(item => {
item.addEventListener('click', this.select.bind(this))
})
}
show() {
this.component.style.display = this.display.projects
this.title_component.style.display = 'none'
}
hide() {
this.component.style.display = 'none'
this.title_component.style.display = this.display.project
}
}
class Controls {
display = {
up: '',
reset: '',
}
component_id = ''
component = null
buttons = {
up: null,
reset: null,
add: null
}
constructor({component_id}) {
this.component_id = component_id
this.component = document.getElementById(this.component_id)
const buttons = this.component.querySelectorAll('button')
this.buttons.up = buttons[0]
this.buttons.reset = buttons[1]
this.buttons.add = buttons[2]
this.display.up = buttons[0].style.display
this.display.reset = buttons[1].style.display
this.watch()
this.hide()
}
watch() {
Object.entries(this.buttons).forEach(([key, value]) => {
const name = key.replace('_button', '')
value.addEventListener('click', this.action[name].bind(this))
})
}
hide() {
this.buttons.up.style.display = this.display.up
this.buttons.reset.style.display = this.display.reset
}
show() {
this.buttons.up.style.display = 'none'
this.buttons.reset.style.display = 'none'
}
action = {
reset: event => {
event.preventDefault()
reservations.action.reset(event)
return false
},
up: event => {
event.preventDefault()
reservations.action.up(event)
return false
},
add: event => {
event.preventDefault()
reservations.action.add(event)
return false
}
}
}
class Reservations {
display = {
reservations: '',
}
component_id = ''
component = null
formatters = {
date: null,
ufs: null
}
columnNames = []
reservations = []
constructor({component_id, formatters = {date, ufs}}) {
this.component_id = component_id
this.component = document.getElementById(this.component_id)
this.display.reservations = this.component.style.display
this.formatters = formatters
this.set().columnNames()
this.hide()
}
set() {
return {
reservations: reservations => {
this.reservations = reservations
return this
},
columnNames: () => {
const tds = this.component.querySelector('thead tr').querySelectorAll('th')
this.columnNames = []
tds.forEach(td => {
let name = td.innerHTML.toLowerCase()
if (name === '') {
return
}
if (name.includes('?')) {
name = name.replaceAll(/[¿?]/g, '')
}
this.columnNames.push(name)
})
return this
}
}
}
columnsData() {
return this.reservations.map(reservation => {
const date = new Date(Date.parse(reservation.fecha) + 24 * 60 * 60 * 1000)
return {
id: reservation.id,
unidades: reservation.summary,
cliente: reservation.buyer.nombreCompleto,
fecha: this.formatters.date.format(date),
oferta: `${this.formatters.ufs.format(reservation.offer)} UF`,
valida: reservation.valid ? '<span class="ui green text">Si</span>' : '<span class="ui red text">No</span>',
operador: reservation.broker?.name ?? '',
}
})
}
draw() {
const tbody = this.component.querySelector('tbody')
tbody.innerHTML = ''
this.columnsData().forEach(column => {
const tr = document.createElement('tr')
const contents = []
const id = column.id
this.columnNames.forEach(name => {
contents.push(`<td>${column[name]}</td>`)
})
const actions = this.drawActions(id)
if (actions !== '') {
contents.push(actions)
}
tr.innerHTML = contents.join("\n")
tbody.appendChild(tr)
})
this.show()
}
drawActions(id) {
return `
<td class="right aligned">
<button class="ui green mini icon button approve" data-id="${id}" title="Aprobar">
<i class="check icon"></i>
</button>
<button class="ui red mini icon button reject" data-id="${id}" title="Rechazar">
<i class="trash icon"></i>
</button>
</td>`
}
empty() {
const tbody = this.component.querySelector('tbody')
tbody.innerHTML = ''
const col_span = this.columnNames.length + 1
const tr = document.createElement('tr')
tr.innerHTML = `<td colspan="${col_span}">No hay cierres</td>`
tbody.appendChild(tr)
this.show()
}
show() {
this.component.style.display = this.display.reservations
}
hide() {
this.component.style.display = 'none'
}
}
class ActiveReservations extends Reservations {
constructor({component_id, formatters = {date, ufs}}) {
super({component_id, formatters})
}
columnsData() {
const data = super.columnsData();
return data.map(row => {
delete(row['valida'])
return row
})
}
drawActions(id) {
return `
<td class="right aligned">
<button class="ui green mini icon button edit" data-id="${id}" title="Promesar">
<i class="right chevron icon"></i>
</button>
<button class="ui red mini icon button remove" data-id="${id}" title="Abandonar">
<i class="trash icon"></i>
</button>
</td>`
}
}
class PendingReservations extends Reservations {
constructor({component_id, formatters = {date, ufs}}) {
super({component_id, formatters})
}
}
class RejectedReservations extends Reservations {
constructor({component_id, formatters = {date, ufs}}) {
super({component_id, formatters})
}
columnsData() {
const data = super.columnsData()
return this.reservations.map((reservation, idx) => {
data[idx]['estado'] = reservation.state.charAt(0).toUpperCase() + reservation.state.slice(1)
data[idx]['comentarios'] = reservation.comments?.join('<br />\n') ?? ''
return data[idx]
})
}
drawActions(id) {
return ''
}
}
const reservations = {
components: {
projects: null,
loader: null,
results: null,
controls: null,
reservations: {
active: null,
pending: null,
rejected: null
},
modals: {
add: null
}
},
display: {
loader: '',
results: '',
},
get: {
send: (project_id, url_segment, component) => {
const url = `/api/ventas/reservations/project/${project_id}/${url_segment}`
return APIClient.fetch(url).then(response => response.json()).then(json => {
if (json.reservations.length === 0) {
component.empty()
return
}
component.set().reservations(json.reservations).draw()
})
},
active: project_id => {
return reservations.get.send(project_id, 'active', reservations.components.reservations.active)
/*const url = `/ventas/reservations/project/${project_id}/active`
return APIClient.fetch(url).then(json => {
if (json.reservations.length === 0) {
return
}
this.components.reservations.active.set().reservations(json.reservations).draw()
})*/
},
pending: project_id => {
return reservations.get.send(project_id, 'pending', reservations.components.reservations.pending)
/*const url = `/ventas/reservations/project/${project_id}/pending`
return APIClient.fetch(url).then(json => {
if (json.reservations.length === 0) {
return
}
this.components.reservations.pending.set().reservations(json.reservations).draw()
})*/
},
rejected: project_id => {
return reservations.get.send(project_id, 'rejected', reservations.components.reservations.rejected)
/*const url = `/ventas/reservations/project/${project_id}/rejected`
return APIClient.fetch(url).then(json => {
if (json.reservations.length === 0) {
return
}
this.components.reservations.rejected.set().reservations(json.reservations).draw()
})*/
},
reservations: project_id => {
reservations.loading.show()
const promises = []
promises.push(reservations.get.active(project_id))
promises.push(reservations.get.pending(project_id))
promises.push(reservations.get.rejected(project_id))
return Promise.any(promises).then(() => {
reservations.loading.hide()
})
}
},
loading: {
show: () => {
reservations.components.loader.style.display = reservations.display.loader
},
hide: () => {
reservations.components.loader.style.display = 'none'
}
},
action: {
reset: event => {
event.preventDefault()
reservations.components.projects.current_project = null
Object.entries(reservations.components.reservations).forEach(([key, value]) => {
reservations.components.reservations[key].reservations = []
reservations.components.reservations[key].hide()
})
reservations.show.projects()
return false
},
up: event => {
event.preventDefault()
Object.values(reservations.components.reservations).forEach(reservations => reservations.hide())
reservations.show.projects()
return false
},
add: event => {
event.preventDefault()
reservations.components.modals.add.show()
return false
},
reservations: () => {
Object.values(reservations.components.reservations).forEach(reservations => {
reservations.draw()
})
}
},
show: {
projects: () => {
reservations.components.projects.show()
reservations.components.results.style.display = 'none'
},
results: () => {
reservations.components.projects.hide()
reservations.components.results.style.display = reservations.display.results
}
},
setup(configuration) {
const formatters = {
date: new Intl.DateTimeFormat('es-CL', {year: 'numeric', month: 'long', day: 'numeric'}),
ufs: new Intl.NumberFormat('es-CL', {minimumFractionDigits: 2, maximumFractionDigits: 2})
}
this.components.loader = document.getElementById(configuration.ids.loader)
this.components.projects = new Projects({component_id: configuration.ids.projects, title_id: configuration.ids.project})
this.components.controls = new Controls({component_id: configuration.ids.controls})
this.components.reservations.active = new ActiveReservations({component_id: configuration.ids.active, formatters})
this.components.reservations.pending = new PendingReservations({component_id: configuration.ids.pending, formatters})
this.components.reservations.rejected = new RejectedReservations({component_id: configuration.ids.rejected, formatters})
this.display.loader = this.components.loader.style.display
this.loading.hide()
$(`#${configuration.ids.tabs} .item`).tab()
this.components.results = document.getElementById(configuration.ids.results)
this.display.results = this.components.results.style.display
this.show.projects()
this.components.modals.add = new AddReservationModal()
}
}
$(document).ready(() => {
reservations.setup({
ids: {
projects: 'projects',
project: 'project',
results: 'results',
loader: 'loader',
controls: 'controls',
tabs: 'tabs',
active: 'active_reservations',
pending: 'pending_reservations',
rejected: 'rejected_reservations',
}
})
})
</script>
@endpush

View File

@ -1,733 +0,0 @@
<div class="ui modal" id="add_reservation_modal">
<div class="header">
Agregar Cierre
</div>
<div class="content">
<form class="ui form" id="add_reservation_form">
<input type="hidden" name="project_id" />
<div class="three wide required field">
<label>Fecha</label>
<div class="ui calendar" id="add_date">
<div class="ui icon input">
<i class="calendar icon"></i>
<input type="text" name="date" />
</div>
</div>
</div>
<div class="fields">
<div class="three wide required field">
<label>RUT</label>
<div class="ui right labeled input" id="add_rut">
<input type="text" name="rut" placeholder="RUT" />
<div class="ui basic label">-<span id="add_digit"></span></div>
</div>
</div>
<div class="field">
<label></label>
<div class="ui inline loader" id="add_rut_loader"></div>
</div>
</div>
<div class="fields">
<div class="three wide required field">
<label>Nombre</label>
<input type="text" name="name" placeholder="Nombre" />
</div>
<div class="six wide required field">
<label>Apellidos</label>
<input type="text" name="last_name" placeholder="Apellido Paterno" />
</div>
<div class="six wide field">
<label></label>
<input type="text" name="last_name2" placeholder="Apellido Materno" />
</div>
</div>
<div class="fields">
<div class="three wide field">
<label>Dirección</label>
<input type="text" name="calle" placeholder="Calle" />
</div>
<div class="field">
<label></label>
<input type="text" name="numero" placeholder="" />
</div>
<div class="three wide field">
<label></label>
<input type="text" name="extra" placeholder="Otros Detalles" />
</div>
</div>
<div class="fields">
<div class="three wide field">
<label>Comuna</label>
<div class="ui search selection dropdown" id="add_comuna">
<input type="hidden" name="comuna" />
<i class="dropdown icon"></i>
<div class="default text">Comuna</div>
<div class="menu"></div>
</div>
</div>
<div class="seven wide field">
<label>Región</label>
<div class="ui search selection dropdown" id="add_region">
<input type="hidden" name="region" />
<i class="dropdown icon"></i>
<div class="default text">Región</div>
<div class="menu">
@foreach($regions as $region)
<div class="item" data-value="{{$region->id}}">{{$region->numeral}} - {{$region->descripcion}}</div>
@endforeach
</div>
</div>
</div>
</div>
<div class="fields">
<div class="field">
<label>Telefono</label>
<input type="text" name="phone" placeholder="Telefono" />
</div>
<div class="field">
<label>Correo</label>
<div class="ui labeled input">
<input type="text" name="email_name" placeholder="Correo" />
<div class="ui basic label">@</div>
<input type="text" name="email_domain" placeholder="Dominio" />
</div>
</div>
</div>
<div class="fields">
<div class="field">
<label>Estado Civil</label>
<input type="text" name="civil_status" placeholder="Estado Civil" />
</div>
<div class="field">
<label>Profesión</label>
<input type="text" name="profession" placeholder="Profesión" />
</div>
<div class="field">
<label>Fecha de Nacimiento</label>
<div class="ui calendar" id="add_birthdate">
<div class="ui icon input">
<i class="calendar icon"></i>
<input type="text" name="birthdate" />
</div>
</div>
</div>
</div>
<div class="six wide field">
<label>Operador *</label>
<div class="ui clearable search selection dropdown" id="add_broker">
<input type="hidden" name="broker" />
<i class="dropdown icon"></i>
<div class="default text">Operador</div>
<div class="menu"></div>
</div>
</div>
<div class="field">
<label>Agregar Promoción</label>
<button type="button" class="ui icon button" id="add_promotion">
<i class="plus icon"></i>
</button>
</div>
<div id="add_promotions"></div>
<h4 class="ui dividing header">Unidades</h4>
<div class="fields" id="add_unit_buttons"></div>
<div id="add_units"></div>
</form>
</div>
<div class="actions">
<div class="ui cancel button">
Cancelar
</div>
<div class="ui green ok button">
Agregar
</div>
</div>
</div>
@include('layout.body.scripts.rut')
@push('page_scripts')
<script>
class AddModalPromotions {
ids = {
button: '',
elements: ''
}
data = {
promotions: []
}
components = {
button: null,
promotions: null,
}
display = {
button: ''
}
constructor() {
this.ids = {
button: 'add_promotion',
elements: 'add_promotions'
}
this.setup()
}
add() {
const idx = Math.max(this.data.promotions.length, 0, Math.max(...this.data.promotions) + 1)
this.data.promotions.push(idx)
this.draw.promotions()
}
reset() {
this.data.promotions = []
this.draw.promotions()
}
remove(idx) {
this.data.promotions = this.data.promotions.filter(promotion => promotion !== idx)
this.draw.promotions()
}
draw = {
promotion: idx => {
const promotions = this.data.promotions.map(promotion => {
return `<div class="item" data-value="${promotion.id}">${promotion.name}</div>`
})
return [
`<div class="fields promotion" data-id="${idx}">`,
'<div class="three wide field">',
'<label>Promoción</label>',
`<div class="ui search selection dropdown">`,
'<input type="hidden" name="promotions[]" />',
'<i class="dropdown icon"></i>',
'<div class="default text">Promoción</div>',
`<div class="menu">${promotions.join('')}</div>`,
'</div>',
'</div>',
'<div class="two wide field">',
'<label></label>',
`<button class="ui red tiny icon button remove_promotion" type="button" data-id="${idx}"><i class="trash icon"></i></button>`,
'</div>',
'</div>'
].join('')
},
promotions: () => {
if (this.data.promotions.length === 0) {
this.components.button.parentElement.style.display = 'none'
this.components.promotions.innerHTML = ''
return
}
this.components.button.parentElement.style.display = this.display.button
this.components.promotions.innerHTML = this.data.promotions.map((promotion, idx) => {
return this.draw.promotion(idx)
}).join('')
this.components.promotions.querySelectorAll('.dropdown').forEach(dropdown => {
$(dropdown).dropdown()
})
this.components.promotions.querySelectorAll('.remove_promotion').forEach(button => {
button.addEventListener('click', () => {
const idx = Number(button.dataset.id)
this.remove(idx)
})
})
}
}
setup() {
this.components.button = document.getElementById(this.ids.button)
this.components.promotions = document.getElementById(this.ids.elements)
this.components.button.addEventListener('click', () => {
this.add()
})
this.display.button = this.components.button.parentElement.style.display
this.draw.promotions()
}
}
class AddModalUnits {
ids = {
buttons_holder: '',
units: ''
}
data = {
button_map: {},
types: {},
units: [],
}
components = {
buttons_holder: null,
units: null,
}
constructor() {
this.ids = {
buttons_holder: 'add_unit_buttons',
units: 'add_units'
}
this.data.button_map = {
'departamento': 'building',
'estacionamiento': 'car',
'bodega': 'warehouse',
'terraza': 'vector square'
}
this.setup()
}
draw = {
button: type => {
return [
'<div class="field">',
`<button class="ui icon button" type="button" data-type="${type}" title="${type.charAt(0).toUpperCase() + type.slice(1)}">`,
'<i class="plus icon"></i>',
`<i class="${this.data.button_map[type]} icon"></i>`,
'</button>',
'</div>'
].join('')
},
buttons: () => {
this.components.buttons_holder.innerHTML = Object.keys(this.data.types).map(type => {
return this.draw.button(type)
}).join('')
this.components.buttons_holder.querySelectorAll('.button').forEach(button => {
button.addEventListener('click', () => {
const type = button.dataset.type
this.add(type)
})
})
},
units: () => {
if (this.data.units.length === 0) {
this.components.units.innerHTML = ''
return
}
this.components.units.innerHTML = this.data.units.map(unit => {
return [
'<div class="fields">',
'<div class="four wide field">',
`<label>${unit.type.charAt(0).toUpperCase() + unit.type.slice(1)}</label>`,
`<div class="ui search selection dropdown">`,
'<input type="hidden" name="units[]" />',
'<i class="dropdown icon"></i>',
`<div class="default text">${unit.type.charAt(0).toUpperCase() + unit.type.slice(1)}</div>`,
'<div class="menu">',
this.data.types[unit.type].map(unit => {
return `<div class="item" data-value="${unit.value}">${unit.name}</div>`
}).join(''),
'</div>',
'</div>',
'</div>',
'<div class="field">',
'<label></label>',
`<button class="ui red tiny icon button remove_unit" type="button" data-id="${unit.idx}"><i class="trash icon"></i></button>`,
'</div>',
'</div>',
].join('')
}).join('')
this.components.units.querySelectorAll('.dropdown').forEach(dropdown => {
$(dropdown).dropdown()
})
this.components.units.querySelectorAll('.remove_unit').forEach(button => {
button.addEventListener('click', () => {
const idx = Number(button.dataset.id)
this.remove(idx)
})
})
}
}
reset() {
this.data.units = []
this.draw.units()
}
add(type) {
const idx = Math.max(this.data.units.length, 0, Math.max(...this.data.units.map(unit => unit.idx)) + 1)
this.data.units.push({idx, type})
this.draw.units()
}
remove(idx) {
this.data.units = this.data.units.filter(unit => unit.idx !== idx)
this.draw.units()
}
setup() {
this.components.buttons_holder = document.getElementById(this.ids.buttons_holder)
this.components.units = document.getElementById(this.ids.units)
this.draw.buttons()
}
}
class AddReservationModal {
ids = {
modal: '',
form: '',
date: '',
rut: '',
digit: '',
birthdate: '',
comuna: '',
region: '',
broker: '',
promotion_button: '',
promotions: '',
unit_buttons: '',
units: ''
}
components = {
$modal: null,
form: null,
$date: null,
$rut: null,
rut: null,
digit: null,
$birthdate: null,
$comuna: null,
$region: null,
$broker: null,
promotion_button: null,
promotions: null,
unit_buttons: null,
units: null,
$loader: null
}
data = {
current_project: null,
comunas: {},
brokers: {},
promotions: {},
unit_buttons: [],
units: {},
added_units: {},
current_user: null
}
maps = {
unit_types: {
departamento: 'building',
estacionamiento: 'car',
bodega: 'warehouse',
terraza: 'tree',
}
}
constructor() {
this.ids = {
modal: 'add_reservation_modal',
form: 'add_reservation_form',
date: 'add_date',
rut: 'add_rut',
digit: 'add_digit',
birthdate: 'add_birthdate',
comuna: 'add_comuna',
region: 'add_region',
broker: 'add_broker',
promotion_button: 'add_promotion',
promotions: 'add_promotions',
unit_buttons: 'add_unit_buttons',
units: 'add_units',
loader: 'add_rut_loader'
}
this.setup()
}
load(project_id) {
this.reset()
this.data.current_project = project_id
this.components.form.querySelector('input[name="project_id"]').value = project_id
this.get.brokers(project_id)
this.get.promotions(project_id).then(promotions => {
this.components.promotions.data.promotions = promotions
this.components.promotions.draw.promotions()
})
this.get.units(project_id).then(units => {
this.components.units.data.types = units
this.components.units.draw.buttons()
})
}
reset() {
this.components.form.reset()
this.components.promotions.reset()
this.components.units.reset()
}
add() {
const url = '/api/ventas/reservations/add'
const form = document.getElementById(this.ids.form)
const body = new FormData(form)
const date = this.components.$date.calendar('get date')
console.debug(date)
body.set('date', [date.getFullYear(), date.getMonth() + 1, date.getDate()].join('-'))
body.set('comuna', this.components.$comuna.dropdown('get value'))
body.set('region', this.components.$region.dropdown('get value'))
body.set('broker_rut', this.components.$broker.dropdown('get value'))
/*body.set('promotions[]', '')
this.components.promotions.forEach(promotion => {
body.append('promotions[]', promotion.querySelector('promotion').value)
})*/
/*body.set('units[]', '')
this.components.units.forEach(unit => {
body.append('units[]', unit.querySelector('unit').value)
})*/
const method = 'post'
return APIClient.fetch(url, {method, body}).then(response => response.json()).then(json => {
if (json.success) {
window.location.reload()
}
})
}
get = {
comunas: region_id => {
if (region_id in this.data.comunas) {
this.components.$comuna.dropdown('change values', this.data.comunas[region_id])
if (this.data.current_user !== null && this.data.current_user?.direccion?.comuna !== null) {
this.components.$comuna.dropdown('set selected', this.data.current_user.direccion.comuna.id)
}
return
}
const uri = `/api/region/${region_id}/comunas`
return APIClient.fetch(uri).then(response => response.json()).then(json => {
if (json.comunas.length === 0) {
return
}
this.data.comunas[region_id] = json.comunas.map(comuna => {
return {
text: comuna.descripcion,
name: comuna.descripcion,
value: comuna.id
}
})
this.components.$comuna.dropdown('change values', this.data.comunas[region_id])
if (this.data.current_user !== null && this.data.current_user?.direccion?.comuna !== null) {
this.components.$comuna.dropdown('set selected', this.data.current_user.direccion.comuna.id)
}
})
},
brokers: project_id => {
if (project_id in this.data.brokers) {
return new Promise((resolve, reject) => {
resolve(this.data.brokers[project_id])
})
}
const uri = `/api/proyecto/${project_id}/brokers`
return APIClient.fetch(uri).then(response => response.json()).then(json => {
if (json.contracts.length === 0) {
return
}
const formatter = new Intl.NumberFormat('es-CL', { style: 'percent', minimumFractionDigits: 2 })
this.data.brokers[project_id] = json.contracts.map(contract => {
return {
id: contract.id,
broker_rut: contract.broker_rut,
commission: formatter.format(contract.commission),
name: '',
text: '',
}
})
const promises = []
json.contracts.forEach(contract => {
promises.push(this.get.broker(contract.broker_rut))
})
return Promise.all(promises).then(data => {
data.forEach(broker => {
if (!('rut' in broker)) {
return
}
const idx = this.data.brokers[project_id].findIndex(contract => contract.broker_rut === broker.rut)
this.data.brokers[project_id][idx].name = this.data.brokers[project_id][idx].text = `${broker.name} - ${this.data.brokers[project_id][idx].commission}`
})
this.fill.brokers()
})
})
},
broker: (broker_rut) => {
const uri = `/api/proyectos/broker/${broker_rut}`
return APIClient.fetch(uri).then(response => response.json()).then(json => {
if (!('broker' in json)) {
return []
}
return json.broker
})
},
promotions: project_id => {
if (project_id in this.data.promotions) {
return new Promise((resolve, reject) => {
resolve(this.data.promotions[project_id])
})
}
const uri = `/api/proyecto/${project_id}/promotions`
return APIClient.fetch(uri).then(response => response.json()).then(json => {
if (json.promotions.length === 0) {
return this.data.promotions[project_id] = []
}
return this.data.promotions[project_id] = json.promotions.map(promotion => {
return {
text: promotion.name,
name: promotion.name,
value: promotion.id
}
})
})
},
units: project_id => {
if (project_id in this.data.units) {
return new Promise((resolve, reject) => {
resolve(this.data.units[project_id])
})
}
const uri = `/api/proyecto/${project_id}/unidades`
return APIClient.fetch(uri).then(response => response.json()).then(json => {
if (json.total === 0) {
this.data.units[project_id] = {}
return this.data.units[project_id]
}
if (!(project_id in this.data.units)) {
this.data.units[project_id] = {}
}
Object.entries(json.unidades).forEach(([type, units]) => {
if (!(type in this.data.units[project_id])) {
this.data.units[project_id][type] = []
}
units.forEach(unit => {
this.data.units[project_id][type].push({
text: unit.descripcion,
name: unit.descripcion,
value: unit.id
})
})
})
return this.data.units[project_id]
})
},
user: rut => {
if (this.data.current_user !== null && this.data.current_user?.rut === rut) {
return this.data.current_user
}
this.loader.show()
const uri = `/api/persona/${rut}`
return APIClient.fetch(uri).then(response => response.json()).then(json => {
this.loader.hide()
if (!json.success) {
return
}
this.data.current_user = json.persona
return json.persona
})
}
}
fill = {
user: user => {
const form = this.components.form
form.querySelector('input[name="name"]').value = user.nombres || ''
form.querySelector('input[name="last_name"]').value = user.apellidoPaterno || ''
form.querySelector('input[name="last_name2"]').value = user.apellidoMaterno || ''
form.querySelector('input[name="calle"]').value = user.datos?.direccion?.calle || ''
form.querySelector('input[name="numero"]').value = user.datos?.direccion?.numero || ''
form.querySelector('input[name="extra"]').value = user.datos?.direccion?.extra || ''
if (parseInt(this.components.$region.dropdown('get value')) !== user.datos?.direccion?.comuna?.provincia?.region?.id) {
this.components.$region.dropdown('set selected', user.datos?.direccion?.comuna?.provincia?.region?.id)
} else {
this.components.$comuna.dropdown('set selected', user.datos?.direccion?.comuna?.id)
}
form.querySelector('input[name="phone"]').value = user.datos?.telefono
const email_parts = user.datos?.email.split('@')
form.querySelector('input[name="email_name"]').value = email_parts[0]
form.querySelector('input[name="email_domain"]').value = email_parts[1]
if ('estadoCivil' in user.datos) {
form.querySelector('input[name="civil_status"]').value = user.datos?.estadoCivil.charAt(0).toUpperCase() + user.datos?.estadoCivil.slice(1)
} else {
form.querySelector('input[name="civil_status"]').value = ''
}
if ('ocupacion' in user.datos) {
form.querySelector('input[name="profession"]').value = user.datos?.ocupacion
} else {
form.querySelector('input[name="profession"]').value = ''
}
if ('fechaNacimiento' in user.datos) {
this.components.$birthdate.calendar('set date', user.datos?.fechaNacimiento)
}
},
brokers: () => {
this.components.$broker.dropdown('change values', this.data.brokers[this.data.current_project])
},
units: () => {
const buttons = []
Object.entries(this.maps.unit_types).forEach(([type, map]) => {
if (!(type in this.data.units[this.data.current_project])) {
return
}
buttons.push(`<div class="field"><div class="ui icon button" data-type="${type}" title="${type.charAt(0).toUpperCase() + type.slice(1)}"><i class="plus icon"></i><i class="${map} icon"></i></div></div>`)
})
this.components.unit_buttons.innerHTML = buttons.join('')
this.components.unit_buttons.querySelectorAll('.ui.icon.button').forEach(button => {
button.addEventListener('click', () => {
this.units.add(button.dataset.type)
})
})
}
}
watch = {
region: (value, text, $choice) => {
this.get.comunas(value)
},
}
loader = {
show: () => {
this.components.$loader.show()
},
hide: () => {
this.components.$loader.hide()
}
}
show() {
this.reset()
this.components.$modal.modal('show')
}
setup() {
this.components.$modal = $(`#${this.ids.modal}`)
this.components.form = document.getElementById(this.ids.form)
this.components.$date = $(`#${this.ids.date}`)
this.components.rut = document.getElementById(this.ids.rut)
this.components.digit = document.getElementById(this.ids.digit)
this.components.$birthdate = $(`#${this.ids.birthdate}`)
this.components.$comuna = $(`#${this.ids.comuna}`)
this.components.$region = $(`#${this.ids.region}`)
this.components.$broker = $(`#${this.ids.broker}`)
this.components.promotions = new AddModalPromotions()
this.components.units = new AddModalUnits()
this.components.$modal.modal({
onApprove: () => {
this.add()
}
})
this.components.form.addEventListener('submit', event => {
event.preventDefault()
this.add()
return false
})
const cdo = structuredClone(calendar_date_options)
cdo['startDate'] = new Date()
cdo['maxDate'] = new Date()
this.components.$date.calendar(cdo)
const rutInput = this.components.rut.querySelector('input')
rutInput.addEventListener('input', event => {
const value = event.currentTarget.value.replace(/\D/g, '')
if (value.length <= 3) {
return
}
this.components.digit.textContent = Rut.digitoVerificador(value)
})
rutInput.addEventListener('blur', event => {
const value = event.currentTarget.value.replace(/\D/g, '')
if (value.length <= 3) {
return
}
event.currentTarget.value = Rut.format(value)
this.get.user(value).then(user => {
this.fill.user(user)
})
})
const cdo2 = structuredClone(cdo)
cdo2['startDate'].setFullYear(cdo2['startDate'].getFullYear() - 18)
cdo2['maxDate'].setFullYear(cdo2['maxDate'].getFullYear() - 18)
this.components.$birthdate.calendar(cdo2)
this.components.$region.dropdown({
fireOnInit: true,
onChange: this.watch.region
})
this.components.$region.dropdown('set selected', 13)
this.components.$comuna.dropdown()
this.components.$broker.dropdown()
this.components.$loader = $(`#${this.ids.loader}`)
}
}
</script>
@endpush

View File

@ -224,5 +224,9 @@ return [
$container->get(Incoviba\Service\Queue::class)
)
->register($container->get(Incoviba\Service\Venta\MediosPago\Toku::class));
},
Incoviba\Service\FileUpload::class => function(ContainerInterface $container) {
return new Incoviba\Service\FileUpload($container->get(Psr\Log\LoggerInterface::class))
->register($container->get(Incoviba\Service\FileUpload\ExcelBase::class));
}
];

View File

@ -1,34 +0,0 @@
<?php
namespace Incoviba\Controller\API;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Incoviba\Common\Ideal;
use Incoviba\Common\Implement;
use Incoviba\Exception\ServiceAction;
use Incoviba\Repository;
use Incoviba\Service;
class Personas extends Ideal\Controller
{
use withJson;
public function get(ServerRequestInterface $request, ResponseInterface $response,
Service\Persona $personaService, int $rut): ResponseInterface
{
$output = [
'rut' => $rut,
'persona' => null,
'success' => false
];
try {
$persona = $personaService->getById($rut);
$output['persona'] = $persona;
$output['success'] = true;
} catch (ServiceAction\Read $exception) {
$this->logger->error($exception->getMessage(), ['exception' => $exception]);
}
return $this->withJson($response, $output);
}
}

View File

@ -187,18 +187,5 @@ class Proyectos
}
return $this->withJson($response, $output);
}
public function promotions(ServerRequestInterface $request, ResponseInterface $response,
Service\Venta\Promotion $promotionService, int $proyecto_id): ResponseInterface
{
$output = [
'project_id' => $proyecto_id,
'promotions' => []
];
try {
$output['promotions'] = $promotionService->getByProject($proyecto_id);
} catch (Read $exception) {
return $this->withError($response, $exception);
}
return $this->withJson($response, $output);
}
}

View File

@ -1,13 +1,16 @@
<?php
namespace Incoviba\Controller\API\Ventas;
use DateTime;
use Exception;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Incoviba\Common\Implement\Exception\EmptyRedis;
use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Common\Implement\Exception\{EmptyRedis,EmptyResult};
use Psr\Log\LoggerInterface;
use Incoviba\Controller\API\{withJson,emptyBody};
use Incoviba\Service;
use Incoviba\Controller\withRedis;
use Incoviba\Exception\ServiceAction\Create;
use Incoviba\Service;
class Precios
{
@ -51,4 +54,29 @@ class Precios
}
}
}
public function import(ServerRequestInterface $request, ResponseInterface $response,
LoggerInterface $logger,
Service\Venta\Precio $precioService): ResponseInterface
{
$body = $request->getParsedBody();
$projectId = $body['project_id'];
$date = $body['date'];
$file = $request->getUploadedFiles()['file'];
$output = [
'input' => $body,
'total' => 0,
'precios' => [],
'status' => false
];
$date = DateTime::createFromFormat('Y-m-d', $date);
try {
$output['precios'] = $precioService->import($projectId, $date, $file);
$output['total'] = count($output['precios']);
$output['status'] = true;
} catch (Create | Exception $exception) {
$logger->warning($exception);
}
return $this->withJson($response, $output);
}
}

View File

@ -11,8 +11,7 @@ class Reservations
{
use withJson;
public function __invoke(ServerRequestInterface $request, ResponseInterface $response,
Service\Venta\Reservation $reservationService): ResponseInterface
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, Service\Venta\Reservation $reservationService): ResponseInterface
{
$reservations = [];
try {
@ -23,18 +22,6 @@ class Reservations
return $this->withJson($response, compact('reservations'));
}
public function getByProject(ServerRequestInterface $request, ResponseInterface $response,
Service\Venta\Reservation $reservationService, int $project_id): ResponseInterface
{
$reservations = [];
try {
$reservations = $reservationService->getByProject($project_id);
} catch (ServiceAction\Read $exception) {
return $this->withError($response, $exception);
}
return $this->withJson($response, compact('reservations'));
}
public function get(ServerRequestInterface $request, ResponseInterface $response, Service\Venta\Reservation $reservationService, int $reservation_id): ResponseInterface
{
$output = [
@ -113,47 +100,4 @@ class Reservations
return $this->withJson($response, $output);
}
public function active(ServerRequestInterface $request, ResponseInterface $response,
Service\Venta\Reservation $reservationService, int $project_id): ResponseInterface
{
$output = [
'project_id' => $project_id,
'reservations' => [],
'success' => false,
];
try {
$output['reservations'] = $reservationService->getActive($project_id);
$output['success'] = true;
} catch (ServiceAction\Read) {}
return $this->withJson($response, $output);
}
public function pending(ServerRequestInterface $request, ResponseInterface $response,
Service\Venta\Reservation $reservationService, int $project_id): ResponseInterface
{
$output = [
'project_id' => $project_id,
'reservations' => [],
'success' => false,
];
try {
$output['reservations'] = $reservationService->getPending($project_id);
$output['success'] = true;
} catch (ServiceAction\Read) {}
return $this->withJson($response, $output);
}
public function rejected(ServerRequestInterface $request, ResponseInterface $response,
Service\Venta\Reservation $reservationService, int $project_id): ResponseInterface
{
$output = [
'project_id' => $project_id,
'reservations' => [],
'success' => false,
];
try {
$output['reservations'] = $reservationService->getRejected($project_id);
$output['success'] = true;
} catch (ServiceAction\Read) {}
return $this->withJson($response, $output);
}
}

View File

@ -9,9 +9,9 @@ use Incoviba\Model;
class Precios
{
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, View $view, Service\Proyecto $proyectoService): ResponseInterface
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, View $view, Service\Proyecto $proyectoService, ?int $project_id = null): ResponseInterface
{
$proyectos = array_map(function(Model\Proyecto $proyecto) {return ['id' => $proyecto->id, 'descripcion' => $proyecto->descripcion];}, $proyectoService->getVendibles());
return $view->render($response, 'ventas.precios.list', compact('proyectos'));
return $view->render($response, 'ventas.precios.list', compact('proyectos', 'project_id'));
}
}

View File

@ -1,28 +0,0 @@
<?php
namespace Incoviba\Controller\Ventas;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Incoviba\Common\Alias\View;
use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Exception\ServiceAction\Read;
use Incoviba\Repository;
use Incoviba\Service;
class Reservations
{
public function __invoke(ServerRequestInterface $request, ResponseInterface $response,
Service\Proyecto $proyectoService, Repository\Region $regionRepository,
View $view): ResponseInterface
{
$projects = [];
try {
$projects = $proyectoService->getVendibles('descripcion');
} catch (Read) {}
$regions = [];
try {
$regions = $regionRepository->fetchAll();
} catch (EmptyResult) {}
return $view->render($response, 'ventas.reservations', compact('projects', 'regions'));
}
}

View File

@ -1,13 +0,0 @@
<?php
namespace Incoviba\Exception\Model;
use Throwable;
use Exception;
class InvalidState extends Exception
{
public function __construct(string $message = "Invalid state", int $code = 505, ?Throwable $previous = null)
{
parent::__construct($message, $code, $previous);
}
}

View File

@ -1,7 +1,6 @@
<?php
namespace Incoviba\Model;
use Incoviba\Common\Implement\Exception\EmptyResult;
use InvalidArgumentException;
use Incoviba\Common\Ideal;
use Incoviba\Model\Persona\Datos;
@ -28,11 +27,7 @@ class Persona extends Ideal\Model
public function datos(): ?Datos
{
if (!isset($this->datos)) {
try {
$this->datos = $this->runFactory('datos');
} catch (EmptyResult) {
$this->datos = null;
}
$this->datos = $this->runFactory('datos');
}
return $this->datos;
}

View File

@ -1,10 +1,7 @@
<?php
namespace Incoviba\Model\Proyecto;
use DateTimeImmutable;
use DateTimeInterface;
use Incoviba\Common;
use Incoviba\Model\Proyecto;
class Broker extends Common\Ideal\Model
{
@ -29,36 +26,6 @@ class Broker extends Common\Ideal\Model
}
return $this->contracts;
}
public function getContract(Proyecto $proyecto, ?DateTimeInterface $date = null): ?Proyecto\Broker\Contract
{
if ($date === null) {
$date = new DateTimeImmutable();
}
$contracts = $this->contracts();
$valid = array_filter($contracts, fn(Proyecto\Broker\Contract $contract) => $contract->project->id === $proyecto->id);
$valid = array_filter($valid, fn(Proyecto\Broker\Contract $contract) => $contract->wasActive($date));
if (count($valid) === 0) {
return null;
}
return last($valid);
}
public function applyCommission(Proyecto $proyecto, float $price, ?DateTimeInterface $date = null): float
{
$contract = $this->getContract($proyecto, $date);
if ($contract === null) {
return $price;
}
return $contract->activate()->apply($proyecto, $price);
}
public function reverseCommission(Proyecto $proyecto, float $price, ?DateTimeInterface $date = null): float
{
$contract = $this->getContract($proyecto, $date);
if ($contract === null) {
return $price;
}
return $contract->activate()->reverse($proyecto, $price);
}
public function rutFull(): string
{

View File

@ -1,7 +1,6 @@
<?php
namespace Incoviba\Model\Proyecto\Broker;
use DateTimeInterface;
use Incoviba\Common;
use Incoviba\Model;
@ -42,51 +41,6 @@ class Contract extends Common\Ideal\Model
return $this->promotions;
}
public function isActive(): bool
{
$state = $this->current();
return $state !== null and $state->isActive();
}
public function activate(): self
{
$this->current()->activate();
return $this;
}
public function wasActive(DateTimeInterface $date): bool
{
$states = $this->states();
return array_any($states, fn($state) => $state->date <= $date);
}
public function value(float $price): float
{
if (!$this->isActive()) {
return $price;
}
return $price * (1 + $this->commission);
}
public function inverse(float $price): float
{
if (!$this->isActive()) {
return $price;
}
return $price / (1 + $this->commission);
}
public function apply(Model\Proyecto $project, float $price): float
{
if (!$this->isActive() or $this->project->id !== $project->id) {
return $price;
}
return $this->value($price);
}
public function reverse(Model\Proyecto $project, float $price): float
{
if (!$this->isActive() or $this->project->id !== $project->id) {
return $price;
}
return $this->inverse($price);
}
protected function jsonComplement(): array
{
return [

View File

@ -11,16 +11,6 @@ class State extends Common\Ideal\Model
public DateTimeInterface $date;
public State\Type $type;
public function isActive(): bool
{
return $this->type === State\Type::ACTIVE;
}
public function activate(): self
{
$this->type = State\Type::ACTIVE;
return $this;
}
protected function jsonComplement(): array
{
return [

View File

@ -3,7 +3,6 @@ namespace Incoviba\Model\Venta;
use DateTimeInterface;
use Incoviba\Common;
use Incoviba\Model\Proyecto;
use Incoviba\Model\Proyecto\Broker;
use Incoviba\Model\Venta\Promotion\State;
use Incoviba\Model\Venta\Promotion\Type;
@ -62,95 +61,13 @@ class Promotion extends Common\Ideal\Model
return $this->units;
}
public function isActive(): bool
{
return $this->state === State::ACTIVE;
}
public function activate(): self
{
$this->state = State::ACTIVE;
return $this;
}
public function value(float $price): float
{
if (!$this->isActive()) {
return $price;
}
if ($this->type === Type::FIXED) {
return $price + $this->amount;
}
return $price / (1 - $this->amount);
}
public function inverse(float $price): float
{
if (!$this->isActive()) {
return $price;
}
if ($this->type === Type::FIXED) {
return $price - $this->amount;
}
return $price * (1 - $this->amount);
}
public function apply(Unidad $unit, float $price, ?Broker $broker = null): float
{
if (!$this->isActive()) {
return $price;
}
$projectIds = array_map(fn(Proyecto $proyecto) => $proyecto->id, $this->projects());
if (in_array($unit->proyectoTipoUnidad->proyecto->id, $projectIds)) {
return $this->value($price);
}
if ($broker !== null) {
$brokerIds = array_map(fn(Broker $broker) => $broker->id, $this->brokers());
if (in_array($broker->id, $brokerIds)) {
return $this->value($price);
}
}
$typeIds = array_map(fn(Proyecto\TipoUnidad $type) => $type->id, $this->unitTypes());
if (in_array($unit->proyectoTipoUnidad->tipoUnidad->id, $typeIds)) {
return $this->value($price);
}
$lineIds = array_map(fn(Proyecto\ProyectoTipoUnidad $line) => $line->id, $this->unitLines());
if (in_array($unit->proyectoTipoUnidad->id, $lineIds)) {
return $this->value($price);
}
$unitIds = array_map(fn(Unidad $unit) => $unit->id, $this->units());
if (in_array($unit->id, $unitIds)) {
return $this->value($price);
}
return $price;
}
public function reverse(Unidad $unit, float $price, ?Broker $broker = null): float
{
if (!$this->isActive()) {
return $price;
}
$projectIds = array_map(fn(Proyecto $proyecto) => $proyecto->id, $this->projects());
if (in_array($unit->proyectoTipoUnidad->proyecto->id, $projectIds)) {
return $this->inverse($price);
}
if ($broker !== null) {
$brokerIds = array_map(fn(Broker $broker) => $broker->id, $this->brokers());
if (in_array($broker->id, $brokerIds)) {
return $this->inverse($price);
}
}
$typeIds = array_map(fn(Proyecto\TipoUnidad $type) => $type->id, $this->unitTypes());
if (in_array($unit->proyectoTipoUnidad->tipoUnidad->id, $typeIds)) {
return $this->inverse($price);
}
$lineIds = array_map(fn(Proyecto\ProyectoTipoUnidad $line) => $line->id, $this->unitLines());
if (in_array($unit->proyectoTipoUnidad->id, $lineIds)) {
return $this->inverse($price);
}
$unitIds = array_map(fn(Unidad $unit) => $unit->id, $this->units());
if (in_array($unit->id, $unitIds)) {
return $this->inverse($price);
}
return $price;
}
protected function jsonComplement(): array
{

View File

@ -7,44 +7,11 @@ use Incoviba\Model;
class Reservation extends Common\Ideal\Model
{
public Model\Proyecto $project;
public Model\Persona $buyer;
public DateTimeInterface $date;
public array $units = [];
public array $promotions = [];
public ?Model\Proyecto\Broker $broker = null;
public function offer(): float
{
return array_sum(array_column($this->units, 'value'));
}
public function withCommission(): float
{
$base = 0;
foreach ($this->units as $unit) {
foreach ($this->promotions as $promotion) {
$base += $promotion->activate()->reverse($unit['unit'], $unit['value'], $this->broker);
}
}
return $base;
}
public function base(): float
{
$base = $this->withCommission();
if ($this->broker !== null) {
$base = $this->broker->reverseCommission($this->project, $base, $this->date);
}
return $base;
}
public function price(): float
{
$price = 0;
foreach ($this->units as $unit) {
$price += $unit->unit->precio($this->date);
}
return $price;
}
protected array $states = [];
public function states(): array
@ -71,12 +38,13 @@ class Reservation extends Common\Ideal\Model
$this->units[$i]['value'] = $value;
return $this;
}
$this->units[] = (object) [
$this->units[] = [
'unit' => $unit,
'value' => $value,
];
return $this;
}
public function removeUnit(int $unit_id): self
{
if (($i = $this->findUnit($unit_id)) === null) {
@ -86,6 +54,7 @@ class Reservation extends Common\Ideal\Model
$this->units = array_values($this->units);
return $this;
}
public function findUnit(int $unit_id): ?int
{
foreach ($this->units as $idx => $unit) {
@ -95,43 +64,20 @@ class Reservation extends Common\Ideal\Model
}
return null;
}
public function hasUnit(int $unit_id): bool
{
return $this->findUnit($unit_id) !== null;
}
public function summary(): string
{
$unitSummary = array_map(function($unit) {
$type = $unit->unit->proyectoTipoUnidad->tipoUnidad->descripcion;
$cap = strtoupper(strstr($type, 0, 1));
return "{$cap}{$unit->unit->descripcion}";
}, $this->units);
return implode('', $unitSummary);
}
public function valid(): bool
{
$base = $this->base();
$price = $this->price();
return $base >= $price;
}
protected function jsonComplement(): array
{
return [
'project_id' => $this->project->id,
'buyer' => $this->buyer,
'buyer_rut' => $this->buyer->rut,
'date' => $this->date->format('Y-m-d'),
'units' => $this->units,
'promotions' => $this->promotions,
'broker' => $this->broker,
'offer' => $this->offer(),
'with_commission' => $this->withCommission(),
'base' => $this->base(),
'price' => $this->price(),
'valid' => $this->valid(),
'summary' => $this->summary()
'broker_rut' => $this->broker?->rut,
];
}
}

View File

@ -1,17 +0,0 @@
<?php
namespace Incoviba\Model\Venta\Reservation\Detail;
enum Type: int
{
case Unit = 1;
case Promotion = 2;
case Broker = 3;
public function jsonSerialize(): array
{
return [
'id' => $this->value,
'description' => $this->name
];
}
}

View File

@ -9,14 +9,17 @@ class State extends Common\Ideal\Model
{
public Model\Venta\Reservation $reservation;
public DateTimeInterface $date;
public Model\Venta\Reservation\State\Type $type;
public int $type;
protected function jsonComplement(): array
{
return [
'reservation_id' => $this->reservation->id,
'date' => $this->date->format('Y-m-d'),
'type' => $this->type
'type' => [
'id' => $this->type,
'description' => State\Type::name($this->type)
]
];
}
}
}

View File

@ -7,15 +7,13 @@ enum Type: int
case INACTIVE = 0;
case REJECTED = -1;
public function jsonSerialize(): array
public static function name(int $type): string
{
return [
'id' => $this->value,
'description' => $this->name
];
return match ($type) {
self::ACTIVE => 'active',
self::INACTIVE => 'inactive',
self::REJECTED => 'rejected',
default => throw new \InvalidArgumentException('Unexpected match value')
};
}
public static function getTypes(): array
{
return [self::ACTIVE->value, self::INACTIVE->value, self::REJECTED->value];
}
}
}

View File

@ -43,6 +43,11 @@ class Inmobiliaria extends Ideal\Repository
return $this->update($model, ['dv', 'razon', 'abreviacion', 'cuenta', 'banco', 'sociedad'], $new_data);
}
/**
* @param string|array|null $sorting
* @return array
* @throws Implement\Exception\EmptyResult
*/
public function fetchAllActive(null|string|array $sorting = null): array
{
$query = $this->connection->getQueryBuilder()
@ -58,4 +63,18 @@ class Inmobiliaria extends Ideal\Repository
}
return $this->fetchMany($query, [1, 8]);
}
/**
* @param string $name
* @return Model\Inmobiliaria
* @throws Implement\Exception\EmptyResult
*/
public function fetchByName(string $name): Model\Inmobiliaria
{
$query = $this->connection->getQueryBuilder()
->select()
->from($this->getTable())
->where('razon LIKE :name OR abreviacion LIKE :name');
return $this->fetchOne($query, ['name' => "%{$name}%"]);
}
}

View File

@ -29,9 +29,6 @@ class Datos extends Ideal\Repository
->register('direccion_id', (new Implement\Repository\Mapper())
->setProperty('direccion')
->setFunction(function($data) {
if ($data['direccion_id'] === null) {
return null;
}
return $this->direccionRepository->fetchById($data['direccion_id']);
})->setDefault(null))
->register('telefono', (new Implement\Repository\Mapper())->setFunction(function($data) {

View File

@ -85,6 +85,11 @@ class Proyecto extends Ideal\Repository
return $this->fetchOne($query, [$id]);
}
/**
* @param string $name
* @return Model\Proyecto
* @throws Implement\Exception\EmptyResult
*/
public function fetchByName(string $name): Model\Proyecto
{
$query = $this->connection->getQueryBuilder()

View File

@ -7,6 +7,8 @@ use Incoviba\Common\Define;
use Incoviba\Common\Implement;
use Incoviba\Model;
use Incoviba\Repository;
use PDO;
use PDOException;
class EstadoPrecio extends Ideal\Repository
{
@ -44,11 +46,24 @@ class EstadoPrecio extends Ideal\Repository
return $this->update($model, ['precio', 'estado', 'fecha'], $new_data);
}
/**
* @param int $precio_id
* @return array
* @throws Implement\Exception\EmptyResult
*/
public function fetchByPrecio(int $precio_id): array
{
$query = "SELECT * FROM `{$this->getTable()}` WHERE `precio` = ?";
error_log($query.PHP_EOL,3,'/logs/query.log');
error_log($precio_id.PHP_EOL,3,'/logs/query.log');
return $this->fetchMany($query, [$precio_id]);
}
/**
* @param int $precio_id
* @return Define\Model
* @throws Implement\Exception\EmptyResult
*/
public function fetchCurrentByPrecio(int $precio_id): Define\Model
{
$query = "SELECT e1.*

View File

@ -1,6 +1,7 @@
<?php
namespace Incoviba\Repository\Venta;
use Incoviba\Common\Implement\Exception\EmptyResult;
use PDO;
use PDOException;
use Incoviba\Common\Ideal;

View File

@ -3,19 +3,14 @@ namespace Incoviba\Repository\Venta;
use DateTimeInterface;
use DateInterval;
use Incoviba\Common\Define;
use Incoviba\Exception\Model\InvalidState;
use PDO;
use Incoviba\Common;
use Incoviba\Model;
use Incoviba\Repository;
use PDOException;
class Reservation extends Common\Ideal\Repository
{
public function __construct(Common\Define\Connection $connection,
protected Repository\Proyecto $proyectoRepository,
protected Repository\Persona $personaRepository,
public function __construct(Common\Define\Connection $connection, protected Repository\Persona $personaRepository,
protected Repository\Proyecto\Broker $brokerRepository,
protected Unidad $unitRepository, protected Promotion $promotionRepository)
{
@ -30,33 +25,37 @@ class Reservation extends Common\Ideal\Repository
public function create(?array $data = null): Model\Venta\Reservation
{
$map = (new Common\Implement\Repository\MapperParser())
->register('project_id', (new Common\Implement\Repository\Mapper())
->setProperty('project')
->setFunction(function($data) {
return $this->proyectoRepository->fetchById($data['project_id']);
}))
->register('buyer_rut', (new Common\Implement\Repository\Mapper())
->setProperty('buyer')
->setFunction(function($data) {
->setFunction(function($data) use ($data) {
return $this->personaRepository->fetchById($data['buyer_rut']);
}))
->register('date', new Common\Implement\Repository\Mapper\DateTime('date'));
->register('date', new Common\Implement\Repository\Mapper\DateTime('date'))
->register('broker_rut', (new Common\Implement\Repository\Mapper())
->setProperty('broker')
->setDefault(null)
->setFunction(function($data) use ($data) {
try {
return $this->brokerRepository->fetchById($data['broker_rut']);
} catch (Common\Implement\Exception\EmptyResult) {
return null;
}
}));
return $this->parseData(new Model\Venta\Reservation(), $data, $map);
}
public function save(Common\Define\Model $model): Model\Venta\Reservation
{
$model->id = $this->saveNew([
'project_id',
'buyer_rut',
'date'
'date',
'broker_rut'
], [
$model->project->id,
$model->buyer->rut,
$model->date->format('Y-m-d')
$model->date->format('Y-m-d'),
$model->broker?->rut
]);
$this->saveUnits($model);
$this->savePromotions($model);
$this->saveBroker($model);
return $model;
}
@ -68,20 +67,15 @@ class Reservation extends Common\Ideal\Repository
*/
public function edit(Common\Define\Model $model, array $new_data): Model\Venta\Reservation
{
$model = $this->update($model, ['project_id', 'buyer_rut', 'date'], $new_data);
$this->editUnits($model, $new_data);
$this->editPromotions($model, $new_data);
$this->editBroker($model, $new_data);
return $model;
return $this->update($model, ['buyer_rut', 'date', 'broker_rut'], $new_data);
}
public function load(array $data_row): Model\Venta\Reservation
{
$model = parent::load($data_row);
$this->fetchUnits($model, $data_row);
$this->fetchBroker($model, $data_row);
$this->fetchPromotions($model, $data_row);
$this->fetchUnits($model);
$this->fetchPromotions($model);
return $model;
}
@ -99,86 +93,6 @@ class Reservation extends Common\Ideal\Repository
->where('buyer_rut = :buyer_rut AND date >= :date');
return $this->fetchOne($query, ['buyer_rut' => $buyer_rut, 'date' => $date->sub(new DateInterval('P10D'))->format('Y-m-d')]);
}
public function fetchByProject(int $project_id): array
{
$query = $this->connection->getQueryBuilder()
->select()
->from('reservations')
->where('project_id = :project_id');
return $this->fetchMany($query, ['project_id' => $project_id]);
}
/**
* @param int $project_id
* @param int $state
* @return array
* @throws Common\Implement\Exception\EmptyResult
* @throws InvalidState
*/
public function fetchState(int $project_id, int $state): array
{
if (!in_array($state, Model\Venta\Reservation\State\Type::getTypes())) {
throw new InvalidState();
}
$sub1 = $this->connection->getQueryBuilder()
->select('MAX(id) AS id, reservation_id')
->from('reservation_states')
->group('reservation_id');
$sub2 = $this->connection->getQueryBuilder()
->select('er1.*')
->from('reservation_states er1')
->joined("INNER JOIN ({$sub1}) er0 ON er0.id = er1.id");
$query = $this->connection->getQueryBuilder()
->select()
->from('reservations')
->joined("INNER JOIN ({$sub2}) er ON er.reservation_id = reservations.id")
->where('project_id = :project_id AND er.type = :state');
return $this->fetchMany($query, ['project_id' => $project_id,
'state' => $state]);
}
/**
* @param int $project_id
* @return array
* @throws Common\Implement\Exception\EmptyResult
*/
public function fetchActive(int $project_id): array
{
try {
return $this->fetchState($project_id, Model\Venta\Reservation\State\Type::ACTIVE->value);
} catch (InvalidState $exception) {
throw new Common\Implement\Exception\EmptyResult('Select active reservations', $exception);
}
}
/**
* @param int $project_id
* @return array
* @throws Common\Implement\Exception\EmptyResult
*/
public function fetchPending(int $project_id): array
{
try {
return $this->fetchState($project_id, Model\Venta\Reservation\State\Type::INACTIVE->value);
} catch (InvalidState $exception) {
throw new Common\Implement\Exception\EmptyResult('Select pending reservations', $exception);
}
}
/**
* @param int $project_id
* @return array
* @throws Common\Implement\Exception\EmptyResult
*/
public function fetchRejected(int $project_id): array
{
try {
return $this->fetchState($project_id, Model\Venta\Reservation\State\Type::REJECTED->value);
} catch (InvalidState $exception) {
throw new Common\Implement\Exception\EmptyResult('Select rejected reservations', $exception);
}
}
protected function saveUnits(Model\Venta\Reservation $reservation): void
{
@ -187,71 +101,22 @@ class Reservation extends Common\Ideal\Repository
}
$queryCheck = $this->connection->getQueryBuilder()
->select('COUNT(id) AS cnt')
->from('reservation_details')
->where('reservation_id = :id AND type = :type AND reference_id = :unit_id');
->from('reservation_data')
->where('reservation_id = :id AND type = "Unit" AND reference_id = :unit_id');
$statementCheck = $this->connection->prepare($queryCheck);
$queryInsert = $this->connection->getQueryBuilder()
->insert()
->into('reservation_details')
->into('reservation_data')
->columns(['reservation_id', 'type', 'reference_id', 'value'])
->values([':reservation_id', ':type', ':reference_id', ':value']);
$statementInsert = $this->connection->prepare($queryInsert);
foreach ($reservation->units as $unit) {
$statementCheck->execute([
'id' => $reservation->id,
'type' => Model\Venta\Reservation\Detail\Type::Unit->value,
'unit_id' => $unit->unit->id
]);
$statementCheck->execute(['id' => $reservation->id, 'unit_id' => $unit['unit']->id]);
$result = $statementCheck->fetch(PDO::FETCH_ASSOC);
if ($result['cnt'] > 0) {
continue;
}
$statementInsert->execute([
'reservation_id' => $reservation->id,
'type' => Model\Venta\Reservation\Detail\Type::Unit->value,
'reference_id' => $unit->unit->id,
'value' => $unit->value
]);
}
$this->cleanUpUnits($reservation);
}
protected function cleanUpUnits(Model\Venta\Reservation $reservation): void
{
$this->cleanUpDetails($reservation,
Model\Venta\Reservation\Detail\Type::Unit->value,
array_map(fn($unit) => $unit->unit->id, $reservation->units));
}
protected function saveBroker(Model\Venta\Reservation &$reservation): void
{
if ($reservation->broker === null) {
$this->removeBroker($reservation);
return;
}
try {
$queryCheck = $this->connection->getQueryBuilder()
->select('id')
->from('reservation_details')
->where('reservation_id = :id AND type = :type');
$statementCheck = $this->connection->execute($queryCheck, [
'id' => $reservation->id,
'type' => Model\Venta\Reservation\Detail\Type::Broker->value
]);
$result = $statementCheck->fetch(PDO::FETCH_ASSOC);
$new_id = $reservation->broker->id;
$reservation->broker = $this->brokerRepository->fetchById($result['id']);
$this->editBroker($reservation, ['broker_id' => $new_id]);
} catch (PDOException) {
$queryInsert = $this->connection->getQueryBuilder()
->insert()
->into('reservation_details')
->columns(['reservation_id', 'type', 'reference_id'])
->values([':reservation_id', ':type', ':reference_id']);
$this->connection->execute($queryInsert, [
'reservation_id' => $reservation->id,
'type' => Model\Venta\Reservation\Detail\Type::Broker->value,
'reference_id' => $reservation->broker->id
]);
$statementInsert->execute(['reservation_id' => $reservation->id, 'type' => 'Unit', 'reference_id' => $unit['unit']->id, 'value' => $unit['value']]);
}
}
protected function savePromotions(Model\Venta\Reservation $reservation): void
@ -261,152 +126,60 @@ class Reservation extends Common\Ideal\Repository
}
$queryCheck = $this->connection->getQueryBuilder()
->select('COUNT(id) AS cnt')
->from('reservation_details')
->where('reservation_id = :id AND type = :type AND reference_id = :promotion_id');
->from('reservation_data')
->where('reservation_id = :id AND type = "Promotion" AND reference_id = :promotion_id');
$statementCheck = $this->connection->prepare($queryCheck);
$queryInsert = $this->connection->getQueryBuilder()
->insert()
->into('reservation_details')
->into('reservation_data')
->columns(['reservation_id', 'type', 'reference_id'])
->values([':reservation_id', ':type', ':reference_id']);
$statementInsert = $this->connection->prepare($queryInsert);
foreach ($reservation->promotions as $promotion) {
$statementCheck->execute([
'id' => $reservation->id,
'type' => Model\Venta\Reservation\Detail\Type::Promotion->value,
'promotion_id' => $promotion->id
]);
$statementCheck->execute(['id' => $reservation->id, 'promotion_id' => $promotion->id]);
$result = $statementCheck->fetch(PDO::FETCH_ASSOC);
if ($result['cnt'] > 0) {
continue;
}
$statementInsert->execute([
'reservation_id' => $reservation->id,
'type' => Model\Venta\Reservation\Detail\Type::Promotion->value,
'reference_id' => $promotion->id
]);
$statementInsert->execute(['reservation_id' => $reservation->id, 'type' => 'Promotion', 'reference_id' => $promotion->id]);
}
$this->cleanUpPromotions($reservation);
}
protected function cleanUpPromotions(Model\Venta\Reservation $reservation): void
{
$this->cleanUpDetails($reservation,
Model\Venta\Reservation\Detail\Type::Promotion->value,
array_map(fn($promotion) => $promotion->id, $reservation->promotions));
}
protected function cleanUpDetails(Model\Venta\Reservation $reservation, int $type_id, array $currentIds): void
{
$queryCheck = $this->connection->getQueryBuilder()
->select('COUNT(id) AS cnt')
->from('reservation_details')
->where('reservation_id = :id AND type = :type');
$statementCheck = $this->connection->prepare($queryCheck);
$deleteParam = implode(', ', array_map(fn($id) => ":id$id", $currentIds));
$queryDelete = $this->connection->getQueryBuilder()
->delete()
->from('reservation_details')
->where("reservation_id = :id AND type = :type AND reference_id NOT IN ({$deleteParam})");
$statementDelete = $this->connection->prepare($queryDelete);
try {
$statementCheck->execute([
'id' => $reservation->id,
'type' => $type_id
]);
$result = $statementCheck->fetch(PDO::FETCH_ASSOC);
if ($result['cnt'] <= count($currentIds)) {
return;
}
$deleteIdValues = array_combine(array_map(fn($id) => "id$id", $currentIds), $currentIds);
$statementDelete->execute(array_merge(
['id' => $reservation->id, 'type' => $type_id],
$deleteIdValues));
} catch (PDOException) {}
}
protected function editUnits(Model\Venta\Reservation &$reservation, array $new_data): void
protected function editUnits(Model\Venta\Reservation $reservation, array $new_data): void
{
$querySelect = $this->connection->getQueryBuilder()
->select()
->from('reservation_details')
->where('reservation_id = :id AND type = :type AND reference_id = :unit_id');
->from('reservation_data')
->where('reservation_id = :id AND type = "Unit" AND reference_id = :unit_id');
$statementSelect = $this->connection->prepare($querySelect);
$queryUpdate = $this->connection->getQueryBuilder()
->update('reservation_details')
->update('reservation_data')
->set('value = :value')
->where('reservation_id = :id AND type = :type AND reference_id = :unit_id');
->where('reservation_id = :id AND type = "Unit" AND reference_id = :unit_id');
$statementUpdate = $this->connection->prepare($queryUpdate);
$queryInsert = $this->connection->getQueryBuilder()
->insert()
->into('reservation_details')
->columns(['reservation_id', 'type', 'reference_id', 'value'])
->values([':reservation_id', ':type', ':reference_id', ':value']);
$statementInsert = $this->connection->prepare($queryInsert);
foreach ($new_data['units'] as $unit) {
$idx = $reservation->findUnit($unit['unit_id']);
foreach ($new_data as $unit_id => $value) {
$idx = $reservation->findUnit($unit_id);
if ($idx === null) {
$reservation->addUnit($this->unitRepository->fetchById($unit['unit_id']), $unit['value']);
$statementInsert->execute([
'reservation_id' => $reservation->id,
'type' => Model\Venta\Reservation\Detail\Type::Unit->value,
'reference_id' => $unit['unit_id'],
'value' => $unit['value']
]);
$reservation->addUnit($this->unitRepository->fetchById($unit_id), $value);
continue;
}
$statementSelect->execute([
'id' => $reservation->id,
'type' => Model\Venta\Reservation\Detail\Type::Unit->value,
'unit_id' => $unit['unit_id']
]);
$statementSelect->execute(['id' => $reservation->id, 'unit_id' => $unit_id]);
$result = $statementSelect->fetch(PDO::FETCH_ASSOC);
if (!$result) {
$reservation->addUnit($this->unitRepository->fetchById($unit['unit_id']), $unit['value']);
$statementInsert->execute([
'reservation_id' => $reservation->id,
'type' => Model\Venta\Reservation\Detail\Type::Unit->value,
'reference_id' => $unit['unit_id'],
'value' => $unit['value']
]);
continue;
}
$statementUpdate->execute([
'id' => $reservation->id,
'type' => Model\Venta\Reservation\Detail\Type::Unit->value,
'unit_id' => $unit['unit_id'],
'value' => $unit['value']
]);
$reservation->units[$idx]['value'] = $unit['value'];
$statementUpdate->execute(['id' => $reservation->id, 'unit_id' => $unit_id, 'value' => $value]);
$reservation->units[$idx]['value'] = $value;
}
}
protected function editBroker(Model\Venta\Reservation &$reservation, array $new_data): void
{
if (!array_key_exists('broker_id', $new_data) or $new_data['broker_id'] === $reservation->broker->id) {
return;
}
try {
$query = $this->connection->getQueryBuilder()
->update('reservation_details')
->set('reference_id = :broker_id')
->where('reservation_id = :id AND type = :type');
$this->connection->execute($query, [
'id' => $reservation->id,
'type' => Model\Venta\Reservation\Detail\Type::Broker->value,
'broker_id' => $new_data['broker_id']
]);
$reservation->broker = $this->brokerRepository->fetchById($new_data['broker_id']);
} catch (PDOException) {}
}
protected function editPromotions(Model\Venta\Reservation &$reservation, array $new_data): void
protected function editPromotions(Model\Venta\Reservation $reservation, array $new_data): void
{
$querySelect = $this->connection->getQueryBuilder()
->select()
->from('reservation_details')
->from('reservation_data')
->where('reservation_id = :id AND type = "Promotion" AND reference_id = :promotion_id');
$statementSelect = $this->connection->prepare($querySelect);
$queryUpdate = $this->connection->getQueryBuilder()
->update('reservation_details')
->update('reservation_data')
->set('value = :value')
->where('reservation_id = :id AND type = "Promotion" AND reference_id = :promotion_id');
$statementUpdate = $this->connection->prepare($queryUpdate);
@ -425,26 +198,13 @@ class Reservation extends Common\Ideal\Repository
$reservation->promotions[$idx] = $this->promotionRepository->fetchById($promotion_id);
}
}
protected function fetchUnits(Model\Venta\Reservation &$reservation, array $new_data): Model\Venta\Reservation
{
$this->fetchSavedUnits($reservation);
if (array_key_exists('units', $new_data) and count($new_data['units']) > 0) {
$this->fetchUnsavedUnits($reservation, $new_data);
}
return $reservation;
}
protected function fetchSavedUnits(Model\Venta\Reservation &$reservation): Model\Venta\Reservation
protected function fetchUnits(Model\Venta\Reservation &$reservation): Model\Venta\Reservation
{
$query = $this->connection->getQueryBuilder()
->select()
->from('reservation_details')
->where('reservation_id = :id AND type = ?');
$statement = $this->connection->execute($query, [
'id' => $reservation->id,
Model\Venta\Reservation\Detail\Type::Unit->value
]);
->from('reservation_data')
->where('reservation_id = :id AND type = "Unit"');
$statement = $this->connection->execute($query, ['id' => $reservation->id]);
while ($result = $statement->fetch(PDO::FETCH_ASSOC)) {
try {
@ -453,69 +213,13 @@ class Reservation extends Common\Ideal\Repository
}
return $reservation;
}
protected function fetchUnsavedUnits(Model\Venta\Reservation &$reservation, array $new_data): Model\Venta\Reservation
{
if (!array_key_exists('units', $new_data) or count($new_data['units']) > 0) {
return $reservation;
}
$queryCheck = $this->connection->getQueryBuilder()
->select('COUNT(id) AS cnt')
->from('reservation_details')
->where('reservation_id = :id AND type = :type AND reference_id = :unit_id');
$statementCheck = $this->connection->prepare($queryCheck);
foreach ($new_data['units'] as $unit) {
$statementCheck->execute([
'id' => $reservation->id,
'type' => Model\Venta\Reservation\Detail\Type::Unit->value,
'unit_id' => $unit['unit_id']
]);
$result = $statementCheck->fetch(PDO::FETCH_ASSOC);
if ($result['cnt'] > 0) {
continue;
}
try {
$reservation->addUnit($this->unitRepository->fetchById($unit['unit_id']), $unit['value']);
} catch (Common\Implement\Exception\EmptyResult) {}
}
return $reservation;
}
protected function fetchBroker(Model\Venta\Reservation &$reservation, array $new_data): Model\Venta\Reservation
{
if (!array_key_exists('broker_id', $new_data)) {
$query = $this->connection->getQueryBuilder()
->select('reference_id')
->from('reservation_details')
->where('reservation_id = :id AND type = :type');
try {
$statement =$this->connection->execute($query, [
'id' => $reservation->id,
'type' => Model\Venta\Reservation\Detail\Type::Broker->value
]);
$result = $statement->fetch(PDO::FETCH_ASSOC);
$reservation->broker = $this->brokerRepository->fetchById($result['reference_id']);
} catch (PDOException) {}
return $reservation;
}
try {
$reservation->broker = $this->brokerRepository->fetchById($new_data['broker_id']);
} catch (Common\Implement\Exception\EmptyResult) {}
return $reservation;
}
protected function fetchPromotions(Model\Venta\Reservation &$reservation, array $new_data): Model\Venta\Reservation
{
$this->fetchSavedPromotions($reservation);
$this->fetchUnsavedPromotions($reservation, $new_data);
return $reservation;
}
protected function fetchSavedPromotions(Model\Venta\Reservation &$reservation): Model\Venta\Reservation
protected function fetchPromotions(Model\Venta\Reservation $reservation): Model\Venta\Reservation
{
$query = $this->connection->getQueryBuilder()
->select()
->from('reservation_details')
->where('type = :type AND reservation_id = :id');
$statement = $this->connection->execute($query,
['id' => $reservation->id, 'type' => Model\Venta\Reservation\Detail\Type::Promotion->value]);
->from('reservation_data')
->where('type = "Promotion" AND reservation_id = :id');
$statement = $this->connection->execute($query, ['id' => $reservation->id]);
while ($result = $statement->fetch(PDO::FETCH_ASSOC)) {
try {
$reservation->promotions []= $this->promotionRepository->fetchById($result['reference_id']);
@ -523,43 +227,4 @@ class Reservation extends Common\Ideal\Repository
}
return $reservation;
}
protected function fetchUnsavedPromotions(Model\Venta\Reservation &$reservation, array $new_data): Model\Venta\Reservation
{
if (!array_key_exists('promotions', $new_data) or count($new_data['promotions']) > 0) {
return $reservation;
}
$queryCheck = $this->connection->getQueryBuilder()
->select('COUNT(id) AS cnt')
->from('reservation_details')
->where('type = :type AND reservation_id = :id AND reference_id = :promotion_id');
$statementCheck = $this->connection->prepare($queryCheck);
foreach ($new_data['promotions'] as $promotion) {
$statementCheck->execute([
'id' => $reservation->id,
'promotion_id' => $promotion
]);
$result = $statementCheck->fetch(PDO::FETCH_ASSOC);
if ($result['cnt'] > 0) {
continue;
}
try {
$reservation->promotions []= $this->promotionRepository->fetchById($promotion);
} catch (Common\Implement\Exception\EmptyResult) {}
}
return $reservation;
}
protected function removeBroker(Model\Venta\Reservation &$reservation): void
{
try {
$query = $this->connection->getQueryBuilder()
->delete()
->from('reservation_details')
->where('reservation_id = :id AND type = :type');
$this->connection->execute($query, [
'id' => $reservation->id,
'type' => Model\Venta\Reservation\Detail\Type::Broker->value
]);
$reservation->broker = null;
} catch (PDOException) {}
}
}

View File

@ -22,7 +22,7 @@ class State extends Common\Ideal\Repository
$map = (new Common\Implement\Repository\MapperParser(['type']))
->register('reservation_id', (new Common\Implement\Repository\Mapper())
->setProperty('reservation')
->setFunction(function($data) {
->setFunction(function($data) use ($data) {
return $this->reservationRepository->fetchById($data['reservation_id']);
}))
->register('date', new Common\Implement\Repository\Mapper\DateTime('date'));

View File

@ -4,6 +4,7 @@ namespace Incoviba\Repository\Venta;
use Incoviba\Common\Ideal;
use Incoviba\Common\Define;
use Incoviba\Common\Implement;
use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Model;
class TipoEstadoPrecio extends Ideal\Repository
@ -31,4 +32,18 @@ class TipoEstadoPrecio extends Ideal\Repository
{
return $this->update($model, ['descripcion'], $new_data);
}
/**
* @param string $descripcion
* @return Model\Venta\TipoEstadoPrecio
* @throws EmptyResult
*/
public function fetchByDescripcion(string $descripcion): Model\Venta\TipoEstadoPrecio
{
$query = $this->connection->getQueryBuilder()
->select()
->from($this->getTable())
->where('descripcion = ?');
return $this->fetchOne($query, [$descripcion]);
}
}

View File

@ -0,0 +1,59 @@
<?php
namespace Incoviba\Service;
use InvalidArgumentException;
use Psr\Http\Message\UploadedFileInterface;
use Incoviba\Common\Ideal;
use Incoviba\Exception\ServiceAction;
use Incoviba\Service\FileUpload\FileUploadInterface;
class FileUpload extends Ideal\Service implements FileUploadInterface
{
protected array $uploads = [];
public function register(FileUploadInterface $fileUpload, string $filetype = 'default'): self
{
$this->uploads [$filetype]= $fileUpload;
return $this;
}
/**
* @param UploadedFileInterface $uploadedFile
* @return array
* @throws ServiceAction\Read
*/
public function getData(UploadedFileInterface $uploadedFile): array
{
try {
$type = $this->getFileType($uploadedFile);
} catch (InvalidArgumentException $exception) {
throw new ServiceAction\Read(__CLASS__, $exception);
}
$uploader = $this->getUploader($type);
return $uploader->getData($uploadedFile);
}
/**
* @param UploadedFileInterface $uploadedFile
* @return string|null
*/
protected function getFileType(UploadedFileInterface $uploadedFile): ?string
{
$fileType = $uploadedFile->getClientMediaType();
$typesMap = [
'text/csv' => 'csv',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' => 'xlsx',
'application/vnd.ms-excel' => 'xls',
];
if (!array_key_exists($fileType, $typesMap)) {
throw new InvalidArgumentException("File type {$fileType} not supported.");
}
return $typesMap[$fileType];
}
protected function getUploader(string $type): FileUploadInterface
{
if (!array_key_exists($type, $this->uploads)) {
return $this->uploads['default'];
}
return $this->uploads[$type];
}
}

View File

@ -0,0 +1,147 @@
<?php
namespace Incoviba\Service\FileUpload;
use InvalidArgumentException;
use OutOfBoundsException;
use Psr\Http\Message\UploadedFileInterface;
use PhpOffice\PhpSpreadsheet;
use Incoviba\Common\Ideal;
use Incoviba\Exception\ServiceAction\Read;
class ExcelBase extends Ideal\Service implements FileUploadInterface
{
/**
* @param UploadedFileInterface $uploadedFile
* @return array
* @throws Read
*/
public function getData(UploadedFileInterface $uploadedFile): array
{
$tempFilename = $this->createTempFile($uploadedFile);
$reader = PhpSpreadsheet\IOFactory::createReaderForFile($tempFilename);
$reader->setReadDataOnly(true);
$workbook = $reader->load($tempFilename);
try {
$sheet = $this->findSheet($workbook);
} catch (OutOfBoundsException $exception) {
throw new Read(__CLASS__, $exception);
}
$titles = $this->extractTitles($sheet);
$data = $this->extractData($sheet, $titles);
unlink($tempFilename);
return $data;
}
/**
* @param PhpSpreadsheet\Spreadsheet $workbook
* @return PhpSpreadsheet\Worksheet\Worksheet
* @throws OutOfBoundsException
*/
protected function findSheet(PhpSpreadsheet\Spreadsheet $workbook): PhpSpreadsheet\Worksheet\Worksheet
{
$sheet = $workbook->getActiveSheet();
if ($this->findTable($sheet)) {
return $sheet;
}
$sheets = $workbook->getAllSheets();
foreach ($sheets as $sheet) {
if ($this->findTable($sheet)) {
return $sheet;
}
}
throw new OutOfBoundsException('No table found in the workbook.');
}
protected function findTable(PhpSpreadsheet\Worksheet\Worksheet $sheet): bool
{
$rowIterator = $sheet->getRowIterator();
foreach ($rowIterator as $row) {
if ($row->isEmpty()) {
continue;
}
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(true);
if ($cellIterator->valid()) {
return true;
}
foreach ($cellIterator as $cell) {
if ($cell->getCalculatedValue() !== '') {
return true;
}
}
}
return false;
}
protected function createTempFile(UploadedFileInterface $uploadedFile): string
{
$filename = $uploadedFile->getClientFilename();
$extension = pathinfo($filename, PATHINFO_EXTENSION);
$tempFilename = tempnam(sys_get_temp_dir(), $extension);
$uploadedFile->moveTo($tempFilename);
return $tempFilename;
}
protected function extractTitles(PhpSpreadsheet\Worksheet\Worksheet $sheet): array
{
$titles = [];
$iterator = $sheet->getRowIterator();
foreach ($iterator as $row) {
if ($row->isEmpty()) {
continue;
}
$titles = $this->getRowData($row);
break;
}
return $titles;
}
protected function extractData(PhpSpreadsheet\Worksheet\Worksheet $sheet, array $titles): array
{
$data = [];
$rowIterator = $sheet->getRowIterator();
foreach ($rowIterator as $row) {
if ($row->isEmpty()) {
continue;
}
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(true);
if ($cellIterator->current() === $titles[0]) {
continue;
}
try {
$rowData = $this->getRowData($row, $titles);
} catch (InvalidArgumentException $exception) {
if ($exception->getCode() === 1000) {
continue;
}
throw $exception;
}
$data []= array_combine($titles, $rowData);
}
return $data;
}
protected function getRowData(PhpSpreadsheet\Worksheet\Row $row, ?array $titles = null): array
{
$data = [];
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(true);
foreach ($cellIterator as $cell) {
if ($cell->getCalculatedValue() === null) {
continue;
}
$value = $cell->getCalculatedValue();
if ($value === null) {
continue;
}
$value = mb_strtolower($value);
if ($titles !== null and in_array($value, $titles)) {
throw new InvalidArgumentException('Row matches title', 1000);
}
$data []= $value;
}
return $data;
}
}

View File

@ -0,0 +1,9 @@
<?php
namespace Incoviba\Service\FileUpload;
use Psr\Http\Message\UploadedFileInterface;
interface FileUploadInterface
{
public function getData(UploadedFileInterface $uploadedFile): array;
}

View File

@ -35,7 +35,7 @@ class Persona extends Ideal\Service
/**
* @param int $rut
* @return Model\Persona
* @throws Read
* @throws Read|Create
*/
public function getById(int $rut): Model\Persona
{
@ -44,11 +44,7 @@ class Persona extends Ideal\Service
} catch (Implement\Exception\EmptyResult) {
try {
$this->propietarioRepository->fetchById($rut);
try {
return $this->add(compact('rut'));
} catch (Create $exception) {
throw new Read(__CLASS__, $exception);
}
return $this->add(compact('rut'));
} catch (Implement\Exception\EmptyResult $exception) {
throw new Read(__CLASS__, $exception);
}

View File

@ -1,19 +1,31 @@
<?php
namespace Incoviba\Service\Venta;
use DateTimeInterface;
use PDOException;
use Psr\Http\Message\UploadedFileInterface;
use Psr\Log\LoggerInterface;
use Incoviba\Common\Ideal;
use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Exception\ServiceAction\Read;
use Incoviba\Repository;
use Incoviba\Exception\ServiceAction;
use Incoviba\Model;
use Incoviba\Repository;
class Precio
class Precio extends Ideal\Service
{
public function __construct(protected Repository\Venta\Precio $precioRepository, protected Repository\Venta\EstadoPrecio $estadoPrecioRepository) {}
public function __construct(LoggerInterface $logger,
protected Repository\Venta\Precio $precioRepository,
protected Repository\Venta\EstadoPrecio $estadoPrecioRepository,
protected Precio\Estado $estadoPrecioService,
protected Precio\Import $importService)
{
parent::__construct($logger);
}
/**
* @param int $proyecto_id
* @return array
* @throws Read
* @throws ServiceAction\Read
*/
public function getByProyecto(int $proyecto_id): array
{
@ -25,14 +37,14 @@ class Precio
}
return $precios;
} catch (EmptyResult $exception) {
throw new Read(__CLASS__, $exception);
throw new ServiceAction\Read(__CLASS__, $exception);
}
}
/**
* @param int $unidad_id
* @return Model\Venta\Precio
* @throws Read
* @throws ServiceAction\Read
*/
public function getVigenteByUnidad(int $unidad_id): Model\Venta\Precio
{
@ -42,14 +54,14 @@ class Precio
$precio->current = $this->estadoPrecioRepository->fetchCurrentByPrecio($precio->id);
return $precio;
} catch (EmptyResult $exception) {
throw new Read(__CLASS__, $exception);
throw new ServiceAction\Read(__CLASS__, $exception);
}
}
/**
* @param int $unidad_id
* @return array
* @throws Read
* @throws ServiceAction\Read
*/
public function getByUnidad(int $unidad_id): array
{
@ -61,7 +73,51 @@ class Precio
}
return $precios;
} catch (EmptyResult $exception) {
throw new Read(__CLASS__, $exception);
throw new ServiceAction\Read(__CLASS__, $exception);
}
}
/**
* @param int $projectId
* @param DateTimeInterface $date
* @param UploadedFileInterface $uploadedFile
* @return array
* @throws ServiceAction\Create
*/
public function import(int $projectId, DateTimeInterface $date, UploadedFileInterface $uploadedFile): array
{
$pricesData = $this->importService->importData($projectId, $date, $uploadedFile);
$prices = [];
foreach ($pricesData as $data) {
try {
$price = $this->precioRepository->create($data);
$price = $this->precioRepository->save($price);
$prices[] = $price;
} catch (EmptyResult | PDOException $exception) {
$this->logger->error('Problemas para agregar precio', ['data' => $data, 'exception' => $exception]);
}
}
foreach ($prices as $price) {
$idx = array_search($price->unidad->id, array_column($pricesData, 'unidad'));
$row = $pricesData[$idx];
try {
$this->estadoPrecioService->replacePrices($price->unidad, $date, $price);
} catch (ServiceAction\Update $exception) {
$this->logger->error('Problemas para reemplazar precios', [
'data' => $row,
'exception' => $exception
]);
}
try {
$this->estadoPrecioService->updatePrice($price, $row['fecha']);
} catch (ServiceAction\Update $exception) {
$this->logger->error('Problemas para actualizar estado de precio', [
'data' => $row,
'exception' => $exception
]);
}
}
return $prices;
}
}

View File

@ -0,0 +1,89 @@
<?php
namespace Incoviba\Service\Venta\Precio;
use DateTimeInterface;
use Incoviba\Model\Venta\Precio;
use Incoviba\Model\Venta\Unidad;
use PDOException;
use Psr\Log\LoggerInterface;
use Incoviba\Common\Ideal;
use Incoviba\Common\Implement;
use Incoviba\Exception\ServiceAction;
use Incoviba\Model;
use Incoviba\Repository;
class Estado extends Ideal\Service
{
public function __construct(LoggerInterface $logger,
protected Repository\Venta\Precio $precioRepository,
protected Repository\Venta\EstadoPrecio $estadoPrecioRepository,
protected Repository\Venta\TipoEstadoPrecio $tipoEstadoPrecioRepository)
{
parent::__construct($logger);
}
/**
* @param Model\Venta\Precio $price
* @param DateTimeInterface $date
* @return void
* @throws ServiceAction\Update
*/
public function updatePrice(Model\Venta\Precio $price, DateTimeInterface $date): void
{
try {
$tipoEstado = $this->tipoEstadoPrecioRepository->fetchByDescripcion('vigente');
} catch (Implement\Exception\EmptyResult $exception) {
throw new ServiceAction\Update(__CLASS__, $exception);
}
$data = [
'precio' => $price->id,
'fecha' => $date->format('Y-m-d'),
'estado' => $tipoEstado->id
];
try {
$estado = $this->estadoPrecioRepository->create($data);
$this->estadoPrecioRepository->save($estado);
} catch (Implement\Exception\EmptyResult | PDOException $exception) {
throw new ServiceAction\Update(__CLASS__, $exception);
}
}
/**
* @param Unidad $unidad
* @param DateTimeInterface $date
* @param Precio $price
* @return void
* @throws ServiceAction\Update
*/
public function replacePrices(Model\Venta\Unidad $unidad, DateTimeInterface $date, Model\Venta\Precio $price): void
{
try {
$tipoEstado = $this->tipoEstadoPrecioRepository->fetchByDescripcion('reemplazado');
} catch (Implement\Exception\EmptyResult $exception) {
throw new ServiceAction\Update(__CLASS__, $exception);
}
try {
$precios = $this->precioRepository->fetchByUnidad($unidad->id);
foreach ($precios as $p) {
if ($p->id === $price->id) {
continue;
}
try {
$estado = $this->estadoPrecioRepository->fetchCurrentByPrecio($p->id);
if ($estado->tipoEstadoPrecio->id === $tipoEstado->id) {
continue;
}
$data = [
'precio' => $p->id,
'estado' => $tipoEstado->id,
'fecha' => $date->format('Y-m-d')
];
$estado = $this->estadoPrecioRepository->create($data);
$this->estadoPrecioRepository->save($estado);
} catch (Implement\Exception\EmptyResult) {}
}
} catch (Implement\Exception\EmptyResult $exception) {
throw new ServiceAction\Update(__CLASS__, $exception);
}
}
}

View File

@ -0,0 +1,243 @@
<?php
namespace Incoviba\Service\Venta\Precio;
use DateTime;
use DateTimeInterface;
use PDOException;
use Psr\Http\Message\UploadedFileInterface;
use Psr\Log\LoggerInterface;
use Incoviba\Common\Ideal;
use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Exception\ServiceAction;
use Incoviba\Model;
use Incoviba\Service;
use Incoviba\Repository;
class Import extends Ideal\Service
{
public function __construct(LoggerInterface $logger,
protected Repository\Venta\Precio $precioRepository,
protected Repository\Inmobiliaria $inmobiliariaRepository,
protected Repository\Proyecto $proyectoRepository,
protected Repository\Venta\Unidad $unidadRepository,
protected Service\FileUpload $fileUploadService)
{
parent::__construct($logger);
}
/**
* @param int $projectId
* @param DateTimeInterface $date
* @param UploadedFileInterface $uploadedFile
* @return array
* @throws ServiceAction\Create
*/
public function importData(int $projectId, DateTimeInterface $date, UploadedFileInterface $uploadedFile): array
{
try {
$data = $this->fileUploadService->getData($uploadedFile);
} catch (ServiceAction\Read $exception) {
throw new ServiceAction\Create(__CLASS__, $exception);
}
$mappedData = $this->mapData($data, $projectId, $date);
$pricesData = [];
foreach ($mappedData as $row) {
$pricesData[] = [
'unidad' => $row['unidad'],
'valor' => $row['precio'],
'fecha' => $row['fecha']
];
}
try {
$priceUnitIds = array_map(fn($price) => $price['unidad'], $pricesData);
$prices = $this->precioRepository->fetchVigentesByUnidades($priceUnitIds);
$priceUnitIds = array_map(fn(array $p) => $p['id'], $prices);
$pricePrices = array_map(fn(array $p) => $p['precio']->valor, $prices);
return array_filter($pricesData, function($price) use ($priceUnitIds, $pricePrices) {
$idx = array_search($price['unidad'], $priceUnitIds);
if ($idx === false) {
return true;
}
return $pricePrices[$idx] !== $price['valor'];
});
} catch (EmptyResult $exception) {
throw new ServiceAction\Create(__CLASS__, $exception);
}
}
protected array $realTitlesMap;
protected function extractTitlesFromData(array $data): array
{
if (isset($this->realTitlesMap)) {
return $this->realTitlesMap;
}
$baseTitlesMap = [
'proyecto' => [],
'precio' => [],
'unidad' => ['departamento'],
'tipo' => ['tipo unidad'],
'fecha' => []
];
$realTitlesMap = [];
$titles = array_keys($data[0]);
foreach ($baseTitlesMap as $base => $optionals) {
foreach ($titles as $title) {
if (str_contains($title, $base)) {
$realTitlesMap[$title] = $base;
break;
}
foreach ($optionals as $optional) {
if (str_contains($title, $optional)) {
$realTitlesMap[$title] = $base;
break;
}
}
}
}
return $this->realTitlesMap = $realTitlesMap;
}
protected function mapData(array $data, int $projectId, DateTimeInterface $date): array
{
$mappedData = $this->mapTitles($data);
$mappedData = $this->mapProjects($mappedData, $projectId);
$mappedData = $this->mapUnits($mappedData);
return $this->mapDates($mappedData, $date);
}
protected function mapTitles(array $data): array
{
$titlesMap = $this->extractTitlesFromData($data);
$mappedData = [];
foreach ($data as $row) {
$mappedData []= $this->mapRow($row, $titlesMap);
}
return $mappedData;
}
protected function mapProjects(array $data, int $projectId): array
{
if (!array_key_exists('proyecto', $data[0])) {
return array_map(function($row) use ($projectId) {
$row['proyecto'] = $projectId;
return $row;
},$data);
}
$projects = $this->extractProjectsFromData($data);
$mappedData = [];
foreach ($data as $row) {
$mappedRow = $row;
$mappedRow['proyecto'] = $projects[$row['proyecto']]?->id ?? $projectId;
$mappedData []= $mappedRow;
}
return $mappedData;
}
protected function mapUnits(array $data): array
{
if (!array_key_exists('unidad', $data[0]) or !array_key_exists('tipo', $data[0])) {
return $data;
}
$unidades = [];
$mappedData = [];
foreach ($data as $row) {
if (!isset($unidades[$row['proyecto']])) {
$unidades[$row['proyecto']] = $this->unidadRepository->fetchByProyecto($row['proyecto']);
}
$tipo = $this->mapTipoUnidad($row['tipo']);
$unidad = array_filter($unidades[$row['proyecto']], function(Model\Venta\Unidad $unidad) use ($row, $tipo) {
return $unidad->descripcion == $row['unidad']
and $unidad->proyectoTipoUnidad->tipoUnidad->descripcion == $tipo;
});
if (count($unidad) === 0) {
$this->logger->warning('Unidad no encontrada', ['row' => $row]);
continue;
}
$mappedRow = $row;
$mappedRow['unidad'] = array_shift($unidad)->id;
unset($mappedRow['tipo']);
$mappedData []= $mappedRow;
}
return $mappedData;
}
protected function mapDates(array $data, DateTimeInterface $date): array
{
if (!array_key_exists('fecha', $data[0])) {
return array_map(function($row) use ($date) {
$row['fecha'] = $date;
return $row;
}, $data);
}
$mappedData = [];
foreach ($data as $row) {
$mappedRow = $row;
$newDate = DateTime::createFromFormat('d/m/Y', $row['fecha']);
$mappedRow['fecha'] = $newDate;
if ($newDate === false) {
$mappedRow['fecha'] = $date;
}
$mappedData []= $mappedRow;
}
return $mappedData;
}
protected function mapRow(array $row, array $titlesMap): array
{
$mappedRow = [];
foreach ($row as $key => $value) {
$mappedRow[$titlesMap[$key]] = $value;
}
return $mappedRow;
}
protected function mapTipoUnidad(string $tipo): string
{
if (str_contains(mb_strtolower($tipo), 'bod')) {
return 'bodega';
}
if (str_contains(mb_strtolower($tipo), 'est')) {
return 'estacionamiento';
}
if (str_contains(mb_strtolower($tipo), 'terr')) {
return 'terraza';
}
return 'departamento';
}
protected array $projectsMap;
protected function extractProjectsFromData(array $data): array
{
if (isset($this->projectsMap)) {
return $this->projectsMap;
}
$projectNames = array_unique(array_map(fn($row) => $row['proyecto'], $data));
$projects = [];
foreach ($projectNames as $projectName) {
try {
$projects[$projectName] = $this->proyectoRepository->fetchByName($projectName);
} catch (EmptyResult $exception) {
try {
$inm = $this->inmobiliariaRepository->fetchByName($projectName);
$inmProjects = $this->proyectoRepository->fetchByInmobiliaria($inm->rut);
$projects[$projectName] = $inmProjects[0];
} catch (EmptyResult $exception2) {
$this->logger->warning('Neither Project nor Society found', [
'projectName' => $projectName,
'exceptions' => [
[
'code' => $exception->getCode(),
'message' => $exception->getMessage(),
'file' => $exception->getFile(),
'line' => $exception->getLine(),
'data' => $exception->getData(),
'trace' => $exception->getTraceAsString()
],
[
'code' => $exception2->getCode(),
'message' => $exception2->getMessage(),
'file' => $exception2->getFile(),
'line' => $exception2->getLine(),
'data' => $exception2->getData(),
'trace' => $exception2->getTraceAsString()
]
],
]);
}
}
}
return $this->projectsMap = $projects;
}
}

View File

@ -48,20 +48,6 @@ class Promotion extends Ideal\Service
}
}
/**
* @param int $project_id
* @return array
* @throws Exception\ServiceAction\Read
*/
public function getByProject(int $project_id): array
{
try {
return array_map([$this, 'process'], $this->promotionRepository->fetchByProject($project_id));
} catch (Implement\Exception\EmptyResult $exception) {
throw new Exception\ServiceAction\Read(__CLASS__, $exception);
}
}
/**
* @param int $contract_id
* @return array

View File

@ -14,9 +14,7 @@ use Incoviba\Repository;
class Reservation extends Ideal\Service\API
{
public function __construct(LoggerInterface $logger,
protected Repository\Venta\Reservation $reservationRepository,
protected Repository\Venta\Reservation\State $stateRepository)
public function __construct(LoggerInterface $logger, protected Repository\Venta\Reservation $reservationRepository)
{
parent::__construct($logger);
}
@ -24,19 +22,11 @@ class Reservation extends Ideal\Service\API
public function getAll(null|string|array $order = null): array
{
try {
return array_map([$this, 'process'], $this->reservationRepository->fetchAll($order));
return $this->reservationRepository->fetchAll($order);
} catch (Implement\Exception\EmptyResult) {
return [];
}
}
public function getByProject(int $project_id): array
{
try {
return array_map([$this, 'process'], $this->reservationRepository->fetchByProject($project_id));
} catch (Implement\Exception\EmptyResult $exception) {
throw new ServiceAction\Read(__CLASS__, $exception);
}
}
public function get(int $id): Model\Venta\Reservation
{
@ -47,48 +37,6 @@ class Reservation extends Ideal\Service\API
}
}
/**
* @param int $project_id
* @return array
* @throws ServiceAction\Read
*/
public function getActive(int $project_id): array
{
try {
return array_map([$this, 'process'], $this->reservationRepository->fetchActive($project_id));
} catch (Implement\Exception\EmptyResult $exception) {
throw new ServiceAction\Read(__CLASS__, $exception);
}
}
/**
* @param int $project_id
* @return array
* @throws ServiceAction\Read
*/
public function getPending(int $project_id): array
{
try {
return array_map([$this, 'process'], $this->reservationRepository->fetchPending($project_id));
} catch (Implement\Exception\EmptyResult $exception) {
throw new ServiceAction\Read(__CLASS__, $exception);
}
}
/**
* @param int $project_id
* @return array
* @throws ServiceAction\Read
*/
public function getRejected(int $project_id): array
{
try {
return array_map([$this, 'process'], $this->reservationRepository->fetchRejected($project_id));
} catch (Implement\Exception\EmptyResult $exception) {
throw new ServiceAction\Read(__CLASS__, $exception);
}
}
public function add(array $data): Model\Venta\Reservation
{
try {
@ -128,12 +76,6 @@ class Reservation extends Ideal\Service\API
}
protected function process(Define\Model $model): Model\Venta\Reservation
{
$model->addFactory('states', new Implement\Repository\Factory()
->setArgs(['reservation_id' => $model->id])
->setCallable(function(int $reservation_id) {
return $this->stateRepository->fetchByReservation($reservation_id);
})
);
return $model;
}
}

View File

@ -0,0 +1,164 @@
<?php
namespace Incoviba\Test\Unit\Service\Venta\Precio;
use Psr\Log\LoggerInterface;
use PHPUnit\Framework\TestCase;
use Faker;
use Incoviba\Model;
use Incoviba\Repository;
use Incoviba\Service;
class EstadoTest extends TestCase
{
protected LoggerInterface $logger;
protected Repository\Venta\Precio $precioRepository;
protected Repository\Venta\EstadoPrecio $estadoPrecioRepository;
protected Repository\Venta\TipoEstadoPrecio $tipoEstadoPrecioRepository;
protected function setUp(): void
{
$this->logger = $this->getMockBuilder(LoggerInterface::class)
->disableOriginalConstructor()
->getMock();
$this->precioRepository = $this->getMockBuilder(Repository\Venta\Precio::class)
->disableOriginalConstructor()
->getMock();
$this->estadoPrecioRepository = $this->getMockBuilder(Repository\Venta\EstadoPrecio::class)
->disableOriginalConstructor()
->getMock();
$this->tipoEstadoPrecioRepository = $this->getMockBuilder(Repository\Venta\TipoEstadoPrecio::class)
->disableOriginalConstructor()
->getMock();
}
public function testUpdatePrice(): void
{
$uniqueElements = 1000;
$faker = Faker\Factory::create();
$tipoEstadoPrecio = $this->getMockBuilder(Model\Venta\TipoEstadoPrecio::class)
->disableOriginalConstructor()
->getMock();
$tipoEstadoPrecio->id = $faker->unique()->numberBetween(1, $uniqueElements);
$tipoEstadoPrecio->descripcion = 'vigente';
$tipoEstadoPrecioRepository = $this->getMockBuilder(Repository\Venta\TipoEstadoPrecio::class)
->disableOriginalConstructor()
->getMock();
$tipoEstadoPrecioRepository->method('fetchByDescripcion')->with('vigente')->willReturn($tipoEstadoPrecio);
$unidad = $this->getMockBuilder(Model\Venta\Unidad::class)
->disableOriginalConstructor()
->getMock();
$unidad->id = $faker->unique()->numberBetween(1, $uniqueElements);
$precio = $this->getMockBuilder(Model\Venta\Precio::class)
->disableOriginalConstructor()
->getMock();
$precio->id = $faker->unique()->numberBetween(1, $uniqueElements);
$precio->unidad = $unidad;
$estadoPrecio = $this->getMockBuilder(Model\Venta\EstadoPrecio::class)
->disableOriginalConstructor()
->getMock();
$estadoPrecio->id = $faker->unique()->numberBetween(1, $uniqueElements);
$estadoPrecio->precio = $precio;
$estadoPrecio->tipoEstadoPrecio = $tipoEstadoPrecio;
$estadoPrecioRepository = $this->getMockBuilder(Repository\Venta\EstadoPrecio::class)
->disableOriginalConstructor()
->getMock();
$estadoPrecioRepository->method('create')->willReturn($estadoPrecio);
$estadoPrecioRepository->method('save')->willReturnArgument(0);
$date = $faker->dateTimeBetween('-6 months');
$estadoPrecioService = new Service\Venta\Precio\Estado($this->logger, $this->precioRepository,
$estadoPrecioRepository, $tipoEstadoPrecioRepository);
$estadoPrecioService->updatePrice($precio, $date);
$this->assertTrue(true);
}
public function testReplacePrices(): void
{
$uniqueElements = 1000;
$faker = Faker\Factory::create();
$tipoEstadoPrecio1 = $this->getMockBuilder(Model\Venta\TipoEstadoPrecio::class)
->disableOriginalConstructor()
->getMock();
$tipoEstadoPrecio1->id = $faker->unique()->numberBetween(1, $uniqueElements);
$tipoEstadoPrecio1->descripcion = 'vigente';
$tipoEstadoPrecio = $this->getMockBuilder(Model\Venta\TipoEstadoPrecio::class)
->disableOriginalConstructor()
->getMock();
$tipoEstadoPrecio->id = $faker->unique()->numberBetween(1, $uniqueElements);
$tipoEstadoPrecio->descripcion = 'reemplazado';
$this->tipoEstadoPrecioRepository->method('fetchByDescripcion')
->willReturnCallback(function($descripcion) use ($tipoEstadoPrecio, $tipoEstadoPrecio1) {
return match ($descripcion) {
'vigente' => $tipoEstadoPrecio1,
'reemplazado' => $tipoEstadoPrecio,
};
});
$unidad = $this->getMockBuilder(Model\Venta\Unidad::class)
->disableOriginalConstructor()
->getMock();
$unidad->id = $faker->unique()->numberBetween(1, $uniqueElements);
$preciosCount = $faker->numberBetween(1, 10);
$precios = [];
$estados = [];
for ($i = 0; $i < $preciosCount; $i++) {
$precio = $this->getMockBuilder(Model\Venta\Precio::class)
->disableOriginalConstructor()
->getMock();
$precio->id = $faker->unique()->numberBetween(1, $uniqueElements);
$precios []= $precio;
$estado = $this->getMockBuilder(Model\Venta\EstadoPrecio::class)
->disableOriginalConstructor()
->getMock();
$estado->id = $faker->unique()->numberBetween(1, $uniqueElements);
$estado->precio = $precio;
$estado->tipoEstadoPrecio = $tipoEstadoPrecio1;
$estados []= $estado;
}
$this->precioRepository->method('fetchByUnidad')->with($unidad->id)->willReturn($precios);
$this->estadoPrecioRepository->method('fetchCurrentByPrecio')->willReturnCallback(function($precio_id) use ($estados) {
$idx = array_search($precio_id, array_map(fn($estado) => $estado->precio->id, $estados));
return $estados[$idx];
});
$newEstados = [];
foreach ($precios as $precio) {
$estado = $this->getMockBuilder(Model\Venta\EstadoPrecio::class)
->disableOriginalConstructor()
->getMock();
$estado->id = $faker->unique()->numberBetween(1, $uniqueElements);
$estado->precio = $precio;
$estado->tipoEstadoPrecio = $tipoEstadoPrecio;
$newEstados []= $estado;
}
$this->estadoPrecioRepository->method('create')->willReturnCallback(function($data) use ($newEstados) {
$idx = array_search($data['precio'], array_map(fn($estado) => $estado->precio->id, $newEstados));
return $newEstados[$idx];
});
$this->estadoPrecioRepository->method('save')->willReturnArgument(0);
$precio = $this->getMockBuilder(Model\Venta\Precio::class)
->disableOriginalConstructor()
->getMock();
$precio->id = $faker->unique()->numberBetween(1, $uniqueElements);
$precio->unidad = $unidad;
$date = $faker->dateTimeBetween('-6 months');
$estadoPrecioService = new Service\Venta\Precio\Estado($this->logger, $this->precioRepository,
$this->estadoPrecioRepository, $this->tipoEstadoPrecioRepository);
$estadoPrecioService->replacePrices($unidad, $date, $precio);
$this->assertTrue(true);
}
}