Merge pull request #4737 from turbo124/v5-develop

Fixes for dependencies.
This commit is contained in:
David Bomba 2021-01-21 07:59:06 +11:00 committed by GitHub
commit dadfb6d6a7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
24 changed files with 680 additions and 295 deletions

View File

@ -1 +1 @@
5.0.50 5.0.52

View File

@ -155,10 +155,5 @@ class SendTestEmails extends Command
->setSubject($message['subject']) ->setSubject($message['subject'])
->setBody($message['body']); ->setBody($message['body']);
// Mail::to(config('ninja.testvars.test_email'), 'Mr Test')
// ->cc($cc_emails)
// ->bcc($bcc_emails)
//->replyTo(also_available_if_needed)
//->send(new TemplateEmail($email_builder, $user, $client));
} }
} }

View File

@ -12,7 +12,7 @@
namespace App\Events\Invoice; namespace App\Events\Invoice;
use App\Models\Company; use App\Models\Company;
use App\Models\Invoice; use App\Models\InvoiceInvitation;
use Illuminate\Queue\SerializesModels; use Illuminate\Queue\SerializesModels;
/** /**
@ -22,36 +22,34 @@ class InvoiceWasEmailedAndFailed
{ {
use SerializesModels; use SerializesModels;
/** public $invitation;
* @var Invoice
*/
public $invoice;
/** public $message;
* @var array
*/
public $errors;
public $company; public $company;
public $event_vars; public $event_vars;
public $template;
/** /**
* Create a new event instance. * Create a new event instance.
* *
* @param Invoice $invoice * @param InvoiceInvitation $invitation
* @param Company $company * @param Company $company
* @param string $errors * @param string $errors
* @param array $event_vars * @param array $event_vars
*/ */
public function __construct(Invoice $invoice, Company $company, string $errors, array $event_vars) public function __construct(InvoiceInvitation $invitation, Company $company, string $message, string $template, array $event_vars)
{ {
$this->invoice = $invoice; $this->invitation = $invitation;
$this->company = $company; $this->company = $company;
$this->errors = $errors; $this->message = $message;
$this->event_vars = $event_vars; $this->event_vars = $event_vars;
$this->template = $template;
} }
} }

View File

@ -30,7 +30,7 @@ function nlog($output, $context = []): void
} }
$trace = debug_backtrace(); $trace = debug_backtrace();
\Illuminate\Support\Facades\Log::channel('invoiceninja')->info(print_r($trace[1]['class'],1), []); // \Illuminate\Support\Facades\Log::channel('invoiceninja')->info(print_r($trace[1]['class'],1), []);
\Illuminate\Support\Facades\Log::channel('invoiceninja')->info($output, $context); \Illuminate\Support\Facades\Log::channel('invoiceninja')->info($output, $context);
} }

View File

