589 lines
21 KiB
PHP
589 lines
21 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers\Api\Admin\Invoice;
|
|
|
|
use App\Enums\Invoice\InvoiceStatus;
|
|
use App\Helpers\OrderHelper;
|
|
use App\Http\Controllers\Controller;
|
|
use App\Http\Requests\InvoiceRequest;
|
|
use App\Http\Resources\Api\Admin\InvoiceResource;
|
|
use App\Mail\InvoiceNotificationMail;
|
|
use App\Models\Customer;
|
|
use App\Models\Invoice;
|
|
use App\Models\InvoiceItem;
|
|
use App\Models\Order;
|
|
use App\Models\Payment;
|
|
use App\Repositories\Invoice\InvoiceRepositoryInterface;
|
|
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;
|
|
use Illuminate\Support\Facades\Log;
|
|
use Illuminate\Support\Facades\Mail;
|
|
use Illuminate\Support\Facades\Storage;
|
|
use Throwable;
|
|
use Yajra\DataTables\Facades\DataTables;
|
|
|
|
class InvoiceController extends Controller
|
|
{
|
|
public function __construct(
|
|
private readonly InvoiceRepositoryInterface $invoiceRepository,
|
|
private readonly InvoiceItemRepositoryInterface $invoiceItemRepository,
|
|
private readonly InvoiceAttachmentRepositoryInterface $attachmentRepository,
|
|
private readonly InvoicePdfService $invoicePdfService,
|
|
private readonly InvoicePaymentService $invoicePaymentService,
|
|
) {}
|
|
|
|
public function index(Request $request): JsonResponse
|
|
{
|
|
$query = $this->invoiceRepository->filter(
|
|
$request->all(),
|
|
['payment', 'customer', 'order'],
|
|
[],
|
|
['*'],
|
|
true
|
|
);
|
|
|
|
return response()->json([
|
|
'error' => false,
|
|
'data' => [
|
|
'items' => InvoiceResource::collection($query->get())->resolve(),
|
|
'total' => $query->count(),
|
|
],
|
|
]);
|
|
}
|
|
|
|
public function datatable(Request $request): JsonResponse
|
|
{
|
|
$query = $this->invoiceRepository->filter(
|
|
$request->all(),
|
|
['payment', 'customer', 'order'],
|
|
[],
|
|
['*'],
|
|
true
|
|
);
|
|
|
|
return DataTables::eloquent($query)
|
|
->addColumn('invoice_number', fn($d) => $d->invoice_number)
|
|
->addColumn('date', fn($d) => $d->date)
|
|
->addColumn('customer', fn($d) => $d->customer?->fullname)
|
|
->addColumn('payment', fn($d) => $d->payment?->name)
|
|
->addColumn('total', fn($d) => $d->total)
|
|
->addColumn('status', fn($d) => $d->status)
|
|
->addColumn('action', fn($d) => $d->id)
|
|
->rawColumns(['invoice_number', 'date', 'customer', 'payment', 'total', 'status', 'action'])
|
|
->make(true);
|
|
}
|
|
|
|
/**
|
|
* Admin tạo thêm 1 invoice thủ công cho 1 order đã tồn tại — chỉ dùng cho phụ
|
|
* phí/điều chỉnh thuộc CHÍNH dịch vụ trong order đó (vd. phạt trễ hạn, phí xử lý).
|
|
* Order cố định: không dùng endpoint này để bán thêm dịch vụ mới — dịch vụ mới phải
|
|
* là 1 Order riêng (qua OrderController::store). Đi qua cùng convention với renewal
|
|
* invoice ở nơi khác trong codebase: gắn order_id vào order gốc, tự sinh invoice_number.
|
|
*/
|
|
public function store(Request $request): JsonResponse
|
|
{
|
|
$validated = $request->validate([
|
|
'order_id' => 'required|integer|exists:orders,id',
|
|
'invoice_type' => 'nullable|integer|in:1,2,3',
|
|
'description' => 'nullable|string|max:500',
|
|
'due_date' => 'nullable|date',
|
|
'sub_total' => 'required|numeric|min:0',
|
|
'tax' => 'nullable|numeric|min:0',
|
|
]);
|
|
|
|
$order = Order::find($validated['order_id']);
|
|
$subTotal = (int) $validated['sub_total'];
|
|
$tax = (int) ($validated['tax'] ?? 0);
|
|
$total = $subTotal + $tax;
|
|
|
|
try {
|
|
$invoice = DB::transaction(function () use ($order, $validated, $subTotal, $tax, $total) {
|
|
$invoice = Invoice::create([
|
|
'invoice_number' => OrderHelper::generateOrderNumber('INV'),
|
|
'customer_id' => $order->customer_id,
|
|
'order_id' => $order->id,
|
|
'invoice_type' => $validated['invoice_type'] ?? 3,
|
|
'sub_total' => $subTotal,
|
|
'discount_amount' => 0,
|
|
'tax' => $tax,
|
|
'total' => $total,
|
|
'status' => InvoiceStatus::UNPAID->value,
|
|
'due_date' => $validated['due_date'] ?? now()->addDays(7)->toDateString(),
|
|
]);
|
|
|
|
InvoiceItem::create([
|
|
'invoice_id' => $invoice->id,
|
|
'type' => 'service',
|
|
'description' => $validated['description'] ?: 'Hóa đơn bổ sung',
|
|
'months' => 0,
|
|
'quantity' => 1,
|
|
'unit_price' => $subTotal,
|
|
'total_price' => $subTotal,
|
|
]);
|
|
|
|
return $invoice;
|
|
});
|
|
|
|
return response()->json([
|
|
'error' => false,
|
|
'message' => 'Đã tạo hóa đơn',
|
|
'data' => new InvoiceResource($invoice->load('invoiceItems')),
|
|
], 201);
|
|
} catch (\Exception $e) {
|
|
return response()->json([
|
|
'error' => true,
|
|
'message' => $e->getMessage()
|
|
], 500);
|
|
}
|
|
}
|
|
|
|
public function show(int $id): JsonResponse
|
|
{
|
|
$invoice = $this->invoiceRepository->findWithRelationships($id, ['payment', 'invoiceItem', 'customer']);
|
|
|
|
if (!$invoice) {
|
|
return response()->json([
|
|
'error' => true,
|
|
'message' => "Can't find invoice by ID #" . $id
|
|
], 404);
|
|
}
|
|
|
|
return response()->json([
|
|
'error' => false,
|
|
'data' => new InvoiceResource($invoice)
|
|
]);
|
|
}
|
|
|
|
public function update(InvoiceRequest $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);
|
|
}
|
|
|
|
$request->validated();
|
|
|
|
$action = strtolower((string) $request->get('action'));
|
|
$status = match ($action) {
|
|
'paid' => InvoiceStatus::PAID->value,
|
|
'cancel' => InvoiceStatus::CANCELLED->value,
|
|
default => null,
|
|
};
|
|
|
|
if ($status === null) {
|
|
return response()->json([
|
|
'error' => true,
|
|
'message' => 'Invalid invoice action.',
|
|
], 422);
|
|
}
|
|
|
|
try {
|
|
DB::beginTransaction();
|
|
$invoice->load(['order', 'customer']);
|
|
|
|
if ($status === InvoiceStatus::PAID->value) {
|
|
$this->invoicePaymentService->markPaidByAdmin($invoice, auth()->id());
|
|
} else {
|
|
$this->assertCancellable($invoice);
|
|
$invoice->update([
|
|
'status' => $status,
|
|
'paid_at' => null,
|
|
]);
|
|
}
|
|
|
|
DB::commit();
|
|
|
|
return response()->json([
|
|
'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([
|
|
'error' => true,
|
|
'message' => $e->getMessage()
|
|
], 500);
|
|
}
|
|
}
|
|
|
|
public function destroy(int $id): JsonResponse
|
|
{
|
|
$invoice = $this->invoiceRepository->find($id);
|
|
|
|
if (!$invoice) {
|
|
return response()->json([
|
|
'error' => true,
|
|
'message' => "Can't find invoice by ID #" . $id
|
|
], 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
|
|
// `services.invoice_id` pointing at this invoice is already handled by the
|
|
// FK's onDelete('set null').
|
|
$this->invoiceRepository->delete($id);
|
|
|
|
return response()->json([
|
|
'error' => false,
|
|
'message' => 'Invoice deleted successfully'
|
|
]);
|
|
} catch (\Exception $e) {
|
|
return response()->json([
|
|
'error' => true,
|
|
'message' => $e->getMessage()
|
|
], 500);
|
|
}
|
|
}
|
|
|
|
public function markAsPaid(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);
|
|
}
|
|
|
|
// 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']);
|
|
$invoice = $this->invoicePaymentService->markPaidByAdmin(
|
|
$invoice,
|
|
auth()->id(),
|
|
receivedAmount: $validated['received_amount'] ?? null,
|
|
);
|
|
|
|
DB::commit();
|
|
|
|
$outstanding = InvoicePaymentService::outstanding($invoice);
|
|
|
|
return response()->json([
|
|
'error' => false,
|
|
'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([
|
|
'error' => true,
|
|
'message' => $e->getMessage()
|
|
], 500);
|
|
}
|
|
}
|
|
|
|
public function cancel(int $id): JsonResponse
|
|
{
|
|
$invoice = $this->invoiceRepository->find($id);
|
|
|
|
if (!$invoice) {
|
|
return response()->json([
|
|
'error' => true,
|
|
'message' => "Can't find invoice by ID #" . $id
|
|
], 404);
|
|
}
|
|
|
|
try {
|
|
$this->assertCancellable($invoice);
|
|
|
|
DB::beginTransaction();
|
|
$invoice->update([
|
|
'status' => InvoiceStatus::CANCELLED->value,
|
|
'paid_at' => null
|
|
]);
|
|
DB::commit();
|
|
|
|
return response()->json([
|
|
'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([
|
|
'error' => true,
|
|
'message' => $e->getMessage()
|
|
], 500);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 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
|
|
{
|
|
$invoice = $this->invoiceRepository->find($id);
|
|
if (!$invoice) {
|
|
return response()->json(['error' => true, 'message' => "Can't find invoice #$id"], 404);
|
|
}
|
|
|
|
$attachments = $this->attachmentRepository->getByInvoice($id);
|
|
|
|
return response()->json([
|
|
'error' => false,
|
|
'data' => $attachments,
|
|
]);
|
|
}
|
|
|
|
public function uploadAttachment(Request $request, int $id): JsonResponse
|
|
{
|
|
$invoice = $this->invoiceRepository->find($id);
|
|
if (!$invoice) {
|
|
return response()->json(['error' => true, 'message' => "Can't find invoice #$id"], 404);
|
|
}
|
|
|
|
$request->validate([
|
|
'file' => 'required|file|mimes:jpg,jpeg,png,gif,pdf,doc,docx,xls,xlsx|max:10240',
|
|
]);
|
|
|
|
$file = $request->file('file');
|
|
$path = $file->store("invoice-attachments/{$id}", 'public');
|
|
$uploader = $request->user()?->username ?? $request->user()?->name ?? 'admin';
|
|
|
|
$attachment = $this->attachmentRepository->create([
|
|
'invoice_id' => $id,
|
|
'filename' => $file->getClientOriginalName(),
|
|
'path' => $path,
|
|
'disk' => 'public',
|
|
'mime_type' => $file->getMimeType(),
|
|
'size' => $file->getSize(),
|
|
'uploaded_by' => $uploader,
|
|
]);
|
|
|
|
return response()->json([
|
|
'error' => false,
|
|
'message' => 'File uploaded successfully',
|
|
'data' => $attachment,
|
|
], 201);
|
|
}
|
|
|
|
public function deleteAttachment(int $id, int $attachmentId): JsonResponse
|
|
{
|
|
$invoice = $this->invoiceRepository->find($id);
|
|
if (!$invoice) {
|
|
return response()->json(['error' => true, 'message' => "Can't find invoice #$id"], 404);
|
|
}
|
|
|
|
$attachment = $this->attachmentRepository->find($attachmentId);
|
|
if (!$attachment || $attachment->invoice_id !== $id) {
|
|
return response()->json(['error' => true, 'message' => 'Attachment not found'], 404);
|
|
}
|
|
|
|
$this->attachmentRepository->deleteWithFile($attachmentId);
|
|
|
|
return response()->json([
|
|
'error' => false,
|
|
'message' => 'Attachment deleted',
|
|
]);
|
|
}
|
|
|
|
// ─── Send Mail ───────────────────────────────────────────────────────────────
|
|
|
|
public function sendMail(Request $request, int $id): JsonResponse
|
|
{
|
|
$request->validate([
|
|
'message' => 'nullable|string|max:1000',
|
|
'type' => 'nullable|string|in:invoice,renewal',
|
|
]);
|
|
|
|
$invoice = $this->invoiceRepository->find($id);
|
|
if (!$invoice) {
|
|
return response()->json(['error' => true, 'message' => "Can't find invoice #$id"], 404);
|
|
}
|
|
|
|
$invoice->load('customer');
|
|
$customer = $invoice->customer;
|
|
if (!$customer || !$customer->email) {
|
|
return response()->json(['error' => true, 'message' => 'Customer email not found'], 422);
|
|
}
|
|
|
|
$attachments = $this->attachmentRepository->getByInvoice($id);
|
|
$companyName = setting('general.company_name') ?: config('app.name');
|
|
$type = $request->get('type', 'invoice');
|
|
$message = $request->get(
|
|
'message',
|
|
$type === 'renewal'
|
|
? "Dịch vụ của quý khách sắp đến hạn gia hạn. Vui lòng kiểm tra hóa đơn #{$invoice->order_num} được đính kèm và hoàn tất thanh toán để dịch vụ không bị gián đoạn."
|
|
: "Vui lòng xem thông tin hóa đơn #{$invoice->order_num} của bạn."
|
|
);
|
|
$paymentUrl = url('/client/invoices/' . $invoice->invoice_number . '/payment');
|
|
try {
|
|
$invoicePdf = $this->invoicePdfService->generate($invoice);
|
|
$invoicePdfFileName = $this->invoicePdfService->generateFileName($invoice);
|
|
|
|
Mail::to($customer->email)->send(
|
|
new InvoiceNotificationMail(
|
|
$invoice,
|
|
$attachments,
|
|
$customer->fullname,
|
|
$message,
|
|
$companyName,
|
|
$type,
|
|
$invoicePdf,
|
|
$invoicePdfFileName,
|
|
$paymentUrl
|
|
)
|
|
);
|
|
} catch (Throwable $e) {
|
|
Log::error('InvoiceController@sendMail failed', [
|
|
'invoice_id' => $id,
|
|
'invoice_number' => $invoice->invoice_number ?? null,
|
|
'customer_email' => $customer->email,
|
|
'type' => $type,
|
|
'error' => $e->getMessage(),
|
|
]);
|
|
|
|
return response()->json([
|
|
'error' => true,
|
|
'message' => 'Không thể gửi email: ' . $e->getMessage(),
|
|
], 500);
|
|
}
|
|
|
|
return response()->json([
|
|
'error' => false,
|
|
'message' => "Email đã được gửi tới {$customer->email}",
|
|
]);
|
|
}
|
|
}
|