From f72e7374e83c5c7d1e36353a75832cafa0054384 Mon Sep 17 00:00:00 2001 From: Grzegorz Date: Mon, 30 Nov 2026 08:23:59 +0100 Subject: [PATCH] feat(invoices): delete unused proformas --- .../Controllers/Admin/InvoiceController.php | 120 +++++++++- lang/de/admin.php | 8 + lang/en/admin.php | 8 + lang/pl/admin.php | 8 + lang/tr/admin.php | 8 + lang/zh/admin.php | 8 + resources/views/admin/invoices/show.blade.php | 17 ++ routes/admin.php | 1 + tests/Feature/ProformaDeletionTest.php | 205 ++++++++++++++++++ 9 files changed, 378 insertions(+), 5 deletions(-) create mode 100644 tests/Feature/ProformaDeletionTest.php diff --git a/app/Http/Controllers/Admin/InvoiceController.php b/app/Http/Controllers/Admin/InvoiceController.php index 03c104990..160de66e1 100644 --- a/app/Http/Controllers/Admin/InvoiceController.php +++ b/app/Http/Controllers/Admin/InvoiceController.php @@ -8,15 +8,20 @@ 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; @@ -24,6 +29,9 @@ 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; @@ -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')); } /** @@ -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); @@ -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); } @@ -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} + */ + 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. */ diff --git a/lang/de/admin.php b/lang/de/admin.php index f6456afc4..f1fc9cc87 100644 --- a/lang/de/admin.php +++ b/lang/de/admin.php @@ -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', diff --git a/lang/en/admin.php b/lang/en/admin.php index 524b9c619..b7a0fb284 100644 --- a/lang/en/admin.php +++ b/lang/en/admin.php @@ -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', diff --git a/lang/pl/admin.php b/lang/pl/admin.php index d72f74da1..d4ce88704 100644 --- a/lang/pl/admin.php +++ b/lang/pl/admin.php @@ -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', diff --git a/lang/tr/admin.php b/lang/tr/admin.php index cc35dd3dc..63348947b 100644 --- a/lang/tr/admin.php +++ b/lang/tr/admin.php @@ -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', diff --git a/lang/zh/admin.php b/lang/zh/admin.php index 10de824aa..e9dcb687d 100644 --- a/lang/zh/admin.php +++ b/lang/zh/admin.php @@ -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' => '催缴', diff --git a/resources/views/admin/invoices/show.blade.php b/resources/views/admin/invoices/show.blade.php index 797837d96..7df1cfb77 100644 --- a/resources/views/admin/invoices/show.blade.php +++ b/resources/views/admin/invoices/show.blade.php @@ -18,6 +18,23 @@ @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 +
+ @csrf + @method('DELETE') + +
+ @endif
@csrf diff --git a/routes/admin.php b/routes/admin.php index 7cc44a894..b88b01efc 100644 --- a/routes/admin.php +++ b/routes/admin.php @@ -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'); diff --git a/tests/Feature/ProformaDeletionTest.php b/tests/Feature/ProformaDeletionTest.php new file mode 100644 index 000000000..d3c3b0acc --- /dev/null +++ b/tests/Feature/ProformaDeletionTest.php @@ -0,0 +1,205 @@ +create([ + 'role_id' => AdminRole::factory()->fullAdmin()->create()->id, + ]); +} + +function proformaDeleteInvoice(array $overrides = []): Invoice +{ + $client = Client::factory()->create(); + + return Invoice::factory()->create(array_merge([ + 'client_id' => $client->id, + 'type' => 'proforma', + 'status' => 'unpaid', + 'invoice_num' => 'PRO-DEL-1', + 'total' => 10, + ], $overrides)); +} + +it('deletes a clean proforma and its items', function () { + $invoice = proformaDeleteInvoice(); + $item = InvoiceItem::factory()->create([ + 'invoice_id' => $invoice->id, + 'client_id' => $invoice->client_id, + ]); + + $this->actingAs(proformaDeleteAdmin(), 'admin') + ->delete(route('admin.invoices.destroy', $invoice)) + ->assertRedirect(route('admin.invoices.index')) + ->assertSessionHas('success'); + + expect(Invoice::find($invoice->id))->toBeNull() + ->and(InvoiceItem::find($item->id))->toBeNull(); +}); + +it('detaches linked orders and says which ones need a new invoice', function () { + $invoice = proformaDeleteInvoice(); + $order = Order::factory()->pending()->create([ + 'client_id' => $invoice->client_id, + 'invoice_id' => $invoice->id, + 'order_num' => 'ORD-DEL-1', + ]); + + $response = $this->actingAs(proformaDeleteAdmin(), 'admin') + ->delete(route('admin.invoices.destroy', $invoice)); + + $response->assertRedirect(route('admin.invoices.index'))->assertSessionHas('success'); + + expect($order->fresh()->invoice_id)->toBeNull() + ->and($order->fresh()->status)->toBe('pending') + ->and(session('success'))->toContain('ORD-DEL-1') + ->and(session('success'))->toContain('new invoice') + ->and(Invoice::find($invoice->id))->toBeNull() + ->and(ActivityLog::where('client_id', $invoice->client_id)->where('description', 'like', '%ORD-DEL-1%')->exists())->toBeTrue(); +}); + +it('refuses to delete a VAT invoice', function () { + $invoice = proformaDeleteInvoice(['type' => 'vat']); + + $this->actingAs(proformaDeleteAdmin(), 'admin') + ->from(route('admin.invoices.show', $invoice)) + ->delete(route('admin.invoices.destroy', $invoice)) + ->assertRedirect(route('admin.invoices.show', $invoice)) + ->assertSessionHas('error'); + + expect(Invoice::find($invoice->id))->not->toBeNull(); +}); + +it('refuses to delete a paid proforma', function () { + $invoice = proformaDeleteInvoice(['status' => 'paid']); + $admin = proformaDeleteAdmin(); + + $this->actingAs($admin, 'admin') + ->get(route('admin.invoices.show', $invoice)) + ->assertOk() + ->assertSee('disabled title="'.e(__('admin.invoices.delete_proforma_blocked')).'"', false); + + $this->actingAs($admin, 'admin') + ->from(route('admin.invoices.show', $invoice)) + ->delete(route('admin.invoices.destroy', $invoice)) + ->assertSessionHas('error'); + + expect(Invoice::find($invoice->id))->not->toBeNull(); +}); + +it('refuses to delete a proforma that has a payment', function () { + $invoice = proformaDeleteInvoice(); + Transaction::factory()->create([ + 'client_id' => $invoice->client_id, + 'invoice_id' => $invoice->id, + ]); + + $this->actingAs(proformaDeleteAdmin(), 'admin') + ->from(route('admin.invoices.show', $invoice)) + ->delete(route('admin.invoices.destroy', $invoice)) + ->assertSessionHas('error'); + + expect(Invoice::find($invoice->id))->not->toBeNull(); +}); + +it('refuses to delete a proforma replaced by a VAT invoice', function () { + $invoice = proformaDeleteInvoice(); + Invoice::factory()->create([ + 'client_id' => $invoice->client_id, + 'type' => 'vat', + 'status' => 'paid', + 'source_invoice_id' => $invoice->id, + ]); + + $this->actingAs(proformaDeleteAdmin(), 'admin') + ->from(route('admin.invoices.show', $invoice)) + ->delete(route('admin.invoices.destroy', $invoice)) + ->assertSessionHas('error'); + + expect(Invoice::find($invoice->id))->not->toBeNull(); +}); + +it('refuses to delete a proforma with a payment notification', function () { + $invoice = proformaDeleteInvoice(); + PaymentNotification::create([ + 'invoice_id' => $invoice->id, + 'client_id' => $invoice->client_id, + 'sender_name' => 'Customer', + 'amount' => 10, + 'transfer_date' => now()->toDateString(), + 'status' => 'pending', + ]); + + $this->actingAs(proformaDeleteAdmin(), 'admin') + ->from(route('admin.invoices.show', $invoice)) + ->delete(route('admin.invoices.destroy', $invoice)) + ->assertSessionHas('error'); + + expect(Invoice::find($invoice->id))->not->toBeNull(); +}); + +it('refuses to delete a proforma carrying a billable item', function () { + $invoice = proformaDeleteInvoice(); + BillableItem::create([ + 'client_id' => $invoice->client_id, + 'description' => 'Manual charge', + 'amount' => 10, + 'invoice_id' => $invoice->id, + ]); + + $this->actingAs(proformaDeleteAdmin(), 'admin') + ->from(route('admin.invoices.show', $invoice)) + ->delete(route('admin.invoices.destroy', $invoice)) + ->assertSessionHas('error'); + + expect(Invoice::find($invoice->id))->not->toBeNull(); +}); + +it('shows delete only for a deletable proforma and warns about detached orders', function () { + $invoice = proformaDeleteInvoice(); + $order = Order::factory()->pending()->create([ + 'client_id' => $invoice->client_id, + 'invoice_id' => $invoice->id, + 'order_num' => 'ORD-DEL-2', + ]); + + $this->actingAs(proformaDeleteAdmin(), 'admin') + ->get(route('admin.invoices.show', $invoice)) + ->assertOk() + ->assertSee(route('admin.invoices.destroy', $invoice), false) + ->assertSee('ORD-DEL-2', false) + ->assertSee(e(__('admin.invoices.delete_proforma')), false); + + $vat = proformaDeleteInvoice(['type' => 'vat']); + + $this->actingAs(proformaDeleteAdmin(), 'admin') + ->get(route('admin.invoices.show', $vat)) + ->assertOk() + ->assertDontSee('action="'.route('admin.invoices.destroy', $vat).'"', false); +}); + +it('protects proforma deletion with the manage_invoices permission', function () { + $invoice = proformaDeleteInvoice(); + $admin = Admin::factory()->create([ + 'role_id' => AdminRole::factory()->create([ + 'name' => 'Invoice viewer '.uniqid(), + 'permissions' => ['list_invoices', 'view_invoices'], + ])->id, + ]); + + $this->actingAs($admin, 'admin') + ->delete(route('admin.invoices.destroy', $invoice)) + ->assertForbidden(); + + expect(Invoice::find($invoice->id))->not->toBeNull(); +});