Cron Job To Disable Product Magento 1.7 CE - magento-1.7

How do I set up a cron job in magento step by step. If I have a attribute that has a set date, i want the cron job to disable the product if the day has past...

1) Create a custom Module, there's many guides to this out there - or use a Module Creator to get your started.
2) Added Cron job setup to your modules config
config.xml
...
<crontab>
<jobs>
<mymodule_disable>
<schedule>
<!-- every 10 min -->
<cron_expr>*/10 * * * *</cron_expr>
</schedule>
<run>
<model>mymodule/Scheduler::disable</model>
</run>
</mymodule_disable>
</jobs>
</crontab>
</config>
Now Create an class to handle the task for you (modulename/Model/Scheduler.php)
Scheduler.php
<?php
class Mymodule_Model_Scheduler
{
/**
* Disable prodcuts for us
*/
public static function disable()
{
// This will be run every 10 minutes, we want to get applicable products
// you will need to customize the filter for what you need, subtracting
// or adding date values etc.. you get the idea :)
$date = Mage::getModel('core/date')->gmtDate(); // add/subtract etc
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addfieldtofilter('custom_date_attr', array(
array('to' => $date),
//array('gteq' => $date)
));
foreach($collection as $product) {
$product->setStatus(Mage_Catalog_Model_Product_Status::STATUS_DISABLED);
$product->save();
}
}
}
Now you need to setup a cron job to run Magentos Scheduler, example:
*/10 * * * * php -f /path/to/magento/cron.php

Related

Override magento 2 block ../module_sales/block/adminhtml/totals.php

