I'm trying to trigger push notifications and emails in the background of my Lumen API. I created the WarningUser class that creates both queues:
<?php
namespace App\Utils;
use App\Jobs\ProcessNotification;
use App\Mail\AllMail;
use Illuminate\Support\Facades\Mail;
class WarningUser
{
public static function send($user, $message, $url, $data = [])
{
$url = env('APP_URL_FRONT') . $url;
dispatch(new ProcessNotification($user, $data, $message, $url));
$emailData = EmailTexts::texts('pt', $data)[$message];
Mail::to($user->email)->queue(new AllMail($emailData['title'], $emailData['content']));
return true;
}
}
First we have the ProcessNotification job, which connects to Firebase and sends the notification:
<?php
namespace App\Jobs;
use Kreait\Firebase\Factory;
use Kreait\Firebase\Messaging\Notification;
use Kreait\Firebase\Messaging\CloudMessage;
class ProcessNotification extends Job
{
protected $user = null;
protected $data = null;
protected $message = null;
protected $url = null;
public function __construct($user, $data, $message, $url)
{
$this->user = $user;
$this->data = $data;
$this->message = $message;
$this->url = $url;
}
public function handle()
{
if (\is_string($this->user->token) and $this->user->token !== '') {
$messaging = (new Factory())
->withServiceAccount(__DIR__.'/../../private-key.json')
->createMessaging();
$notificationData = NotificationTexts::texts('pt', $this->data)[$this->message];
$messageAlert = CloudMessage::withTarget('token', $this->user->token)
->withNotification(Notification::create($notificationData['title'], $notificationData['content']))
->withData([ 'url' => $this->url ]);
$messaging->send($messageAlert);
}
}
}
And finally AllMail that sends a simple email:
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class AllMail extends Mailable implements ShouldQueue
{
use Queueable, SerializesModels;
protected $title;
protected $body;
public function __construct($title, $body)
{
$this->title = $title;
$this->body = $body;
}
public function build()
{
return $this
->subject($this->title)
->view('email')
->with([
'title' => $this->title,
'body' => $this->body
]);
}
}
I've tested both codes without using queues, and they work, but when I put the queue it stops working. The processes are recorded in my database (mongodb):
But the queue is never processed, I tried to execute php artisan queue: work andphp artisan queue: listen, but neither case works.
The queue is never attempted to be processed, nor does it go to the failed_jobs table
My config / queue.php is as follows. And my .env is with QUEUE_CONNECTION = database
<?php
return [
'default' => env('QUEUE_CONNECTION', 'database'),
'connections' => [
'sync' => [
'driver' => 'sync',
],
'database' => [
'driver' => 'database',
'table' => 'jobs',
'queue' => 'default',
'retry_after' => 90,
],
'beanstalkd' => [
'driver' => 'beanstalkd',
'host' => 'localhost',
'queue' => 'default',
'retry_after' => 90,
'block_for' => 0,
],
'sqs' => [
'driver' => 'sqs',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'),
'queue' => env('SQS_QUEUE', 'your-queue-name'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
],
'redis' => [
'driver' => 'redis',
'connection' => 'default',
'queue' => env('REDIS_QUEUE', 'default'),
'retry_after' => 90,
'block_for' => null,
],
],
'failed' => [
'driver' => env('QUEUE_FAILED_DRIVER', 'database'),
'database' => env('DB_CONNECTION', 'mongodb'),
'table' => 'failed_jobs',
],
];
Can someone help me? I no longer know what the error may be.
PS: At no time is a browser or console error displayed
I managed to solve, for Mongo we need to use some more settings:
The connection in queue.php must be:
'connections' => [
'database' => [
'driver' => 'mongodb',
'table' => 'jobs',
'queue' => 'default',
'expire' => 60,
],
...
And we need to register the package provider that works with mongo:
Jenssegers\Mongodb\MongodbQueueServiceProvider::class,
Related
I am having trouble with a simple form. I am quite sure that I miss some critical info about this topic...
I created a custom module, I created a custom form
<?php
class modulename_History_Block_Adminhtml_History_Edit_Form extends Mage_Adminhtml_Block_Widget_Form {
protected function _prepareForm()
{
$form = new Varien_Data_Form(array(
'id' => 'edit_form',
'name' => 'edit_form',
'action' => $this->getUrl('*/*/history', array('id' => 'orders_export')),
'method' => 'post',
'enctype' => 'multipart/form-data',
'data' =>'somethingsomethingdarkaside'
));
$this->setForm($form);
$fieldset = $form->addFieldset('Filtrování objednávek', array('legend'=> 'Nastavte filtr pro report objednávek'));
$dateTimeFormatIso = Mage::app()->getLocale()->getDateTimeFormat(Mage_Core_Model_Locale::FORMAT_TYPE_SHORT);
$fieldset->addField('date_from', 'date', array(
'label' => 'Změna statusu objednávek od:',
'title' => 'Změna statusu objednávek od:',
'time' => true,
'name' => 'filter_date_from',
'image' => $this->getSkinUrl('images/grid-cal.gif'),
'format' => $dateTimeFormatIso,
'required' => true,
));
$fieldset->addField('export_history_order_status_changed', 'button', array(
'label' => 'Exportovat do souboru:',
'value' => 'Export',
'name' => 'export_history_order_status_changed',
'class' => 'form-button',
'onclick' => "setLocation('{$this->getUrl('*/*/export')}')",
));
$form->setUseContainer(true);
return parent::_prepareForm();
}
And then there is a controller. When the button is pressed, it goes to the correct controller to a correct action. However no data in post received:
<?php
class modulename_History_Adminhtml_History_HistoryController extends Mage_Adminhtml_Controller_Action {
protected function _initAction()
{
return $this;
}
/**
* A page with the form, creating the block with it.
*
*/
public function editAction()
{
$this->_title('Historie objednavky')
->loadLayout()
->_setActiveMenu('modulename/historymenu');
$this->_addContent($this->getLayout()->createBlock('modulename_history/adminhtml_history_edit'));
$this->renderLayout();
}
/**
* A main entrance - when the filter is set and the "export" button pressed then this is the function which starts.
*
* #return bool|Mage_Core_Controller_Varien_Action - either we return a downloadable file or we return false.
*/
public function exportAction()
{
if ($this->_setParameters())
{
if ($this->_setOrdersIds())
{
return $this->_getDownloadFile();
}
}
return false;
}
/**
* Try to get parameters from the admin form. If all correct then we return true. If there is something not set
* then we are unable to continue and we return false.
*
* #return bool - either we were successful with getting the parameters or not.
*/
protected function _setParameters()
{
$parameters = $this->getRequest()->getParams();
$pokus = $this->getRequest()->getPost();
$necf = $this->getRequest()->getPost('edit_form');
$neco = Mage::app()->getRequest()->getParam('edit_form');
}
}
Hellou,
so a competent colleque find an answer within minutes. I mean it was as silly as expected, just remove on click action on button and set the heading from the button to the form. And changed the button to submit. I quess the guy I copied the code from used some other spells of high magic so it worked for him. I hope this will help. Correct form below:
<?php
class modulename_History_Block_Adminhtml_History_Edit_Form extends
Mage_Adminhtml_Block_Widget_Form {
protected function _prepareForm()
{
$form = new Varien_Data_Form(array(
'id' => 'edit_form',
'name' => 'edit_form',
//'action' => $this->getUrl('*/*/history', array('id' => 'orders_export')),
'action' => $this->getUrl('*/*/export', array('id' => 'orders_export')),
'method' => 'post',
'enctype' => 'multipart/form-data',
'data' =>'somethingsomethingdarkaside'
));
$this->setForm($form);
$fieldset = $form->addFieldset('Filtrování objednávek', array('legend'=> 'Nastavte filtr pro report objednávek'));
$dateTimeFormatIso = Mage::app()->getLocale()->getDateTimeFormat(Mage_Core_Model_Locale::FORMAT_TYPE_SHORT);
$fieldset->addField('date_from', 'date', array(
'label' => 'Změna statusu objednávek od:',
'title' => 'Změna statusu objednávek od:',
'time' => true,
'name' => 'filter_date_from',
'image' => $this->getSkinUrl('images/grid-cal.gif'),
'format' => $dateTimeFormatIso,
'required' => true,
));
$fieldset->addField('export_history_order_status_changed', 'submit', array(
'label' => 'Exportovat do souboru:',
'value' => 'Export',
'name' => 'export_history_order_status_changed',
'class' => 'form-button',
//'onclick' => "setLocation('{$this->getUrl('*/*/export')}')",
));
$form->setUseContainer(true);
return parent::_prepareForm();
}
I'm trying to connect a postgres db but I get this error
my database.php file I have the default connection too add
$db['newdb'] = array(
'dsn' => 'pgsql:host=192.xxx.x.xxx;port=5432;dbname=dbname',
'hostname' => 'localhost',
'username' => 'username',
'password' => 'password',
'database' => 'dbname',
'dbdriver' => 'pgsql',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
here my modal
<?php
class Model extends CI_Model {
private $db_b;
function __construct(){
$this->db_b = $this->load->database('newdb', TRUE);
}
public function getData()
{
$this->db_b->order_by('ad_reference_id', 'asc');
$query = $this->db_b->get('table');
if ($query->num_rows() > 0) {
return $query->result();
} else {
return false;
}
}
}
I got this ERROR
An Error Was Encountered
Invalid DB driver
Why is it not working? :(
You have designated a driver that does not exist with this
'dbdriver' => 'pgsql',
I think what you want is
'dbdriver' => 'postgre',
Edit: Checking PHP configuration
Create a controller called Info.php
Here's the code for it.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Info extends CI_Controller
{
public function index()
{
phpinfo();
}
}
Direct the browser to yoursite.com/info and search the resulting page for postgres.
I have a plugin that i want to modify functionality of a method within specific class in Magento 2 however am not quite sure on how to access the original object and return the modified data.
Original Method
protected function _initTotals()
{
$source = $this->getSource();
$this->_totals = [];
$this->_totals['subtotal'] = new \Magento\Framework\DataObject(
['code' => 'subtotal', 'value' => $source->getSubtotal(), 'label' => __('Subtotal')]
);
/**
* Add shipping
*/
if (!$source->getIsVirtual() && ((double)$source->getShippingAmount() || $source->getShippingDescription())) {
$this->_totals['shipping'] = new \Magento\Framework\DataObject(
[
'code' => 'shipping',
'field' => 'shipping_amount',
'value' => $this->getSource()->getShippingAmount(),
'label' => __('Shipping & Handling'),
]
);
}
/**
* Add discount
*/
if ((double)$this->getSource()->getDiscountAmount()) {
if ($this->getSource()->getDiscountDescription()) {
$discountLabel = __('Discount (%1)', $source->getDiscountDescription());
} else {
$discountLabel = __('Discount');
}
$this->_totals['discount'] = new \Magento\Framework\DataObject(
[
'code' => 'discount',
'field' => 'discount_amount',
'value' => $source->getDiscountAmount(),
'label' => $discountLabel,
]
);
}
$this->_totals['grand_total'] = new \Magento\Framework\DataObject(
[
'code' => 'grand_total',
'field' => 'grand_total',
'strong' => true,
'value' => $source->getGrandTotal(),
'label' => __('Grand Total'),
]
);
/**
* Base grandtotal
*/
if ($this->getOrder()->isCurrencyDifferent()) {
$this->_totals['base_grandtotal'] = new \Magento\Framework\DataObject(
[
'code' => 'base_grandtotal',
'value' => $this->getOrder()->formatBasePrice($source->getBaseGrandTotal()),
'label' => __('Grand Total to be Charged'),
'is_formated' => true,
]
);
}
return $this;
}
This i have set to have a plugin to modify functionality of method above with di.xml:
<type name="Magento\Sales\Block\Order\Totals">
<plugin disabled="false" name="Harrigo_EverDiscountLabel_Plugin_Magento_Sales_Block_Order_Totals" sortOrder="10" type="Harrigo\EverDiscountLabel\Plugin\Magento\Sales\Block\Order\Totals"/>
</type>
Plugin
class Totals
{
public function after_initTotals(
\Magento\Sales\Block\Order\Totals $subject,
$result
) {
if ((double)$subject->getSource()->getDiscountAmount() != 0 OR $subject->getSource()->getDiscountDescription() != null) {
if ($subject->getSource()->getDiscountDescription()) {
$discountLabel = __('Offer (%1)', $source->getDiscountDescription());
} else {
$discountLabel = __('Offer');
}
$subject->_totals['discount'] = new \Magento\Framework\DataObject(
[
'code' => 'discount',
'field' => 'discount_amount',
'value' => $source->getDiscountAmount(),
'label' => $discountLabel,
]
);
}
return $subject;
}
}
Have used $subject instead of $this within the plugin, this does not work for me however. How do I access the $this object within the plugin to add / overwrite $this->_totals['discount'] and return the updated $this object from within the plugin. I have it working fine with a standard preference but would rather use a plugin if possible.
I think you should check this before implementing above code.
http://devdocs.magento.com/guides/v2.0/extension-dev-guide/plugins.html
As per devdocs for Magento2 protected functions can not be intercepted so We can not use plugins for that.
May be that is causing issue in your case.
Hope this helps!
I'm having problems sending a mail with cakephp2, I know I can send emails because I have my postfix configured, and I can send e-mails with command line or php. So please, can you send me an example of cakephp2 sending emails.
This is the error message
Invalid email: "you#localhost"
Error: An Internal Error Has Occurred.
I've also tried with the ssl via gmail and it doesn't work either, and it's giving me a really hard time.
thanks guys
by the way, I'm trying the exact example of this url http://book.cakephp.org/2.0/en/core-utility-libraries/email.html
Your app/config/Email.
class EmailConfig {
public $gmail = array(
'port' => '465',
'timeout' => '300',
'host' => 'ssl://smtp.gmail.com',
'username' => '<your_email>#gmail.com',
'password' => '<you_password>',
'transport' => 'Smtp'
); }
your file = app/controller/appController.php insert this function
public function sendEmail($type, $options){
try {
$Email = new CakeEmail($type);
$Email->config($options);
$Email->template = "email_confirmation";
$Email->emailFormat('html');
//$this->idCrudRash = $options;
$Email->send();
} catch (SocketException $e) {
die('Erro ao enviar email:'. $e->getMessage());
$this->log(sprintf('Erro ao enviar email: %s', $e->getMessage()));
}
}
for user: app/controller/contato.php
$options = array(
'emailFormat' => 'html',
'from' => array(
$config['email_noanswer'] => $config['site_name']
),
'subject' => 'Confirmação de Cadastro',
'to' => $this->request->data['User']['email'],
//'template' => 'default',
'template' => 'email_confirmation',
'viewVars' => array(
'title_for_layout' => 'Confirmação de Email ' . $config['site_name'],
'name' => $this->request->data['User']['name'],
'email' => $this->request->data['User']['email'],
//'cpf' => base64_encode($this->request->data['User']['cpf']),
'site_name' => $config['site_name'],
),
);
$this->sendEmail('gmail', $options);
In your email.php file, please remove the default 'from' value, it overrides your passed param.
public $default = array(
'transport' => 'Mail',
'from' => 'you#localhost', // remove this line
...
);
In app/config/Email
public $smtp = array(
'transport' => 'Smtp',
'from' => array('no-reply#xyz.com' => 'no-reply#xyz.com'),
'host' => 'ssl://smtp.abc.com',
'port' => 465,
'timeout' => 30,
'username' => 'username',
'password' => 'password',
'client' => null,
'log' => false,
);
In Your Controller
App::uses('AppController', 'Controller');
App::uses('CakeEmail', 'Network/Email');
public function index()
{
$this->layout = 'layout';
$this->set('title', "Title");
if ($this->request->is('Post')) {
if (!empty($this->request->data)) {
if ($this->Modal->Save($this->request->data)) {
$to = 'test#anc.com';
$subject = 'Your_subject';
$message = $this->request->data;
if ($this->sendmail($to, $subject, $message)) {
echo"sent";die;
}
} else {
echo"wrong";die;
}
}
}
}
public function sendmail($to = null, $subject = '', $messages = null, $ccParam = null, $from = null, $reply = null, $path = null, $file_name = null)
{
$this->layout = false;
$this->render(false);
$name = $messages['Modalname']['name'];
$email = $messages['Modalname']['email'];
$Email = new CakeEmail();
$Email->config('smtp');
$Email->viewVars(array('name' => $name, 'email' => $email));
$Email->template('comman_email_template', 'comman_email_template');
return $Email->emailFormat('html')
->from(array('no-reply#xyz.com' => 'no-reply#xyz.com'))
->to($to)
->subject($subject)
->send();
}
Create a layout and view for email template.and add the data value that have been sent.
I got RegisterController.php and inside of it I got:
class RegisterController extends AppController {
public $name = 'Register';
public $components = array('Session');
public function index() {
if ($this->request->is('account')) {
// if ($this->Post->save($this->request->data)) {
echo "got it";
$this->Session->setFlash('Your post has been saved.');
$this->redirect(array('action' => 'index'));
// }
}
}
}
My /View/Register/index.tcp file:
<?php
echo $this->Form->create('Account');
echo $this->Form->input('username');
echo $this->Form->input('password');
$options = array(
'label' => 'Register',
'class' => 'submit'
);
echo $this->Form->end($options);
?>
And my /Model/Account.php file:
<?php
class Account extends AppModel {
public $name = 'Account';
public $validate = array(
'username' => array(
'rule' => 'notEmpty'
),
'password' => array(
'notEmpty' => array(
'rule' => 'notEmpty',
'message' => 'Can not be empty.'
),
'minLength' => array(
'rule' => array('minLength', '8'),
'message' => 'Min. 8 chars.'
)
)
);
}
?>
The problem is that, I'm clicking on the submit button, and nothing happends. It should at least check for validation.
Where is the error?
Should work if you add the action in options:
echo $this->Form->create('Account', array('action' => 'your/url'));