How to send a scheduled email based on a date for the user using Laravel 8? - email

I want to send 7 days prior to the user, Theirs Selected plan is going to expire. I have implemented using command and cron jobs to run the command. But it is not working. Please anybody guide me to correct my mistake?
app/Console/Commands/AutoPlanRenewalMail.php
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Mail;
use App\Mail\PlanRenewalMail;
use App\User;
class AutoPlanRenewalMail extends Command
{
/**
* The name and signature of the console command.
*
* #var string
*/
protected $signature = 'auto:planrenewal';
/**
* The console command description.
*
* #var string
*/
protected $description = 'Command description';
/**
* Create a new command instance.
*
* #return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* #return int
*/
public function handle()
{
$users = User::whereNotNull('plan_validity')->get();
$check = true;
foreach($users as $user){
if(Carbon::parse($user->plan_validity)->diffInDays(Carbon::now()) == 7){ //Or however your date field on user is called
Mail::to($user)->send(new PlanRenewalMail($user));
}
}
return 0;
}
}
app/Console/kernal.php
<?php
namespace App\Console;
use App\Console\Commands\AutoPlanRenewalMail;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* #var array
*/
protected $commands = [
AutoPlanRenewalMail::class,
];
/**
* Define the application's command schedule.
*
* #param \Illuminate\Console\Scheduling\Schedule $schedule
* #return void
*/
protected function schedule(Schedule $schedule)
{
// $schedule->command('inspire')->hourly();
$schedule->command('auto:planrenewal')->daily();
}
/**
* Register the commands for the application.
*
* #return void
*/
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}
app/Mail/PlanRenewalMail.php
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class PlanRenewalMail extends Mailable
{
use Queueable, SerializesModels;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct()
{
//
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
//return $this->view('view.name');
return $this->subject("{{ ENV('APP_NAME') }} EXPIRING")
->view('emails.plan-renewal-mail');
}
}
cron jobs
* * * * * /usr/local/bin/php /home/username(changed to my username)/public_html/artisan schedule:run >> /dev/null 2>&1
then included email template blade file. But any email didn't get still. Is there any coding errors?

Related

Put request entity linked to some others entity symfony

i'm stucked on something: i have to entity Profile and Job
in the Job entity i have :
/**
* #var string
* #Gedmo\Translatable
* #ORM\Column(name="label", type="string", length=255)
* #Serializer\Groups({"profile_details","profile_put"})
* #Serializer\Type("string")
* #Serializer\Expose()
*/
private $label;
in the Profile entity i have :
* #var Job
*
* #Assert\NotBlank(message="app.profile.job.not_blank")
* #ORM\ManyToOne(targetEntity="App\Entity\Job")
* #ORM\JoinColumn(name="job_id", referencedColumnName="id")
* #Serializer\Groups({"profile_details","user_details","corporate_details","profile_put"})
* #Serializer\Type("App\Entity\Job")
* #Serializer\Expose()
*/
private $job;
/**
* #return Job
*/
public function getJob(): Job
{
return $this->job;
}
/**
* #param Job $job
*
* #return Profile
*/
public function setJob(Job $job): Profile
{
$this->job = $job;
return $this;
}
EDIT:
in the controller :
public function putAction(Request $request, Profile $profile): Profile
{
$profile
->setJob($request->get('job'))
$errors = $this->validator->validate($profile);
if (count($errors) > 0) {
throw new UnprocessableEntityHttpException((string) $errors);
}
$this->entityManager->persist($profile);
$this->entityManager->flush();
return $profile;
}
I'm trying to perform a put on the Profile entity to change some normal string fields. I don't know how to set the put request body on postman, i tried to put just the label but i got : "Argument 1 passed to App\\Entity\\Profile::setJob() must be an instance of App\\Entity\\Job, array given, called in /srv/api/src/Controller/ProfileController.php on line 114"

How to attach invoice PDF instead of packing slip in magento 2

