Listado de Precios para Contrato Broker

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -187,4 +187,5 @@ class Proyectos
}
return $this->withJson($response, $output);
}
}

View File

@ -5,9 +5,11 @@ use DateTimeImmutable;
use DateMalformedStringException;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Incoviba\Common\Implement;
use Incoviba\Controller\API\withJson;
use Incoviba\Service;
use Incoviba\Exception\ServiceAction;
use Incoviba\Repository;
use Incoviba\Service;
class Contracts
{
@ -140,4 +142,34 @@ class Contracts
return $this->withJson($response, $output);
}
public function promotions(ServerRequestInterface $request, ResponseInterface $response,
Service\Proyecto\Broker\Contract $contractService,
Repository\Venta\Unidad $unitRepository,
Repository\Venta\Promotion $promotionRepository,
int $contract_id): ResponseInterface
{
$input = $request->getParsedBody();
$output = [
'contract_id' => $contract_id,
'input' => $input,
'unidades' => [],
];
$unit_ids = $input['unidad_ids'];
if (is_string($unit_ids)) {
$unit_ids = json_decode($input['unidad_ids'], true);
}
foreach ($unit_ids as $unit_id) {
try {
$unit = $unitRepository->fetchById($unit_id);
$contractService->getById($contract_id);
$promotion = $promotionRepository->fetchByContractAndUnit($contract_id, $unit->id);
$output['unidades'] []= [
'id' => $unit->id,
'promotion' => $promotion
];
} catch (ServiceAction\Read | Implement\Exception\EmptyResult) {}
}
return $this->withJson($response, $output);
}
}

View File

@ -0,0 +1,85 @@
<?php
namespace Incoviba\Controller\API\Proyectos;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Incoviba\Common\Ideal;
use Incoviba\Common\Implement;
use Incoviba\Controller\API\withJson;
use Incoviba\Controller\withRedis;
use Incoviba\Exception;
use Incoviba\Model;
use Incoviba\Repository;
use Incoviba\Service;
class Unidades extends Ideal\Controller
{
use withJson;
use withRedis;
public function precios(ServerRequestInterface $request, ResponseInterface $response,
Service\Proyecto $proyectoService,
Repository\Venta\Precio $precioRepository,
int $proyecto_id): ResponseInterface
{
$input = $request->getParsedBody();
$output = [
'proyecto_id' => $proyecto_id,
'input' => $input,
'precios' => []
];
$unidad_ids = $input['unidad_ids'];
if (is_string($unidad_ids)) {
$unidad_ids = json_decode($input['unidad_ids'], true);
}
try {
$proyecto = $proyectoService->getById($proyecto_id);
foreach ($unidad_ids as $unidad_id) {
try {
$output['precios'][] = [
'id' => $unidad_id,
'precio' => $precioRepository->fetchVigenteByUnidad((int) $unidad_id)
];
} catch (Implement\Exception\EmptyResult) {}
}
} catch (Implement\Exception\EmptyResult) {}
return $this->withJson($response, $output);
}
public function estados(ServerRequestInterface $request, ResponseInterface $response,
Service\Proyecto $proyectoService,
Repository\Venta\Unidad $unidadRepository,
int $proyecto_id): ResponseInterface
{
$input = $request->getParsedBody();
$output = [
'proyecto_id' => $proyecto_id,
'input' => $input,
'estados' => []
];
$unidad_ids = $input['unidad_ids'];
if (is_string($unidad_ids)) {
$unidad_ids = json_decode($input['unidad_ids'], true);
}
try {
$proyecto = $proyectoService->getById($proyecto_id);
foreach ($unidad_ids as $unidad_id) {
try {
$unidad = $unidadRepository->fetchById($unidad_id);
} catch (Implement\Exception\EmptyResult) {
try {
$output['estados'][] = [
'id' => $unidad_id,
'sold' => $unidadRepository->fetchSoldByUnidad((int) $unidad_id)
];
} catch (Implement\Exception\EmptyResult) {
$output['estados'][] = [
'id' => $unidad_id,
'sold' => false
];
}
}
}
} catch (Implement\Exception\EmptyResult) {}
return $this->withJson($response, $output);
}
}

