Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat - Product option refactoring #1477

Merged
merged 4 commits into from
Jan 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 0 additions & 6 deletions packages/admin/resources/lang/en/productoption.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,6 @@
'handle' => [
'label' => 'Handle',
],
'position' => [
'label' => 'Position',
],
],

'form' => [
Expand All @@ -31,9 +28,6 @@
'handle' => [
'label' => 'Handle',
],
'position' => [
'label' => 'Position',
],
],

];
32 changes: 12 additions & 20 deletions packages/admin/src/Filament/Resources/ProductOptionResource.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@ protected static function getMainFormComponents(): array
static::getNameFormComponent(),
static::getLabelFormComponent(),
static::getHandleFormComponent(),
static::getPositionFormComponent(),
];
}

Expand Down Expand Up @@ -76,29 +75,21 @@ protected static function getHandleFormComponent(): Component
->maxLength(255);
}

protected static function getPositionFormComponent(): Component
{
return Forms\Components\TextInput::make('position')
->label(__('lunarpanel::productoption.form.position.label'))
->numeric()
->minValue(1)
->maxValue(100)
->required();
}

public static function getDefaultTable(Table $table): Table
{
return $table
->columns([
Tables\Columns\TextColumn::make('name.en') // TODO: Need to determine correct way to localise, maybe custom column type?
->label(__('lunarpanel::productoption.table.name.label')),
Tables\Columns\TextColumn::make('label.en') // TODO: Need to determine correct way to localise, maybe custom column type?
Tables\Columns\TextColumn::make('name')
->formatStateUsing(
fn (ProductOption $option) => $option->translate('name'),
)->label(__('lunarpanel::productoption.table.name.label')),
Tables\Columns\TextColumn::make('label')
->formatStateUsing(
fn (ProductOption $option) => $option->translate('label'),
)
->label(__('lunarpanel::productoption.table.label.label')),
Tables\Columns\TextColumn::make('handle')
->label(__('lunarpanel::productoption.table.handle.label')),
Tables\Columns\TextColumn::make('position')
->label(__('lunarpanel::productoption.table.position.label'))
->sortable(),
])
->filters([
//
Expand All @@ -111,9 +102,10 @@ public static function getDefaultTable(Table $table): Table
Tables\Actions\DeleteBulkAction::make(),
]),
])
->searchable()
->defaultSort('position', 'asc')
->reorderable('position');
->modifyQueryUsing(
fn ($query) => $query->shared()
)
->searchable();
}

public static function getRelations(): array
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,17 @@
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Model;
use Lunar\Models\ProductOptionValue;

