Listado de Precios para Contrato Broker

This commit is contained in:
Juan Pablo Vial
2025-03-13 12:18:08 -03:00
parent 346001db8e
commit 68aebdb4fe
18 changed files with 826 additions and 14 deletions

View File

@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
use Phinx\Migration\AbstractMigration;
final class AlterPromotionsAddContractId 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('promotions')
->addColumn('contract_id', 'integer', ['signed' => false, 'null' => false, 'default' => 0, 'after' => 'id'])
->addForeignKey('contract_id', 'broker_contracts', 'id', ['delete' => 'cascade', 'update' => 'cascade'])
->update();
}
}

View File

@ -21,6 +21,8 @@ $app->group('/proyecto/{proyecto_id}', function($app) {
$app->get('/vendible[/]', [Proyectos::class, 'superficies']);
});
$app->group('/unidades', function($app) {
$app->post('/precios[/]', [Proyectos\Unidades::class, 'precios']);
$app->post('/estados[/]', [Proyectos\Unidades::class, 'estados']);
$app->get('/disponibles[/]', [Proyectos::class, 'disponibles']);
$app->get('[/]', [Proyectos::class, 'unidades']);
});

View File

@ -22,6 +22,9 @@ $app->group('/broker/{broker_rut}', function($app) {
$app->post('/add[/]', [Contracts::class, 'add']);
$app->get('[/]', [Contracts::class, 'getByBroker']);
});
$app->group('/contract/{contract_id}', function($app) {
$app->post('/promotions[/]', [Contracts::class, 'promotions']);
});
$app->delete('[/]', [Brokers::class, 'delete']);
$app->get('[/]', [Brokers::class, 'get']);
});

View File

@ -5,5 +5,8 @@ $app->group('/brokers', function($app) {
$app->get('[/]', Brokers::class);
});
$app->group('/broker/{broker_rut}', function($app) {
$app->group('/contract/{contract_id}', function($app) {
$app->get('[/]', [Brokers\Contracts::class, 'show']);
});
$app->get('[/]', [Brokers::class, 'show']);
});

View File

