2026-09-22 14:55:18 +03:00
|
|
|
<?php
|
|
|
|
|
|
|
|
|
|
namespace Modules\Core\Catalog\Services;
|
|
|
|
|
|
|
|
|
|
use Lunar\Models\ProductVariant;
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Generates a SKU for every ProductVariant missing one — extracted out of
|
|
|
|
|
* Command\BackfillMissingSkusCommand (which becomes a thin CLI wrapper
|
|
|
|
|
* around this, keeping --dry-run/progress-bar concerns out of the
|
2026-09-24 22:50:41 +03:00
|
|
|
* reusable logic) so MigrateImport\Shopify\Services\ShopifyExportImporter can
|
|
|
|
|
* also call it directly, once every product job in its import batch has
|
|
|
|
|
* finished (see that class's own import()), with no CLI concerns at all.
|
2026-09-22 14:55:18 +03:00
|
|
|
*
|
|
|
|
|
* Format is "SKU-P{product_id}-V{variant_id}": deterministic and
|
|
|
|
|
* guaranteed unique without a uniqueness check, since product_id/
|
|
|
|
|
* variant_id already are. Only variants with a null `sku` are touched —
|
|
|
|
|
* not an importer bug when one shows up after a Shopify import, the
|
|
|
|
|
* source CSV rows genuinely had no `Variant SKU` value (see
|
2026-09-24 22:50:41 +03:00
|
|
|
* MigrateImport\Shopify\Services\ShopifyExportImporter).
|
2026-09-22 14:55:18 +03:00
|
|
|
*/
|
|
|
|
|
class SkuBackfillService
|
|
|
|
|
{
|
|
|
|
|
/**
|
|
|
|
|
* @param ?callable(ProductVariant, string): void $onEach invoked
|
|
|
|
|
* once per variant with the sku about to be written (or, when
|
|
|
|
|
* $dryRun is true, that WOULD be written) — the command's own
|
|
|
|
|
* --dry-run listing and progress bar hook in here without this
|
|
|
|
|
* service knowing anything about console output.
|
|
|
|
|
* @return int the number of variants processed
|
|
|
|
|
*/
|
|
|
|
|
public function backfill(bool $dryRun = false, ?callable $onEach = null): int
|
|
|
|
|
{
|
|
|
|
|
$query = ProductVariant::query()->whereNull('sku');
|
|
|
|
|
$total = $query->count();
|
|
|
|
|
|
|
|
|
|
if ($total === 0) {
|
|
|
|
|
return 0;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
$query->chunkById(500, function ($variants) use ($dryRun, $onEach) {
|
|
|
|
|
foreach ($variants as $variant) {
|
|
|
|
|
$sku = "SKU-P{$variant->product_id}-V{$variant->id}";
|
|
|
|
|
|
|
|
|
|
if (! $dryRun) {
|
|
|
|
|
$variant->update(['sku' => $sku]);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if ($onEach !== null) {
|
|
|
|
|
$onEach($variant, $sku);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return $total;
|
|
|
|
|
}
|
|
|
|
|
}
|