feature/cierres (#25)

Varios cambios

Co-authored-by: Juan Pablo Vial <jpvialb@incoviba.cl>
Reviewed-on: #25
This commit is contained in:
2025-07-22 13:18:00 +00:00
parent ba57cad514
commit 307f2ac7d7
418 changed files with 20045 additions and 984 deletions

View File

@ -0,0 +1,219 @@
@extends('proyectos.brokers.base')
@section('brokers_content')
<table id="brokers" class="ui table">
<thead>
<tr>
<th>RUT</th>
<th>Nombre</th>
<th>Contacto</th>
<th>Contratos</th>
<th class="right aligned">
<button class="ui small tertiary green icon button" id="add_button">
<i class="plus icon"></i>
</button>
</th>
</tr>
</thead>
@foreach($brokers as $broker)
<tr>
<td class="top aligned">
<span
@if ($broker->data()?->legalName !== '')
data-tooltip="{{ $broker->data()?->legalName }}" data-position="right center"
@endif
>
{{$broker->rutFull()}}
</span>
</td>
<td class="top aligned">
<a href="{{ $urls->base }}/proyectos/broker/{{ $broker->rut }}">
{{$broker->name}}
<i class="angle right icon"></i>
</a>
</td>
<td class="top aligned">
<span
@if ($broker->data()?->representative?->email !== '' || $broker->data()?->representative?->phone !== '')
data-tooltip="{{ ($broker->data()?->representative?->email !== '') ? "Email: " . $broker->data()?->representative?->email : '' }}{{ ($broker->data()?->representative?->phone !== '') ? ' Teléfono: ' . $broker->data()?->representative?->phone : '' }}" data-position="right center"
@endif
>
{{ $broker->data()?->representative?->name }}
</span>
</td>
<td class="top aligned">
<div class="ui list">
@foreach($broker->contracts() as $contract)
<div class="item">
<a href="{{$urls->base}}/proyectos/broker/{{$broker->rut}}/contract/{{$contract->id}}" data-tooltip="{{$contract->current()->date->format('d-m-Y')}}" data-position="right center">
{{$contract->project->descripcion}} ({{$format->percent($contract->commission, 2, true)}})
</a>
</div>
@endforeach
</div>
</td>
<td class="top aligned right aligned">
<button class="ui small tertiary icon button edit_button" data-index="{{$broker->rut}}">
<i class="edit icon"></i>
</button>
<button class="ui small tertiary red icon button remove_button" data-index="{{$broker->rut}}">
<i class="remove icon"></i>
</button>
</td>
</tr>
@endforeach
</table>
@include('proyectos.brokers.add_modal')
@include('proyectos.brokers.edit_modal')
@endsection
@push('page_scripts')
<script>
function storeBrokers() {
localStorage.setItem('brokers', '{!! json_encode(array_map(function($broker) {
$arr = json_decode(json_encode($broker), true);
array_walk_recursive($arr, function(&$val, $key) {
if ($val === null) {
$val = '';
}
});
$arr['contracts'] = $broker->contracts();
return $arr;
}, $brokers)) !!}')
}
const brokersHandler = {
ids: {
buttons: {
add: 'add_button',
edit: 'edit_button',
remove: 'remove_button'
},
modals: {
add: '',
edit: ''
},
forms: {
add: '',
edit: ''
}
},
modals: {
add: null,
edit: null
},
events() {
return {
add: clickEvent => {
clickEvent.preventDefault()
brokersHandler.actions().add()
},
edit: clickEvent => {
clickEvent.preventDefault()
const broker_rut = parseInt(clickEvent.currentTarget.dataset.index)
brokersHandler.actions().edit(broker_rut)
},
delete: clickEvent => {
clickEvent.preventDefault()
const broker_rut = clickEvent.currentTarget.dataset.index
brokersHandler.actions().delete(broker_rut)
}
}
},
buttonWatch() {
document.getElementById(brokersHandler.ids.buttons.add).addEventListener('click', brokersHandler.events().add)
Array.from(document.getElementsByClassName(brokersHandler.ids.buttons.edit)).forEach(button => {
button.addEventListener('click', brokersHandler.events().edit)
})
Array.from(document.getElementsByClassName(brokersHandler.ids.buttons.remove)).forEach(button => {
button.addEventListener('click', brokersHandler.events().delete)
})
},
actions() {
return {
add: () => {
this.modals.add.show()
},
edit: broker_rut => {
const localData = JSON.parse(localStorage.getItem('brokers'))
const broker = localData.find(broker => broker.rut === broker_rut)
const data = {
rut: broker_rut,
name: broker.name,
legal_name: broker.data?.legal_name || '',
contact: broker.data?.representative?.name || '',
email: broker.data?.representative?.email || '',
phone: broker.data?.representative?.phone || '',
address: broker.data?.representative?.address || '',
contracts: broker.contracts
}
this.modals.edit.load(data)
},
delete: broker_rut => {
brokersHandler.execute().delete(broker_rut)
}
}
},
execute() {
return {
add: data => {
const url = '{{$urls->api}}/proyectos/brokers/add'
const method = 'post'
const body = new FormData()
body.append('brokers[]', JSON.stringify(data))
return APIClient.fetch(url, {method, body}).then(response => response.json()).then(json => {
if (!json.success) {
console.error(json.errors)
alert('No se pudo agregar operador.')
return
}
window.location.reload()
})
},
edit: data => {
const url = '{{$urls->api}}/proyectos/brokers/edit'
const method = 'post'
const body = new FormData()
body.append('brokers[]', JSON.stringify(data))
return APIClient.fetch(url, {method, body}).then(response => response.json()).then(json => {
if (!json.success) {
console.error(json.errors)
alert('No se pudo editar operador.')
return
}
window.location.reload()
})
},
delete: broker_rut => {
const url = '{{$urls->api}}/proyectos/broker/' + broker_rut
const method = 'delete'
return APIClient.fetch(url, {method}).then(response => response.json()).then(json => {
if (!json.success) {
console.error(json.errors)
alert('No se pudo eliminar operador.')
return
}
window.location.reload()
})
}
}
},
setup(ids) {
brokersHandler.ids = ids
brokersHandler.buttonWatch()
this.modals.add = new AddModal(brokersHandler)
this.modals.edit = new EditModal(brokersHandler)
}
}
$(document).ready(() => {
storeBrokers()
brokersHandler.setup({
buttons: {
add: 'add_button',
edit: 'edit_button',
remove: 'remove_button',
},
})
})
</script>
@endpush

