0

I want to send an Email through a cron job. Once the Seller adds new product Customer (Store Followed) I get a mail is working fine. But if for each new product customer will gets a mail then how can I send a mail only once if seller upload more product also.

I am new to Cron jobs so can you please explain it

controller.php

/**
     * Save New Products
     * 
     * @return void
     */
    public function newpostAction() {


        /**
         *  Check license key
         */
        Mage::helper('marketplace')->checkMarketplaceKey();
        /**
         *  Initilize customer and seller group id
         */
        $customerGroupId = $sellerGroupId = $customerStatus = '';
        Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
        $customerGroupId = Mage::getSingleton('customer/session')->getCustomerGroupId();
        $sellerGroupId = Mage::helper('marketplace')->getGroupId();
        $customerStatus = Mage::getSingleton('customer/session')->getCustomer()->getCustomerstatus();
        if (!$this->_getSession()->isLoggedIn() && $customerGroupId != $sellerGroupId) {
            Mage::getSingleton('core/session')->addError($this->__('You must have a Seller Account to access this page'));
            $this->_redirect('marketplace/seller/login');
            return;
        }
        /**
         *  Checking whether customer approved or not  
         */
        if ($customerStatus != 1) {
            Mage::getSingleton('core/session')->addError($this->__('Admin Approval is required. Please wait until admin confirms your Seller Account'));
            $this->_redirect('marketplace/seller/login');
            return;
        }
        /**
         *  Initializing variables
         */
        $productNameTrim = $set = $setbase = $type = $store = $sellerId = '';
        /**
         *  Getting  product values       
         */
        $type = $this->getRequest()->getPost('type');
        /**
         *  Attribute set 
         */
        $set = $this->getRequest()->getPost('set');
       $setbase = $this->getRequest()->getPost('setbase');
        $store = $this->getRequest()->getPost('store');
        if (Mage::getSingleton('customer/session')->isLoggedIn()) {
            $sellerId = Mage::getSingleton('customer/session')->getCustomer()->getId();
        }
        /**
         *  Getting group id
         */
        $groupId = Mage::helper('marketplace')->getGroupId();
        /**
         *  Getting product data from product array
         */
        $productData = $this->getRequest()->getPost('product');

        $silkType = $productData['silktype'];

        /**
         *  Getting product categories from category_ids array    
         */
        $categoryIds = $this->getRequest()->getPost('category_ids');
        if (!empty($productData['name']) && !empty($productData['description']) && isset($productData['price']) && isset($productData['stock_data']['qty']) && !empty($type)) {
            /**
             *  Initilize product weight
             */
            if ($type == 'simple') {
                if (!isset($productData['weight'])) {
                    $productData['weight'] = 0;
                }
            }
            /**
             *  Assing product short description     
             */
            if (!empty($productData['short_description'])) {
                $productData['short_description'] = $productData['short_description'];
            }
            /**
             *  Assign create at time
             */
            $createdAt = Mage::getModel('core/date')->gmtDate();

            /**
             *  Getting instance for catalog product collection       
             */
            $product = Mage::getModel('catalog/product');
            /**
             *  Initialize product sku 
             */         

            if(isset($productData['sku'])){
                $skuProductId = Mage::getModel('catalog/product')
                ->getIdBySku(trim($productData['sku']));        
            if(!empty($skuProductId)){
                /**
                 *  Error message redirect to create new product page
                 */
                Mage::getSingleton('core/session')->addError($this->__('SKU Not Available'));
                $this->_redirect('marketplace/product/new/');
                return;
            }
            }           


            /**
             *  Initialize product attribute set id
             */
            if (!empty($set)) {
            $product->setAttributeSetId($set);
            }else{           
            $sDefaultAttributeSetId = Mage::getSingleton('eav/config')
                ->getEntityType(Mage_Catalog_Model_Product::ENTITY)
                ->getDefaultAttributeSetId();  
            $product->setAttributeSetId($sDefaultAttributeSetId);
            }    

            /**
             *  Initialize product type
             */
            if (isset($type)) {
                $product->setTypeId($type);
            }


            /**
             *  Initialize product categories
             */
            if (isset($categoryIds)) {
                $product->setCategoryIds($categoryIds);
            }
            $product->setSilktype($silkType);

            /**
             *  Storing product data's to all store view 
             */
            $product->setStoreId(0);

            /**
             *  Initialize product create at time
             */
            if (isset($createdAt)) {
                $product->setCreatedAt($createdAt);
            }
            /**
             *  Initialize seller id  
             */
            if (isset($sellerId)) {
                $product->setSellerId($sellerId);
            }

            /**
             *  Initialize group id  
             */
            if (isset($groupId)) {
                $product->setGroupId($groupId);
            }           

            /**
             * Set is assign product 
             */
            $product->setIsAssignProduct(0);

            $uploadsData = new Zend_File_Transfer_Adapter_Http();
            $filesDataArray = $uploadsData->getFileInfo();

            /**
             *  Checking whether image exist or not    
             */
            if (!empty($filesDataArray)) {
                foreach ($filesDataArray as $key => $value) {
                    /**
                     *  Initilize file name
                     */
                    $filename = $key;

                    if (substr($key, 0, 5) == 'image') {
                        if (isset($filesDataArray[$filename]['name']) && (file_exists($filesDataArray[$filename]['tmp_name']))) {
                            try {
                                $imagesPath[] = Mage::helper('marketplace/marketplace')->uploadImage($filename, $filesDataArray);
                            } catch (Exception $e) {
                                /**
                                 *  Display error message for images upload   
                                 */
                                Mage::getSingleton('core/session')->addError($this->__($e->getMessage()));
                            }
                        }
                    }
                }
            }

            /**
             *  Adding Product images       
             */
            if (!empty($imagesPath)) {
                $product->setMediaGallery(array('images' => array(), 'values' => array()));
                foreach ($imagesPath as $value) {
                    $product->addImageToMediaGallery($value, array('image', 'small_image', 'thumbnail'), false, false);
                }
            }


            /**
             *   Initialize dispatch event for product prepare  
             */
            Mage::dispatchEvent(
                    'catalog_product_prepare_save', array('product' => $product, 'request' => $this->getRequest())
            );         

            /**
             *  Assign configurable product data
             */
            if ($type == 'configurable') {              
                $attributeIds = $this->getRequest()->getPost('attributes');
                $isInStock = 1;
                if(isset($productData['stock_data']['is_in_stock'])){
                    $isInStock = $productData['stock_data']['is_in_stock'];
                }            
                $productData['stock_data'] = array();               
                if(count($attributeIds) >= 1){
                    $attributeIds = array_unique($attributeIds);                
                    $product->getTypeInstance()->setUsedProductAttributeIds($attributeIds);                 
                    $configurableAttributesData = $product->getTypeInstance()->getConfigurableAttributesAsArray();                  
                    $product->setCanSaveConfigurableAttributes(true);
                    $product->setConfigurableAttributesData($configurableAttributesData);
                    $product->setConfigurableProductsData(array());
                }
            }

            /**
             *  Adding data to product instanse
             */
            if (!empty($productData)) {
                $product->addData($productData);
            }
            /**
             *  Saving new product      
             */
            try {
                $product->save();

                if($type == 'configurable'){
                    $stockItem = Mage::getModel('cataloginventory/stock_item');
                    $stockItem->assignProduct($product);
                    $stockItem->setData('stock_id', 1);
                    if(isset($productData['stock_data']['qty'])){
                    $stockItem->setData('qty', $productData['stock_data']['qty']);
                    }else{
                        $stockItem->setData('qty', 0);
                    }
                    $stockItem->setData('use_config_min_qty', 1);
                    $stockItem->setData('use_config_backorders', 1);
                    $stockItem->setData('min_sale_qty', 1);
                    $stockItem->setData('use_config_min_sale_qty', 1);
                    $stockItem->setData('use_config_max_sale_qty', 1);
                    $stockItem->setData('is_in_stock', $isInStock);
                    $stockItem->setData('use_config_notify_stock_qty', 1);
                    $stockItem->setData('manage_stock', 1);
                    $stockItem->save();

                    //This section is what was required.
                    $stockStatus = Mage::getModel('cataloginventory/stock_status');
                    $stockStatus->assignProduct($product);
                    $stockStatus->saveProductStatus($product->getId(), 1);
                }

                $productId = $product->getId();

                /**
                 * Load the product
                 */
                $product = Mage::getModel('catalog/product')->load($productId);
                /**
                 * Get all images
                 */
                $mediaGallery = $product->getMediaGallery();
                /**
                 * If there are images
                 */
                if (isset($mediaGallery['images']) && !empty($store)) {
                    /**
                     * Loop through the images
                     */
                    $increment = 0;
                    foreach ($mediaGallery['images'] as $image) {
                        /**
                         * Set the first image as the base image                       
                         */
                        if($increment == $setbase){                      
                        $product->setStoreId($store)
                                ->setImage($image['file'])
                                ->setSmallImage($image['file'])
                                ->setThumbnail($image['file']);

                            $product->save();
                        } 
                        $increment++;
                        /**
                         * Stop
                         */

                    }

                }

                /**
                 *   Initialize product options                            
                 */
                if (!empty($productData['options'])) {
                    $product->setProductOptions($productData['options']);
                    $product->setCanSaveCustomOptions(1);
                    $product->save();
                }

                /**
                 *  Checking whether image or not
                 */
                if (!empty($imagesPath)) {
                    foreach ($imagesPath as $deleteImage) {
                        /**
                         *  Checking whether image exist or not    
                         */
                        if (file_exists($deleteImage)) {
                            /**
                             *  Delete images from temporary folder      
                             */
                            unlink($deleteImage);
                        }
                    }
                }

                /**
                 *  Function for adding downloadable product sample and link data
                 */
                $downloadProductId = $product->getId();
                if ($type == 'downloadable' && isset($downloadProductId) && isset($store)) {
                    $this->addDownloadableProductData($downloadProductId, $store);
                }

                /**
                 *  Success message redirect to manage product page
                 */
                if (Mage::helper('marketplace')->getProductApproval() == 1) {
                    Mage::getSingleton('core/session')->addSuccess($this->__('Your product is added successfully'));
                      $mail = Mage::getModel('core/email');
            /*$mail = Mage::getModel('core/email');
            $mail->setToName('User');
            $mail->setToEmail('[email protected]');
            $mail->setBody('Send Test mail to you.....');
            $mail->setSubject('Test Mail');
            $mail->setFromEmail('[email protected]');
            $mail->setFromName("Send Test mail to you.....");
            $mail->setType('html');// YOu can use Html or text as Mail format
            $mail->send(); */

            $sellerData = Mage::getSingleton('customer/session')->getCustomer();
    $sellerIdss = $sellerData->getId();
    $seller_mail = $sellerData->getEmail();

        $collectionss = Mage::getModel('followup/followup')->getCollection()
                            ->addFieldToFilter('seller_id', $sellerIdss)
                            ->addFieldToFilter('seller_email', $seller_mail);

        foreach($collectionss as $item){
        $mycustomer_email =  $item->getCustomerEmail();
        $mycustomer_name = $item->getCustomerName();

        $template_id = 'customer_update';        
                     $email_to = $mycustomer_email;
                     $customer_name   = $cus_name;
                     $email_template  = Mage::getModel('core/email_template')->loadDefault($template_id);
                     $custom_variable = $mycustomer_name;
                     //$custom_variable1 = $cus_email;
                     $custom_variable1 = $this->getRequest()->getPost('store_name');
                     $email_template_variables = array(
                        'custom_variable' => $custom_variable,
                        'custom_variable1' => $custom_variable1);
                        //'custom_variable2' => $custom_variable2);
                     $sender_name = Mage::getStoreConfig(Mage_Core_Model_Store::XML_PATH_STORE_STORE_NAME);
                     $sender_email = Mage::getStoreConfig('trans_email/ident_general/email');
                     $email_template->setSenderName($sender_name);
                     $email_template->setSenderEmail($sender_email);
                     $email_template->send($email_to, $customer_name, $email_template_variables);

}

                    if (Mage::getStoreConfig('marketplace/product/addproductemailnotification') == 1) {
                        /**
                         *  Sending email for added new product
                         */
                        $templateId = (int) Mage::getStoreConfig('marketplace/product/addproductemailnotificationtemplate');
                        $adminEmailId = Mage::getStoreConfig('marketplace/marketplace/admin_email_id');
                        $toMailId = Mage::getStoreConfig("trans_email/ident_$adminEmailId/email");
                        $toName = Mage::getStoreConfig("trans_email/ident_$adminEmailId/name");

                        /**
                         *  Selecting template id
                         */
                        if ($templateId) {
                            $emailTemplate = Mage::getModel('core/email_template')->load($templateId);
                        } else {
                            $emailTemplate = Mage::getModel('core/email_template')
                                    ->loadDefault('marketplace_product_addproductemailnotificationtemplate');
                        }
                        $customer = Mage::getModel('customer/customer')->load($sellerId);
                        $selleremail = $customer->getEmail();
                        $recipient = $toMailId;
                        $sellername = $customer->getName();
                        $productname = $product->getName();
                        $producturl = $product->getProductUrl();
                        $emailTemplate->setSenderName($sellername);
                        $emailTemplate->setSenderEmail($selleremail);
                        $emailTemplateVariables = (array('ownername' => $toName, 'sellername' => $sellername, 'selleremail' => $selleremail, 'productname' => $productname, 'producturl' => $producturl));
                        $emailTemplate->setDesignConfig(array('area' => 'frontend'));
                        $processedTemplate = $emailTemplate->getProcessedTemplate($emailTemplateVariables);
                        $emailTemplate->send($recipient, $sellername, $emailTemplateVariables);



                    }
                } else {
                    Mage::getSingleton('core/session')->addSuccess($this->__('Your product is awaiting moderation'));
                     /*$mail = Mage::getModel('core/email');
            $mail->setToName('User');
            $mail->setToEmail('[email protected]');
            $mail->setBody('Send Test mail to you.....');
            $mail->setSubject('Test Mail');
            $mail->setFromEmail('[email protected]');
            $mail->setFromName("Send Test mail to you.....");
            $mail->setType('html');// YOu can use Html or text as Mail format
            $mail->send(); */

            foreach($collectionss as $item){
        $mycustomer_email =  $item->getCustomerEmail();
        $mycustomer_name = $item->getCustomerName();

        $template_id = 'customer_update';        
                     $email_to = $mycustomer_email;
                     $customer_name   = $cus_name;
                     $email_template  = Mage::getModel('core/email_template')->loadDefault($template_id);
                     $custom_variable = $mycustomer_name;
                     //$custom_variable1 = $cus_email;
                     $custom_variable1 = $this->getRequest()->getPost('store_name');
                     $email_template_variables = array(
                        'custom_variable' => $custom_variable,
                        'custom_variable1' => $custom_variable1);
                        //'custom_variable2' => $custom_variable2);
                     $sender_name = Mage::getStoreConfig(Mage_Core_Model_Store::XML_PATH_STORE_STORE_NAME);
                     $sender_email = Mage::getStoreConfig('trans_email/ident_general/email');
                     $email_template->setSenderName($sender_name);
                     $email_template->setSenderEmail($sender_email);
                     $email_template->send($email_to, $customer_name, $email_template_variables);

}

                    if (Mage::getStoreConfig('marketplace/product/addproductemailnotification') == 1) {
                        /**
                         *  Sending email for added new product
                         */
                        $templateId = (int) Mage::getStoreConfig('marketplace/product/addproductapprovalemailnotificationtemplate');
                        $adminEmailId = Mage::getStoreConfig('marketplace/marketplace/admin_email_id');
                        $toMailId = Mage::getStoreConfig("trans_email/ident_$adminEmailId/email");
                        $toName = Mage::getStoreConfig("trans_email/ident_$adminEmailId/name");

                        if ($templateId) {
                            $emailTemplate = Mage::getModel('core/email_template')->load($templateId);
                        } else {
                            $emailTemplate = Mage::getModel('core/email_template')
                                    ->loadDefault('marketplace_product_addproductapprovalemailnotificationtemplate');
                        }
                        $customer = Mage::getModel('customer/customer')->load($sellerId);
                        $selleremail = $customer->getEmail();
                        $recipient = $toMailId;
                        $sellername = $customer->getName();
                        $productname = $product->getName();
                        $producturl = Mage::helper('adminhtml')->getUrl('adminhtml/catalog_product/edit', array('id' => $product->getId()));

                        $emailTemplate->setSenderName($sellername);
                        $emailTemplate->setSenderEmail($selleremail);
                        $emailTemplateVariables = (array('ownername' => $toName, 'sellername' => $sellername, 'selleremail' => $selleremail, 'productname' => $productname, 'producturl' => $producturl));
                        $emailTemplate->setDesignConfig(array('area' => 'frontend'));
                        $processedTemplate = $emailTemplate->getProcessedTemplate($emailTemplateVariables);
                        $emailTemplate->send($recipient, $sellername, $emailTemplateVariables);


                    }
                }

                if($type == 'configurable'){                
                $this->_redirect('marketplace/product/configurable/',array('id'=>$productId,'set'=>$set));
                return;
                }                

                $this->_redirect('marketplace/product/manage/');
            } catch (Mage_Core_Exception $e) {
                /**
                 *  Error message redirect to create new product page
                 */
                Mage::getSingleton('core/session')->addError($this->__($e->getMessage()));          
                $this->_redirect('marketplace/product/create/');
            } catch (Exception $e) {
                /**
                 *  Error message redirect to create new product page
                 */
                Mage::getSingleton('core/session')->addError($this->__($e->getMessage()));
                $this->_redirect('marketplace/product/create/');
            }
        } else {
            Mage::getSingleton('core/session')->addError($this->__('Please enter all required fields'));
            if($type == 'configurable'){
                $this->_redirect('marketplace/product/selectattributes/',array('set'=>$set));
                return;
            }
            $this->_redirect('marketplace/product/new');
        }
    }