I want to attach invoice pdf instead of packing slip while creating shipment.
I am using Fooman Email attachment extension version 2.0.8
My magento is 2.2.5 Can anyone know how can I change the attched PDF in shipping confirmation mail ?
Currently it is attaching packing slip but I want to attach invoice pdf in shipping confirmation mail.
We had a similar problem using fooman. We also wanted to send our invoice on shipment creation, while disableing the standard transactional invoice mail on invoice creation. I wrote a module that sends the invoice email together with the shipping email, which is not exactly what you are looking for but maybe you can leverage that.
The module is pretty simple. Except from boilerplate registration.php and module.xml, all you need is to override InvoiceOrder from Magento\Sales\Model and comment out this line:
$this->notifierInterface->notify($order, $invoice, $comment);
like so:
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Sales\Model;
use Magento\Framework\App\ResourceConnection;
use Magento\Sales\Api\Data\InvoiceCommentCreationInterface;
use Magento\Sales\Api\Data\InvoiceCreationArgumentsInterface;
use Magento\Sales\Api\InvoiceOrderInterface;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Sales\Model\Order\Config as OrderConfig;
use Magento\Sales\Model\Order\Invoice\NotifierInterface;
use Magento\Sales\Model\Order\InvoiceDocumentFactory;
use Magento\Sales\Model\Order\InvoiceRepository;
use Magento\Sales\Model\Order\OrderStateResolverInterface;
use Magento\Sales\Model\Order\PaymentAdapterInterface;
use Magento\Sales\Model\Order\Validation\InvoiceOrderInterface as InvoiceOrderValidator;
use Psr\Log\LoggerInterface;
/**
* Class InvoiceOrder
* #SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class InvoiceOrder implements InvoiceOrderInterface
{
/**
* #var ResourceConnection
*/
private $resourceConnection;
/**
* #var OrderRepositoryInterface
*/
private $orderRepository;
/**
* #var InvoiceDocumentFactory
*/
private $invoiceDocumentFactory;
/**
* #var PaymentAdapterInterface
*/
private $paymentAdapter;
/**
* #var OrderStateResolverInterface
*/
private $orderStateResolver;
/**
* #var OrderConfig
*/
private $config;
/**
* #var InvoiceRepository
*/
private $invoiceRepository;
/**
* #var InvoiceOrderValidator
*/
private $invoiceOrderValidator;
/**
* #var NotifierInterface
*/
private $notifierInterface;
/**
* #var LoggerInterface
*/
private $logger;
/**
* InvoiceOrder constructor.
* #param ResourceConnection $resourceConnection
* #param OrderRepositoryInterface $orderRepository
* #param InvoiceDocumentFactory $invoiceDocumentFactory
* #param PaymentAdapterInterface $paymentAdapter
* #param OrderStateResolverInterface $orderStateResolver
* #param OrderConfig $config
* #param InvoiceRepository $invoiceRepository
* #param InvoiceOrderValidator $invoiceOrderValidator
* #param NotifierInterface $notifierInterface
* #param LoggerInterface $logger
* #SuppressWarnings(PHPMD.ExcessiveParameterList)
*/
public function __construct(
ResourceConnection $resourceConnection,
OrderRepositoryInterface $orderRepository,
InvoiceDocumentFactory $invoiceDocumentFactory,
PaymentAdapterInterface $paymentAdapter,
OrderStateResolverInterface $orderStateResolver,
OrderConfig $config,
InvoiceRepository $invoiceRepository,
InvoiceOrderValidator $invoiceOrderValidator,
NotifierInterface $notifierInterface,
LoggerInterface $logger
) {
$this->resourceConnection = $resourceConnection;
$this->orderRepository = $orderRepository;
$this->invoiceDocumentFactory = $invoiceDocumentFactory;
$this->paymentAdapter = $paymentAdapter;
$this->orderStateResolver = $orderStateResolver;
$this->config = $config;
$this->invoiceRepository = $invoiceRepository;
$this->invoiceOrderValidator = $invoiceOrderValidator;
$this->notifierInterface = $notifierInterface;
$this->logger = $logger;
}
/**
* #param int $orderId
* #param bool $capture
* #param array $items
* #param bool $notify
* #param bool $appendComment
* #param \Magento\Sales\Api\Data\InvoiceCommentCreationInterface|null $comment
* #param \Magento\Sales\Api\Data\InvoiceCreationArgumentsInterface|null $arguments
* #return int
* #throws \Magento\Sales\Api\Exception\DocumentValidationExceptionInterface
* #throws \Magento\Sales\Api\Exception\CouldNotInvoiceExceptionInterface
* #throws \Magento\Framework\Exception\InputException
* #throws \Magento\Framework\Exception\NoSuchEntityException
* #throws \DomainException
*/
public function execute(
$orderId,
$capture = false,
array $items = [],
$notify = false,
$appendComment = false,
InvoiceCommentCreationInterface $comment = null,
InvoiceCreationArgumentsInterface $arguments = null
) {
$connection = $this->resourceConnection->getConnection('sales');
$order = $this->orderRepository->get($orderId);
$invoice = $this->invoiceDocumentFactory->create(
$order,
$items,
$comment,
($appendComment && $notify),
$arguments
);
$errorMessages = $this->invoiceOrderValidator->validate(
$order,
$invoice,
$capture,
$items,
$notify,
$appendComment,
$comment,
$arguments
);
if ($errorMessages->hasMessages()) {
throw new \Magento\Sales\Exception\DocumentValidationException(
__("Invoice Document Validation Error(s):\n" . implode("\n", $errorMessages->getMessages()))
);
}
$connection->beginTransaction();
try {
$order = $this->paymentAdapter->pay($order, $invoice, $capture);
$order->setState(
$this->orderStateResolver->getStateForOrder($order, [OrderStateResolverInterface::IN_PROGRESS])
);
$order->setStatus($this->config->getStateDefaultStatus($order->getState()));
$invoice->setState(\Magento\Sales\Model\Order\Invoice::STATE_PAID);
$this->invoiceRepository->save($invoice);
$this->orderRepository->save($order);
$connection->commit();
} catch (\Exception $e) {
$this->logger->critical($e);
$connection->rollBack();
throw new \Magento\Sales\Exception\CouldNotInvoiceException(
__('Could not save an invoice, see error log for details')
);
}
if ($notify) {
if (!$appendComment) {
$comment = null;
}
//$this->notifierInterface->notify($order, $invoice, $comment);
}
return $invoice->getEntityId();
}
}
Now all you have to do is setup events.xml and observe sales_order_shipment_save_after
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name='sales_order_shipment_save_after'>
<observer name='SendInvoiceWithShipment' instance='Vendor\Module\Observer\SendInvoiceWithShipment'
/>
</event>
</config>
Observer leverages standard Magento 2 transactional email $this->_invoiceSender->send($invoice); like so:
<?php
namespace Vendor\Module\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Sales\Model\Order;
use Magento\Sales\Model\Order\Email\Sender\InvoiceSender;
class SendInvoiceWithShipment implements ObserverInterface
{
protected $_invoiceSender;
public function __construct(
InvoiceSender $invoiceSender
) {
$this->_invoiceSender = $invoiceSender;
}
public function execute(\Magento\Framework\Event\Observer $observer)
{
$order = $observer->getShipment()->getOrder();
if (!$order) {
// Dont send invoice if order is not provided
return;
}
$invoices = $order->getInvoiceCollection();
foreach ($invoices as $invoice) {
try {
$this->_invoiceSender->send($invoice);
} catch (\Exception $e) {
// Do something if failed to send
}
}
}
}

