Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
120 changes: 115 additions & 5 deletions app/Http/Controllers/Admin/InvoiceController.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,22 +8,30 @@
use App\Mail\InvoiceCreatedMail;
use App\Mail\PaymentReminderMail;
use App\Models\ActivityLog;
use App\Models\BillableItem;
use App\Models\Client;
use App\Models\Currency;
use App\Models\Invoice;
use App\Models\InvoiceChargeAttempt;
use App\Models\InvoiceItem;
use App\Models\InvoiceProduct;
use App\Models\Order;
use App\Models\PaymentMethod;
use App\Models\PaymentNotification;
use App\Models\Product;
use App\Models\Setting;
use App\Models\TaxRule;
use App\Services\AutoChargeService;
use App\Services\InvoicePdfService;
use App\Services\InvoiceService;
use App\Services\Module\ModuleRegistry;
use App\Services\PaymentService;
use App\Support\AutoCharge;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Lang;
use Illuminate\Support\Facades\Mail;
use Illuminate\View\View;
use Symfony\Component\HttpFoundation\StreamedResponse;
Expand Down Expand Up @@ -119,13 +127,15 @@ public function show(Invoice $invoice): View
// gateway can charge. chargeNow() asks the rest again, under its claim.
$canChargeNow = AutoCharge::enabled()
&& in_array(strtolower((string) $invoice->status), [InvoiceStatus::Unpaid->value, InvoiceStatus::Overdue->value, InvoiceStatus::PartiallyPaid->value], true)
&& \App\Models\PaymentMethod::query()
&& PaymentMethod::query()
->where('client_id', $invoice->client_id)
->where('status', \App\Models\PaymentMethod::STATUS_ACTIVE)
->where('status', PaymentMethod::STATUS_ACTIVE)
->whereIn('gateway_name', array_keys(app(ModuleRegistry::class)->tokenisedGateways()))
->exists();

return view('admin.invoices.show', compact('invoice', 'taxRules', 'activityLog', 'chargeReview', 'canChargeNow'));
$proformaDeletion = $this->proformaDeletionState($invoice);

return view('admin.invoices.show', compact('invoice', 'taxRules', 'activityLog', 'chargeReview', 'canChargeNow', 'proformaDeletion'));
}

/**
Expand Down Expand Up @@ -157,7 +167,7 @@ public function show(Invoice $invoice): View
* scheduled run: pressing the button twice, or while the 06:45 run has the
* invoice, charges once.
*/
public function chargeNow(Invoice $invoice, \App\Services\AutoChargeService $charger): RedirectResponse
public function chargeNow(Invoice $invoice, AutoChargeService $charger): RedirectResponse
{
$outcome = $charger->chargeNow($invoice);

Expand All @@ -169,7 +179,7 @@ public function chargeNow(Invoice $invoice, \App\Services\AutoChargeService $cha
);

$key = 'admin.invoices.charge_now_'.$outcome;
$message = \Illuminate\Support\Facades\Lang::has($key) ? __($key) : __('admin.invoices.charge_now_refused', ['reason' => $outcome]);
$message = Lang::has($key) ? __($key) : __('admin.invoices.charge_now_refused', ['reason' => $outcome]);

return back()->with($outcome === 'charged' ? 'success' : 'error', $message);
}
Expand Down Expand Up @@ -622,6 +632,106 @@ public function cancel(Invoice $invoice): RedirectResponse
return back()->with('success', __('admin.messages.invoice_cancelled', ['num' => $invoice->invoice_num]));
}

