1
0
mirror of https://github.com/invoiceninja/invoiceninja.git synced 2024-11-14 23:22:52 +01:00
invoiceninja/app/Services/Invoice/HandleRestore.php

94 lines
2.5 KiB
PHP
Raw Normal View History

<?php
/**
* Invoice Ninja (https://invoiceninja.com).
*
* @link https://github.com/invoiceninja/invoiceninja source repository
*
2022-04-27 05:20:41 +02:00
* @copyright Copyright (c) 2022. Invoice Ninja LLC (https://invoiceninja.com)
*
2021-06-16 08:58:16 +02:00
* @license https://www.elastic.co/licensing/elastic-license
*/
namespace App\Services\Invoice;
use App\Models\Invoice;
use App\Services\AbstractService;
2021-05-20 23:58:46 +02:00
use App\Utils\Ninja;
use App\Utils\Traits\GeneratesCounter;
class HandleRestore extends AbstractService
{
2021-05-20 23:58:46 +02:00
use GeneratesCounter;
private $invoice;
private $payment_total = 0;
public function __construct(Invoice $invoice)
{
$this->invoice = $invoice;
}
public function run()
{
2022-03-15 10:20:05 +01:00
$this->invoice->restore();
if (!$this->invoice->is_deleted) {
return $this->invoice;
}
//determine whether we need to un-delete payments OR just modify the payment amount /applied balances.
foreach ($this->invoice->payments as $payment) {
2020-12-04 23:08:10 +01:00
//restore the payment record
2022-03-15 10:20:05 +01:00
$this->invoice->restore();
}
//adjust ledger balance
2021-01-21 05:05:05 +01:00
$this->invoice->ledger()->updateInvoiceBalance($this->invoice->balance, "Restored invoice {$this->invoice->number}")->save();
$this->invoice->client->service()->updateBalance($this->invoice->balance)->save();
$this->windBackInvoiceNumber();
2022-03-15 10:20:05 +01:00
$this->invoice->is_deleted = false;
$this->invoice->save();
return $this->invoice;
}
private function windBackInvoiceNumber()
{
$findme = '_' . ctrans('texts.deleted');
$pos = strpos($this->invoice->number, $findme);
$new_invoice_number = substr($this->invoice->number, 0, $pos);
2020-12-21 11:46:46 +01:00
if (strlen($new_invoice_number) == 0) {
2020-12-17 21:11:31 +01:00
$new_invoice_number = null;
2020-12-21 11:46:46 +01:00
}
2020-12-17 21:11:31 +01:00
try {
2021-05-20 23:58:46 +02:00
$exists = Invoice::where(['company_id' => $this->invoice->company_id, 'number' => $new_invoice_number])->exists();
if($exists)
$this->invoice->number = $this->getNextInvoiceNumber($this->invoice->client, $this->invoice, $this->invoice->recurring_id);
else
$this->invoice->number = $new_invoice_number;
2021-05-20 23:58:46 +02:00
2021-10-14 08:54:38 +02:00
$this->invoice->saveQuietly();
} catch (\Exception $e) {
2021-05-20 23:58:46 +02:00
nlog("I could not wind back the invoice number");
if(Ninja::isHosted()){
\Sentry\captureMessage("I could not wind back the invoice number");
app('sentry')->captureException($e);
}
}
}
}