1
0
mirror of https://github.com/invoiceninja/invoiceninja.git synced 2024-11-10 21:22:58 +01:00

Merge pull request #4738 from turbo124/v5-develop

Fixes for ledger
This commit is contained in:
David Bomba 2021-01-21 15:51:41 +11:00 committed by GitHub
commit ce0ebaa63a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
31 changed files with 81 additions and 63 deletions

View File

@ -298,7 +298,7 @@ class CheckData extends Command
$invoice_balance = $client->invoices->where('is_deleted', false)->where('status_id', '>', 1)->sum('balance');
$credit_balance = $client->credits->where('is_deleted', false)->sum('balance');
$invoice_balance -= $credit_balance;
// $invoice_balance -= $credit_balance;//doesn't make sense to remove the credit amount
$ledger = CompanyLedger::where('client_id', $client->id)->orderBy('id', 'DESC')->first();
@ -388,9 +388,9 @@ class CheckData extends Command
foreach (Client::cursor()->where('is_deleted', 0) as $client) {
//$invoice_balance = $client->invoices->where('is_deleted', false)->where('status_id', '>', 1)->sum('balance');
$invoice_balance = Invoice::where('client_id', $client->id)->where('is_deleted', false)->where('status_id', '>', 1)->withTrashed()->sum('balance');
$client_balance = Credit::where('client_id', $client->id)->where('is_deleted', false)->withTrashed()->sum('balance');
$credit_balance = Credit::where('client_id', $client->id)->where('is_deleted', false)->withTrashed()->sum('balance');
$invoice_balance -= $client_balance;
// $invoice_balance -= $credit_balance;
$ledger = CompanyLedger::where('client_id', $client->id)->orderBy('id', 'DESC')->first();

View File

@ -331,7 +331,7 @@ class CreateTestData extends Command
$this->info('Creating '.$this->count.' clients');
for ($x = 0; $x < $this->count * 500; $x++) {
for ($x = 0; $x < $this->count * 200; $x++) {
$z = $x + 1;
$this->info('Creating client # '.$z);

View File

@ -687,8 +687,8 @@ class InvoiceController extends BaseController
break;
case 'delete':
//need to make sure the invoice is cancelled first!!
//$invoice->service()->handleCancellation()->save();
//$invoice->service()->handleCancellation()s->save();
nlog("inside delete");
$this->invoice_repo->delete($invoice);
if (! $bulk) {

View File

@ -53,21 +53,40 @@ class ValidInvoicesRules implements Rule
//todo optimize this into a single query
foreach ($this->input['invoices'] as $invoice) {
$unique_array[] = $invoice['invoice_id'];
$inv = Invoice::whereId($invoice['invoice_id'])->first();
if (! $inv) {
$this->error_msg = 'Invoice not found ';
return false;
}
if ($inv->client_id != $this->input['client_id']) {
$this->error_msg = 'Selected invoices are not from a single client';
return false;
}
if($inv->status_id == Invoice::STATUS_DRAFT && $invoice['amount'] <= $inv->amount){
//catch here nothing to do - we need this to prevent the last elseif triggering
}
else if($inv->status_id == Invoice::STATUS_DRAFT && $invoice['amount'] > $inv->amount){
$this->error_msg = 'Amount cannot be greater than invoice balance';
return false;
}
else if($invoice['amount'] > $inv->balance) {
$this->error_msg = 'Amount cannot be greater than invoice balance';
return false;
}
}
if (! (array_unique($unique_array) == $unique_array)) {

View File

@ -96,7 +96,7 @@ class ZipInvoices extends BaseMailerJob implements ShouldQueue
Mail::to($this->email)
->send(new DownloadInvoices(Storage::disk(config('filesystems.default'))->url($path.$file_name), $this->company));
} catch (\Exception $e) {
$this->failed($e);
// //$this->failed($e);
}
UnlinkFile::dispatch(config('filesystems.default'), $path.$file_name)->delay(now()->addHours(1));

View File

@ -96,7 +96,7 @@ class EntityFailedSendMailer extends BaseMailerJob implements ShouldQueue
->send(new EntityNotificationMailer($mail_obj));
} catch (\Exception $e) {
nlog("failing in EntityFailedSendMailer");
$this->failed($e);
//$this->failed($e);
$this->logMailError($e->getMessage(), $this->entity->client);
}
}

View File

@ -83,7 +83,7 @@ class EntityPaidMailer extends BaseMailerJob implements ShouldQueue
Mail::to($this->user->email)
->send(new EntityNotificationMailer($mail_obj));
} catch (\Exception $e) {
$this->failed($e);
// //$this->failed($e);
$this->logMailError($e->getMessage(), $this->payment->client);
}
}