View File

@ -0,0 +1,115 @@
<div class="ui modal" id="add_broker_modal">
<div class="header">
Agregar Operador
</div>
<div class="content">
<form class="ui form" id="add_broker_form">
<div class="fields">
<div class="field">
<label>RUT</label>
<div class="ui right labeled input">
<input type="text" name="rut" placeholder="RUT" maxlength="10" required />
<div class="ui basic label">-<span id="digit"></span></div>
</div>
</div>
</div>
<div class="fields">
<div class="field">
<label>Nombre</label>
<input type="text" name="name" placeholder="Nombre" required />
</div>
<div class="six wide field">
<label>Razón Social</label>
<input type="text" name="legal_name" placeholder="Razón Social" required />
</div>
</div>
<div class="fields">
<div class="field">
<label>Contacto</label>
<input type="text" name="contact" placeholder="Contacto" />
</div>
</div>
<div class="fields">
<div class="field">
<label>Correo</label>
<input type="email" name="email" placeholder="Correo" />
</div>
<div class="field">
<label>Teléfono</label>
<input type="text" name="phone" placeholder="Teléfono" />
</div>
</div>
</form>
</div>
<div class="actions">
<div class="ui deny button">
Cancelar
</div>
<div class="ui positive right labeled icon button">
Agregar
<i class="checkmark icon"></i>
</div>
</div>
</div>
@include('layout.body.scripts.rut')
@push('page_scripts')
<script>
class AddModal {
ids
modal
handler
constructor(handler) {
this.handler = handler
this.ids = {
modal: 'add_broker_modal',
form: 'add_broker_form',
digit: 'digit'
}
this.modal = $(`#${this.ids.modal}`)
this.modal.modal({
onApprove: () => {
const form = document.getElementById(this.ids.form)
const data = {
rut: form.querySelector('[name="rut"]').value.replace(/\D/g, ''),
digit: Rut.digitoVerificador(form.querySelector('[name="rut"]').value),
name: form.querySelector('[name="name"]').value,
legal_name: form.querySelector('[name="legal_name"]').value,
contact: form.querySelector('[name="contact"]').value || '',
email: form.querySelector('[name="email"]').value || '',
phone: form.querySelector('[name="phone"]').value || ''
}
this.handler.execute().add(data)
}
})
this.modal.modal('hide')
const value = document.querySelector(`#${this.ids.form} input[name="rut"]`).value
this.update().digit(value)
this.watch().rut()
}
update() {
return {
digit: value => {
if (value.length > 3) {
document.getElementById(this.ids.digit).textContent = Rut.digitoVerificador(value)
}
}
}
}
watch() {
return {
rut: () => {
document.querySelector(`#${this.ids.form} input[name="rut"]`).addEventListener('input', event => {
const value = event.currentTarget.value
this.update().digit(value)
})
}
}
}
show() {
this.modal.modal('show')
}
}
</script>
@endpush

