Import Precios

This commit is contained in:
Juan Pablo Vial
2025-08-27 19:27:18 -04:00
parent 4e4c0b7648
commit ad64ffa436
19 changed files with 1049 additions and 21 deletions

View File

@ -1,13 +1,16 @@
<?php
namespace Incoviba\Controller\API\Ventas;
use DateTime;
use Exception;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Incoviba\Common\Implement\Exception\EmptyRedis;
use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Common\Implement\Exception\{EmptyRedis,EmptyResult};
use Psr\Log\LoggerInterface;
use Incoviba\Controller\API\{withJson,emptyBody};
use Incoviba\Service;
use Incoviba\Controller\withRedis;
use Incoviba\Exception\ServiceAction\Create;
use Incoviba\Service;
class Precios
{
@ -51,4 +54,29 @@ class Precios
}
}
}
public function import(ServerRequestInterface $request, ResponseInterface $response,
LoggerInterface $logger,
Service\Venta\Precio $precioService): ResponseInterface
{
$body = $request->getParsedBody();
$projectId = $body['project_id'];
$date = $body['date'];
$file = $request->getUploadedFiles()['file'];
$output = [
'input' => $body,
'total' => 0,
'precios' => [],
'status' => false
];
$date = DateTime::createFromFormat('Y-m-d', $date);
try {
$output['precios'] = $precioService->import($projectId, $date, $file);
$output['total'] = count($output['precios']);
$output['status'] = true;
} catch (Create | Exception $exception) {
$logger->warning($exception);
}
return $this->withJson($response, $output);
}
}

View File

@ -9,9 +9,9 @@ use Incoviba\Model;
class Precios
{
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, View $view, Service\Proyecto $proyectoService): ResponseInterface
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, View $view, Service\Proyecto $proyectoService, ?int $project_id = null): ResponseInterface
{
$proyectos = array_map(function(Model\Proyecto $proyecto) {return ['id' => $proyecto->id, 'descripcion' => $proyecto->descripcion];}, $proyectoService->getVendibles());
return $view->render($response, 'ventas.precios.list', compact('proyectos'));
return $view->render($response, 'ventas.precios.list', compact('proyectos', 'project_id'));
}
}

View File

@ -43,6 +43,11 @@ class Inmobiliaria extends Ideal\Repository
return $this->update($model, ['dv', 'razon', 'abreviacion', 'cuenta', 'banco', 'sociedad'], $new_data);
}
/**
* @param string|array|null $sorting
* @return array
* @throws Implement\Exception\EmptyResult
*/
public function fetchAllActive(null|string|array $sorting = null): array
{
$query = $this->connection->getQueryBuilder()
@ -58,4 +63,18 @@ class Inmobiliaria extends Ideal\Repository
}
return $this->fetchMany($query, [1, 8]);
}
/**
* @param string $name
* @return Model\Inmobiliaria
* @throws Implement\Exception\EmptyResult
*/
public function fetchByName(string $name): Model\Inmobiliaria
{
$query = $this->connection->getQueryBuilder()
->select()
->from($this->getTable())
->where('razon LIKE :name OR abreviacion LIKE :name');
return $this->fetchOne($query, ['name' => "%{$name}%"]);
}
}

View File