observer.php

 public function mailme()
    {
        $fromDate = date('Y-m-d H:i:s', strtotime(date('Y-m-d', strtotime(date('Y-m-d') .' -1 day'))));
        $toDate = date('Y-m-d H:i:s', strtotime(date('Y-m-d')));
        $collection = $this->getCollectionWithDates($fromDate, $toDate);
if ($collection->getSize() > 0) {

$sellerData = Mage::getSingleton('customer/session')->getCustomer();
    $sellerIdss = $sellerData->getId();
    $seller_mail = $sellerData->getEmail();
        $collectionss = Mage::getModel('followup/followup')->getCollection()
                            ->addFieldToFilter('seller_id', $sellerIdss)
                            ->addFieldToFilter('seller_email', $seller_mail);
        foreach($collectionss as $item){
        $mycustomer_email =  $item->getCustomerEmail();
        $mycustomer_name = $item->getCustomerName();
        $template_id = 'customer_update';        
                     $email_to = $mycustomer_email;
                     $customer_name   = $cus_name;
                     $email_template  = Mage::getModel('core/email_template')->loadDefault($template_id);
                     $custom_variable = $mycustomer_name;
                     //$custom_variable1 = $cus_email;
                     $custom_variable1 = $this->getRequest()->getPost('store_name');
                     $email_template_variables = array(
                        'custom_variable' => $custom_variable,
                        'custom_variable1' => $custom_variable1);
                        //'custom_variable2' => $custom_variable2);
                     $sender_name = Mage::getStoreConfig(Mage_Core_Model_Store::XML_PATH_STORE_STORE_NAME);
                     $sender_email = Mage::getStoreConfig('trans_email/ident_general/email');
                     $email_template->setSenderName($sender_name);
                     $email_template->setSenderEmail($sender_email);
                     $email_template->send($email_to, $customer_name, $email_template_variables);

}

}
return $this;
}

