1 Commits

Author SHA1 Message Date
742de657c5 develop (#45)
Co-authored-by: Juan Pablo Vial <jpvialb@incoviba.cl>
Reviewed-on: #45
2025-10-04 11:40:52 -03:00
7 changed files with 38 additions and 112 deletions

View File

@ -2,7 +2,6 @@
namespace Incoviba\Common\Define\Cartola; namespace Incoviba\Common\Define\Cartola;
use Psr\Http\Message\UploadedFileInterface; use Psr\Http\Message\UploadedFileInterface;
use Incoviba\Exception\ServiceAction\Read;
interface Banco interface Banco
{ {
@ -10,7 +9,6 @@ interface Banco
* Process bank movements for database inserts * Process bank movements for database inserts
* @param UploadedFileInterface $file * @param UploadedFileInterface $file
* @return array * @return array
* @throws Read
*/ */
public function process(UploadedFileInterface $file): array; public function process(UploadedFileInterface $file): array;

View File

@ -3,16 +3,10 @@ namespace Incoviba\Common\Ideal\Cartola;
use Incoviba\Common\Define; use Incoviba\Common\Define;
use Incoviba\Common\Ideal\Service; use Incoviba\Common\Ideal\Service;
use Incoviba\Exception\ServiceAction\Read;
use Psr\Http\Message\UploadedFileInterface; use Psr\Http\Message\UploadedFileInterface;
abstract class Banco extends Service implements Define\Cartola\Banco abstract class Banco extends Service implements Define\Cartola\Banco
{ {
/**
* @param UploadedFileInterface $file
* @return array
* @throws Read
*/
public function process(UploadedFileInterface $file): array public function process(UploadedFileInterface $file): array
{ {
$filename = $this->processUploadedFile($file); $filename = $this->processUploadedFile($file);
@ -46,7 +40,6 @@ abstract class Banco extends Service implements Define\Cartola\Banco
* Process the temp file from getFilename and remove it * Process the temp file from getFilename and remove it
* @param string $filename * @param string $filename
* @return array * @return array
* @throws Read
*/ */
protected function processFile(string $filename): array protected function processFile(string $filename): array
{ {
@ -95,7 +88,6 @@ abstract class Banco extends Service implements Define\Cartola\Banco
* Translate uploaded file data to database data * Translate uploaded file data to database data
* @param string $filename * @param string $filename
* @return array * @return array
* @throws Read
*/ */
abstract protected function parseFile(string $filename): array; abstract protected function parseFile(string $filename): array;
} }

View File

@ -338,7 +338,6 @@
data.errors.forEach(errorData => { data.errors.forEach(errorData => {
console.error(errorData) console.error(errorData)
}) })
throw Error('Error al importar cartolas')
} }
this.data.movimientos = data.movimientos.map(movimiento => new Movimiento(movimiento)) this.data.movimientos = data.movimientos.map(movimiento => new Movimiento(movimiento))
this.draw().movimientos() this.draw().movimientos()

View File

@ -2,7 +2,6 @@
namespace Incoviba\Controller\API\Contabilidad; namespace Incoviba\Controller\API\Contabilidad;
use DateTimeImmutable; use DateTimeImmutable;
use Incoviba\Exception\ServiceAction\Read;
use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Message\ServerRequestInterface;
use Incoviba\Common\Ideal\Controller; use Incoviba\Common\Ideal\Controller;
@ -118,21 +117,24 @@ class Cartolas extends Controller
UPLOAD_ERR_CANT_WRITE => 'No se pudo escribir el archivo', UPLOAD_ERR_CANT_WRITE => 'No se pudo escribir el archivo',
UPLOAD_ERR_EXTENSION => 'Una extensión de PHP detuvo la subida del archivo' UPLOAD_ERR_EXTENSION => 'Una extensión de PHP detuvo la subida del archivo'
]; ];
if (!is_array($files['file'])) { if (is_array($files['file'])) {
$files['file'] = [$files['file']]; foreach ($files['file'] as $i => $file) {
$body['cuenta_id'] = [$body['cuenta_id']]; if ($file->getError() !== UPLOAD_ERR_OK) {
} $output['errors'] []= ['filename' => $file->getClientFilename(), 'error' => $errors[$file->getError()]];
foreach ($files['file'] as $i => $file) { continue;
if ($file->getError() !== UPLOAD_ERR_OK) { }
$output['errors'] []= ['filename' => $file->getClientFilename(), 'error' => $errors[$file->getError()]]; try {
continue; $output['movimientos'] = array_merge($output['movimientos'], $cartolaService->import($body['cuenta_id'][$i], $file));
} catch (EmptyResult) {}
} }
try { } else {
$output['movimientos'] = array_merge($output['movimientos'], $cartolaService->import($body['cuenta_id'][$i], $file)); $file = $files['file'];
} catch (Read $exception) { if ($file->getError() !== UPLOAD_ERR_OK) {
$output['errors'] []= ['filename' => $file->getClientFilename(), $output['errors'][] = ['filename' => $file->getClientFilename(), 'error' => $errors[$file->getError()]];
'error' => ['message' => $exception->getMessage(), 'file' => $exception->getFile(), } else {
'line' => $exception->getLine()]]; try {
$output['movimientos'] = $cartolaService->import($body['cuenta_id'], $file);
} catch (EmptyResult) {}
} }
} }
return $this->withJson($response, $output); return $this->withJson($response, $output);

View File

@ -1,21 +1,18 @@
<?php <?php
namespace Incoviba\Service\Contabilidad; namespace Incoviba\Service\Contabilidad;
use DateMalformedStringException;
use PDOException; use PDOException;
use DateTimeImmutable; use DateTimeImmutable;
use DateTimeInterface; use DateTimeInterface;
use Psr\Http\Message\StreamFactoryInterface;
use Psr\Http\Message\UploadedFileInterface;
use Psr\Log\LoggerInterface;
use PhpOffice\PhpSpreadsheet;
use Incoviba\Common\Define\Cartola\Banco; use Incoviba\Common\Define\Cartola\Banco;
use Incoviba\Common\Define\Contabilidad\Exporter; use Incoviba\Common\Define\Contabilidad\Exporter;
use Incoviba\Common\Ideal\Service; use Incoviba\Common\Ideal\Service;
use Incoviba\Common\Implement\Exception; use Incoviba\Common\Implement\Exception;
use Incoviba\Exception\ServiceAction\Read;
use Incoviba\Model; use Incoviba\Model;
use Incoviba\Repository; use Incoviba\Repository;
use Psr\Http\Message\StreamFactoryInterface;
use Psr\Http\Message\UploadedFileInterface;
use Psr\Log\LoggerInterface;
class Cartola extends Service class Cartola extends Service
{ {
@ -35,13 +32,6 @@ class Cartola extends Service
$this->bancos[$name] = $banco; $this->bancos[$name] = $banco;
return $this; return $this;
} }
/**
* @param Model\Contabilidad\Banco $banco
* @param UploadedFileInterface $file
* @return array
* @throws Read
*/
public function process(Model\Contabilidad\Banco $banco, UploadedFileInterface $file): array public function process(Model\Contabilidad\Banco $banco, UploadedFileInterface $file): array
{ {
return $this->bancos[strtolower($banco->nombre)]->process($file); return $this->bancos[strtolower($banco->nombre)]->process($file);
@ -103,19 +93,9 @@ class Cartola extends Service
return compact('cartola', 'movimientos'); return compact('cartola', 'movimientos');
} }
/**
* @param int $cuenta_id
* @param UploadedFileInterface $file
* @return array
* @throws Read
*/
public function import(int $cuenta_id, UploadedFileInterface $file): array public function import(int $cuenta_id, UploadedFileInterface $file): array
{ {
try { $cuenta = $this->cuentaRepository->fetchById($cuenta_id);
$cuenta = $this->cuentaRepository->fetchById($cuenta_id);
} catch (Exception\EmptyResult $exception) {
throw new Read(__CLASS__, $exception);
}
$movimientos = $this->process($cuenta->banco, $file); $movimientos = $this->process($cuenta->banco, $file);
$inmobiliaria = $cuenta->inmobiliaria; $inmobiliaria = $cuenta->inmobiliaria;
@ -126,23 +106,15 @@ class Cartola extends Service
if (array_key_exists('centro_costo', $dataMovimiento) and $dataMovimiento['centro_costo'] !== 0) { if (array_key_exists('centro_costo', $dataMovimiento) and $dataMovimiento['centro_costo'] !== 0) {
$dataMovimiento['centro_costo_id'] = $dataMovimiento['centro_costo']; $dataMovimiento['centro_costo_id'] = $dataMovimiento['centro_costo'];
} }
try { $dataMovimiento['fecha'] = new DateTimeImmutable($dataMovimiento['fecha']);
$dataMovimiento['fecha'] = new DateTimeImmutable($dataMovimiento['fecha']);
} catch (DateMalformedStringException) {
continue;
}
if (array_key_exists('rut', $dataMovimiento)) { if (array_key_exists('rut', $dataMovimiento)) {
if ($dataMovimiento['rut'] === '') { $ruts = $this->parseRut($dataMovimiento['rut']);
unset($dataMovimiento['rut']); if (key_exists('rut', $ruts)) {
$dataMovimiento['rut'] = $ruts['rut'];
$dataMovimiento['digito'] = $ruts['digito'];
} else { } else {
$ruts = $this->parseRut($dataMovimiento['rut']); $dataMovimiento['rut'] = $ruts[0]['rut'];
if (key_exists('rut', $ruts)) { $dataMovimiento['digito'] = $ruts[0]['digito'];
$dataMovimiento['rut'] = $ruts['rut'];
$dataMovimiento['digito'] = $ruts['digito'];
} else {
$dataMovimiento['rut'] = $ruts[0]['rut'];
$dataMovimiento['digito'] = $ruts[0]['digito'];
}
} }
} }
try { try {
@ -161,28 +133,14 @@ class Cartola extends Service
$fechas = array_unique(array_map(function($movimiento) { $fechas = array_unique(array_map(function($movimiento) {
return $movimiento['fecha']->format('Y-m-d'); return $movimiento['fecha']->format('Y-m-d');
}, $movimientos)); }, $movimientos));
if (count($fechas) === 0) {
throw new Read(__CLASS__);
}
foreach ($fechas as $dia) { foreach ($fechas as $dia) {
try { try {
$dayDate = new DateTimeImmutable($dia); $this->cartolaRepository->fetchByCuentaAndFecha($cuenta->id, new DateTimeImmutable($dia));
} catch (DateMalformedStringException) {
continue;
}
try {
$this->cartolaRepository->fetchByCuentaAndFecha($cuenta->id, $dayDate);
continue; continue;
} catch (Exception\EmptyResult) {} } catch (Exception\EmptyResult) {}
$movs = array_filter($movimientos, function($movimiento) use ($dia) { $movs = array_filter($movimientos, function($movimiento) use ($dia) {
return $movimiento['fecha']->format('Y-m-d') === $dia; return $movimiento['fecha'] === $dia;
}); });
if (count($movs) === 0) {
continue;
}
$cargos = array_sum(array_map(function($movimiento) { $cargos = array_sum(array_map(function($movimiento) {
return $movimiento['cargo']; return $movimiento['cargo'];
}, $movs)); }, $movs));
@ -195,19 +153,11 @@ class Cartola extends Service
'abonos' => $abonos, 'abonos' => $abonos,
'saldo' => $saldo 'saldo' => $saldo
]; ];
$this->buildCartola($cuenta, $dayDate, $cartolaData); $this->buildCartola($cuenta, new DateTimeImmutable($dia), $cartolaData);
} }
try { $startDate = new DateTimeImmutable(min($fechas));
$startDate = new DateTimeImmutable(min($fechas)); $endDate = new DateTimeImmutable(max($fechas));
} catch (DateMalformedStringException $exception) {
throw new Read(__CLASS__, $exception);
}
try {
$endDate = new DateTimeImmutable(max($fechas));
} catch (DateMalformedStringException $exception) {
throw new Read(__CLASS__, $exception);
}
$movimientosFaltantes = $this->movimientoService->findMissing($cuenta, $addedMovimientos, $startDate, $endDate); $movimientosFaltantes = $this->movimientoService->findMissing($cuenta, $addedMovimientos, $startDate, $endDate);
$movimientosObsoletos = []; $movimientosObsoletos = [];
if (count($movimientosFaltantes) > 0) { if (count($movimientosFaltantes) > 0) {

View File

@ -3,7 +3,6 @@ namespace Incoviba\Service\Contabilidad\Cartola;
use DateTimeImmutable; use DateTimeImmutable;
use Incoviba\Common\Ideal\Cartola\Banco; use Incoviba\Common\Ideal\Cartola\Banco;
use Incoviba\Exception\ServiceAction\Read;
use PhpOffice\PhpSpreadsheet; use PhpOffice\PhpSpreadsheet;
use Psr\Http\Message\UploadedFileInterface; use Psr\Http\Message\UploadedFileInterface;
@ -11,8 +10,8 @@ class Itau extends Banco
{ {
use isExcel; use isExcel;
const int CUENTA_CORRIENTE = 0; const CUENTA_CORRIENTE = 0;
const int ULTIMOS_MOVIMIENTOS = 1; const ULTIMOS_MOVIMIENTOS = 1;
public function processMovimientosDiarios(array $movimientos): array public function processMovimientosDiarios(array $movimientos): array
{ {
@ -45,12 +44,6 @@ class Itau extends Banco
$ext = pathinfo($uploadedFile->getClientFilename(), PATHINFO_EXTENSION); $ext = pathinfo($uploadedFile->getClientFilename(), PATHINFO_EXTENSION);
return "/tmp/cartola.{$ext}"; return "/tmp/cartola.{$ext}";
} }
/**
* @param string $filename
* @return array
* @throws Read
*/
protected function parseFile(string $filename): array protected function parseFile(string $filename): array
{ {
$ext = pathinfo($filename, PATHINFO_EXTENSION); $ext = pathinfo($filename, PATHINFO_EXTENSION);
@ -69,7 +62,7 @@ class Itau extends Banco
break; break;
} }
} catch (PhpSpreadsheet\Exception $exception) { } catch (PhpSpreadsheet\Exception $exception) {
throw new Read(__CLASS__, $exception); $this->logger->critical($exception);
} }
return $data; return $data;
} }
@ -173,11 +166,6 @@ class Itau extends Banco
}); });
} }
/**
* @param PhpSpreadsheet\Worksheet\Worksheet $sheet
* @return int
* @throws PhpSpreadsheet\Exception
*/
protected function identifySheet(PhpSpreadsheet\Worksheet\Worksheet $sheet): int protected function identifySheet(PhpSpreadsheet\Worksheet\Worksheet $sheet): int
{ {
foreach ($sheet->getRowIterator(1, 10) as $row) { foreach ($sheet->getRowIterator(1, 10) as $row) {
@ -189,7 +177,7 @@ class Itau extends Banco
return self::ULTIMOS_MOVIMIENTOS; return self::ULTIMOS_MOVIMIENTOS;
} }
} }
throw new PhpSpreadsheet\Exception('Incorrect type of Worksheet'); throw new PhpSpreadsheet\Exception();
} }
protected function getDateRange(PhpSpreadsheet\Worksheet\Row $row): array protected function getDateRange(PhpSpreadsheet\Worksheet\Row $row): array
{ {

View File

@ -12,9 +12,6 @@ class MiIndicador implements Provider
public function __construct(protected ClientInterface $client) {} public function __construct(protected ClientInterface $client) {}
/** /**
* @param string $money_symbol
* @param DateTimeInterface|null $dateTime
* @return float
* @throws EmptyResponse * @throws EmptyResponse
*/ */
public function get(string $money_symbol, ?DateTimeInterface $dateTime = null): float public function get(string $money_symbol, ?DateTimeInterface $dateTime = null): float
@ -36,7 +33,7 @@ class MiIndicador implements Provider
$body = $response->getBody(); $body = $response->getBody();
$json = json_decode($body->getContents()); $json = json_decode($body->getContents());
if (empty($json) or !isset($json->codigo) or !isset($json->serie) or $json->codigo !== $money_symbol or count($json->serie) === 0) { if (empty($json) or $json->codigo !== $money_symbol or count($json->serie) === 0) {
throw new EmptyResponse($request_uri); throw new EmptyResponse($request_uri);
} }
return $json->serie[0]->valor; return $json->serie[0]->valor;