@ -85,6 +85,11 @@ class Proyecto extends Ideal\Repository
return $this->fetchOne($query, [$id]);
}
/**
* @param string $name
* @return Model\Proyecto
* @throws Implement\Exception\EmptyResult
*/
public function fetchByName(string $name): Model\Proyecto
{
$query = $this->connection->getQueryBuilder()

View File

@ -7,6 +7,8 @@ use Incoviba\Common\Define;
use Incoviba\Common\Implement;
use Incoviba\Model;
use Incoviba\Repository;
use PDO;
use PDOException;
class EstadoPrecio extends Ideal\Repository
{
@ -44,11 +46,24 @@ class EstadoPrecio extends Ideal\Repository
return $this->update($model, ['precio', 'estado', 'fecha'], $new_data);
}
/**
* @param int $precio_id
* @return array
* @throws Implement\Exception\EmptyResult
*/
public function fetchByPrecio(int $precio_id): array
{
$query = "SELECT * FROM `{$this->getTable()}` WHERE `precio` = ?";
error_log($query.PHP_EOL,3,'/logs/query.log');
error_log($precio_id.PHP_EOL,3,'/logs/query.log');
return $this->fetchMany($query, [$precio_id]);
}
/**
* @param int $precio_id
* @return Define\Model
* @throws Implement\Exception\EmptyResult
*/
public function fetchCurrentByPrecio(int $precio_id): Define\Model
{
$query = "SELECT e1.*

View File

@ -1,6 +1,7 @@
<?php
namespace Incoviba\Repository\Venta;
use Incoviba\Common\Implement\Exception\EmptyResult;
use PDO;
use PDOException;
use Incoviba\Common\Ideal;

View File

@ -4,6 +4,7 @@ namespace Incoviba\Repository\Venta;
use Incoviba\Common\Ideal;
use Incoviba\Common\Define;
use Incoviba\Common\Implement;
use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Model;
class TipoEstadoPrecio extends Ideal\Repository
@ -31,4 +32,18 @@ class TipoEstadoPrecio extends Ideal\Repository
{
return $this->update($model, ['descripcion'], $new_data);
}
/**
* @param string $descripcion
* @return Model\Venta\TipoEstadoPrecio
* @throws EmptyResult
*/
public function fetchByDescripcion(string $descripcion): Model\Venta\TipoEstadoPrecio
{
$query = $this->connection->getQueryBuilder()
->select()
->from($this->getTable())
->where('descripcion = ?');
return $this->fetchOne($query, [$descripcion]);
}
}

View File

@ -0,0 +1,59 @@
<?php
namespace Incoviba\Service;
use InvalidArgumentException;
use Psr\Http\Message\UploadedFileInterface;
use Incoviba\Common\Ideal;
use Incoviba\Exception\ServiceAction;
use Incoviba\Service\FileUpload\FileUploadInterface;
class FileUpload extends Ideal\Service implements FileUploadInterface
{
protected array $uploads = [];
public function register(FileUploadInterface $fileUpload, string $filetype = 'default'): self
{
$this->uploads [$filetype]= $fileUpload;
return $this;
}
/**
* @param UploadedFileInterface $uploadedFile
* @return array
* @throws ServiceAction\Read
*/
public function getData(UploadedFileInterface $uploadedFile): array
{
try {
$type = $this->getFileType($uploadedFile);
} catch (InvalidArgumentException $exception) {
throw new ServiceAction\Read(__CLASS__, $exception);
}
$uploader = $this->getUploader($type);
return $uploader->getData($uploadedFile);
}
/**
* @param UploadedFileInterface $uploadedFile
* @return string|null
*/
protected function getFileType(UploadedFileInterface $uploadedFile): ?string
{
$fileType = $uploadedFile->getClientMediaType();
$typesMap = [
'text/csv' => 'csv',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' => 'xlsx',
'application/vnd.ms-excel' => 'xls',
];
if (!array_key_exists($fileType, $typesMap)) {
throw new InvalidArgumentException("File type {$fileType} not supported.");
}
return $typesMap[$fileType];
}
protected function getUploader(string $type): FileUploadInterface
{
if (!array_key_exists($type, $this->uploads)) {
return $this->uploads['default'];
}
return $this->uploads[$type];
}
}

View File

@ -0,0 +1,147 @@
<?php
namespace Incoviba\Service\FileUpload;
use InvalidArgumentException;
use OutOfBoundsException;
use Psr\Http\Message\UploadedFileInterface;
use PhpOffice\PhpSpreadsheet;
use Incoviba\Common\Ideal;
use Incoviba\Exception\ServiceAction\Read;
class ExcelBase extends Ideal\Service implements FileUploadInterface
{
/**
* @param UploadedFileInterface $uploadedFile
* @return array
* @throws Read
*/
public function getData(UploadedFileInterface $uploadedFile): array
{
$tempFilename = $this->createTempFile($uploadedFile);
$reader = PhpSpreadsheet\IOFactory::createReaderForFile($tempFilename);
$reader->setReadDataOnly(true);
$workbook = $reader->load($tempFilename);
try {
$sheet = $this->findSheet($workbook);
} catch (OutOfBoundsException $exception) {
throw new Read(__CLASS__, $exception);
}
$titles = $this->extractTitles($sheet);
$data = $this->extractData($sheet, $titles);
unlink($tempFilename);
return $data;
}
/**
* @param PhpSpreadsheet\Spreadsheet $workbook
* @return PhpSpreadsheet\Worksheet\Worksheet
* @throws OutOfBoundsException
*/
protected function findSheet(PhpSpreadsheet\Spreadsheet $workbook): PhpSpreadsheet\Worksheet\Worksheet
{
$sheet = $workbook->getActiveSheet();
if ($this->findTable($sheet)) {
return $sheet;
}
$sheets = $workbook->getAllSheets();
foreach ($sheets as $sheet) {
if ($this->findTable($sheet)) {
return $sheet;
}
}
throw new OutOfBoundsException('No table found in the workbook.');
}
protected function findTable(PhpSpreadsheet\Worksheet\Worksheet $sheet): bool
{
$rowIterator = $sheet->getRowIterator();
foreach ($rowIterator as $row) {
if ($row->isEmpty()) {
continue;
}
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(true);
if ($cellIterator->valid()) {
return true;
}
foreach ($cellIterator as $cell) {
if ($cell->getCalculatedValue() !== '') {
return true;
}
}
}
return false;
}
protected function createTempFile(UploadedFileInterface $uploadedFile): string
{
$filename = $uploadedFile->getClientFilename();
$extension = pathinfo($filename, PATHINFO_EXTENSION);
$tempFilename = tempnam(sys_get_temp_dir(), $extension);
$uploadedFile->moveTo($tempFilename);
return $tempFilename;
}
protected function extractTitles(PhpSpreadsheet\Worksheet\Worksheet $sheet): array
{
$titles = [];
$iterator = $sheet->getRowIterator();
foreach ($iterator as $row) {
if ($row->isEmpty()) {
continue;
}
$titles = $this->getRowData($row);
break;
}
return $titles;
}
protected function extractData(PhpSpreadsheet\Worksheet\Worksheet $sheet, array $titles): array
{
$data = [];
$rowIterator = $sheet->getRowIterator();
foreach ($rowIterator as $row) {
if ($row->isEmpty()) {
continue;
}
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(true);
if ($cellIterator->current() === $titles[0]) {
continue;
}
try {
$rowData = $this->getRowData($row, $titles);
} catch (InvalidArgumentException $exception) {
if ($exception->getCode() === 1000) {
continue;
}
throw $exception;
}
$data []= array_combine($titles, $rowData);
}
return $data;
}
protected function getRowData(PhpSpreadsheet\Worksheet\Row $row, ?array $titles = null): array
{
$data = [];
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(true);
foreach ($cellIterator as $cell) {
if ($cell->getCalculatedValue() === null) {
continue;
}
$value = $cell->getCalculatedValue();
if ($value === null) {
continue;
}
$value = mb_strtolower($value);
if ($titles !== null and in_array($value, $titles)) {
throw new InvalidArgumentException('Row matches title', 1000);
}
$data []= $value;
}
return $data;
}
}

View File

@ -0,0 +1,9 @@
<?php
namespace Incoviba\Service\FileUpload;
use Psr\Http\Message\UploadedFileInterface;
interface FileUploadInterface
{
public function getData(UploadedFileInterface $uploadedFile): array;
}

View File

@ -1,19 +1,31 @@
<?php
namespace Incoviba\Service\Venta;
use DateTimeInterface;
use PDOException;
use Psr\Http\Message\UploadedFileInterface;
use Psr\Log\LoggerInterface;
use Incoviba\Common\Ideal;
use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Exception\ServiceAction\Read;
use Incoviba\Repository;
use Incoviba\Exception\ServiceAction;
use Incoviba\Model;
use Incoviba\Repository;
class Precio
class Precio extends Ideal\Service
{
public function __construct(protected Repository\Venta\Precio $precioRepository, protected Repository\Venta\EstadoPrecio $estadoPrecioRepository) {}
public function __construct(LoggerInterface $logger,
protected Repository\Venta\Precio $precioRepository,
protected Repository\Venta\EstadoPrecio $estadoPrecioRepository,
protected Precio\Estado $estadoPrecioService,
protected Precio\Import $importService)
{
parent::__construct($logger);
}
/**
* @param int $proyecto_id
* @return array
* @throws Read
* @throws ServiceAction\Read
*/
public function getByProyecto(int $proyecto_id): array
{
@ -25,14 +37,14 @@ class Precio
}
return $precios;
} catch (EmptyResult $exception) {
throw new Read(__CLASS__, $exception);
throw new ServiceAction\Read(__CLASS__, $exception);
}
}
/**
* @param int $unidad_id
* @return Model\Venta\Precio
* @throws Read
* @throws ServiceAction\Read
*/
public function getVigenteByUnidad(int $unidad_id): Model\Venta\Precio
{
@ -42,14 +54,14 @@ class Precio
$precio->current = $this->estadoPrecioRepository->fetchCurrentByPrecio($precio->id);
return $precio;
} catch (EmptyResult $exception) {
throw new Read(__CLASS__, $exception);
throw new ServiceAction\Read(__CLASS__, $exception);
}
}
/**
* @param int $unidad_id
* @return array
* @throws Read
* @throws ServiceAction\Read
*/
public function getByUnidad(int $unidad_id): array
{
@ -61,7 +73,51 @@ class Precio
}
return $precios;
} catch (EmptyResult $exception) {
throw new Read(__CLASS__, $exception);
throw new ServiceAction\Read(__CLASS__, $exception);
}
}
/**
* @param int $projectId
* @param DateTimeInterface $date
* @param UploadedFileInterface $uploadedFile
* @return array
* @throws ServiceAction\Create
*/
public function import(int $projectId, DateTimeInterface $date, UploadedFileInterface $uploadedFile): array
{
$pricesData = $this->importService->importData($projectId, $date, $uploadedFile);
$prices = [];
foreach ($pricesData as $data) {
try {
$price = $this->precioRepository->create($data);
$price = $this->precioRepository->save($price);
$prices[] = $price;
} catch (EmptyResult | PDOException $exception) {
$this->logger->error('Problemas para agregar precio', ['data' => $data, 'exception' => $exception]);
}
}
foreach ($prices as $price) {
$idx = array_search($price->unidad->id, array_column($pricesData, 'unidad'));
$row = $pricesData[$idx];
try {
$this->estadoPrecioService->replacePrices($price->unidad, $date, $price);
} catch (ServiceAction\Update $exception) {
$this->logger->error('Problemas para reemplazar precios', [
'data' => $row,
'exception' => $exception
]);
}
try {
$this->estadoPrecioService->updatePrice($price, $row['fecha']);
} catch (ServiceAction\Update $exception) {
$this->logger->error('Problemas para actualizar estado de precio', [
'data' => $row,
'exception' => $exception
]);
}
}
return $prices;
}
}

