Merge branch 'v5-develop' of https://github.com/invoiceninja/invoiceninja into feature-inbound-email-expenses

This commit is contained in:
paulwer 2024-06-24 14:38:38 +02:00
commit 4a56c114d0
74 changed files with 3372 additions and 2842 deletions

View File

@ -66,7 +66,7 @@ jobs:
- name: Build project - name: Build project
run: | run: |
shopt -s dotglob shopt -s dotglob
tar --exclude='public/storage' --exclude='./htaccess' --exclude='invoiceninja.zip' -zcvf /home/runner/work/invoiceninja/react-invoiceninja.tar * tar --exclude='public/storage' --exclude='./htaccess' --exclude='invoiceninja.zip' -zcvf /home/runner/work/invoiceninja/invoiceninja.tar *
- name: Release - name: Release
uses: softprops/action-gh-release@v1 uses: softprops/action-gh-release@v1
if: startsWith(github.ref, 'refs/tags/') if: startsWith(github.ref, 'refs/tags/')
@ -74,4 +74,4 @@ jobs:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with: with:
files: | files: |
/home/runner/work/invoiceninja/react-invoiceninja.tar /home/runner/work/invoiceninja/invoiceninja.tar

View File

@ -1,84 +0,0 @@
on:
release:
types: [released]
name: Upload Release Asset
jobs:
build:
name: Upload Release Asset
runs-on: ubuntu-latest
steps:
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: 8.2
extensions: mysql, mysqlnd, sqlite3, bcmath, gd, curl, zip, openssl, mbstring, xml
- name: Checkout code
uses: actions/checkout@v1
with:
ref: v5-develop
- name: Copy .env file
run: |
cp .env.example .env
- name: Install composer dependencies
run: |
composer config -g github-oauth.github.com ${{ secrets.GITHUB_TOKEN }}
composer install --no-dev
- name: Prepare Laravel Application
run: |
cp .env.example .env
php artisan key:generate --force
php artisan optimize
php artisan storage:link --force
sudo php artisan cache:clear
sudo find ./vendor/bin/ -type f -exec chmod +x {} \;
sudo find ./ -type d -exec chmod 755 {} \;
- name: Prepare React FrontEnd
run: |
git clone https://${{secrets.commit_secret}}@github.com/invoiceninja/ui.git
cd ui
git checkout develop
npm i
npm run build
mkdir -p ../public/react/${{ github.event.release.tag_name }}/
cp -r dist/react/* ../public/react/${{ github.event.release.tag_name }}/
cp -r dist/react/* ../public/react/
cp dist/index.html ../resources/views/react/index.blade.php
mkdir -p ../public/tinymce_6.4.2/tinymce/js/
cp -r node_modules/tinymce ../public/tinymce_6.4.2/tinymce/js/
cd ..
rm -rf ui
php artisan ninja:react
- name: Prepare JS/CSS assets
run: |
npm i
npm run production
- name: Cleanup Builds
run: |
sudo rm -rf bootstrap/cache/*
sudo rm -rf node_modules
sudo rm -rf .git
sudo rm .env
- name: Build project
run: |
shopt -s dotglob
tar --exclude='public/storage' --exclude='./htaccess' --exclude='invoiceninja.zip' -zcvf /home/runner/work/invoiceninja/invoiceninja.tar *
- name: Release
uses: softprops/action-gh-release@v1
if: startsWith(github.ref, 'refs/tags/')
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
files: |
/home/runner/work/invoiceninja/invoiceninja.tar

View File

@ -1 +1 @@
5.9.9 5.10.2

View File

@ -56,8 +56,6 @@ class CreateAccount extends Command
{ {
$this->info(date('r').' Create Single Account...'); $this->info(date('r').' Create Single Account...');
$this->warmCache();
$this->createAccount(); $this->createAccount();
} }

View File

@ -109,7 +109,7 @@ class ActivityExport extends BaseExport
$query = Activity::query() $query = Activity::query()
->where('company_id', $this->company->id); ->where('company_id', $this->company->id);
$query = $this->addDateRange($query); $query = $this->addDateRange($query, 'activities');
return $query; return $query;
} }

View File

@ -1243,15 +1243,16 @@ class BaseExport
* Add Date Range * Add Date Range
* *
* @param Builder $query * @param Builder $query
* @param ?string $table_name
* @return Builder * @return Builder
*/ */
protected function addDateRange(Builder $query): Builder protected function addDateRange(Builder $query, ?string $table_name = null): Builder
{ {
$query = $this->applyProductFilters($query); $query = $this->applyProductFilters($query);
$date_range = $this->input['date_range']; $date_range = $this->input['date_range'];
if (array_key_exists('date_key', $this->input) && strlen($this->input['date_key']) > 1) { if (array_key_exists('date_key', $this->input) && strlen($this->input['date_key']) > 1 && ($table_name && $this->columnExists($table_name, $this->input['date_key']))) {
$this->date_key = $this->input['date_key']; $this->date_key = $this->input['date_key'];
} }
@ -1608,5 +1609,18 @@ class BaseExport
ZipDocuments::dispatch($documents, $this->company, $user); ZipDocuments::dispatch($documents, $this->company, $user);
} }
} }
/**
* Tests that the column exists
* on the table prior to adding it to
* the query builder
*
* @param string $table
* @param string $column
* @return bool
*/
public function columnExists($table, $column): bool
{
return \Illuminate\Support\Facades\Schema::hasColumn($table, $column);
}
} }

View File

@ -131,7 +131,7 @@ class ClientExport extends BaseExport
$query->where('is_deleted', 0); $query->where('is_deleted', 0);
} }
$query = $this->addDateRange($query); $query = $this->addDateRange($query,' clients');
if($this->input['document_email_attachment'] ?? false) { if($this->input['document_email_attachment'] ?? false) {
$this->queueDocuments($query); $this->queueDocuments($query);

View File

@ -63,7 +63,7 @@ class ContactExport extends BaseExport
$q->where('is_deleted', false); $q->where('is_deleted', false);
}); });
$query = $this->addDateRange($query); $query = $this->addDateRange($query, 'client_contacts');
return $query; return $query;

View File

@ -108,7 +108,7 @@ class CreditExport extends BaseExport
->where('company_id', $this->company->id) ->where('company_id', $this->company->id)
->where('is_deleted', $this->input['include_deleted'] ?? false); ->where('is_deleted', $this->input['include_deleted'] ?? false);
$query = $this->addDateRange($query); $query = $this->addDateRange($query, 'credits');
$clients = &$this->input['client_id']; $clients = &$this->input['client_id'];

View File

@ -76,7 +76,7 @@ class DocumentExport extends BaseExport
$query = Document::query()->where('company_id', $this->company->id); $query = Document::query()->where('company_id', $this->company->id);
$query = $this->addDateRange($query); $query = $this->addDateRange($query, 'documents');
if($this->input['document_email_attachment'] ?? false) { if($this->input['document_email_attachment'] ?? false) {
$this->queueDocuments($query); $this->queueDocuments($query);

View File

@ -89,7 +89,7 @@ class ExpenseExport extends BaseExport
$query->where('is_deleted', 0); $query->where('is_deleted', 0);
} }
$query = $this->addDateRange($query); $query = $this->addDateRange($query, 'expenses');
if($this->input['status'] ?? false) { if($this->input['status'] ?? false) {
$query = $this->addExpenseStatusFilter($query, $this->input['status']); $query = $this->addExpenseStatusFilter($query, $this->input['status']);

View File

@ -67,7 +67,7 @@ class InvoiceExport extends BaseExport
$query->where('is_deleted', 0); $query->where('is_deleted', 0);
} }
$query = $this->addDateRange($query); $query = $this->addDateRange($query, 'invoices');
$clients = &$this->input['client_id']; $clients = &$this->input['client_id'];

View File

@ -79,7 +79,7 @@ class InvoiceItemExport extends BaseExport
$query->where('is_deleted', 0); $query->where('is_deleted', 0);
} }
$query = $this->addDateRange($query); $query = $this->addDateRange($query, 'invoices');
$clients = &$this->input['client_id']; $clients = &$this->input['client_id'];

View File

@ -62,7 +62,7 @@ class PaymentExport extends BaseExport
->where('company_id', $this->company->id) ->where('company_id', $this->company->id)
->where('is_deleted', 0); ->where('is_deleted', 0);
$query = $this->addDateRange($query); $query = $this->addDateRange($query, 'payments');
$clients = &$this->input['client_id']; $clients = &$this->input['client_id'];

View File

@ -75,12 +75,11 @@ class ProductExport extends BaseExport
->withTrashed() ->withTrashed()
->where('company_id', $this->company->id); ->where('company_id', $this->company->id);
if(!$this->input['include_deleted'] ?? false) { //@phpstan-ignore-line
if(!$this->input['include_deleted'] ?? false) {
$query->where('is_deleted', 0); $query->where('is_deleted', 0);
} }
$query = $this->addDateRange($query); $query = $this->addDateRange($query, 'products');
if($this->input['document_email_attachment'] ?? false) { if($this->input['document_email_attachment'] ?? false) {
$this->queueDocuments($query); $this->queueDocuments($query);

View File

@ -129,7 +129,7 @@ class ProductSalesExport extends BaseExport
->where('is_deleted', 0) ->where('is_deleted', 0)
->whereIn('status_id', [Invoice::STATUS_SENT, Invoice::STATUS_PARTIAL, Invoice::STATUS_PAID]); ->whereIn('status_id', [Invoice::STATUS_SENT, Invoice::STATUS_PARTIAL, Invoice::STATUS_PAID]);
$query = $this->addDateRange($query); $query = $this->addDateRange($query, 'invoices');
$query = $this->filterByClients($query); $query = $this->filterByClients($query);

View File

@ -67,7 +67,7 @@ class PurchaseOrderExport extends BaseExport
$query->where('is_deleted', 0); $query->where('is_deleted', 0);
} }
$query = $this->addDateRange($query); $query = $this->addDateRange($query, 'purchase_orders');
$clients = &$this->input['client_id']; $clients = &$this->input['client_id'];

View File

@ -71,7 +71,7 @@ class PurchaseOrderItemExport extends BaseExport
$query->where('is_deleted', 0); $query->where('is_deleted', 0);
} }
$query = $this->addDateRange($query); $query = $this->addDateRange($query, 'purchase_orders');
$clients = &$this->input['client_id']; $clients = &$this->input['client_id'];

View File

@ -73,7 +73,7 @@ class QuoteExport extends BaseExport
$query->where('is_deleted', 0); $query->where('is_deleted', 0);
} }
$query = $this->addDateRange($query); $query = $this->addDateRange($query, 'quotes');
$clients = &$this->input['client_id']; $clients = &$this->input['client_id'];

View File

@ -74,7 +74,7 @@ class QuoteItemExport extends BaseExport
$query->where('is_deleted', 0); $query->where('is_deleted', 0);
} }
$query = $this->addDateRange($query); $query = $this->addDateRange($query, 'quotes');
$clients = &$this->input['client_id']; $clients = &$this->input['client_id'];

View File

@ -65,7 +65,7 @@ class RecurringInvoiceExport extends BaseExport
$query->where('is_deleted', 0); $query->where('is_deleted', 0);
} }
$query = $this->addDateRange($query); $query = $this->addDateRange($query, 'recurring_invoices');
$clients = &$this->input['client_id']; $clients = &$this->input['client_id'];

View File