I am trying to override magento block but everytime main block from vendor is executed. No errors are shown.
Magento block:
vendor/magento/module_sales/block/adminhtml/totals.php
Created block in custom module:
[vendor]/[module]/block/adminhtml/totals.php
Modified di.xml file in:
[vendor]/[module]/etc/di.xml
Preference in di.xml file:
...
<preference for="Magento\Sales\Block\Adminhtml\Totals"
type="Iways\Sales\Block\Adminhtml\Totals" />
...
Content of block in custom module:
namespace Iways\Sales\Block\Adminhtml;
use Magento\Framework\DataObject;
use Magento\Sales\Block\Adminhtml\Totals as DefaultTotals;
class Totals extends DefaultTotals
{
...
I have tried to check if file is executed with xdebug but it isnt.
If you override a block, you also want to add a sequence in your module.xml. You have to make sure the module of the block you want to override is being loaded before your module is being loaded. See Component load order. Add the module Magento_Sales to your sequence.
If that doesn't work:
Are you sure your module is registered by Magento, can you find your module in `app/etc/config.php'?
Are you sure there's no other module which overrides that block already?
The block that I was trying to extend has already been extended by another block in:
module_sales/block/adminhtml/order/totals.php
So in general, all I needed to do is to extend that block mentioned above.
Posting this solution for Magento v-2.3.5
Override this class \Magento\Sales\Block\Adminhtml\Order\Totals
app/code/Taktheer/ExtendCoupanTotals/etc/di.xml
<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Magento\Sales\Block\Adminhtml\Order\Totals" type="Taktheer\ExtendCoupanTotals\Rewrite\Magento\Sales\Block\Adminhtml\Order\Totals"/>
</config>
app/code/Taktheer/ExtendCoupanTotals/Rewrite/Magento/Sales/Block/Adminhtml/Order/Totals.php
<?php
/**
* Copyright © Unyscape Infocom Pvt. Ltd. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Taktheer\ExtendCoupanTotals\Rewrite\Magento\Sales\Block\Adminhtml\Order;
class Totals extends \Magento\Sales\Block\Adminhtml\Order\Totals
{
/**
* Initialize order totals array
*
* #return $this
*/
protected function _initTotals()
{
parent::_initTotals();
$order = $this->getSource();
if ($order->getCouponCode()) {
$discountLabel = __('Discount (%1)', $order->getCouponCode());
} else {
$discountLabel = __('Discount');
}
$this->_totals['discount'] = new \Magento\Framework\DataObject(
[
'code' => 'discount',
'value' => $order->getDiscountAmount(),
'base_value' => $order->getBaseDiscountAmount(),
'label' => $discountLabel,
]
);
return $this;
}
}
======================== Happy Coding =============================

Make Laravel use database Queue instead of sync

I need help with Laravel Queues if someone can help me further, i have done these steps till now
changed the QUEUE DRIVER in .env file to database
created migrations for queue table jobs and failed-jobs
php artisan queue:table
php artisan queue:failed-table
and i have run php artisan migrate
created a new Job
php artisan make:job SendNewArticleNotification
Update:
Ok i have created a route /queue
Route::get('/queue', function () {
dispatch(new \App\Jobs\SendNewArticleNotification);
});
and in my Job SendNewArticleNotification i have this
<?php
namespace App\Jobs;
use App\User;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class SendNewArticleNotification implements ShouldQueue
{
use InteractsWithQueue, Queueable, SerializesModels;
/**
* Create a new job instance.
*
* #return void
*/
public function __construct()
{
//
}
/**
* Execute the job.
*
* #return void
*/
public function handle()
{
$users = User::all();
$article = \App\Article::first();
foreach ($users as $user) {
$user->notify(new \App\Notifications\Published($article));
}
}
}
And when i hit my /queue route the emails are beeing sent but they are not using the database table....it takes more than 30 seconds to send 50 mails...
UPDATE
Ok i finally figured it out that dispatch() needs to be inside of a controller method because the controller has the trait dispatches jobs....and now my jobs are in queue in DB table jobs....so how do i trigger them behind the scenes?
Put your dispatch in your controller method and then run
php artisan queue:work

How to write Monolog logs into a file AND remote database

I have a Symfony2 -project and it writes the logs into different files beautifully, but I would like it to write the logs into a remote database(mongodb) as well. I would like to keep the actual log files in the servers as a backup in case something goes wrong with the database connection.
Question 1:
Is it even possible to save the same logs into two different places at the same time?
Question 2:
How do I save the logs into the mongodb? I don't necessarily need specific mongodb-instructions, but some guidelines on how to write into a remote db with monologger. The mongodb-specific instructions are also welcome if available. ;)
Question 3(OPTIONAL):
Can I get a full error stack into the logs somehow? Where could one find a full list of what data the Monolog can actually write and how to write?
There was a very good Blogpost sometime back for logging to a mysql database with monolog and doctrine. I can't find it anymore so i will just add the neccessary Files here and you can adjust it.
The whole logic is done in the DatabaseHandler so you can just change from
mysql inserts to a handling for your mongodb.
This code is not mine if anyone knows the original post please comment.
BacktraceLoggerListener.php
namespace UtilsBundle\EventListener;
use Symfony\Component\HttpKernel\Log\LoggerInterface;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
class BacktraceLoggerListener{
private $_logger;
public function __construct(LoggerInterface $logger = null)
{
$this->_logger = $logger;
}
public function onKernelException(GetResponseForExceptionEvent $event)
{
$this->_logger->addError($event->getException());
}
}
DatabaseHandler.php
namespace UtilsBundle\Logger;
use Monolog\Handler\AbstractProcessingHandler;
use Monolog\Logger;
/**
* Stores to database
*
*/
class DatabaseHandler extends AbstractProcessingHandler{
protected $_container;
/**
* #param string $stream
* #param integer $level The minimum logging level at which this handler will be triggered
* #param Boolean $bubble Whether the messages that are handled can bubble up the stack or not
*/
public function __construct($level = Logger::DEBUG, $bubble = true)
{
parent::__construct($level, $bubble);
}
/**
*
* #param type $container
*/
public function setContainer($container)
{
$this->_container = $container;
}
/**
* {#inheritdoc}
*/
protected function write(array $record)
{
// Ensure the doctrine channel is ignored (unless its greater than a warning error), otherwise you will create an infinite loop, as doctrine like to log.. a lot..
if( 'doctrine' == $record['channel'] ) {
if( (int)$record['level'] >= Logger::WARNING ) {
error_log($record['message']);
}
return;
}
// Only log errors greater than a warning
// TODO - you could ideally add this into configuration variable
if( (int)$record['level'] >= Logger::NOTICE ) {
try
{
// Logs are inserted as separate SQL statements, separate to the current transactions that may exist within the entity manager.
$em = $this->_container->get('doctrine')->getManager();
$conn = $em->getConnection();
$created = date('Y-m-d H:i:s');
$serverData = ""; //$record['extra']['server_data'];
$referer = "";
if (isset($_SERVER['HTTP_REFERER'])){
$referer= $_SERVER['HTTP_REFERER'];
}
$stmt = $em->getConnection()->prepare('INSERT INTO system_log(log, level, server_data, modified, created)
VALUES(' . $conn->quote($record['message']) . ', \'' . $record['level'] . '\', ' . $conn->quote($referer) . ', \'' . $created . '\', \'' . $created . '\');');
$stmt->execute();
} catch( \Exception $e ) {
// Fallback to just writing to php error logs if something really bad happens
error_log($record['message']);
error_log($e->getMessage());
}
}
}
}
We used xml here but this can be done in
services.yml too
services.xml
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
<services>
<service id="utils.database.logger" class="UtilsBundle\Logger\DatabaseHandler">
<call method="setContainer">
<argument type="service" id="service_container" />
</call>
</service>
<service id="utils.backtrace.logger.listener" class="UtilsBundle\EventListener\BacktraceLoggerListener">
<argument type="service" id="logger" />
<tag name="monolog.logger" channel="backtrace" />
<tag name="kernel.event_listener" event="kernel.exception" method="onKernelException" />
</service>
</services>
And lastly add the handler to your monolog config in
config_**.yml so here for production for example
config_prod.yml
monolog:
handlers:
main:
type: rotating_file
action_level: error
max_files: 10
handler: nested
nested:
type: stream
path: "%kernel.logs_dir%/%kernel.environment%.log"
level: debug
console:
type: console
database:
type: service
level: notice
id: utils.database.logger
channels: ["!translation"]
Hope that helps
Hope I can some things up for you:
Question 1: Yes its possible. E.G. you can do smt. like:
$this->logger->pushHandler(new StreamHandler('/path/to/logs/123_info.log', Logger::INFO));
$this->logger->pushHandler(new StreamHandler('/path/to/logs/456_warning.log', Logger::INFO));
So if $this->logger->addInfo("testinfo"); this is getting logged in both streams.
Question 2: There is a MongoDBHandler as according to the StreamHandler. You should be able do configure it and pass it along to the pushHandler method or if you want to have it in your services look at MongoDBConfiguration.
Question 3:
This should help: Configure Monolog
Hope that helps.

Typo3 - Extbase CommandController for scheduler task

i ve created an empty extbase/fluid extension and added an ImportCommandController for a scheduler task. For some reason i am not able to load that task in my scheduler. Please note that i want to realise my task via CommandController (http://wiki.typo3.org/CommandController_In_Scheduler_Task) and NOT via \TYPO3\CMS\Scheduler\Task\AbstractTask.
ext_localconf.php
<?php
if (!defined('TYPO3_MODE')) {
die('Access denied.');
}
$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['extbase']['commandControllers'][] = 'VENDORx\\Sched\\Command\\ImportCommandController';
Classes/Command/ImportCommandController.php
<?php
namespace VENDORx\Sched\Command;
/**
*
*
* #package Sched
* #license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3 or later
*
*/
class ImportCommandController extends \TYPO3\CMS\Extbase\Mvc\Controller\CommandController {
public function importCommand($commandIdentifier= NULL) {
echo 'command run';
}
}
?>
any idea whats missing??
As Jost already mentioned you neet proper Annotations:
/**
* #param integer $commandIdentifier
*/
public function importCommand($commandIdentifier = NULL) {
$this->outputLine('command run');
}
Select "Extbase-CommandController-Task" in dropdown
You'll get another select field on the bottom where you can find your "ImportCommand" select and save

Magento 1.9 Wrong customer created and last login dates

I am running Magento v.1.9.0.1 and I am facing a problem with the dates displayed when editing a customer via the admin area. For example,
Last Logged In: 11 Feb 7791 4:23:48 μ.μ.
Last Logged In (Europe/Istanbul): 09 Feb 2015 3:16:31 μ.μ.
Account Created on: 02 Sep 2015 4:16:11 μ.μ.
The client registered on the 9th of February 2015. I searched around and found topics about other Magento versions that said for some dates Magento is swapping the dates, hence the difference between actual created date (09/02/2015) and reported created date (02/09/2015).
I couldn't find anything about version 1.9 nor anything about the year reported for last logged in (7791!).
Is there a fix for this problem?
Thank you for your time.
Faced same issue in Magento 1.8.1 , and applied below solution for account created date and last login date.Because some how Magento is converting day to month and month to date in customer edit section.
Path : app\code\core\Mage\Adminhtml\Block\Customer\Edit\Tab\View.php
Override below methods from above file :
public function getCreateDate()
{
$cutomerId = $this->getRequest()->getParam('id');
$connection = Mage::getSingleton('core/resource')->getConnection('core_read');
$select = $connection->select()
->from('customer_entity', array('created_at'))
->where('entity_id=?',$cutomerId);
$rowArray = $connection->fetchRow($select);
return $this->_getCoreHelper()->formatDate($rowArray['created_at'],
Mage_Core_Model_Locale::FORMAT_TYPE_MEDIUM, true);
}
public function getStoreCreateDate()
{
$cutomerId = $this->getRequest()->getParam('id');
$connection = Mage::getSingleton('core/resource')->getConnection('core_read');
$select = $connection->select()
->from('customer_entity', array('created_at'))
->where('entity_id=?',$cutomerId);
$rowArray = $connection->fetchRow($select);
return $this->_getCoreHelper()->formatDate($rowArray['created_at'],
Mage_Core_Model_Locale::FORMAT_TYPE_MEDIUM, true);
}
public function getLastLoginDate()
{
if ($date = $this->getCustomerLog()->getLoginAtTimestamp()) {
$date = Mage::app()->getLocale()->storeDate(
$this->getCustomer()->getStoreId(),
$date,
true
);
return $this->formatDate($date, Mage_Core_Model_Locale::FORMAT_TYPE_MEDIUM, true);
}
return Mage::helper('customer')->__('Never');
}
I have also faced the same issue for quite a long time till i found the solution http://www.customerparadigm.com/magento-bug-magento-customer-create-date-juxtaposition/
Summary of the files in the Magento Extension for solving the Magento Date Switch Fix:
Created.php:
app/code/local/CustomerParadigm/Datefix/Model/Entity/Attribute/Backend/Time/Created.php
<?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license#magento.com so we can send you a copy immediately.
*
// * DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magento.com for more information.
*
* #category Mage
* #package Mage_Eav
* #copyright Copyright (c) 2006-2015 X.commerce, Inc. (http://www.magento.com)
* #license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/**
* Entity/Attribute/Model - attribute backend default
*
* #category Mage
* #package Mage_Eav
* #author Magento Core Team <core#magentocommerce.com>
*/
class CustomerParadigm_Datefix_Model_Entity_Attribute_Backend_Time_Created extends Mage_Eav_Model_Entity_Attribute_Backend_Time_Created
{
/**
* Returns date format if it matches a certain mask.
* #param $date
* #return null|string
*/
/* This shouldn't be needed for the datetime switch bug fix. Removing for testing.
protected function _getFormat($date)
{
if (is_string($date) && preg_match('#^\d{4,4}-\d{2,2}-\d{2,2} \d{2,2}:\d{2,2}:\d{2,2}$#', $date)) {
return 'yyyy-MM-dd HH:mm:ss';
}
return null;
}
*/
/**
* Set created date
* Set created date in UTC time zone
*
* #param Mage_Core_Model_Object $object
* #return Mage_Eav_Model_Entity_Attribute_Backend_Time_Created
*/
public function beforeSave($object)
{
$attributeCode = $this->getAttribute()->getAttributeCode();
$date = $object->getData($attributeCode);
if (is_null($date)) {
if ($object->isObjectNew()) {
$object->setData($attributeCode, Varien_Date::now());
}
} else {
// Date switch fix
$date = strtotime($date);
// convert to UTC
$zendDate = Mage::app()->getLocale()->utcDate(null, $date, true);
$object->setData($attributeCode, $zendDate->getIso());
}
return $this;
}
/**
* Convert create date from UTC to current store time zone
*
* #param Varien_Object $object
* #return Mage_Eav_Model_Entity_Attribute_Backend_Time_Created
*/
public function afterLoad($object)
{
$attributeCode = $this->getAttribute()->getAttributeCode();
$date = $object->getData($attributeCode);
// Date switch fix
if (!is_null($date)) {
$date = strtotime($date);
}
$zendDate = Mage::app()->getLocale()->storeDate(null, $date, true);
$object->setData($attributeCode, $zendDate->getIso());
parent::afterLoad($object);
return $this;
}
}
app/code/local/CustomerParadigm/Datefix/etc/config.xml
<config>
<global>
<models>
<eav>
<rewrite>
<entity_attribute_backend_time_created>CustomerParadigm_Datefix_Model_Entity_Attribute_Backend_Time_Created</entity_attribute_backend_time_created>
</rewrite>
</eav>
</models>
</global>
</config>
/app/etc/module/ CustomerParadigm_Datefix.xml
<?xml version=”1.0″?>
<config>
<modules>
<CustomerParadigm_Datefix>
<active>true</active>
<codePool>local</codePool>
</CustomerParadigm_Datefix>
</modules>
</config>
I am not having much reputation to comment, so pointing out through a response:
#Digisha: You have mentioned this for getLastLoginDate()
public function getLastLoginDate()
{
if ($date = $this->getCustomerLog()->getLoginAtTimestamp()) {
$date = Mage::app()->getLocale()->storeDate(
$this->getCustomer()->getStoreId(),
$date,
true
);
return $this->formatDate($date, Mage_Core_Model_Locale::FORMAT_TYPE_MEDIUM, true);
}
return Mage::helper('customer')->__('Never');
}
I just want to ask if this is correct parameter for if condition:
if ($date = $this->getCustomerLog()->getLoginAtTimestamp())
I don't think so, you are assinging and then how is this correct??