View File

@ -90,7 +90,7 @@ class EntitySentMailer extends BaseMailerJob implements ShouldQueue
Mail::to($this->user->email)
->send(new EntityNotificationMailer($mail_obj));
} catch (\Exception $e) {
$this->failed($e);
// //$this->failed($e);
$this->logMailError($e->getMessage(), $this->entity->client);
}
}

View File

@ -88,7 +88,7 @@ class EntityViewedMailer extends BaseMailerJob implements ShouldQueue
Mail::to($this->user->email)
->send(new EntityNotificationMailer($mail_obj));
} catch (\Exception $e) {
$this->failed($e);
//$this->failed($e);
$this->logMailError($e->getMessage(), $this->entity->client);
}
}

View File

@ -73,7 +73,7 @@ class MailRouter extends BaseMailerJob implements ShouldQueue
Mail::to($this->to_user->email)
->send($this->mailable);
} catch (\Exception $e) {
$this->failed($e);
//$this->failed($e);
if ($this->to_user instanceof ClientContact) {
$this->logMailError($e->getMessage(), $this->to_user->client);

View File

@ -98,7 +98,7 @@ class PaymentFailureMailer extends BaseMailerJob implements ShouldQueue
Mail::to($company_user->user->email)
->send(new EntityNotificationMailer($mail_obj));
} catch (\Exception $e) {
$this->failed($e);
//$this->failed($e);
$this->logMailError($e->getMessage(), $this->client);
}
}

View File

@ -308,7 +308,7 @@ class SendReminders implements ShouldQueue
$invoice = $invoice->calc()->getInvoice();
$this->invoice->client->service()->updateBalance($this->invoice->balance - $temp_invoice_balance)->save();
$this->invoice->ledger()->updateInvoiceBalance($this->invoice->balance - $temp_invoice_balance);
$this->invoice->ledger()->updateInvoiceBalance($this->invoice->balance - $temp_invoice_balance, "Late Fee Adjustment for invoice {$this->invoice->number}");
return $invoice;
}

View File

@ -84,7 +84,7 @@ class EmailPayment extends BaseMailerJob implements ShouldQueue
} catch (\Exception $e) {
nlog("mailing failed with message " . $e->getMessage());
event(new PaymentWasEmailedAndFailed($this->payment, $this->company, Mail::failures(), Ninja::eventVars()));
$this->failed($e);
//$this->failed($e);
return $this->logMailError($e->getMessage(), $this->payment->client);
}

View File

@ -79,7 +79,7 @@ class UserEmailChanged extends BaseMailerJob implements ShouldQueue
Mail::to($this->new_email)
->send(new UserNotificationMailer($mail_obj));
} catch (\Exception $e) {
$this->failed($e);
//$this->failed($e);
$this->logMailError($e->getMessage(), $this->company->owner());
}
}

View File

@ -49,10 +49,7 @@ class ClientContact extends Authenticatable implements HasLocalePreference
'hashed_id',
];
protected $with = [
// 'client',
// 'company'
];
protected $with = [];
protected $casts = [
'updated_at' => 'timestamp',
@ -87,12 +84,6 @@ class ClientContact extends Authenticatable implements HasLocalePreference
'client_id',
];
/* Changing the username to id allows us to login() a contact that doesn't have an email address set*/
public function username()
{
return 'id';
}
public function getEntityType()
{
return self::class;

View File

@ -264,7 +264,7 @@ class BaseDriver extends AbstractPaymentDriver
if (collect($invoice->line_items)->contains('type_id', '3')) {
$invoice->service()->toggleFeesPaid()->save();
$invoice->client->service()->updateBalance($fee_total)->save();
$invoice->ledger()->updateInvoiceBalance($fee_total, $notes = 'Gateway fee adjustment');
$invoice->ledger()->updateInvoiceBalance($fee_total, "Gateway fee adjustment for invoice {$invoice->number}");
}
});
}