@ -74,7 +74,7 @@ class TaskExport extends BaseExport
$query->where('is_deleted', 0); $query->where('is_deleted', 0);
} }
$query = $this->addDateRange($query); $query = $this->addDateRange($query, 'tasks');
$clients = &$this->input['client_id']; $clients = &$this->input['client_id'];
@ -184,13 +184,13 @@ class TaskExport extends BaseExport
foreach ($logs as $key => $item) { foreach ($logs as $key => $item) {
if (in_array('task.start_date', $this->input['report_keys']) || in_array('start_date', $this->input['report_keys'])) { if (in_array('task.start_date', $this->input['report_keys']) || in_array('start_date', $this->input['report_keys'])) {
$carbon_object = Carbon::createFromTimeStamp($item[0])->setTimezone($timezone_name); $carbon_object = Carbon::createFromTimeStamp((int)$item[0])->setTimezone($timezone_name);
$entity['task.start_date'] = $carbon_object->format($date_format_default); $entity['task.start_date'] = $carbon_object->format($date_format_default);
$entity['task.start_time'] = $carbon_object->format('H:i:s'); $entity['task.start_time'] = $carbon_object->format('H:i:s');
} }
if ((in_array('task.end_date', $this->input['report_keys']) || in_array('end_date', $this->input['report_keys'])) && $item[1] > 0) { if ((in_array('task.end_date', $this->input['report_keys']) || in_array('end_date', $this->input['report_keys'])) && $item[1] > 0) {
$carbon_object = Carbon::createFromTimeStamp($item[1])->setTimezone($timezone_name); $carbon_object = Carbon::createFromTimeStamp((int)$item[1])->setTimezone($timezone_name);
$entity['task.end_date'] = $carbon_object->format($date_format_default); $entity['task.end_date'] = $carbon_object->format($date_format_default);
$entity['task.end_time'] = $carbon_object->format('H:i:s'); $entity['task.end_time'] = $carbon_object->format('H:i:s');
} }

View File

@ -68,7 +68,7 @@ class VendorExport extends BaseExport
$query->where('is_deleted', 0); $query->where('is_deleted', 0);
} }
$query = $this->addDateRange($query); $query = $this->addDateRange($query, 'vendors');
if($this->input['document_email_attachment'] ?? false) { if($this->input['document_email_attachment'] ?? false) {
$this->queueDocuments($query); $this->queueDocuments($query);

View File

@ -60,7 +60,7 @@ class TaskDecorator extends Decorator implements DecoratorInterface
if(is_array($logs)) { if(is_array($logs)) {
$item = $logs[0]; $item = $logs[0];
return Carbon::createFromTimeStamp($item[0])->setTimezone($timezone_name)->format($date_format_default); return Carbon::createFromTimeStamp((int)$item[0])->setTimezone($timezone_name)->format($date_format_default);
} }
return ''; return '';
@ -89,7 +89,7 @@ class TaskDecorator extends Decorator implements DecoratorInterface
if(is_array($logs)) { if(is_array($logs)) {
$item = $logs[1]; $item = $logs[1];
return Carbon::createFromTimeStamp($item[1])->setTimezone($timezone_name)->format($date_format_default); return Carbon::createFromTimeStamp((int)$item[1])->setTimezone($timezone_name)->format($date_format_default);
} }
return ''; return '';

View File

@ -121,8 +121,16 @@ class PaymentController extends Controller
{ {
/** @var \App\Models\CompanyGateway $gateway **/ /** @var \App\Models\CompanyGateway $gateway **/
$gateway = CompanyGateway::findOrFail($request->input('company_gateway_id')); $gateway = CompanyGateway::findOrFail($request->input('company_gateway_id'));
$payment_hash = PaymentHash::where('hash', $request->payment_hash)->firstOrFail(); $payment_hash = PaymentHash::with('fee_invoice')->where('hash', $request->payment_hash)->firstOrFail();
$invoice = Invoice::with('client')->find($payment_hash->fee_invoice_id);
// if($payment_hash)
$invoice = $payment_hash->fee_invoice;
// else
// $invoice = Invoice::with('client')->where('id',$payment_hash->fee_invoice_id)->orderBy('id','desc')->first();
// $invoice = Invoice::with('client')->find($payment_hash->fee_invoice_id);
$client = $invoice ? $invoice->client : auth()->guard('contact')->user()->client; $client = $invoice ? $invoice->client : auth()->guard('contact')->user()->client;
// 09-07-2022 catch duplicate responses for invoices that already paid here. // 09-07-2022 catch duplicate responses for invoices that already paid here.

View File

@ -192,6 +192,7 @@ class ImportController extends Controller
$contents = file_get_contents($file->getPathname()); $contents = file_get_contents($file->getPathname());
// Store the csv in cache with an expiry of 10 minutes // Store the csv in cache with an expiry of 10 minutes
Cache::put($hash.'-'.$entityType, base64_encode($contents), 600); Cache::put($hash.'-'.$entityType, base64_encode($contents), 600);
nlog($hash.'-'.$entityType);
} }
} }

View File

@ -503,7 +503,7 @@ class InvoiceController extends BaseController
$invoices = Invoice::withTrashed()->whereIn('id', $this->transformKeys($ids))->company()->get(); $invoices = Invoice::withTrashed()->whereIn('id', $this->transformKeys($ids))->company()->get();
if (! $invoices) { if ($invoices->count() == 0 ) {
return response()->json(['message' => 'No Invoices Found']); return response()->json(['message' => 'No Invoices Found']);
} }

View File

@ -12,6 +12,7 @@
namespace App\Http\Requests\Invoice; namespace App\Http\Requests\Invoice;
use App\Http\Requests\Request; use App\Http\Requests\Request;
use App\Exceptions\DuplicatePaymentException;
class BulkInvoiceRequest extends Request class BulkInvoiceRequest extends Request
{ {
@ -29,7 +30,21 @@ class BulkInvoiceRequest extends Request
'template' => 'sometimes|string', 'template' => 'sometimes|string',
'template_id' => 'sometimes|string', 'template_id' => 'sometimes|string',
'send_email' => 'sometimes|bool', 'send_email' => 'sometimes|bool',
'subscriptin_id' => 'sometimes|string', 'subscription_id' => 'sometimes|string',
]; ];
} }
public function prepareForValidation()
{
/** @var \App\Models\User $user */
$user = auth()->user();
if(\Illuminate\Support\Facades\Cache::has($this->ip()."|".$this->input('action', 0)."|".json_encode($this->input('ids', ''))."|".$user->company()->company_key))
throw new DuplicatePaymentException('Duplicate request.', 429);
\Illuminate\Support\Facades\Cache::put(($this->ip()."|".$this->input('action', 0)."|".json_encode($this->input('ids', ''))."|".$user->company()->company_key), true, 1);
}
} }

View File

@ -123,7 +123,7 @@ class StoreInvoiceRequest extends Request
$client = \App\Models\Client::withTrashed()->find($input['client_id']); $client = \App\Models\Client::withTrashed()->find($input['client_id']);
if($client) { if($client) {
$input['due_date'] = \Illuminate\Support\Carbon::parse($input['date'])->addDays($client->getSetting('payment_terms'))->format('Y-m-d'); $input['due_date'] = \Illuminate\Support\Carbon::parse($input['date'])->addDays((int)$client->getSetting('payment_terms'))->format('Y-m-d');
} }
} }

View File

@ -116,7 +116,7 @@ class UpdateInvoiceRequest extends Request
//handles edge case where we need for force set the due date of the invoice. //handles edge case where we need for force set the due date of the invoice.
if((isset($input['partial_due_date']) && strlen($input['partial_due_date']) > 1) && (!array_key_exists('due_date', $input) || (empty($input['due_date']) && empty($this->invoice->due_date)))) { if((isset($input['partial_due_date']) && strlen($input['partial_due_date']) > 1) && (!array_key_exists('due_date', $input) || (empty($input['due_date']) && empty($this->invoice->due_date)))) {
$client = \App\Models\Client::withTrashed()->find($input['client_id']); $client = \App\Models\Client::withTrashed()->find($input['client_id']);
$input['due_date'] = \Illuminate\Support\Carbon::parse($input['date'])->addDays($client->getSetting('payment_terms'))->format('Y-m-d'); $input['due_date'] = \Illuminate\Support\Carbon::parse($input['date'])->addDays((int)$client->getSetting('payment_terms'))->format('Y-m-d');
} }
$this->replace($input); $this->replace($input);

View File

@ -45,7 +45,8 @@ class StoreProjectRequest extends Request
$rules['name'] = 'required'; $rules['name'] = 'required';
$rules['client_id'] = 'required|exists:clients,id,company_id,'.$user->company()->id; $rules['client_id'] = 'required|exists:clients,id,company_id,'.$user->company()->id;
$rules['budgeted_hours'] = 'sometimes|numeric'; $rules['budgeted_hours'] = 'sometimes|numeric';
$rules['task_rate'] = 'required|bail|numeric';
if (isset($this->number)) { if (isset($this->number)) {
$rules['number'] = Rule::unique('projects')->where('company_id', $user->company()->id); $rules['number'] = Rule::unique('projects')->where('company_id', $user->company()->id);
} }
@ -79,6 +80,8 @@ class StoreProjectRequest extends Request
$input['budgeted_hours'] = 0; $input['budgeted_hours'] = 0;
} }
$input['task_rate'] = isset($input['task_rate']) ? $input['task_rate'] : 0;
$this->replace($input); $this->replace($input);
} }

View File

@ -105,7 +105,7 @@ class StoreQuoteRequest extends Request
if(isset($input['partial_due_date']) && (!isset($input['due_date']) || strlen($input['due_date']) <= 1)) { if(isset($input['partial_due_date']) && (!isset($input['due_date']) || strlen($input['due_date']) <= 1)) {
$client = \App\Models\Client::withTrashed()->find($input['client_id']); $client = \App\Models\Client::withTrashed()->find($input['client_id']);
$valid_days = ($client && strlen($client->getSetting('valid_until')) >= 1) ? $client->getSetting('valid_until') : 7; $valid_days = ($client && strlen($client->getSetting('valid_until')) >= 1) ? $client->getSetting('valid_until') : 7;
$input['due_date'] = \Carbon\Carbon::parse($input['date'])->addDays($valid_days)->format('Y-m-d'); $input['due_date'] = \Carbon\Carbon::parse($input['date'])->addDays((int)$valid_days)->format('Y-m-d');
} }
$this->replace($input); $this->replace($input);

View File

@ -104,6 +104,8 @@ class BaseImport
return null; return null;
} }
nlog("found {$entity_type}");
$csv = base64_decode($base64_encoded_csv); $csv = base64_decode($base64_encoded_csv);
$csv = mb_convert_encoding($csv, 'UTF-8', 'UTF-8'); $csv = mb_convert_encoding($csv, 'UTF-8', 'UTF-8');

View File

@ -112,8 +112,7 @@ class CreateRawPdf
try { try {
$pdf = $ps->boot()->getPdf(); $pdf = $ps->boot()->getPdf();
} catch (\Exception $e) { } catch (\Exception $e) {
echo "EXCEPTION::".PHP_EOL; nlog($e->getMessage());
echo $e->getMessage().PHP_EOL;
throw new FilePermissionsFailure('Unable to generate the raw PDF'); throw new FilePermissionsFailure('Unable to generate the raw PDF');
} }

View File

