Separacion de Promocion de Contrato y Precio

"Simplificacion" de datos en listado de precios
This commit is contained in:
Juan Pablo Vial
2025-03-17 22:49:48 -03:00
parent 2e49e2c947
commit bae0f1f555
13 changed files with 479 additions and 278 deletions

View File

@ -0,0 +1,6 @@
@prepend('page_scripts')
<script src='https://unpkg.com/simple-statistics@7.8.8/dist/simple-statistics.min.js'></script>
<script>
const Stat = ss
</script>
@endprepend

View File

@ -8,11 +8,46 @@
{{ $contract->broker->name }} - {{ $contract->project->descripcion }}
@endsection
@include('layout.body.scripts.stats')
@prepend('page_scripts')
<script>
class TableHandler {
commission
constructor(commission) {
this.commission = commission
}
draw() {}
prices(units) {
const prices = []
units.forEach(unit => {
const price = unit.precio?.valor ?? 0
let amount = 1
unit.promotions?.forEach(promotion => {
amount /= 1/(1 - promotion.amount)
})
amount /= 1/(1 - this.commission)
amount = 1 - amount
prices.push({
id: unit.id,
base: price,
amount,
final: price / (1 - amount)
})
})
return prices
}
}
</script>
@endprepend
@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 class="ui statistic">
<div class="value">{{ $format->percent($contract->commission, 2, true) }}</div>
<div class="label">
Comisión desde {{ $contract->current()->date->format('d/m/Y') }}
</div>
</div>
<br />
<div class="ui active inline loader"></div>
<div id="results">
<div class="ui top attached tabular menu">
@ -21,75 +56,20 @@
<a class="item" data-tab="unidades">Unidades</a>
</div>
<div class="ui bottom attached tab basic horizontally fitted segment active" data-tab="tipos">
<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>
@include('proyectos.brokers.contracts.show.tipo')
</div>
<div class="ui bottom attached tab basic horizontally fitted segment" data-tab="lineas">
<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">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>
@include('proyectos.brokers.contracts.show.linea')
</div>
<div class="ui bottom attached tab basic horizontally fitted segment" data-tab="unidades">
<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>
@include('proyectos.brokers.contracts.show.unidades')
</div>
</div>
@endsection
@include('layout.body.scripts.datatables')
@include('layout.body.scripts.datatables.searchbuilder')
@include('layout.body.scripts.datatables.buttons')
@push('page_scripts')
<script>
@ -100,12 +80,18 @@
},
data: {
project_id: {{ $contract->project->id }},
commission: {{ $contract->commission }},
units: []
},
formatters: {
ufs: new Intl.NumberFormat('es-CL', { style: 'decimal', minimumFractionDigits: 2, maximumFractionDigits: 2 }),
percent: new Intl.NumberFormat('es-CL', { style: 'percent', minimumFractionDigits: 2 })
},
handlers: {
tipo: null,
linea: null,
unit: null
},
get() {
return {
units: () => {
@ -139,7 +125,7 @@
}
json.unidades.forEach(unidad => {
const idx = units.data.units.findIndex(u => u.id === parseInt(unidad.id))
units.data.units[idx].promotion = unidad.promotion
units.data.units[idx].promotions = unidad.promotions
})
}))
})
@ -198,179 +184,22 @@
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()
units.handlers.units.draw({units: units.data.units, formatters: units.formatters})
},
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")
})
units.handlers.tipo.draw({units: units.data.units, formatters: units.formatters})
},
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"><span data-tooltip="${unidades[0].proyecto_tipo_unidad.tipologia}" data-position="right center">${linea}</span></td>`,
`<td class="center aligned">${orientacion}</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")
})
units.handlers.lineas.draw({units: units.data.units, formatters: units.formatters})
}
}
},
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)
units.handlers.tipo = new TipoTable(units.data.commission)
units.handlers.lineas = new LineasTable(units.data.commission)
units.handlers.units = new UnitsTable(units.data.commission)
$(`#${units.ids.results}`).find('.tabular.menu .item').tab({
onVisible: function(tabPath) {
@ -401,7 +230,7 @@
}
}
$(document).ready(function () {
units.setup({results: 'results', units: 'unidades', tipos: 'tipos', lineas: 'lineas', loader: '.ui.loader'})
units.setup({results: 'results', loader: '.ui.loader'})
})
</script>
@endpush

View File