View File

@ -306,7 +306,7 @@ class BasePaymentDriver
if (collect($invoice->line_items)->contains('type_id', '3')) {
$invoice->service()->toggleFeesPaid()->save();
$invoice->client->service()->updateBalance($fee_total)->save();
$invoice->ledger()->updateInvoiceBalance($fee_total, $notes = 'Gateway fee adjustment');
$invoice->ledger()->updateInvoiceBalance($fee_total, "Gateway fee adjustment for Invoice {$invoice->number}");
}
});
}

View File

@ -293,7 +293,7 @@ class BaseRepository
if (($state['finished_amount'] != $state['starting_amount']) && ($model->status_id != Invoice::STATUS_DRAFT)) {
$model->ledger()->updateInvoiceBalance(($state['finished_amount'] - $state['starting_amount']));
$model->ledger()->updateInvoiceBalance(($state['finished_amount'] - $state['starting_amount']), "Update adjustment for invoice {$model->number}");
$model->client->service()->updateBalance(($state['finished_amount'] - $state['starting_amount']))->save();
}

View File

@ -58,6 +58,10 @@ class ClientContactRepository extends BaseRepository
$update_contact->client_id = $client->id;
}
/* We need to set NULL email addresses to blank strings to pass authentication*/
if(array_key_exists('email', $contact) && is_null($contact['email']))
$contact['email'] = '';
$update_contact->fill($contact);
if (array_key_exists('password', $contact) && strlen($contact['password']) > 1) {
@ -77,6 +81,7 @@ class ClientContactRepository extends BaseRepository
$new_contact->contact_key = Str::random(40);
$new_contact->is_primary = true;
$new_contact->confirmed = true;
$new_contact->email = ' ';
$new_contact->save();
}
}

View File

@ -64,7 +64,6 @@ class PaymentRepository extends BaseRepository
*/
private function applyPayment(array $data, Payment $payment): ?Payment
{
nlog($data);
$is_existing_payment = true;

View File

@ -136,11 +136,13 @@ class PaymentMethod
foreach ($this->gateways as $gateway) {
foreach ($gateway->driver($this->client)->gatewayTypes() as $type) {
if (isset($gateway->fees_and_limits) && property_exists($gateway->fees_and_limits, $type)) {
if ($this->validGatewayForAmount($gateway->fees_and_limits->{$type}, $this->amount)) {
if ($this->validGatewayForAmount($gateway->fees_and_limits->{$type}, $this->amount) && $gateway->fees_and_limits->{$type}->is_enabled) {
$this->payment_methods[] = [$gateway->id => $type];
}
} else {
$this->payment_methods[] = [$gateway->id => $type];
//$this->payment_methods[] = [$gateway->id => $type];
}
}
}

View File

@ -93,10 +93,6 @@ class AddGatewayFee extends AbstractService
/**Refresh Invoice values*/
$this->invoice = $this->invoice->calc()->getInvoice();
/*Update client balance*/ // don't increment until we have process the payment!
//$this->invoice->client->service()->updateBalance($gateway_fee)->save();
//$this->invoice->ledger()->updateInvoiceBalance($gateway_fee, $notes = 'Gateway fee adjustment');
return $this->invoice;
}
@ -122,10 +118,6 @@ class AddGatewayFee extends AbstractService
$this->invoice = $this->invoice->calc()->getInvoice();
// $this->invoice->client->service()->updateBalance($gateway_fee)->save();
// $this->invoice->ledger()->updateInvoiceBalance($gateway_fee, $notes = 'Discount fee adjustment');
return $this->invoice;
}
}

View File

@ -100,11 +100,6 @@ class ApplyPayment extends AbstractService
}
}
// $this->payment
// ->ledger()
// ->updatePaymentBalance($this->payment_amount * -1);
$this->payment
->ledger()
->updatePaymentBalance($amount_paid);