@ -188,13 +188,13 @@ class SendReminders implements ShouldQueue
switch ($schedule_reminder) { switch ($schedule_reminder) {
case 'after_invoice_date': case 'after_invoice_date':
return Carbon::parse($invoice->date)->addDays($num_days_reminder)->startOfDay()->addSeconds($offset); return Carbon::parse($invoice->date)->addDays((int)$num_days_reminder)->startOfDay()->addSeconds($offset);
break; break;
case 'before_due_date': case 'before_due_date':
return Carbon::parse($invoice->due_date)->subDays($num_days_reminder)->startOfDay()->addSeconds($offset); return Carbon::parse($invoice->due_date)->subDays((int)$num_days_reminder)->startOfDay()->addSeconds($offset);
break; break;
case 'after_due_date': case 'after_due_date':
return Carbon::parse($invoice->due_date)->addDays($num_days_reminder)->startOfDay()->addSeconds($offset); return Carbon::parse($invoice->due_date)->addDays((int)$num_days_reminder)->startOfDay()->addSeconds($offset);
break; break;
default: default:
return null; return null;

View File

@ -71,7 +71,7 @@ class SystemMaintenance implements ShouldQueue
} }
Invoice::with('invitations') Invoice::with('invitations')
->whereBetween('created_at', [now()->subYear(), now()->subDays($delete_pdf_days)]) ->whereBetween('created_at', [now()->subYear(), now()->subDays((int)$delete_pdf_days)])
->withTrashed() ->withTrashed()
->cursor() ->cursor()
->each(function ($invoice) { ->each(function ($invoice) {
@ -81,7 +81,7 @@ class SystemMaintenance implements ShouldQueue
}); });
Quote::with('invitations') Quote::with('invitations')
->whereBetween('created_at', [now()->subYear(), now()->subDays($delete_pdf_days)]) ->whereBetween('created_at', [now()->subYear(), now()->subDays((int)$delete_pdf_days)])
->withTrashed() ->withTrashed()
->cursor() ->cursor()
->each(function ($quote) { ->each(function ($quote) {
@ -91,7 +91,7 @@ class SystemMaintenance implements ShouldQueue
}); });
Credit::with('invitations') Credit::with('invitations')
->whereBetween('created_at', [now()->subYear(), now()->subDays($delete_pdf_days)]) ->whereBetween('created_at', [now()->subYear(), now()->subDays((int)$delete_pdf_days)])
->withTrashed() ->withTrashed()
->cursor() ->cursor()
->each(function ($credit) { ->each(function ($credit) {
@ -107,7 +107,7 @@ class SystemMaintenance implements ShouldQueue
return; return;
} }
Backup::where('created_at', '<', now()->subDays($delete_backup_days)) Backup::where('created_at', '<', now()->subDays((int)$delete_backup_days))
->cursor() ->cursor()
->each(function ($backup) { ->each(function ($backup) {
nlog("deleting {$backup->filename}"); nlog("deleting {$backup->filename}");

View File

@ -125,22 +125,15 @@ class QuoteReminderJob implements ShouldQueue
return; return;
} }
$reminder_template = $quote->calculateTemplate('invoice'); $reminder_template = $quote->calculateTemplate('quote');
nrlog("#{$quote->number} => reminder template = {$reminder_template}"); nrlog("#{$quote->number} => reminder template = {$reminder_template}");
$quote->service()->touchReminder($reminder_template)->save(); $quote->service()->touchReminder($reminder_template)->save();
$fees = $this->calcLateFee($quote, $reminder_template);
if($quote->isLocked()) {
return $this->addFeeToNewQuote($quote, $reminder_template, $fees);
}
$quote = $this->setLateFee($quote, $fees[0], $fees[1]);
//20-04-2022 fixes for endless reminders - generic template naming was wrong //20-04-2022 fixes for endless reminders - generic template naming was wrong
$enabled_reminder = 'enable_'.$reminder_template; $enabled_reminder = 'enable_quote_'.$reminder_template;
if ($reminder_template == 'endless_reminder') { // if ($reminder_template == 'endless_reminder') {
$enabled_reminder = 'enable_reminder_endless'; // $enabled_reminder = 'enable_reminder_endless';
} // }
if (in_array($reminder_template, ['reminder1', 'reminder2', 'reminder3', 'reminder_endless', 'endless_reminder']) && if (in_array($reminder_template, ['reminder1', 'reminder2', 'reminder3', 'reminder_endless', 'endless_reminder']) &&
$quote->client->getSetting($enabled_reminder) && $quote->client->getSetting($enabled_reminder) &&
@ -149,9 +142,9 @@ class QuoteReminderJob implements ShouldQueue
$quote->invitations->each(function ($invitation) use ($quote, $reminder_template) { $quote->invitations->each(function ($invitation) use ($quote, $reminder_template) {
if ($invitation->contact && !$invitation->contact->trashed() && $invitation->contact->email) { if ($invitation->contact && !$invitation->contact->trashed() && $invitation->contact->email) {
EmailEntity::dispatch($invitation, $invitation->company, $reminder_template); EmailEntity::dispatch($invitation, $invitation->company, $reminder_template);
nrlog("Firing reminder email for invoice {$quote->number} - {$reminder_template}"); nrlog("Firing reminder email for quote {$quote->number} - {$reminder_template}");
$quote->entityEmailEvent($invitation, $reminder_template); $quote->entityEmailEvent($invitation, $reminder_template);
$quote->sendEvent(Webhook::EVENT_REMIND_INVOICE, "client"); $quote->sendEvent(Webhook::EVENT_REMIND_QUOTE, "client");
} }
}); });
} }
@ -162,162 +155,4 @@ class QuoteReminderJob implements ShouldQueue
} }
} }
private function addFeeToNewQuote(Quote $over_due_quote, string $reminder_template, array $fees)
{
$amount = $fees[0];
$percent = $fees[1];
$quote = false;
//2024-06-07 this early return prevented any reminders from sending for users who enabled lock_invoices.
if ($amount > 0 || $percent > 0) {
// return;
$fee = $amount;
if ($over_due_quote->partial > 0) {
$fee += round($over_due_quote->partial * $percent / 100, 2);
} else {
$fee += round($over_due_quote->balance * $percent / 100, 2);
}
/** @var \App\Models\Invoice $quote */
$quote = InvoiceFactory::create($over_due_quote->company_id, $over_due_quote->user_id);
$quote->client_id = $over_due_quote->client_id;
$quote->date = now()->format('Y-m-d');
$quote->due_date = now()->format('Y-m-d');
$quote_item = new InvoiceItem();
$quote_item->type_id = '5';
$quote_item->product_key = trans('texts.fee');
$quote_item->notes = ctrans('texts.late_fee_added_locked_invoice', ['invoice' => $over_due_quote->number, 'date' => $this->translateDate(now()->startOfDay(), $over_due_invoice->client->date_format(), $over_due_invoice->client->locale())]);
$quote_item->quantity = 1;
$quote_item->cost = $fee;
$quote_items = [];
$quote_items[] = $quote_item;
$quote->line_items = $quote_items;
/**Refresh Invoice values*/
$quote = $quote->calc()->getInvoice();
$quote->service()
->createInvitations()
->applyNumber()
->markSent()
->save();
}
if(!$quote) {
$quote = $over_due_quote;
}
$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']) &&
$quote->client->getSetting($enabled_reminder) &&
$quote->client->getSetting('send_reminders') &&
(Ninja::isSelfHost() || $quote->company->account->isPaidHostedClient())) {
$quote->invitations->each(function ($invitation) use ($quote, $reminder_template) {
if ($invitation->contact && !$invitation->contact->trashed() && $invitation->contact->email) {
EmailEntity::dispatch($invitation, $invitation->company, $reminder_template);
nrlog("Firing reminder email for qipte {$quote->number} - {$reminder_template}");
event(new QuoteReminderWasEmailed($invitation, $invitation->company, Ninja::eventVars(auth()->user() ? auth()->user()->id : null), $reminder_template));
$quote->sendEvent(Webhook::EVENT_REMIND_QUOTE, "client");
}
});
}
$quote->service()->setReminder()->save();
}
/**
* Calculates the late if - if any - and rebuilds the invoice
*
* @param Invoice $quote
* @param string $template
* @return array
*/
private function calcLateFee($quote, $template): array
{
$late_fee_amount = 0;
$late_fee_percent = 0;
switch ($template) {
case 'reminder1':
$late_fee_amount = $quote->client->getSetting('late_fee_amount1');
$late_fee_percent = $quote->client->getSetting('late_fee_percent1');
break;
case 'reminder2':
$late_fee_amount = $quote->client->getSetting('late_fee_amount2');
$late_fee_percent = $quote->client->getSetting('late_fee_percent2');
break;
case 'reminder3':
$late_fee_amount = $quote->client->getSetting('late_fee_amount3');
$late_fee_percent = $quote->client->getSetting('late_fee_percent3');
break;
case 'endless_reminder':
$late_fee_amount = $quote->client->getSetting('late_fee_endless_amount');
$late_fee_percent = $quote->client->getSetting('late_fee_endless_percent');
break;
default:
$late_fee_amount = 0;
$late_fee_percent = 0;
break;
}
return [$late_fee_amount, $late_fee_percent];
}
/**
* Applies the late fee to the invoice line items
*
* @param Invoice $quote
* @param float $amount The fee amount
* @param float $percent The fee percentage amount
*
* @return Invoice
*/
private function setLateFee($quote, $amount, $percent): Invoice
{
$temp_invoice_balance = $quote->balance;
if ($amount <= 0 && $percent <= 0) {
return $quote;
}
$fee = $amount;
if ($quote->partial > 0) {
$fee += round($quote->partial * $percent / 100, 2);
} else {
$fee += round($quote->balance * $percent / 100, 2);
}
$quote_item = new InvoiceItem();
$quote_item->type_id = '5';
$quote_item->product_key = trans('texts.fee');
$quote_item->notes = ctrans('texts.late_fee_added', ['date' => $this->translateDate(now()->startOfDay(), $quote->client->date_format(), $quote->client->locale())]);
$quote_item->quantity = 1;
$quote_item->cost = $fee;
$quote_items = $quote->line_items;
$quote_items[] = $quote_item;
$quote->line_items = $quote_items;
/**Refresh Invoice values*/
$quote = $quote->calc()->getInvoice();
$quote->ledger()->updateInvoiceBalance($quote->balance - $temp_invoice_balance, "Late Fee Adjustment for invoice {$quote->number}");
$quote->client->service()->calculateBalance();
return $quote;
}
} }

View File

@ -21,6 +21,7 @@ class UpdateInvoiceActivity implements ShouldQueue
{ {
protected $activity_repo; protected $activity_repo;
public $delay = 10;
/** /**
* Create the event listener. * Create the event listener.
* *
@ -52,5 +53,6 @@ class UpdateInvoiceActivity implements ShouldQueue
$fields->invoice_id = $event->invoice->id; $fields->invoice_id = $event->invoice->id;
$this->activity_repo->save($fields, $event->invoice, $event->event_vars); $this->activity_repo->save($fields, $event->invoice, $event->event_vars);
} }
} }

View File

@ -397,28 +397,50 @@ class Quote extends BaseModel
*/ */
public function calculateTemplate(string $entity_string): string public function calculateTemplate(string $entity_string): string
{ {
return $entity_string;
$client = $this->client;
if ($entity_string != 'quote') {
return $entity_string;
}
if ($this->inReminderWindow(
$client->getSetting('quote_schedule_reminder1'),
$client->getSetting('quote_num_days_reminder1')
) && ! $this->reminder1_sent) {
return 'reminder1';
// } elseif ($this->inReminderWindow(
// $client->getSetting('schedule_reminder2'),
// $client->getSetting('num_days_reminder2')
// ) && ! $this->reminder2_sent) {
// return 'reminder2';
// } elseif ($this->inReminderWindow(
// $client->getSetting('schedule_reminder3'),
// $client->getSetting('num_days_reminder3')
// ) && ! $this->reminder3_sent) {
// return 'reminder3';
// } elseif ($this->checkEndlessReminder(
// $this->reminder_last_sent,
// $client->getSetting('endless_reminder_frequency_id')
// )) {
// return 'endless_reminder';
} else {
return $entity_string;
}
} }
/** /**
* isPayable - proxy for matching Invoice status as
* to whether the quote is still valid, allows
* reuse of UpdateReminder class
*
* @return bool * @return bool
*/ */
public function isPayable(): bool public function canRemind(): bool
{ {
if ($this->status_id == self::STATUS_SENT && $this->is_deleted == false && $this->due_date->gte(now()->addSeconds($this->timezone_offset()))) { if (in_array($this->status_id, [self::STATUS_DRAFT, self::STATUS_APPROVED, self::STATUS_CONVERTED]) || $this->is_deleted)
return true;
} elseif ($this->status_id == self::STATUS_DRAFT || $this->is_deleted) {
return false; return false;
} elseif (in_array($this->status_id, [self::STATUS_APPROVED, self::STATUS_CONVERTED])) {
return false; return true;
} else {
return false;
}
} }
} }

View File

