1
0
mirror of https://github.com/invoiceninja/invoiceninja.git synced 2024-11-11 21:52:35 +01:00
invoiceninja/app/Jobs/Util/ReminderJob.php

315 lines
12 KiB
PHP
Raw Normal View History

<?php
/**
* Invoice Ninja (https://invoiceninja.com).
*
* @link https://github.com/invoiceninja/invoiceninja source repository
*
2023-01-28 23:21:40 +01:00
* @copyright Copyright (c) 2023. Invoice Ninja LLC (https://invoiceninja.com)
*
2021-06-16 08:58:16 +02:00
* @license https://www.elastic.co/licensing/elastic-license
*/
namespace App\Jobs\Util;
2023-05-04 01:42:42 +02:00
use App\Utils\Ninja;
use App\Models\Invoice;
use App\Libraries\MultiDB;
use Illuminate\Bus\Queueable;
use Illuminate\Support\Carbon;
2021-07-01 01:14:30 +02:00
use App\DataMapper\InvoiceItem;
2023-04-27 02:19:55 +02:00
use App\Factory\InvoiceFactory;
2021-05-19 02:15:29 +02:00
use App\Jobs\Entity\EmailEntity;
2021-07-01 01:14:30 +02:00
use App\Utils\Traits\MakesDates;
2023-05-04 01:42:42 +02:00
use Illuminate\Support\Facades\App;
2021-05-25 23:31:17 +02:00
use App\Utils\Traits\MakesReminders;
2023-05-04 01:42:42 +02:00
use Illuminate\Support\Facades\Auth;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
class ReminderJob implements ShouldQueue
{
2023-03-17 07:23:48 +01:00
use Dispatchable;
use InteractsWithQueue;
use Queueable;
use SerializesModels;
use MakesReminders;
use MakesDates;
2021-08-09 00:44:51 +02:00
public $tries = 1;
public function __construct()
{
}
/**
* Execute the job.
*
* @return void
*/
2023-03-17 07:23:48 +01:00
public function handle(): void
{
2022-11-27 06:25:55 +01:00
set_time_limit(0);
2023-05-04 01:42:42 +02:00
Auth::logout();
2023-02-16 02:36:09 +01:00
if (! config('ninja.db.multi_db_enabled')) {
nlog("Sending invoice reminders on ".now()->format('Y-m-d h:i:s'));
Invoice::query()
->where('is_deleted', 0)
->whereIn('status_id', [Invoice::STATUS_SENT, Invoice::STATUS_PARTIAL])
->whereNull('deleted_at')
->where('balance', '>', 0)
->where('next_send_date', '<=', now()->toDateTimeString())
->whereHas('client', function ($query) {
$query->where('is_deleted', 0)
->where('deleted_at', null);
})
->whereHas('company', function ($query) {
$query->where('is_disabled', 0);
})
2022-11-27 06:25:55 +01:00
->with('invitations')->chunk(50, function ($invoices) {
2023-02-16 02:36:09 +01:00
foreach ($invoices as $invoice) {
$this->sendReminderForInvoice($invoice);
}
2022-11-27 06:25:55 +01:00
2023-05-26 05:13:32 +02:00
sleep(1);
});
} else {
//multiDB environment, need to
2023-03-17 07:23:48 +01:00
2023-02-16 02:36:09 +01:00
foreach (MultiDB::$dbs as $db) {
MultiDB::setDB($db);
nlog("Sending invoice reminders on db {$db} ".now()->format('Y-m-d h:i:s'));
Invoice::query()
->where('is_deleted', 0)
->whereIn('status_id', [Invoice::STATUS_SENT, Invoice::STATUS_PARTIAL])
->whereNull('deleted_at')
->where('balance', '>', 0)
->where('next_send_date', '<=', now()->toDateTimeString())
->whereHas('client', function ($query) {
$query->where('is_deleted', 0)
->where('deleted_at', null);
})
->whereHas('company', function ($query) {
$query->where('is_disabled', 0);
})
2022-11-27 06:25:55 +01:00
->with('invitations')->chunk(50, function ($invoices) {
2023-03-17 07:23:48 +01:00
2023-02-16 02:36:09 +01:00
foreach ($invoices as $invoice) {
$this->sendReminderForInvoice($invoice);
}
2022-11-27 06:25:55 +01:00
2023-05-26 05:13:32 +02:00
sleep(1);
});
}
}
}
private function sendReminderForInvoice(Invoice $invoice)
2023-02-16 02:36:09 +01:00
{
2023-04-27 02:19:55 +02:00
App::forgetInstance('translator');
$t = app('translator');
$t->replace(Ninja::transformTranslations($invoice->client->getMergedSettings()));
App::setLocale($invoice->client->locale());
if ($invoice->isPayable()) {
//Attempts to prevent duplicates from sending
2023-02-16 02:36:09 +01:00
if ($invoice->reminder_last_sent && Carbon::parse($invoice->reminder_last_sent)->startOfDay()->eq(now()->startOfDay())) {
nlog("caught a duplicate reminder for invoice {$invoice->number}");
return;
}
2023-02-16 02:36:09 +01:00
$reminder_template = $invoice->calculateTemplate('invoice');
2023-07-27 09:33:55 +02:00
nlog("reminder template = {$reminder_template}");
2023-02-16 02:36:09 +01:00
$invoice->service()->touchReminder($reminder_template)->save();
2023-04-27 02:19:55 +02:00
$fees = $this->calcLateFee($invoice, $reminder_template);
if($invoice->isLocked())
2023-04-27 02:19:55 +02:00
return $this->addFeeToNewInvoice($invoice, $reminder_template, $fees);
$invoice = $this->setLateFee($invoice, $fees[0], $fees[1]);
2023-02-16 02:36:09 +01:00
//20-04-2022 fixes for endless reminders - generic template naming was wrong
$enabled_reminder = 'enable_'.$reminder_template;
if ($reminder_template == 'endless_reminder') {
$enabled_reminder = 'enable_reminder_endless';
}
2023-07-27 09:33:55 +02:00
2023-02-16 02:36:09 +01:00
if (in_array($reminder_template, ['reminder1', 'reminder2', 'reminder3', 'reminder_endless', 'endless_reminder']) &&
$invoice->client->getSetting($enabled_reminder) &&
$invoice->client->getSetting('send_reminders') &&
(Ninja::isSelfHost() || $invoice->company->account->isPaidHostedClient())) {
2023-02-16 02:36:09 +01:00
$invoice->invitations->each(function ($invitation) use ($invoice, $reminder_template) {
if ($invitation->contact && !$invitation->contact->trashed() && $invitation->contact->email) {
2023-03-17 07:23:48 +01:00
EmailEntity::dispatch($invitation, $invitation->company, $reminder_template);
2023-02-16 02:36:09 +01:00
nlog("Firing reminder email for invoice {$invoice->number} - {$reminder_template}");
2023-03-17 07:23:48 +01:00
$invoice->entityEmailEvent($invitation, $reminder_template);
}
2023-02-16 02:36:09 +01:00
});
}
$invoice->service()->setReminder()->save();
} else {
$invoice->next_send_date = null;
$invoice->save();
}
}
2021-07-01 01:14:30 +02:00
2023-08-08 10:56:31 +02:00
private function addFeeToNewInvoice(Invoice $over_due_invoice, string $reminder_template, array $fees)
2023-04-27 02:19:55 +02:00
{
$amount = $fees[0];
$percent = $fees[1];
$temp_invoice_balance = $over_due_invoice->balance;
if ($amount <= 0 && $percent <= 0) {
return;
}
$fee = $amount;
if ($over_due_invoice->partial > 0) {
$fee += round($over_due_invoice->partial * $percent / 100, 2);
} else {
$fee += round($over_due_invoice->balance * $percent / 100, 2);
}
/** @var \App\Models\Invoice $invoice */
2023-04-27 02:19:55 +02:00
$invoice = InvoiceFactory::create($over_due_invoice->company_id, $over_due_invoice->user_id);
$invoice->client_id = $over_due_invoice->client_id;
2023-04-27 02:19:55 +02:00
$invoice->date = now()->format('Y-m-d');
$invoice->due_date = now()->format('Y-m-d');
$invoice_item = new InvoiceItem();
$invoice_item->type_id = '5';
$invoice_item->product_key = trans('texts.fee');
2023-04-27 03:16:57 +02:00
$invoice_item->notes = ctrans('texts.late_fee_added_locked_invoice', ['invoice' => $over_due_invoice->number, 'date' => $this->translateDate(now()->startOfDay(), $over_due_invoice->client->date_format(), $over_due_invoice->client->locale())]);
2023-04-27 02:19:55 +02:00
$invoice_item->quantity = 1;
$invoice_item->cost = $fee;
$invoice_items = [];
$invoice_items[] = $invoice_item;
$invoice->line_items = $invoice_items;
/**Refresh Invoice values*/
$invoice = $invoice->calc()->getInvoice();
$invoice->service()
->createInvitations()
->applyNumber()
->markSent()
->save();
$enabled_reminder = 'enable_'.$reminder_template;
if ($reminder_template == 'endless_reminder') {
$enabled_reminder = 'enable_reminder_endless';
}
if (in_array($reminder_template, ['reminder1', 'reminder2', 'reminder3', 'reminder_endless', 'endless_reminder']) &&
$invoice->client->getSetting($enabled_reminder) &&
$invoice->client->getSetting('send_reminders') &&
(Ninja::isSelfHost() || $invoice->company->account->isPaidHostedClient())) {
$invoice->invitations->each(function ($invitation) use ($invoice, $reminder_template) {
if ($invitation->contact && !$invitation->contact->trashed() && $invitation->contact->email) {
EmailEntity::dispatch($invitation, $invitation->company, $reminder_template);
nlog("Firing reminder email for invoice {$invoice->number} - {$reminder_template}");
$invoice->entityEmailEvent($invitation, $reminder_template);
}
});
}
$invoice->service()->setReminder()->save();
}
2021-07-01 01:14:30 +02:00
/**
* Calculates the late if - if any - and rebuilds the invoice
*
* @param Invoice $invoice
* @param string $template
2023-04-27 02:19:55 +02:00
* @return array
2021-07-01 01:14:30 +02:00
*/
2023-04-27 02:19:55 +02:00
private function calcLateFee($invoice, $template): array
2021-07-01 01:14:30 +02:00
{
$late_fee_amount = 0;
$late_fee_percent = 0;
switch ($template) {
case 'reminder1':
$late_fee_amount = $invoice->client->getSetting('late_fee_amount1');
$late_fee_percent = $invoice->client->getSetting('late_fee_percent1');
break;
case 'reminder2':
$late_fee_amount = $invoice->client->getSetting('late_fee_amount2');
$late_fee_percent = $invoice->client->getSetting('late_fee_percent2');
break;
case 'reminder3':
$late_fee_amount = $invoice->client->getSetting('late_fee_amount3');
$late_fee_percent = $invoice->client->getSetting('late_fee_percent3');
break;
case 'endless_reminder':
$late_fee_amount = $invoice->client->getSetting('late_fee_endless_amount');
$late_fee_percent = $invoice->client->getSetting('late_fee_endless_percent');
break;
default:
$late_fee_amount = 0;
$late_fee_percent = 0;
break;
}
2023-04-27 02:19:55 +02:00
return [$late_fee_amount, $late_fee_percent];
2021-07-01 01:14:30 +02:00
}
/**
* Applies the late fee to the invoice line items
*
* @param Invoice $invoice
* @param float $amount The fee amount
* @param float $percent The fee percentage amount
*
* @return Invoice
*/
2023-03-17 07:23:48 +01:00
private function setLateFee($invoice, $amount, $percent): Invoice
2021-07-01 01:14:30 +02:00
{
2021-08-19 00:02:28 +02:00
2021-07-01 01:14:30 +02:00
$temp_invoice_balance = $invoice->balance;
if ($amount <= 0 && $percent <= 0) {
return $invoice;
}
$fee = $amount;
if ($invoice->partial > 0) {
$fee += round($invoice->partial * $percent / 100, 2);
} else {
$fee += round($invoice->balance * $percent / 100, 2);
}
2023-03-17 07:23:48 +01:00
$invoice_item = new InvoiceItem();
2021-07-01 01:14:30 +02:00
$invoice_item->type_id = '5';
$invoice_item->product_key = trans('texts.fee');
$invoice_item->notes = ctrans('texts.late_fee_added', ['date' => $this->translateDate(now()->startOfDay(), $invoice->client->date_format(), $invoice->client->locale())]);
$invoice_item->quantity = 1;
$invoice_item->cost = $fee;
$invoice_items = $invoice->line_items;
$invoice_items[] = $invoice_item;
$invoice->line_items = $invoice_items;
/**Refresh Invoice values*/
2022-11-24 10:33:52 +01:00
$invoice = $invoice->calc()->getInvoice();
2022-09-02 04:30:02 +02:00
nlog('adjusting client balance and invoice balance by #'.$invoice->number.' '.($invoice->balance - $temp_invoice_balance));
2022-11-24 10:33:52 +01:00
$invoice->client->service()->updateBalance($invoice->balance - $temp_invoice_balance);
2021-07-23 02:31:30 +02:00
$invoice->ledger()->updateInvoiceBalance($invoice->balance - $temp_invoice_balance, "Late Fee Adjustment for invoice {$invoice->number}");
2021-07-01 01:14:30 +02:00
return $invoice;
}
2023-08-02 12:10:42 +02:00
}