View File

@ -147,8 +147,8 @@ class AutoBillInvoice extends AbstractService
->save();
$this->invoice->ledger()
->updateInvoiceBalance($amount * -1, 'Invoice payment using Credit')
->updateCreditBalance($amount * -1, 'Credits used to pay down Invoice ' . $this->invoice->number)
->updateInvoiceBalance($amount * -1, "Invoice {$this->invoice->number} payment using Credit {$current_credit->number}")
->updateCreditBalance($amount * -1, "Credit {$current_credit->number} used to pay down Invoice {$this->invoice->number}")
->save();
event(new PaymentWasCreated($payment, $payment->company, Ninja::eventVars()));
@ -325,7 +325,7 @@ class AutoBillInvoice extends AbstractService
if ($starting_amount != $this->invoice->amount && $this->invoice->status_id != Invoice::STATUS_DRAFT) {
$this->invoice->client->service()->updateBalance($this->invoice->amount - $starting_amount)->save();
$this->invoice->ledger()->updateInvoiceBalance($this->invoice->amount - $starting_amount, 'Invoice balance updated after stale gateway fee removed')->save();
$this->invoice->ledger()->updateInvoiceBalance($this->invoice->amount - $starting_amount, "Invoice {$this->invoice->number} balance updated after stale gateway fee removed")->save();
}
return $this;

View File

@ -42,7 +42,7 @@ class HandleCancellation extends AbstractService
$this->backupCancellation($adjustment);
//set invoice balance to 0
$this->invoice->ledger()->updateInvoiceBalance($adjustment, 'Invoice cancellation');
$this->invoice->ledger()->updateInvoiceBalance($adjustment, "Invoice {$this->invoice->number} cancellation");
$this->invoice->balance = 0;
$this->invoice = $this->invoice->service()->setStatus(Invoice::STATUS_CANCELLED)->save();
@ -57,11 +57,13 @@ class HandleCancellation extends AbstractService
public function reverse()
{
/* The stored cancelled object - contains the adjustment and status*/
$cancellation = $this->invoice->backup->cancellation;
/* Will turn the negative cancellation amount to a positive adjustment*/
$adjustment = $cancellation->adjustment * -1;
$this->invoice->ledger()->updateInvoiceBalance($adjustment, 'Invoice cancellation REVERSAL');
$this->invoice->ledger()->updateInvoiceBalance($adjustment, "Invoice {$this->invoice->number} reversal");
/* Reverse the invoice status and balance */
$this->invoice->balance += $adjustment;

View File

@ -71,14 +71,15 @@ class HandleRestore extends AbstractService
}
//adjust ledger balance
$this->invoice->ledger()->updateInvoiceBalance($this->invoice->balance, 'Restored invoice {$this->invoice->number}')->save();
$this->invoice->ledger()->updateInvoiceBalance($this->invoice->balance, "Restored invoice {$this->invoice->number}")->save();
//adjust paid to dates
$this->invoice->client->service()->updatePaidToDate($this->payment_total)->save();
$this->invoice->client->service()->updateBalance($this->invoice->balance)->save();
$this->invoice->ledger()->updatePaymentBalance($this->payment_total, 'Restored payment for invoice {$this->invoice->number}')->save();
// you only need to touch the ledger ONCE per transaction.
// $this->invoice->ledger()->updatePaymentBalance($this->payment_total*-1, "Restored payment for invoice {$this->invoice->number}")->save();
$this->windBackInvoiceNumber();

View File

