HOME


Mini Shell 1.0
Redirecting to https://devs.lapieza.net/iniciar-sesion Redirecting to https://devs.lapieza.net/iniciar-sesion.
DIR: /var/www/devs.lapieza.net/app/Models/
Upload File :
Current File : /var/www/devs.lapieza.net/app/Models/ProductsImport_old.php
<?php

namespace App\Models;

use Auth;
use Carbon\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithValidation;

//class ProductsImport implements ToModel, WithHeadingRow, WithValidation
class ProductsImport implements ToCollection, WithHeadingRow, WithValidation, ToModel {
    private $rows = 0;

    public function collection(Collection $rows) {
        $user = Auth::user();
        $canImport = true;
        $importLimit = 0;

        if ($user->user_type == 'seller' && addon_is_activated('seller_subscription')) {
            $currentProductCount = $user->products()->count();
            $totalAllowed = $user->shop->seller_package->product_upload_limit;
            $importLimit = $totalAllowed - $currentProductCount;

            if ($importLimit <= 0 || $user->shop->package_invalid_at == null || Carbon::now()->diffInDays(Carbon::parse($user->shop->package_invalid_at), false) < 0) {
                $canImport = false;
                flash(translate('Has alcanzado el limite de productos, actualiza tu paquete.'))->warning();
            }
        }

        if ($canImport) {
            $importedCount = 0;


            foreach ($rows as $row) {
                if ($importedCount >= $importLimit) {
                    flash(translate("Se han importado $importedCount has alcanzado tu limite de {$importLimit} productos, actualiza tu paquete"))->warning();
                    break;
                }

                $approved = 1;
                if ($user->user_type == 'seller' && get_setting('product_approve_by_admin') == 1) {
                    $approved = 0;
                }
                $product = Product::create([
                    'name' => $row['name'],
                    'description' => $row['description'],
                    'added_by' => $user->user_type == 'seller' ? 'seller' : 'admin',
                    'user_id' => $user->user_type == 'seller' ? $user->id : User::where('user_type', 'admin')->first()->id,
                    'approved' => $approved,
                    'category_id' => $row['category_id'],
                    'brand_id' => $row['brand_id'],
                    'video_provider' => $row['video_provider'],
                    'video_link' => $row['video_link'],
                    'tags' => $row['tags'],
                    'unit_price' => $row['unit_price'],
                    'unit' => $row['unit'],
                    'meta_title' => $row['name'],
                    'meta_description' => $row['description'],
                    'est_shipping_days' => $row['est_shipping_days'],
                    'colors' => json_encode(array()),
                    'choice_options' => json_encode(array()),
                    'variations' => json_encode(array()),
                    'slug' => preg_replace('/[^A-Za-z0-9\-]/', '', str_replace(' ', '-', strtolower($row['slug']))) . '-' . Str::random(5),
                    'thumbnail_img' => $this->downloadThumbnail($row['thumbnail_img']),
                    'photos' => $this->downloadGalleryImages($row['photos']),
                ]);
                ProductStock::create([
                    'product_id' => $product->id,
                    'qty' => $row['current_stock'],
                    'price' => $row['unit_price'],
                    'sku' => $row['sku'],
                    'variant' => '',
                ]);

                $importedCount++;
            }

            if ($importedCount >= 0) {
                flash(translate('Productos importados exitosamente'))->success();
            }
        }
    }

    public function downloadThumbnail($url) {
        try {
            $upload = new Upload;
            $upload->external_link = $url;
            $upload->type = 'image';
            $upload->save();
            return $upload->id;
        } catch (\Exception $e) {
        }
        return null;
    }

    public function downloadGalleryImages($urls) {
        $data = array();
        foreach (explode(',', str_replace(' ', '', $urls)) as $url) {
            $data[] = $this->downloadThumbnail($url);
        }
        return implode(',', $data);
    }

    public function model(array $row) {
        ++$this->rows;
    }

    public function getRowCount(): int {
        return $this->rows;
    }

    public function rules(): array {
        return [
            // Can also use callback validation rules
            'unit_price' => function ($attribute, $value, $onFailure) {
                if (!is_numeric($value)) {
                    $onFailure('Unit price is not numeric');
                }
            }
        ];
    }
}