feat: implement currency rates tracking with models, migrations and views

هذا الالتزام موجود في:
2025-05-24 05:59:12 +03:00
الأصل 72b4eff3ee
التزام b19748ef20
21 ملفات معدلة مع 690 إضافات و361 حذوفات

عرض الملف

@@ -4,8 +4,8 @@ APP_KEY=
APP_DEBUG=true
APP_URL=http://localhost
APP_LOCALE=en
APP_FALLBACK_LOCALE=en
APP_LOCALE=ar
APP_FALLBACK_LOCALE=ar
APP_FAKER_LOCALE=en_US
APP_MAINTENANCE_DRIVER=file

عرض الملف

@@ -1,61 +1,20 @@
<p align="center"><a href="https://laravel.com" target="_blank"><img src="https://raw.githubusercontent.com/laravel/art/master/logo-lockup/5%20SVG/2%20CMYK/1%20Full%20Color/laravel-logolockup-cmyk-red.svg" width="400" alt="Laravel Logo"></a></p>
## Yemen Currency
<p align="center">
<a href="https://github.com/laravel/framework/actions"><img src="https://github.com/laravel/framework/workflows/tests/badge.svg" alt="Build Status"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/dt/laravel/framework" alt="Total Downloads"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/v/laravel/framework" alt="Latest Stable Version"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/l/laravel/framework" alt="License"></a>
</p>
This is a Laravel application that scrapes currency data from boqash.com, stores it in a SQLite database, and provides an API to access the data.
## About Laravel
## Installation
to be added
Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experience to be truly fulfilling. Laravel takes the pain out of development by easing common tasks used in many web projects, such as:
## Plan
- [x] Add html view to show the currency data
- [x] Save command data to database
- [ ] make proper pagination
- [ ] save tabs state as query param
- [ ] make a complete test for the project
- [ ] make the app A PWA
- [ ] put a place for ads
- [ ] add some useful information like what is buy price and sell price, the resource of the data, etc
- [Simple, fast routing engine](https://laravel.com/docs/routing).
- [Powerful dependency injection container](https://laravel.com/docs/container).
- Multiple back-ends for [session](https://laravel.com/docs/session) and [cache](https://laravel.com/docs/cache) storage.
- Expressive, intuitive [database ORM](https://laravel.com/docs/eloquent).
- Database agnostic [schema migrations](https://laravel.com/docs/migrations).
- [Robust background job processing](https://laravel.com/docs/queues).
- [Real-time event broadcasting](https://laravel.com/docs/broadcasting).
Laravel is accessible, powerful, and provides tools required for large, robust applications.
## Learning Laravel
Laravel has the most extensive and thorough [documentation](https://laravel.com/docs) and video tutorial library of all modern web application frameworks, making it a breeze to get started with the framework.
You may also try the [Laravel Bootcamp](https://bootcamp.laravel.com), where you will be guided through building a modern Laravel application from scratch.
If you don't feel like reading, [Laracasts](https://laracasts.com) can help. Laracasts contains thousands of video tutorials on a range of topics including Laravel, modern PHP, unit testing, and JavaScript. Boost your skills by digging into our comprehensive video library.
## Laravel Sponsors
We would like to extend our thanks to the following sponsors for funding Laravel development. If you are interested in becoming a sponsor, please visit the [Laravel Partners program](https://partners.laravel.com).
### Premium Partners
- **[Vehikl](https://vehikl.com)**
- **[Tighten Co.](https://tighten.co)**
- **[Kirschbaum Development Group](https://kirschbaumdevelopment.com)**
- **[64 Robots](https://64robots.com)**
- **[Curotec](https://www.curotec.com/services/technologies/laravel)**
- **[DevSquad](https://devsquad.com/hire-laravel-developers)**
- **[Redberry](https://redberry.international/laravel-development)**
- **[Active Logic](https://activelogic.com)**
## Contributing
Thank you for considering contributing to the Laravel framework! The contribution guide can be found in the [Laravel documentation](https://laravel.com/docs/contributions).
## Code of Conduct
In order to ensure that the Laravel community is welcoming to all, please review and abide by the [Code of Conduct](https://laravel.com/docs/contributions#code-of-conduct).
## Security Vulnerabilities
If you discover a security vulnerability within Laravel, please send an e-mail to Taylor Otwell via [taylor@laravel.com](mailto:taylor@laravel.com). All security vulnerabilities will be promptly addressed.
## License
The Laravel framework is open-sourced software licensed under the [MIT license](https://opensource.org/licenses/MIT).
## Future Plans
- add react native app to show the currency data

عرض الملف

@@ -2,6 +2,9 @@
namespace App\Console\Commands;
use App\Models\City;
use App\Models\Currency;
use App\Models\Rate;
use App\Services\CurrencyService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
@@ -14,8 +17,6 @@ class FetchCurrencyCommand extends Command
/**
* Execute the console command.
*
* @return int
*/
public function handle(CurrencyService $currencyService): int
{
@@ -23,19 +24,43 @@ class FetchCurrencyCommand extends Command
try {
if ($this->option('today')) {
$this->fetchTodayData($currencyService);
$data = $this->fetchTodayData($currencyService);
} else {
$this->fetchHistoricalData($currencyService);
$data = $this->fetchHistoricalData($currencyService);
}
foreach ($data as $item) {
$city = match ($item['city']) {
'Sanaa' => City::where('name', 'sanaa')->first(),
'Aden' => City::where('name', 'aden')->first(),
};
$currency = match ($item['currency']) {
'USD' => Currency::where('code', 'USD')->first(),
'SAR' => Currency::where('code', 'SAR')->first(),
};
$rate = Rate::updateOrCreate([
'city_id' => $city->id,
'currency_id' => $currency->id,
'date' => $item['date'],
], [
'buy_price' => $item['price_buy'],
'sell_price' => $item['price_sell'],
]);
}
$this->info('Currency data fetched successfully!');
return Command::SUCCESS;
} catch (\Exception $e) {
$this->error('Failed to fetch currency data: '.$e->getMessage());
Log::error('Currency fetch command failed', [
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString()
'trace' => $e->getTraceAsString(),
]);
return Command::FAILURE;
}
}
@@ -43,7 +68,7 @@ class FetchCurrencyCommand extends Command
/**
* Fetch and display today's currency data.
*
* @return void
* @return array
*/
protected function fetchTodayData(CurrencyService $currencyService)
{
@@ -51,6 +76,7 @@ class FetchCurrencyCommand extends Command
if (empty($data)) {
$this->warn('No currency data available for today.');
return;
}
@@ -64,16 +90,18 @@ class FetchCurrencyCommand extends Command
$item['price_buy'],
$item['price_sell'],
$item['date'],
$item['day']
$item['day'],
];
}, $data)
);
return $data;
}
/**
* Fetch and display historical currency data.
*
* @return void
* @return array
*/
protected function fetchHistoricalData(CurrencyService $currencyService)
{
@@ -81,6 +109,7 @@ class FetchCurrencyCommand extends Command
if (empty($data)) {
$this->warn('No historical currency data available.');
return;
}
@@ -94,9 +123,11 @@ class FetchCurrencyCommand extends Command
$item['price_buy'],
$item['price_sell'],
$item['date'],
$item['day']
$item['day'],
];
}, $data)
);
return $data;
}
}

عرض الملف

@@ -0,0 +1,34 @@
<?php
namespace App\Http\Controllers;
use App\Models\City;
use App\Models\Rate;
class RateController extends Controller
{
public function __invoke()
{
$supportedCities = City::query()
->whereIn('name', City::supportedCities())
->get()
->sortByDesc(fn ($city) => $city->name === 'sanaa')
->values();
$rates = Rate::query()
->with('currency', 'city')
->orderBy('city_id', 'asc')
->orderBy('currency_id', 'asc')
->orderBy('date', 'desc')
->get()
->groupBy(fn ($rate) => $rate->city_id.'-'.$rate->currency_id)
->map(fn ($group) => $group->first())
->groupBy('city_id');
return view('rates', [
'rates' => $rates,
'supportedCities' => $supportedCities,
]);
}
}

32
app/Models/City.php Normal file
عرض الملف

@@ -0,0 +1,32 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class City extends Model
{
/** @use HasFactory<\Database\Factories\CityFactory> */
use HasFactory;
const SANAA = 'sanaa';
const ADEN = 'aden';
protected $fillable = [
'name',
'label',
];
/**
* Get all supported cities
*/
public static function supportedCities(): array
{
return [
self::SANAA,
self::ADEN,
];
}
}

36
app/Models/Currency.php Normal file
عرض الملف

@@ -0,0 +1,36 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Currency extends Model
{
/** @use HasFactory<\Database\Factories\CurrencyFactory> */
use HasFactory;
/**
* The supported currency codes.
*/
const USD = 'USD';
const SAR = 'SAR';
protected $fillable = [
'code',
'name',
'symbol',
];
/**
* Get all supported currency codes
*/
public static function supportedCurrencies(): array
{
return [
self::USD,
self::SAR,
];
}
}

33
app/Models/Rate.php Normal file
عرض الملف

@@ -0,0 +1,33 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Rate extends Model
{
use HasFactory;
protected $fillable = [
'currency_id',
'city_id',
'buy_price',
'sell_price',
'date',
];
protected $casts = [
'date' => 'date:Y-m-d',
];
public function currency()
{
return $this->belongsTo(Currency::class);
}
public function city()
{
return $this->belongsTo(City::class);
}
}

عرض الملف

@@ -0,0 +1,40 @@
<?php
namespace Database\Factories;
use App\Models\City;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\City>
*/
class CityFactory extends Factory
{
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'name' => fake()->randomElement(City::supportedCities()),
];
}
public function sanaa()
{
return $this->state([
'name' => City::SANAA,
'label' => 'صنعاء',
]);
}
public function aden()
{
return $this->state([
'name' => City::ADEN,
'label' => 'عدن',
]);
}
}

عرض الملف

@@ -0,0 +1,56 @@
<?php
namespace Database\Factories;
use App\Models\Currency;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Currency>
*/
class CurrencyFactory extends Factory
{
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
$code = fake()->randomElement(Currency::supportedCurrencies());
$name = match ($code) {
Currency::USD => 'دولار أمريكي',
Currency::SAR => 'ريال سعودي',
};
$symbol = match ($code) {
Currency::USD => '$',
Currency::SAR => '﷼',
};
return [
'code' => $code,
'name' => $name,
'symbol' => $symbol,
];
}
public function saudiRial()
{
return $this->state([
'code' => Currency::SAR,
'name' => 'ريال سعودي',
'symbol' => '﷼',
]);
}
public function usdDollar()
{
return $this->state([
'code' => Currency::USD,
'name' => 'دولار أمريكي',
'symbol' => '$',
]);
}
}

عرض الملف

@@ -0,0 +1,63 @@
<?php
namespace Database\Factories;
use App\Models\City;
use App\Models\Currency;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Rate>
*/
class RateFactory extends Factory
{
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'currency_id' => Currency::factory(),
'city_id' => City::factory(),
'buy_price' => fn ($attributes) => $attributes['currency_id'] == Currency::SAR
? fake()->randomFloat(2, 1, 300)
: fake()->randomFloat(2, 500, 1000),
'sell_price' => fn ($attributes) => $attributes['currency_id'] == Currency::SAR
? fake()->randomFloat(2, 1, 300)
: fake()->randomFloat(2, 500, 1000),
'date' => fake()->dateTimeBetween('-20 days', 'today'),
];
}
public function withDate($date)
{
return $this->state([
'date' => $date,
]);
}
public function today()
{
return $this->state([
'date' => now(),
]);
}
public function yesterday()
{
return $this->state([
'date' => now()->subDay(),
]);
}
public function last20Days()
{
return $this->state([
'date' => fake()->unique()->dateTimeBetween('-20 days', 'yesterday'),
]);
}
}

عرض الملف

@@ -0,0 +1,30 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('currencies', function (Blueprint $table) {
$table->id();
$table->string('code');
$table->string('name');
$table->string('symbol');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('currencies');
}
};

عرض الملف

@@ -0,0 +1,34 @@
<?php
use App\Models\City;
use App\Models\Currency;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('rates', function (Blueprint $table) {
$table->id();
$table->foreignIdFor(Currency::class);
$table->foreignIdFor(City::class);
$table->decimal('buy_price');
$table->decimal('sell_price');
$table->date('date');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('rates');
}
};

عرض الملف

@@ -0,0 +1,29 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('cities', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('label');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('cities');
}
};

عرض الملف

@@ -0,0 +1,18 @@
<?php
namespace Database\Seeders;
use App\Models\City;
use Illuminate\Database\Seeder;
class CitySeeder extends Seeder
{
/**
* Run the database seeds.
*/
public function run(): void
{
City::factory()->sanaa()->create();
City::factory()->aden()->create();
}
}

عرض الملف

@@ -0,0 +1,18 @@
<?php
namespace Database\Seeders;
use App\Models\Currency;
use Illuminate\Database\Seeder;
class CurrencySeeder extends Seeder
{
/**
* Run the database seeds.
*/
public function run(): void
{
Currency::factory()->saudiRial()->create();
Currency::factory()->usdDollar()->create();
}
}

عرض الملف

@@ -2,7 +2,9 @@
namespace Database\Seeders;
use App\Models\User;
use App\Models\City;
use App\Models\Currency;
use App\Models\Rate;
// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
@@ -13,11 +15,19 @@ class DatabaseSeeder extends Seeder
*/
public function run(): void
{
// User::factory(10)->create();
// currencies
$saudiRial = Currency::factory()->saudiRial()->create();
$usdDollar = Currency::factory()->usdDollar()->create();
User::factory()->create([
'name' => 'Test User',
'email' => 'test@example.com',
]);
// cities
$sanaa = City::factory()->sanaa()->create();
$aden = City::factory()->aden()->create();
// rates
Rate::factory()->recycle($usdDollar)->recycle($sanaa)->create();
Rate::factory()->recycle($usdDollar)->recycle($aden)->create();
Rate::factory()->recycle($saudiRial)->recycle($sanaa)->create();
Rate::factory()->recycle($saudiRial)->recycle($aden)->create();
}
}

عرض الملف

@@ -0,0 +1,18 @@
<?php
namespace Database\Seeders;
use App\Models\Rate;
use Illuminate\Database\Seeder;
class RateSeeder extends Seeder
{
/**
* Run the database seeds.
*/
public function run(): void
{
Rate::factory()->today()->create();
Rate::factory()->last20Days()->count(5)->create();
}
}

عرض الملف

@@ -0,0 +1,168 @@
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>أسعار العملات في اليمن</title>
<style>
/* Mobile-first styles */
body {
font-family: Arial, sans-serif;
line-height: 1.6;
margin: 0;
padding: 15px;
color: #333;
}
.container {
max-width: 400px;
margin: 0 auto;
}
h1 {
color: #2c3e50;
font-size: 24px;
margin-bottom: 10px;
text-align: center;
}
.tabs {
display: flex;
margin-bottom: 10px;
border-bottom: 1px solid #ddd;
}
.tab {
padding: 10px 20px;
cursor: pointer;
background: #f1f1f1;
border: 1px solid #ddd;
border-bottom: none;
border-radius: 5px 5px 0 0;
margin-left: 5px;
font-weight: light;
}
.tab.active {
background: #fff;
border-bottom: 1px solid #fff;
margin-bottom: -1px;
font-weight: bold;
text-decoration: underline;
text-decoration-style: wavy;
text-underline-offset: 5px;
}
.currency-card {
background: #f9f9f9;
border-radius: 8px;
padding: 15px;
margin-bottom: 5px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
display: none;
}
.currency-card.active {
display: block;
}
.currency-info {
margin-bottom: 5px;
display: flex;
justify-content: space-between;
}
.currency-info strong {
font-weight: bold;
}
.date-info {
text-align: center;
margin-top: 15px;
font-style: italic;
color: #666;
}
/* Tablet and larger screens */
@media (min-width: 600px) {
h1 {
font-size: 28px;
}
.currency-card {
padding: 20px;
}
}
</style>
</head>
<body>
<div class="container">
<h1>أسعار العملات في اليمن</h1>
<div class="tabs">
@foreach ($supportedCities as $city)
<div class="tab {{ $loop->first ? 'active' : '' }}" onclick="showTab(event, '{{ $city->id }}')">
<span class="">{{ $city->label }} </span>
</div>
@endforeach
</div>
@foreach ($rates as $cityId => $cityRates)
@php
$city = $supportedCities->firstWhere('id', $cityId);
@endphp
<div id="{{ $cityId }}" class="currency-card {{ $loop->first ? 'active' : '' }}">
@foreach ($cityRates as $rate)
<div style="margin-bottom: {{ $loop->last ? '0' : '10px' }}; border-bottom: {{ $loop->last ? 'none' : '1px dashed #ccc' }}; padding-bottom: 10px;">
<div class="currency-info">
<strong>العملة:</strong>
<span>{{ $rate->currency->name }}</span>
</div>
<div class="currency-info">
<strong>سعر الشراء:</strong>
<span>{{ $rate->buy_price }} ريال يمني</span>
</div>
<div class="currency-info">
<strong>سعر البيع:</strong>
<span>{{ $rate->sell_price }} ريال يمني</span>
</div>
<div class="currency-info">
<strong>التاريخ:</strong>
<span>{{ $rate->date->format('Y-m-d') }}</span>
</div>
<div class="currency-info">
<strong>اليوم:</strong>
<span>{{ $rate->date->locale('ar')->isoFormat('dddd') }}</span>
</div>
<div class="date-info">
آخر تحديث: {{ $rate->updated_at?->diffForHumans() }}
</div>
</div>
@endforeach
</div>
@endforeach
</div>
<script>
function showTab(event, tabId) {
// Hide all cards
document.querySelectorAll('.currency-card').forEach(card => {
card.classList.remove('active');
});
// Show selected
document.getElementById(tabId).classList.add('active');
// Update tabs
document.querySelectorAll('.tab').forEach(tab => {
tab.classList.remove('active');
});
event.currentTarget.classList.add('active');
}
</script>
</body>
</html>

تم حذف اختلاف الملف لأن أحد الأسطر أو أكثر طويلة جداً

عرض الملف

@@ -1,9 +1,7 @@
<?php
use Illuminate\Foundation\Inspiring;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Schedule;
Schedule::command('currency:fetch --today')
->everySixHours() //
->everySixHours()
->appendOutputTo(storage_path('logs/currency-fetch.log'));

عرض الملف

@@ -1,7 +1,6 @@
<?php
use App\Http\Controllers\RateController;
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('welcome');
});
Route::get('/', RateController::class);