/**
* Delete an unused proforma. Unlike cancellation this removes the document
* itself, so it is limited to a proforma that has no money or legal trail.
* Orders pointing at it are detached rather than left with a dead invoice.
*/
public function destroy(Invoice $invoice): RedirectResponse
{
$admin = $this->adminName();

$result = DB::transaction(function () use ($invoice, $admin): array {
$locked = Invoice::whereKey($invoice->id)->lockForUpdate()->first();

if (! $locked) {
return ['deleted' => false, 'orders' => ''];
}

$state = $this->proformaDeletionState($locked);
if (! $state['can_delete']) {
return ['deleted' => false, 'orders' => ''];
}

$orders = $state['orders']
->map(fn (Order $order) => $order->order_num ?: '#'.$order->id)
->implode(', ');

foreach ($state['orders'] as $order) {
$order->update(['invoice_id' => null]);

ActivityLog::log(
__('admin.invoices.proforma_order_detached_log', [
'order' => $order->order_num ?: '#'.$order->id,
'num' => $locked->invoice_num ?: '#'.$locked->id,
]),
$admin,
$order->client_id
);
}

ActivityLog::log(
__('admin.invoices.proforma_deleted_log', ['num' => $locked->invoice_num ?: '#'.$locked->id]),
$admin,
$locked->client_id,
$locked->id
);

$locked->delete();

return ['deleted' => true, 'orders' => $orders];
});

if (! $result['deleted']) {
return back()->with('error', __('admin.invoices.delete_proforma_blocked'));
}

$num = $invoice->invoice_num ?: '#'.$invoice->id;

return redirect()->route('admin.invoices.index')->with('success', $result['orders'] !== ''
? __('admin.invoices.proforma_deleted_orders', ['num' => $num, 'orders' => $result['orders']])
: __('admin.invoices.proforma_deleted', ['num' => $num]));
}

/**
* Whether a proforma can be hard-deleted, and which orders point at it.
*
* Cancellation keeps the document and returns money. Deletion removes the
* row, so it must never be used on something that has become evidence of a
* payment or a legal document.
*
* @return array{can_delete: bool, orders: Collection<int, Order>}
*/
private function proformaDeletionState(Invoice $invoice): array
{
$orders = Order::where('invoice_id', $invoice->id)->orderBy('id')->get();

if (! $invoice->isProforma()) {
return ['can_delete' => false, 'orders' => $orders];
}

if (! in_array(strtolower((string) $invoice->status), [
InvoiceStatus::Draft->value,
InvoiceStatus::Unpaid->value,
InvoiceStatus::Overdue->value,
InvoiceStatus::Cancelled->value,
], true)) {
return ['can_delete' => false, 'orders' => $orders];
}

if (round((float) $invoice->credit, 2) > 0
|| $invoice->replacementInvoice()->exists()
|| $invoice->transactions()->exists()
|| $invoice->chargeAttempt()->exists()
|| $invoice->ksefInvoice()->exists()
|| PaymentNotification::where('invoice_id', $invoice->id)->exists()
|| BillableItem::where('invoice_id', $invoice->id)->exists()) {
return ['can_delete' => false, 'orders' => $orders];
}

return ['can_delete' => true, 'orders' => $orders];
}