View File

@ -0,0 +1,89 @@
<?php
namespace Incoviba\Service\Venta\Precio;
use DateTimeInterface;
use Incoviba\Model\Venta\Precio;
use Incoviba\Model\Venta\Unidad;
use PDOException;
use Psr\Log\LoggerInterface;
use Incoviba\Common\Ideal;
use Incoviba\Common\Implement;
use Incoviba\Exception\ServiceAction;
use Incoviba\Model;
use Incoviba\Repository;
class Estado extends Ideal\Service
{
public function __construct(LoggerInterface $logger,
protected Repository\Venta\Precio $precioRepository,
protected Repository\Venta\EstadoPrecio $estadoPrecioRepository,
protected Repository\Venta\TipoEstadoPrecio $tipoEstadoPrecioRepository)
{
parent::__construct($logger);
}
/**
* @param Model\Venta\Precio $price
* @param DateTimeInterface $date
* @return void
* @throws ServiceAction\Update
*/
public function updatePrice(Model\Venta\Precio $price, DateTimeInterface $date): void
{
try {
$tipoEstado = $this->tipoEstadoPrecioRepository->fetchByDescripcion('vigente');
} catch (Implement\Exception\EmptyResult $exception) {
throw new ServiceAction\Update(__CLASS__, $exception);
}
$data = [
'precio' => $price->id,
'fecha' => $date->format('Y-m-d'),
'estado' => $tipoEstado->id
];
try {
$estado = $this->estadoPrecioRepository->create($data);
$this->estadoPrecioRepository->save($estado);
} catch (Implement\Exception\EmptyResult | PDOException $exception) {
throw new ServiceAction\Update(__CLASS__, $exception);
}
}
/**
* @param Unidad $unidad
* @param DateTimeInterface $date
* @param Precio $price
* @return void
* @throws ServiceAction\Update
*/
public function replacePrices(Model\Venta\Unidad $unidad, DateTimeInterface $date, Model\Venta\Precio $price): void
{
try {
$tipoEstado = $this->tipoEstadoPrecioRepository->fetchByDescripcion('reemplazado');
} catch (Implement\Exception\EmptyResult $exception) {
throw new ServiceAction\Update(__CLASS__, $exception);
}
try {
$precios = $this->precioRepository->fetchByUnidad($unidad->id);
foreach ($precios as $p) {
if ($p->id === $price->id) {
continue;
}
try {
$estado = $this->estadoPrecioRepository->fetchCurrentByPrecio($p->id);
if ($estado->tipoEstadoPrecio->id === $tipoEstado->id) {
continue;
}
$data = [
'precio' => $p->id,
'estado' => $tipoEstado->id,
'fecha' => $date->format('Y-m-d')
];
$estado = $this->estadoPrecioRepository->create($data);
$this->estadoPrecioRepository->save($estado);
} catch (Implement\Exception\EmptyResult) {}
}
} catch (Implement\Exception\EmptyResult $exception) {
throw new ServiceAction\Update(__CLASS__, $exception);
}
}
}

