<?php
namespace App\Controller;
use App\Entity\AttributeItems;
use App\Entity\Attributes;
use App\Entity\Products;
use App\Entity\Category;
use App\Entity\MeasurmentUnit;
use App\Entity\SiteProductsMedia;
use App\Entity\MediaObject;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpKernel\Attribute\AsController;
use Symfony\Component\HttpFoundation\JsonResponse;
use App\Repository\ProductsRepository;
use App\Repository\SiteProductsRepository;
use App\Repository\ProductBalanceInStorageRepository;
use App\Repository\MediaObjectsRepository;
use Symfony\Component\HttpFoundation\StreamedResponse;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\IOFactory;
use App\Service\Translit;
use Intervention\Image\ImageManager;
use Symfony\Component\HttpKernel\KernelInterface;
use App\Service\ImageResize;
#[AsController]
class ProductController
{
private $ProductsRepository;
private $entityManager;
private $kernel;
public function __construct(EntityManagerInterface $entityManager, ProductsRepository $ProductsRepository, KernelInterface $kernel )
{
$this->entityManager = $entityManager;
$this->ProductsRepository = $ProductsRepository;
$this->kernel = $kernel;
}
#[Route(
name: 'product_filter',
path: '/api/products/filter',
methods: ['GET'],
)]
public function __invoke(Request $request): Response
{
$_get = $request->query->all();
$query =$_get['search']; // Отримуємо параметр "query" з URL.
$t = $_get['type']; // Отримуємо параметр "query" з URL.
if($t == '1'){
$data = explode(' ', $query );
$products = $this->ProductsRepository->searchByNameSpecefycal($data, $query);
}else{
$products = $this->ProductsRepository->searchByNameOrBarcode($query);
}
if (empty($products)) {
return new JsonResponse([]);
}
return new JsonResponse($products, 200);
}
#[Route(
name: 'set_show_products',
path: '/set-show-products',
)]
public function set_show_products(ProductBalanceInStorageRepository $ProductBalanceInStorageRepository, Request $request): Response
{
die;
$productsBlance = $ProductBalanceInStorageRepository->findAll();
if($productsBlance){
echo count($productsBlance) . "<br>";
}
$sumBalance = [];
foreach($productsBlance as $pb){
$id = $pb->getProduct()->getId();
if(!isset($sumBalance[$id]))
$sumBalance[$id] = ['sum' => 0, 'product' => $pb->getProduct()];
$sumBalance[$id]['sum'] += $pb->getCount();
}
$c = 0;
foreach($sumBalance as $sb){
if($sb['sum'] >= 300){
$c++;
$sb['product']->setShow(true);
}else{
$sb['product']->setShow(false);
}
$this->entityManager->persist( $sb['product'] );
}
$this->entityManager->flush();
echo count($sumBalance) . "<br>";
echo $c;
die;
}
#[Route(
name: 'set_site_product_img',
path: '/set-site-product-img',
)]
public function set_site_product_img(SiteProductsRepository $SiteProductsRepository, Request $request): Response
{
$productsSite = $SiteProductsRepository->findAll();
foreach ( $productsSite as $ps){
$isMedia = false;
// echo '<pre>';
// echo count($ps->getSiteProductsMedia());
//print_r($ps->getSiteProductsMedia());
// die;
if(count($ps->getSiteProductsMedia()) == 0){
if($ps->getProducts() != null){
foreach($ps->getProducts() as $p){
if( !$isMedia AND $p->getMedia() != null AND count($p->getMedia()) > 0){
foreach($p->getMedia() as $m){
$spm = new SiteProductsMedia();
$spm->setSiteProduct($ps);
$spm->setMedia($m);
$spm->setMain($m->isMain());
$this->entityManager->persist($spm);
// $this->entityManager->flush();
if($p->getMainMedia() != null){
if($p->getMainMedia()->getId() == $m->getId()){
$ps->setMainSiteProductMedia($spm);
$this->entityManager->persist($spm);
}
}
$isMedia = true;
// $this->entityManager->flush();
}
}
}
}
// var_dump($ps->getMainSiteProductMedia());
}
}
$this->entityManager->flush();
die;
}
#[Route(
name: 'get_product',
path: '/get-product',
)]
public function get_product(SiteProductsRepository $SiteProductsRepository, Request $request): Response
{
die;
$find = $this->entityManager->getRepository(Products::class)->findAll();
foreach($find as $p){
if(empty($p->getPriceIncome()))
continue;
$arr = [
'gurt_1' => round($p->getPriceIncome() + ($p->getPriceIncome() * 0.05), 2),
'gurt_2' => round($p->getPriceIncome() + ($p->getPriceIncome() * 0.07), 2),
'gurt_3' => round($p->getPriceIncome() + ($p->getPriceIncome() * 0.09), 2),
'gurt_4' => round($p->getPriceIncome() + ($p->getPriceIncome() * 0.1), 2),
];
echo $p->getPriceIncome(). '---'.json_encode($arr).'<br>';
$p->setPriceCategory($arr);
$this->entityManager->persist($p);
}
$this->entityManager->flush();
// echo count( $find);
die;
}
#[Route(
name: 'export_form',
path: '/api/export_csv',
methods: ['GET']
)]
public function export_csv( EntityManagerInterface $entityManager, Request $request): StreamedResponse
{
$products = $entityManager->getRepository(Products::class)->findAll();
$attributes = $entityManager->getRepository(Attributes::class)->findAll();
// echo count($products); die;
if( $products ){
$header = [
'name',
'site_name',
'article',
'code',
'all_category',
'last_category',
// 'attributes',
];
$arrAttr = [];
foreach($attributes as $attr){
$arrAttr[$attr->getId()] = '';
$header[] = $attr->getName();
}
$response = new StreamedResponse(function () use ($arrAttr, $header, $products) {
$csv = fopen('php://output', 'w+');
fprintf($csv, "\xEF\xBB\xBF");
fputcsv($csv, $header, ';');
foreach($products as $prod){
if(count($prod->getCategory()) > 0 OR count($prod->getAttributeItems()) > 0){
$prodAttr = $arrAttr;
$arr = [];
$arr[] = $prod->getName();
$siteName = '';
if($prod->getSiteProduct())
$siteName = $prod->getSiteProduct()->getName();
$arr[] = $siteName;
$arr[] = $prod->getArticle();
$arr[] = $prod->getCode1c();
$category = '';
foreach($prod->getCategory() as $cat){
// file_put_contents('Category.log', strpos($category, $cat->getName()) . "\n", FILE_APPEND);
// if($cat->isMain()){
// }
if($cat->getParent()){
if($cat->getParent()->getParent()){
$p = $cat->getParent()->getParent();
// if($p->isMain()){
if(!str_contains($category, $p->getName()."|"))
$category .= $p->getName()."|";
// }
}
// if($cat->getParent()->isMain()){
if(!str_contains($category, $cat->getParent()->getName()."|"))
$category .= $cat->getParent()->getName()."|";
// }
}
if(!str_contains($category, $cat->getName()."|"))
$category .= $cat->getName()."|";
}
$arr[] = $category;
$lastCategory = '';
foreach($prod->getCategory() as $cat){
// if(count($prod->getCategory()) > 0)
$lastCategory .= $cat->getName(). " | ";
}
$arr[] = $lastCategory;
if(count($prod->getAttributeItems()) > 0){
foreach($prod->getAttributeItems() as $attrItem){
if($attrItem->getAttribute() !=null)
$prodAttr[$attrItem->getAttribute()->getId()] = $attrItem->getName();
}
foreach($prodAttr as $v){
$arr[] = $v;
}
}
fputcsv($csv, $arr, ';');
}
}
fclose($csv);
});
$response->headers->set('Content-Type', 'application/csv');
$response->headers->set('Content-Encoding', 'UTF-8');
$response->headers->set('Content-Disposition', 'attachment; filename="file.csv"');
$response->headers->set('Cache-Control', 'no-store');
}
return $response;
}
#[Route(
name: 'setMainImage',
path: '/set-main-mage',
)]
public function setMainImage(Request $request): Response
{
// die;
$find = $this->entityManager->getRepository(Products::class)->findAll();
$i = 0;
foreach($find as $product){
if(count($product->getMedia()) > 0 && $product->getMainMedia() == null){
$i++;
// $product->setMainMedia($product->getMedia()[0]);
// $this->entityManager->persist($product);
}
if($product->getSiteProduct() != null){
// $product->setName($product->getSiteProduct()->getName());
// $this->entityManager->persist($product);
}
}
$this->entityManager->flush();
echo $i;
// echo count( $find);
die;
}
#[Route(
name: 'getPrices',
path: '/get-prices',
)]
public function getPrices( EntityManagerInterface $entityManager, Request $request): Response
{
// die;
$category = [];
// echo '<pre>';
// print_r($request->query->all());
// die;
$category = $request->query->get('category');
$products = $entityManager->getRepository(Products::class)->findBy(['show' => true]);
// if(!empty( $category_id)){
// $query = $entityManager->getRepository(Category::class)->find($category_id);
// $categories[] = $query;
// }else{
$categories = $entityManager->getRepository(Category::class)->findBy([], ['sort' => 'ASC']);
// }
$catArr = [];
foreach($categories as $cat){
if( !empty($category) ){
if(in_array( $cat->getId(), $category) ){
$catArr[$cat->getId()] = [
'name' => $cat->getName(),
'products' => []
];
}
}else{
$catArr[$cat->getId()] = [
'name' => $cat->getName(),
'products' => []
];
}
}
foreach($products as $prod){
foreach($prod->getCategory() as $prodCat){
if(isset($catArr[$prodCat->getId()]))
$catArr[$prodCat->getId()]['products'][] = $prod;
}
}
$spreadsheet = new Spreadsheet();
// Get active sheet - it is also possible to retrieve a specific sheet
$sheet = $spreadsheet->getActiveSheet();
// Set cell name and merge cells
// $sheet->setCellValue('A1', 'Крамар ціни');
$sheet->getRowDimension(1)->setRowHeight(90);
$sheet->getColumnDimension('A')->setWidth(50);
$sheet->getColumnDimension('B')->setWidth(10);
$sheet->getColumnDimension('C')->setWidth(30);
$sheet->getColumnDimension('D')->setWidth(50);
$sheet->getColumnDimension('E')->setWidth(60);
$sheet->getColumnDimension('G')->setWidth(60);
// Set cell alignment and font weight
$styleArray = [
'alignment' => [
'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
],
'font' => [
'bold' => true,
],
];
$sheet->getStyle('B1')->applyFromArray($styleArray)->getAlignment()->setWrapText(true);
$sheet->getStyle('C1')->applyFromArray($styleArray)->getAlignment()->setWrapText(true);
$sheet->getStyle('A:A')->applyFromArray($styleArray)->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
$sheet->mergeCells('A1:B1');
// Add image to worksheet
$imgPath = 'logo.png';
$drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
$drawing->setPath($imgPath);
$drawing->setCoordinates('A1'); // Set coordinates
$drawing->setWidth(200); // Set width
$drawing->setHeight(100); // Set height
$drawing->setWorksheet($sheet);
$sheet->setCellValue('C1', 'https://felso.com.ua');
// $sheet->setCellValue('C1', '');
$sheet->mergeCells('A2:G2');
$sheet->mergeCells('A3:G3');
$sheet->setCellValue('A2', 'Адреса компанії: м.Львів, вул.Манастирського 2 ');
$sheet->setCellValue('A3', 'Номер телефону +38 (068) 844-11-44 +38 (073) 844-11-44');
// $sheet->setCellValue('D3', 'При замовленні від 0 до 100 кг. однієї позиції')->getStyle('D3')->applyFromArray($styleArray)->getAlignment()->setWrapText(true);
// $sheet->setCellValue('E3', 'При замовленні від 100 до 500 кг. однієї позиції')->getStyle('E3')->applyFromArray($styleArray)->getAlignment()->setWrapText(true);
// $sheet->setCellValue('F3', 'При замовленні від 500 до 1 тонни однієї позиції')->getStyle('F3')->applyFromArray($styleArray)->getAlignment()->setWrapText(true);
// $sheet->setCellValue('G3', 'При замовленні від 1 тонни')->getStyle('G3')->applyFromArray($styleArray)->getAlignment()->setWrapText(true);
// Set column names
$columnNames = [
'Назва',
'Артикул',
'',
'характеристики',
'комплектація',
'Ціна',
'Посилання',
// 'Гурт 2',
// 'Гурт 1',
// 'VIP',
];
$columnLetter = 'A';
foreach ($columnNames as $columnName) {
// Allow to access AA column if needed and more
$sheet->setCellValue($columnLetter.'4', $columnName)->getStyle($columnLetter.'4')->applyFromArray($styleArray);
$columnLetter++;
}
$row = 5;
foreach($catArr as $key => $category){
$sheet->setCellValue("A{$row}", $category['name'])->mergeCells("A{$row}:G{$row}");
$sheet->getStyle("A{$row}")->applyFromArray($styleArray);
$row++;
if(count($category['products']) > 0)
foreach ($category['products'] as $product) {
/** Характеристики */
$params = '';
foreach($product->getAttributeItems() as $attributeItems){
$params .= $attributeItems->getAttribute()->getName() . ' - ' . $attributeItems->getName() . "\n";
}
/** Комплектація */
$productComplact = '';
foreach($product->getProductInfos() as $productInfos){
$productComplact .= $productInfos->getName() . "\n";
}
$columnLetter++;
$sheet->getRowDimension($row)->setRowHeight(100*0.75); // переведення 100px в пункти
$sheet->setCellValue('A'.$row, $product->getName());
$sheet->getStyle('A' . $row)->getAlignment()->setWrapText(true);
$sheet->setCellValue('B'.$row, $product->getArticle());
$sheet->getStyle('B' . $row)->getAlignment()->setWrapText(true); // Вмикає перенесення тексту
// $sheet->setCellValue('C'.$row, $product->getPrice());
/** Характеристики */
$sheet->setCellValue('D'.$row, strip_tags($params) );
$sheet->getStyle('D' . $row)->getAlignment()->setWrapText(true); // Вмикає перенесення тексту
$sheet->setCellValue('E'.$row, $productComplact);
$sheet->getStyle('E' . $row)->getAlignment()->setWrapText(true); // Вмикає перенесення тексту
$sheet->setCellValue('F'.$row, $product->getPrice());
$sheet->setCellValue('G'.$row, 'https://felso.com.ua/product/' . $product->getId());
// $sheet->getStyle('C' . $row)->getAlignment()->setWrapText(true); // Вмикає перенесення тексту
// $sheet->getRowDimension($row)->setRowHeight(-1); // Автоматична висота рядка
if($product->getMainMedia() != null){
// Отримуємо рік і місяць із дати завантаження
$uploadDate = $product->getMainMedia()->getUploadTimestamp();
$year = $uploadDate->format('Y');
$month = $uploadDate->format('m');
// Формуємо повний шлях до зображення
$imgPath = $_SERVER["DOCUMENT_ROOT"] . '/media/' . $year . '/' . $month . '/90_px_' . $product->getMainMedia()->filePath;
if(file_exists($imgPath)){
// $ = 'logo.png';
$drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
$drawing->setPath($imgPath);
$drawing->setCoordinates('C'.$row); // Set coordinates
$drawing->setWidth(150); // Set width
$drawing->setHeight(100); // Set height
$drawing->setWorksheet($sheet);
}
}
$row++;
}
}
$writer = new Xlsx($spreadsheet);
$fileName = 'products_' . date('YmdHis') . '.xlsx';
$writer->save($fileName);
// Вивантаження файлу
// Set the content-type:
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Length: ' . filesize($fileName));
readfile($fileName); // send file
unlink($fileName); // delete file
return new Response();
}
#[Route(
name: 'addAttrCategory',
path: '/add-attr-category',
)]
public function addAttrCategory( EntityManagerInterface $entityManager ){
$products = $entityManager->getRepository(Products::class)->findBy(['show' => true]);
foreach( $products as $product ){
if(count($product->getAttributeItems()) > 0 ){
foreach($product->getAttributeItems() as $attrItem){
$attibute = $attrItem->getAttribute();
foreach($product->getCategory() as $category){
$attrItem->addCategory($category);
$attibute->addCategory($category);
$entityManager->persist($attrItem);
$entityManager->persist($attibute);
}
}
}
}
$entityManager->flush();
echo 1111;
die;
}
#[Route(
name: 'getDublicate',
path: '/get-dublicate',
)]
public function getDublicate( EntityManagerInterface $entityManager, Request $request): Response
{
set_time_limit(0);
$duplicates = $entityManager->createQueryBuilder()
->select('p.article')
->from(Products::class, 'p')
->where('p.deleted = FALSE')
->groupBy('p.article')
->having('COUNT(p.article) > 1')
->getQuery()
->getResult();
$i = 0;
foreach ($duplicates as $duplicate) {
// echo $duplicate['article'] . "<br>";
$products = $entityManager->getRepository(Products::class)
->findBy(['article' => $duplicate['article'], 'deleted' => false]);
// Keep the first product and remove the rest
$deleted = true;
$isDeleted = false;
foreach ($products as $product) {
echo $product->getArticle();
if(count($product->getOrderProducts()) > 0){
$deleted = false;
echo ' - - false';
}elseif(count( $product->getCategory()) > 0 OR count( $product->getAttributeItems()) > 0){
$deleted = false;
echo '- false';
}else{
$deleted = true;
echo ' - true';
}
if($deleted AND !$isDeleted){
$i++;
$isDeleted = true;
$product->setDeleted(true);
$product->setDescription('delete dublicate product ' . date('Y-m-d H:i:s'));
$entityManager->persist( $product );
}
echo '<br>';
}
if($i === 200){
$entityManager->flush();
$i=0;
}
}
$entityManager->flush();
die;
}
#[Route(
name: 'importProductFromExcel',
path: '/product/import-from-excel',
)]
function importProductFromExcel(EntityManagerInterface $entityManager, Translit $translit){
echo '<pre>';
$inputFileName = 'products.xlsx';
$spreadsheet = IOFactory::load($inputFileName);
$sheet = $spreadsheet->getActiveSheet();
$i = 0;
$category = [];
$attributes = [];
$products = [];
// $url = $sheet->getDrawingCollection();
// $sheet->getCell('C1')->getValue()
// echo '<pre>';
// print_r($url);
// var_dump($url); die;
// die;
foreach ($sheet->getRowIterator() as $row) {
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(FALSE);
$data = [];
foreach ($cellIterator as $cell) {
// echo '<pre>';
// print_r($cell->getWorksheet()->getDrawingCollection());
$value = $cell->getValue();
// $drawing = $cell->getWorksheet()->getDrawingCollection();
// $hyperlink = $cell->getHyperlink();
// if ($hyperlink) {
// $value = $hyperlink->getUrl();
// }
$data[] = $value;
}
// Assuming your Excel file has columns: id, name, price
// echo '<pre>';
if($i==0){
foreach($data as $k => $d){
if($k >= 5 AND !empty($d)){
$n = str_replace(':', '', $d);
$attributes[$k] = [
'name' => trim($n),
'slug' => $translit->convert(trim($n)),
'items' => []
];
}
}
// print_r($data);
$i++;
continue;
}
foreach($data as $k => $d){
if($k >= 5 AND !empty($d)){
$attributes[$k]['items'][$translit->convert(trim($d))] = trim($d);
}
}
if(!empty($data[3]))
$category[ $translit->convert(trim( $data[4] )) ] = trim( $data[4] );
$products[$i]['data'] = $data;
$i++;
}
// print_r($category);
// print_r($attributes);
// die;
// die;
$findCategory = $entityManager->getRepository(Category::class)->findAll();
$findAttributes = $entityManager->getRepository(Attributes::class)->findAll();
foreach($category as $slug => $c){
$find = false;
foreach($findCategory as $fCat){
if($fCat->getName() == $c){
$find = true;
}
}
if(!$find){
$entityCat = new Category();
$entityCat->setName($c);
$entityCat->setSlug($slug);
$entityCat->setMain(true);
$entityCat->setType('category');
$entityManager->persist( $entityCat );
}
}
// echo '<pre>';
// print_r($attributes); die;
foreach($attributes as $name => $attrs){
$attr = false;
$entityAttr = '';
foreach($findAttributes as $fAttr){
if($fAttr->getName() == $attrs['name']){
$entityAttr = $fAttr;
$attr = true;
foreach($attrs['items'] as $i => $a){
foreach($fAttr->getAttributeItems() as $f_a_i){
if($f_a_i->getName() == $a){
unset($attrs['items'][$i]);
}
}
}
}
}
if(!$attr){
$entityAttr = new Attributes();
$entityAttr->setName($attrs['name']);
$entityAttr->setSlug($attrs['slug']);
$entityManager->persist( $entityAttr );
}
if(count($attrs['items']) > 0){
foreach($attrs['items'] as $i => $a){
$entityAttrItem = new AttributeItems();
$entityAttrItem->setName($a);
$entityAttrItem->setSlug($i);
$entityAttrItem->setAttribute($entityAttr);
$entityManager->persist( $entityAttrItem );
}
}
}
// die;
$entityManager->flush();
// die;
$findCategory = $entityManager->getRepository(Category::class)->findAll();
$findAttributes = $entityManager->getRepository(Attributes::class)->findAll();
$findAttributesItems = $entityManager->getRepository(AttributeItems::class)->findAll();
$findProducts = $entityManager->getRepository(Products::class)->findAll();
$measurmentUnit = $entityManager->getRepository(MeasurmentUnit::class)->findOneBy(['name' => 'Штука']);
// print_r($products); die;
foreach($products as $product){
$search = false;
$findProduct = '';
foreach($findProducts as $f_p){
if($f_p->getArticle() == $product['data'][1]){
$search = true;
$findProduct = $f_p;
}
}
$price = floatval(trim(str_replace('грн', '' , $product['data'][2])));
if(!$search and !empty($product['data'][0])){
$newProduct = new Products();
$newProduct->setName($product['data'][0]);
$newProduct->setArticle($product['data'][1]);
$newProduct->setPrice($price);
$newProduct->setShow(true);
$findProduct->setBalance(1);
// $newProduct->setPackingType($product['data'][7] . ' | ' . $product['data'][7]);
$newProduct->getMeasurementUnit($measurmentUnit);
foreach($product['data'] as $k => $d){
if($k >= 5 AND !empty($d)){
foreach($findAttributesItems as $ati){
if($ati->getName() == trim($d)){
$newProduct->addAttributeItem($ati);
}
}
}
if($k == 4 AND !empty($d)){
foreach ($findCategory as $f_c){
if($f_c->getName() == trim($d)){
$newProduct->addCategory($f_c);
}
}
}
}
$entityManager->persist( $newProduct );
}else{
echo $findProduct->getName() . "<br>";
$findProduct->setPrice($price);
$findProduct->setShow(true);
$findProduct->setBalance(1);
foreach($product['data'] as $k => $d){
$searvhAttr = false;
if($k >= 5 AND !empty($d)){
foreach( $findProduct->getAttributeItems() as $productAttrItem){
if( $productAttrItem->getName() == $d){
$searvhAttr = true;
}
}
if(!$searvhAttr){
foreach($findAttributesItems as $ati){
if($ati->getName() == trim($d)){
$findProduct->addAttributeItem($ati);
}
}
$entityManager->persist( $findProduct );
}
}
}
// if(empty( $findProduct->getCategory() )){
foreach($product['data'] as $k => $d){
if($k == 4 AND !empty($d)){
foreach ($findCategory as $f_c){
if($f_c->getName() == trim($d)){
echo $f_c->getName(). "<br>";
$findProduct->addCategory($f_c);
}
}
}
}
// }
$entityManager->persist( $findProduct );
}
}
$entityManager->flush();
// $findProducts = $entityManager->getRepository(Products::class)->findAll();
// foreach ($sheet->getDrawingCollection() as $in => $drawing) {
// // print_r($drawing->getCoordinates());
// $c = str_replace('E', '', $drawing->getCoordinates() );
// // print_r($sheet->getCell( "B$c" )->getValue());
// // echo "<br>";
// foreach($findProducts as $f_p){
// if($f_p->getArticle() == $sheet->getCell( "B$c" )->getValue()){
// $zipReader = fopen($drawing->getPath(),'r');
// $imageContents = '';
// while (!feof($zipReader)) {
// $imageContents .= fread($zipReader,1024);
// }
// fclose($zipReader);
// $extension = $drawing->getExtension();
// $imageBase64 = base64_encode($imageContents);
// $url = 'https://api-felso-brand.inneti.net/api/media_objects?product=' . $f_p->getId();
// $imageFile = new \CURLFile($imageBase64, 'image/' . $extension, 'image.' . $extension);
// echo $url; echo '<br>';
// // Set up the cURL request
// // Ініціалізуємо cURL-сесію
// $ch = curl_init();
// // Встановлюємо параметри запиту
// curl_setopt($ch, CURLOPT_URL, $url);
// curl_setopt($ch, CURLOPT_POST, 1);
// curl_setopt($ch, CURLOPT_POSTFIELDS, ['image' => $imageFile]);
// // curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// // Execute the cURL request
// // Виконуємо запит
// $response = curl_exec($ch);
// // $json = json_decode($response);
// // Перевіряємо наявність помилок
// if (curl_errno($ch)) {
// echo 'Error:' . curl_error($ch);
// }
// // Закриваємо cURL-сесію
// curl_close($ch);
// die;
// }
// }
// // $zipReader = fopen($drawing->getPath(),'r');
// // $imageContents = '';
// // while (!feof($zipReader)) {
// // $imageContents .= fread($zipReader,1024);
// // }
// // fclose($zipReader);
// // $extension = $drawing->getExtension();
// // $imageBase64 = base64_encode($imageContents);
// // $url = 'https://api-felso-brand.inneti.net/api/media_objects?product=' . $entity->getId();
// // $imageFile = new CURLFile($imageBase64, 'image/' . $extension, 'image.' . $extension);
// // // Set up the cURL request
// // $ch = curl_init();
// // curl_setopt($ch, CURLOPT_URL, $url);
// // curl_setopt($ch, CURLOPT_POST, 1);
// // curl_setopt($ch, CURLOPT_POSTFIELDS, ['image' => $imageFile]);
// // curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// // // Execute the cURL request
// // $response = curl_exec($ch);
// // // Close cURL resource
// // curl_close($ch);
// // }
// // $myFileName = '00_Image_'.++$i.'.'.$extension;
// // file_put_contents($myFileName,$imageContents);
// }
// $entityManager->flush();
echo 111;
die;
// return $this->redirectToRoute('app_homepage');
}
public function imgCurl($entity, $imgUrl, $type='img'){
// continue;
// $img = file_get_contents($imgUrl);
$url = 'https://api-felso.inneti.net/api/media_objects';
if( $type == 'img' )
$url .= '?product=' . $entity->getId();
// echo " $url<br><br>";
// Файл, який ви хочете відправити
$file_path = $imgUrl;
// Ініціалізуємо cURL-сесію
$ch = curl_init();
// Встановлюємо параметри запиту
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, [
'file' => new \CURLFile($file_path)
]);
echo '----';
// Виконуємо запит
$response = curl_exec($ch);
echo '|||';
// $json = json_decode($response);
// Перевіряємо наявність помилок
if (curl_errno($ch)) {
echo '2Error:' . curl_error($ch); die;
}
// Закриваємо cURL-сесію
curl_close($ch);
return $response;
}
public function newImg($findProducts, $pathProductsDir, $pathNew, ){
echo $findProducts->getName() . "+++<br>";
$uploadTimestamp = new \DateTime();
$mediaObject = new MediaObject();
// $mediaObject->file = $uploadedFile;
$mediaObject->uploadTimestamp = $uploadTimestamp;
$mediaObject->filePath = $findProducts->getId().$pathProductsDir;
$mediaObject->setName('product_img');
$mediaObject->setProduct($findProducts);
$this->entityManager->persist( $mediaObject );
$this->entityManager->flush();
$year = date('Y');
$month = date('m');
$documentRoot = $this->kernel->getProjectDir() . '/public/media';
$path = $documentRoot . "/$year/$month/";
$sizes = [90, 230, 700, 1200];
$manager = new ImageManager(
new \Intervention\Image\Drivers\Gd\Driver()
);
foreach($sizes as $s){
$image = $manager->read($pathNew);
$image->scale(width: $s);
$newName = "{$s}_px_" . $findProducts->getId().$pathProductsDir;
$image->save($path . $newName );
$newMedia = new MediaObject();
$newMedia->filePath = $newName;
$newMedia->setName("resize-$s");
$newMedia->setSize($s);
$newMedia->setResizeImgParent($mediaObject);
$this->entityManager->persist($newMedia);
$this->entityManager->flush();
}
$findProducts = null;
return $mediaObject;
}
#[Route(
name: 'importProductImg',
path: '/product/import-img',
)]
function importProductImg(EntityManagerInterface $entityManager, Translit $translit, MediaObjectsRepository $mediaObjectsRepository, ?\DateTimeInterface $uploadTimestamp){
echo '<pre>';
$path = 'products_img';
$nextPaths = scandir($path);
print_r($nextPaths);
foreach($nextPaths as $nextPath){
if($nextPath == '.' OR $nextPath == '..')
continue;
$pathCat = "$path/$nextPath";
$pathCatDirs = scandir($pathCat);
foreach($pathCatDirs as $pathCatDir){
if($pathCatDir == '.' OR $pathCatDir == '..')
continue;
// if($pathCatDir == 'ID1250')
// die;
// print_r($pathCatDir); die;
file_put_contents('import-img.log', $pathCatDir . "\n", FILE_APPEND);
$pathProducts = "$pathCat/$pathCatDir";
$pathProductsDirs = scandir($pathProducts);
echo "<b>$pathCatDir</b><br>";
$findProducts = $entityManager->getRepository(Products::class)->findOneBy(['article' => $pathCatDir]);
if($findProducts ){
echo "<b>" . $findProducts->getName() . "</b><br>";
foreach($findProducts->getMedia() as $m){
echo $m->getId() . "<br>";
$findProducts->removeMedium($m);
}
$mainMedia = $findProducts->getMainMedia();
if($mainMedia){
echo "main - " . $mainMedia->getId() . "<br>";
$mainMedia->removeMainProduct($findProducts);
$entityManager->persist( $findProducts );
}
$MainMediaHover = $findProducts->getMainMediaHover();
if($MainMediaHover){
echo "hover - main - " . $MainMediaHover->getId() . "<br>";
$MainMediaHover->removeProductsHover($findProducts);
$entityManager->persist( $MainMediaHover );
}
$entityManager->persist( $findProducts );
$entityManager->flush();
}else{
continue;
}
// echo $findProducts->getName();
echo "<br>";
foreach($pathProductsDirs as $pathProductsDir){
if($pathProductsDir == '.' OR $pathProductsDir == '..')
continue;
$pathImg = $this->kernel->getProjectDir() . "/public/$pathProducts/$pathProductsDir";
$pathNew = $this->kernel->getProjectDir() . "/public/media/" . date('Y') . "/" . date('m') . "/".$findProducts->getId()."$pathProductsDir";
echo $pathImg . "---<br>";
echo $pathNew . "---<br>";
if($pathProductsDir == '1_0.png'){
if(copy($pathImg, $pathNew)){
$mediaObject = $this->newImg($findProducts, $pathProductsDir, $pathNew);
$findProducts->setMainMedia($mediaObject);
$entityManager->persist( $findProducts );
}
}elseif($pathProductsDir == '1_1.png'){
if(copy($pathImg, $pathNew)){
$mediaObject = $this->newImg($findProducts, $pathProductsDir, $pathNew);
$findProducts->setMainMediaHover($mediaObject);
$entityManager->persist( $findProducts );
}
}else{
if(copy($pathImg, $pathNew)){
$mediaObject = $this->newImg($findProducts, $pathProductsDir, $pathNew);
// $findProducts->setMainMediaHover($mediaObject);
$entityManager->persist( $findProducts );
}
}
}
$entityManager->flush();
$entityManager->clear();
$findProducts = '';
// die;
}
}
// print_r($nextPaths);
die;
}
#[Route('/products/export-xml', name: 'export_xml')]
public function exportXml(EntityManagerInterface $entityManager, Request $request): Response
{
$_get = $request->query->all();
$categoryId = isset($_get['category']) && !empty($_get['category']) ? $_get['category'] : null;
// echo '<pre>';
// var_dump($categoryId);
// die;
$categories = $entityManager->getRepository(Category::class)->findAll();
$products = $entityManager->getRepository(Products::class)->findAll();
$xml = new \SimpleXMLElement('<yml_catalog/>');
$xml->addAttribute('date', date('Y-m-d H:i'));
$shop = $xml->addChild('shop');
$shop->addChild('name', '2PR');
$shop->addChild('company', '2PR');
$shop->addChild('url', 'https://felso.inneti.net/');
$shop->addChild('phone', '068-844-11-44');
$shop->addChild('platform', 'Store');
$shop->addChild('version', '2.1.0.1');
// $currencies = $shop->addChild('currencies');
// $currencies->addChild('currency')->addAttribute('id', 'UAH')->addAttribute('rate', '1');
// Додаємо категорії
$categoriesXml = $shop->addChild('categories');
foreach ($categories as $category) {
if($categoryId !== null AND !in_array($category->getId(), $categoryId)){
continue;
}
$categoryXml = $categoriesXml->addChild('category', $category->getName());
$categoryXml->addAttribute('id', $category->getId());
if ($category->getParent()) {
$categoryXml->addAttribute('parentId', $category->getParent()->getId());
}
}
// Додаємо продукти
$offers = $shop->addChild('offers');
foreach ($products as $product) {
if($categoryId !== null){
$search = false;
foreach($product->getCategory() as $cat){
if( in_array($cat->getId() , $categoryId) )
$search = true;
}
if(!$search)
continue;
}
$cat = '';
if($product->getCategory() != null AND count($product->getCategory()) > 0)
$cat = $product->getCategory()[0]->getId();
$img = '';
if($product->getMainMedia() != null){
// Отримуємо рік і місяць із дати завантаження
$uploadDate = $product->getMainMedia()->getUploadTimestamp();
$year = $uploadDate->format('Y');
$month = $uploadDate->format('m');
// Формуємо повний шлях до зображення
$img = 'https://api-felso-brand.inneti.net/media/' . $year . '/' . $month . '/' . $product->getMainMedia()->filePath;
}
// $img =
$offer = $offers->addChild('offer');
$offer->addAttribute('id', $product->getId());
$offer->addAttribute('available', $product->isShow() ? 'true' : 'false');
$offer->addChild('url', 'https://felso.inneti.net/product/' . $product->getId());
$offer->addChild('price', $product->getPrice());
$offer->addChild('currencyId', 'UAH');
$offer->addChild('categoryId', $cat );
$offer->addChild('picture', $img);
// $offer->addChild('vendor', $product->getVendor());
$offer->addChild('vendorCode', $product->getArticle());
$offer->addChild('name', $product->getName());
$offer->addChild('description', htmlspecialchars($product->getDescription()));
}
// Конвертація у XML
$response = new Response($xml->asXML());
$response->headers->set('Content-Type', 'application/xml');
return $response;
}
}