@ -117,55 +117,55 @@ class EmailController extends BaseController
$subject = $request->input('subject'); $subject = $request->input('subject');
$body = $request->input('body'); $body = $request->input('body');
$entity_string = strtolower(class_basename($entity_obj)); $entity_string = strtolower(class_basename($entity_obj));
$template = $request->input('template'); $template = str_replace("email_template_", "", $request->input('template'));
$template = str_replace("email_template_", "", $template);
$data = [
'subject' => $subject,
'body' => $body
];
$entity_obj->invitations->each(function ($invitation) use ($data, $entity_string, $entity_obj, $template) {
$entity_obj->invitations->each(function ($invitation) use ($subject, $body, $entity_string, $entity_obj, $template) {
if ($invitation->contact->send_email && $invitation->contact->email) { if ($invitation->contact->send_email && $invitation->contact->email) {
$data = [
'subject' => $subject,
'body' => $body
];
$entity_obj->service()->markSent()->save(); $entity_obj->service()->markSent()->save();
//@TODO why is this dispatchNow instead of just dispatch?
//update - changing to dispatch and see if something breaks.
EmailEntity::dispatch($invitation, $invitation->company, $template, $data)->delay(now()->addSeconds(5)); EmailEntity::dispatch($invitation, $invitation->company, $template, $data)->delay(now()->addSeconds(5));
} }
}); });
$entity_obj->last_sent_date = now(); $entity_obj->last_sent_date = now();
$entity_obj->save(); $entity_obj->save();
/*Only notify the admin ONCE, not once per contact/invite*/ /*Only notify the admin ONCE, not once per contact/invite*/
if ($entity_obj instanceof Invoice) { if ($entity_obj instanceof Invoice) {
$this->entity_type = Invoice::class; $this->entity_type = Invoice::class;
$this->entity_transformer = InvoiceTransformer::class; $this->entity_transformer = InvoiceTransformer::class;
if ($entity_obj->invitations->count() >= 1) { if ($entity_obj->invitations->count() >= 1)
$entity_obj->entityEmailEvent($entity_obj->invitations->first(), 'invoice', $template); $entity_obj->entityEmailEvent($entity_obj->invitations->first(), 'invoice', $template);
}
} }
if ($entity_obj instanceof Quote) { if ($entity_obj instanceof Quote) {
$this->entity_type = Quote::class; $this->entity_type = Quote::class;
$this->entity_transformer = QuoteTransformer::class; $this->entity_transformer = QuoteTransformer::class;
if ($entity_obj->invitations->count() >= 1) { if ($entity_obj->invitations->count() >= 1)
event(new QuoteWasEmailed($entity_obj->invitations->first(), $entity_obj->company, Ninja::eventVars(), 'quote')); event(new QuoteWasEmailed($entity_obj->invitations->first(), $entity_obj->company, Ninja::eventVars(), 'quote'));
}
} }
if ($entity_obj instanceof Credit) { if ($entity_obj instanceof Credit) {
$this->entity_type = Credit::class; $this->entity_type = Credit::class;
$this->entity_transformer = CreditTransformer::class; $this->entity_transformer = CreditTransformer::class;
if ($entity_obj->invitations->count() >= 1) { if ($entity_obj->invitations->count() >= 1)
event(new CreditWasEmailed($entity_obj->invitations->first(), $entity_obj->company, Ninja::eventVars(), 'credit')); event(new CreditWasEmailed($entity_obj->invitations->first(), $entity_obj->company, Ninja::eventVars(), 'credit'));
}
} }
if ($entity_obj instanceof RecurringInvoice) { if ($entity_obj instanceof RecurringInvoice) {

View File

@ -711,6 +711,7 @@ class InvoiceController extends BaseController
break; break;
case 'email': case 'email':
//check query parameter for email_type and set the template else use calculateTemplate //check query parameter for email_type and set the template else use calculateTemplate
if (request()->has('email_type') && property_exists($invoice->company->settings, request()->input('email_type'))) { if (request()->has('email_type') && property_exists($invoice->company->settings, request()->input('email_type'))) {
$this->reminder_template = $invoice->client->getSetting(request()->input('email_type')); $this->reminder_template = $invoice->client->getSetting(request()->input('email_type'));
} else { } else {
@ -725,7 +726,7 @@ class InvoiceController extends BaseController
}); });
if ($invoice->invitations->count() >= 1) { if ($invoice->invitations->count() >= 1) {
$invoice->entityEmailEvent($invoice->invitations->first(), $this->reminder_template); $invoice->entityEmailEvent($invoice->invitations->first(), 'invoice', $this->reminder_template);
} }
if (! $bulk) { if (! $bulk) {

View File

@ -15,6 +15,7 @@ use App\Events\Invoice\InvoiceReminderWasEmailed;
use App\Events\Invoice\InvoiceWasEmailed; use App\Events\Invoice\InvoiceWasEmailed;
use App\Events\Invoice\InvoiceWasEmailedAndFailed; use App\Events\Invoice\InvoiceWasEmailedAndFailed;
use App\Jobs\Mail\BaseMailerJob; use App\Jobs\Mail\BaseMailerJob;
use App\Jobs\Mail\EntityFailedSendMailer;
use App\Libraries\MultiDB; use App\Libraries\MultiDB;
use App\Mail\TemplateEmail; use App\Mail\TemplateEmail;
use App\Models\Activity; use App\Models\Activity;
@ -39,29 +40,32 @@ class EmailEntity extends BaseMailerJob implements ShouldQueue
{ {
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public $invitation; public $invitation; //The entity invitation
public $company; public $company; //The company
public $settings; public $settings; //The settings object
public $entity_string; public $entity_string; //The entity string ie. invoice, quote, credit
public $reminder_template; public $reminder_template; //The base template we are using
public $entity; public $entity; //The entity object
public $html_engine; public $html_engine; //The HTMLEngine object
public $email_entity_builder; public $email_entity_builder; //The email builder which merges the template and text
public $template_data; public $template_data; //The data to be merged into the template
/** /**
* EmailEntity constructor. * EmailEntity constructor.
*
*
* @param Invitation $invitation * @param Invitation $invitation
* @param Company $company * @param Company $company
* @param ?string $reminder_template * @param ?string $reminder_template
* @param array $template_data
*/ */
public function __construct($invitation, Company $company, ?string $reminder_template = null, $template_data = null) public function __construct($invitation, Company $company, ?string $reminder_template = null, $template_data = null)
{ {
@ -92,12 +96,14 @@ class EmailEntity extends BaseMailerJob implements ShouldQueue
*/ */
public function handle() public function handle()
{ {
if ($this->company->is_disabled) { /* Don't fire emails if the company is disabled */
if ($this->company->is_disabled)
return true; return true;
}
/* Set DB */
MultiDB::setDB($this->company->db); MultiDB::setDB($this->company->db);
/* Set the correct mail driver */
$this->setMailDriver(); $this->setMailDriver();
try { try {
@ -105,12 +111,10 @@ class EmailEntity extends BaseMailerJob implements ShouldQueue
->send( ->send(
new TemplateEmail( new TemplateEmail(
$this->email_entity_builder, $this->email_entity_builder,
$this->invitation->contact->user,
$this->invitation->contact->client $this->invitation->contact->client
) )
); );
} catch (\Exception $e) { } catch (\Exception $e) {
$this->entityEmailFailed($e->getMessage()); $this->entityEmailFailed($e->getMessage());
$this->logMailError($e->getMessage(), $this->entity->client); $this->logMailError($e->getMessage(), $this->entity->client);
} }
@ -132,11 +136,12 @@ class EmailEntity extends BaseMailerJob implements ShouldQueue
} }
} }
/* Switch statement to handling failure notifications */
private function entityEmailFailed($message) private function entityEmailFailed($message)
{ {
switch ($this->entity_string) { switch ($this->entity_string) {
case 'invoice': case 'invoice':
event(new InvoiceWasEmailedAndFailed($this->invitation->invoice, $this->company, $message, Ninja::eventVars())); event(new InvoiceWasEmailedAndFailed($this->invitation, $this->company, $message, $this->reminder_template, Ninja::eventVars()));
break; break;
default: default:
@ -145,30 +150,7 @@ class EmailEntity extends BaseMailerJob implements ShouldQueue
} }
} }
// private function entityEmailSucceeded() /* Builds the email builder object */
// {
// switch ($this->reminder_template) {
// case 'invoice':
// event(new InvoiceWasEmailed($this->invitation, $this->company, Ninja::eventVars()));
// break;
// case 'reminder1':
// event(new InvoiceReminderWasEmailed($this->invitation, $this->company, Ninja::eventVars(), Activity::INVOICE_REMINDER1_SENT));
// break;
// case 'reminder2':
// event(new InvoiceReminderWasEmailed($this->invitation, $this->company, Ninja::eventVars(), Activity::INVOICE_REMINDER2_SENT));
// break;
// case 'reminder3':
// event(new InvoiceReminderWasEmailed($this->invitation, $this->company, Ninja::eventVars(), Activity::INVOICE_REMINDER3_SENT));
// break;
// case 'reminder_endless':
// event(new InvoiceReminderWasEmailed($this->invitation, $this->company, Ninja::eventVars(), Activity::INVOICE_REMINDER_ENDLESS_SENT));
// break;
// default:
// # code...
// break;
// }
// }
private function resolveEmailBuilder() private function resolveEmailBuilder()
{ {
$class = 'App\Mail\Engine\\' . ucfirst(Str::camel($this->entity_string)) . "EmailEngine"; $class = 'App\Mail\Engine\\' . ucfirst(Str::camel($this->entity_string)) . "EmailEngine";

View File

@ -12,6 +12,7 @@
namespace App\Jobs\Mail; namespace App\Jobs\Mail;
use App\Libraries\MultiDB; use App\Libraries\MultiDB;
use App\Mail\Admin\EntityFailedSendObject;
use App\Mail\Admin\EntityNotificationMailer; use App\Mail\Admin\EntityNotificationMailer;
use App\Mail\Admin\EntitySentObject; use App\Mail\Admin\EntitySentObject;
use Illuminate\Bus\Queueable; use Illuminate\Bus\Queueable;
@ -40,6 +41,8 @@ class EntityFailedSendMailer extends BaseMailerJob implements ShouldQueue
public $settings; public $settings;
public $template; public $template;
public $message;
/** /**
* Create a new job instance. * Create a new job instance.
* *
@ -48,7 +51,7 @@ class EntityFailedSendMailer extends BaseMailerJob implements ShouldQueue
* @param $user * @param $user
* @param $company * @param $company
*/ */
public function __construct($invitation, $entity_type, $user, $company, $template) public function __construct($invitation, $entity_type, $user, $company, $template, $message)
{ {
$this->company = $company; $this->company = $company;
@ -63,6 +66,8 @@ class EntityFailedSendMailer extends BaseMailerJob implements ShouldQueue
$this->settings = $invitation->contact->client->getMergedSettings(); $this->settings = $invitation->contact->client->getMergedSettings();
$this->template = $template; $this->template = $template;
$this->message = $message;
} }
/** /**
@ -72,12 +77,10 @@ class EntityFailedSendMailer extends BaseMailerJob implements ShouldQueue
*/ */
public function handle() public function handle()
{ {
nlog("entity sent mailer");
/*If we are migrating data we don't want to fire these notification*/ /*If we are migrating data we don't want to fire these notification*/
if ($this->company->is_disabled) { if ($this->company->is_disabled)
return true; return true;
}
//Set DB //Set DB
MultiDB::setDb($this->company->db); MultiDB::setDb($this->company->db);
@ -85,13 +88,14 @@ class EntityFailedSendMailer extends BaseMailerJob implements ShouldQueue
//if we need to set an email driver do it now //if we need to set an email driver do it now
$this->setMailDriver(); $this->setMailDriver();
$mail_obj = (new EntitySentObject($this->invitation, $this->entity_type, $this->template))->build(); $mail_obj = (new EntityFailedSendObject($this->invitation, $this->entity_type, $this->template, $this->message))->build();
$mail_obj->from = [config('mail.from.address'), config('mail.from.name')]; $mail_obj->from = [config('mail.from.address'), config('mail.from.name')];
try { try {
Mail::to($this->user->email) Mail::to($this->user->email)
->send(new EntityNotificationMailer($mail_obj)); ->send(new EntityNotificationMailer($mail_obj));
} catch (\Exception $e) { } catch (\Exception $e) {
nlog("failing in EntityFailedSendMailer");
$this->failed($e); $this->failed($e);
$this->logMailError($e->getMessage(), $this->entity->client); $this->logMailError($e->getMessage(), $this->entity->client);
} }

View File

@ -72,12 +72,10 @@ class EntitySentMailer extends BaseMailerJob implements ShouldQueue
*/ */
public function handle() public function handle()
{ {
nlog("entity sent mailer");
/*If we are migrating data we don't want to fire these notification*/ /*If we are migrating data we don't want to fire these notification*/
if ($this->company->is_disabled) { if ($this->company->is_disabled)
return true; return true;
}
//Set DB //Set DB
MultiDB::setDb($this->company->db); MultiDB::setDb($this->company->db);

View File

@ -80,7 +80,7 @@ class EmailPayment extends BaseMailerJob implements ShouldQueue
try { try {
$mail = Mail::to($this->contact->email, $this->contact->present()->name()); $mail = Mail::to($this->contact->email, $this->contact->present()->name());
$mail->send(new TemplateEmail($email_builder, $this->contact->user, $this->contact->client)); $mail->send(new TemplateEmail($email_builder, $this->contact->client));
} catch (\Exception $e) { } catch (\Exception $e) {
nlog("mailing failed with message " . $e->getMessage()); nlog("mailing failed with message " . $e->getMessage());
event(new PaymentWasEmailedAndFailed($this->payment, $this->company, Mail::failures(), Ninja::eventVars())); event(new PaymentWasEmailedAndFailed($this->payment, $this->company, Mail::failures(), Ninja::eventVars()));

View File

@ -39,17 +39,19 @@ class InvoiceEmailFailedActivity implements ShouldQueue
*/ */
public function handle($event) public function handle($event)
{ {
nlog("inside activity_repo");
MultiDB::setDb($event->company->db); MultiDB::setDb($event->company->db);
$fields = new stdClass; $fields = new stdClass;
$fields->invoice_id = $event->invoice->id; $fields->invoice_id = $event->invitation->invoice->id;
$fields->client_id = $event->invoice->client_id; $fields->client_id = $event->invitation->invoice->client_id;
$fields->user_id = $event->invoice->user_id; $fields->user_id = $event->invitation->invoice->user_id;
$fields->company_id = $event->invoice->company_id; $fields->company_id = $event->invitation->invoice->company_id;
$fields->activity_type_id = Activity::EMAIL_INVOICE_FAILED; $fields->activity_type_id = Activity::EMAIL_INVOICE_FAILED;
$fields->notes = $event->errors; $fields->notes = $event->message;
$this->activity_repo->save($fields, $event->invoice, $event->event_vars); $this->activity_repo->save($fields, $event->invitation->invoice, $event->event_vars);
} }
} }

View File

@ -41,22 +41,32 @@ class InvoiceEmailedNotification implements ShouldQueue
$invoice->last_sent_date = now(); $invoice->last_sent_date = now();
$invoice->save(); $invoice->save();
/* We loop through each user and determine whether they need to be notified */
foreach ($event->invitation->company->company_users as $company_user) { foreach ($event->invitation->company->company_users as $company_user) {
/* The User */
$user = $company_user->user; $user = $company_user->user;
/* This is only here to handle the alternate message channels - ie Slack */
$notification = new EntitySentNotification($event->invitation, 'invoice'); $notification = new EntitySentNotification($event->invitation, 'invoice');
/* Returns an array of notification methods */
$methods = $this->findUserNotificationTypes($event->invitation, $company_user, 'invoice', ['all_notifications', 'invoice_sent']); $methods = $this->findUserNotificationTypes($event->invitation, $company_user, 'invoice', ['all_notifications', 'invoice_sent']);
/* If one of the methods is email then we fire the EntitySentMailer */
if (($key = array_search('mail', $methods)) !== false && $first_notification_sent === true) { if (($key = array_search('mail', $methods)) !== false && $first_notification_sent === true) {
unset($methods[$key]); unset($methods[$key]);
EntitySentMailer::dispatch($event->invitation, 'invoice', $user, $event->invitation->company, $event->template); EntitySentMailer::dispatch($event->invitation, 'invoice', $user, $event->invitation->company, $event->template);
/* This prevents more than one notification being sent */
$first_notification_sent = false; $first_notification_sent = false;
} }
/* Override the methods in the Notification Class */
$notification->method = $methods; $notification->method = $methods;
/* Notify on the alternate channels */
$user->notify($notification); $user->notify($notification);
} }
} }

View File

@ -11,6 +11,7 @@
namespace App\Listeners\Invoice; namespace App\Listeners\Invoice;
use App\Jobs\Mail\EntityFailedSendMailer;
use App\Jobs\Mail\EntitySentMailer; use App\Jobs\Mail\EntitySentMailer;
use App\Libraries\MultiDB; use App\Libraries\MultiDB;
use App\Notifications\Admin\EntitySentNotification; use App\Notifications\Admin\EntitySentNotification;
@ -33,6 +34,8 @@ class InvoiceFailedEmailNotification implements ShouldQueue
*/ */
public function handle($event) public function handle($event)
{ {
nlog("inside a failed notification");
MultiDB::setDb($event->company->db); MultiDB::setDb($event->company->db);
$first_notification_sent = true; $first_notification_sent = true;
@ -51,7 +54,7 @@ class InvoiceFailedEmailNotification implements ShouldQueue
if (($key = array_search('mail', $methods)) !== false && $first_notification_sent === true) { if (($key = array_search('mail', $methods)) !== false && $first_notification_sent === true) {
unset($methods[$key]); unset($methods[$key]);
EntitySentMailer::dispatch($event->invitation, 'invoice', $user, $event->invitation->company, $event->template); EntityFailedSendMailer::dispatch($event->invitation, 'invoice', $user, $event->invitation->company, $event->template, $event->message);
$first_notification_sent = false; $first_notification_sent = false;
} }

View File

@ -34,7 +34,9 @@ class EntityFailedSendObject
private $template_body; private $template_body;
public function __construct($invitation, $entity_type, $template) private $message;
public function __construct($invitation, $entity_type, $template, $message)
{ {
$this->invitation = $invitation; $this->invitation = $invitation;
$this->entity_type = $entity_type; $this->entity_type = $entity_type;
@ -42,6 +44,7 @@ class EntityFailedSendObject
$this->contact = $invitation->contact; $this->contact = $invitation->contact;
$this->company = $invitation->company; $this->company = $invitation->company;
$this->template = $template; $this->template = $template;
$this->message = $message;
} }
public function build() public function build()
@ -127,6 +130,7 @@ class EntityFailedSendObject
'amount' => $this->getAmount(), 'amount' => $this->getAmount(),
'client' => $this->contact->present()->name(), 'client' => $this->contact->present()->name(),
'invoice' => $this->entity->number, 'invoice' => $this->entity->number,
'error' => $this->message,
] ]
), ),
'url' => $this->invitation->getAdminLink(), 'url' => $this->invitation->getAdminLink(),

View File

@ -34,6 +34,7 @@ class EntityNotificationMailer extends Mailable
*/ */
public function build() public function build()
{ {
return $this->from(config('mail.from.address'), config('mail.from.name')) return $this->from(config('mail.from.address'), config('mail.from.name'))
->subject($this->mail_obj->subject) ->subject($this->mail_obj->subject)
->markdown($this->mail_obj->markdown, $this->mail_obj->data) ->markdown($this->mail_obj->markdown, $this->mail_obj->data)

View File

@ -91,6 +91,7 @@ class EntitySentObject
$this->template_subject = "texts.notification_credit_sent_subject"; $this->template_subject = "texts.notification_credit_sent_subject";
$this->template_body = "texts.notification_credit_sent"; $this->template_body = "texts.notification_credit_sent";
break; break;
default: default:
$this->template_subject = "texts.notification_invoice_sent_subject"; $this->template_subject = "texts.notification_invoice_sent_subject";
$this->template_body = "texts.notification_invoice_sent"; $this->template_body = "texts.notification_invoice_sent";
@ -115,20 +116,25 @@ class EntitySentObject
); );
} }
private function getData() private function getMessage()
{ {
$settings = $this->entity->client->getMergedSettings(); return ctrans(
return [
'title' => $this->getSubject(),
'message' => ctrans(
$this->template_body, $this->template_body,
[ [
'amount' => $this->getAmount(), 'amount' => $this->getAmount(),
'client' => $this->contact->present()->name(), 'client' => $this->contact->present()->name(),
'invoice' => $this->entity->number, 'invoice' => $this->entity->number,
] ]
), );
}
private function getData()
{
$settings = $this->entity->client->getMergedSettings();
return [
'title' => $this->getSubject(),
'message' => $this->getMessage(),
'url' => $this->invitation->getAdminLink(), 'url' => $this->invitation->getAdminLink(),
'button' => ctrans("texts.view_{$this->entity_type}"), 'button' => ctrans("texts.view_{$this->entity_type}"),
'signature' => $settings->email_signature, 'signature' => $settings->email_signature,

View File

@ -23,18 +23,12 @@ class TemplateEmail extends Mailable
private $build_email; private $build_email;
private $user; //the user the email will be sent from
private $client; private $client;
private $footer; public function __construct($build_email, Client $client)
public function __construct($build_email, User $user, Client $client)
{ {
$this->build_email = $build_email; $this->build_email = $build_email;
$this->user = $user; //this is inappropriate here, need to refactor 'user' in this context the 'user' could also be the 'system'
$this->client = $client; $this->client = $client;
} }

View File

@ -42,6 +42,7 @@ use App\Events\Invoice\InvoiceWasCancelled;
use App\Events\Invoice\InvoiceWasCreated; use App\Events\Invoice\InvoiceWasCreated;
use App\Events\Invoice\InvoiceWasDeleted; use App\Events\Invoice\InvoiceWasDeleted;
use App\Events\Invoice\InvoiceWasEmailed; use App\Events\Invoice\InvoiceWasEmailed;
use App\Events\Invoice\InvoiceWasEmailedAndFailed;
use App\Events\Invoice\InvoiceWasMarkedSent; use App\Events\Invoice\InvoiceWasMarkedSent;
use App\Events\Invoice\InvoiceWasPaid; use App\Events\Invoice\InvoiceWasPaid;
use App\Events\Invoice\InvoiceWasRestored; use App\Events\Invoice\InvoiceWasRestored;
@ -128,6 +129,7 @@ use App\Listeners\Invoice\InvoiceDeletedActivity;
use App\Listeners\Invoice\InvoiceEmailActivity; use App\Listeners\Invoice\InvoiceEmailActivity;
use App\Listeners\Invoice\InvoiceEmailFailedActivity; use App\Listeners\Invoice\InvoiceEmailFailedActivity;
use App\Listeners\Invoice\InvoiceEmailedNotification; use App\Listeners\Invoice\InvoiceEmailedNotification;
use App\Listeners\Invoice\InvoiceFailedEmailNotification;
use App\Listeners\Invoice\InvoicePaidActivity; use App\Listeners\Invoice\InvoicePaidActivity;
use App\Listeners\Invoice\InvoiceReminderEmailActivity; use App\Listeners\Invoice\InvoiceReminderEmailActivity;
use App\Listeners\Invoice\InvoiceRestoredActivity; use App\Listeners\Invoice\InvoiceRestoredActivity;
@ -310,6 +312,7 @@ class EventServiceProvider extends ServiceProvider
], ],
InvoiceWasEmailedAndFailed::class => [ InvoiceWasEmailedAndFailed::class => [
InvoiceEmailFailedActivity::class, InvoiceEmailFailedActivity::class,
InvoiceFailedEmailNotification::class,
], ],
InvoiceReminderWasEmailed::class => [ InvoiceReminderWasEmailed::class => [
InvoiceReminderEmailActivity::class, InvoiceReminderEmailActivity::class,

View File

@ -64,6 +64,8 @@ class PaymentRepository extends BaseRepository
*/ */
private function applyPayment(array $data, Payment $payment): ?Payment private function applyPayment(array $data, Payment $payment): ?Payment
{ {
nlog($data);
$is_existing_payment = true; $is_existing_payment = true;
//check currencies here and fill the exchange rate data if necessary //check currencies here and fill the exchange rate data if necessary
@ -117,6 +119,8 @@ class PaymentRepository extends BaseRepository
if (array_key_exists('invoices', $data) && is_array($data['invoices']) && count($data['invoices']) > 0) { if (array_key_exists('invoices', $data) && is_array($data['invoices']) && count($data['invoices']) > 0) {
$invoice_totals = array_sum(array_column($data['invoices'], 'amount')); $invoice_totals = array_sum(array_column($data['invoices'], 'amount'));
nlog("invoice totals = {$invoice_totals}");
$invoices = Invoice::whereIn('id', array_column($data['invoices'], 'invoice_id'))->get(); $invoices = Invoice::whereIn('id', array_column($data['invoices'], 'invoice_id'))->get();
$payment->invoices()->saveMany($invoices); $payment->invoices()->saveMany($invoices);
@ -155,6 +159,11 @@ class PaymentRepository extends BaseRepository
event(new PaymentWasCreated($payment, $payment->company, Ninja::eventVars())); event(new PaymentWasCreated($payment, $payment->company, Ninja::eventVars()));
} }
nlog("payment amount = {$payment->amount}");
nlog("payment applied = {$payment->applied}");
nlog("invoice totals = {$invoice_totals}");
nlog("credit totals = {$credit_totals}");
$payment->applied += ($invoice_totals - $credit_totals); //wont work because - check tests $payment->applied += ($invoice_totals - $credit_totals); //wont work because - check tests
// $payment->applied += $invoice_totals; //wont work because - check tests // $payment->applied += $invoice_totals; //wont work because - check tests

View File

@ -30,52 +30,97 @@ class ApplyPayment extends AbstractService
$this->payment_amount = $payment_amount; $this->payment_amount = $payment_amount;
} }
/* Apply payment to a single invoice */
public function run() public function run()
{ {
$this->invoice->fresh('client');
$amount_paid = 0;
if ($this->invoice->hasPartial()) {
if ($this->invoice->partial == $this->payment_amount)
{
//is partial and amount is exactly the partial amount
$amount_paid = $this->payment_amount * -1;
$this->invoice->service()->clearPartial()->setDueDate()->setStatus(Invoice::STATUS_PARTIAL)->updateBalance($amount_paid);
}
elseif ($this->invoice->partial > 0 && $this->invoice->partial > $this->payment_amount)
{
//partial amount exists, but the amount is less than the partial amount
$amount_paid = $this->payment_amount * -1;
$this->invoice->service()->updatePartial($amount_paid)->updateBalance($amount_paid);
}
elseif ($this->invoice->partial > 0 && $this->invoice->partial < $this->payment_amount)
{
//partial exists and the amount paid is GREATER than the partial amount
$amount_paid = $this->payment_amount * -1;
$this->invoice->service()->clearPartial()->setDueDate()->setStatus(Invoice::STATUS_PARTIAL)->updateBalance($amount_paid);
}
}
else
{
if ($this->payment_amount == $this->invoice->balance)
{
$amount_paid = $this->payment_amount * -1;
$this->invoice->service()->clearPartial()->setStatus(Invoice::STATUS_PAID)->updateBalance($amount_paid);
}
elseif ($this->payment_amount < $this->invoice->balance)
{
//partial invoice payment made
$amount_paid = $this->payment_amount * -1;
$this->invoice->service()->clearPartial()->setStatus(Invoice::STATUS_PARTIAL)->updateBalance($amount_paid);
}
elseif ($this->payment_amount > $this->invoice->balance)
{
//partial invoice payment made
$amount_paid = $this->invoice->balance * -1;
$this->invoice->service()->clearPartial()->setStatus(Invoice::STATUS_PAID)->updateBalance($amount_paid);
}
}
// $this->payment
// ->ledger()
// ->updatePaymentBalance($this->payment_amount * -1);
$this->payment $this->payment
->ledger() ->ledger()
->updatePaymentBalance($this->payment_amount * -1); ->updatePaymentBalance($amount_paid);
// info("apply payment method - current client balance = {$this->payment->client->balance}"); $this->invoice->client->service()->updateBalance($amount_paid)->save();
// info("reducing client balance by payment amount {$this->payment_amount}");
$this->invoice->client->service()->updateBalance($this->payment_amount * -1)->save();
// info("post client balance = {$this->invoice->client->balance}");
/* Update Pivot Record amount */ /* Update Pivot Record amount */
$this->payment->invoices->each(function ($inv) { $this->payment->invoices->each(function ($inv) use($amount_paid){
if ($inv->id == $this->invoice->id) { if ($inv->id == $this->invoice->id) {
$inv->pivot->amount = $this->payment_amount; $inv->pivot->amount = ($amount_paid*-1);
$inv->pivot->save(); $inv->pivot->save();
} }
}); });
$this->invoice->fresh('client');
// info("1 end of apply payment method the client balance = {$this->invoice->client->balance}");
if ($this->invoice->hasPartial()) {
//is partial and amount is exactly the partial amount
if ($this->invoice->partial == $this->payment_amount) {
$this->invoice->service()->clearPartial()->setDueDate()->setStatus(Invoice::STATUS_PARTIAL)->updateBalance($this->payment_amount * -1);
} elseif ($this->invoice->partial > 0 && $this->invoice->partial > $this->payment_amount) { //partial amount exists, but the amount is less than the partial amount
$this->invoice->service()->updatePartial($this->payment_amount * -1)->updateBalance($this->payment_amount * -1);
} elseif ($this->invoice->partial > 0 && $this->invoice->partial < $this->payment_amount) { //partial exists and the amount paid is GREATER than the partial amount
$this->invoice->service()->clearPartial()->setDueDate()->setStatus(Invoice::STATUS_PARTIAL)->updateBalance($this->payment_amount * -1);
}
} elseif ($this->payment_amount == $this->invoice->balance) { //total invoice paid.
$this->invoice->service()->clearPartial()->setStatus(Invoice::STATUS_PAID)->updateBalance($this->payment_amount * -1);
} elseif ($this->payment_amount < $this->invoice->balance) { //partial invoice payment made
$this->invoice->service()->clearPartial()->setStatus(Invoice::STATUS_PARTIAL)->updateBalance($this->payment_amount * -1);
}
// info("2 end of apply payment method the client balnace = {$this->invoice->client->balance}");
$this->invoice->service()->applyNumber()->save(); $this->invoice->service()->applyNumber()->save();
// info("3 end of apply payment method the client balnace = {$this->invoice->client->balance}");
return $this->invoice; return $this->invoice;
} }
} }

635
composer.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -13,7 +13,7 @@ return [
'require_https' => env('REQUIRE_HTTPS', true), 'require_https' => env('REQUIRE_HTTPS', true),
'app_url' => rtrim(env('APP_URL', ''), '/'), 'app_url' => rtrim(env('APP_URL', ''), '/'),
'app_domain' => env('APP_DOMAIN', ''), 'app_domain' => env('APP_DOMAIN', ''),
'app_version' => '5.0.50', 'app_version' => '5.0.52',
'minimum_client_version' => '5.0.16', 'minimum_client_version' => '5.0.16',
'terms_version' => '1.0.1', 'terms_version' => '1.0.1',
'api_secret' => env('API_SECRET', false), 'api_secret' => env('API_SECRET', false),

View File

@ -728,9 +728,9 @@ return [
'disable' => 'Disable', 'disable' => 'Disable',
'invoice_quote_number' => 'Invoice and Quote Numbers', 'invoice_quote_number' => 'Invoice and Quote Numbers',
'invoice_charges' => 'Invoice Surcharges', 'invoice_charges' => 'Invoice Surcharges',
'notification_invoice_bounced' => 'We were unable to deliver Invoice :invoice to :contact.', 'notification_invoice_bounced' => 'We were unable to deliver Invoice :invoice to :contact. \n :error',
'notification_invoice_bounced_subject' => 'Unable to deliver Invoice :invoice', 'notification_invoice_bounced_subject' => 'Unable to deliver Invoice :invoice',
'notification_quote_bounced' => 'We were unable to deliver Quote :invoice to :contact.', 'notification_quote_bounced' => 'We were unable to deliver Quote :invoice to :contact. \n :error',
'notification_quote_bounced_subject' => 'Unable to deliver Quote :invoice', 'notification_quote_bounced_subject' => 'Unable to deliver Quote :invoice',
'custom_invoice_link' => 'Custom Invoice Link', 'custom_invoice_link' => 'Custom Invoice Link',
'total_invoiced' => 'Total Invoiced', 'total_invoiced' => 'Total Invoiced',
@ -3372,6 +3372,6 @@ return [
'required_payment_information_more' => 'To complete a payment we need more details about you.', 'required_payment_information_more' => 'To complete a payment we need more details about you.',
'required_client_info_save_label' => 'We will save this, so you don\'t have to enter it next time.', 'required_client_info_save_label' => 'We will save this, so you don\'t have to enter it next time.',
'notification_credit_bounced' => 'We were unable to deliver Credit :invoice to :contact.', 'notification_credit_bounced' => 'We were unable to deliver Credit :invoice to :contact. \n :error',
'notification_credit_bounced_subject' => 'Unable to deliver Credit :invoice', 'notification_credit_bounced_subject' => 'Unable to deliver Credit :invoice',
]; ];

View File

@ -1,5 +1,6 @@
@component('email.template.master', ['design' => 'light', 'settings' => $settings]) @component('email.template.master', ['design' => 'light', 'settings' => $settings])
@slot('header') @slot('header')
@include('email.components.header', ['logo' => $logo]) @include('email.components.header', ['logo' => $logo])
@endslot @endslot