View File

@ -0,0 +1,243 @@
<?php
namespace Incoviba\Service\Venta\Precio;
use DateTime;
use DateTimeInterface;
use PDOException;
use Psr\Http\Message\UploadedFileInterface;
use Psr\Log\LoggerInterface;
use Incoviba\Common\Ideal;
use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Exception\ServiceAction;
use Incoviba\Model;
use Incoviba\Service;
use Incoviba\Repository;
class Import extends Ideal\Service
{
public function __construct(LoggerInterface $logger,
protected Repository\Venta\Precio $precioRepository,
protected Repository\Inmobiliaria $inmobiliariaRepository,
protected Repository\Proyecto $proyectoRepository,
protected Repository\Venta\Unidad $unidadRepository,
protected Service\FileUpload $fileUploadService)
{
parent::__construct($logger);
}
/**
* @param int $projectId
* @param DateTimeInterface $date
* @param UploadedFileInterface $uploadedFile
* @return array
* @throws ServiceAction\Create
*/
public function importData(int $projectId, DateTimeInterface $date, UploadedFileInterface $uploadedFile): array
{
try {
$data = $this->fileUploadService->getData($uploadedFile);
} catch (ServiceAction\Read $exception) {
throw new ServiceAction\Create(__CLASS__, $exception);
}
$mappedData = $this->mapData($data, $projectId, $date);
$pricesData = [];
foreach ($mappedData as $row) {
$pricesData[] = [
'unidad' => $row['unidad'],
'valor' => $row['precio'],
'fecha' => $row['fecha']
];
}
try {
$priceUnitIds = array_map(fn($price) => $price['unidad'], $pricesData);
$prices = $this->precioRepository->fetchVigentesByUnidades($priceUnitIds);
$priceUnitIds = array_map(fn(array $p) => $p['id'], $prices);
$pricePrices = array_map(fn(array $p) => $p['precio']->valor, $prices);
return array_filter($pricesData, function($price) use ($priceUnitIds, $pricePrices) {
$idx = array_search($price['unidad'], $priceUnitIds);
if ($idx === false) {
return true;
}
return $pricePrices[$idx] !== $price['valor'];
});
} catch (EmptyResult $exception) {
throw new ServiceAction\Create(__CLASS__, $exception);
}
}
protected array $realTitlesMap;
protected function extractTitlesFromData(array $data): array
{
if (isset($this->realTitlesMap)) {
return $this->realTitlesMap;
}
$baseTitlesMap = [
'proyecto' => [],
'precio' => [],
'unidad' => ['departamento'],
'tipo' => ['tipo unidad'],
'fecha' => []
];
$realTitlesMap = [];
$titles = array_keys($data[0]);
foreach ($baseTitlesMap as $base => $optionals) {
foreach ($titles as $title) {
if (str_contains($title, $base)) {
$realTitlesMap[$title] = $base;
break;
}
foreach ($optionals as $optional) {
if (str_contains($title, $optional)) {
$realTitlesMap[$title] = $base;
break;
}
}
}
}
return $this->realTitlesMap = $realTitlesMap;
}
protected function mapData(array $data, int $projectId, DateTimeInterface $date): array
{
$mappedData = $this->mapTitles($data);
$mappedData = $this->mapProjects($mappedData, $projectId);
$mappedData = $this->mapUnits($mappedData);
return $this->mapDates($mappedData, $date);
}
protected function mapTitles(array $data): array
{
$titlesMap = $this->extractTitlesFromData($data);
$mappedData = [];
foreach ($data as $row) {
$mappedData []= $this->mapRow($row, $titlesMap);
}
return $mappedData;
}
protected function mapProjects(array $data, int $projectId): array
{
if (!array_key_exists('proyecto', $data[0])) {
return array_map(function($row) use ($projectId) {
$row['proyecto'] = $projectId;
return $row;
},$data);
}
$projects = $this->extractProjectsFromData($data);
$mappedData = [];
foreach ($data as $row) {
$mappedRow = $row;
$mappedRow['proyecto'] = $projects[$row['proyecto']]?->id ?? $projectId;
$mappedData []= $mappedRow;
}
return $mappedData;
}
protected function mapUnits(array $data): array
{
if (!array_key_exists('unidad', $data[0]) or !array_key_exists('tipo', $data[0])) {
return $data;
}
$unidades = [];
$mappedData = [];
foreach ($data as $row) {
if (!isset($unidades[$row['proyecto']])) {
$unidades[$row['proyecto']] = $this->unidadRepository->fetchByProyecto($row['proyecto']);
}
$tipo = $this->mapTipoUnidad($row['tipo']);
$unidad = array_filter($unidades[$row['proyecto']], function(Model\Venta\Unidad $unidad) use ($row, $tipo) {
return $unidad->descripcion == $row['unidad']
and $unidad->proyectoTipoUnidad->tipoUnidad->descripcion == $tipo;
});
if (count($unidad) === 0) {
$this->logger->warning('Unidad no encontrada', ['row' => $row]);
continue;
}
$mappedRow = $row;
$mappedRow['unidad'] = array_shift($unidad)->id;
unset($mappedRow['tipo']);
$mappedData []= $mappedRow;
}
return $mappedData;
}
protected function mapDates(array $data, DateTimeInterface $date): array
{
if (!array_key_exists('fecha', $data[0])) {
return array_map(function($row) use ($date) {
$row['fecha'] = $date;
return $row;
}, $data);
}
$mappedData = [];
foreach ($data as $row) {
$mappedRow = $row;
$newDate = DateTime::createFromFormat('d/m/Y', $row['fecha']);
$mappedRow['fecha'] = $newDate;
if ($newDate === false) {
$mappedRow['fecha'] = $date;
}
$mappedData []= $mappedRow;
}
return $mappedData;
}
protected function mapRow(array $row, array $titlesMap): array
{
$mappedRow = [];
foreach ($row as $key => $value) {
$mappedRow[$titlesMap[$key]] = $value;
}
return $mappedRow;
}
protected function mapTipoUnidad(string $tipo): string
{
if (str_contains(mb_strtolower($tipo), 'bod')) {
return 'bodega';
}
if (str_contains(mb_strtolower($tipo), 'est')) {
return 'estacionamiento';
}
if (str_contains(mb_strtolower($tipo), 'terr')) {
return 'terraza';
}
return 'departamento';
}
protected array $projectsMap;
protected function extractProjectsFromData(array $data): array
{
if (isset($this->projectsMap)) {
return $this->projectsMap;
}
$projectNames = array_unique(array_map(fn($row) => $row['proyecto'], $data));
$projects = [];
foreach ($projectNames as $projectName) {
try {
$projects[$projectName] = $this->proyectoRepository->fetchByName($projectName);
} catch (EmptyResult $exception) {
try {
$inm = $this->inmobiliariaRepository->fetchByName($projectName);
$inmProjects = $this->proyectoRepository->fetchByInmobiliaria($inm->rut);
$projects[$projectName] = $inmProjects[0];
} catch (EmptyResult $exception2) {
$this->logger->warning('Neither Project nor Society found', [
'projectName' => $projectName,
'exceptions' => [
[
'code' => $exception->getCode(),
'message' => $exception->getMessage(),
'file' => $exception->getFile(),
'line' => $exception->getLine(),
'data' => $exception->getData(),
'trace' => $exception->getTraceAsString()
],
[
'code' => $exception2->getCode(),
'message' => $exception2->getMessage(),
'file' => $exception2->getFile(),
'line' => $exception2->getLine(),
'data' => $exception2->getData(),
'trace' => $exception2->getTraceAsString()
]
],
]);
}
}
}
return $this->projectsMap = $projects;
}
}