View File

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

View File

@ -0,0 +1,489 @@
@extends('proyectos.brokers.base')
@section('brokers_title')
{{ $contract->broker->name }} - {{ $contract->project->descripcion }}
@endsection
@section('brokers_header')
{{ $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) {
return units.map(unit => {
let price = unit.valor ?? (unit.precio?.valor ?? 0)
const broker = price / (1 - this.commission)
const promotions = unit.promotions?.map(promotion => {
if (promotion.type === 1) {
return {
name: promotion.description,
type: promotion.type,
amount: promotion.amount,
final: broker + promotion.amount
}
}
return {
name: promotion.description,
type: promotion.type,
amount: promotion.amount,
final: broker / (1 - promotion.amount)
}
}) ?? []
return {
id: unit.id,
base: price,
commission: this.commission,
broker,
promotions
}
})
}
}
class GroupedTableHandler extends TableHandler {
promotions = {
names: new Set(),
values: []
}
process() {
return {
prices: prices => {
let promotions = {}
prices.map(price => price.promotions).forEach(promotionArray => {
promotionArray.forEach(p => {
if (!Object.hasOwn(promotions, p.name)) {
promotions[p.name] = {
name: p.name,
type: p.type,
amount: [],
final: []
}
}
promotions[p.name].amount.push(p.amount)
promotions[p.name].final.push(p.final)
})
})
return promotions
},
promotions: () => {
return {
names: promotions => {
Object.keys(promotions).forEach(name => {
this.add().promotion().name(name)
})
},
values: ({promotions, formatters}) => {
const temp = Object.values(promotions)
if (temp.length > 0) {
const data = temp.map(p => {
return {
name: p.name,
type: p.type,
amount: {
min: Math.min(...p.amount),
max: Math.max(...p.amount),
desv: Stat.standardDeviation(p.amount),
mean: Stat.mean(p.amount)
},
final: {
min: Math.min(...p.final),
max: Math.max(...p.final),
desv: Stat.standardDeviation(p.final),
mean: Stat.mean(p.final)
}
}
})
this.add().promotion().values({promotions: data, formatters})
return
}
this.promotions.values.push([])
}
}
}
}
}
add() {
return {
promotion: () => {
return {
name: name => {
this.promotions.names.add(name)
},
values: ({promotions, formatters}) => {
this.promotions.values.push(promotions.map(promotion => {
const amount_tooltip = [
`Min: ${promotion.type === 1 ? 'UF ' + formatters.ufs.format(promotion.amount.min) : formatters.percent.format(promotion.amount.min)}`,
`Max: ${promotion.type === 1 ? 'UF ' + formatters.ufs.format(promotion.amount.max) : formatters.percent.format(promotion.amount.max)}`,
`Desv: ${promotion.type === 1 ? 'UF ' + formatters.ufs.format(promotion.amount.desv) : formatters.percent.format(promotion.amount.desv)}`
].join("\n").replaceAll(' ', '&nbsp;')
const final_tooltip = [
`Min: UF ${formatters.ufs.format(promotion.final.min)}`,
`Max: UF ${formatters.ufs.format(promotion.final.max)}`,
`Desv: UF ${formatters.ufs.format(promotion.final.desv)}`
].join("\n").replaceAll(' ', '&nbsp;')
return {
name: promotion.name,
value: [
`<td class="right aligned"><span data-tooltip="${amount_tooltip}" data-position="right center" data-variation="wide multiline">${promotion.type === 1 ? formatters.ufs.format(promotion.amount.mean) : formatters.percent.format(promotion.amount.mean)}</td>`,
`<td class="right aligned"><span data-tooltip="${final_tooltip}" data-position="right center" data-variation="wide multiline">UF ${formatters.ufs.format(promotion.final.mean)}</td></td>`,
].join("\n")
}
}))
}
}
}
}
}
build() {
return {
promotions: (table, tbody) => {
if (this.promotions.names.size > 0) {
const title = document.getElementById(this.ids.promotions)
title.innerHTML = this.promotions.names.size > 0 ? Array.from(this.promotions.names)[0] : ''
title.setAttribute('colspan', '2')
if (this.promotions.names.size > 1) {
const thead = table.querySelector('thead')
Array.from(this.promotions.names).slice(1).forEach(name => {
thead.insertAdjacentHTML('beforeend', `<th class="right aligned" style="text-decoration: overline" colspan="2">${name}</th>`)
})
}
const trs = tbody.querySelectorAll('tr')
this.promotions.values.forEach((row, i) => {
const tr = trs[i]
const td = tr.querySelector('td.promotions')
if (row.length === 0) {
td.setAttribute('colspan', 2 * this.promotions.names.size)
return
}
td.remove()
this.promotions.names.forEach(name => {
const index = row.findIndex(r => r.name === name)
if (index === -1) {
tr.insertAdjacentHTML('beforeend', '<td colspan="2"></td>')
return
}
tr.insertAdjacentHTML('beforeend', row[index].value)
})
})
}
}
}
}
}
</script>
@endprepend
@section('brokers_content')
<div class="ui statistic">
<div class="value">{{ $format->percent($contract->commission ?? 0, 2, true) }}</div>
<div class="label">
Comisión desde {{ $contract->current()?->date?->format('d/m/Y') }}
</div>
</div>
<br />
<div class="ui card">
<div class="content">
<div class="header">
Promociones Aplicadas
</div>
<div class="description">
@if (count($contract->promotions()) === 0)
- Ninguna
@else
<div class="ui list">
@foreach ($contract->promotions() as $promotion)
<div class="item">
{{ $promotion->description }} {{ $format->percent($promotion->amount, 2, true) }} {{ ucwords($promotion->type->name()) }}
</div>
@endforeach
</div>
@endif
</div>
</div>
</div>
<div class="ui very basic segment">
<div class="ui active inline loader" id="loader"></div>
<div class="ui indicating progress" id="load_progress">
<div class="bar">
<div class="progress"></div>
</div>
</div>
</div>
<div id="results">
<div class="ui top attached tabular menu">
<a class="item active" data-tab="tipos">Tipos</a>
<a class="item" data-tab="lineas">Líneas</a>
<a class="item" data-tab="unidades">Unidades</a>
</div>
<div class="ui top attached indicating progress" id="values_progress">
<div class="bar"></div>
</div>
<div class="ui bottom attached tab basic fitted segment active" data-tab="tipos">
@include('proyectos.brokers.contracts.show.tipo')
</div>
<div class="ui bottom attached tab basic fitted segment" data-tab="lineas">
@include('proyectos.brokers.contracts.show.linea')
</div>
<div class="ui bottom attached tab basic fitted segment" data-tab="unidades">
@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>
const units = {
ids: {
units: '',
loader: '',
progress: '',
load_progress: ''
},
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: () => {
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: progress_bar => {
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 = []
const url = `{{ $urls->api }}/proyectos/broker/{{ $contract->broker->rut }}/contract/{{ $contract->id }}/promotions`
const method = 'post'
chunks.forEach(chunk => {
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 => {
progress_bar.progress('increment', json.input.unidad_ids.length)
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].promotions = unidad.promotions
})
}))
})
return Promise.all(promises)
},
prices: progress_bar => {
/*const unsold = [...units.data.units.filter(unit => !unit.sold), ...units.data.units.filter(unit => unit.sold && unit.proyecto_tipo_unidad.tipo_unidad.descripcion !== 'departamento')]
const current_total = progress_bar.progress('get total')
progress_bar.progress('set total', current_total + unsold.length)*/
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 = []
const url = `{{ $urls->api }}/proyecto/{{ $contract->project->id }}/unidades/precios`
const method = 'post'
chunks.forEach(chunk => {
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 => {
progress_bar.progress('increment', json.input.unidad_ids.length)
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)
},
values: progress_bar => {
const sold = units.data.units.filter(unit => unit.sold && unit.proyecto_tipo_unidad.tipo_unidad.descripcion === 'departamento')
progress_bar.progress('set total', sold.length)
const chunkSize = 10
const chunks = []
for (let i = 0; i < sold.length; i += chunkSize) {
chunks.push(sold.slice(i, i + chunkSize).map(u => u.id))
}
const promises = []
const url = `{{ $urls->api }}/ventas/by/unidades`
const method = 'post'
chunks.forEach(chunk => {
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 => {
progress_bar.progress('increment', json.input.unidad_ids.length)
if (json.ventas.length === 0) {
return
}
json.ventas.forEach(({unidad_id, venta}) => {
const unidades = venta.propiedad.unidades
const otras_unidades = unidades.filter(unit => unit.id !== parseInt(unidad_id) && unit.proyecto_tipo_unidad.tipo_unidad.descripcion !== 'departamento')
const departamentos = unidades.filter(unit => unit.proyecto_tipo_unidad.tipo_unidad.descripcion === 'departamento' && unit.id !== parseInt(unidad_id))
const precios = otras_unidades.map(unit => {
const idx = units.data.units.findIndex(u => u.id === unit.id)
return units.data.units[idx].precio?.valor ?? 0
}).reduce((sum, precio) => sum + precio, 0)
if (departamentos.length === 0) {
const idx = units.data.units.findIndex(unit => unit.id === parseInt(unidad_id))
units.data.units[idx].valor = venta.valor - precios
units.data.units[idx].venta = venta
return
}
const sum_precios = departamentos.map(departamento => {
const idx = units.data.units.findIndex(unit => unit.id === departamento.id)
return units.data.units[idx].precio
}).reduce((sum, precio) => sum + precio, 0)
departamentos.forEach(departamento => {
const idx = units.data.units.findIndex(unit => unit.id === departamento.id)
const saldo = venta.valor - precios
units.data.units[idx].valor = saldo / sum_precios * departamento.precio
units.data.units[idx].venta = venta
})
})
}))
})
return Promise.all(promises)
},
sold: progress_bar => {
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 = []
const url = `{{ $urls->api }}/proyecto/{{ $contract->project->id }}/unidades/estados`
const method = 'post'
chunks.forEach(chunk => {
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 => {
progress_bar.progress('increment', json.input.unidad_ids.length)
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: () => {
units.handlers.units.draw({units: units.data.units, formatters: units.formatters})
},
tipos: () => {
units.handlers.tipo.draw({units: units.data.units, formatters: units.formatters})
},
lineas: () => {
units.handlers.lineas.draw({units: units.data.units, formatters: units.formatters})
}
}
},
setup(ids) {
units.ids = ids
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) {
if (tabPath !== 'unidades') {
return
}
$(this.querySelector('table')).DataTable().columns.adjust().draw()
this.querySelector('table').style.width = ''
}
})
document.getElementById(units.ids.results).style.visibility = 'hidden'
document.getElementById(units.ids.progress).style.visibility = 'hidden'
document.getElementById(units.ids.load_progress).style.visibility = 'hidden'
const loader = $(`#${units.ids.loader}`)
units.get().units().then(() => {
document.getElementById(units.ids.load_progress).style.visibility = 'visible'
const units_length = units.data.units.length
const progress_bar = $(`#${units.ids.load_progress}`)
progress_bar.progress({ total: units_length * 3 })
loader.hide()
units.get().promotions(progress_bar).then(() => {
units.get().sold(progress_bar).then(() => {
units.get().prices(progress_bar).then(() => {
document.getElementById(units.ids.results).style.visibility = 'visible'
loader.parent().remove()
units.draw().units()
units.draw().tipos()
units.draw().lineas()
document.getElementById(units.ids.progress).style.visibility = 'visible'
const progress_bar = $(`#${units.ids.progress}`)
progress_bar.progress()
units.get().values(progress_bar).then(() => {
document.getElementById(units.ids.progress).remove()
units.draw().units()
units.draw().tipos()
units.draw().lineas()
})
})
})
})
})
}
}
$(document).ready(function () {
units.setup({results: 'results', loader: 'loader', progress: 'values_progress', load_progress: 'load_progress'})
})
</script>
@endpush