@ -0,0 +1,80 @@
<table class="ui table" id="lineas">
<thead>
<tr>
<th>Tipo</th>
<th class="center aligned">Línea</th>
<th class="center aligned">Orientación</th>
<th class="center aligned">Cantidad</th>
<th class="right aligned" style="text-decoration: overline">Precio Lista</th>
<th class="right aligned" style="text-decoration: overline">Porcentaje</th>
<th class="right aligned" style="text-decoration: overline">Precio Final</th>
</tr>
</thead>
<tbody></tbody>
</table>
@push('page_scripts')
<script>
class LineasTable extends TableHandler {
ids = {
lineas: 'lineas'
}
constructor(commission) {
super(commission)
}
draw({units, formatters}) {
const table = document.getElementById(this.ids.lineas)
const tbody = table.querySelector('tbody')
const lineas = Object.groupBy(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]) => {
const parts = linea.split(',')
const tipo = parts[0]
const orientacion = parts[2]
const prices = this.prices(unidades)
const base_tooltip = [
`Min: UF ${formatters.ufs.format(Math.min(...prices.map(p => p.base)))}`,
`Max: UF ${formatters.ufs.format(Math.max(...prices.map(p => p.base)))}`,
`Desv: UF ${formatters.ufs.format(Stat.standardDeviation(prices.map(p => p.base)))}`
].join("\n").replaceAll(' ', '&nbsp;')
const amount_tooltip = [
`Min: ${formatters.percent.format(Math.min(...prices.map(p => p.amount)))}`,
`Max: ${formatters.percent.format(Math.max(...prices.map(p => p.amount)))}`,
`Desv: ${formatters.percent.format(Stat.standardDeviation(prices.map(p => p.amount)))}`
].join("\n").replaceAll(' ', '&nbsp;')
const final_tooltip = [
`Min: UF ${formatters.ufs.format(Math.min(...prices.map(p => p.final)))}`,
`Max: UF ${formatters.ufs.format(Math.max(...prices.map(p => p.final)))}`,
`Desv: UF ${formatters.ufs.format(Stat.standardDeviation(prices.map(p => p.final)))}`
].join("\n").replaceAll(' ', '&nbsp;')
tbody.innerHTML += [
`<tr>`,
`<td>${tipo.charAt(0).toUpperCase() + tipo.slice(1)}</td>`,
`<td class="center aligned"><span data-tooltip="${unidades[0].proyecto_tipo_unidad.tipologia}" data-position="right center">${parts[1]}</span></td>`,
`<td class="center aligned">${orientacion}</td>`,
`<td class="center aligned">${unidades.length}</td>`,
`<td class="right aligned"><span data-tooltip="${base_tooltip}" data-position="right center" data-variation="wide multiline">UF ${formatters.ufs.format(Stat.mean(prices.map(p => p.base)))}</span></td>`,
`<td class="right aligned"><span data-tooltip="${amount_tooltip}" data-position="right center" data-variation="wide multiline">${formatters.percent.format(Stat.mean(prices.map(p => p.amount)))}</span></td>`,
`<td class="right aligned"><span data-tooltip="${final_tooltip}" data-position="right center" data-variation="wide multiline">UF ${formatters.ufs.format(Stat.mean(prices.map(p => p.final)))}</span></td>`,
`</tr>`
].join("\n")
})
}
}
</script>
@endpush

View File

