Advertisement
baby_in_magento

ProductBreakdown.php

Oct 9th, 2023 (edited)
79
0
104 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 32.28 KB | None | 0 0
  1. <?php
  2.  
  3. namespace Froogal\Catalog\Model;
  4.  
  5. use GuzzleHttp\Client;
  6. use Magento\Framework\App\Helper\Context;
  7. use Magento\Store\Model\ScopeInterface;
  8. use Magento\Framework\App\Config\ScopeConfigInterface;
  9. use Magento\Customer\Api\CustomerRepositoryInterface;
  10.  
  11.  
  12.  
  13.  
  14. class ProductBreakDown extends \Magento\Framework\Model\AbstractModel implements \Froogal\Catalog\Api\ProductBreakDownInterface
  15. {
  16.  
  17.     const RINGSIZE_AMOUNT_INCREMENT = 0.1;
  18.  
  19.     /**
  20.      * @var ScopeConfigInterface
  21.      */
  22.     protected $scopeConfigInterface;
  23.     protected $customerSession;
  24.  
  25.     protected $helperData;
  26.  
  27.     protected $productSolitaireInterface;
  28.  
  29.     protected $productRepository;
  30.  
  31.     protected $ruleResource;
  32.     public function __construct(
  33.         ScopeConfigInterface $scopeConfigInterface,
  34.         CustomerRepositoryInterface $customerRepository,
  35.         \Magento\Customer\Model\CustomerFactory $customerFactory,
  36.         \Magento\Customer\Model\Session $customerSession,
  37.         \Froogal\Catalog\Helper\Helpers $helperData,
  38.         \Magento\Tax\Model\Calculation $taxCalculation,
  39.         \Froogal\Catalog\Helper\TaxData $taxData,
  40.         \Froogal\Catalog\Api\ProductSolitaireInterface $productSolitaireInterface,
  41.         \Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
  42.         \Magento\CatalogRule\Model\ResourceModel\Rule $rule
  43.  
  44.  
  45.     ) {
  46.         $this->client = new Client();
  47.         $this->scopeConfigInterface = $scopeConfigInterface;
  48.         $this->customerRepository = $customerRepository;
  49.         $this->_customerFactory = $customerFactory;
  50.         $this->customerSession = $customerSession;
  51.         $this->helperData = $helperData;
  52.         $this->taxCalculation = $taxCalculation;
  53.         $this->taxData = $taxData;
  54.         $this->productSolitaireInterface = $productSolitaireInterface;
  55.         $this->productRepository = $productRepository;
  56.         $this->ruleResource = $rule;
  57.  
  58.     }
  59.  
  60.    
  61.    
  62.     public function getProductBreakDown($productId,$productVariant=null,$customOptionId=null,$optionValue=null,$ringSize=null,$goldColor=null,$diamondId=null,$carat=null,$pcnumber=null,$size=null)
  63.     {
  64.         $writer = new \Zend_Log_Writer_Stream(BP . '/var/log/custom.log');
  65.         $logger = new \Zend_Log();
  66.         $logger->addWriter($writer);
  67.         $logger->info('customOptionId' . $customOptionId.'optionValue' . $optionValue.'ringSize' . $ringSize );
  68.  
  69.         $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
  70.         if($pcnumber)
  71.         {
  72.             $mainProduct = $this->getProductByAttributes($pcnumber,$size);
  73.         }
  74.         else
  75.         {
  76.             $mainProduct = $objectManager->create('Magento\Catalog\Model\Product')->load($productId);
  77.         }        
  78.         $variantId = $mainProduct->getData('display_variant') ?? null;
  79.         $productConstituentInfo = [];
  80.         $productByvariants = [];
  81.         $goldproductConstituents = [];
  82.         $diamondproductConstituents = [];
  83.         $gemstoneproductConstituents = [];
  84.         if(($goldColor != '') && ($goldColor !='undefined') && ($goldColor != null))
  85.         {
  86.             $goldproductConstituents = $objectManager->create('Froogal\Catalog\Model\ProductRelation')->getCollection()
  87.             ->addFieldToFilter('product_id', $productId)
  88.             ->addFieldToFilter('color', array('like' => "%$goldColor%"))
  89.             ->getData();
  90.             if(count($goldproductConstituents) > 0)
  91.             {
  92.                 $variantId = $goldproductConstituents[0]['variant_id'] ?? null;
  93.             }
  94.         }
  95.         if($carat !=null)
  96.         {
  97.             $diamondproductConstituents = $objectManager->create('Froogal\Catalog\Model\ProductRelation')->getCollection()
  98.             ->addFieldToFilter('product_id', $productId)
  99.             ->addFieldToFilter('carat', array('like' => "%$carat%"))
  100.             ->getData();
  101.             if(count($diamondproductConstituents) > 0)
  102.             {
  103.                 $variantId = $diamondproductConstituents[0]['variant_id'] ?? null;
  104.             }
  105.         }
  106.        
  107.             $productByvariants = $objectManager->create('Froogal\Catalog\Model\ProductRelation')->getCollection()
  108.             ->addFieldToFilter('product_id', $productId)
  109.             ->addFieldToFilter('variant_id', array('like' => "%$variantId%"))
  110.             ->getData();
  111.        
  112.  
  113.         $productConstituents =  array_merge($productConstituentInfo,$productByvariants);
  114.         $outletModel = $objectManager->create('Froogal\Outlets\Model\OutletInventoryFactory')->create()->load($variantId,'variant_id');
  115.         $ringSize = ($ringSize == $outletModel->getSize()) ? $outletModel->getSize() : $ringSize;
  116.         $productRingSize = $mainProduct->getResource()->getAttribute('ring_size')->getFrontend()->getValue($mainProduct) ?? 0;
  117.         $finalPrice = $mainProduct->getFinalPrice();
  118.         $originalPrice = $mainProduct->getFinalPrice();
  119.         $actualFinalPrice = (($finalPrice * 100) / (100 + 10));                        
  120.         $diffPrice = $finalPrice - $actualFinalPrice;
  121.  
  122.         //catalog rules
  123.         $date = date('Y-m-d');
  124.         $websiteId = 1;
  125.         $customerGroupId = null;
  126.         $regularPrice = 0;
  127.         $glowSku = '';
  128.         $action_amount = 0;
  129.         $rules = $this->getRules($date, $websiteId, $customerGroupId, $productId);
  130.         $makingDiscountRule = in_array('custom_mak',array_column($rules, 'action_operator'));
  131.         $discountAmount = $this->getProductDiscount($mainProduct);
  132.         if($makingDiscountRule)
  133.         {
  134.             $action_amount = $rules[0]['action_amount'] ?? 0;
  135.             $makingChargesValue = $mainProduct->getData('making_charges_value');
  136.             $makingChargesDiscountValue = ($makingChargesValue * ($action_amount / 100));
  137.         }
  138.        
  139.         if($variantId)
  140.         {
  141.             $productVariant = $objectManager->create('Froogal\Catalog\Model\ProductVariant')->load($variantId);
  142.             $glowSku = $productVariant['glow_sku'];
  143.         }
  144.         if ($customOptionId) {
  145.             if($discountAmount)
  146.             {
  147.                 $regularPrice = $mainProduct->getPriceInfo()->getPrice('regular_price')->getValue();
  148.                 $finalPrice = $this->getOptionPrice($mainProduct,$regularPrice,$productRingSize,$customOptionId,$optionValue);
  149.             }
  150.             else
  151.             {
  152.                 $finalPrice = $this->getOptionPrice($mainProduct,$finalPrice,$productRingSize,$customOptionId,$optionValue);
  153.             }
  154.  
  155.             // $finalPrice = $mainProduct->getFinalPrice() + $option->getPrice();
  156.         } else {
  157.             $finalPrice = $mainProduct->getPrice();
  158.         }
  159.  
  160.         $finalArray = [];
  161.         if(!empty($productConstituents))
  162.         {
  163.             $countryCode = $this->scopeConfigInterface->getValue(\Magento\Shipping\Model\Config::XML_PATH_ORIGIN_COUNTRY_ID);
  164.             $regionCode = $this->scopeConfigInterface->getValue(\Magento\Shipping\Model\Config::XML_PATH_ORIGIN_REGION_ID);
  165.  
  166.             $customerTaxClassId = $this->scopeConfigInterface->getValue('tax/classes/default_customer_tax_class');
  167.             /** @var \Magento\Catalog\Model\Product $product */
  168.             $productTaxClassId = $mainProduct->getData('tax_class_id');
  169.  
  170.             // THE ACTUAL CALCULATION CALL
  171.  
  172.             /** @var \Magento\Tax\Model\Calculation $taxCalculation */
  173.             $taxPercent = $this->taxCalculation->getRate(
  174.                 new \Magento\Framework\DataObject(
  175.                     [
  176.                         'country_id' => $countryCode,
  177.                         'region_id' => $regionCode,
  178.                         'customer_class_id' => $customerTaxClassId,
  179.                         'product_class_id' => $productTaxClassId
  180.                     ]
  181.                 )
  182.             );
  183.  
  184.             $diamondCarats = 0;
  185.             $diamondPrice = 0;
  186.             $goldWeight = 0;
  187.             $goldPrice = 0;
  188.             $gemstoneCarats = 0;
  189.             $gemstonePrice = 0;
  190.             $platinumWeight = 0;
  191.             $platinumPrice = 0;
  192.             $goldColor = 0;
  193.             $carats = 0;
  194.             foreach($productConstituents as $productConstituentData)
  195.             {  
  196.                 $contituentProductId = $productConstituentData['contituent_product_id'];
  197.                 $color = $productConstituentData['color'];
  198.                 $contituentProduct = $objectManager->create('Magento\Catalog\Model\Product')->load($contituentProductId);
  199.                 $contituentProductPrice = $contituentProduct->getPrice();
  200.                 $constituentType = $contituentProduct->getResource()->getAttribute('constituent_type')->getFrontend()->getValue($contituentProduct);
  201.                 if ($constituentType == "Diamond") {
  202.                     $carats = ((float) $productConstituentData['qty']) * ($productConstituentData['carat'] ?? 1);
  203.                     $diamondCarats += $carats;
  204.                     if($carat == $carats)
  205.                     {
  206.                         $diamondCarats = $carats;
  207.                     }                    
  208.                     $diamondPrice += $contituentProductPrice * $carats;
  209.  
  210.                 } elseif ($constituentType == "Gold") {
  211.                     $goldWeight += $productConstituentData['qty'];
  212.                     if ($ringSize!='undefined' && $ringSize != $productRingSize && $goldColor == $color) {
  213.                         $goldWeight = $productConstituentData['qty'];                        
  214.                         $sizeDifference = max(0, (float)$ringSize - (float)$productRingSize);
  215.                         $weightDifference = $sizeDifference * self::RINGSIZE_AMOUNT_INCREMENT;                        
  216.                         if ($weightDifference) {
  217.                             $goldWeight += $weightDifference;
  218.                         }
  219.                     }
  220.                     else if ($ringSize!='undefined' && $ringSize != $productRingSize) {
  221.                         $sizeDifference = max(0, (int)$ringSize - (int)$productRingSize);
  222.                         $weightDifference = $sizeDifference * self::RINGSIZE_AMOUNT_INCREMENT;
  223.                         if ($weightDifference) {
  224.                             $goldWeight += $weightDifference;
  225.                         }
  226.                     }
  227.                     $goldPrice += $contituentProductPrice * ((float) $goldWeight);
  228.                 } elseif ($constituentType == "Gemstone") {
  229.                     $carats = ((float) $productConstituentData['qty']) * ($productConstituentData['carat'] ?? 1);
  230.                     $gemstoneCarats += $carats;
  231.                     $gemstonePrice += $contituentProductPrice * $carats;
  232.                 } elseif ($constituentType == "Platinum") {
  233.                     $platinumWeight = $productConstituentData['qty'];
  234.                     $platinumPrice += $contituentProductPrice * ((float) $platinumWeight);
  235.                 }
  236.             }
  237.             if ($productVariant === 'solitaire') {
  238.                $productBreakDown = $this->getSolitaireProductBreakDown($productId,$diamondId,$customOptionId,$optionValue,$ringSize,$goldColor=null,$carat=null,$pcnumber=null,$size=null);
  239.                return $this->helperData->success('Product BreakDown', $productBreakDown);
  240.             }
  241.             $constituentsTotal = 0;
  242.             $content = [];
  243.             $productDetails=[
  244.                 'variant_carat'=> "({$carats}g)",
  245.                 'variant_weight'=> $goldWeight,
  246.                 'variant_sku'=> $glowSku,
  247.                 'variant_color'=> $color
  248.             ];
  249.             if ($goldPrice) {
  250.                 $content[] = [
  251.                     'variant_type' => "Gold ({$goldWeight}g)",
  252.                     'variant_price' => $goldPrice,
  253.                 ];
  254.                 $constituentsTotal += $goldPrice;
  255.             }
  256.             if ($diamondPrice) {
  257.                 $diamondPrice = $diamondPrice + $diffPrice;
  258.                 $content[] = [
  259.                     'variant_type' => "Diamonds ({$diamondCarats}cts)",
  260.                     'variant_price' => $diamondPrice,
  261.                 ];
  262.                 $constituentsTotal += $diamondPrice;
  263.             }
  264.             if ($gemstonePrice) {
  265.                 $content[] = [
  266.                     'variant_type' => "Gemstones ({$gemstoneCarats}cts)",
  267.                     'variant_price' => $gemstonePrice,
  268.                 ];
  269.                 $constituentsTotal += $gemstonePrice;
  270.             }
  271.             if ($platinumPrice) {
  272.                 $content[] = [
  273.                     'variant_type' => "Platinum ({$platinumWeight}g)",
  274.                     'variant_price' => $platinumPrice,
  275.                 ];
  276.                 $constituentsTotal += $platinumPrice;
  277.             }
  278.             $gemstoneAttributePrice = (float) $mainProduct->getData('gemstone_price');
  279.             if ($gemstoneAttributePrice) {
  280.                 $content[] = [
  281.                     'variant_type' => "Gemstones",
  282.                     'variant_price' => $gemstoneAttributePrice,
  283.                 ];
  284.                 $constituentsTotal += $gemstoneAttributePrice;
  285.             }
  286.             $logger->info('constituentsTotal'.json_encode($constituentsTotal));
  287.             $netAmount = round($finalPrice * 100 / (100 + $taxPercent));
  288.             $taxAmount = round($finalPrice - $netAmount);
  289.  
  290.            // $valueAddition = round(max($netAmount - $constituentsTotal, 0),2);
  291.            $valueAddition = $product->getResource()->getAttribute('making_charges_value')->getFrontend()->getValue($product);
  292.  
  293.  
  294.             $logger->info('valueAddition='.$valueAddition.'netamount=' .$netAmount .'constituentsTotal='.$constituentsTotal.'taxamount='.$taxAmount);
  295.             $finalDiscountAmount = max(0,$regularPrice - $originalPrice);
  296.             $makingChargesDiscountValue = round(max($regularPrice - $finalPrice,0));
  297.  
  298.  
  299.             // $finalDiscountAmount = round(max($valueAddition * ($action_amount / 100),0));
  300.             $discountedTaxAmount = 0;
  301.             if($makingDiscountRule)
  302.             {
  303.                 $makingChargesDiscountValue = round(max($valueAddition * ($action_amount / 100),0));
  304.                 $makingTaxOnDiscount = $makingChargesDiscountValue * ($taxPercent / 100);
  305.                 $discountedTaxAmount = $taxAmount - $makingTaxOnDiscount;
  306.             }
  307.            
  308.             $finalArray = [
  309.                 'content' => $content,
  310.                 'productDetails' => $productDetails,
  311.                 'totalPrice' => $finalPrice,
  312.                 'discountAmount' => $finalDiscountAmount,
  313.                 'product_discount' => $finalDiscountAmount,
  314.                 'valueAddition' => $valueAddition,
  315.                 'tax' => $taxAmount,
  316.                 'effectiveTax' => $discountedTaxAmount
  317.             ];
  318.         }
  319.         return $this->helperData->success('Product BreakDown', $finalArray);
  320.     }
  321.  
  322.     public function getOptionPrice($product,$finalPrice,$ringSize,$customOptionId,$optionValue)
  323.     {
  324.         $writer = new \Zend_Log_Writer_Stream(BP . '/var/log/custom.log');
  325.         $logger = new \Zend_Log();
  326.         $logger->addWriter($writer);
  327.         $_objectManager = \Magento\Framework\App\ObjectManager::getInstance();
  328.         $customOptions = $_objectManager->get('Magento\Catalog\Model\Product\Option')->getProductOptionCollection($product);
  329.         if (count($customOptions) > 0) {
  330.             foreach ($customOptions as $options) {                
  331.                 $optionTitle = strtolower($options->getTitle());
  332.                 if ($optionTitle == 'ring size') {
  333.                     $optionData = $options->getValues();
  334.                     foreach ($optionData as $data) {
  335.  
  336.                         $size = $data->getTitle();                            
  337.                         $optionTypeId = $data->getData('option_type_id');
  338.                         if($optionTypeId == $optionValue)
  339.                         {
  340.                             // $logger->info('optiontypeid=' . $optionTypeId . 'optionvalue=' . $optionValue . 'size=' . $size . 'ringsize=' . $ringSize);
  341.  
  342.                             $customOptionPrice = $data->getPrice();
  343.                             $finalPrice = $finalPrice + $customOptionPrice;
  344.                             $logger->info('customOptionPrice='.$customOptionPrice.'finalprice=' . $finalPrice);
  345.                         }                          
  346.  
  347.                     }
  348.                 }
  349.             }
  350.         }
  351.         return $finalPrice;
  352.     }
  353.     public function getSolitaireProductDetails($productId,$diamondId)
  354.     {
  355.         $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
  356.         $productRelation = $objectManager->create('Froogal\Catalog\Model\ProductRelation')->getCollection()->addFieldToFilter('product_id', $productId)->getData();
  357.         $response = $this->productSolitaireInterface->getSolitaireItemRate($diamondId);
  358.         $solitaireDetails = $response['response']['body'];
  359.         if(empty($solitaireDetails))
  360.         {
  361.             return $this->helperData->error('No Diamond was found',$solitaireDetails);
  362.         }
  363.         $solitaireDetails = $response['response']['body']['diamond'] ?? null;
  364.         $data = [
  365.             ['value' => 'Diamond','label' => 'Constituent Type','attribute_code' => 'constituent_type'],
  366.             ['value' => $solitaireDetails['diamond_id'] ?? '','label' => 'DiamondID','attribute_code' => 'diamond_id'],
  367.             ['value' => $solitaireDetails['shape'] ?? '','label' => 'Shape','attribute_code' => 'shape'],
  368.             ['value' => $solitaireDetails['size'] ?? '','label' => 'Size','attribute_code' => 'carat'],
  369.             ['value' => $solitaireDetails['color'] ?? '','label' => 'Color','attribute_code' => 'color'],
  370.             ['value' => $solitaireDetails['clarity'] ?? '','label' => 'Quality','attribute_code' => 'quality'],
  371.             ['value' => $solitaireDetails['cut'] ?? '','label' => 'Cut','attribute_code' => 'cut'],
  372.             ['value' => $solitaireDetails['stock_num'] ?? '','label' => 'Style Code','attribute_code' => 'style_code'],
  373.             ['value' => $solitaireDetails['symmetry'] ?? '','label' => 'Symmetry','attribute_code' => 'symmetry'],
  374.             ['value' => $solitaireDetails['currency_symbol'] ?? '','Symbol' => 'DiamondID','attribute_code' => 'currency_symbol'],
  375.             ['value' => $solitaireDetails['total_sales_price_in_currency'] ?? '','label' => 'Diamond Price','attribute_code' => 'total_sales_price_in_currency']
  376.         ];
  377.        
  378.         $content = [];
  379.         $finalArray = [];
  380.         if (!empty($productRelation)) {
  381.  
  382.             foreach ($productRelation as $productRelationValue) {
  383.                 $masterProductId = $productRelationValue['contituent_product_id'];
  384.  
  385.                 $qty = $productRelationValue['qty'];
  386.                 $carat = $productRelationValue['carat'];
  387.  
  388.                 $product = $objectManager->create('Magento\Catalog\Model\Product')->load($masterProductId);
  389.                 $price = $product->getPrice();
  390.                 $weightUnit = $this->scopeConfigInterface->getValue(
  391.                     'general/locale/weight_unit',
  392.                     ScopeInterface::SCOPE_STORE
  393.                 );
  394.  
  395.                 $constituentType = $product->getResource()->getAttribute('constituent_type')->getFrontend()->getValue($product);
  396.                
  397.                 if ($constituentType == 'Gold') {
  398.                     // $data[] = ['value' => $productRelationValue['glow_sku'],'label' => 'Glow Sku','attribute_code' => 'glow_sku'];
  399.                     // $data[] = ['value' => $productRelationValue['qty'],'label' => 'Gold Weight','attribute_code' => 'gold_weight'];  
  400.                     // $data[] = ['value' => $productRelationValue['carat'],'label' => 'Gold Carat','attribute_code' => 'gold_carat'];  
  401.                     // $data[] = ['value' => $productRelationValue['color'],'label' => 'Gold Color','attribute_code' => 'gold_color'];
  402.                 }
  403.                 else if ($constituentType == 'Platinum') {
  404.                     // $data[] = ['value' => $productRelationValue['glow_sku'],'label' => 'Glow Sku','attribute_code' => 'glow_sku'];            
  405.                 }
  406.                 else if ($constituentType == 'Gemstone') {                  
  407.                     $carats = ((float) $productRelationValue['qty']) * ($productRelationValue['carat'] ?? 1);
  408.                     $gemstoneCarats += $carats;
  409.                     // $data[] = ['value' => $gemstoneCarats,'label' => 'GemStone Weight','attribute_code' => 'gemstone_weight'];            
  410.                 }                
  411.             }
  412.         }
  413.         // array_push($content, $data);
  414.         return $this->helperData->success('Solitaire Product Details',$data);
  415.          
  416.     }
  417.  
  418.     protected function getProductDiscount($product)
  419.     {
  420.        
  421.         $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
  422.         $rule = $objectManager->create('\Magento\CatalogRule\Model\RuleFactory')->create();
  423.         $discountAmount = $rule->calcProductPriceRule($product,$product->getPrice());
  424.         return $discountAmount;
  425.     }
  426.  
  427.     public function getSolitaireProductBreakDown($productId, $diamondId,$customOptionId,$optionValue,$ringSize,$goldColor=null,$carat=null,$pcnumber=null,$size=null)
  428.     {
  429.         $writer = new \Zend_Log_Writer_Stream(BP . '/var/log/custom.log');
  430.         $logger = new \Zend_Log();
  431.         $logger->addWriter($writer);
  432.         $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
  433.         if($pcnumber)
  434.         {
  435.             $mainProduct = $this->getProductByAttributes($pcnumber,$size);
  436.         }
  437.         else
  438.         {
  439.             $mainProduct = $objectManager->create('Magento\Catalog\Model\Product')->load($productId);
  440.         }
  441.         //$mainProduct = $objectManager->create('Magento\Catalog\Model\Product')->load($productId);
  442.        
  443.        // $productConstituents = $objectManager->create('Froogal\Catalog\Model\ProductRelation')->getCollection()->addFieldToFilter('product_id', $productId)->addFieldToFilter('variant_id', array('like' => "%$variantId%"))->getData();
  444.        $productRingSize = $ringSize != '' ? $ringSize : ($mainProduct->getResource()->getAttribute('ring_size')->getFrontend()->getValue($mainProduct) ?? 0);
  445.        $variantId = $mainProduct->getData('display_variant') ?? null;
  446.        $glowSku = '';      
  447.        if($goldColor !=null && $goldColor !='undefined')
  448.        {
  449.            $productConstituents = $objectManager->create('Froogal\Catalog\Model\ProductRelation')->getCollection()
  450.            ->addFieldToFilter('product_id', $productId)
  451.            ->addFieldToFilter('variant_id', array('like' => "%$variantId%"))
  452.         //    ->addFieldToFilter('color', array('like' => "%$goldColor%"))
  453.            ->getData();
  454.        }
  455.        else if($carat !=null)
  456.        {
  457.            $productConstituents = $objectManager->create('Froogal\Catalog\Model\ProductRelation')->getCollection()
  458.            ->addFieldToFilter('product_id', $productId)
  459.            ->addFieldToFilter('variant_id', array('like' => "%$variantId%"))
  460.         //    ->addFieldToFilter('carat', array('like' => "%$carat%"))
  461.            ->getData();
  462.        }
  463.        else
  464.        {
  465.            $productConstituents = $objectManager->create('Froogal\Catalog\Model\ProductRelation')->getCollection()
  466.            ->addFieldToFilter('product_id', $productId)
  467.            ->addFieldToFilter('variant_id', array('like' => "%$variantId%"))
  468.            ->getData();
  469.         //    return $productConstituents;
  470.        }
  471.         $productCalclator = $objectManager->create('\Froogal\Catalog\Model\ProductPriceCalculator');
  472.         $finalPrice = $productCalclator->getFinalPrice($productId,$diamondId);
  473.         // return $finalPrice;
  474.         $discountAmount = $this->getProductDiscount($mainProduct);
  475.         // return $discountAmount;
  476.         $regularPrice = 0;
  477.         if($variantId)
  478.         {
  479.             $productVariant = $objectManager->create('Froogal\Catalog\Model\ProductVariant')->load($variantId);
  480.             $glowSku = $productVariant['glow_sku'];
  481.         }
  482.         if ($customOptionId) {
  483.             if($discountAmount)
  484.             {
  485.                 // $regularPrice = $mainProduct->getPriceInfo()->getPrice('regular_price')->getValue();
  486.                 $finalPrice = $this->getOptionPrice($mainProduct,$finalPrice,$productRingSize,$customOptionId,$optionValue);
  487.             }
  488.             else
  489.             {
  490.                 $finalPrice = $this->getOptionPrice($mainProduct,$finalPrice,$productRingSize,$customOptionId,$optionValue);
  491.             }
  492.  
  493.         } else {
  494.             $finalPrice = $mainProduct->getFinalPrice();
  495.         }
  496.         $finalArray = [];
  497.         if(!empty($productConstituents))
  498.         {
  499.             $countryCode = $this->scopeConfigInterface->getValue(\Magento\Shipping\Model\Config::XML_PATH_ORIGIN_COUNTRY_ID);
  500.             $regionCode = $this->scopeConfigInterface->getValue(\Magento\Shipping\Model\Config::XML_PATH_ORIGIN_REGION_ID);
  501.  
  502.             $customerTaxClassId = $this->scopeConfigInterface->getValue('tax/classes/default_customer_tax_class');
  503.             /** @var \Magento\Catalog\Model\Product $product */
  504.             $productTaxClassId = $mainProduct->getData('tax_class_id');
  505.  
  506.             // THE ACTUAL CALCULATION CALL
  507.  
  508.             /** @var \Magento\Tax\Model\Calculation $taxCalculation */
  509.             $taxPercent = $this->taxCalculation->getRate(
  510.                 new \Magento\Framework\DataObject(
  511.                     [
  512.                         'country_id' => $countryCode,
  513.                         'region_id' => $regionCode,
  514.                         'customer_class_id' => $customerTaxClassId,
  515.                         'product_class_id' => $productTaxClassId
  516.                     ]
  517.                 )
  518.             );
  519.  
  520.             $diamondCarats = 0;
  521.             $diamondPrice = 0;
  522.             $goldWeight = 0;
  523.             $goldPrice = 0;
  524.             $gemstoneCarats = 0;
  525.             $gemstonePrice = 0;
  526.             $platinumWeight = 0;
  527.             $platinumPrice = 0;
  528.             $goldColor = 0;
  529.             foreach($productConstituents as $productConstituentData)
  530.             {  
  531.                 $contituentProductId = $productConstituentData['contituent_product_id'];
  532.                 // $glowSku = $productConstituentData['glow_sku'] ?? '';
  533.                 $color = $productConstituentData['color']?? '' ;
  534.                 $contituentProduct = $objectManager->create('Magento\Catalog\Model\Product')->load($contituentProductId);
  535.                 $contituentProductPrice = $contituentProduct->getPrice();
  536.                 $constituentType = $contituentProduct->getResource()->getAttribute('constituent_type')->getFrontend()->getValue($contituentProduct);
  537.                 if ($constituentType == "Diamond") {
  538.                     // $request['body']['diamond_id'] = $diamondId;
  539.                     $response = $this->productSolitaireInterface->getSolitaireItemRate($diamondId);
  540.                     $solitaireDetails = $response['response']['body'];
  541.                     if(empty($solitaireDetails))
  542.                     {
  543.                         $diamondPrice = 0;
  544.                     }
  545.                     else
  546.                     {
  547.                         $solitaireDetails = $solitaireDetails['diamond'];
  548.                         $diamondPrice = $solitaireDetails['total_sales_price_in_currency'] ?? '';
  549.                         $diamondCarats = $solitaireDetails['size'];
  550.                     }                  
  551.                      
  552.                 }                
  553.  
  554.                 if ($constituentType == "Gold") {
  555.                     $goldWeight += $productConstituentData['qty'];
  556.  
  557.                     if ($ringSize!='undefined' && $ringSize != $productRingSize) {
  558.                         $sizeDifference = max(0, $ringSize - $productRingSize);
  559.                         $weightDifference = $sizeDifference * 0.1;
  560.                         if ($weightDifference) {
  561.                             $goldWeight += $weightDifference;
  562.                         }
  563.                     }
  564.                     $goldPrice += $contituentProductPrice * ((float) $goldWeight);
  565.                 } elseif ($constituentType == "Gemstone") {
  566.                     $carats = ((float) $productConstituentData['qty']) * ($productConstituentData['carat'] ?? 1);
  567.                     $gemstoneCarats += $carats;
  568.                     $gemstonePrice += $contituentProductPrice * $carats;
  569.                 } elseif ($constituentType == "Platinum") {
  570.                     $platinumWeight = $productConstituentData['qty'];
  571.                     $platinumPrice += $contituentProductPrice * ((float) $platinumWeight);
  572.                 }
  573.             }
  574.             // return $finalPrice;
  575.             $constituentsTotal = 0;
  576.             $content = [];
  577.             $productDetails=[
  578.                 'variant_carat'=> "({$diamondCarats}g)",
  579.                 'variant_weight'=> $goldWeight,
  580.                 'variant_sku'=> $glowSku,
  581.                 'variant_color'=> $color
  582.             ];
  583.             if ($goldPrice) {
  584.                 $content[] = [
  585.                     'variant_type' => "Gold ({$goldWeight}g)",
  586.                     'variant_price' => $goldPrice,
  587.                 ];
  588.                 $constituentsTotal += $goldPrice;
  589.             }
  590.             if ($diamondPrice) {
  591.                 $content[] = [
  592.                     'variant_type' => "Diamonds ({$diamondCarats}cts)",
  593.                     'variant_price' => $diamondPrice,
  594.                 ];
  595.                 $constituentsTotal += $diamondPrice;
  596.             }
  597.             if ($gemstonePrice) {
  598.                 $content[] = [
  599.                     'variant_type' => "Gemstones ({$gemstoneCarats}cts)",
  600.                     'variant_price' => $gemstonePrice,
  601.                 ];
  602.                 $constituentsTotal += $gemstonePrice;
  603.             }
  604.             if ($platinumPrice) {
  605.                 $content[] = [
  606.                     'variant_type' => "Platinum ({$platinumWeight}g)",
  607.                     'variant_price' => $platinumPrice,
  608.                 ];
  609.                 $constituentsTotal += $platinumPrice;
  610.             }
  611.             $gemstoneAttributePrice = (float) $mainProduct->getData('gemstone_price');
  612.             if ($gemstoneAttributePrice) {
  613.                 $content[] = [
  614.                     'variant_type' => "Gemstones",
  615.                     'variant_price' => $gemstoneAttributePrice,
  616.                 ];
  617.                 $constituentsTotal += $gemstoneAttributePrice;
  618.             }
  619.             $netAmount = round($finalPrice * 100 / (100 + $taxPercent));
  620.             $taxAmount = round($finalPrice - $netAmount);
  621.            
  622.             $valueAddition = round(max($netAmount - $constituentsTotal, 0),2);
  623.            
  624.             $finalDiscountAmount = max(0,$regularPrice - $discountAmount);
  625.             // return $finalPrice;
  626.             $objectManager = \Magento\Framework\App\ObjectManager::getInstance();              
  627.             $action = $objectManager->create('\Magento\Catalog\Model\ResourceModel\Product\Action');
  628.             $storeId = $objectManager->create('\Froogal\Catalog\Cron\PricingCalculation')->getStoreId();
  629.            
  630.             $updateAttributes['solitaire_final_price'] = $finalPrice;
  631.             $action->updateAttributes([$productId], $updateAttributes, $storeId);
  632.  
  633.             $finalArray = [
  634.                 'content' => $content,
  635.                 'productDetails' => $productDetails,
  636.                 'totalPrice' => $finalPrice,
  637.                 'discountAmount' => $finalDiscountAmount,
  638.                 'valueAddition' => $valueAddition,
  639.                 'tax' => $taxAmount,
  640.             ];
  641.         }
  642.  
  643.         return $finalArray;
  644.     }
  645.  
  646.     public function getProductByAttributes($pcnumber,$size)
  647.     {
  648.         $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
  649.         $outletInventory = $objectManager->create('Froogal\Outlets\Model\ResourceModel\OutletInventory\CollectionFactory')->create()->addFieldToSelect('*')->addFieldToFilter('pc_number',$pcnumber)->addFieldToFilter('size',$size)->setOrder('id', 'asc')->getFirstItem();
  650.         if($outletInventory)
  651.         {
  652.             $glowSku = $outletInventory->getData('glow_sku');
  653.             $mainProduct = $objectManager->create('Magento\Catalog\Model\Product')->loadByAttribute('glow_sku',$glowSku);
  654.             return $mainProduct;
  655.         }
  656.     }
  657.  
  658.    
  659.     public function getRules($date, $websiteId, $customerGroupId, $productId)
  660.     {
  661.        
  662.         /** @var [] $rules catalog rules */
  663.         $rules = $this->ruleResource->getRulesFromProduct($date, $websiteId, $customerGroupId, $productId);
  664.         return $rules;
  665.     }
  666.  
  667.    
  668. }
  669.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement