Changeset View
Changeset View
Standalone View
Standalone View
src/database/migrations/2023_02_17_100000_tax_rates_table.php
- This file was added.
<?php | |||||
use Illuminate\Support\Facades\Schema; | |||||
use Illuminate\Database\Schema\Blueprint; | |||||
use Illuminate\Database\Migrations\Migration; | |||||
use Illuminate\Support\Facades\DB; | |||||
return new class extends Migration | |||||
{ | |||||
/** | |||||
* Run the migrations. | |||||
* | |||||
* @return void | |||||
*/ | |||||
public function up() | |||||
{ | |||||
Schema::create('tax_rates', function (Blueprint $table) { | |||||
$table->string('id', 36)->primary(); | |||||
$table->string('country', 2); | |||||
$table->timestamp('start')->useCurrent(); | |||||
$table->double('rate', 5, 2); | |||||
$table->unique(['country', 'start']); | |||||
}); | |||||
Schema::table( | |||||
'payments', | |||||
function (Blueprint $table) { | |||||
// FIXME: It could be a foreign key instead, but I don't see a good reason for that | |||||
$table->double('tax_rate', 5, 2)->default(0); | |||||
// FIXME: A better name than base_amount? | |||||
$table->integer('base_amount')->nullable(); // temporarily allow null | |||||
} | |||||
); | |||||
DB::table('payments')->update(['base_amount' => DB::raw("`amount`")]); | |||||
Schema::table( | |||||
'payments', | |||||
function (Blueprint $table) { | |||||
$table->integer('base_amount')->nullable(false)->change(); // remove nullable | |||||
} | |||||
); | |||||
// Migrate old tax rates (and existing payments) | |||||
if (($countries = \env('VAT_COUNTRIES')) && ($rate = \env('VAT_RATE'))) { | |||||
$countries = explode(',', strtoupper(trim($countries))); | |||||
foreach ($countries as $country) { | |||||
\App\TaxRate::create([ | |||||
'start' => new DateTime('2015-01-01 00:00:00'), | |||||
'rate' => $rate, | |||||
'country' => $country, | |||||
]); | |||||
} | |||||
DB::table('payments')->whereIn('wallet_id', function ($query) use ($countries) { | |||||
$query->select('id') | |||||
->from('wallets') | |||||
->whereIn('user_id', function ($query) use ($countries) { | |||||
$query->select('user_id') | |||||
->from('user_settings') | |||||
->where('key', 'country') | |||||
->whereIn('value', $countries); | |||||
}); | |||||
}) | |||||
->update(['tax_rate' => $rate]); | |||||
} | |||||
} | |||||
/** | |||||
* Reverse the migrations. | |||||
* | |||||
* @return void | |||||
*/ | |||||
public function down() | |||||
{ | |||||
Schema::dropIfExists('tax_rates'); | |||||
Schema::table( | |||||
'payments', | |||||
function (Blueprint $table) { | |||||
$table->dropColumn('tax_rate'); | |||||
$table->dropColumn('base_amount'); | |||||
} | |||||
); | |||||
} | |||||
}; |