@ -0,0 +1,61 @@
<table class="ui table" id="tipos">
<thead>
<tr>
<th>Tipo</th>
<th class="center aligned">Cantidad</th>
<th class="right aligned" style="text-decoration: overline">Precio Base</th>
<th class="right aligned" style="text-decoration: overline">Porcentaje</th>
<th class="right aligned" style="text-decoration: overline">Precio Final</th>
</tr>
</thead>
<tbody></tbody>
</table>
@push('page_scripts')
<script>
class TipoTable extends TableHandler {
ids = {
tipos: 'tipos'
}
constructor(commission) {
super(commission)
}
draw({units, formatters}) {
const table = document.getElementById(this.ids.tipos)
const tbody = table.querySelector('tbody')
tbody.innerHTML = ''
const groups = Object.groupBy(units, unit => {
return unit.proyecto_tipo_unidad.tipo_unidad.descripcion
})
Object.entries(groups).forEach(([tipo, unidades]) => {
const prices = this.prices(unidades)
const base_tooltip = [
`Min: UF ${formatters.ufs.format(Math.min(...prices.map(p => p.base)))}`,
`Max: UF ${formatters.ufs.format(Math.max(...prices.map(p => p.base)))}`,
`Desv: UF ${formatters.ufs.format(Stat.standardDeviation(prices.map(p => p.base)))}`
].join("\n").replaceAll(' ', '&nbsp;')
const amount_tooltip = [
`Min: ${formatters.percent.format(Math.min(...prices.map(p => p.amount)))}`,
`Max: ${formatters.percent.format(Math.max(...prices.map(p => p.amount)))}`,
`Desv: ${formatters.percent.format(Stat.standardDeviation(prices.map(p => p.amount)))}`
].join("\n").replaceAll(' ', '&nbsp;')
const final_tooltip = [
`Min: UF ${formatters.ufs.format(Math.min(...prices.map(p => p.final)))}`,
`Max: UF ${formatters.ufs.format(Math.max(...prices.map(p => p.final)))}`,
`Desv: UF ${formatters.ufs.format(Stat.standardDeviation(prices.map(p => p.final)))}`
].join("\n").replaceAll(' ', '&nbsp;')
tbody.innerHTML += [
`<tr>`,
`<td>${tipo.charAt(0).toUpperCase() + tipo.slice(1)}</td>`,
`<td class="center aligned">${unidades.length}</td>`,
`<td class="right aligned"><span data-tooltip="${base_tooltip}" data-position="right center" data-variation="wide multiline">UF ${formatters.ufs.format(Stat.mean(prices.map(p => p.base)))}</span></td>`,
`<td class="right aligned"><span data-tooltip="${amount_tooltip}" data-position="right center" data-variation="wide multiline">${formatters.percent.format(Stat.mean(prices.map(p => p.amount)))}</span></td>`,
`<td class="right aligned"><span data-tooltip="${final_tooltip}" data-position="right center" data-variation="wide multiline">UF ${formatters.ufs.format(Stat.mean(prices.map(p => p.final)))}</span></td>`,
`</tr>`
].join("\n")
})
}
}
</script>
@endpush

View File

@ -0,0 +1,124 @@
<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 Lista</th>
<th class="right aligned">Porcentaje</th>
<th class="right aligned">Precio Final</th>
<th>Fecha Inicio</th>
<th>Fecha Término</th>
</tr>
</thead>
<tbody></tbody>
</table>
@push('page_scripts')
<script>
class UnitsTable extends TableHandler {
ids = {
units: 'unidades',
}
constructor(commission) {
super(commission)
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, 7],
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, 9],
}
},
top1End: {
buttons: [
{
extend: 'excelHtml5',
className: 'green',
text: 'Exportar a Excel <i class="file excel icon"></i>',
title: 'Comisiones {{ $contract->broker->name }} {{ $contract->project->descripcion }}',
download: 'open',
exportOptions: {
columns: [0, 2, 4, 5, 6, 7],
/*format: {
body: (data, row, columnIdx, node) => {
const formats = this.columns.filter(columnDef => columnDef.format)
const match = formats.map(({title}) => title).indexOf(this.columns[columnIdx].title)
if (match > -1) {
return formats[match].format(data)
}
if (typeof data === 'string' && data.includes('<span data-tooltip')) {
return data.replace(/<span data-tooltip="(.*)">(.*)<\/span>/, '$2')
}
return data
}
}*/
},
customize: xlsx => {
const sheet = xlsx.xl.worksheets['sheet1.xml']
const columns = Object.values($('row[r="2"] t', sheet).map((idx, column) => column.textContent))
const columnStylesMap = {
Valor: '63',
Fecha: '15'
}
Object.entries(columnStylesMap).forEach((column, style) => {
const columnIndex = String.fromCharCode('A'.charCodeAt(0) + columns.indexOf(column))
$(`c[r^="${columnIndex}"]`, sheet).attr('s', style)
})
}
}
]
}
}
$(`#${this.ids.units}`).DataTable(dto)
}
draw({units, formatters}) {
const table = $(`#${this.ids.units}`).DataTable()
table.clear()
const tableData = []
const prices = this.prices(units)
units.forEach(unidad => {
const tipo = unidad.proyecto_tipo_unidad.tipo_unidad.descripcion
const price = prices.find(p => p.id === unidad.id)
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',
'UF ' + formatters.ufs.format(price.base ?? 0),
formatters.percent.format(price.amount ?? 0),
'UF ' + formatters.ufs.format(price.final ?? 0),
unidad.promotion?.start_date ?? '',
unidad.promotion?.end_date ?? '',
])
})
table.rows.add(tableData)
table.draw()
}
}
</script>
@endpush