public function getCollectionWithDates($fromDate, $toDate)
    {
        $collection = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect('*')
        ->addWebsiteFilter(4);
        $collection->addAttributeToFilter('share_mss', array('eq' => 1));//"2016-08-01 00:00:00" example format
        $collection->addAttributeToFilter('updated_at', array('gteq' => $fromDate));//"2016-08-01 00:00:00" example format
        //$collection->addAttributeToFilter('created_at', array('lteq' => $toDate));
        $collection->addAttributeToFilter(
                        'status',
                        array('eq' => Mage_Catalog_Model_Product_Status::STATUS_ENABLED));
        return $collection;
    }

config.xml

<marketplace_mailme>
               <schedule><cron_expr>*/5 * * * *</cron_expr></schedule>
               <run><model>marketplace/observer::mailme</model></run>
        </marketplace_mailme>

1 Answer 1

1

You can set your cron job to execute once in a day for example mid night 11PM.

In your newpost function

  1. Take the current time that means 11PM.

  2. Check the product created datetime.

  3. Load/select obnly those product create before one day(it means product should be created yesterday after 11PM).

  4. So now you have list of product which were created in 24 hours.

  5. Every day at 11PM you corn will execute and send the email regarding products created in 24 hours.

What you say!!

Edit This sets your cron jobs. whcih execute your observer and mailme function