Send Email from Laravel Commands and Scheduler

I'm trying to make a scheduled task using commands but does not work MailFacade to send emails.
The Command Class:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Mail;
class ToDoUserAlert extends Command
{
/**
* The name and signature of the console command.
*
* #var string
*/
protected $signature = 'toDoAlert';
/**
* The console command description.
*
* #var string
*/
protected $description = 'Send ToDo user alerts by email';
/**
* Create a new command instance.
*
* #return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* #return mixed
*/
public function handle()
{
Mail::raw(date('Y-m-d').' '.date('H:i'), function ($message) {
$message->to('sairam.santana#gmail.com');
$message->subject('Reminder Notification');
});
}
}
Kerner:
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* #var array
*/
protected $commands = [
Commands\ToDoUserAlert::class,
];
/**
* Define the application's command schedule.
*
* #param \Illuminate\Console\Scheduling\Schedule $schedule
* #return void
*/
protected function schedule(Schedule $schedule)
{
$schedule->command('toDoAlert')->everyMinute();
}
}

add role in zfcuser form registration

i am using zfcuser, bjyauthorize et roleuserbridge.
i want to add a field in the form registration. I followed this tutorial step :
http://resoftsol.com/adding-custom-fields-to-zfcuser-register-form/
in the module front i have added :
- the directory entity with files user et userinterface:
namespace Front\Entity;
interface UserInterface
{
/**
* Get id.
*
* #return int
*/
public function getId();
/**
* Set id.
*
* #param int $id
* #return UserInterface
*/
public function setId($id);
/**
* Get username.
*
* #return string
*/
public function getUsername();
/**
* Set username.
*
* #param string $username
* #return UserInterface
*/
public function setUsername($username);
/**
* Get email.
*
* #return string
*/
public function getEmail();
/**
* Set email.
*
* #param string $email
* #return UserInterface
*/
public function setEmail($email);
/**
* Get displayName.
*
* #return string
*/
public function getDisplayName();
/**
* Set displayName.
*
* #param string $displayName
* #return UserInterface
*/
public function setDisplayName($displayName);
/**
* Get password.
*
* #return string password
*/
public function getPassword();
/**
* Set password.
*
* #param string $password
* #return UserInterface
*/
public function setPassword($password);
/**
* Get state.
*
* #return int
*/
public function getState();
/**
* Set state.
*
* #param int $state
* #return UserInterface
*/
public function setState($state);
/**
* Get role.
*
* #return string
*/
public function getRole();
/**
* Set role.
*
* #param string $role
* #return UserInterface
*/
public function setRole($role);
}
++++++++++++++++++++
namespace Font\Entity;
class User implements UserInterface
{
/**
* #var int
*/
protected $id;
/**
* #var string
*/
protected $username;
/**
* #var string
*/
protected $email;
/**
* #var string
*/
protected $displayName;
/**
* #var string
*/
protected $password;
/**
* #var int
*/
protected $state;
/**
* #var string
*/
protected $role;
/**
* Get id.
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set id.
*
* #param int $id
* #return UserInterface
*/
public function setId($id)
{
$this->id = (int) $id;
return $this;
}
/**
* Get username.
*
* #return string
*/
public function getUsername()
{
return $this->username;
}
/**
* Set username.
*
* #param string $username
* #return UserInterface
*/
public function setUsername($username)
{
$this->username = $username;
return $this;
}
/**
* Get email.
*
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set email.
*
* #param string $email
* #return UserInterface
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get displayName.
*
* #return string
*/
public function getDisplayName()
{
return $this->displayName;
}
/**
* Set displayName.
*
* #param string $displayName
* #return UserInterface
*/
public function setDisplayName($displayName)
{
$this->displayName = $displayName;
return $this;
}
/**
* Get password.
*
* #return string
*/
public function getPassword()
{
return $this->password;
}
/**
* Set password.
*
* #param string $password
* #return UserInterface
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* Get state.
*
* #return int
*/
public function getState()
{
return $this->state;
}
/**
* Set state.
*
* #param int $state
* #return UserInterface
*/
public function setState($state)
{
$this->state = $state;
return $this;
}
/**
* Get role.
*
* #return string
*/
public function getRole()
{
return $this->role;
}
/**
* Set role.
*
* #param string $role
* #return UserInterface
*/
public function setRole($role)
{
$this->role = $role;
return $this;
}
}
++++++++++++++++++++++++++
also i have add the mapp directory.
i had the following error :
Catchable fatal error: Argument 1 passed to ZfcUser\Validator\AbstractRecord::setMapper()
must be an instance of ZfcUser\Mapper\UserInterface, instance of Front\Mapper\User given,
called in C:\wamppp\www\projet\vendor\zendframework\zendframework\library\Zend\Validator
\AbstractValidator.php on line 139 and defined in C:\wamppp\www\projet\vendor\zf-commons
\zfc-user\src\ZfcUser\Validator\AbstractRecord.php on line 65
I just had the problem myself and was able to solve it... finally.
Copy the ZfcUser\Validator folder into your module.
Adapt the namespace and change the expected Object type of the method AbstractRecord::setMapper to your user entity / interface, whatever you have there now.
Also, in the code you provided the namespaces arent identical. Yout got "Front" and "Font" there.
Edit: forgot the important part xD
After you have done that you need the following code in the config file (my module is called User):
'zfcuser_register_form' => function ($sm) {
$options = $sm->get('zfcuser_module_options');
$form = new ZfcUser\Form\Register(null, $options);
//$form->setCaptchaElement($sm->get('zfcuser_captcha_element'));
$form->setInputFilter(new ZfcUser\Form\RegisterFilter(
new User\Validator\NoRecordExists(array(
'mapper' => $sm->get('zfcuser_user_mapper'),
'key' => 'email'
)),
new User\Validator\NoRecordExists(array(
'mapper' => $sm->get('zfcuser_user_mapper'),
'key' => 'username'
)),
$options
));
return $form;
},
I hope this helps.
You should not create your own interface(and if you do, your new interface should extend ZfcUser\Entity\UserInterface), instead just make your user entity extend the ZfcUser\Entity\UserInterface.

Doctrine 2.x and zend framework integration 1.11 - entity generation errors no #ORM etc

I have integrated zend with doctrine, and everything works but when I start to genereate entities using doctrine cli: doctrine orm:generate-entities
I get php Entities class without #ORM, #Entity in comments.
Example:
<?php
use Doctrine\ORM\Mapping as ORM;
/**
* Tag
*/
class Tag
{
/**
* #var string $tagName
*/
private $tagName;
/**
* #var \Doctrine\Common\Collections\ArrayCollection
*/
private $eventevent;
/**
* Constructor
*/
public function __construct()
{
$this->eventevent = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get tagName
*
* #return string
*/
public function getTagName()
{
return $this->tagName;
}
/**
* Add eventevent
*
* #param Event $eventevent
* #return Tag
*/
public function addEventevent(\Event $eventevent)
{
$this->eventevent[] = $eventevent;
return $this;
}
/**
* Remove eventevent
*
* #param Event $eventevent
*/
public function removeEventevent(\Event $eventevent)
{
$this->eventevent->removeElement($eventevent);
}
/**
* Get eventevent
*
* #return Doctrine\Common\Collections\Collection
*/
public function getEventevent()
{
return $this->eventevent;
}
}