@ -684,7 +684,7 @@ class RecurringInvoice extends BaseModel
return null; return null;
} }
return $new_date->addDays($client_payment_terms); //add the number of days in the payment terms to the date return $new_date->addDays((int)$client_payment_terms); //add the number of days in the payment terms to the date
} }
/** /**

View File

@ -549,7 +549,7 @@ class RecurringQuote extends BaseModel
case 'terms': case 'terms':
return $this->calculateDateFromTerms($date); return $this->calculateDateFromTerms($date);
default: default:
return $this->setDayOfMonth($date, $this->due_date_days); return $this->setDayOfMonth($date, ($this->due_date_days ?? 1));
} }
} }
@ -569,7 +569,7 @@ class RecurringQuote extends BaseModel
return null; return null;
} }
return $new_date->addDays($client_payment_terms); //add the number of days in the payment terms to the date return $new_date->addDays((int)$client_payment_terms); //add the number of days in the payment terms to the date
} }
/** /**

View File

@ -208,7 +208,7 @@ class Task extends BaseModel
$parts = json_decode($this->time_log) ?: []; $parts = json_decode($this->time_log) ?: [];
if (count($parts)) { if (count($parts)) {
return Carbon::createFromTimeStamp($parts[0][0])->timestamp; return Carbon::createFromTimeStamp((int)$parts[0][0])->timestamp;
} else { } else {
return null; return null;
} }
@ -281,11 +281,11 @@ class Task extends BaseModel
$parent_entity = $this->client ?? $this->company; $parent_entity = $this->client ?? $this->company;
if($log[0]) { if($log[0]) {
$log[0] = Carbon::createFromTimestamp($log[0])->format($parent_entity->date_format().' H:i:s'); $log[0] = Carbon::createFromTimestamp((int)$log[0])->format($parent_entity->date_format().' H:i:s');
} }
if($log[1] && $log[1] != 0) { if($log[1] && $log[1] != 0) {
$log[1] = Carbon::createFromTimestamp($log[1])->format($parent_entity->date_format().' H:i:s'); $log[1] = Carbon::createFromTimestamp((int)$log[1])->format($parent_entity->date_format().' H:i:s');
} else { } else {
$log[1] = ctrans('texts.running'); $log[1] = ctrans('texts.running');
} }
@ -313,11 +313,11 @@ class Task extends BaseModel
if($log[0]) { if($log[0]) {
$logged['start_date_raw'] = $log[0]; $logged['start_date_raw'] = $log[0];
} }
$logged['start_date'] = Carbon::createFromTimestamp($log[0])->setTimeZone($this->company->timezone()->name)->format($parent_entity->date_format().' H:i:s'); $logged['start_date'] = Carbon::createFromTimestamp((int)$log[0])->setTimeZone($this->company->timezone()->name)->format($parent_entity->date_format().' H:i:s');
if($log[1] && $log[1] != 0) { if($log[1] && $log[1] != 0) {
$logged['end_date_raw'] = $log[1]; $logged['end_date_raw'] = $log[1];
$logged['end_date'] = Carbon::createFromTimestamp($log[1])->setTimeZone($this->company->timezone()->name)->format($parent_entity->date_format().' H:i:s'); $logged['end_date'] = Carbon::createFromTimestamp((int)$log[1])->setTimeZone($this->company->timezone()->name)->format($parent_entity->date_format().' H:i:s');
} else { } else {
$logged['end_date_raw'] = 0; $logged['end_date_raw'] = 0;
$logged['end_date'] = ctrans('texts.running'); $logged['end_date'] = ctrans('texts.running');

View File

@ -81,6 +81,8 @@ class ActivityRepository extends BaseRepository
return; return;
} }
$entity = $entity->fresh();
if (get_class($entity) == Invoice::class if (get_class($entity) == Invoice::class
|| get_class($entity) == Quote::class || get_class($entity) == Quote::class
|| get_class($entity) == Credit::class || get_class($entity) == Credit::class

View File

@ -64,6 +64,8 @@ class InvoiceRepository extends BaseRepository
*/ */
public function delete($invoice): Invoice public function delete($invoice): Invoice
{ {
$invoice = $invoice->fresh();
if ($invoice->is_deleted) { if ($invoice->is_deleted) {
return $invoice; return $invoice;
} }

View File

@ -157,7 +157,7 @@ class TaskRepository extends BaseRepository
{ {
if(isset($time_log[0][0])) { if(isset($time_log[0][0])) {
return \Carbon\Carbon::createFromTimestamp($time_log[0][0])->addSeconds($task->company->utc_offset()); return \Carbon\Carbon::createFromTimestamp((int)$time_log[0][0])->addSeconds($task->company->utc_offset());
} }
return null; return null;

View File

@ -37,6 +37,50 @@ trait ChartQueries
", ['company_currency' => $this->company->settings->currency_id, 'company_id' => $this->company->id, 'start_date' => $start_date, 'end_date' => $end_date]); ", ['company_currency' => $this->company->settings->currency_id, 'company_id' => $this->company->id, 'start_date' => $start_date, 'end_date' => $end_date]);
} }
public function getAggregateExpenseQuery($start_date, $end_date)
{
$user_filter = $this->is_admin ? '' : 'AND expenses.user_id = '.$this->user->id;
return DB::select("
SELECT
sum(expenses.amount / IFNULL(CAST(JSON_UNQUOTE(JSON_EXTRACT(clients.settings, '$.currency_id')) AS SIGNED), :company_currency2)) as amount,
IFNULL(expenses.currency_id, :company_currency) as currency_id
FROM expenses
JOIN clients
ON expenses.client_id=clients.id
WHERE expenses.is_deleted = 0
AND expenses.company_id = :company_id
AND (expenses.date BETWEEN :start_date AND :end_date)
{$user_filter}
GROUP BY currency_id
", ['company_currency2' => $this->company->settings->currency_id, 'company_currency' => $this->company->settings->currency_id, 'company_id' => $this->company->id, 'start_date' => $start_date, 'end_date' => $end_date]);
}
public function getAggregateExpenseChartQuery($start_date, $end_date)
{
$user_filter = $this->is_admin ? '' : 'AND expenses.user_id = '.$this->user->id;
return DB::select("
SELECT
sum(expenses.amount / IFNULL(CAST(JSON_UNQUOTE(JSON_EXTRACT(clients.settings, '$.currency_id')) AS SIGNED), :company_currency)) as total,
expenses.date
FROM expenses
JOIN clients
ON expenses.client_id=clients.id
WHERE (expenses.date BETWEEN :start_date AND :end_date)
AND expenses.company_id = :company_id
AND expenses.is_deleted = 0
{$user_filter}
GROUP BY expenses.date
", [
'company_currency' => $this->company->settings->currency_id,
'company_id' => $this->company->id,
'start_date' => $start_date,
'end_date' => $end_date,
]);
}
public function getExpenseChartQuery($start_date, $end_date, $currency_id) public function getExpenseChartQuery($start_date, $end_date, $currency_id)
{ {
@ -88,6 +132,53 @@ trait ChartQueries
]); ]);
} }
public function getAggregatePaymentQuery($start_date, $end_date)
{
$user_filter = $this->is_admin ? '' : 'AND payments.user_id = '.$this->user->id;
return DB::select("
SELECT sum(payments.amount / payments.exchange_rate) as amount,
IFNULL(payments.currency_id, :company_currency) as currency_id
FROM payments
WHERE payments.is_deleted = 0
{$user_filter}
AND payments.company_id = :company_id
AND (payments.date BETWEEN :start_date AND :end_date)
GROUP BY currency_id
", [
'company_currency' => $this->company->settings->currency_id,
'company_id' => $this->company->id,
'start_date' => $start_date,
'end_date' => $end_date,
]);
}
public function getAggregatePaymentChartQuery($start_date, $end_date)
{
$user_filter = $this->is_admin ? '' : 'AND payments.user_id = '.$this->user->id;
return DB::select("
SELECT
sum((payments.amount - payments.refunded) / payments.exchange_rate) as total,
payments.date,
IFNULL(payments.currency_id, :company_currency) AS currency_id
FROM payments
WHERE payments.company_id = :company_id
AND payments.is_deleted = 0
{$user_filter}
AND payments.status_id IN (4,5,6)
AND (payments.date BETWEEN :start_date AND :end_date)
GROUP BY payments.date
", [
'company_currency' => $this->company->settings->currency_id,
'company_id' => $this->company->id,
'start_date' => $start_date,
'end_date' => $end_date,
]);
}
public function getPaymentChartQuery($start_date, $end_date, $currency_id) public function getPaymentChartQuery($start_date, $end_date, $currency_id)
{ {
@ -142,28 +233,54 @@ trait ChartQueries
", ['company_currency' => $this->company->settings->currency_id, 'company_id' => $this->company->id, 'start_date' => $start_date, 'end_date' => $end_date]); ", ['company_currency' => $this->company->settings->currency_id, 'company_id' => $this->company->id, 'start_date' => $start_date, 'end_date' => $end_date]);
} }
public function getRevenueQueryX($start_date, $end_date) public function getAggregateOutstandingQuery($start_date, $end_date)
{ {
$user_filter = $this->is_admin ? '' : 'AND clients.user_id = '.$this->user->id; $user_filter = $this->is_admin ? '' : 'AND clients.user_id = '.$this->user->id;
return DB::select(" return DB::select("
SELECT SELECT
sum(invoices.paid_to_date) as paid_to_date, sum(invoices.balance / IFNULL(CAST(JSON_UNQUOTE(JSON_EXTRACT(clients.settings, '$.currency_id')) AS SIGNED), :company_currency2)) as amount,
COUNT(invoices.id) as outstanding_count,
IFNULL(CAST(JSON_UNQUOTE(JSON_EXTRACT( clients.settings, '$.currency_id' )) AS SIGNED), :company_currency) AS currency_id IFNULL(CAST(JSON_UNQUOTE(JSON_EXTRACT( clients.settings, '$.currency_id' )) AS SIGNED), :company_currency) AS currency_id
FROM clients FROM clients
JOIN invoices JOIN invoices
on invoices.client_id = clients.id on invoices.client_id = clients.id
WHERE invoices.company_id = :company_id WHERE invoices.status_id IN (2,3)
AND invoices.company_id = :company_id
AND clients.is_deleted = 0 AND clients.is_deleted = 0
{$user_filter} {$user_filter}
AND invoices.is_deleted = 0 AND invoices.is_deleted = 0
AND invoices.amount > 0 AND invoices.balance > 0
AND invoices.status_id IN (3,4)
AND (invoices.date BETWEEN :start_date AND :end_date) AND (invoices.date BETWEEN :start_date AND :end_date)
GROUP BY currency_id ", [
", ['company_currency' => $this->company->settings->currency_id, 'company_id' => $this->company->id, 'start_date' => $start_date, 'end_date' => $end_date]); 'company_currency2' => $this->company->settings->currency_id,
'company_currency' => $this->company->settings->currency_id,
'company_id' => $this->company->id,
'start_date' => $start_date,
'end_date' => $end_date]);
} }
public function getAggregateRevenueQuery($start_date, $end_date)
{
$user_filter = $this->is_admin ? '' : 'AND payments.user_id = '.$this->user->id;
return DB::select("
SELECT
sum((payments.amount - payments.refunded) * payments.exchange_rate) as paid_to_date,
payments.currency_id AS currency_id
FROM payments
WHERE payments.company_id = :company_id
AND payments.is_deleted = 0
{$user_filter}
AND payments.status_id IN (1,4,5,6)
AND (payments.date BETWEEN :start_date AND :end_date)
GROUP BY payments.currency_id
", ['company_id' => $this->company->id, 'start_date' => $start_date, 'end_date' => $end_date]);
}
public function getRevenueQuery($start_date, $end_date) public function getRevenueQuery($start_date, $end_date)
{ {
$user_filter = $this->is_admin ? '' : 'AND payments.user_id = '.$this->user->id; $user_filter = $this->is_admin ? '' : 'AND payments.user_id = '.$this->user->id;
@ -182,6 +299,30 @@ trait ChartQueries
", ['company_id' => $this->company->id, 'start_date' => $start_date, 'end_date' => $end_date]); ", ['company_id' => $this->company->id, 'start_date' => $start_date, 'end_date' => $end_date]);
} }
public function getAggregateInvoicesQuery($start_date, $end_date)
{
$user_filter = $this->is_admin ? '' : 'AND clients.user_id = '.$this->user->id;
return DB::select("
SELECT
sum(invoices.amount / IFNULL(CAST(JSON_UNQUOTE(JSON_EXTRACT(clients.settings, '$.currency_id')) AS SIGNED), :company_currency2)) as invoiced_amount,
IFNULL(CAST(JSON_UNQUOTE(JSON_EXTRACT( clients.settings, '$.currency_id' )) AS SIGNED), :company_currency) AS currency_id
FROM clients
JOIN invoices
on invoices.client_id = clients.id
WHERE invoices.status_id IN (2,3,4)
AND invoices.company_id = :company_id
{$user_filter}
AND invoices.amount > 0
AND clients.is_deleted = 0
AND invoices.is_deleted = 0
AND (invoices.date BETWEEN :start_date AND :end_date)
GROUP BY invoices.company_id
", ['company_currency2' => $this->company->settings->currency_id, 'company_currency' => $this->company->settings->currency_id, 'company_id' => $this->company->id, 'start_date' => $start_date, 'end_date' => $end_date]);
}
public function getInvoicesQuery($start_date, $end_date) public function getInvoicesQuery($start_date, $end_date)
{ {
$user_filter = $this->is_admin ? '' : 'AND clients.user_id = '.$this->user->id; $user_filter = $this->is_admin ? '' : 'AND clients.user_id = '.$this->user->id;
@ -204,6 +345,32 @@ trait ChartQueries
", ['company_currency' => $this->company->settings->currency_id, 'company_id' => $this->company->id, 'start_date' => $start_date, 'end_date' => $end_date]); ", ['company_currency' => $this->company->settings->currency_id, 'company_id' => $this->company->id, 'start_date' => $start_date, 'end_date' => $end_date]);
} }
public function getAggregateOutstandingChartQuery($start_date, $end_date)
{
$user_filter = $this->is_admin ? '' : 'AND clients.user_id = '.$this->user->id;
return DB::select("
SELECT
sum(invoices.balance / IFNULL(CAST(JSON_UNQUOTE(JSON_EXTRACT(clients.settings, '$.currency_id')) AS SIGNED), :company_currency)) as total,
invoices.date
FROM clients
JOIN invoices
on invoices.client_id = clients.id
WHERE invoices.status_id IN (2,3,4)
AND invoices.company_id = :company_id
AND clients.is_deleted = 0
AND invoices.is_deleted = 0
{$user_filter}
AND (invoices.date BETWEEN :start_date AND :end_date)
GROUP BY invoices.company_id
", [
'company_currency' => (int) $this->company->settings->currency_id,
'company_id' => $this->company->id,
'start_date' => $start_date,
'end_date' => $end_date,
]);
}
public function getOutstandingChartQuery($start_date, $end_date, $currency_id) public function getOutstandingChartQuery($start_date, $end_date, $currency_id)
{ {
$user_filter = $this->is_admin ? '' : 'AND clients.user_id = '.$this->user->id; $user_filter = $this->is_admin ? '' : 'AND clients.user_id = '.$this->user->id;
@ -234,6 +401,32 @@ trait ChartQueries
} }
public function getAggregateInvoiceChartQuery($start_date, $end_date)
{
$user_filter = $this->is_admin ? '' : 'AND clients.user_id = '.$this->user->id;
return DB::select("
SELECT
sum(invoices.amount / IFNULL(CAST(JSON_UNQUOTE(JSON_EXTRACT(clients.settings, '$.currency_id')) AS SIGNED), :company_currency)) as total,
invoices.date
FROM clients
JOIN invoices
on invoices.client_id = clients.id
WHERE invoices.company_id = :company_id
AND clients.is_deleted = 0
AND invoices.is_deleted = 0
{$user_filter}
AND invoices.status_id IN (2,3,4)
AND (invoices.date BETWEEN :start_date AND :end_date)
GROUP BY invoices.company_id
", [
'company_currency' => (int) $this->company->settings->currency_id,
'company_id' => $this->company->id,
'start_date' => $start_date,
'end_date' => $end_date,
]);
}
public function getInvoiceChartQuery($start_date, $end_date, $currency_id) public function getInvoiceChartQuery($start_date, $end_date, $currency_id)
{ {
$user_filter = $this->is_admin ? '' : 'AND clients.user_id = '.$this->user->id; $user_filter = $this->is_admin ? '' : 'AND clients.user_id = '.$this->user->id;

View File

@ -88,6 +88,12 @@ class ChartService
$data[$key]['expenses'] = $this->getExpenseChartQuery($start_date, $end_date, $key); $data[$key]['expenses'] = $this->getExpenseChartQuery($start_date, $end_date, $key);
} }
$data[999]['invoices'] = $this->getAggregateInvoiceChartQuery($start_date, $end_date);
$data[999]['outstanding'] = $this->getAggregateOutstandingChartQuery($start_date, $end_date);
$data[999]['payments'] = $this->getAggregatePaymentChartQuery($start_date, $end_date);
$data[999]['expenses'] = $this->getAggregateExpenseChartQuery($start_date, $end_date);
return $data; return $data;
} }
@ -123,6 +129,17 @@ class ChartService
} }
$aggregate_revenue = $this->getAggregateRevenueQuery($start_date, $end_date);
$aggregate_outstanding = $this->getAggregateOutstandingQuery($start_date, $end_date);
$aggregate_expenses = $this->getAggregateExpenseQuery($start_date, $end_date);
$aggregate_invoices = $this->getAggregateInvoicesQuery($start_date, $end_date);
$data[999]['invoices'] = $aggregate_invoices !== false ? $aggregate_invoices : new \stdClass();
$data[999]['expense'] = $aggregate_expenses !== false ? $aggregate_expenses : new \stdClass();
$data[999]['outstanding'] = $aggregate_outstanding !== false ? $aggregate_outstanding : new \stdClass();
$data[999]['revenue'] = $aggregate_revenue !== false ? $aggregate_revenue : new \stdClass();
return $data; return $data;
} }

