feat(catalog): track variant replacements
This commit is contained in:
@@ -0,0 +1,86 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
$requiresForeignKeyRecreation = in_array(DB::getDriverName(), ['mysql', 'mariadb'], true);
|
||||
|
||||
Schema::table('variantes', function (Blueprint $table) use ($requiresForeignKeyRecreation): void {
|
||||
if ($requiresForeignKeyRecreation) {
|
||||
$table->dropForeign(['inventory_id']);
|
||||
}
|
||||
|
||||
$table->dropUnique('variantes_inventory_id_unique');
|
||||
$table->index('inventory_id');
|
||||
|
||||
if ($requiresForeignKeyRecreation) {
|
||||
$table->foreign('inventory_id')->references('id')->on('inventories')->restrictOnDelete();
|
||||
}
|
||||
|
||||
$table->foreignId('replaced_by_variant_id')
|
||||
->nullable()
|
||||
->after('inventory_id')
|
||||
->constrained('variantes')
|
||||
->nullOnDelete();
|
||||
$table->timestamp('sales_disabled_at')
|
||||
->nullable()
|
||||
->after('replaced_by_variant_id');
|
||||
$table->index(
|
||||
['sales_disabled_at', 'replaced_by_variant_id'],
|
||||
'variants_sellable_index',
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
$requiresForeignKeyRecreation = in_array(DB::getDriverName(), ['mysql', 'mariadb'], true);
|
||||
|
||||
DB::table('variantes')
|
||||
->orderBy('id')
|
||||
->get()
|
||||
->groupBy('inventory_id')
|
||||
->each(function ($variants): void {
|
||||
$variants->skip(1)->each(function (object $variant): void {
|
||||
$inventory = DB::table('inventories')->where('id', $variant->inventory_id)->first();
|
||||
|
||||
if ($inventory === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$inventoryId = DB::table('inventories')->insertGetId([
|
||||
'sold_units' => $inventory->sold_units,
|
||||
'reserved_stock' => 0,
|
||||
'real_stock' => $inventory->real_stock,
|
||||
]);
|
||||
|
||||
DB::table('variantes')->where('id', $variant->id)->update([
|
||||
'inventory_id' => $inventoryId,
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
Schema::table('variantes', function (Blueprint $table) use ($requiresForeignKeyRecreation): void {
|
||||
$table->dropIndex('variants_sellable_index');
|
||||
$table->dropConstrainedForeignId('replaced_by_variant_id');
|
||||
$table->dropColumn('sales_disabled_at');
|
||||
|
||||
if ($requiresForeignKeyRecreation) {
|
||||
$table->dropForeign(['inventory_id']);
|
||||
}
|
||||
|
||||
$table->dropIndex(['inventory_id']);
|
||||
$table->unique('inventory_id');
|
||||
|
||||
if ($requiresForeignKeyRecreation) {
|
||||
$table->foreign('inventory_id')->references('id')->on('inventories')->restrictOnDelete();
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user