View File

@ -0,0 +1,91 @@
<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 Base</th>
<th class="right aligned" style="text-decoration: overline">Comisión</th>
<th class="right aligned" style="text-decoration: overline">Precio Operador</th>
<th class="center aligned" style="text-decoration: overline" id="linea_promociones">Promociones</th>
</tr>
</thead>
<tbody></tbody>
</table>
@push('page_scripts')
<script>
class LineasTable extends GroupedTableHandler {
ids = {
lineas: 'lineas',
promotions: 'linea_promociones'
}
constructor(commission) {
super(commission)
}
draw({units, formatters}) {
const table = document.getElementById(this.ids.lineas)
const tbody = table.querySelector('tbody')
tbody.innerHTML = ''
const lineas = Object.groupBy(units, unit => {
return [unit.proyecto_tipo_unidad.tipo_unidad.descripcion, unit.proyecto_tipo_unidad.nombre, unit.orientacion]
})
this.promotions.names = new Set()
this.promotions.values = []
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 commission_tooltip = [
`Min: ${formatters.percent.format(Math.min(...prices.map(p => p.commission)))}`,
`Max: ${formatters.percent.format(Math.max(...prices.map(p => p.commission)))}`,
`Desv: ${formatters.percent.format(Stat.standardDeviation(prices.map(p => p.commission)))}`
].join("\n").replaceAll(' ', '&nbsp;')
const broker_tooltip = [
`Min: ${formatters.ufs.format(Math.min(...prices.map(p => p.broker)))}`,
`Max: ${formatters.ufs.format(Math.max(...prices.map(p => p.broker)))}`,
`Desv: ${formatters.ufs.format(Stat.standardDeviation(prices.map(p => p.broker)))}`
].join("\n").replaceAll(' ', '&nbsp;')
const promotions = this.process().prices(prices)
this.process().promotions().names(promotions)
this.process().promotions().values({promotions, formatters})
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="${commission_tooltip}" data-position="right center" data-variation="wide multiline">${formatters.percent.format(Stat.mean(prices.map(p => p.commission)))}</span></td>`,
`<td class="right aligned"><span data-tooltip="${broker_tooltip}" data-position="right center" data-variation="wide multiline">UF ${formatters.ufs.format(Stat.mean(prices.map(p => p.broker)))}</span></td>`,
`<td class="right aligned promotions"></td>`,
`</tr>`
].join("\n")
})
this.build().promotions(table, tbody)
}
}
</script>
@endpush

View File

@ -0,0 +1,71 @@
<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">Comisión</th>
<th class="right aligned" style="text-decoration: overline">Precio Operador</th>
<th class="center aligned" style="text-decoration: overline" id="tipo_promociones">Promociones</th>
</tr>
</thead>
<tbody></tbody>
</table>
@push('page_scripts')
<script>
class TipoTable extends GroupedTableHandler {
ids = {
tipos: 'tipos',
promotions: 'tipo_promociones'
}
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
})
this.promotions.names = new Set()
this.promotions.values = []
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 commission_tooltip = [
`Min: ${formatters.percent.format(Math.min(...prices.map(p => p.commission)))}`,
`Max: ${formatters.percent.format(Math.max(...prices.map(p => p.commission)))}`,
`Desv: ${formatters.percent.format(Stat.standardDeviation(prices.map(p => p.commission)))}`
].join("\n").replaceAll(' ', '&nbsp;')
const broker_tooltip = [
`Min: ${formatters.ufs.format(Math.min(...prices.map(p => p.broker)))}`,
`Max: ${formatters.ufs.format(Math.max(...prices.map(p => p.broker)))}`,
`Desv: ${formatters.ufs.format(Stat.standardDeviation(prices.map(p => p.broker)))}`
].join("\n").replaceAll(' ', '&nbsp;')
const promotions = this.process().prices(prices)
this.process().promotions().names(promotions)
this.process().promotions().values({promotions, formatters})
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="${commission_tooltip}" data-position="right center" data-variation="wide multiline">${formatters.percent.format(Stat.mean(prices.map(p => p.commission)))}</span></td>`,
`<td class="right aligned"><span data-tooltip="${broker_tooltip}" data-position="right center" data-variation="wide multiline">UF ${formatters.ufs.format(Stat.mean(prices.map(p => p.broker)))}</span></td>`,
`<td class="right aligned promotions"></td>`,
`</tr>`
].join("\n")
})
this.build().promotions(table, tbody)
}
}
</script>
@endpush