class ValuesRelationManager extends RelationManager
{
protected static string $relationship = 'values';

protected static ?string $recordTitleAttribute = 'name.en'; // TODO: localise somehow
public function getTableRecordTitle(Model $record): ?string
{
return $record->translate('name');
}

public function form(Form $form): Form
{
Expand All @@ -29,8 +34,10 @@ public function table(Table $table): Table
return $table

->columns([
Tables\Columns\TextColumn::make('name.en'),
Tables\Columns\TextColumn::make('handle'),
Tables\Columns\TextColumn::make('name')
->formatStateUsing(
fn (ProductOptionValue $productOption) => $productOption->translate('name')
),
Tables\Columns\TextColumn::make('position'),
])
->filters([
Expand Down
2 changes: 1 addition & 1 deletion packages/core/database/factories/ProductOptionFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public function definition(): array
'label' => [
'en' => $name,
],
'position' => self::$position++,
'shared' => true,
];
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Lunar\Base\Migration;

class CreateProductProductOptionTable extends Migration
{
public function up()
{
Schema::create($this->prefix.'product_product_option', function (Blueprint $table) {
$table->foreignId('product_id')->constrained($this->prefix.'products');
$table->foreignId('product_option_id')->constrained($this->prefix.'products');
$table->smallInteger('position')->index();
});
}

public function down()
{
Schema::dropIfExists($this->prefix.'product_product_option');
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
<?php

use Illuminate\Support\Facades\Schema;
use Lunar\Base\Migration;
use Lunar\Facades\DB;

class UpdateProductOptionRelations extends Migration
{
public $withinTransaction = true;

public function up()
{
$variantsTable = $this->prefix.'product_variants';
$productsTable = $this->prefix.'products';
$optionsTable = $this->prefix.'product_options';
$optionValueTable = $this->prefix.'product_option_values';
$variantOptionsValueTable = $this->prefix.'product_option_value_product_variant';

DB::table($variantOptionsValueTable)->join(
$variantsTable,
"{$variantOptionsValueTable}.variant_id",
'=',
"{$variantsTable}.id"
)->join(
$optionValueTable,
"{$variantOptionsValueTable}.value_id",
'=',
"{$optionValueTable}.id"
)->join(
$optionsTable,
"{$optionValueTable}.product_option_id",
'=',
"{$optionsTable}.id"
)->join(
$productsTable,
"{$variantsTable}.product_id",
'=',
"{$productsTable}.id"
)->select([
"{$productsTable}.id as product_id",
"{$optionsTable}.id as product_option_id",
"{$optionsTable}.position",
])->groupBy(['product_id', 'product_option_id'])
->orderBy('product_id')
->chunk(2, function ($rows) {
DB::table(
$this->prefix.'product_product_option'
)->insert(
$rows->map(
fn ($row) => (array) $row
)->toArray()
);
});
}

public function down()
{
Schema::dropIfExists($this->prefix.'product_product_option');
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Lunar\Base\Migration;

class RemovePositionFromProductOptionsTable extends Migration
{
public function up()
{
Schema::table($this->prefix.'product_options', function (Blueprint $table) {
$table->dropColumn('position');
});
}

public function down()
{
Schema::table($this->prefix.'product_options', function (Blueprint $table) {
$table->smallInteger('position')->after('label');
});
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Lunar\Base\Migration;

class AddAndSetSharedToProductOptionsTable extends Migration
{
public $withinTransaction = true;

public function up()
{
Schema::table($this->prefix.'product_options', function (Blueprint $table) {
$table->boolean('shared')->after('handle')->default(false)->index();
});

\Lunar\Facades\DB::table($this->prefix.'product_options')->update([
'shared' => true,
]);
}

public function down()
{
Schema::table($this->prefix.'product_options', function (Blueprint $table) {
$table->dropColumn('shared');
});
}
}
10 changes: 10 additions & 0 deletions packages/core/src/Models/Product.php
Original file line number Diff line number Diff line change
Expand Up @@ -213,4 +213,14 @@ public function prices(): HasManyThrough
'priceable_id'
)->wherePriceableType(ProductVariant::class);
}

public function productOptions(): BelongsToMany
{
$prefix = config('lunar.database.table_prefix');

return $this->belongsToMany(
ProductOption::class,
"{$prefix}product_product_option"
)->withPivot(['position'])->orderByPivot('position');
}
}
12 changes: 12 additions & 0 deletions packages/core/src/Models/ProductOption.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Lunar\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Casts\AsCollection;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
Expand Down Expand Up @@ -39,6 +40,7 @@ class ProductOption extends BaseModel implements SpatieHasMedia
protected $casts = [
'name' => AsCollection::class,
'label' => AsCollection::class,
'shared' => 'boolean',
];

/**
Expand Down Expand Up @@ -75,6 +77,16 @@ protected function label(): Attribute
*/
protected $guarded = [];

public function scopeShared(Builder $builder)
{
return $builder->where('shared', '=', true);
}

public function scopeExclusive(Builder $builder)
{
return $builder->where('shared', '=', false);
}

/**
* Get the values.
*
Expand Down
21 changes: 1 addition & 20 deletions tests/core/Unit/Models/ProductOptionTest.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<?php

uses(\Lunar\Tests\Core\TestCase::class);

use Illuminate\Database\QueryException;
use Illuminate\Support\Str;
use Lunar\Models\ProductOption;
Expand All @@ -15,7 +16,6 @@
'id' => $productOption->id,
'name' => json_encode($productOption->name),
'handle' => $productOption->handle,
'position' => $productOption->position,
]);

$this->assertDatabaseCount((new ProductOption)->getTable(), 1);
Expand Down Expand Up @@ -46,25 +46,6 @@
$this->assertDatabaseCount((new ProductOption)->getTable(), 2);
});

test('can update all product option positions', function () {
$productOptions = ProductOption::factory(10)->create()->each(function ($productOption) {
$productOption->update([
'position' => $productOption->id,
]);
});

expect($productOptions->pluck('position')->toArray())->toEqual(range(1, 10));

$position = 10;
foreach ($productOptions as $productOption) {
$productOption->position = $position;
$productOption->save();
$position--;
}

expect($productOptions->pluck('position')->toArray())->toEqual(array_reverse(range(1, 10)));
});

test('can delete product option', function () {
$productOption = ProductOption::factory()->create();
$this->assertDatabaseCount((new ProductOption)->getTable(), 1);
Expand Down
27 changes: 27 additions & 0 deletions tests/core/Unit/Models/ProductTest.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<?php

uses(\Lunar\Tests\Core\TestCase::class);

use Illuminate\Database\Eloquent\Collection as EloquentCollection;
use Lunar\Facades\DB;
use Lunar\Models\Brand;
Expand Down Expand Up @@ -34,6 +35,32 @@
expect($product->attribute_data)->toEqual($attribute_data);
});

test('can fetch product options', function () {
$attribute_data = collect([
'meta_title' => new \Lunar\FieldTypes\Text('I like cake'),
'pack_qty' => new \Lunar\FieldTypes\Number(12345),
'description' => new \Lunar\FieldTypes\TranslatedText(collect([
'en' => new \Lunar\FieldTypes\Text('Blue'),
'fr' => new \Lunar\FieldTypes\Text('Bleu'),
])),
]);

$product = Product::factory()
->for(ProductType::factory())
->create([
'attribute_data' => $attribute_data,
]);

$productOptions = \Lunar\Models\ProductOption::factory(2)->create();

foreach ($productOptions as $index => $productOption) {
$product->productOptions()->attach($productOption, ['position' => $index + 1]);
}

expect($product->refresh()->productOptions)->toHaveCount(2);

})->group('momo');

test('can fetch using status scope', function () {
$attribute_data = collect([
'meta_title' => new \Lunar\FieldTypes\Text('I like cake'),
Expand Down
Loading