View File

@ -0,0 +1,24 @@
<?php
namespace Incoviba\Controller\Proyectos\Brokers;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Incoviba\Common\Alias\View;
use Incoviba\Common\Ideal\Controller;
use Incoviba\Exception;
use Incoviba\Service;
class Contracts extends Controller
{
public function show(ServerRequestInterface $request, ResponseInterface $response, View $view,
Service\Proyecto\Broker\Contract $contractService,
int $broker_rut, int $contract_id): ResponseInterface
{
$contract = null;
try {
$contract = $contractService->getById($contract_id);
} catch (Exception\ServiceAction\Read) {}
return $view->render($response, 'proyectos.brokers.contracts.show', compact('contract'));
}
}

View File

@ -32,6 +32,15 @@ class Contract extends Common\Ideal\Model
return $this->current;
}
protected array $promotions = [];
public function promotions(): array
{
if (count($this->promotions) === 0) {
$this->promotions = $this->runFactory('promotions');
}
return $this->promotions;
}
protected function jsonComplement(): array
{
return [

View File

@ -3,9 +3,11 @@ namespace Incoviba\Model\Venta;
use DateTimeInterface;
use Incoviba\Common;
use Incoviba\Model\Proyecto\Broker;
class Promotion extends Common\Ideal\Model
{
public Broker\Contract $contract;
public Precio $price;
public float $amount;
public DateTimeInterface $startDate;
@ -13,11 +15,18 @@ class Promotion extends Common\Ideal\Model
public DateTimeInterface $validUntil;
public int $state;
public function price(): float
{
return $this->price->valor * $this->amount;
}
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'),
@ -27,4 +36,4 @@ class Promotion extends Common\Ideal\Model
]
];
}
}
}

View File

@ -45,6 +45,18 @@ class Unidad extends Ideal\Model
return $precio;
}
protected bool $sold;
public function sold(): bool
{
if (!isset($this->sold)) {
$this->sold = false;
try {
$this->sold = $this->runFactory('sold') ?? false;
} catch (EmptyResult) {}
}
return $this->sold;
}
public function jsonSerialize(): mixed
{
$output = array_merge(parent::jsonSerialize(), [
@ -59,6 +71,7 @@ class Unidad extends Ideal\Model
$output['precios'] = $this->precios;
$output['current_precio'] = $this->currentPrecio;
}
$output['sold'] = $this->sold() ?? false;
return $output;
}
}

View File