View File

@ -245,7 +245,7 @@ class InstantPayment
$hash_data['billing_context'] = Cache::get($this->request->query('hash')); $hash_data['billing_context'] = Cache::get($this->request->query('hash'));
} elseif ($this->request->hash) { } elseif ($this->request->hash) {
$hash_data['billing_context'] = Cache::get($this->request->hash); $hash_data['billing_context'] = Cache::get($this->request->hash);
} elseif ($old_hash = PaymentHash::query()->where('fee_invoice_id', $first_invoice->id)->whereNull('payment_id')->first()) { } elseif ($old_hash = PaymentHash::query()->where('fee_invoice_id', $first_invoice->id)->whereNull('payment_id')->orderBy('id','desc')->first()) {
if (isset($old_hash->data->billing_context)) { if (isset($old_hash->data->billing_context)) {
$hash_data['billing_context'] = $old_hash->data->billing_context; $hash_data['billing_context'] = $old_hash->data->billing_context;
} }

View File

@ -292,9 +292,9 @@ class InvoiceService
//12-10-2022 //12-10-2022
if ($this->invoice->partial > 0 && !$this->invoice->partial_due_date) { if ($this->invoice->partial > 0 && !$this->invoice->partial_due_date) {
$this->invoice->partial_due_date = Carbon::parse($this->invoice->date)->addDays($this->invoice->client->getSetting('payment_terms')); $this->invoice->partial_due_date = Carbon::parse($this->invoice->date)->addDays((int)$this->invoice->client->getSetting('payment_terms'));
} else { } else {
$this->invoice->due_date = Carbon::parse($this->invoice->date)->addDays($this->invoice->client->getSetting('payment_terms')); $this->invoice->due_date = Carbon::parse($this->invoice->date)->addDays((int)$this->invoice->client->getSetting('payment_terms'));
} }
return $this; return $this;

View File

@ -19,7 +19,7 @@ use Carbon\Carbon;
class UpdateReminder extends AbstractService class UpdateReminder extends AbstractService
{ {
public function __construct(public Invoice | Quote $invoice, public mixed $settings = null) public function __construct(public Invoice $invoice, public mixed $settings = null)
{ {
} }
@ -47,7 +47,7 @@ class UpdateReminder extends AbstractService
if (is_null($this->invoice->reminder1_sent) && if (is_null($this->invoice->reminder1_sent) &&
$this->settings->schedule_reminder1 == 'after_invoice_date') { $this->settings->schedule_reminder1 == 'after_invoice_date') {
$reminder_date = Carbon::parse($this->invoice->date)->startOfDay()->addDays($this->settings->num_days_reminder1); $reminder_date = Carbon::parse($this->invoice->date)->startOfDay()->addDays((int)$this->settings->num_days_reminder1);
if ($reminder_date->gt(now())) { if ($reminder_date->gt(now())) {
$date_collection->push($reminder_date); $date_collection->push($reminder_date);
@ -58,7 +58,7 @@ class UpdateReminder extends AbstractService
($this->invoice->partial_due_date || $this->invoice->due_date) && ($this->invoice->partial_due_date || $this->invoice->due_date) &&
$this->settings->schedule_reminder1 == 'before_due_date') { $this->settings->schedule_reminder1 == 'before_due_date') {
$partial_or_due_date = ($this->invoice->partial > 0 && isset($this->invoice->partial_due_date)) ? $this->invoice->partial_due_date : $this->invoice->due_date; $partial_or_due_date = ($this->invoice->partial > 0 && isset($this->invoice->partial_due_date)) ? $this->invoice->partial_due_date : $this->invoice->due_date;
$reminder_date = Carbon::parse($partial_or_due_date)->startOfDay()->subDays($this->settings->num_days_reminder1); $reminder_date = Carbon::parse($partial_or_due_date)->startOfDay()->subDays((int)$this->settings->num_days_reminder1);
// nlog("1. {$reminder_date->format('Y-m-d')}"); // nlog("1. {$reminder_date->format('Y-m-d')}");
if ($reminder_date->gt(now())) { if ($reminder_date->gt(now())) {
@ -71,7 +71,7 @@ class UpdateReminder extends AbstractService
$this->settings->schedule_reminder1 == 'after_due_date') { $this->settings->schedule_reminder1 == 'after_due_date') {
$partial_or_due_date = ($this->invoice->partial > 0 && isset($this->invoice->partial_due_date)) ? $this->invoice->partial_due_date : $this->invoice->due_date; $partial_or_due_date = ($this->invoice->partial > 0 && isset($this->invoice->partial_due_date)) ? $this->invoice->partial_due_date : $this->invoice->due_date;
$reminder_date = Carbon::parse($partial_or_due_date)->startOfDay()->addDays($this->settings->num_days_reminder1); $reminder_date = Carbon::parse($partial_or_due_date)->startOfDay()->addDays((int)$this->settings->num_days_reminder1);
// nlog("2. {$reminder_date->format('Y-m-d')}"); // nlog("2. {$reminder_date->format('Y-m-d')}");
if ($reminder_date->gt(now())) { if ($reminder_date->gt(now())) {
@ -81,7 +81,7 @@ class UpdateReminder extends AbstractService
if (is_null($this->invoice->reminder2_sent) && if (is_null($this->invoice->reminder2_sent) &&
$this->settings->schedule_reminder2 == 'after_invoice_date') { $this->settings->schedule_reminder2 == 'after_invoice_date') {
$reminder_date = Carbon::parse($this->invoice->date)->startOfDay()->addDays($this->settings->num_days_reminder2); $reminder_date = Carbon::parse($this->invoice->date)->startOfDay()->addDays((int)$this->settings->num_days_reminder2);
if ($reminder_date->gt(now())) { if ($reminder_date->gt(now())) {
$date_collection->push($reminder_date); $date_collection->push($reminder_date);
@ -93,7 +93,7 @@ class UpdateReminder extends AbstractService
$this->settings->schedule_reminder2 == 'before_due_date') { $this->settings->schedule_reminder2 == 'before_due_date') {
$partial_or_due_date = ($this->invoice->partial > 0 && isset($this->invoice->partial_due_date)) ? $this->invoice->partial_due_date : $this->invoice->due_date; $partial_or_due_date = ($this->invoice->partial > 0 && isset($this->invoice->partial_due_date)) ? $this->invoice->partial_due_date : $this->invoice->due_date;
$reminder_date = Carbon::parse($partial_or_due_date)->startOfDay()->subDays($this->settings->num_days_reminder2); $reminder_date = Carbon::parse($partial_or_due_date)->startOfDay()->subDays((int)$this->settings->num_days_reminder2);
// nlog("3. {$reminder_date->format('Y-m-d')}"); // nlog("3. {$reminder_date->format('Y-m-d')}");
if ($reminder_date->gt(now())) { if ($reminder_date->gt(now())) {
@ -106,7 +106,7 @@ class UpdateReminder extends AbstractService
$this->settings->schedule_reminder2 == 'after_due_date') { $this->settings->schedule_reminder2 == 'after_due_date') {
$partial_or_due_date = ($this->invoice->partial > 0 && isset($this->invoice->partial_due_date)) ? $this->invoice->partial_due_date : $this->invoice->due_date; $partial_or_due_date = ($this->invoice->partial > 0 && isset($this->invoice->partial_due_date)) ? $this->invoice->partial_due_date : $this->invoice->due_date;
$reminder_date = Carbon::parse($partial_or_due_date)->startOfDay()->addDays($this->settings->num_days_reminder2); $reminder_date = Carbon::parse($partial_or_due_date)->startOfDay()->addDays((int)$this->settings->num_days_reminder2);
// nlog("4. {$reminder_date->format('Y-m-d')}"); // nlog("4. {$reminder_date->format('Y-m-d')}");
if ($reminder_date->gt(now())) { if ($reminder_date->gt(now())) {
@ -116,7 +116,7 @@ class UpdateReminder extends AbstractService
if (is_null($this->invoice->reminder3_sent) && if (is_null($this->invoice->reminder3_sent) &&
$this->settings->schedule_reminder3 == 'after_invoice_date') { $this->settings->schedule_reminder3 == 'after_invoice_date') {
$reminder_date = Carbon::parse($this->invoice->date)->startOfDay()->addDays($this->settings->num_days_reminder3); $reminder_date = Carbon::parse($this->invoice->date)->startOfDay()->addDays((int)$this->settings->num_days_reminder3);
if ($reminder_date->gt(now())) { if ($reminder_date->gt(now())) {
$date_collection->push($reminder_date); $date_collection->push($reminder_date);
@ -128,7 +128,7 @@ class UpdateReminder extends AbstractService
$this->settings->schedule_reminder3 == 'before_due_date') { $this->settings->schedule_reminder3 == 'before_due_date') {
$partial_or_due_date = ($this->invoice->partial > 0 && isset($this->invoice->partial_due_date)) ? $this->invoice->partial_due_date : $this->invoice->due_date; $partial_or_due_date = ($this->invoice->partial > 0 && isset($this->invoice->partial_due_date)) ? $this->invoice->partial_due_date : $this->invoice->due_date;
$reminder_date = Carbon::parse($partial_or_due_date)->startOfDay()->subDays($this->settings->num_days_reminder3); $reminder_date = Carbon::parse($partial_or_due_date)->startOfDay()->subDays((int)$this->settings->num_days_reminder3);
// nlog("5. {$reminder_date->format('Y-m-d')}"); // nlog("5. {$reminder_date->format('Y-m-d')}");
if ($reminder_date->gt(now())) { if ($reminder_date->gt(now())) {
@ -141,7 +141,7 @@ class UpdateReminder extends AbstractService
$this->settings->schedule_reminder3 == 'after_due_date') { $this->settings->schedule_reminder3 == 'after_due_date') {
$partial_or_due_date = ($this->invoice->partial > 0 && isset($this->invoice->partial_due_date)) ? $this->invoice->partial_due_date : $this->invoice->due_date; $partial_or_due_date = ($this->invoice->partial > 0 && isset($this->invoice->partial_due_date)) ? $this->invoice->partial_due_date : $this->invoice->due_date;
$reminder_date = Carbon::parse($partial_or_due_date)->startOfDay()->addDays($this->settings->num_days_reminder3); $reminder_date = Carbon::parse($partial_or_due_date)->startOfDay()->addDays((int)$this->settings->num_days_reminder3);
// nlog("6. {$reminder_date->format('Y-m-d')}"); // nlog("6. {$reminder_date->format('Y-m-d')}");
if ($reminder_date->gt(now())) { if ($reminder_date->gt(now())) {

View File

@ -27,10 +27,6 @@ class RefundPayment
private float $credits_used = 0; private float $credits_used = 0;
private $gateway_refund_status;
private $activity_repository;
private bool $refund_failed = false; private bool $refund_failed = false;
private string $refund_failed_message = ''; private string $refund_failed_message = '';

View File

@ -35,7 +35,7 @@ class MarkSent
if ($this->quote->due_date != '' || $this->client->getSetting('valid_until') == '') { if ($this->quote->due_date != '' || $this->client->getSetting('valid_until') == '') {
} else { } else {
$this->quote->due_date = Carbon::parse($this->quote->date)->addDays($this->client->getSetting('valid_until')); $this->quote->due_date = Carbon::parse($this->quote->date)->addDays((int)$this->client->getSetting('valid_until'));
} }
$this->quote $this->quote

View File

@ -17,7 +17,7 @@ use App\Jobs\EDocument\CreateEDocument;
use App\Models\Project; use App\Models\Project;
use App\Models\Quote; use App\Models\Quote;
use App\Repositories\QuoteRepository; use App\Repositories\QuoteRepository;
use App\Services\Invoice\UpdateReminder; use App\Services\Quote\UpdateReminder;
use App\Utils\Ninja; use App\Utils\Ninja;
use App\Utils\Traits\MakesHash; use App\Utils\Traits\MakesHash;
use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Storage;
@ -266,6 +266,41 @@ class QuoteService
return $this; return $this;
} }
/*When a reminder is sent we want to touch the dates they were sent*/
public function touchReminder(string $reminder_template)
{
nrlog(now()->format('Y-m-d h:i:s') . " INV #{$this->quote->number} : Touching Reminder => {$reminder_template}");
switch ($reminder_template) {
case 'reminder1':
$this->quote->reminder1_sent = now();
$this->quote->reminder_last_sent = now();
$this->quote->last_sent_date = now();
break;
case 'reminder2':
$this->quote->reminder2_sent = now();
$this->quote->reminder_last_sent = now();
$this->quote->last_sent_date = now();
break;
case 'reminder3':
$this->quote->reminder3_sent = now();
$this->quote->reminder_last_sent = now();
$this->quote->last_sent_date = now();
break;
case 'endless_reminder':
$this->quote->reminder_last_sent = now();
$this->invoice->last_sent_date = now();
break;
default:
$this->quote->reminder1_sent = now();
$this->quote->reminder_last_sent = now();
$this->quote->last_sent_date = now();
break;
}
return $this;
}
/** /**
* Saves the quote. * Saves the quote.
* @return Quote|null * @return Quote|null

View File

@ -0,0 +1,209 @@
<?php
/**
* Invoice Ninja (https://invoiceninja.com).
*
* @link https://github.com/invoiceninja/invoiceninja source repository
*
* @copyright Copyright (c) 2024. Invoice Ninja LLC (https://invoiceninja.com)
*
* @license https://www.elastic.co/licensing/elastic-license
*/
namespace App\Services\Quote;
use App\Models\Quote;
use App\Services\AbstractService;
use App\Models\RecurringInvoice;
use Carbon\Carbon;
class UpdateReminder extends AbstractService
{
public function __construct(public Quote $quote, public mixed $settings = null)
{
}
/* We only support setting reminders based on the due date, not the partial due date */
public function run()
{
if (! $this->settings) {
$this->settings = $this->quote->client->getMergedSettings();
}
if (!$this->quote->canRemind()) {
$this->quote->next_send_date = null;
$this->quote->saveQuietly();
return $this->quote; //exit early
}
if ($this->quote->next_send_date) {
$this->quote->next_send_date = null;
}
$offset = $this->quote->client->timezone_offset();
$date_collection = collect();
if (is_null($this->quote->reminder1_sent) &&
$this->settings->quote_schedule_reminder1 == 'after_quote_date') {
$reminder_date = Carbon::parse($this->quote->date)->startOfDay()->addDays((int)$this->settings->quote_num_days_reminder1);
if ($reminder_date->gt(now())) {
$date_collection->push($reminder_date);
}
}
if (is_null($this->quote->reminder1_sent) &&
($this->quote->partial_due_date || $this->quote->due_date) &&
$this->settings->quote_schedule_reminder1 == 'before_valid_until_date') {
$partial_or_due_date = ($this->quote->partial > 0 && isset($this->quote->partial_due_date)) ? $this->quote->partial_due_date : $this->quote->due_date;
$reminder_date = Carbon::parse($partial_or_due_date)->startOfDay()->subDays((int)$this->settings->quote_num_days_reminder1);
// nlog("1. {$reminder_date->format('Y-m-d')}");
if ($reminder_date->gt(now())) {
$date_collection->push($reminder_date);
}
}
if (is_null($this->quote->reminder1_sent) &&
($this->quote->partial_due_date || $this->quote->due_date) &&
$this->settings->quote_schedule_reminder1 == 'after_valid_until_date') {
$partial_or_due_date = ($this->quote->partial > 0 && isset($this->quote->partial_due_date)) ? $this->quote->partial_due_date : $this->quote->due_date;
$reminder_date = Carbon::parse($partial_or_due_date)->startOfDay()->addDays((int)$this->settings->quote_num_days_reminder1);
// nlog("2. {$reminder_date->format('Y-m-d')}");
if ($reminder_date->gt(now())) {
$date_collection->push($reminder_date);
}
}
// if (is_null($this->quote->reminder2_sent) &&
// $this->settings->schedule_reminder2 == 'after_valid_until_date') {
// $reminder_date = Carbon::parse($this->quote->date)->startOfDay()->addDays($this->settings->num_days_reminder2);
// if ($reminder_date->gt(now())) {
// $date_collection->push($reminder_date);
// }
// }
// if (is_null($this->quote->reminder2_sent) &&
// ($this->quote->partial_due_date || $this->quote->due_date) &&
// $this->settings->schedule_reminder2 == 'before_valid_until_date') {
// $partial_or_due_date = ($this->quote->partial > 0 && isset($this->quote->partial_due_date)) ? $this->quote->partial_due_date : $this->quote->due_date;
// $reminder_date = Carbon::parse($partial_or_due_date)->startOfDay()->subDays($this->settings->num_days_reminder2);
// // nlog("3. {$reminder_date->format('Y-m-d')}");
// if ($reminder_date->gt(now())) {
// $date_collection->push($reminder_date);
// }
// }
// if (is_null($this->quote->reminder2_sent) &&
// ($this->quote->partial_due_date || $this->quote->due_date) &&
// $this->settings->schedule_reminder2 == 'after_valid_until_date') {
// $partial_or_due_date = ($this->quote->partial > 0 && isset($this->quote->partial_due_date)) ? $this->quote->partial_due_date : $this->quote->due_date;
// $reminder_date = Carbon::parse($partial_or_due_date)->startOfDay()->addDays($this->settings->num_days_reminder2);
// // nlog("4. {$reminder_date->format('Y-m-d')}");
// if ($reminder_date->gt(now())) {
// $date_collection->push($reminder_date);
// }
// }
// if (is_null($this->quote->reminder3_sent) &&
// $this->settings->schedule_reminder3 == 'after_valid_until_date') {
// $reminder_date = Carbon::parse($this->quote->date)->startOfDay()->addDays($this->settings->num_days_reminder3);
// if ($reminder_date->gt(now())) {
// $date_collection->push($reminder_date);
// }
// }
// if (is_null($this->quote->reminder3_sent) &&
// ($this->quote->partial_due_date || $this->quote->due_date) &&
// $this->settings->schedule_reminder3 == 'before_valid_until_date') {
// $partial_or_due_date = ($this->quote->partial > 0 && isset($this->quote->partial_due_date)) ? $this->quote->partial_due_date : $this->quote->due_date;
// $reminder_date = Carbon::parse($partial_or_due_date)->startOfDay()->subDays($this->settings->num_days_reminder3);
// // nlog("5. {$reminder_date->format('Y-m-d')}");
// if ($reminder_date->gt(now())) {
// $date_collection->push($reminder_date);
// }
// }
// if (is_null($this->quote->reminder3_sent) &&
// ($this->quote->partial_due_date || $this->quote->due_date) &&
// $this->settings->schedule_reminder3 == 'after_valid_until_date') {
// $partial_or_due_date = ($this->quote->partial > 0 && isset($this->quote->partial_due_date)) ? $this->quote->partial_due_date : $this->quote->due_date;
// $reminder_date = Carbon::parse($partial_or_due_date)->startOfDay()->addDays($this->settings->num_days_reminder3);
// // nlog("6. {$reminder_date->format('Y-m-d')}");
// if ($reminder_date->gt(now())) {
// $date_collection->push($reminder_date);
// }
// }
// if ($this->quote->last_sent_date &&
// $this->settings->enable_reminder_endless &&
// ($this->quote->reminder1_sent || $this->settings->schedule_reminder1 == "" || !$this->settings->enable_reminder1) &&
// ($this->quote->reminder2_sent || $this->settings->schedule_reminder2 == "" || !$this->settings->enable_reminder2) &&
// ($this->quote->reminder3_sent || $this->settings->schedule_reminder3 == "" || !$this->settings->enable_reminder3)) {
// $reminder_date = $this->addTimeInterval($this->quote->last_sent_date, (int) $this->settings->endless_reminder_frequency_id);
// if ($reminder_date) {
// if ($reminder_date->gt(now())) {
// $date_collection->push($reminder_date);
// }
// }
// }
if ($date_collection->count() >= 1 && $date_collection->sort()->first()->gte(now())) {
$this->quote->next_send_date = $date_collection->sort()->first()->addSeconds($offset);
} else {
$this->quote->next_send_date = null;
}
return $this->quote;
}
private function addTimeInterval($date, $endless_reminder_frequency_id): ?Carbon
{
if (! $date) {
return null;
}
switch ($endless_reminder_frequency_id) {
case RecurringInvoice::FREQUENCY_DAILY:
return Carbon::parse($date)->addDay()->startOfDay();
case RecurringInvoice::FREQUENCY_WEEKLY:
return Carbon::parse($date)->addWeek()->startOfDay();
case RecurringInvoice::FREQUENCY_TWO_WEEKS:
return Carbon::parse($date)->addWeeks(2)->startOfDay();
case RecurringInvoice::FREQUENCY_FOUR_WEEKS:
return Carbon::parse($date)->addWeeks(4)->startOfDay();
case RecurringInvoice::FREQUENCY_MONTHLY:
return Carbon::parse($date)->addMonthNoOverflow()->startOfDay();
case RecurringInvoice::FREQUENCY_TWO_MONTHS:
return Carbon::parse($date)->addMonthsNoOverflow(2)->startOfDay();
case RecurringInvoice::FREQUENCY_THREE_MONTHS:
return Carbon::parse($date)->addMonthsNoOverflow(3)->startOfDay();
case RecurringInvoice::FREQUENCY_FOUR_MONTHS:
return Carbon::parse($date)->addMonthsNoOverflow(4)->startOfDay();
case RecurringInvoice::FREQUENCY_SIX_MONTHS:
return Carbon::parse($date)->addMonthsNoOverflow(6)->startOfDay();
case RecurringInvoice::FREQUENCY_ANNUALLY:
return Carbon::parse($date)->addYear()->startOfDay();
case RecurringInvoice::FREQUENCY_TWO_YEARS:
return Carbon::parse($date)->addYears(2)->startOfDay();
case RecurringInvoice::FREQUENCY_THREE_YEARS:
return Carbon::parse($date)->addYears(3)->startOfDay();
default:
return null;
}
}
}

View File

@ -100,7 +100,7 @@ class ARDetailReport extends BaseExport
->orderBy('due_date', 'ASC') ->orderBy('due_date', 'ASC')
->whereIn('status_id', [Invoice::STATUS_SENT, Invoice::STATUS_PARTIAL]); ->whereIn('status_id', [Invoice::STATUS_SENT, Invoice::STATUS_PARTIAL]);
$query = $this->addDateRange($query); $query = $this->addDateRange($query, 'invoices');
$query = $this->filterByClients($query); $query = $this->filterByClients($query);

View File

@ -110,7 +110,7 @@ class ClientBalanceReport extends BaseExport
$query = Invoice::query()->where('client_id', $client->id) $query = Invoice::query()->where('client_id', $client->id)
->whereIn('status_id', [Invoice::STATUS_SENT, Invoice::STATUS_PARTIAL]); ->whereIn('status_id', [Invoice::STATUS_SENT, Invoice::STATUS_PARTIAL]);
$query = $this->addDateRange($query); $query = $this->addDateRange($query, 'invoices');
return [ return [
$client->present()->name(), $client->present()->name(),

View File

@ -103,7 +103,7 @@ class ClientSalesReport extends BaseExport
$query = Invoice::query()->where('client_id', $client->id) $query = Invoice::query()->where('client_id', $client->id)
->whereIn('status_id', [Invoice::STATUS_SENT, Invoice::STATUS_PARTIAL, Invoice::STATUS_PAID]); ->whereIn('status_id', [Invoice::STATUS_SENT, Invoice::STATUS_PARTIAL, Invoice::STATUS_PAID]);
$query = $this->addDateRange($query); $query = $this->addDateRange($query, 'invoices');
$amount = $query->sum('amount'); $amount = $query->sum('amount');
$balance = $query->sum('balance'); $balance = $query->sum('balance');

View File

@ -81,7 +81,7 @@ class TaxSummaryReport extends BaseExport
->where('is_deleted', 0) ->where('is_deleted', 0)
->orderBy('balance', 'desc'); ->orderBy('balance', 'desc');
$query = $this->addDateRange($query); $query = $this->addDateRange($query, 'invoices');
$this->csv->insertOne([ctrans('texts.tax_summary')]); $this->csv->insertOne([ctrans('texts.tax_summary')]);
$this->csv->insertOne([ctrans('texts.created_on'),' ',$this->translateDate(now()->format('Y-m-d'), $this->company->date_format(), $this->company->locale())]); $this->csv->insertOne([ctrans('texts.created_on'),' ',$this->translateDate(now()->format('Y-m-d'), $this->company->date_format(), $this->company->locale())]);

View File

@ -69,7 +69,7 @@ class UserSalesReport extends BaseExport
->where('is_deleted', 0) ->where('is_deleted', 0)
->whereIn('status_id', [Invoice::STATUS_SENT, Invoice::STATUS_PARTIAL, Invoice::STATUS_PAID]); ->whereIn('status_id', [Invoice::STATUS_SENT, Invoice::STATUS_PARTIAL, Invoice::STATUS_PAID]);
$query = $this->addDateRange($query); $query = $this->addDateRange($query, 'invoices');
$query = $this->filterByClients($query); $query = $this->filterByClients($query);

View File

@ -174,7 +174,7 @@ class SubscriptionStatus extends AbstractService
*/ */
private function checkRefundable(): self private function checkRefundable(): self
{ {
if(!$this->recurring_invoice->subscription->refund_period || $this->recurring_invoice->subscription->refund_period === 0) { if(!$this->recurring_invoice->subscription->refund_period || (int)$this->recurring_invoice->subscription->refund_period == 0) {
return $this->setRefundable(false); return $this->setRefundable(false);
} }

View File

@ -40,6 +40,11 @@ class UserTransformer extends EntityTransformer
public function transform(User $user) public function transform(User $user)
{ {
$ref = new \stdClass;
$ref->free = 0;
$ref->pro = 0;
$ref->enterprise = 0;
return [ return [
'id' => $this->encodePrimaryKey($user->id), 'id' => $this->encodePrimaryKey($user->id),
'first_name' => $user->first_name ?: '', 'first_name' => $user->first_name ?: '',
@ -66,7 +71,7 @@ class UserTransformer extends EntityTransformer
'language_id' => (string) $user->language_id ?: '', 'language_id' => (string) $user->language_id ?: '',
'user_logged_in_notification' => (bool) $user->user_logged_in_notification, 'user_logged_in_notification' => (bool) $user->user_logged_in_notification,
'referral_code' => (string) $user->referral_code, 'referral_code' => (string) $user->referral_code,
'referral_meta' => $user->referral_meta ? (object)$user->referral_meta : new \stdClass, 'referral_meta' => $user->referral_meta ? (object)$user->referral_meta : $ref,
]; ];
} }

View File

@ -78,7 +78,7 @@ trait MakesDates
*/ */
public function formatDatetime($date, string $format): string public function formatDatetime($date, string $format): string
{ {
return Carbon::createFromTimestamp($date)->format($format.' g:i a'); return Carbon::createFromTimestamp((int)$date)->format($format.' g:i a');
} }
/** /**
@ -89,7 +89,7 @@ trait MakesDates
*/ */
public function formatDateTimestamp($timestamp, string $format): string public function formatDateTimestamp($timestamp, string $format): string
{ {
return Carbon::createFromTimestamp($timestamp)->format($format); return Carbon::createFromTimestamp((int)$timestamp)->format($format);
} }
private function convertToDateObject($date) private function convertToDateObject($date)

View File

@ -32,13 +32,13 @@ trait MakesReminders
switch ($schedule_reminder) { switch ($schedule_reminder) {
case 'after_invoice_date': case 'after_invoice_date':
return Carbon::parse($this->date)->addDays($num_days_reminder)->startOfDay()->addSeconds($offset)->isSameDay(Carbon::now()); return Carbon::parse($this->date)->addDays((int)$num_days_reminder)->startOfDay()->addSeconds($offset)->isSameDay(Carbon::now());
case 'before_due_date': case 'before_due_date':
$partial_or_due_date = ($this->partial > 0 && isset($this->partial_due_date)) ? $this->partial_due_date : $this->due_date; $partial_or_due_date = ($this->partial > 0 && isset($this->partial_due_date)) ? $this->partial_due_date : $this->due_date;
return Carbon::parse($partial_or_due_date)->subDays($num_days_reminder)->startOfDay()->addSeconds($offset)->isSameDay(Carbon::now()); return Carbon::parse($partial_or_due_date)->subDays((int)$num_days_reminder)->startOfDay()->addSeconds($offset)->isSameDay(Carbon::now());
case 'after_due_date': case 'after_due_date':
$partial_or_due_date = ($this->partial > 0 && isset($this->partial_due_date)) ? $this->partial_due_date : $this->due_date; $partial_or_due_date = ($this->partial > 0 && isset($this->partial_due_date)) ? $this->partial_due_date : $this->due_date;
return Carbon::parse($partial_or_due_date)->addDays($num_days_reminder)->startOfDay()->addSeconds($offset)->isSameDay(Carbon::now()); return Carbon::parse($partial_or_due_date)->addDays((int)$num_days_reminder)->startOfDay()->addSeconds($offset)->isSameDay(Carbon::now());
default: default:
return null; return null;
} }
@ -82,6 +82,9 @@ trait MakesReminders
private function checkEndlessReminder($last_sent_date, $endless_reminder_frequency_id): bool private function checkEndlessReminder($last_sent_date, $endless_reminder_frequency_id): bool
{ {
if(!$last_sent_date)
return false;
if (Carbon::now()->startOfDay()->eq($this->addTimeInterval($last_sent_date, $endless_reminder_frequency_id))) { if (Carbon::now()->startOfDay()->eq($this->addTimeInterval($last_sent_date, $endless_reminder_frequency_id))) {
return true; return true;
} }

View File

@ -17,8 +17,8 @@ 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', 'invoicing.co'), 'app_domain' => env('APP_DOMAIN', 'invoicing.co'),
'app_version' => env('APP_VERSION', '5.9.9'), 'app_version' => env('APP_VERSION', '5.10.2'),
'app_tag' => env('APP_TAG', '5.9.9'), 'app_tag' => env('APP_TAG', '5.10.2'),
'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

@ -0,0 +1,28 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('payment_hashes', function (Blueprint $table) {
$table->unsignedInteger('fee_invoice_id')->nullable()->index()->change();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
//
}
};

View File

@ -1,4 +1,3 @@
/*!999999\- enable the sandbox mode */
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */; /*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
@ -2431,7 +2430,6 @@ CREATE TABLE `webhooks` (
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
/*!999999\- enable the sandbox mode */
INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (1,'2014_10_12_100000_create_password_resets_table',1); INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (1,'2014_10_12_100000_create_password_resets_table',1);
INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (2,'2014_10_13_000000_create_users_table',1); INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (2,'2014_10_13_000000_create_users_table',1);
INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (3,'2019_11_10_115926_create_failed_jobs_table',1); INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (3,'2019_11_10_115926_create_failed_jobs_table',1);

View File

@ -30,4 +30,5 @@ parameters:
- '#Socialite#' - '#Socialite#'
- '#Access to protected property#' - '#Access to protected property#'
- '#Call to undefined method .*#' - '#Call to undefined method .*#'
- '#Argument of an invalid type stdClass supplied for foreach, only iterables are supported.#' - '#Argument of an invalid type stdClass supplied for foreach, only iterables are supported.#'
- '#Comparison operation ">=" between int<1, max> and 1 is always true#'

View File

@ -18,7 +18,7 @@ const RESOURCES = {"icons/Icon-512.png": "0f9aff01367f0a0c69773d25ca16ef35",
"canvaskit/skwasm.wasm": "e42815763c5d05bba43f9d0337fa7d84", "canvaskit/skwasm.wasm": "e42815763c5d05bba43f9d0337fa7d84",
"version.json": "1592dbbd49cf08963e29ab3a85640d96", "version.json": "1592dbbd49cf08963e29ab3a85640d96",
"favicon.png": "dca91c54388f52eded692718d5a98b8b", "favicon.png": "dca91c54388f52eded692718d5a98b8b",
"main.dart.js": "2eda432fffde6d4286d209de85530d53", "main.dart.js": "0512d8a34cb5c2d5d565a27c3666d9f9",
"assets/NOTICES": "412b336cf9e33e70058d612857effae1", "assets/NOTICES": "412b336cf9e33e70058d612857effae1",
"assets/AssetManifest.bin": "bf3be26e7055ad9a32f66b3a56138224", "assets/AssetManifest.bin": "bf3be26e7055ad9a32f66b3a56138224",
"assets/assets/images/logo_light.png": "e5f46d5a78e226e7a9553d4ca6f69219", "assets/assets/images/logo_light.png": "e5f46d5a78e226e7a9553d4ca6f69219",
@ -307,7 +307,7 @@ const RESOURCES = {"icons/Icon-512.png": "0f9aff01367f0a0c69773d25ca16ef35",
"assets/FontManifest.json": "087fb858dc3cbfbf6baf6a30004922f1", "assets/FontManifest.json": "087fb858dc3cbfbf6baf6a30004922f1",
"assets/fonts/MaterialIcons-Regular.otf": "a57618538ab8b4c4081d4491870ac333", "assets/fonts/MaterialIcons-Regular.otf": "a57618538ab8b4c4081d4491870ac333",
"assets/AssetManifest.json": "759f9ef9973f7e26c2a51450b55bb9fa", "assets/AssetManifest.json": "759f9ef9973f7e26c2a51450b55bb9fa",
"/": "1a380e64c7ec583dff72ce2ed9172654", "/": "a53ace1edfc2ce12fc50cbbade610be3",
"favicon.ico": "51636d3a390451561744c42188ccd628", "favicon.ico": "51636d3a390451561744c42188ccd628",
"manifest.json": "ef43d90e57aa7682d7e2cfba2f484a40"}; "manifest.json": "ef43d90e57aa7682d7e2cfba2f484a40"};
// The application shell files that are downloaded before a service worker can // The application shell files that are downloaded before a service worker can

2076
public/main.dart.js vendored

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

2820
public/main.foss.dart.js vendored

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -553567,7 +553567,7 @@
_this.super$__AccountManagementState_State_SingleTickerProviderStateMixin$dispose(); _this.super$__AccountManagementState_State_SingleTickerProviderStateMixin$dispose();
}, },
build$1(context) { build$1(context) {
var viewModel, state, company, t2, user, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15, _this = this, _null = null, _s6_ = ":count", var viewModel, state, company, t2, user, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15, t16, _this = this, _null = null, _s6_ = ":count",
_s11_ = "count_hours", _s11_ = "count_hours",
_s10_ = "count_days", _s10_ = "count_days",
_s16_ = "referral_program", _s16_ = "referral_program",
@ -553708,27 +553708,32 @@
t2 = J.$index$asx(t2, "require_password_with_social_login"); t2 = J.$index$asx(t2, "require_password_with_social_login");
t2.toString; t2.toString;
t2 = A._setArrayType([A.FormCard$(_null, A._setArrayType([t8, t4, A.BoolDropdownButton$(_null, _null, _null, _null, t2, _null, new A._AccountManagementState_build_closure2(viewModel, company), company.oauthPasswordRequired)], t14), _null, _null, false, _null, true, _null, _null)], t14); t2 = A._setArrayType([A.FormCard$(_null, A._setArrayType([t8, t4, A.BoolDropdownButton$(_null, _null, _null, _null, t2, _null, new A._AccountManagementState_build_closure2(viewModel, company), company.oauthPasswordRequired)], t14), _null, _null, false, _null, true, _null, _null)], t14);
t4 = t5.$index(0, t6); t4 = A._setArrayType([], t14);
t4.toString; t3 = A.StoreProvider_of(context, type$.AppState).__Store__state_A;
t4 = J.$index$asx(t4, _s12_); t3 === $ && A.throwUnnamedLateFieldNI();
if (t4 == null) { if (t3.get$isHosted()) {
t3 = t5.$index(0, _s2_); t3 = t5.$index(0, t6);
t3.toString; t3.toString;
t3 = J.$index$asx(t3, _s12_); t3 = J.$index$asx(t3, _s12_);
t3.toString; if (t3 == null) {
} else t3 = t5.$index(0, _s2_);
t3 = t4; t3.toString;
t3 = A.Text$(t3, _null, _null, _null, _null, _null, _null, _null, _null, _null); t3 = J.$index$asx(t3, _s12_);
t3 = A._setArrayType([A.ListTile$(false, _null, _null, _null, true, _null, _null, false, _null, _null, _null, _null, new A._AccountManagementState_build_closure3(user, t1), false, _null, _null, _null, A.Text$("https://app.invoicing.co/#/register?rc=" + user.referralCode, _null, 1, B.TextOverflow_2, _null, _null, _null, _null, _null, _null), _null, t3, A.Icon$(B.IconData_57744_MaterialIcons_null_false, _null, _null, _null), _null), new A.SizedBox(_null, 16, _null, _null)], t14); t3.toString;
for (t4 = user.referralMeta, t5 = t4.get$keys(0), t8 = t5._map, t5 = A.LinkedHashMapKeyIterator$(t8, t8._modifications, t5.$ti._precomputed1), t4 = t4._map$_map; t5.moveNext$0();) { }
t8 = t5.__js_helper$_current; t3 = A.Text$(t3, _null, _null, _null, _null, _null, _null, _null, _null, _null);
t3.push(new A.Padding(B.EdgeInsets_40_10_40_10, A.Row$(A._setArrayType([new A.Spacer(_null), new A.SizedBox(120, _null, new A.Text(t1.lookup$1(t8), _null, A.Theme_of(context).textTheme.headlineSmall, _null, _null, _null, _null, _null, _null, _null, _null), _null), new A.Text(A.S(t4.$index(0, t8)), _null, A.Theme_of(context).textTheme.headlineSmall, _null, _null, _null, _null, _null, _null, _null, _null), new A.Spacer(_null)], t14), B.CrossAxisAlignment_2, B.MainAxisAlignment_0, B.MainAxisSize_1, _null), _null)); t3 = A._setArrayType([A.ListTile$(false, _null, _null, _null, true, _null, _null, false, _null, _null, _null, _null, new A._AccountManagementState_build_closure3(user, t1), false, _null, _null, _null, A.Text$("https://app.invoicing.co/#/register?rc=" + user.referralCode, _null, 1, B.TextOverflow_2, _null, _null, _null, _null, _null, _null), _null, t3, A.Icon$(B.IconData_57744_MaterialIcons_null_false, _null, _null, _null), _null), new A.SizedBox(_null, 16, _null, _null)], t14);
for (t5 = user.referralMeta, t8 = t5.get$keys(0), t16 = t8._map, t8 = A.LinkedHashMapKeyIterator$(t16, t16._modifications, t8.$ti._precomputed1), t5 = t5._map$_map; t8.moveNext$0();) {
t16 = t8.__js_helper$_current;
t3.push(new A.Padding(B.EdgeInsets_40_10_40_10, A.Row$(A._setArrayType([new A.Spacer(_null), new A.SizedBox(180, _null, new A.Text(t1.lookup$1(t16), _null, A.Theme_of(context).textTheme.headlineSmall, _null, _null, _null, _null, _null, _null, _null, _null), _null), new A.Text(A.S(t5.$index(0, t16)), _null, A.Theme_of(context).textTheme.headlineSmall, _null, _null, _null, _null, _null, _null, _null, _null), new A.Spacer(_null)], t14), B.CrossAxisAlignment_2, B.MainAxisAlignment_0, B.MainAxisSize_1, _null), _null));
}
t3.push(new A.SizedBox(_null, 10, _null, _null));
B.JSArray_methods.addAll$1(t4, t3);
} }
t3.push(new A.SizedBox(_null, 10, _null, _null));
t1 = $.$get$LocalizationsProvider__localizedValues().$index(0, t6); t1 = $.$get$LocalizationsProvider__localizedValues().$index(0, t6);
t1.toString; t1.toString;
t3.push(new A.AppButton(_null, _null, J.$index$asx(t1, "learn_more").toUpperCase(), new A._AccountManagementState_build_closure4(), _null, _null)); t4.push(new A.AppButton(_null, _null, J.$index$asx(t1, "learn_more").toUpperCase(), new A._AccountManagementState_build_closure4(), _null, _null));
return A.EditScaffold$(_null, t13, new A.AppTabForm(t11, t12, A._setArrayType([new A._AccountOverview(viewModel, _null), new A.ScrollableListView(t9, _null, _null, true, false, _null), new A.ScrollableListView(t15, _null, _null, true, false, _null), new A.ScrollableListView(t2, _null, _null, _null, false, _null), new A.ScrollableListView(A._setArrayType([A.FormCard$(_null, t3, _null, B.CrossAxisAlignment_3, false, _null, true, _null, _null)], t14), _null, _null, _null, false, _null)], t14), t10, _null, _null), _null, _null, _null, false, _null, _null, viewModel.onSavePressed, _null, t7); return A.EditScaffold$(_null, t13, new A.AppTabForm(t11, t12, A._setArrayType([new A._AccountOverview(viewModel, _null), new A.ScrollableListView(t9, _null, _null, true, false, _null), new A.ScrollableListView(t15, _null, _null, true, false, _null), new A.ScrollableListView(t2, _null, _null, _null, false, _null), new A.ScrollableListView(A._setArrayType([A.FormCard$(_null, t4, _null, B.CrossAxisAlignment_3, false, _null, true, _null, _null)], t14), _null, _null, _null, false, _null)], t14), t10, _null, _null), _null, _null, _null, false, _null, _null, viewModel.onSavePressed, _null, t7);
} }
}; };
A._AccountManagementState_didChangeDependencies_closure.prototype = { A._AccountManagementState_didChangeDependencies_closure.prototype = {

View File

@ -0,0 +1,218 @@
<?php
/**
* Invoice Ninja (https://invoiceninja.com).
*
* @link https://github.com/invoiceninja/invoiceninja source repository
*
* @copyright Copyright (c) 2021. Invoice Ninja LLC (https://invoiceninja.com)
*
* @license https://www.elastic.co/licensing/elastic-license
*/
namespace Tests\Feature;
use Tests\TestCase;
use App\Models\User;
use App\Utils\Ninja;
use App\Models\Client;
use App\Models\Account;
use App\Models\Company;
use App\Models\Quote;
use Tests\MockAccountData;
use App\Models\CompanyToken;
use App\Models\ClientContact;
use App\Jobs\Util\ReminderJob;
use Illuminate\Support\Carbon;
use App\Utils\Traits\MakesHash;
use App\DataMapper\CompanySettings;
use App\Factory\CompanyUserFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Routing\Middleware\ThrottleRequests;
use Illuminate\Foundation\Testing\DatabaseTransactions;
/**
* @test
* @covers App\Jobs\Util\QuoteReminderJob
*/
class QuoteReminderTest extends TestCase
{
use MakesHash;
use DatabaseTransactions;
use MockAccountData;
public $faker;
protected function setUp() :void
{
parent::setUp();
$this->withoutMiddleware(
ThrottleRequests::class
);
$this->faker = \Faker\Factory::create();
Model::reguard();
$this->makeTestData();
$this->withoutExceptionHandling();
}
public $company;
public $user;
public $payload;
public $account;
public $client;
public $token;
public $cu;
public $invoice;
private function buildData($settings = null)
{
$this->account = Account::factory()->create([
'hosted_client_count' => 1000,
'hosted_company_count' => 1000,
]);
$this->account->num_users = 3;
$this->account->save();
$this->user = User::factory()->create([
'account_id' => $this->account->id,
'confirmation_code' => 'xyz123',
'email' => $this->faker->unique()->safeEmail(),
]);
if(!$settings) {
$settings = CompanySettings::defaults();
$settings->client_online_payment_notification = false;
$settings->client_manual_payment_notification = false;
}
$this->company = Company::factory()->create([
'account_id' => $this->account->id,
'settings' => $settings,
]);
$this->company->settings = $settings;
$this->company->save();
$this->cu = CompanyUserFactory::create($this->user->id, $this->company->id, $this->account->id);
$this->cu->is_owner = true;
$this->cu->is_admin = true;
$this->cu->is_locked = false;
$this->cu->save();
$this->token = \Illuminate\Support\Str::random(64);
$company_token = new CompanyToken;
$company_token->user_id = $this->user->id;
$company_token->company_id = $this->company->id;
$company_token->account_id = $this->account->id;
$company_token->name = 'test token';
$company_token->token = $this->token;
$company_token->is_system = true;
$company_token->save();
$this->client = Client::factory()->create([
'user_id' => $this->user->id,
'company_id' => $this->company->id,
'is_deleted' => 0,
'name' => 'bob',
'address1' => '1234',
'balance' => 100,
'paid_to_date' => 50,
]);
ClientContact::factory()->create([
'user_id' => $this->user->id,
'client_id' => $this->client->id,
'company_id' => $this->company->id,
'is_primary' => 1,
'first_name' => 'john',
'last_name' => 'doe',
'email' => 'john@doe.com',
'send_email' => true,
]);
$this->quote = Quote::factory()->create([
'user_id' => $this->user->id,
'company_id' => $this->company->id,
'client_id' => $this->client->id,
'date' => now()->addSeconds($this->client->timezone_offset())->format('Y-m-d'),
'next_send_date' => null,
'due_date' => Carbon::now()->addSeconds($this->client->timezone_offset())->addDays(5)->format('Y-m-d'),
'last_sent_date' => now()->addSeconds($this->client->timezone_offset()),
'reminder_last_sent' => null,
'status_id' => 2,
'amount' => 10,
'balance' => 10,
]);
}
public function testNullReminder()
{
$settings = $this->company->settings;
$settings->enable_quote_reminder1 = false;
$settings->quote_schedule_reminder1 = '';
$settings->quote_num_days_reminder1 = 1;
$this->buildData(($settings));
$this->quote->date = now()->subMonths(2)->format('Y-m-d');
$this->quote->due_date = now()->subMonth()->format('Y-m-d');
$this->quote->last_sent_date = now();
$this->quote->next_send_date = null;
$this->quote->service()->setReminder($settings)->save();
$this->quote = $this->quote->fresh();
$this->assertNull($this->quote->next_send_date);
}
public function testBeforeValidReminder()
{
$settings = $this->company->settings;
$settings->enable_quote_reminder1 = true;
$settings->quote_schedule_reminder1 = 'before_valid_until_date';
$settings->quote_num_days_reminder1 = 1;
$this->buildData(($settings));
$this->quote->date = now()->addMonth()->format('Y-m-d');
$this->quote->partial_due_date = null;
$this->quote->due_date = now()->addMonths(2)->format('Y-m-d');
$this->quote->last_sent_date = null;
$this->quote->next_send_date = null;
$this->quote->save();
$this->assertTrue($this->quote->canRemind());
$this->quote->service()->setReminder($settings)->save();
$this->quote = $this->quote->fresh();
$this->assertNotNull($this->quote->next_send_date);
nlog($this->quote->next_send_date);
$this->assertEquals(now()->addMonths(2)->subDay()->format('Y-m-d'), \Carbon\Carbon::parse($this->quote->next_send_date)->addSeconds($this->quote->client->timezone_offset())->format('Y-m-d'));
}
}