/**
* Export invoices as CSV.
*/
Expand Down
8 changes: 8 additions & 0 deletions lang/de/admin.php
Original file line number Diff line number Diff line change
Expand Up @@ -1678,6 +1678,14 @@
'invoices.item_removed' => 'Werbebuchung entfernt.',
'invoices.items_locked' => 'Positionen einer bezahlten, stornierten oder erstatteten Rechnung können nicht geändert werden.',
'invoices.delete_item' => 'Artikel löschen',
'invoices.delete_proforma' => 'Proforma löschen',
'invoices.confirm_delete_proforma' => 'Proforma #:num löschen? Dies kann nicht rückgängig gemacht werden.',
'invoices.confirm_delete_proforma_orders' => 'Proforma #:num löschen? Bestellungen :orders werden getrennt und benötigen eine neue Rechnung. Dies kann nicht rückgängig gemacht werden.',
'invoices.delete_proforma_blocked' => 'Diese Proforma kann nicht gelöscht werden, weil sie bezahlt, ersetzt oder mit Zahlungen oder anderen Dokumenten verknüpft ist.',
'invoices.proforma_deleted' => 'Proforma #:num gelöscht.',
'invoices.proforma_deleted_orders' => 'Proforma #:num gelöscht. Getrennte Bestellungen: :orders. Sie benötigen eine neue Rechnung.',
'invoices.proforma_deleted_log' => 'Proforma #:num gelöscht',
'invoices.proforma_order_detached_log' => 'Bestellung #:order von gelöschter Proforma #:num getrennt',
'invoices.confirm_delete_item' => 'Diese Werbebuchung löschen?',
'invoices.send' => 'Senden',
'invoices.remind' => 'Erinnern',
Expand Down
8 changes: 8 additions & 0 deletions lang/en/admin.php
Original file line number Diff line number Diff line change
Expand Up @@ -1678,6 +1678,14 @@
'invoices.item_removed' => 'Line item removed.',
'invoices.items_locked' => 'Line items cannot be changed on a paid, cancelled or refunded invoice.',
'invoices.delete_item' => 'Delete item',
'invoices.delete_proforma' => 'Delete proforma',
'invoices.confirm_delete_proforma' => 'Delete proforma #:num? This cannot be undone.',
'invoices.confirm_delete_proforma_orders' => 'Delete proforma #:num? Orders :orders will be detached and will need a new invoice. This cannot be undone.',
'invoices.delete_proforma_blocked' => 'This proforma cannot be deleted because it is paid, replaced, or has payments or other linked documents.',
'invoices.proforma_deleted' => 'Proforma #:num deleted.',
'invoices.proforma_deleted_orders' => 'Proforma #:num deleted. Detached orders: :orders. They will need a new invoice.',
'invoices.proforma_deleted_log' => 'Proforma #:num deleted',
'invoices.proforma_order_detached_log' => 'Order #:order detached from deleted proforma #:num',
'invoices.confirm_delete_item' => 'Delete this line item?',
'invoices.send' => 'Send',
'invoices.remind' => 'Remind',
Expand Down
8 changes: 8 additions & 0 deletions lang/pl/admin.php
Original file line number Diff line number Diff line change
Expand Up @@ -1678,6 +1678,14 @@
'invoices.item_removed' => 'Usunięto pozycję.',
'invoices.items_locked' => 'Nie można zmieniać pozycji opłaconej, anulowanej lub zwróconej faktury.',
'invoices.delete_item' => 'Usuń pozycję',
'invoices.delete_proforma' => 'Usuń proformę',
'invoices.confirm_delete_proforma' => 'Usunąć proformę #:num? Tej operacji nie można cofnąć.',
'invoices.confirm_delete_proforma_orders' => 'Usunąć proformę #:num? Zamówienia :orders zostaną odłączone i będą wymagały nowej faktury. Tej operacji nie można cofnąć.',
'invoices.delete_proforma_blocked' => 'Nie można usunąć tej proformy, ponieważ jest opłacona, zastąpiona fakturą lub ma płatności albo inne powiązane dokumenty.',
'invoices.proforma_deleted' => 'Proforma #:num została usunięta.',
'invoices.proforma_deleted_orders' => 'Proforma #:num została usunięta. Odłączone zamówienia: :orders. Będą wymagały nowej faktury.',
'invoices.proforma_deleted_log' => 'Proforma #:num usunięta',
'invoices.proforma_order_detached_log' => 'Zamówienie #:order odłączone od usuniętej proformy #:num',
'invoices.confirm_delete_item' => 'Usunąć tę pozycję?',
'invoices.send' => 'Wyślij',
'invoices.remind' => 'Przypomnij',
Expand Down
8 changes: 8 additions & 0 deletions lang/tr/admin.php
Original file line number Diff line number Diff line change
Expand Up @@ -1660,6 +1660,14 @@
'invoices.item_removed' => 'Kalem kaldırıldı.',
'invoices.items_locked' => 'Ödenmiş, iptal edilmiş ya da iade edilmiş faturanın kalemleri değiştirilemez.',
'invoices.delete_item' => 'Kalemi sil',
'invoices.delete_proforma' => 'Proformayı sil',
'invoices.confirm_delete_proforma' => 'Proforma #:num silinsin mi? Bu işlem geri alınamaz.',
'invoices.confirm_delete_proforma_orders' => 'Proforma #:num silinsin mi? :orders siparişleri ayrılacak ve yeni bir faturaya ihtiyaç duyacak. Bu işlem geri alınamaz.',
'invoices.delete_proforma_blocked' => 'Bu proforma ödendiği, değiştirildiği veya ödemeler ya da başka belgelerle bağlantılı olduğu için silinemez.',
'invoices.proforma_deleted' => 'Proforma #:num silindi.',
'invoices.proforma_deleted_orders' => 'Proforma #:num silindi. Ayrılan siparişler: :orders. Yeni bir faturaya ihtiyaç duyacaklar.',
'invoices.proforma_deleted_log' => 'Proforma #:num silindi',
'invoices.proforma_order_detached_log' => 'Sipariş #:order, silinen proforma #:num\'dan ayrıldı',
'invoices.confirm_delete_item' => 'Bu kalemi silmek istiyor musunuz?',
'invoices.send' => 'Gönder',
'invoices.remind' => 'Hatırlat',
Expand Down
8 changes: 8 additions & 0 deletions lang/zh/admin.php
Original file line number Diff line number Diff line change
Expand Up @@ -1678,6 +1678,14 @@
'invoices.item_removed' => '已删除明细。',
'invoices.items_locked' => '已支付、已取消或已退款的发票不能修改明细。',
'invoices.delete_item' => '删除明细',
'invoices.delete_proforma' => '删除形式发票',
'invoices.confirm_delete_proforma' => '删除形式发票 #:num?此操作无法撤销。',
'invoices.confirm_delete_proforma_orders' => '删除形式发票 #:num?订单 :orders 将被解除关联,并需要新的发票。此操作无法撤销。',
'invoices.delete_proforma_blocked' => '此形式发票无法删除,因为它已付款、已被替换,或存在付款或其他关联文件。',
'invoices.proforma_deleted' => '形式发票 #:num 已删除。',
'invoices.proforma_deleted_orders' => '形式发票 #:num 已删除。已解除关联的订单::orders。它们需要新的发票。',
'invoices.proforma_deleted_log' => '形式发票 #:num 已删除',
'invoices.proforma_order_detached_log' => '订单 #:order 已从删除的形式发票 #:num 解除关联',
'invoices.confirm_delete_item' => '确定删除此明细吗?',
'invoices.send' => '发送',
'invoices.remind' => '催缴',
Expand Down
17 changes: 17 additions & 0 deletions resources/views/admin/invoices/show.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,23 @@
<button type="submit" class="btn btn-danger btn-sm">{{ __('common.actions.cancel') }}</button>
</form>
@endif
@if($invoice->isProforma())
@php
$canDeleteProforma = $proformaDeletion['can_delete'] ?? false;
$detachedOrders = ($proformaDeletion['orders'] ?? collect())
->map(fn ($order) => $order->order_num ?: '#'.$order->id)
->implode(', ');
$deleteProformaNum = $invoice->invoice_num ?: '#'.$invoice->id;
$confirmDeleteProforma = $detachedOrders !== ''
? __('admin.invoices.confirm_delete_proforma_orders', ['num' => $deleteProformaNum, 'orders' => $detachedOrders])
: __('admin.invoices.confirm_delete_proforma', ['num' => $deleteProformaNum]);
@endphp
<form method="POST" action="{{ route('admin.invoices.destroy', $invoice) }}" style="display:inline;" @if($canDeleteProforma) onsubmit="return pnConfirm(event, @js($confirmDeleteProforma))" @endif>
@csrf
@method('DELETE')
<button type="submit" class="btn btn-danger btn-sm" @if(!$canDeleteProforma) disabled title="{{ __('admin.invoices.delete_proforma_blocked') }}" @endif>{{ __('admin.invoices.delete_proforma') }}</button>
</form>
@endif
<form method="POST" action="{{ route('admin.invoices.send', $invoice) }}" style="display:inline;">
@csrf
<button type="submit" class="btn btn-default btn-sm">{{ __('admin.invoices.send') }}</button>
Expand Down
1 change: 1 addition & 0 deletions routes/admin.php
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,7 @@
Route::post('invoices/{invoice}/charge-now', [InvoiceController::class, 'chargeNow'])->name('invoices.charge-now');
Route::post('invoices/{invoice}/charge-review/release', [InvoiceController::class, 'releaseChargeReview'])->name('invoices.charge-review.release');
Route::post('invoices/{invoice}/cancel', [InvoiceController::class, 'cancel'])->name('invoices.cancel');
Route::delete('invoices/{invoice}', [InvoiceController::class, 'destroy'])->name('invoices.destroy');
Route::post('invoices/{invoice}/refund', [InvoiceController::class, 'refund'])->name('invoices.refund');
Route::post('invoices/{invoice}/send', [InvoiceController::class, 'sendInvoice'])->name('invoices.send');
Route::post('invoices/{invoice}/remind', [InvoiceController::class, 'sendReminder'])->name('invoices.remind');
Expand Down
Loading
Loading