@ -3,10 +3,11 @@ namespace Incoviba\Repository\Venta;
use Incoviba\Common;
use Incoviba\Model;
use Incoviba\Repository\Proyecto\Broker;
class Promotion extends Common\Ideal\Repository
{
public function __construct(Common\Define\Connection $connection, protected Precio $precioRepository)
public function __construct(Common\Define\Connection $connection, protected Broker\Contract $contractRepository, protected Precio $precioRepository)
{
parent::__construct($connection);
}
@ -18,31 +19,70 @@ class Promotion extends Common\Ideal\Repository
public function create(?array $data = null): Model\Venta\Promotion
{
$map = (new Implement\Repository\MapperParser(['amount', 'type']))
->register('price_id', (new Implement\Repository\Mapper())
$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 Implement\Repository\Mapper\DateTime('start_date', 'startDate'))
->register('end_date', new Implement\Repository\Mapper\DateTime('end_date', 'endDate'))
->register('valid_until', new Implement\Repository\Mapper\DateTime('valid_until', 'validUntil'));
->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'));
return $this->parseData(new Model\Venta\Promotion(), $data, $map);
}
public function save(Common\Define\Model $model): Model\Venta\Promotion
{
$model->id = $this->saveNew(
['amount', 'type', 'start_date', 'end_date', 'valid_until', 'price_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]
['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]
);
return $model;
}
public function edit(Common\Define\Model $model, array $new_data): Model\Venta\Promotion
{
return $this->update($model, ['amount', 'type', 'start_date', 'end_date', 'valid_until', 'price_id'], $new_data);
return $this->update($model, ['contract_id', 'amount', 'type', 'start_date', 'end_date', 'valid_until', 'price_id'], $new_data);
}
/**
* @param int $contract_id
* @return array
* @throws Common\Implement\Exception\EmptyResult
*/
public function fetchByContract(int $contract_id): array
{
$query = $this->connection->getQueryBuilder()
->select()
->from($this->getTable())
->where('contract_id = :contract_id');
return $this->fetchMany($query, ['contract_id' => $contract_id]);
}
/**
* @param int $contract_id
* @return array
* @throws Common\Implement\Exception\EmptyResult
*/
public function fetchActiveByContract(int $contract_id): array
{
$query = $this->connection->getQueryBuilder()
->select()
->from($this->getTable())
->where('contract_id = :contract_id AND state = :state');
return $this->fetchMany($query, ['contract_id' => $contract_id, 'state' => Model\Venta\Promotion\State::ACTIVE]);
}
/**
* @param int $price_id
* @return array
* @throws Common\Implement\Exception\EmptyResult
*/
public function fetchByPrice(int $price_id): array
{
$query = $this->connection->getQueryBuilder()
@ -51,6 +91,12 @@ class Promotion extends Common\Ideal\Repository
->where('price_id = :price_id');
return $this->fetchMany($query, ['price_id' => $price_id]);
}
/**
* @param int $price_id
* @return array
* @throws Common\Implement\Exception\EmptyResult
*/
public function fetchActiveByPrice(int $price_id): array
{
$query = $this->connection->getQueryBuilder()
@ -59,4 +105,57 @@ class Promotion extends Common\Ideal\Repository
->where('price_id = :price_id AND state = :state');
return $this->fetchMany($query, ['price_id' => $price_id, 'state' => Model\Venta\Promotion\State::ACTIVE]);
}
/**
* @param int $project_id
* @return array
* @throws Common\Implement\Exception\EmptyResult
*/
public function fetchByProject(int $project_id): array
{
$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 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');
return $this->fetchMany($query, ['project_id' => $project_id]);
}
/**
* @param int $project_id
* @return array
* @throws Common\Implement\Exception\EmptyResult
*/
public function fetchActiveByProject(int $project_id): array
{
$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 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');
return $this->fetchMany($query, ['project_id' => $project_id, 'state' => Model\Venta\Promotion\State::ACTIVE]);
}
/**
* @param int $contract_id
* @param int $unit_id
* @return Model\Venta\Promotion
* @throws Common\Implement\Exception\EmptyResult
*/
public function fetchByContractAndUnit(int $contract_id, int $unit_id): Model\Venta\Promotion
{
$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');
return $this->fetchOne($query, ['contract_id' => $contract_id, 'unit_id' => $unit_id]);
}
}

View File

@ -172,6 +172,18 @@ class Unidad extends Ideal\Repository
->group('unidad.id');
return $this->connection->execute($query, [$unidad_id])->fetch(PDO::FETCH_ASSOC);
}
public function fetchSoldByUnidad(int $unidad_id): Model\Venta\Unidad
{
$query = $this->connection->getQueryBuilder()
->select('a.*')
->from("{$this->getTable()} a")
->joined('INNER JOIN `propiedad_unidad` pu ON pu.`unidad` = a.`id`')
->joined('INNER JOIN `venta` ON `venta`.`propiedad` = `pu`.`propiedad`')
->joined('LEFT OUTER JOIN (SELECT ev1.* FROM `estado_venta` ev1 JOIN (SELECT MAX(`id`) as `id`, `venta` FROM `estado_venta`) ev0 ON ev0.`id` = ev1.`id`) ev ON ev.`venta` = `venta`.`id`')
->joined('LEFT OUTER JOIN `tipo_estado_venta` tev ON tev.`id` = ev.`estado`')
->where('a.id = :unidad_id AND tev.activa = 1');
return $this->fetchOne($query, ['unidad_id' => $unidad_id]);
}
protected function joinProrrateo(): string
{

View File

@ -16,7 +16,8 @@ class Contract extends Ideal\Service
{
public function __construct(LoggerInterface $logger,
protected Repository\Proyecto\Broker\Contract $contractRepository,
protected Repository\Proyecto\Broker\Contract\State $stateRepository)
protected Repository\Proyecto\Broker\Contract\State $stateRepository,
protected Repository\Venta\Promotion $promotionRepository)
{
parent::__construct($logger);
}
@ -145,6 +146,9 @@ class Contract extends Ideal\Service
$contract->addFactory('states', (new Implement\Repository\Factory())
->setCallable([$this->stateRepository, 'fetchByContract'])
->setArgs(['contract_id' => $contract->id]));
$contract->addFactory('promotions', (new Implement\Repository\Factory())
->setCallable([$this->promotionRepository, 'fetchByContract'])
->setArgs(['contract_id' => $contract->id]));
return $contract;
}
}