<global>
        <models>
            <namespace_mycron>
                <class>Namespace_Mycron_Model</class>
            </namespace_mycron>
        </models>
    </global>
    <crontab>
        <jobs>
            <namespace_mycron_send>
                <schedule><cron_expr>0 0 * * *</cron_expr></schedule>
                <run><model>namespace_mycron/observer::mailme</model></run>
            </namespace_mycron_send>
        </jobs>
    </crontab>

your observer function in model

<?php
class Namespace_Mycron_Model_Observer extends Varien_Event_Observer
{
    public function mailme()
    {
        $fromDate = date('Y-m-d H:i:s', strtotime(date('Y-m-d', strtotime(date('Y-m-d') .' -1 day'))));
        $toDate = date('Y-m-d H:i:s', strtotime(date('Y-m-d')));
        $collection = $this->getCollectionWithDates($fromDate, $toDate);
if ($collection->getSize() > 0) {
//send your email
}
return $this;
}

public function getCollectionWithDates($fromDate, $toDate)
    {
        $collection = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect('*')
        ->addWebsiteFilter(4);
        $collection->addAttributeToFilter('share_mss', array('eq' => 1));//"2016-08-01 00:00:00" example format
        $collection->addAttributeToFilter('updated_at', array('gteq' => $fromDate));//"2016-08-01 00:00:00" example format
        //$collection->addAttributeToFilter('created_at', array('lteq' => $toDate));
        $collection->addAttributeToFilter(
                        'status',
                        array('eq' => Mage_Catalog_Model_Product_Status::STATUS_ENABLED));
        return $collection;
    }
}
11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.