<?php
namespace App\Controller\EasyAdmin\Ozon;
use App\Entity\OzonProduct;
use App\Service\AdminUser\Type\AdminUserRoleType;
use Doctrine\ORM\QueryBuilder;
use EasyCorp\Bundle\EasyAdminBundle\Collection\FieldCollection;
use EasyCorp\Bundle\EasyAdminBundle\Collection\FilterCollection;
use EasyCorp\Bundle\EasyAdminBundle\Config\Action;
use EasyCorp\Bundle\EasyAdminBundle\Config\Actions;
use EasyCorp\Bundle\EasyAdminBundle\Config\Crud;
use EasyCorp\Bundle\EasyAdminBundle\Config\Filters;
use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController;
use EasyCorp\Bundle\EasyAdminBundle\Dto\EntityDto;
use EasyCorp\Bundle\EasyAdminBundle\Dto\SearchDto;
use EasyCorp\Bundle\EasyAdminBundle\Field\ArrayField;
use EasyCorp\Bundle\EasyAdminBundle\Field\AssociationField;
use EasyCorp\Bundle\EasyAdminBundle\Field\BooleanField;
use EasyCorp\Bundle\EasyAdminBundle\Field\DateTimeField;
use EasyCorp\Bundle\EasyAdminBundle\Field\Field;
use EasyCorp\Bundle\EasyAdminBundle\Field\IntegerField;
use EasyCorp\Bundle\EasyAdminBundle\Field\NumberField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextareaField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextField;
use EasyCorp\Bundle\EasyAdminBundle\Filter\EntityFilter;
use EasyCorp\Bundle\EasyAdminBundle\Orm\EntityRepository;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
class OzonProductCrudController extends AbstractCrudController
{
private UrlGeneratorInterface $urlGenerator;
public function __construct(UrlGeneratorInterface $urlGenerator)
{
$this->urlGenerator = $urlGenerator;
}
public static function getEntityFqcn(): string
{
return OzonProduct::class;
}
/**
* @param SearchDto $searchDto
* @param EntityDto $entityDto
* @param FieldCollection $fields
* @param FilterCollection $filters
* @return QueryBuilder
*/
public function createIndexQueryBuilder(SearchDto $searchDto, EntityDto $entityDto, FieldCollection $fields, FilterCollection $filters): QueryBuilder
{
$response = $this->get(EntityRepository::class)->createQueryBuilder($searchDto, $entityDto, $fields, $filters);
if(!in_array(AdminUserRoleType::ROLE_ADMIN, $this->getUser()->getRoles())) {
$response
->andWhere('entity.client IN (:clients)')
->setParameter('clients', $this->getUser()->getOzonClients());
}
return $response->orderBy('entity.id', 'DESC');
}
public function configureCrud(Crud $crud): Crud
{
return $crud
->setEntityLabelInSingular('Продаваемые товары')
->setEntityLabelInPlural('Продаваемые товары')
->setDefaultSort(['id' => 'DESC'])
->setPaginatorUseOutputWalkers(true)
->setPaginatorFetchJoinCollection(true)
->setSearchFields(['id', 'clientId', 'taskId', 'srcProductId', 'offerId', 'url', 'sku', 'srcCategoryId', 'categoryId', 'name', 'description', 'barcode', 'vendor', 'vendorCode', 'images', 'attributes', 'depth', 'width', 'height', 'dimensionUnit', 'weight', 'weightUnit', 'price', 'oldPrice', 'recommendedPrice', 'retailPrice', 'premiumPrice', 'buyboxPrice', 'minOzonPrice', 'marketingPrice', 'vat', 'stock', 'stockComing', 'stockPresent', 'stockReserved', 'state', 'validationErrors', 'note', 'stockWriteError', 'priceWriteError', 'infoPrice', 'infoStockFbo', 'infoStockFbs'])
->setPaginatorPageSize(50);
}
public function configureActions(Actions $actions): Actions
{
$ozonProductReprice = Action::new('ozonProductReprice', 'Обновить цену')
->linkToUrl(function (OzonProduct $ozonProduct): string {
return $this->urlGenerator->generate(
'ozon_product_reprice',
['id' => $ozonProduct->getId()],
UrlGeneratorInterface::ABSOLUTE_PATH
);
});
$exportHidePriceProducts = Action::new('exportHidePriceProducts', 'Выгрузить товары с откл. ценой')
->linkToUrl(function (): string {
return $this->urlGenerator->generate(
'ozon_hide_price_products_export',
[],
UrlGeneratorInterface::ABSOLUTE_PATH
);
})
->createAsGlobalAction();
return $actions
->add(Crud::PAGE_INDEX, $ozonProductReprice)
->add(Crud::PAGE_INDEX, $exportHidePriceProducts)
->add(Crud::PAGE_INDEX, Action::DETAIL)
->add(Crud::PAGE_EDIT, Action::INDEX)
->disable('new', 'delete');
}
public function configureFilters(Filters $filters): Filters
{
return $filters
->add(EntityFilter::new('client'))
->add('offerId');
}
public function configureFields(string $pageName): iterable
{
$client = AssociationField::new('client', 'Площадка');
$taskId = IntegerField::new('taskId', 'ID заявки');
$srcProductId = IntegerField::new('srcProductId', 'ID товара');
$offerId = TextField::new('offerId', 'Артикул');
$sku = IntegerField::new('sku', 'SKU товара на Озон');
$srcCategoryId = IntegerField::new('srcCategoryId', 'ID категории на Озон');
$name = TextField::new('name', 'Название');
$description = TextareaField::new('description', 'Описание');
$barcode = TextField::new('barcode', 'Штрихкод');
$vendor = TextField::new('vendor', 'Производитель');
$vendorCode = TextField::new('vendorCode', 'Код производителя');
$url = TextField::new('url', 'Url/Адрес страницы товара');
$imagesText = TextareaField::new('imagesText', 'Изображения');
$attributesText = TextareaField::new('attributesText', 'Характеристики');
$depth = IntegerField::new('depth', 'Глубина');
$width = IntegerField::new('width', 'Ширина');
$height = IntegerField::new('height', 'Высота');
$dimensionUnit = TextField::new('dimensionUnit', 'Единицы размеров');
$weight = IntegerField::new('weight', 'Масса');
$weightUnit = TextField::new('weightUnit', 'Единицы массы');
$isPrepayment = BooleanField::new('isPrepayment', 'Продажа по предоплате');
$price = IntegerField::new('price', 'Цена товара с учетом скидок');
$oldPrice = IntegerField::new('oldPrice', 'Цена до учета скидок');
$recommendedPrice = IntegerField::new('recommendedPrice', 'Рекомендованная цена');
$retailPrice = IntegerField::new('retailPrice', 'Цена товара для поставщиков');
$premiumPrice = IntegerField::new('premiumPrice', 'Цена для клиентов Premium');
$buyboxPrice = IntegerField::new('buyboxPrice', 'Цена главного предложения на Ozon');
$minOzonPrice = IntegerField::new('minOzonPrice', 'Минимальная цена на аналогичный товар');
$marketingPrice = IntegerField::new('marketingPrice', 'Цена на товар с учетом всех акций');
$vat = NumberField::new('vat', 'Ставка НДС для товара');
$stock = IntegerField::new('stock', 'Остатки');
$stockComing = IntegerField::new('stockComing', 'Товары, которые ожидают поставки');
$stockPresent = IntegerField::new('stockPresent', 'Товары в наличии');
$stockReserved = IntegerField::new('stockReserved', 'Товары в резерве');
$hideStock = Field::new('hideStock', 'Скрыть остатки');
$isVisible = BooleanField::new('isVisible', 'Активно');
$visibilityHasPrice = BooleanField::new('visibilityHasPrice', 'Товар активирован');
$visibilityHasStock = BooleanField::new('visibilityHasStock', 'У товара есть цена');
$visibilityActiveProduct = BooleanField::new('visibilityActiveProduct', 'Товар доступен на складе');
$state = TextField::new('state', 'Статус добавления товара в систему');
$validationErrorsText = TextareaField::new('validationErrorsText', 'Информация об ошибках валидации');
$note = TextareaField::new('note', 'Заметка');
$createdAt = DateTimeField::new('createdAt', 'Товар создан');
$hasBaseChanges = BooleanField::new('hasBaseChanges', 'Изменена базовая информация');
$hasInfoChanges = BooleanField::new('hasInfoChanges', 'Изменена редактируемая информация');
$hasActiveChanges = BooleanField::new('hasActiveChanges', 'Изменена активность товара');
$hasPrepaymentChanges = BooleanField::new('hasPrepaymentChanges', 'Изменена продажа по предоплате');
$hasStockChanges = BooleanField::new('hasStockChanges', 'Есть неотправленные изменения остатков');
$hasPriceChanges = BooleanField::new('hasPriceChanges', 'Есть неотправленные изменения цен');
$isDeleted = BooleanField::new('isDeleted', 'Товар удален');
$productSources = ArrayField::new('productSources', 'Информация о SKU Ozon');
$id = IntegerField::new('id', 'ID');
$noMinStock = Field::new('noMinStock', 'Остатки от 1')->setTemplatePath('admin/default/field_toggle_inverse.html.twig');
$stateText = TextField::new('stateText', 'Статус добавления товара в систему');
$stockWriteTm = DateTimeField::new('stockWriteTm', 'Время последней отправки остатков на Озон');
$stockWriteUpdated = BooleanField::new('stockWriteUpdated', 'Остатки изменены');
$stockWriteError = TextareaField::new('stockWriteError', 'Ошибки изменения остатков на Озон');
$priceWriteTm = DateTimeField::new('priceWriteTm', 'Время последней отправки цен на Озон');
$priceWriteUpdated = BooleanField::new('priceWriteUpdated', 'Цены изменены');
$priceWriteError = TextareaField::new('priceWriteError', 'Ошибки изменения цен на Озон');
$isKgt = BooleanField::new('isKgt', 'КГТ');
$priceRub = Field::new('priceRub', 'Цена');
$stateStr = TextareaField::new('stateStr', 'Статус');
$infoReadTm = DateTimeField::new('infoReadTm', 'Обновлено');
$reserves = ArrayField::new('reserves', 'Резервы');
$hidePrice = BooleanField::new('hidePrice', 'Не передавать цену');
switch ($pageName) {
case Crud::PAGE_INDEX:
$fields = [
$client, $srcProductId, $offerId, $name, $isKgt, $priceRub, $hidePrice, $stateStr,
$stock, $hideStock, $noMinStock, $infoReadTm, $isVisible, $stockWriteUpdated, $priceWriteUpdated
];
break;
case Crud::PAGE_DETAIL:
$fields = [
$id, $client, $taskId, $srcProductId, $offerId, $sku, $srcCategoryId, $name, $description, $barcode,
$vendor, $vendorCode, $url, $imagesText, $attributesText, $depth, $width, $height, $dimensionUnit,
$weight, $weightUnit, $isPrepayment, $price, $oldPrice, $recommendedPrice, $retailPrice, $premiumPrice,
$buyboxPrice, $minOzonPrice, $marketingPrice, $vat, $stock, $stockComing, $stockPresent, $stockReserved,
$hideStock, $noMinStock, $isVisible, $visibilityHasPrice, $visibilityHasStock, $visibilityActiveProduct,
$stateText, $validationErrorsText, $note, $createdAt, $hasBaseChanges, $hasInfoChanges, $hasActiveChanges,
$hasPrepaymentChanges, $hasStockChanges, $stockWriteTm, $stockWriteUpdated, $stockWriteError, $hasPriceChanges,
$priceWriteTm, $priceWriteUpdated, $priceWriteError, $isDeleted, $productSources, $reserves
];
break;
case Crud::PAGE_NEW:
case Crud::PAGE_EDIT:
$fields = [
$client, $taskId, $srcProductId, $offerId, $sku, $srcCategoryId, $name, $description, $barcode,
$vendor, $vendorCode, $url, $imagesText, $attributesText, $depth, $width, $height, $dimensionUnit,
$weight, $weightUnit, $isPrepayment, $price, $oldPrice, $recommendedPrice, $retailPrice, $premiumPrice,
$buyboxPrice, $minOzonPrice, $marketingPrice, $vat, $stock, $stockComing, $stockPresent, $stockReserved,
$hideStock, $isVisible, $visibilityHasPrice, $visibilityHasStock, $visibilityActiveProduct, $state,
$validationErrorsText, $note, $createdAt, $hasBaseChanges, $hasInfoChanges, $hasActiveChanges,
$hasPrepaymentChanges, $hasStockChanges, $hasPriceChanges, $isDeleted, $productSources
];
break;
default:
$fields = [];
}
return $fields;
}
}