View File

@ -0,0 +1,254 @@
<table class="ui table" id="unidades">
<thead>
<tr>
<th>Estado</th>
<th>Tipo</th>
<th>Tipo Order</th>
<th class="right aligned">Unidad</th>
<th>Unidad Orden</th>
<th>Tipología</th>
<th>Piso</th>
<th>Orientación</th>
<th>m&#0178; Interior</th>
<th>m&#0178; Terraza</th>
<th>m&#0178; Vendibles</th>
<th>m&#0178; Total</th>
<th class="right aligned">Precio Base</th>
<th class="right aligned">Comisión</th>
<th class="right aligned">Precio Operador</th>
<th class="right aligned">UF/</th>
<th class="center aligned" id="unit_promotions">Promociones</th>
</tr>
</thead>
<tbody></tbody>
</table>
@push('page_scripts')
<script>
class UnitsTable extends TableHandler {
ids = {
units: 'unidades',
}
columns = [
'estado',
'tipo',
'tipo_order',
'unidad',
'unidad_order',
'tipologia',
'piso',
'orientacion',
'metros_interior',
'metros_terraza',
'metros',
'metros_total',
'precio_base',
'commission',
'precio_operador',
'UF/m²',
'promociones',
]
set = {
table: false,
titles: false
}
table
constructor(commission) {
super(commission)
}
setup() {
return {
titles: promotions_names => {
if (this.set.titles || promotions_names.size === 0) {
return
}
const nameArray = Array.from(promotions_names)
this.columns.pop()
this.columns.push(`${nameArray[0].toLowerCase().replaceAll(' ', '_')}.amount`)
this.columns.push(`${nameArray[0].toLowerCase().replaceAll(' ', '_')}.final`)
const table = document.getElementById(this.ids.units)
const thead = table.querySelector('thead')
const tr = thead.querySelector('tr')
const th = tr.querySelector('th#unit_promotions')
th.innerHTML = `${nameArray[0]}<br />Porcentaje`
tr.insertAdjacentHTML('beforeend', `<th class="right aligned">${nameArray[0]}<br />Precio Final</th>`)
if (promotions_names.size > 1) {
nameArray.slice(1).forEach(name => {
this.columns.push(`${name.toLowerCase().replaceAll(' ', '_')}.amount`)
this.columns.push(`${name.toLowerCase().replaceAll(' ', '_')}.final`)
tr.insertAdjacentHTML('beforeend', `<th class="right aligned">${name}<br />Porcentaje</th>`)
tr.insertAdjacentHTML('beforeend', `<th class="right aligned">${name}<br />Precio Final</th>`)
})
}
this.set.titles = true
},
table: () => {
if (typeof this.table !== 'undefined' || this.set.table) {
return
}
const dto = structuredClone(datatables_defaults)
dto.pageLength = 100
dto.columnDefs = [
{
target: ['tipo_order', 'unidad_order', 'tipologia', 'piso', 'orientacion', 'metros'].map(column => this.columns.indexOf(column)),
visible: false
},
{
target: ['tipo'].map(column => this.columns.indexOf(column)),
orderData: ['tipo_order'].map(column => this.columns.indexOf(column)),
},
{
target: ['unidad'].map(column => this.columns.indexOf(column)),
orderData: ['unidad_order'].map(column => this.columns.indexOf(column)),
},
{
target: ['unidad', 'precio_base', 'commission', 'precio_operador', 'UF/m²', 'porcentaje', 'precio_final']
.map(column => this.columns.indexOf(column)),
className: 'dt-right right aligned'
}
]
dto.order = ['tipo_order', 'unidad_order'].map(column => [this.columns.indexOf(column), 'asc'])
dto.language.searchBuilder = searchBuilder
const exportColumns = ['tipo', 'unidad', 'tipologia', 'piso', 'orientacion', 'metros_interior', 'metros_terraza', 'metros', 'metros_total', 'precio_operador', 'promociones']
if (typeof this.columns['promotions'] === 'undefined') {
exportColumns.pop()
this.columns.slice(this.columns.indexOf('UF/m²')+1).forEach(name => {
exportColumns.push(name)
})
}
dto.layout = {
top1Start: {
searchBuilder: {
columns: this.columns.filter(column => !['tipo_order', 'unidad_order'].includes(column))
.map(column => this.columns.indexOf(column)),
}
},
top1End: {
buttons: [
{
extend: 'excelHtml5',
className: 'green',
text: 'Exportar a Excel <i class="file excel icon"></i>',
title: 'Lista de Precios - {{ $contract->broker->name }} - {{ $contract->project->descripcion }} - {{ (new DateTime())->format('Y-m-d') }}',
download: 'open',
exportOptions: {
columns: exportColumns
.map(column => this.columns.indexOf(column)),
rows: (idx, data, node) => {
return data[this.columns.indexOf('estado')] === 'Libre'
},
format: {
body: (data, row, columnIdx, node) => {
if (typeof data === 'string' && data.includes('<span')) {
return data.replace(/<span.*>(.*)<\/span>/, '$1')
}
if (typeof data === 'string' && data.includes('UF ')) {
return data.replace('UF ', '').replaceAll('.', '').replaceAll(',', '.')
}
const formatColumns = ['metros', 'metros_interior', 'metros_terraza', 'metros_total']
if (this.set.titles) {
this.columns.filter(column => column.includes('.amount') || column.includes('.final')).forEach(name => {
formatColumns.push(name)
})
}
if (formatColumns.map(column => this.columns.indexOf(column)).includes(columnIdx)) {
return data.replaceAll('.', '').replaceAll(',', '.')
}
return data
}
}
},
}
]
}
}
this.table = $(`#${this.ids.units}`).DataTable(dto)
this.set.table = true
}
}
}
draw({units, formatters}) {
const prices = this.prices(units)
const promotions_names = new Set()
const tableData = []
units.forEach(unidad => {
const tipo = unidad.proyecto_tipo_unidad.tipo_unidad.descripcion
const price = prices.find(p => p.id === unidad.id)
let promotions = []
price.promotions.forEach(p => {
if (Object.hasOwn(promotions, p.name)) {
return
}
promotions[p.name] = {
name: p.name,
type: p.type,
amount: p.type === 1 ? 'UF ' + formatters.ufs.format(p.amount) : formatters.percent.format(p.amount),
final: `UF ${formatters.ufs.format(p.final)}`
}
})
Object.keys(promotions).forEach(name => {
promotions_names.add(name)
})
const temp = Object.values(promotions)
const data = [
unidad.sold ? `<span class="ui yellow text">Vendida</span>` : 'Libre',
tipo.charAt(0).toUpperCase() + tipo.slice(1),
unidad.proyecto_tipo_unidad.tipo_unidad.orden,
unidad.sold && unidad.venta ? `<a href="{{ $urls->base }}/venta/${unidad.venta?.id }" data-tooltip="Valor Promesa: UF ${formatters.ufs.format(unidad.venta?.valor ?? 0)}" data-position="left center">${unidad.descripcion}</a>` : unidad.descripcion,
unidad.descripcion.padStart(4, '0'),
unidad.proyecto_tipo_unidad.tipologia,
unidad.piso,
unidad.orientacion,
formatters.ufs.format(unidad.proyecto_tipo_unidad.util) ?? 0,
formatters.ufs.format(unidad.proyecto_tipo_unidad.terraza) ?? 0,
formatters.ufs.format(unidad.proyecto_tipo_unidad.vendible) ?? 0,
formatters.ufs.format(unidad.proyecto_tipo_unidad.superficie) ?? 0,
'UF ' + formatters.ufs.format(price.base ?? 0),
formatters.percent.format(price.commission ?? 0),
'UF ' + formatters.ufs.format(price.broker ?? 0),
formatters.ufs.format(price.broker / unidad.proyecto_tipo_unidad.vendible),
''
]
if (temp.length > 0) {
data.pop()
temp.forEach((p, i) => {
data.push(p.amount)
data.push(p.final)
})
} else {
if (promotions_names.size > 0) {
Array.from(promotions_names).forEach(name => {
data.push('')
data.push('')
})
}
}
tableData.push(data)
})
this.setup().titles(promotions_names)
this.setup().table()
const table = this.table
table.clear()
table.rows.add(tableData)
table.draw()
}
}
</script>
@endpush