@ -0,0 +1,391 @@
@extends('proyectos.brokers.base')
@section('brokers_title')
{{ $contract->broker->name }} - {{ $contract->project->descripcion }}
@endsection
@section('brokers_header')
{{ $contract->broker->name }} - {{ $contract->project->descripcion }}
@endsection
@section('brokers_content')
<div class="ui compact segment">
<b>Comisión:</b> {{ $format->percent($contract->commission, 2, true) }} <br/>
<b>Fecha Inicio:</b> {{ $contract->current()->date->format('d/m/Y') }} <br/>
</div>
<div class="ui active inline loader"></div>
<table class="ui table" id="tipos">
<thead>
<tr>
<th rowspan="2">Tipo</th>
<th class="center aligned" rowspan="2">Cantidad</th>
<th class="center aligned" colspan="3">Precio</th>
<th class="center aligned" colspan="3">Promoción</th>
<th class="right aligned" rowspan="2">Acciones</th>
</tr>
<tr>
<th class="right aligned">Mínimo</th>
<th class="right aligned">Promedio</th>
<th class="right aligned">Máximo</th>
<th class="right aligned">Mínima</th>
<th class="right aligned">Promedio</th>
<th class="right aligned">Máxima</th>
</tr>
</thead>
<tbody></tbody>
</table>
<table class="ui table" id="lineas">
<thead>
<tr>
<th rowspan="2">Tipo</th>
<th class="center aligned" rowspan="2">Línea</th>
<th class="center aligned" rowspan="2">Orientación</th>
<th class="center aligned" rowspan="2">Tipología</th>
<th class="center aligned" rowspan="2">Cantidad</th>
<th class="center aligned" colspan="3">Precio</th>
<th class="center aligned" colspan="3">Promoción</th>
<th class="right aligned" rowspan="2">Acciones</th>
</tr>
<tr>
<th class="right aligned">Mínimo</th>
<th class="right aligned">Promedio</th>
<th class="right aligned">Máximo</th>
<th class="right aligned">Mínima</th>
<th class="right aligned">Promedio</th>
<th class="right aligned">Máxima</th>
</tr>
</thead>
<tbody></tbody>
</table>
<div id="unidades_container">
<table class="ui table" id="unidades">
<thead>
<tr>
<th>Tipo</th>
<th>Tipo Order</th>
<th class="right aligned">Unidad</th>
<th>Unidad Orden</th>
<th>Estado</th>
<th class="right aligned">Precio</th>
<th class="right aligned">Promoción</th>
<th>Fecha Inicio</th>
<th>Fecha Término</th>
<th class="right aligned">Acciones</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
@endsection
@include('layout.body.scripts.datatables')
@include('layout.body.scripts.datatables.searchbuilder')
@push('page_scripts')
<script>
const units = {
ids: {
units: '',
loader: ''
},
data: {
project_id: {{ $contract->project->id }},
units: []
},
formatters: {
ufs: new Intl.NumberFormat('es-CL', { style: 'decimal', minimumFractionDigits: 2, maximumFractionDigits: 2 }),
percent: new Intl.NumberFormat('es-CL', { style: 'percent', minimumFractionDigits: 2 })
},
get() {
return {
units: () => {
const url = `{{ $urls->api }}/proyecto/${units.data.project_id}/unidades`
return APIClient.fetch(url).then(response => response.json()).then(json => {
if (json.unidades.length === 0) {
console.error(json.errors)
return
}
units.data.units = []
Object.entries(json.unidades).forEach(([tipo, unidades]) => {
units.data.units = [...units.data.units, ...unidades]
})
})
},
promotions: () => {
const chunkSize = 100
const chunks = []
for (let i = 0; i < units.data.units.length; i += chunkSize) {
chunks.push(units.data.units.slice(i, i + chunkSize).map(u => u.id))
}
const promises = []
chunks.forEach(chunk => {
const url = `{{ $urls->api }}/proyectos/broker/{{ $contract->broker->rut }}/contract/{{ $contract->id }}/promotions`
const method = 'post'
const body = new FormData()
chunk.forEach(id => body.append('unidad_ids[]', id))
promises.push(APIClient.fetch(url, {method, body}).then(response => response.json()).then(json => {
if (json.unidades.length === 0) {
return
}
json.unidades.forEach(unidad => {
const idx = units.data.units.findIndex(u => u.id === parseInt(unidad.id))
units.data.units[idx].promotion = unidad.promotion
})
}))
})
return Promise.all(promises)
},
prices: () => {
const chunkSize = 100
const chunks = []
for (let i = 0; i < units.data.units.length; i += chunkSize) {
chunks.push(units.data.units.slice(i, i + chunkSize).map(u => u.id))
}
const promises = []
chunks.forEach(chunk => {
const url = `{{ $urls->api }}/proyecto/{{ $contract->project->id }}/unidades/precios`
const method = 'post'
const body = new FormData()
chunk.forEach(id => body.append('unidad_ids[]', id))
promises.push(APIClient.fetch(url, {method, body}).then(response => response.json()).then(json => {
if (json.precios.length === 0) {
return
}
json.precios.forEach(unidad => {
const idx = units.data.units.findIndex(u => u.id === parseInt(unidad.id))
units.data.units[idx].precio = unidad.precio
})
}))
})
return Promise.all(promises)
},
sold: () => {
const chunkSize = 100
const chunks = []
for (let i = 0; i < units.data.units.length; i += chunkSize) {
chunks.push(units.data.units.slice(i, i + chunkSize).map(u => u.id))
}
const promises = []
chunks.forEach(chunk => {
const url = `{{ $urls->api }}/proyecto/{{ $contract->project->id }}/unidades/estados`
const method = 'post'
const body = new FormData()
chunk.forEach(id => body.append('unidad_ids[]', id))
promises.push(APIClient.fetch(url, {method, body}).then(response => response.json()).then(json => {
if (json.estados.length === 0) {
return
}
json.estados.forEach(unidad => {
const idx = units.data.units.findIndex(u => u.id === parseInt(unidad.id))
units.data.units[idx].sold = unidad.sold
})
}))
})
return Promise.all(promises)
}
}
},
draw() {
return {
units: () => {
const table = $(`#${units.ids.units}`).DataTable()
table.clear()
const tableData = []
units.data.units.forEach(unidad => {
const tipo = unidad.proyecto_tipo_unidad.tipo_unidad.descripcion
const price = unidad.promotion?.price ?? (unidad.precio?.valor ?? 0)
const amount = unidad.promotion?.amount ?? 0
tableData.push([
tipo.charAt(0).toUpperCase() + tipo.slice(1),
unidad.proyecto_tipo_unidad.tipo_unidad.orden,
unidad.descripcion,
unidad.descripcion.padStart(4, '0'),
unidad.sold ? 'Vendida' : 'Disponible',
price === 0 ? '' : 'UF ' + units.formatters.ufs.format(price),
amount === 0 ? '' : units.formatters.percent.format(amount),
unidad.promotion?.start_date ?? '',
unidad.promotion?.end_date ?? '',
`<button type="button" class="ui small tertiary green icon button add_button" data-index="${unidad.id}"><i class="plus icon"></i></button>`
+ `<button type="button" class="ui small tertiary red icon button remove_button" data-index="${unidad.id}"><i class="remove icon"></i></button>`
+ `<div class="ui input"><input type="checkbox" name="unidad_ids[]" value="${unidad.id}"></div>`
])
})
table.rows.add(tableData)
table.draw()
},
tipos: () => {
const table = document.getElementById(units.ids.tipos)
const tbody = table.querySelector('tbody')
tbody.innerHTML = ''
const groups = Object.groupBy(units.data.units, unit => {
return unit.proyecto_tipo_unidad.tipo_unidad.descripcion
})
Object.entries(groups).forEach(([tipo, unidades]) => {
const precios = {
min: null,
avg: 0,
max: 0
}
const amounts = {
min: null,
avg: 0,
max: 0
}
unidades.forEach(unidad => {
if (precios.min === null) {
precios.min = unidad.promotion?.price ?? (unidad.precio?.valor ?? 0)
}
if (amounts.min === null) {
amounts.min = unidad.promotion?.amount ?? 0
}
precios.min = Math.min(precios.min, unidad.promotion?.price ?? (unidad.precio?.valor ?? 0))
precios.avg += unidad.promotion?.price ?? (unidad.precio?.valor ?? 0)
precios.max = Math.max(precios.max, unidad.promotion?.price ?? (unidad.precio?.valor ?? 0))
amounts.min = Math.min(amounts.min, unidad.promotion?.amount ?? 0)
amounts.avg += unidad.promotion?.amount ?? 0
amounts.max = Math.max(amounts.max, unidad.promotion?.amount ?? 0)
})
precios.avg /= unidades.length
amounts.avg /= unidades.length
tbody.innerHTML += [
`<tr>`,
`<td>${tipo.charAt(0).toUpperCase() + tipo.slice(1)}</td>`,
`<td class="center aligned">${unidades.length}</td>`,
`<td class="right aligned">UF ${units.formatters.ufs.format(precios.min)}</td>`,
`<td class="right aligned">UF ${units.formatters.ufs.format(precios.avg)}</td>`,
`<td class="right aligned">UF ${units.formatters.ufs.format(precios.max)}</td>`,
`<td class="right aligned">${units.formatters.percent.format(amounts.min)}</td>`,
`<td class="right aligned">${units.formatters.percent.format(amounts.avg)}</td>`,
`<td class="right aligned">${units.formatters.percent.format(amounts.max)}</td>`,
`<td class="right aligned"><button type="button" class="ui small tertiary green icon button add_tipo_button" data-tipo="${tipo}"><i class="plus icon"></i></button></td>`,
`</tr>`
].join("\n")
})
},
lineas: () => {
const table = document.getElementById(units.ids.lineas)
const tbody = table.querySelector('tbody')
const lineas = Object.groupBy(units.data.units, unit => {
return [unit.proyecto_tipo_unidad.tipo_unidad.descripcion, unit.proyecto_tipo_unidad.nombre, unit.orientacion]
})
Object.entries(lineas).sort(([linea1, unidades1], [linea2, unidades2]) => {
const split1 = linea1.split(',')
const split2 = linea2.split(',')
const ct = unidades1[0].proyecto_tipo_unidad.tipo_unidad.orden - unidades2[0].proyecto_tipo_unidad.tipo_unidad.orden
if (ct === 0) {
const cl = split1[1].localeCompare(split2[1])
if (cl === 0) {
return split1[2].localeCompare(split2[2])
}
return cl
}
return ct
}).forEach(([linea, unidades]) => {
[tipo, linea, orientacion] = linea.split(',')
const precios = {
min: null,
avg: 0,
max: 0
}
const amounts = {
min: null,
avg: 0,
max: 0
}
unidades.forEach(unidad => {
if (precios.min === null) {
precios.min = unidad.promotion?.price ?? (unidad.precio?.valor ?? 0)
}
if (amounts.min === null) {
amounts.min = unidad.promotion?.amount ?? 0
}
precios.min = Math.min(precios.min, unidad.promotion?.price ?? (unidad.precio?.valor ?? 0))
precios.avg += unidad.promotion?.price ?? (unidad.precio?.valor ?? 0)
precios.max = Math.max(precios.max, unidad.promotion?.price ?? (unidad.precio?.valor ?? 0))
amounts.min = Math.min(amounts.min, unidad.promotion?.amount ?? 0)
amounts.avg += unidad.promotion?.amount ?? 0
amounts.max = Math.max(amounts.max, unidad.promotion?.amount ?? 0)
})
precios.avg /= unidades.length
amounts.avg /= unidades.length
tbody.innerHTML += [
`<tr>`,
`<td>${tipo.charAt(0).toUpperCase() + tipo.slice(1)}</td>`,
`<td class="center aligned">${linea}</td>`,
`<td class="center aligned">${orientacion}</td>`,
`<td class="center aligned">${unidades[0].proyecto_tipo_unidad.tipologia}</td>`,
`<td class="center aligned">${unidades.length}</td>`,
`<td class="right aligned">UF ${units.formatters.ufs.format(precios.min)}</td>`,
`<td class="right aligned">UF ${units.formatters.ufs.format(precios.avg)}</td>`,
`<td class="right aligned">UF ${units.formatters.ufs.format(precios.max)}</td>`,
`<td class="right aligned">${units.formatters.percent.format(amounts.min)}</td>`,
`<td class="right aligned">${units.formatters.percent.format(amounts.avg)}</td>`,
`<td class="right aligned">${units.formatters.percent.format(amounts.max)}</td>`,
`<td class="right aligned"><button type="button" class="ui small tertiary green icon button add_linea_button" data-linea="${linea}"><i class="plus icon"></i></button></td>`,
`</tr>`
].join("\n")
})
}
}
},
setup(ids) {
units.ids = ids
const dto = structuredClone(datatables_defaults)
dto.pageLength = 100
dto.columnDefs = [
{
target: [1, 3],
visible: false
},
{
target: 0,
orderData: 1
},
{
target: 2,
orderData: 3
},
{
target: [2, 5, 6],
className: 'dt-right right aligned'
}
]
dto.order = [[1, 'asc'], [3, 'asc']]
dto.language.searchBuilder = searchBuilder
dto.layout = {
top1Start: {
searchBuilder: {
columns: [0, 2, 4, 5, 6, 7, 8],
}
},
}
$(`#${units.ids.units}`).DataTable(dto)
document.getElementById(units.ids.unidades_container).style.visibility = 'hidden'
document.getElementById(units.ids.tipos).style.visibility = 'hidden'
document.getElementById(units.ids.lineas).style.visibility = 'hidden'
units.get().units().then(() => {
units.get().prices().then(() => {
units.get().promotions().then(() => {
units.get().sold().then(() => {
$(units.ids.loader).hide()
document.getElementById(units.ids.unidades_container).style.visibility = 'visible'
document.getElementById(units.ids.tipos).style.visibility = 'visible'
document.getElementById(units.ids.lineas).style.visibility = 'visible'
units.draw().units()
units.draw().tipos()
units.draw().lineas()
})
})
})
})
}
}
$(document).ready(function () {
units.setup({units: 'unidades', unidades_container: 'unidades_container', tipos: 'tipos', lineas: 'lineas', loader: '.ui.loader'})
})
</script>
@endpush

View File

@ -44,7 +44,11 @@
<tbody id="contracts">
@foreach($broker->contracts() as $contract)
<tr>
<td>{{ $contract->project->descripcion }}</td>
<td>
<a href="{{ $urls->base }}/proyectos/broker/{{ $broker->rut }}/contract/{{ $contract->id }}">
{{ $contract->project->descripcion }}
</a>
</td>
<td>{{ $format->percent($contract->commission, 2, true) }}</td>
<td>{{ $contract->current()->date->format('d-m-Y') }}</td>
<td class="right aligned">