<?php
namespace App\Controller;
use App\Entity\Attribute;
use App\Entity\Cart;
use App\Entity\Category;
use App\Entity\Color;
use App\Entity\Grade;
use App\Entity\Manufacturer;
use App\Entity\Model;
use App\Entity\Option;
use App\Entity\Order;
use App\Entity\Product;
use App\Entity\Shop;
use App\Entity\Stock;
use App\Form\SavType;
use App\Form\SearchType;
use App\Form\StockType;
use App\Repository\CategoryRepository;
use App\Repository\ManufacturerRepository;
use App\Repository\OptionRepository;
use App\Repository\StockRepository;
use App\Service\HistoryService;
use App\Service\ShopService;
use App\Service\UserService;
use DateTime;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Translation\TranslatableMessage;
use Symfony\Contracts\Translation\TranslatorInterface;
/**
* @Route("/{_locale<%app.supported_locales%>}/stock")
*/
class StockController extends AbstractController
{
private $shop_config;
private $shop_grades;
private $shop_selling_grades;
private $attributes = array(
'0'=>'size',
'1'=>'storage',
'2'=> 'memory',
'3'=> 'screen_size',
'4'=> 'screen_resolution',
'5'=> 'connectivity',
'6'=> 'connectic',
'7'=> 'width',
'8'=> 'height',
'9'=> 'depth',
'10'=> 'weight',
'11'=> 'ID_recognition',
'12'=> 'battery',
'13'=> 'front_camera',
'14'=> 'rear_camera',
'15'=> 'external_storage',
'16'=> 'SIM',
'17'=> 'OS',
'18'=>'usage',
'19'=> 'format',
'20'=> 'screen type',
'21'=> 'touch',
'22'=> 'webcam',
'23'=> 'audio',
'24'=> 'ratio',
'25'=> 'connectic 2',
'26'=> 'network card',
'27'=> 'graphic card',
'28'=> 'support',
'29'=> 'keyboard',
'30'=> 'numeric pad',
'31'=> 'processor',
'32'=> 'speed',
'33'=> 'generation',
'34'=> 'size',
'35'=> 'norme support',
);
private $cachedPrices=array();
private $capacities=[ //percents on price
32=>0,
64=>25,
128=>20,
256=>15,
512=>12.5,
1000=>12.5
];
/**
* @Route("/", name="app_stock_index", methods={"GET"})
*/
public function index(Request $request, StockRepository $stockRepository, CategoryRepository $categoryRepository, ManufacturerRepository $manufacturerRepository, UserService $userService, RequestStack $requestStack, ShopService $shopService, ParameterBagInterface $params, TranslatorInterface $translator): Response
{
$session = $request->getSession();
$locale = $request->getLocale();
// echo $locale;
$template_sub_file = '_list';
$request = $requestStack->getCurrentRequest();
$user = $this->getUser();
if(!$user->getShop()) {
$userService->setDefaultShop($user);
}
if($shop = $user->getShop()) {
$vat = $shopService->getSetting($shop, 'vat');
if($shopService->getSetting($shop, 'view-as-card')) {
$template_sub_file='_cards';
}
/*
$settings=$shop->getSettings();
foreach($settings as $shop_setting) {
$setting=$shop_setting->getSetting();
if($setting->getMachineName()=='view-as-card' && $shop_setting->getValue()==1) {
$template_sub_file='_cards';
}
//echo $shop_setting->getValue();
}
//temp
if($shop->getId()==9) {
$template_sub_file = '_cards';
}
*/
/*if($shop->getCountry()=='es') {
$vat=21;
}*/
}
$cats = $stockRepository->findCategoriesByShop($shop);
foreach($cats as $k=>$st) {
if(preg_match('/pack/i',$st->getModel()->getCategory()->getName())) {
$st->getModel()->getCategory()->setName("Pack/Deal");
}
//echo $st->getModel()->getCategory()->getName();
//echo $cat->getId();
}
if($shopService->getSetting($shop, 'view-as-card')) {
$categories=array();
foreach($cats as $stock) {
$label=new TranslatableMessage($stock->getModel()->getCategory()->getName());
$categories[$stock->getModel()->getCategory()->getId()]= $label;
}
//$categories = array_merge(array_flip(array('MOBILE', 'TABLET', 'LAPTOP','DESKTOP','SCREEN','PACK','ROUTER','TV')), $categories);
$order=array('1', '2', '3','6','7','12','19','17','13');
uksort($categories, function($key1, $key2) use ($order) {
return (array_search($key1, $order) > array_search($key2, $order));
});
}
$stocks = $stockRepository->findByShop($shop, $request);
foreach($stocks as $s) {
$request->getSession()->remove('stock_'.$s->getId());
}
$list=$this->list($stocks, $manufacturerRepository);
$currentCategory=null;
if($category = $request->query->get('category')) {
$currentCategory=$categoryRepository->find($category);
}
return $this->render('stock/index.html.twig', [
'template_sub_file'=>$template_sub_file,
'stocks' => $list['stocks'],
'manufacturers' => $list['manufacturers'],
'models' => $list['models'],
'colors' => $list['colors'],
'grades' => $list['grades'],
'categories' => isset($categories)?$categories:$list['categories'],
'currentCategory' => $currentCategory,
//'title'=>$translator->trans(ucfirst(strtolower($currentCategory->getName()))),
'shops' => $list['shops'],
'cats'=>$cats,
'vat'=>$vat,
'config'=>$shop?$shop->getConfig():null
]);
}
/**
* @Route("/{id}/card", name="app_stock_card", methods={"POST"})
*/
public function card(Stock $stock, Request $request, ): Response
{
return $this->render('stock/_card.html.twig', [
'stock'=>$stock,
'ajax'=>true
]);
}
public function list($stocks, ManufacturerRepository $manufacturerRepository):array {
$manufacturers = array();
$models = array();
$colors = array();
$grades = array();
$categories = array();
$shops = array();
foreach ($stocks as $stock) {
//$product = $stock->getProduct();
if (!isset($colors[$stock->getColor()->getId()])) {
$colors[$stock->getColor()->getId()] = $stock->getColor()->getName();
}
if (!isset($manufacturers[$stock->getModel()->getManufacturer()->getId()])) {
$manufacturerId=$stock->getModel()->getManufacturer()->getId();
$manufacturerName=$stock->getModel()->getManufacturer()->getName();
if($manufacturerName=="GENERIC") {
$t=explode(' ',$stock->getModel()->getName());
$manufacturerName=$t[0];
if($manufacturer=$manufacturerRepository->findOneBy(['name'=>$t[0]])) {
$manufacturerId=$manufacturer->getId();
}
}
$manufacturers[$manufacturerId] = $manufacturerName;
}
if (!isset($models[$stock->getModel()->getId()])) {
$models[$stock->getModel()->getId()] = $stock->getModel()->getName();
}
if (!isset($grades[$stock->getGrade()])) {
$grades[$stock->getGrade()] = $stock->getGrade();
}
if (!isset($categories[$stock->getModel()->getCategory()->getId()])) {
$categories[$stock->getModel()->getCategory()->getId()] = $stock->getModel()->getCategory()->getName();
}
if (!isset($shops[$stock->getShop()->getId()])) {
$shops[$stock->getShop()->getId()] = $stock->getShop()->getName();
}
if($stock->getQty()==-1) {
//$stock->setQty(1);
}
}
asort($manufacturers);
asort($models);
asort($colors);
asort($grades);
asort($categories);
asort($shops);
return array(
'stocks' => $stocks,
'manufacturers' => $manufacturers,
'models' => $models,
'colors' => $colors,
'grades' => $grades,
'categories' => $categories,
'shops' => $shops
);
}
/**
* @Route("/admin", name="app_stock_admin_list", methods={"GET"})
*/
public function admin(StockRepository $stockRepository, Request $request): Response
{
$stocks=$stockRepository->findBy(['shop'=>$request->query->get('shop')]);
return $this->render('stock/index_admin.html.twig', [
'stocks' => $stocks,
]);
}
/**
* @Route("/{id}", name="app_stock_show", methods={"GET"})
*/
public function show(Stock $stock): Response
{
return $this->render('stock/show.html.twig', [
'stock' => $stock,
]);
}
/**
* @Route("/{id}/edit", name="app_stock_edit", methods={"GET","POST"})
*/
public function edit(Stock $stock, EntityManagerInterface $entityManager, Request $request,): Response
{
$form = $this->createForm(StockType::class, $stock);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager->flush();
}
return $this->renderForm('stock/edit.html.twig', [
'stock' => $stock,
'form' => $form,
]);
}
/**
* @Route("/option", name="app_stock_option_price", methods={"POST","GET"})
*/
public function optionalPrice(Request $request): Response
{
$em = $this->getDoctrine()->getManager();
$price=0;
if($stock=$em->getRepository(Stock::class)->find($request->request->get('stock'))) {
$price=$stock->getPrice();
if($option=$em->getRepository(Option::class)->find($request->request->get('option'))) {
//if($stock->getModel()->getCategory()->hasOption($option)) {
if(str_contains($option->getPrice(), '%')) {
//percent
$price=$stock->getPrice()+(((int)$option->getPrice()*$stock->getPrice())/100);
//}
}
else {
$price=$stock->getPrice()+$option->getPrice();
}
}
}
return new JsonResponse(array(
'price'=>$price
));
}
public function import($em, $bak2_api_url, HistoryService $historyService, $shopId=null)
{
$lastUpdate=new DateTime('now');
$this->em = $em;
if($shopId) {
$shops = [$em->getRepository(Shop::class)->find($shopId)];
} else {
$shops = $em->getRepository(Shop::class)->findBy(['active'=>1]);
}
$destock=$this->getCurrentDestock();
$em->getRepository(Product::class)->reset();
foreach ($shops as $shop) {
//$em->getRepository(Stock::class)->reset($shop);
}
foreach ($shops as $shop) {
$this->cachedPrices=array();
/*if($shop->getId()==9) { // AFPA pas de mà j
continue;
}*/
$shopHasOption=false;
$shopHasCategory=false;
echo "######## ".$shop->getWttName() . " #############\n";
//$em->getRepository(Stock::class)->reset($shop);
$stockData = null;
$this->shop_config = null;
$this->shop_grades = null;
$this->shop_selling_grades = null;
$options=$shop->getOptions();
if(count($options)>0) {
$shopHasOption=true;
}
$shopCat=$shop->getCategories();
$shopCategories=[];
if(count($shopCat)>0) {
$shopHasCategory=true;
foreach($shopCat as $k=>$cat) {
$shopCategories[$cat->getWttId()]=$cat->getWttId();
}
}
echo "######## has options: ".$shopHasOption . " #############\n";
echo "######## has categories: ".$shopHasCategory . " ##".implode(',',$shopCategories)."###########\n";
$configContent = file_get_contents($bak2_api_url . "/tempStock.php?action=config&channel=" . $shop->getWttName());
$configData = json_decode($configContent);
$this->shop_config = reset($configData);
$vboxIds = $this->shop_config->vbox;
$shop->setConfig($configData);
$em->persist($shop);
$em->flush();
$allGrades = $em->getRepository(Grade::class)->findAll();
if (isset($this->shop_config->grades)) {
foreach ($this->shop_config->grades as $from => $to) {
//echo $from . " / " . $to . "\n";
$this->shop_grades[$from] = $this->em->getRepository(Grade::class)->findOneByName($to);
}
} else {
$allGrades = $em->getRepository(Grade::class)->findAll();
foreach ($allGrades as $grade) {
$this->shop_grades[$grade->getName()] = $grade;
}
}
if (isset($this->shop_config->quality)) {
foreach ($this->shop_config->quality as $quality) {
$this->shop_selling_grades[$quality->outGrade] = $quality->quality;
}
} else {
if (isset($this->shop_config->grades)) {
foreach ($this->shop_config->grades as $from => $to) {
//echo $from . " / " . $to . "\n";
$this->shop_selling_grades[$from] = $to;
}
} else {
foreach ($allGrades as $grade) {
$this->shop_selling_grades[$grade->getName()] = $grade->getName();
}
}
}
// var_dump($this->shop_selling_grades);
if(count($this->shop_selling_grades)==1) {
$outGrade = array_key_first($this->shop_selling_grades);
}
$importUrl = $bak2_api_url . "/tempStock.php?action=getProductByTempVbox&vboxes=" . $vboxIds . "&sku_marketplace=".($shop->getId()==5?'b2c':'b2b')."&marketplaceId=" . $shop->getWttId();
echo $importUrl."\n";
$importUrl=preg_replace('/ /','',$importUrl);
$stockContent = file_get_contents($importUrl);
$stockData = json_decode($stockContent);
$disableModels=array();
$existingStock=$em->getRepository(Stock::class)->findBy(array('shop'=>$shop->getId()));
foreach($existingStock as $stock) {
$disableModels[$stock->getModel()->getWttId()]=$stock->getModel();
}
foreach ($stockData as $k => $stockProduct) {
if(!is_object($stockProduct)) {
continue;
}
if (!isset($stockProduct->colorId) || $stockProduct->colorId == 0) {
$stockProduct->colorId = 99;
$stockProduct->color = "UNKNOWN";
}
if (!isset($outGrade) && !isset($this->shop_selling_grades[$stockProduct->outGrade]) && $stockProduct->outGrade!='unknown') {
//var_dump($this->shop_selling_grades);
//echo " ----->" . $stockProduct->outGrade . " (" . $stockProduct->outGradeId . ") not allowed \n";
unset($stockData[$k]);
}
}
foreach ($stockData as $stockProduct) {
if(!is_object($stockProduct)) {
continue;
}
if($shopHasCategory) {
if(!in_array($stockProduct->categoryId, $shopCategories)) {
continue;
}
}
echo "----" . $stockProduct->model . "-(".$stockProduct->modelId.")---\n";
unset($disableModels[$stockProduct->modelId]);
if (!$stockProduct->modelId) {
echo "No modelId : ".$stockProduct->model." / ".$stockProduct->manufacturer." / ".$stockProduct->color." / ".$stockProduct->outGrade."\n";
//var_dump($stockProduct);
continue;
}
if (!$stockProduct->sku) {
if($this->shop_config->sourceable==1) {
$stockProduct->sku="W-".$stockProduct->modelId."-".$stockProduct->colorId."-".$stockProduct->outGradeId;
//$skucontent = file_get_contents($bak2_api_url . "/sku.php?sku=".$sku."&modelId=".$stockProduct->modelId."&outGradeId=".$stockProduct->outGradeId."&colorId=".$stockProduct->colorId."&channel=b2b");
}
else {
echo "No sku : ".$stockProduct->model." / ".$stockProduct->manufacturer." / ".$stockProduct->color." / ".$stockProduct->outGrade."\n";
continue;
}
}
if ($stockProduct->colorId == 0) {
$stockProduct->colorId = 99;
$stockProduct->color = "UNKNOWN";
}
if(!isset($destock[$stockProduct->sku])) {
$destock[$stockProduct->sku]=0;
}
$stockProduct->nb=$stockProduct->nb-$destock[$stockProduct->sku];
if(!isset($outGrade)) {
if (!$grade = $em->getRepository(Grade::class)->findOneBy(array('wttId' => $stockProduct->outGradeId))) {
$grade = new Grade();
$grade->setName($stockProduct->outGrade);
$grade->setWttId($stockProduct->outGradeId);
$em->persist($grade);
$em->flush();
}
}
else {
$grade = $em->getRepository(Grade::class)->findOneBy(array('name' => $outGrade));
}
//echo "Original grade:" . $grade->getName() . "\n";
// var_dump($this->shop_grades);
if(!isset($this->shop_grades[$grade->getName()])) {
echo "Unknown grade: ".$grade->getName()."\n";
continue;
//var_dump($this->shop_grades);
}
else {
$shopGrade = $this->shop_grades[$grade->getName()];
}
//echo "Shop grade: " . $shopGrade->getName() . "\n";
//echo "Selling grade: " . $this->shop_selling_grades[$shopGrade->getName()] . "\n";
//echo $stockProduct->modelId . "\n";
//echo $stockProduct->colorId . "\n";
if (!$color = $em->getRepository(Color::class)->findOneBy(array('wttId' => $stockProduct->colorId))) {
$color = new Color();
$color->setName($stockProduct->color);
$color->setWttId($stockProduct->colorId);
$em->persist($color);
$em->flush();
}
//echo $color->getName() . "\n";
if (!$category = $em->getRepository(Category::class)->findOneBy(array('wttId' => $stockProduct->categoryId))) {
$category = new Category();
$category->setName($stockProduct->categoryName);
$category->setWttId($stockProduct->categoryId);
$category->setType('Model');
$em->persist($category);
$em->flush();
}
if (!$stockProduct->manufacturer) {
$stockProduct->manufacturer = "UNKNOWN";
}
if(!$manufacturer = $em->getRepository(Manufacturer::class)->findOneBy(array('name' => $stockProduct->manufacturer))) {
$manufacturer = new Manufacturer();
$manufacturer->setName($stockProduct->manufacturer);
//$manufacturer->setWttId($stockProduct->manufacturerId);
$em->persist($manufacturer);
$em->flush();
}
if (!$model = $em->getRepository(Model::class)->findOneBy(array('wttId' => $stockProduct->modelId))) {
// var_dump($stockProduct);
$model = new Model();
$model->setName($stockProduct->model);
$model->setWttId($stockProduct->modelId);
$model->setManufacturer($manufacturer);
$model->setCategory($category);
$em->persist($model);
$em->flush();
}
if (isset($stockProduct->attr_id) && isset($stockProduct->attr_val)) {
$tId=explode('|',$stockProduct->attr_id);
$tVal=explode('|',$stockProduct->attr_val);
$tName=explode('|',$stockProduct->attr_name);
foreach($tId as $k=>$v) {
$attributeId=(int)$tId[$k];
//$attributeName=$tName[$k];
$attributeValue=$tVal[$k];
if(($model->getCategory()->getId()==1 || $model->getCategory()->getId()==2) && $attributeId==1 && $capacities=explode('/', $attributeValue)) {
$attributePrice=0;
foreach($capacities as $k2=>$capacity) {
$capacity=(int)$capacity;
if($capacity<4) {
$capacity=1000*$capacity;
}
if($k2==0) {
$attributePrice=0;
}
$capacityName=$capacity<1000?($capacity." GB"):(($capacity/1000)." TB");
if($k2>0) {
$attributePrice=$attributePrice+$this->capacities[$capacity];
}
echo "k2 ".$k2." - attributePrice: ".$attributePrice."\n";
if (!$attribute = $em->getRepository(Attribute::class)->findOneBy(array('model' => $model->getId(),'wttId'=>$attributeId,'name'=>$this->attributes[$attributeId],'value'=>$capacityName))) {
$attribute=new Attribute();
$attribute->setModel($model);
$attribute->setName($this->attributes[$attributeId]);
$attribute->setWttId($attributeId);
$attribute->setValue($capacityName);
//$attribute->setPrice($attributePrice);
$em->persist($attribute);
}
$attribute->setPrice($attributePrice);
$em->persist($attribute);
}
//die();
}
else {
if($attributeValue!='' && $attributeId>0) {
if (!$attribute = $em->getRepository(Attribute::class)->findOneBy(array('model' => $model->getId(),'wttId'=>$attributeId))) {
$attribute=new Attribute();
$attribute->setModel($model);
//$attribute->setName($this->attributes[$attributeId]);
$attribute->setWttId($attributeId);
//$attribute->setValue($attributeValue);
$em->persist($attribute);
}
$attribute->setName($this->attributes[$attributeId]);
$attribute->setValue($attributeValue);
$em->persist($attribute);
}
}
}
}
if(isset($stockProduct->pict) ) {
echo $stockProduct->pict."\n";
if(!$model->getImage() || str_contains($model->getImage(), 'http')) {
echo "update pict\n";
$model->setImage("http://pict.bak2group.com/models/".$stockProduct->pict);
$em->persist($model);
$em->flush();
}
}
/*
$model->setCategory($category);
$em->persist($model);
$em->flush();
*/
//echo $model->getName() . "\n";
$productGrade = $grade->getName();
//echo $category->getName()."\n";
if (!$product = $em->getRepository(Product::class)->findOneBy(array('model' => $model, 'color' => $color, 'grade' => $grade, 'sku' => $stockProduct->sku))) {
$product = new Product();
$product->setColor($color);
$product->setModel($model);
$product->setGrade($grade);
$product->setSku($stockProduct->sku);
$product->setQty($stockProduct->nb);
$product->setName($manufacturer->getName() . " " . $model->getName() . " " . $color->getName() . " " . $grade->getName());
$product->setPrice($stockProduct->$productGrade);
$product->setChannel($shop->getChannel());
$em->persist($product);
$em->flush();
}
$product->setChannel($shop->getChannel());
//$product->setCategory($category);
if($product->getQty()<=0) {
$product->setQty($stockProduct->nb);
$product->setPrice($stockProduct->$productGrade);
//$product->setName($manufacturer->getName()." ".$model->getName()." ".$color->getName()." ".$grade->getName());
$em->persist($product);
$em->flush();
echo "updating ".$product->getName()."\n";
}
if($product->getSku()=='n.a.') {
$product->setSku($stockProduct->sku);
$em->persist($product);
$em->flush();
}
// echo $product->getName() . "\n";
if(!isset($this->shop_selling_grades[$grade->getName()])) {
continue;
}
if (!$stock = $em->getRepository(Stock::class)->findOneBy(array('shop' => $shop, 'model' => $model, 'color' => $color, 'grade' => $this->shop_selling_grades[$grade->getName()]))) {
$stock = new Stock();
//echo "sku:" . $stockProduct->sku . "\n";
$stock->setModel($model);
$stock->setGrade($this->shop_selling_grades[$grade->getName()]);
$stock->setColor($color);
$stock->setShop($shop);
$stock->setQty(0);
$stock->setSourceGrade($stockProduct->outGrade);
$em->persist($stock);
echo "-------------> create model: " . $stockProduct->modelId . " -- Shop grade: " . $shopGrade->getName() . " -- Color: " . $stockProduct->colorId . " (" . $stockProduct->outGrade . ")\n";
}
$overridenPrice=$stock->getPrice();
echo "shop:".$shop->getName()." model: " . $stockProduct->modelId . " -- Shop grade: " . $shopGrade->getName() . " -- Color: " . $stockProduct->colorId . " (" . $stockProduct->outGrade . ")\n";
echo "qty 1: ".$stock->getQty()."\n";
if($stock->getQty()<2) {
$stock->setQty(0);
}
$shopGrade = $shopGrade->getName();
$price = $this->getPriceNet($stockProduct->$shopGrade / 100, $shop, $bak2_api_url);
$sourceGrade=explode(',',$stock->getSourceGrade());
$sourceGrade[]=$stockProduct->outGrade;
$stock->setSourceGrade(implode(',',array_filter(array_unique($sourceGrade))));
$stock->setPrice((int)$price * 100);
$stock->setEnabled(true);
//$stock->setQty($stock->getQty() + $stockProduct->nb);
$stock->setQty($stockProduct->nb);
echo "qty: ".$stock->getQty()."\n";
//options
echo "Options \n";
if($shopHasOption) {
foreach($stock->getOptions() as $option) {
$stock->removeOption($option);
}
if(count($options)>0) {
echo "Has options \n";
$modelAttributes=$stock->getModel()->getAttributes();
$t=array();
foreach($modelAttributes as $attribute) {
if($attribute->getName()=='storage' || $attribute->getName()=='memory') {
$t[$attribute->getName()]=(int)$attribute->getValue();
}
}
$modelAttributes=$t;
foreach($shop->getOptions() as $option) {
// if($option->getCategory()->getId()==$stock->getModel()->getCategory()->getId()) {
if($optionAttribute = $option->getAttribute()) {
if(isset($modelAttributes[$option->getAttribute()->getName()])) {
if((int)$modelAttributes[$option->getAttribute()->getName()]==(int)$option->getAttributeValue()) {
if($option->getCategory()->getId()==$stock->getModel()->getCategory()->getId()) {
$stock->addOption($option);
}
}
}
}
else {
if($option->getCategory()) {
if($option->getCategory()->getId()==$stock->getModel()->getCategory()->getId()) {
$stock->addOption($option);
}
}
}
}
//die();
}
}
else {
foreach($stock->getOptions() as $option) {
$stock->removeOption($option);
}
}
$stock->setUpdated($lastUpdate);
if($stock->isOverride()) {
$stock->setPrice($overridenPrice);
echo "### stock overriden, continue\n";
//die();
continue;
}
$em->persist($stock);
echo "Stock saved\n";
if($stock->getId()) {
if(!$historyService->getHistory('stock', $stock->getId(),'status','created')) {
$historyService->setHistory('stock',$stock->getId(),'status','created');
$historyService->setHistory('stock',$stock->getId(), 'status', 'updated');
$historyService->setHistory('stock',$stock->getId(), 'price', $stock->getPrice());
// $historyService->setHistory('stock',$stock->getId(),'updated');
}
if($historyService->getHistory('stock', $stock->getId(),'price')!=$stock->getPrice()) {
$historyService->setHistory('stock',$stock->getId(), 'price', $stock->getPrice());
$historyService->setHistory('stock',$stock->getId(), 'status', 'updated');
}
echo "History done\n";
}
}
foreach($disableModels as $k=>$model) {
$existingStock=$em->getRepository(Stock::class)->findBy(array('shop'=>$shop->getId(),'model'=>$model));
$stock=$existingStock[0];
$stock->setEnabled(false);
echo "remove ".$model."\n";
$stock->setQty(0);
}
// var_dump($disableModels);
$em->flush();
}
//var_dump($this->cachedPrices);
return new Response('ok');
}
public function getPriceNet($price, $shop, $bak2_api_url)
{
if($price<=0) {
return 0;
}
echo "price: ".$price. " / MP: ".$shop->getWttId()."\n";
//$url=https://share.ddev.site:8443/routine/report/api/tempStock.php?action=getBestPrice&marketplaceId=17&price=".$price;
if(!isset($this->cachedPrices[$price])) {
echo "----prices doesn't exist\n";
$importUrl = $bak2_api_url . "/tempStock.php?action=getBestPrice&marketplaceId=" . $shop->getWttId()."&price=".$price;
echo $importUrl."\n";
$importUrl=preg_replace('/ /','',$importUrl);
$stockContent = file_get_contents($importUrl);
$stockData = json_decode($stockContent);
echo "new price ".$stockData->bsp."\n";
$this->cachedPrices[$price]=$stockData->bsp;
}
else {
echo "----ok prices cached\n";
}
return $this->cachedPrices[$price];
/*
if($price<=0) {
return 0;
}
$internalCost = (float)$this->shop_config->internalCost;
$labor = (float)$this->shop_config->laborCost;
$logistic = (float)$this->shop_config->logisticCost;
$accessory = (float)$this->shop_config->accessoryCost;
$warranty_percentage = (float)$this->shop_config->warranty_perentage;
$warranty_fixe = (float)$this->shop_config->warranty_fixe;
$commision_percentage = (float)$this->shop_config->commision_perentage;
$margin_other_percentage = (float)$this->shop_config->margin_other_percentage;
$margin_tablet_percentage = (float)$this->shop_config->margin_tablet_percentage;
$tva = (100 + (float)$this->shop_config->tva_percentage) / 100;
echo "price:" . $price . "\n";
$bbNet1 = $price / $tva;
echo "bbNet1: " . $bbNet1 . "\n";
$bbNet2 = $bbNet1 - ($commision_percentage / 100 * $price);
echo "bbNet2:" . $bbNet2 . "\n";
$bbNet3 = $bbNet2 - ($warranty_percentage / 100 * $bbNet2) - $warranty_fixe;
echo "bbNet3:" . $bbNet3 . "\n";
$bbNet = $bbNet3 - ($internalCost + $labor + $logistic + $accessory);
echo $bbNet."\n";
echo $internalCost ." + ".$labor ." + ". $logistic ." + ". $accessory."\n";
//Version Nico
//$pp = ($warranty_perentage/100) + ($commision_perentage/100);
//$bbNet = (($price-($tva*$warranty_fixe))/($tva*(1+$pp))) - $labor - $logistic - $accessory;
$bsp1 = $price + $labor + $logistic + $accessory ;
if($category->getId()==2) {
// $bsp1=$bsp1+ $margin_tablet_percentage;
}
else {
// $bsp1=$bsp1+ $margin_other_percentage;
}
echo "bsp1:" . $bsp1 . "\n";
$bsp2 = $bsp1 + ($warranty_percentage / 100 * $bsp1) + $warranty_fixe;
echo "bsp2:" . $bsp2 . "\n";
$bsp = ($bsp2 + ($commision_percentage / 100 * $bsp2)) * $tva;
echo "bsp:" . $bsp . "\n";
return $bsp;
*/
}
private function getResalePrice($price)
{
if($price<=0) {
return 0;
}
if ($price > 300) {
$resalePrice = $price + 15;
} elseif ($price > 100) {
$resalePrice = $price + 10;
} elseif ($price > 50) {
$resalePrice = $price + 5;
} else {
$resalePrice = floor($price * 1.08);
}
return $resalePrice;
}
function getMinPrice($price, $grade)
{
if ($price > 0) {
if ($price < 5 && $grade == 'C') {
$price = 5;
} elseif ($price < 4 && $grade == 'E') {
$price = 4;
} elseif ($price < 3) {
$price = 3;
}
}
return $price;
}
private function getCurrentDestock() {
$destock=array();
$em=$this->em;
if($orders= $em->getRepository(Order::class)->findBy(array('status'=>10))) {
$gradeRepository=$em->getRepository(Grade::class);
$productRepository=$em->getRepository(Product::class);
$cartRepository=$em->getRepository(Cart::class);
foreach($orders as $order) {
foreach($order->getCarts() as $cart) {
$stock=$cart->getStock();
$sourceGrades = $stock->getSourceGrade();
foreach (explode(',', $sourceGrades) as $sourceGrade) {
if ($grade = $gradeRepository->findOneByName($sourceGrade)) {
if ($product = $productRepository->findOneBy(array('grade' => $grade, 'model' => $stock->getModel(), 'color' => $stock->getColor()))) {
if(!isset($destock[$product->getSku()])) {
$destock[$product->getSku()]=0;
}
$destock[$product->getSku()] = $destock[$product->getSku()]+$cart->getQty();
break;
}
}
}
}
}
}
return $destock;
}
public function searchForm() {
$form = $this->createForm(SearchType::class);
return $this->render('stock/search.html.twig', [
'form' => $form->createView()
]);
}
public function getHeader(ParameterBagInterface $params) {
$user=$this->getUser();
$template_sub_file="stock/header.html.twig";
if(file_exists($params->get('kernel.project_dir')."/private/shops/".$user->getShop()->getId()."/templates/stock/header.html.twig")) {
$template_sub_file="shops/".$user->getShop()->getId()."/templates/stock/header.html.twig";
}
return $this->render($template_sub_file);
}
public function getFooter(ParameterBagInterface $params) {
$user=$this->getUser();
$template_sub_file="stock/footer.html.twig";
if(file_exists($params->get('kernel.project_dir')."/private/shops/".$user->getShop()->getId()."/templates/stock/footer.html.twig")) {
$template_sub_file="shops/".$user->getShop()->getId()."/templates/stock/footer.html.twig";
}
return $this->render($template_sub_file);
}
}