This commit is contained in:
baodev0
2026-09-23 15:17:18 +07:00
parent cd38c5d6d0
commit 82a71244ca
107 changed files with 3332 additions and 3306 deletions
@@ -18,6 +18,7 @@ use App\Repositories\InvoiceAttachment\InvoiceAttachmentRepositoryInterface;
use App\Repositories\InvoiceItem\InvoiceItemRepositoryInterface;
use App\Services\InvoicePaymentService;
use App\Services\InvoicePdfService;
use App\Services\InvoiceReminderService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
@@ -193,6 +194,7 @@ class InvoiceController extends Controller
if ($status === InvoiceStatus::PAID->value) {
$this->invoicePaymentService->markPaidByAdmin($invoice, auth()->id());
} else {
$this->assertCancellable($invoice);
$invoice->update([
'status' => $status,
'paid_at' => null,
@@ -205,6 +207,12 @@ class InvoiceController extends Controller
'error' => false,
'message' => 'Invoice updated successfully'
]);
} catch (\InvalidArgumentException $e) {
DB::rollBack();
return response()->json([
'error' => true,
'message' => $e->getMessage()
], 422);
} catch (\Exception $e) {
DB::rollBack();
return response()->json([
@@ -225,6 +233,15 @@ class InvoiceController extends Controller
], 404);
}
// Hoá đơn đã thu tiền là chứng từ gốc: xoá đi thì Transaction và số dư đã trừ vẫn còn,
// sổ sách lệch mà không còn dấu vết. Muốn đảo thì phải đi qua luồng hoàn tiền.
if (in_array((int) $invoice->status, [InvoiceStatus::PAID->value, InvoiceStatus::REFUNDED->value], true)) {
return response()->json([
'error' => true,
'message' => 'Không thể xoá hoá đơn đã thanh toán hoặc đã hoàn tiền. Hãy dùng chức năng hoàn tiền nếu cần đảo giao dịch.',
], 422);
}
try {
// Note: `orders` has no `invoice_id` column (the FK runs the other way —
// invoices.order_id -> orders.id), so there's nothing to clean up there. Any
@@ -244,7 +261,7 @@ class InvoiceController extends Controller
}
}
public function markAsPaid(int $id): JsonResponse
public function markAsPaid(Request $request, int $id): JsonResponse
{
$invoice = $this->invoiceRepository->find($id);
@@ -255,18 +272,42 @@ class InvoiceController extends Controller
], 404);
}
// Bỏ trống = thu đủ hoá đơn. Nhập số nhỏ hơn khi khách mới chuyển được một phần —
// hoá đơn ghi nhận trả một phần và chưa kích hoạt dịch vụ.
$validated = $request->validate([
'received_amount' => 'nullable|integer|min:1',
]);
try {
DB::beginTransaction();
$invoice->load(['order', 'customer']);
$this->invoicePaymentService->markPaidByAdmin($invoice, auth()->id());
$invoice = $this->invoicePaymentService->markPaidByAdmin(
$invoice,
auth()->id(),
receivedAmount: $validated['received_amount'] ?? null,
);
DB::commit();
$outstanding = InvoicePaymentService::outstanding($invoice);
return response()->json([
'error' => false,
'message' => 'Invoice marked as paid'
'message' => $outstanding > 0
? 'Đã ghi nhận thanh toán một phần. Còn thiếu ' . number_format($outstanding) . ' VNĐ.'
: 'Invoice marked as paid',
'data' => [
'amount_paid' => (int) $invoice->amount_paid,
'outstanding' => $outstanding,
],
]);
} catch (\InvalidArgumentException $e) {
DB::rollBack();
return response()->json([
'error' => true,
'message' => $e->getMessage()
], 422);
} catch (\Exception $e) {
DB::rollBack();
return response()->json([
@@ -288,6 +329,8 @@ class InvoiceController extends Controller
}
try {
$this->assertCancellable($invoice);
DB::beginTransaction();
$invoice->update([
'status' => InvoiceStatus::CANCELLED->value,
@@ -299,6 +342,12 @@ class InvoiceController extends Controller
'error' => false,
'message' => 'Invoice cancelled'
]);
} catch (\InvalidArgumentException $e) {
DB::rollBack();
return response()->json([
'error' => true,
'message' => $e->getMessage()
], 422);
} catch (\Exception $e) {
DB::rollBack();
return response()->json([
@@ -308,6 +357,98 @@ class InvoiceController extends Controller
}
}
/**
* Hoàn tiền hoá đơn đã thu — cộng lại số dư khách và ghi Transaction âm, thay cho việc
* huỷ hoá đơn đã thanh toán (nay đã bị chặn) hoặc xử lý tay ngoài hệ thống.
*/
public function refund(Request $request, int $id): JsonResponse
{
$invoice = $this->invoiceRepository->find($id);
if (!$invoice) {
return response()->json([
'error' => true,
'message' => "Can't find invoice by ID #" . $id
], 404);
}
$validated = $request->validate([
'amount' => 'nullable|integer|min:1',
'reason' => 'nullable|string|max:500',
]);
try {
$invoice = $this->invoicePaymentService->refund(
$invoice,
auth()->id(),
$validated['amount'] ?? null,
$validated['reason'] ?? '',
);
} catch (\InvalidArgumentException $e) {
return response()->json(['error' => true, 'message' => $e->getMessage()], 422);
} catch (\Throwable $e) {
Log::error('InvoiceController::refund error: ' . $e->getMessage(), ['invoice_id' => $id]);
return response()->json(['error' => true, 'message' => 'Không thể hoàn tiền, vui lòng thử lại.'], 500);
}
return response()->json([
'error' => false,
'message' => 'Đã hoàn tiền vào số dư khách hàng.',
'data' => ['invoice' => new InvoiceResource($invoice)],
]);
}
/**
* Nhắc thanh toán thủ công — dùng khi kế toán muốn thúc riêng một khách mà không chờ
* mốc tự động trong billing.reminder_offsets.
*/
public function remind(int $id, InvoiceReminderService $reminders): JsonResponse
{
$invoice = $this->invoiceRepository->find($id);
if (!$invoice) {
return response()->json([
'error' => true,
'message' => "Can't find invoice by ID #" . $id
], 404);
}
if (!$reminders->isRemindable($invoice)) {
return response()->json([
'error' => true,
'message' => 'Chỉ nhắc được hoá đơn chưa thanh toán hoặc quá hạn.',
], 422);
}
try {
$reminders->remind($invoice->load('customer'), force: true);
} catch (\Throwable $e) {
return response()->json([
'error' => true,
'message' => 'Không gửi được email nhắc: ' . $e->getMessage(),
], 500);
}
return response()->json([
'error' => false,
'message' => 'Đã gửi email nhắc thanh toán tới ' . $invoice->customer?->email,
]);
}
/**
* Huỷ hoá đơn đã thu tiền sẽ xoá paid_at nhưng không hoàn số dư, không revert order/service,
* trong khi Transaction vẫn còn — sổ sách lệch im lặng. Chặn ở đây, đảo giao dịch phải đi
* qua luồng hoàn tiền.
*/
private function assertCancellable(Invoice $invoice): void
{
if (in_array((int) $invoice->status, [InvoiceStatus::PAID->value, InvoiceStatus::REFUNDED->value], true)) {
throw new \InvalidArgumentException(
'Không thể huỷ hoá đơn đã thanh toán hoặc đã hoàn tiền. Hãy dùng chức năng hoàn tiền nếu cần đảo giao dịch.'
);
}
}
// ─── Attachments ────────────────────────────────────────────────────────────
public function listAttachments(int $id): JsonResponse