first commit

This commit is contained in:
Arturo Corro 2025-03-05 15:03:05 -06:00
commit 33a7dfdadf
11 changed files with 393 additions and 0 deletions

18
.editorconfig Normal file
View File

@ -0,0 +1,18 @@
root = true
[*]
charset = utf-8
end_of_line = lf
indent_size = 4
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true
[*.md]
trim_trailing_whitespace = false
[*.{yml,yaml}]
indent_size = 2
[docker-compose.yml]
indent_size = 4

38
.gitattributes vendored Normal file
View File

@ -0,0 +1,38 @@
* text=auto eol=lf
*.blade.php diff=html
*.css diff=css
*.html diff=html
*.md diff=markdown
*.php diff=php
/.github export-ignore
CHANGELOG.md export-ignore
.styleci.yml export-ignore
# Ignorar archivos de configuración y herramientas de desarrollo
.editorconfig export-ignore
.prettierrc.json export-ignore
.prettierignore export-ignore
.eslintrc.json export-ignore
# Ignorar node_modules y dependencias locales
node_modules/ export-ignore
vendor/ export-ignore
# Ignorar archivos de build
npm-debug.log export-ignore
# Ignorar carpetas de logs y caché
storage/logs/ export-ignore
storage/framework/ export-ignore
# Ignorar carpetas de compilación de frontend
public/build/ export-ignore
dist/ export-ignore
# Ignorar archivos de CI/CD
.github/ export-ignore
.gitlab-ci.yml export-ignore
.vscode/ export-ignore
.idea/ export-ignore

10
.gitignore vendored Normal file
View File

@ -0,0 +1,10 @@
/node_modules
/vendor
/.vscode
/.nova
/.fleet
/.phpactor.json
/.phpunit.cache
/.phpunit.result.cache
/.zed
/.idea

16
.prettierignore Normal file
View File

@ -0,0 +1,16 @@
# Dependencias de Composer y Node.js
/vendor/
/node_modules/
# Caché y logs
/storage/
*.log
*.cache
# Archivos del sistema
.DS_Store
Thumbs.db
# Configuración de editores
.idea/
.vscode/

29
.prettierrc.json Normal file
View File

@ -0,0 +1,29 @@
{
"arrowParens": "avoid",
"bracketSpacing": true,
"bracketSameLine": true,
"htmlWhitespaceSensitivity": "css",
"insertPragma": false,
"jsxSingleQuote": true,
"printWidth": 120,
"proseWrap": "preserve",
"quoteProps": "as-needed",
"requirePragma": false,
"semi": true,
"singleQuote": true,
"tabWidth": 4,
"trailingComma": "none",
"useTabs": false,
"endOfLine": "lf",
"embeddedLanguageFormatting": "auto",
"overrides": [
{
"files": [
"resources/assets/**/*.js"
],
"options": {
"semi": false
}
}
]
}

39
CHANGELOG.md Normal file
View File