View File

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

View File

@ -0,0 +1,52 @@
<div class="ui top attached right aligned basic segment">
<button type="button" class="ui mini tertiary icon button" id="refresh_button">
<i class="sync alternate icon"></i>
</button>
<button type="button" class="ui mini tertiary icon button" id="up_button">
<i class="arrow up icon"></i>
</button>
</div>
<table class="ui table" id="projects">
<thead>
<tr>
<th>Proyecto</th>
</tr>
</thead>
<tbody>
@foreach($projects as $project)
<tr data-index="{{$project->id}}">
<td class="link" colspan="2">{{$project->descripcion}}</td>
</tr>
@endforeach
</tbody>
</table>
@push('page_scripts')
<script>
$(document).ready(function () {
document.querySelectorAll('#projects td.link').forEach(column => {
column.style.cursor = 'pointer'
column.addEventListener('click', () => {
const index = column.parentNode.dataset.index
if (typeof brokers.data.contracts[index] !== 'undefined') {
brokers.data.project_id = index
brokers.draw().brokers(index)
return
}
brokers.get().contracts(index)
})
})
document.getElementById('refresh_button').addEventListener('click', () => {
if (brokers.data.project_id === null) {
return
}
brokers.actions().refresh()
})
document.getElementById('up_button').addEventListener('click', () => {
brokers.actions().up()
})
})
</script>
@endpush

View File

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

View File

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

View File

@ -35,7 +35,7 @@
@endsection
@push('page_scripts')
<script type="text/javascript">
<script>
class Proyecto {
id
estados

View File

@ -141,7 +141,7 @@
@include('layout.body.scripts.chartjs')
@push('page_scripts')
<script type="text/javascript">
<script>
const superficies = {
ids: {
vendible: '',

View File

@ -39,7 +39,7 @@
@endpush
@push('page_scripts')
<script type="text/javascript">
<script>
class Unidad
{
id