@ -36,9 +36,6 @@ class MarkInvoiceDeleted extends AbstractService
if ($this->invoice->is_deleted) {
return $this->invoice;
}
// if(in_array($this->invoice->status_id, ['currencies', 'industries', 'languages', 'countries', 'banks']))
// return $this->
$this->cleanup()
->setAdjustmentAmount()
@ -53,25 +50,26 @@ class MarkInvoiceDeleted extends AbstractService
private function adjustLedger()
{
$this->invoice->ledger()->updatePaymentBalance($this->adjustment_amount * -1);
$this->invoice->ledger()->updatePaymentBalance($this->adjustment_amount * -1, 'Invoice Deleted - reducing ledger balance'); //reduces the payment balance by payment totals
return $this;
}
private function adjustPaidToDate()
{
$this->invoice->client->service()->updatePaidToDate($this->adjustment_amount * -1)->save();
$this->invoice->client->service()->updatePaidToDate($this->adjustment_amount * -1)->save(); //reduces the paid to date by the payment totals
return $this;
}
private function adjustBalance()
{
$this->invoice->client->service()->updateBalance($this->invoice->balance * -1)->save();
$this->invoice->client->service()->updateBalance($this->invoice->balance * -1)->save(); //reduces the client balance by the invoice amount.
return $this;
}
/* Adjust the payment amounts */
private function adjustPayments()
{
//if total payments = adjustment amount - that means we need to delete the payments as well.
@ -79,6 +77,7 @@ class MarkInvoiceDeleted extends AbstractService
if ($this->adjustment_amount == $this->total_payments) {
$this->invoice->payments()->update(['payments.deleted_at' => now(), 'payments.is_deleted' => true]);
} else {
//adjust payments down by the amount applied to the invoice payment.
$this->invoice->payments->each(function ($payment) {
@ -96,6 +95,12 @@ class MarkInvoiceDeleted extends AbstractService
return $this;
}
/**
* Set the values of two variables
*
* $this->adjustment_amount - sum of the invoice paymentables
* $this->total_payments - sum of the invoice payments
*/
private function setAdjustmentAmount()
{
foreach ($this->invoice->payments as $payment) {
@ -111,6 +116,12 @@ class MarkInvoiceDeleted extends AbstractService
return $this;
}
/*
*
* This sets the invoice number to _deleted
* and also removes the links to existing entities
*
*/
private function cleanup()
{
$check = false;
@ -143,7 +154,7 @@ class MarkInvoiceDeleted extends AbstractService
return $number;
}
/* Touches all paymentables as deleted */
private function deletePaymentables()
{
$this->invoice->payments->each(function ($payment) {

View File

@ -51,7 +51,7 @@ class MarkSent extends AbstractService
$this->client->service()->updateBalance($this->invoice->balance)->save();
$this->invoice->ledger()->updateInvoiceBalance($this->invoice->balance);
$this->invoice->ledger()->updateInvoiceBalance($this->invoice->balance, "Invoice {$this->invoice->number} marked as sent.");
event(new InvoiceWasUpdated($this->invoice, $this->invoice->company, Ninja::eventVars()));

View File

@ -47,7 +47,7 @@ class LedgerService
return $this;
}
public function updatePaymentBalance($adjustment)
public function updatePaymentBalance($adjustment, $notes = '')
{
$balance = 0;
@ -63,6 +63,7 @@ class LedgerService
$company_ledger->adjustment = $adjustment;
$company_ledger->balance = $balance + $adjustment;
$company_ledger->activity_id = Activity::UPDATE_PAYMENT;
$company_ledger->notes = $notes;
$company_ledger->save();
$this->entity->company_ledger()->save($company_ledger);

View File

@ -80,7 +80,7 @@ class DeletePayment
if ($this->payment->invoices()->exists()) {
$this->payment->invoices()->each(function ($paymentable_invoice) {
$paymentable_invoice->service()->updateBalance($paymentable_invoice->pivot->amount)->save();
$paymentable_invoice->ledger()->updateInvoiceBalance($paymentable_invoice->pivot->amount)->save();
$paymentable_invoice->ledger()->updateInvoiceBalance($paymentable_invoice->pivot->amount, "Adjusting invoice {$paymentable_invoice->number} due to deletion of Payment {$this->payment->number}")->save();
$paymentable_invoice->client->service()->updateBalance($paymentable_invoice->pivot->amount)->save();
if ($paymentable_invoice->balance == $paymentable_invoice->amount) {

View File

@ -5,7 +5,7 @@
@include('email.components.header', ['logo' => $logo])
@endslot
<h1>{{ $title }}</h1>
<p>{{ $title }}</p>
@slot('greeting')
@lang($message)