@ -0,0 +1,39 @@
# 📜 CHANGELOG - Laravel Exchange Rate API
Este documento sigue el formato [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [0.1.0] - ALPHA - 2024-03-05
### ✨ Added (Agregado)
- 🚀 Primera versión alpha de la librería.
- 🔹 Implementación inicial de [funcionalidad clave 1].
- 🔹 Integración con [dependencia o servicio principal].
- 🔹 Soporte para [Laravel/Vuexy Admin, si aplica].
### 🛠 Changed (Modificado)
- 🔄 Optimización de [código o estructura interna].
### 🐛 Fixed (Correcciones)
- 🐞 Correcciones iniciales en [migraciones, modelos, servicios, etc.].
---
## 📅 Próximos Cambios Planeados
- 📊 **Mejoras en [feature futuro]**.
- 🏪 **Compatibilidad con [Laravel 11, Vuexy, etc.]**.
- 📍 **Integración con [API o funcionalidad esperada]**.
---
**📌 Nota:** Esta es una versión **ALPHA**, aún en desarrollo.
---
## 🔄 Sincronización de Cambios
Este `CHANGELOG.md` se actualiza primero en nuestro repositorio principal en **[Tea - Koneko Git](https://git.koneko.mx/koneko/laravel-exchange-rates-api)** y luego se refleja en GitHub.
Los cambios recientes pueden verse antes en **Tea** que en **GitHub** debido a la sincronización automática.
---
📅 Última actualización: **2024-03-05**.

9
CONTRIBUTING.md Normal file
View File

@ -0,0 +1,9 @@
## 🔐 Acceso al Repositorio Privado
Nuestro servidor Git en **Tea** tiene un registro cerrado. Para contribuir:
1. Abre un **Issue** en [GitHub](https://github.com/koneko-mx/laravel-exchange-rates-api/issues) indicando tu interés en contribuir.
2. Alternativamente, envía un correo a **admin@koneko.mx** solicitando acceso.
3. Una vez aprobado, recibirás una invitación para registrarte y clonar el repositorio.
Si solo necesitas acceso de lectura, puedes clonar la versión pública en **GitHub**.

9
LICENSE Normal file
View File

@ -0,0 +1,9 @@
MIT License
Copyright (c) 2025 koneko
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

104
README.md Normal file
View File

@ -0,0 +1,104 @@
# 📦 Laravel Exchange Rates API
<p align="center">
<a href="https://koneko.mx" target="_blank"> <img src="https://git.koneko.mx/Koneko-ST/koneko-st/raw/branch/main/logo-images/horizontal-05.png" width="400" alt="Koneko Soluciones Tecnológicas Logo"> </a>
</p>
<p align="center">
<a href="https://koneko.mx"><img src="https://img.shields.io/badge/Website-koneko.mx-blue" alt="Sitio Web"></a>
<a href="https://packagist.org/packages/koneko/laravel-exchange-rates-api"><img src="https://img.shields.io/packagist/v/koneko/laravel-exchange-rates-api" alt="Latest Stable Version"></a>
<a href="https://packagist.org/packages/koneko/laravel-exchange-rates-api"><img src="https://img.shields.io/packagist/l/koneko/laravel-exchange-rates-api" alt="License"></a>
<a href="https://git.koneko.mx/koneko"><img src="https://img.shields.io/badge/Git%20Server-Koneko%20Git-orange" alt="Servidor Git"></a>
<a href="https://github.com/koneko-mx/laravel-exchange-rates-api/actions/workflows/tests.yml"><img src="https://github.com/koneko-mx/laravel-exchange-rates-api/actions/workflows/tests.yml/badge.svg" alt="Build Status"></a>
<a href="https://github.com/koneko-mx/laravel-exchange-rates-api/issues"><img src="https://img.shields.io/github/issues/koneko/laravel-exchange-rates-api" alt="Issues"></a>
</p>
---
## 📌 Descripción
**Larvel Exchange Rates API** es un paquete de Laravel diseñado para [descripción breve de la funcionalidad].
### ✨ Características:
- 🔹 Funcionalidad clave 1
- 🔹 Funcionalidad clave 2
- 🔹 Funcionalidad clave 3
---
## 📦 Instalación
Instalar vía **Composer**:
```bash
composer require koneko/laravel-exchange-rates-api
```
Publicar archivos de configuración y migraciones (si aplica):
```bash
php artisan vendor:publish --tag=laravel-exchange-rates-api-config
php artisan migrate
```
---
## 🚀 Uso básico
```php
use Koneko\NombreLibreria\Models\Model;
$model = Model::create([
'campo1' => 'Valor',
'campo2' => 'Otro valor',
]);
```
---
## 📚 Configuración adicional
Si necesitas personalizar la configuración del módulo, publica el archivo de configuración:
```bash
php artisan vendor:publish --tag=laravel-exchange-rates-api-config
```
Esto generará `config/laravel-exchange-rates-api.php`, donde puedes modificar valores predeterminados.
---
## 🛠 Dependencias
Este paquete requiere las siguientes dependencias:
- Laravel 11
- Dependencias específicas de la librería
---
## 🌍 Repositorio Principal y Sincronización
Este repositorio es una **copia sincronizada** del repositorio principal alojado en **[Tea - Koneko Git](https://git.koneko.mx/koneko/laravel-exchange-rates-api)**.
### 🔄 Sincronización con GitHub
- **Repositorio Principal:** [git.koneko.mx](https://git.koneko.mx/koneko/laravel-exchange-rates-api)
- **Repositorio en GitHub:** [github.com/koneko-mx/laravel-exchange-rates-api](https://github.com/koneko-mx/laravel-exchange-rates-api)
- **Los cambios pueden reflejarse primero en Tea antes de GitHub.**
### 🤝 Contribuciones
Si deseas contribuir:
1. Puedes abrir un **Issue** en [GitHub Issues](https://github.com/koneko-mx/laravel-exchange-rates-api/issues).
2. Para Pull Requests, **preferimos contribuciones en Tea**. Contacta a `admin@koneko.mx` para solicitar acceso.
⚠️ **Nota:** Algunos cambios pueden tardar en reflejarse en GitHub, ya que este repositorio se actualiza automáticamente desde Tea.
---
## 🏅 Licencia
Este paquete es de código abierto bajo la licencia [MIT](LICENSE).
---
<p align="center">
Hecho con ❤️ por <a href="https://koneko.mx">Koneko Soluciones Tecnológicas</a>
</p>

View File

@ -0,0 +1,93 @@
<?php
namespace Koneko\CurrencyApi\Services;
use Illuminate\Support\Facades\Http;
use Koneko\VuexyAdmin\Models\CurrencyRate;
use Koneko\VuexyAdmin\Models\Setting;
use Carbon\Carbon;
class CurrencyApiService
{
protected array $providers = ['banxico', 'fixer', 'ecb'];
/**
* Obtiene la tasa de cambio de una moneda en una fecha específica.
*/
public function getExchangeRate(string $currency, $date = null): ?float
{
$date = $date ?: Carbon::now()->toDateString();
return CurrencyRate::where('currency_code', $currency)
->where('date', '<=', $date)
->orderByDesc('date')
->first()
?->exchange_rate;
}
/**
* Actualiza las tasas de cambio de las 10 divisas.
*/
public function updateExchangeRates()
{
foreach ($this->providers as $provider) {
$this->fetchAndStoreRates($provider);
}
}
/**
* Obtiene tasas de un proveedor y las guarda.
*/
protected function fetchAndStoreRates(string $provider)
{
$rates = match ($provider) {
'banxico' => $this->fetchBanxicoRates(),
'fixer' => $this->fetchFixerRates(),
default => []
};
foreach ($rates as $currency => $rate) {
CurrencyRate::updateOrCreate(
['currency_code' => $currency, 'date' => Carbon::now()->toDateString(), 'source' => $provider],
['exchange_rate' => $rate]
);
}
}
/**
* Obtiene tasas de Banxico (solo las divisas disponibles en su API).
*/
protected function fetchBanxicoRates(): array
{
$apiKey = Setting::getValue('banxico.api_key');
$url = "https://www.banxico.org.mx/SieAPIRest/service/v1/series/SF43718,SF46410,SF46407,SF46406,SF60632/datos/oportuno/?token={$apiKey}";
$response = Http::get($url);
if ($response->successful()) {
$data = $response->json();
return [
'USD' => (float) ($data['bmx']['series'][0]['datos'][0]['dato'] ?? null),
'EUR' => (float) ($data['bmx']['series'][1]['datos'][0]['dato'] ?? null),
'GBP' => (float) ($data['bmx']['series'][2]['datos'][0]['dato'] ?? null),
'JPY' => (float) ($data['bmx']['series'][3]['datos'][0]['dato'] ?? null),
'CAD' => (float) ($data['bmx']['series'][4]['datos'][0]['dato'] ?? null),
];
}
return [];
}
/**
* Obtiene tasas de Fixer.io.
*/
protected function fetchFixerRates(): array
{
$apiKey = Setting::getValue('fixer.api_key');
$url = "http://data.fixer.io/api/latest?access_key={$apiKey}&symbols=USD,EUR,GBP,JPY,CAD,AUD,CHF,CNY,GTQ,MXN";
$response = Http::get($url);
return $response->successful() ? $response->json()['rates'] ?? [] : [];
}
}

28
composer.json Normal file
View File

@ -0,0 +1,28 @@
{
"name": "koneko/laravel-exchange-rates-api",
"description": "Laravel Exchange Rates API, es un Servicio para obtener las tasas de cambio de las principales monedas del mundo.",
"keywords": ["laravel", "koneko", "framework", "api", "exchange", "rates", "currencies"],
"type": "library",
"license": "MIT",
"require": {
"php": "^8.2",
"laravel/framework": "^11.31"
},
"autoload": {
"psr-4": {
"Koneko\\ExchangeRatesApi\\": ""
}
},
"authors": [
{
"name": "Arturo Corro Pacheco",
"email": "arturo@koneko.mx"
}
],
"support": {
"source": "https://github.com/koneko-mx/laravel-exchange-rates-api",
"issues": "https://github.com/koneko-mx/laravel-exchange-rates-api/issues"
},
"minimum-stability": "dev",
"prefer-stable": true
}