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,30 @@
<?php
declare(strict_types=1);
use Phinx\Migration\AbstractMigration;
final class CreatePromotionContract 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('promotion_contracts')
->addColumn('promotion_id', 'integer', ['signed' => false, 'null' => false])
->addColumn('contract_id', 'integer', ['signed' => false, 'null' => false])
->addColumn('created_at', 'datetime', ['null' => false, 'default' => 'CURRENT_TIMESTAMP'])
->addForeignKey('promotion_id', 'promotions', 'id', ['delete' => 'CASCADE', 'update' => 'CASCADE'])
->addForeignKey('contract_id', 'broker_contracts', 'id', ['delete' => 'CASCADE', 'update' => 'CASCADE'])
->create();
}
}

View File

@ -4,7 +4,7 @@ declare(strict_types=1);
use Phinx\Migration\AbstractMigration;
final class AlterPromotionsAddContractId extends AbstractMigration
final class AlterPromotionsRemovePrice extends AbstractMigration
{
/**
* Change Method.
@ -20,8 +20,8 @@ final class AlterPromotionsAddContractId extends AbstractMigration
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'])
->dropForeignKey('price_id')
->removeColumn('price_id')
->update();
}
}

View File

@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
use Phinx\Migration\AbstractMigration;
final class CreatePromotionUnit 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('promotion_units')
->addColumn('promotion_id', 'integer', ['signed' => false, 'null' => false])
->addColumn('unit_id', 'integer', ['signed' => false, 'null' => false])
->addColumn('created_at', 'datetime', ['null' => false, 'default' => 'CURRENT_TIMESTAMP'])
->addForeignKey('promotion_id', 'promotions', 'id', ['delete' => 'CASCADE', 'update' => 'CASCADE'])
->addForeignKey('unit_id', 'unidad', 'id', ['delete' => 'CASCADE', 'update' => 'CASCADE'])
->create();
}
}

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

View File

@ -7,33 +7,43 @@ use Incoviba\Model\Proyecto\Broker;
class Promotion extends Common\Ideal\Model
{
public Broker\Contract $contract;
public Precio $price;
public float $amount;
public DateTimeInterface $startDate;
public DateTimeInterface $endDate;
public DateTimeInterface $validUntil;
public int $state;
public function price(): float
protected array $contracts;
public function contracts(): array
{
return $this->price->valor * $this->amount;
if (empty($this->contracts)) {
$this->contracts = $this->runFactory('contracts');
}
return $this->contracts;
}
protected array $units;
public function units(): array
{
if (empty($this->units)) {
$this->units = $this->runFactory('units');
}
return $this->units;
}
protected function jsonComplement(): array
{
return [
'contract_rut' => $this->contract->id,
'price_id' => $this->price->id,
'amount' => $this->amount,
'price' => $this->price(),
'start_date' => $this->startDate->format('Y-m-d'),
'end_date' => $this->endDate->format('Y-m-d'),
'valid_until' => $this->validUntil->format('Y-m-d'),
'state' => [
'id' => $this->state,
'description' => Promotion\State::name($this->state)
]
],
'contracts' => $this->contracts() ?? [],
'units' => $this->units() ?? []
];
}
}

View File

@ -128,6 +128,21 @@ class Contract extends Common\Ideal\Repository
return $this->fetchOne($query, ['project_id' => $projectId, 'broker_rut' => $brokerRut, 'state' => Model\Proyecto\Broker\Contract\State\Type::ACTIVE->value]);
}
/**
* @param int $promotion_id
* @return array
* @throws Common\Implement\Exception\EmptyResult
*/
public function fetchByPromotion(int $promotion_id): array
{
$query = $this->connection->getQueryBuilder()
->select('a.*')
->from("{$this->getTable()} a")
->joined('INNER JOIN promotion_contracts pc ON pc.contract_id = a.id')
->where('pc.promotion_id = :promotion_id');
return $this->fetchMany($query, ['promotion_id' => $promotion_id]);
}
protected function statusJoin(): string
{
return 'INNER JOIN (SELECT bcs1.* FROM broker_contract_states bcs1 INNER JOIN (SELECT MAX(id) AS id, contract_id FROM broker_contract_states GROUP BY contract_id) bcs0 ON bcs0.id = bcs1.id) bcs ON bcs.contract_id = a.id';

View File

@ -20,16 +20,6 @@ class Promotion extends Common\Ideal\Repository
public function create(?array $data = null): Model\Venta\Promotion
{
$map = (new Common\Implement\Repository\MapperParser(['amount', 'type']))
->register('contract_id', (new Common\Implement\Repository\Mapper())
->setProperty('contract')
->setFunction(function($data) {
return $this->contractRepository->fetchById($data['contract_id']);
}))
->register('price_id', (new Common\Implement\Repository\Mapper())
->setProperty('price')
->setFunction(function($data) {
return $this->precioRepository->create($data);
}))
->register('start_date', new Common\Implement\Repository\Mapper\DateTime('start_date', 'startDate'))
->register('end_date', new Common\Implement\Repository\Mapper\DateTime('end_date', 'endDate'))
->register('valid_until', new Common\Implement\Repository\Mapper\DateTime('valid_until', 'validUntil'));
@ -39,15 +29,15 @@ class Promotion extends Common\Ideal\Repository
public function save(Common\Define\Model $model): Model\Venta\Promotion
{
$model->id = $this->saveNew(
['contract_id', 'amount', 'type', 'start_date', 'end_date', 'valid_until', 'price_id'],
[$model->contract->id, $model->amount, $model->type, $model->startDate->format('Y-m-d'),
$model->endDate->format('Y-m-d'), $model->validUntil->format('Y-m-d'), $model->price->id]
['amount', 'type', 'start_date', 'end_date', 'valid_until'],
[$model->amount, $model->type, $model->startDate->format('Y-m-d'),
$model->endDate->format('Y-m-d'), $model->validUntil->format('Y-m-d')]
);
return $model;
}
public function edit(Common\Define\Model $model, array $new_data): Model\Venta\Promotion
{
return $this->update($model, ['contract_id', 'amount', 'type', 'start_date', 'end_date', 'valid_until', 'price_id'], $new_data);
return $this->update($model, ['amount', 'type', 'start_date', 'end_date', 'valid_until'], $new_data);
}
/**
@ -58,9 +48,10 @@ class Promotion extends Common\Ideal\Repository
public function fetchByContract(int $contract_id): array
{
$query = $this->connection->getQueryBuilder()
->select()
->from($this->getTable())
->where('contract_id = :contract_id');
->select('a.*')
->from("{$this->getTable()} a")
->joined('INNER JOIN promotion_contracts pc ON pc.promotion_id = a.id')
->where('pc.contract_id = :contract_id');
return $this->fetchMany($query, ['contract_id' => $contract_id]);
}
@ -72,38 +63,41 @@ class Promotion extends Common\Ideal\Repository
public function fetchActiveByContract(int $contract_id): array
{
$query = $this->connection->getQueryBuilder()
->select()
->from($this->getTable())
->where('contract_id = :contract_id AND state = :state');
->select('a.*')
->from("{$this->getTable()} a")
->joined('INNER JOIN promotion_contracts pc ON pc.promotion_id = a.id')
->where('pc.contract_id = :contract_id AND a.state = :state');
return $this->fetchMany($query, ['contract_id' => $contract_id, 'state' => Model\Venta\Promotion\State::ACTIVE]);
}
/**
* @param int $price_id
* @param int $unit_id
* @return array
* @throws Common\Implement\Exception\EmptyResult
*/
public function fetchByPrice(int $price_id): array
public function fetchByUnit(int $unit_id): array
{
$query = $this->connection->getQueryBuilder()
->select()
->from($this->getTable())
->where('price_id = :price_id');
return $this->fetchMany($query, ['price_id' => $price_id]);
->select('a.*')
->from("{$this->getTable()} a")
->joined('INNER JOIN promotion_units pu ON pu.promotion_id = a.id')
->where('pu.unit_id = :unit_id');
return $this->fetchMany($query, ['unit_id' => $unit_id]);
}
/**
* @param int $price_id
* @param int $unit_id
* @return array
* @throws Common\Implement\Exception\EmptyResult
*/
public function fetchActiveByPrice(int $price_id): array
public function fetchActiveByUnit(int $unit_id): array
{
$query = $this->connection->getQueryBuilder()
->select()
->from($this->getTable())
->where('price_id = :price_id AND state = :state');
return $this->fetchMany($query, ['price_id' => $price_id, 'state' => Model\Venta\Promotion\State::ACTIVE]);
->select('a.*')
->from("{$this->getTable()} a")
->joined('INNER JOIN promotion_units pu ON pu.promotion_id = a.id')
->where('pu.unit_id = :unit_id AND a.state = :state');
return $this->fetchMany($query, ['unit_id' => $unit_id, 'state' => Model\Venta\Promotion\State::ACTIVE]);
}
/**
@ -116,8 +110,8 @@ class Promotion extends Common\Ideal\Repository
$query = $this->connection->getQueryBuilder()
->select('a.*')
->from("{$this->getTable()} a")
->joined('INNER JOIN precio ON precio.id = a.price_id')
->joined('INNER JOIN unidad ON unidad.id = precio.unidad')
->joined('INNER JOIN promotion_units pu ON pu.promotion_id = a.id')
->joined('INNER JOIN unidad ON unidad.id = pu.unit_id')
->joined('INNER JOIN proyecto_tipo_unidad ON proyecto_tipo_unidad.id = unidad.pt')
->joined('INNER JOIN proyecto ON proyecto.id = proyecto_tipo_unidad.proyecto')
->where('proyecto.id = :project_id');
@ -134,8 +128,8 @@ class Promotion extends Common\Ideal\Repository
$query = $this->connection->getQueryBuilder()
->select('a.*')
->from("{$this->getTable()} a")
->joined('INNER JOIN precio ON precio.id = a.price_id')
->joined('INNER JOIN unidad ON unidad.id = precio.unidad')
->joined('INNER JOIN promotion_units pu ON pu.promotion_id = a.id')
->joined('INNER JOIN unidad ON unidad.id = pu.unit_id')
->joined('INNER JOIN proyecto_tipo_unidad ON proyecto_tipo_unidad.id = unidad.pt')
->joined('INNER JOIN proyecto ON proyecto.id = proyecto_tipo_unidad.proyecto')
->where('proyecto.id = :project_id AND a.state = :state');
@ -153,9 +147,9 @@ class Promotion extends Common\Ideal\Repository
$query = $this->connection->getQueryBuilder()
->select('a.*')
->from("{$this->getTable()} a")
->joined('INNER JOIN precio ON precio.id = a.price_id')
->joined('INNER JOIN unidad ON unidad.id = precio.unidad')
->where('a.contract_id = :contract_id AND unidad.id = :unit_id');
->joined('INNER JOIN promotion_contracts pc ON pc.promotion_id = a.id')
->joined('INNER JOIN promotion_units pu ON pu.promotion_id = a.id')
->where('pc.contract_id = :contract_id AND pu.unit_id = :unit_id');
return $this->fetchOne($query, ['contract_id' => $contract_id, 'unit_id' => $unit_id]);
}
}

View File

@ -185,6 +185,21 @@ class Unidad extends Ideal\Repository
return $this->fetchOne($query, ['unidad_id' => $unidad_id]);
}
/**
* @param int $promotion_id
* @return array
* @throws Implement\Exception\EmptyResult
*/
public function fetchByPromotion(int $promotion_id): array
{
$query = $this->connection->getQueryBuilder()
->select('a.*')
->from("{$this->getTable()} a")
->joined('INNER JOIN `promotion_units` pu ON pu.`unit_id` = a.`id`')
->where('pu.`promotion_id` = :promotion_id');
return $this->fetchMany($query, ['promotion_id' => $promotion_id]);
}
protected function joinProrrateo(): string
{
return "LEFT OUTER JOIN unidad_prorrateo up ON up.unidad_id = a.id";

View File

@ -13,7 +13,8 @@ class Promotion extends Ideal\Service
{
public function __construct(LoggerInterface $logger,
protected Repository\Venta\Promotion $promotionRepository,
protected Repository\Proyecto\Broker\Contract $contractRepository)
protected Repository\Proyecto\Broker\Contract $contractRepository,
protected Repository\Venta\Unidad $unidadRepository)
{
parent::__construct($logger);
}
@ -80,6 +81,12 @@ class Promotion extends Ideal\Service
protected function process(Model\Venta\Promotion $model): Model\Venta\Promotion
{
$model->addFactory('contracts', (new Implement\Repository\Factory())
->setCallable([$this->contractRepository, 'fetchByPromotion'])
->setArgs(['promotion_id' => $model->id]));
$model->addFactory('units', (new Implement\Repository\Factory())
->setCallable([$this->unidadRepository, 'fetchByPromotion'])
->setArgs(['promotion_id' => $model->id]));
return $model;
}
}