View File

@ -0,0 +1,85 @@
<?php
namespace Incoviba\Service\Venta;
use Psr\Log\LoggerInterface;
use Incoviba\Common\Ideal;
use Incoviba\Common\Implement;
use Incoviba\Exception;
use Incoviba\Model;
use Incoviba\Repository;
use Incoviba\Service;
class Promotion extends Ideal\Service
{
public function __construct(LoggerInterface $logger,
protected Repository\Venta\Promotion $promotionRepository,
protected Repository\Proyecto\Broker\Contract $contractRepository)
{
parent::__construct($logger);
}
public function getAll(null|string|array $order = null): array
{
try {
return array_map([$this, 'process'], $this->promotionRepository->fetchAll($order));
} catch (Implement\Exception\EmptyResult) {
return [];
}
}
/**
* @param int $promotion_id
* @return Model\Venta\Promotion
* @throws Exception\ServiceAction\Read
*/
public function getById(int $promotion_id): Model\Venta\Promotion
{
try {
return $this->process($this->promotionRepository->fetchById($promotion_id));
} catch (Implement\Exception\EmptyResult $exception) {
throw new Exception\ServiceAction\Read(__CLASS__, $exception);
}
}
/**
* @param int $contract_id
* @return array
*/
public function getByContract(int $contract_id): array
{
try {
return array_map([$this, 'process'], $this->promotionRepository->fetchByContract($contract_id));
} catch (Implement\Exception\EmptyResult) {
try {
$contract = $this->contractRepository->fetchById($contract_id);
return array_map([$this, 'process'], $this->promotionRepository->fetchByProject($contract->project->id));
} catch (Implement\Exception\EmptyResult) {
return [];
}
}
}
/**
* @param int $contract_id
* @return array
*/
public function getActiveByContract(int $contract_id): array
{
try {
return array_map([$this, 'process'], $this->promotionRepository->fetchActiveByContract($contract_id));
} catch (Implement\Exception\EmptyResult) {
try {
$contract = $this->contractRepository->fetchById($contract_id);
return array_map([$this, 'process'], $this->promotionRepository->fetchActiveByProject($contract->project->id));
} catch (Implement\Exception\EmptyResult) {
return [];
}
}
}
protected function process(Model\Venta\Promotion $model): Model\Venta\Promotion
{
return $model;
}
}

View File

@ -1,9 +1,10 @@
<?php
namespace Incoviba\Service\Venta;
use Incoviba\Exception\ServiceAction\Read;
use PDOException;
use Incoviba\Common\Implement\Repository\Factory;
use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Exception\ServiceAction\Read;
use Incoviba\Repository;
use Incoviba\Model;
@ -31,6 +32,10 @@ class Unidad
{
return array_map([$this, 'process'], $this->unidadRepository->fetchByCierre($cierre_id));
}
public function getByProyecto(int $proyecto_id): array
{
return array_map([$this, 'process'], $this->unidadRepository->fetchByProyecto($proyecto_id));
}
public function getDisponiblesByProyecto(int $proyecto_id): array
{
return $this->unidadRepository->fetchDisponiblesByProyecto($proyecto_id);
@ -62,6 +67,10 @@ class Unidad
$unidad->precios = $this->precioService->getByUnidad($unidad->id);
$unidad->currentPrecio = $this->precioService->getVigenteByUnidad($unidad->id);
} catch (Read) {}
$unidad->addFactory('sold', (new Factory())
->setCallable([$this->unidadRepository, 'fetchSoldByUnidad'])
->setArgs(['unidad_id' => $unidad->id])
);
return $unidad;
}
}