feat(admin): IP pool allocation, billing exports, service attachments

- IP pool: sheet import (xlsx/csv) matched by address, bulk allocate/revoke
  with notification email (ip_allocated/ip_revoked), ip_pool_logs history.
- Orders/invoices: Excel export on branded template (BrandedReportWriter),
  shared billing filters, order item service info in list responses.
- Web design quote Excel export; activity log export.
- Service attachments with copy-to-invoice; deployment invoice attachments.
- Customer email attachments stored on disk and attached by path.
- Admin password change endpoint; user.fullname backfill migration;
  orders.user_id backfill from logs.
- Disable deploy workflow until CI/CD is set up.
- Ignore stored customer email and service attachment uploads.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
baodev0
2026-10-15 19:58:36 +07:00
co-authored by Claude Opus 5.5
parent ea5697cb81
commit 46aa138eec
95 changed files with 4247 additions and 454 deletions
@@ -2,6 +2,8 @@
namespace App\Http\Controllers\Api\Admin\ActivityLog;
use App\Exports\ActivityLogsExport;
use App\Exports\BrandedReportWriter;
use App\Http\Controllers\Controller;
use App\Models\ActivityLog;
use App\Repositories\ActivityLog\ActivityLogRepositoryInterface;
@@ -9,6 +11,7 @@ use App\Support\Cache\CacheKey;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
class ActivityLogController extends Controller
{
@@ -39,7 +42,11 @@ class ActivityLogController extends Controller
$cacheKey = CacheKey::build('activity_logs', 'list', array_merge(
$filters,
['per_page' => $perPage, 'page' => (int) $request->get('page', 1)]
[
'per_page' => $perPage,
'page' => (int) $request->get('page', 1),
'version' => $this->cacheVersion(),
]
));
$data = Cache::remember($cacheKey, self::CACHE_TTL, function () use ($filters, $perPage) {
@@ -59,7 +66,10 @@ class ActivityLogController extends Controller
public function show(int $id): JsonResponse
{
$cacheKey = CacheKey::build('activity_logs', 'detail', ['id' => $id]);
$cacheKey = CacheKey::build('activity_logs', 'detail', [
'id' => $id,
'version' => $this->cacheVersion(),
]);
$log = Cache::remember($cacheKey, self::CACHE_TTL * 5, function () use ($id) {
return $this->activityLogRepository->find($id);
@@ -74,7 +84,7 @@ class ActivityLogController extends Controller
public function modules(): JsonResponse
{
$cacheKey = CacheKey::build('activity_logs', 'modules');
$cacheKey = CacheKey::build('activity_logs', 'modules', ['version' => $this->cacheVersion()]);
$modules = Cache::remember($cacheKey, self::CACHE_TTL * 10, function () {
return ActivityLog::query()
@@ -89,7 +99,7 @@ class ActivityLogController extends Controller
public function stats(): JsonResponse
{
$cacheKey = CacheKey::build('activity_logs', 'stats');
$cacheKey = CacheKey::build('activity_logs', 'stats', ['version' => $this->cacheVersion()]);
$stats = Cache::remember($cacheKey, self::CACHE_TTL * 2, function () {
return [
@@ -108,4 +118,65 @@ class ActivityLogController extends Controller
return response()->json(['error' => false, 'data' => $stats]);
}
public function export(Request $request, BrandedReportWriter $writer): BinaryFileResponse
{
$filters = $request->validate($this->filterRules());
$query = $this->activityLogRepository->query(array_filter(
$filters,
fn ($value) => $value !== null && $value !== '',
));
return $writer->download(
new ActivityLogsExport($query),
'lich-su-hoat-dong-' . now()->format('Y-m-d-His') . '.xlsx',
);
}
public function destroy(Request $request): JsonResponse
{
$validated = $request->validate([
'mode' => ['required', 'string', 'in:all,date_range'],
'date_from' => ['required_if:mode,date_range', 'nullable', 'date_format:Y-m-d'],
'date_to' => ['required_if:mode,date_range', 'nullable', 'date_format:Y-m-d', 'after_or_equal:date_from'],
]);
$query = ActivityLog::query();
if ($validated['mode'] === 'date_range') {
$query
->where('created_at', '>=', $validated['date_from'] . ' 00:00:00')
->where('created_at', '<=', $validated['date_to'] . ' 23:59:59');
}
$deleted = $query->delete();
Cache::forever('activity_logs:version', $this->cacheVersion() + 1);
return response()->json([
'error' => false,
'message' => "Đã xóa {$deleted} log hoạt động.",
'data' => ['deleted' => $deleted],
]);
}
private function filterRules(): array
{
return [
'log_name' => ['nullable', 'string', 'max:100'],
'event' => ['nullable', 'string', 'max:100'],
'causer_type' => ['nullable', 'string', 'max:100'],
'causer_id' => ['nullable', 'integer'],
'causer_name' => ['nullable', 'string', 'max:255'],
'subject_type' => ['nullable', 'string', 'max:255'],
'subject_id' => ['nullable', 'string', 'max:255'],
'ip_address' => ['nullable', 'ip'],
'date_from' => ['nullable', 'date_format:Y-m-d'],
'date_to' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:date_from'],
'search' => ['nullable', 'string', 'max:255'],
];
}
private function cacheVersion(): int
{
return (int) Cache::get('activity_logs:version', 1);
}
}
@@ -4,11 +4,13 @@ namespace App\Http\Controllers\Api\Admin\Auth;
use App\Http\Controllers\Controller;
use App\Http\Requests\UpdateProfileRequest;
use App\Http\Requests\UpdateAdminPasswordRequest;
use App\Http\Resources\Api\Admin\AdminUserResource;
use App\Services\ActivityLogger;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\RateLimiter;
use Tymon\JWTAuth\Facades\JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
@@ -93,6 +95,27 @@ class AuthController extends Controller
]);
}
public function updatePassword(UpdateAdminPasswordRequest $request): JsonResponse
{
$user = Auth::guard('admin')->user();
$user->update([
'password' => Hash::make($request->string('password')->toString()),
]);
$this->activityLogger->logAuth(
'password_changed',
'admin',
$user->id,
$user->username ?? $user->email,
);
return response()->json([
'error' => false,
'message' => 'Đổi mật khẩu thành công.',
]);
}
public function refresh(): JsonResponse
{
try {
@@ -2,6 +2,7 @@
namespace App\Http\Controllers\Api\Admin\Customer\Concerns;
use App\Support\MailAttachments;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
@@ -64,6 +65,7 @@ trait ManagesCustomerAccount
'cc' => 'nullable|string|max:1000',
'bcc' => 'nullable|string|max:1000',
'with_layout' => 'nullable|boolean',
...MailAttachments::rules(),
]);
$this->mailService->sendCustomEmail($uuid, $data, Auth::guard('admin')->user(), $request->ip());
@@ -31,7 +31,7 @@ trait HandlesInvoiceAttachments
}
$request->validate([
'file' => 'required|file|mimes:jpg,jpeg,png,gif,webp,pdf,doc,docx,xls,xlsx|max:51200',
'file' => InvoiceAttachment::UPLOAD_RULE,
'type' => 'nullable|in:' . InvoiceAttachment::TYPE_PAYMENT_PROOF . ',' . InvoiceAttachment::TYPE_DEPLOYMENT,
]);
@@ -6,7 +6,12 @@ use App\Enums\Invoice\InvoiceStatus;
use App\Helpers\OrderHelper;
use App\Http\Controllers\Controller;
use App\Http\Requests\InvoiceRequest;
use App\Exports\BrandedReportWriter;
use App\Http\Requests\BillingExportRequest;
use App\Exports\InvoicesExport;
use App\Http\Resources\Api\Admin\InvoiceResource;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use App\Http\Resources\Api\Admin\OrderItemServiceResource;
use App\Models\Invoice;
use App\Models\InvoiceItem;
use App\Models\Order;
@@ -39,7 +44,12 @@ class InvoiceController extends Controller
{
$query = $this->invoiceRepository->filter(
$request->all(),
['payment', 'customer', 'order'],
[
'payment',
'customer',
'order',
...OrderItemServiceResource::relationsFor('order.orderItems'),
],
[],
['*'],
true
@@ -54,6 +64,19 @@ class InvoiceController extends Controller
]);
}
public function export(BillingExportRequest $request, BrandedReportWriter $writer): BinaryFileResponse
{
$query = $this->invoiceRepository->filter(
array_filter($request->validated(), fn ($value) => $value !== null && $value !== []),
['payment', 'customer', 'order', ...OrderItemServiceResource::relationsFor('order.orderItems')],
[],
['*'],
true
);
return $writer->download(new InvoicesExport($query), 'hoa-don-' . now()->format('Y-m-d-His') . '.xlsx');
}
/**
* 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ý).
@@ -0,0 +1,95 @@
<?php
namespace App\Http\Controllers\Api\Admin\IpPool\Concerns;
use App\Models\Customer;
use App\Models\IpPool;
use App\Services\IpPool\IpAllocationService;
use App\Support\MailAttachments;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
trait ManagesIpPoolAllocation
{
public function allocationPreview(Request $request, IpAllocationService $allocation): JsonResponse
{
$data = $this->validateAllocation($request);
return response()->json([
'error' => false,
'data' => $allocation->previewAllocation($data['ids'], $this->allocationCustomer($data), $data),
]);
}
public function allocate(Request $request, IpAllocationService $allocation): JsonResponse
{
$data = $this->validateAllocation($request);
$count = $allocation->allocate($data['ids'], $this->allocationCustomer($data), $data, $request->user('admin'));
return response()->json(['error' => false, 'message' => "Đã cấp phát {$count} IP và gửi email cho khách hàng"]);
}
public function revocationPreview(Request $request, IpAllocationService $allocation): JsonResponse
{
$data = $this->validateRevocation($request);
return response()->json(['error' => false, 'data' => $allocation->previewRevocation($data['ids'], $data)]);
}
public function revoke(Request $request, IpAllocationService $allocation): JsonResponse
{
$data = $this->validateRevocation($request, withRecipients: true);
$recipients = collect($data['recipients'])->keyBy('key')->all();
$count = $allocation->revoke($data['ids'], $data, $recipients, $request->user('admin'));
return response()->json(['error' => false, 'message' => "Đã thu hồi {$count} IP và gửi email thông báo"]);
}
public function logs(int $id): JsonResponse
{
$pool = IpPool::withTrashed()->findOrFail($id);
return response()->json([
'error' => false,
'data' => $pool->logs()->with('user:id,username,fullname')->limit(200)->get(),
]);
}
private function validateAllocation(Request $request): array
{
return $request->validate([
'ids' => 'required|array|min:1|max:1000',
'ids.*' => 'integer',
'customer_uuid' => 'required|string|exists:customers,uuid',
'to' => ['required', 'string', 'max:1000', $this->multiEmailRule()],
'cc' => ['nullable', 'string', 'max:1000', $this->multiEmailRule()],
'date' => 'required|date',
'service_name' => 'nullable|string|max:255',
'services' => 'nullable|array',
'services.*' => 'nullable|string|max:255',
'note' => 'nullable|string|max:2000',
'subject' => 'nullable|string|max:255',
...MailAttachments::rules(),
]);
}
private function validateRevocation(Request $request, bool $withRecipients = false): array
{
return $request->validate([
'ids' => 'required|array|min:1|max:1000',
'ids.*' => 'integer',
'date' => 'required|date',
'note' => 'nullable|string|max:2000',
'recipients' => $withRecipients ? 'required|array|min:1' : 'prohibited',
'recipients.*.key' => 'required|string',
'recipients.*.to' => ['nullable', 'string', 'max:1000', $this->multiEmailRule()],
'recipients.*.cc' => ['nullable', 'string', 'max:1000', $this->multiEmailRule()],
'recipients.*.subject' => 'nullable|string|max:255',
]);
}
private function allocationCustomer(array $data): Customer
{
return Customer::where('uuid', $data['customer_uuid'])->firstOrFail();
}
}
@@ -2,15 +2,13 @@
namespace App\Http\Controllers\Api\Admin\IpPool\Concerns;
use App\Imports\IpPoolImport;
use App\Services\IpPool\IpPoolSheetImporter;
use App\Models\IpPool;
use App\Models\ModuleIpAddress;
use App\Models\ModuleNetwork;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;
use Maatwebsite\Excel\Validators\ValidationException;
trait ManagesIpPoolBulkActions
{
@@ -94,39 +92,24 @@ trait ManagesIpPoolBulkActions
]);
}
public function import(Request $request): JsonResponse
public function importPreview(Request $request, IpPoolSheetImporter $importer): JsonResponse
{
$request->validate([
'file' => 'required|file|mimes:csv,txt|max:10240',
]);
$request->validate(['file' => self::IMPORT_FILE_RULE]);
$countBefore = IpPool::withTrashed()->count();
return response()->json(['error' => false, 'data' => $importer->preview($request->file('file'))]);
}
try {
Excel::import(new IpPoolImport(), $request->file('file'));
} catch (ValidationException $e) {
$errors = [];
foreach ($e->failures() as $failure) {
$errors[] = 'Dòng ' . $failure->row() . ': ' . implode(', ', $failure->errors());
}
public function import(Request $request, IpPoolSheetImporter $importer): JsonResponse
{
$request->validate(['file' => self::IMPORT_FILE_RULE]);
return response()->json([
'error' => true,
'message' => 'Import thất bại',
'errors' => $errors,
], 422);
} catch (\Exception $e) {
return response()->json(['error' => true, 'message' => 'Import thất bại: ' . $e->getMessage()], 500);
}
$countAfter = IpPool::withTrashed()->count();
IpPool::resyncAllContacts();
$summary = $importer->import($request->file('file'));
return response()->json([
'error' => false,
'message' => 'Import thành công',
'created' => max(0, $countAfter - $countBefore),
'message' => "Đã thêm {$summary['create']}, cập nhật {$summary['update']} IP"
. ($summary['error_count'] ? ", bỏ qua {$summary['error_count']} dòng lỗi" : ''),
'data' => $summary,
]);
}
@@ -142,7 +125,7 @@ trait ManagesIpPoolBulkActions
$updated = 0;
$hostByNet = ModuleNetwork::pluck('module_host_id', 'id');
IpPool::chunkById(500, function ($pools) use (&$created, &$updated, $hostByNet) {
IpPool::whereNotNull('module_network_id')->chunkById(500, function ($pools) use (&$created, &$updated, $hostByNet) {
foreach ($pools as $pool) {
$hostId = $hostByNet[$pool->module_network_id] ?? null;
$netmask = $pool->netmask ?: '255.255.255.0';
@@ -6,14 +6,17 @@ use App\Http\Controllers\Controller;
use App\Models\IpPool;
use App\Models\ModuleIpAddress;
use App\Models\ModuleNetwork;
use App\Services\IpPool\IpPoolUsageResolver;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Api\Admin\IpPool\Concerns\ManagesIpPoolAllocation;
use App\Http\Controllers\Api\Admin\IpPool\Concerns\ManagesIpPoolBulkActions;
use App\Http\Controllers\Api\Admin\IpPool\Concerns\ReadsIpPoolUsage;
class IpPoolController extends Controller
{
use ManagesIpPoolAllocation;
use ManagesIpPoolBulkActions;
use ReadsIpPoolUsage;
@@ -22,13 +25,15 @@ class IpPoolController extends Controller
* status/service_id which have defaulting + module_ip_address mirror logic below.
*/
private const EDITABLE_FIELDS = [
'owner_type', 'ip_role', 'parent_ip', 'customer_name', 'service_name',
'allocated_at', 'revoked_at', 'allocation_status',
'ip_block', 'owner_type', 'ip_role', 'parent_ip', 'customer_name', 'service_name',
'allocated_at', 'revoked_at',
'contact_email', 'contact_cc', 'contact_phone',
'monthly_cost', 'selling_price', 'additional_info',
'last_email_type', 'last_email_at', 'updated_by', 'note',
];
private const IMPORT_FILE_RULE = 'required|file|extensions:xlsx,xls,csv|max:20480';
/**
* contact_email/contact_cc may hold multiple addresses separated by comma/semicolon.
*/
@@ -44,14 +49,14 @@ class IpPoolController extends Controller
};
}
public function index(Request $request): JsonResponse
public function index(Request $request, IpPoolUsageResolver $usageResolver): JsonResponse
{
// 'all' lets the admin grid load the full dataset once and filter/sort client-side.
$perPage = $request->boolean('all') ? 20000 : min((int) $request->get('per_page', 15), 500);
$filter = $request->get('filter');
$networkId = $request->get('network_id');
$query = IpPool::with(['network:id,name,type,network', 'service:id,server_name,status,customer_id']);
$query = IpPool::with(['network:id,name,type,network', 'service:id,server_name,status,customer_id', 'customer:id,uuid,fullname']);
if ($filter) {
$query->where('ip_address', 'like', "%{$filter}%");
@@ -62,61 +67,12 @@ class IpPoolController extends Controller
}
$paginator = $query->paginate($perPage);
$usage = $usageResolver->forPools($paginator->getCollection());
// Enrich each item with usage info
$usedIps = ModuleIpAddress::whereIn('ip', $paginator->pluck('ip_address')->toArray())
->where('status', 1)
->with('host:id,name')
->select(['id', 'ip', 'vm_name', 'module_host_id', 'module_network_id', 'status'])
->get()
->keyBy('ip');
// Get vmware info for used IPs
$vmwareMap = [];
if ($usedIps->isNotEmpty()) {
$vmwares = DB::table('module_vmware as mv')
->join('module_ip_address as mia', 'mv.module_ip_address', '=', 'mia.id')
->whereIn('mia.ip', $usedIps->keys()->toArray())
->leftJoin('services as s', 's.id', '=', 'mv.service_id')
->leftJoin('customers as c', 'c.id', '=', 'mv.customer_id')
->select([
'mia.ip',
'mv.name as vm_name',
'mv.id as vm_id',
's.id as service_id',
's.status as service_status',
'c.fullname',
'c.email',
])
->get();
foreach ($vmwares as $vm) {
$vmwareMap[$vm->ip] = $vm;
}
}
$items = $paginator->map(function (IpPool $pool) use ($usedIps, $vmwareMap) {
$data = $pool->toArray();
$ip = $pool->ip_address;
if (isset($usedIps[$ip])) {
$mia = $usedIps[$ip];
$vm = $vmwareMap[$ip] ?? null;
$data['usage'] = [
'assigned' => true,
'vm_name' => $vm?->vm_name ?? $mia->vm_name,
'vm_id' => $vm?->vm_id ?? null,
'service_id' => $vm?->service_id ?? null,
'service_status' => $vm?->service_status ?? null,
'customer_name' => $vm?->fullname ?? null,
'customer_email' => $vm?->email ?? null,
];
} else {
$data['usage'] = ['assigned' => false];
}
return $data;
});
$items = $paginator->map(fn (IpPool $pool) => [
...$pool->toArray(),
'usage' => $usage[$pool->ip_address] ?? ['assigned' => false],
]);
return response()->json([
'error' => false,
@@ -5,7 +5,12 @@ namespace App\Http\Controllers\Api\Admin\Order;
use App\Http\Controllers\Controller;
use App\Http\Requests\OrderRequest;
use App\Http\Requests\UpdateOrderRequest;
use App\Exports\BrandedReportWriter;
use App\Http\Requests\BillingExportRequest;
use App\Exports\OrdersExport;
use App\Http\Resources\Api\Admin\OrderItemServiceResource;
use App\Http\Resources\Api\Admin\OrderResource;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use App\Models\Order;
use App\Models\DomainPricing;
use App\Repositories\Order\OrderRepositoryInterface;
@@ -27,7 +32,13 @@ class OrderController extends Controller
$data = $this->orderRepository->filter(
$request->all(),
['payment', 'customer', 'invoice'],
[
'payment',
'customer',
'invoice',
'orderItems.os',
...OrderItemServiceResource::relationsFor('orderItems'),
],
[],
['*'],
true
@@ -43,6 +54,19 @@ class OrderController extends Controller
]);
}
public function export(BillingExportRequest $request, BrandedReportWriter $writer): BinaryFileResponse
{
$query = $this->orderRepository->filter(
array_filter($request->validated(), fn ($value) => $value !== null && $value !== []),
['payment', 'customer', 'invoices:id,order_id,invoice_number', ...OrderItemServiceResource::relationsFor('orderItems')],
[],
['*'],
true
);
return $writer->download(new OrdersExport($query), 'don-hang-' . now()->format('Y-m-d-His') . '.xlsx');
}
public function domainPricing(): JsonResponse
{
return response()->json([
@@ -0,0 +1,82 @@
<?php
namespace App\Http\Controllers\Api\Admin\Service\Concerns;
use App\Models\Invoice;
use App\Models\InvoiceAttachment;
use App\Models\Service;
use App\Models\ServiceAttachment;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
trait HandlesServiceAttachments
{
public function listAttachments(int $id): JsonResponse
{
$service = Service::with('orderItem')->findOrFail($id);
return response()->json([
'error' => false,
'data' => [
'attachments' => ServiceAttachment::where('service_id', $id)->latest()->get(),
'invoices' => $this->linkedInvoices(collect([$service])),
],
]);
}
public function uploadAttachment(Request $request, int $id): JsonResponse
{
Service::findOrFail($id);
$request->validate(['file' => InvoiceAttachment::UPLOAD_RULE]);
$file = $request->file('file');
$attachment = ServiceAttachment::create([
'service_id' => $id,
'filename' => $file->getClientOriginalName(),
'path' => $file->store("service-attachments/{$id}", 'public'),
'disk' => 'public',
'mime_type' => $file->getMimeType(),
'size' => $file->getSize(),
'uploaded_by' => $request->user()?->username ?? $request->user()?->name ?? 'admin',
]);
return response()->json(['error' => false, 'message' => 'File uploaded successfully', 'data' => $attachment], 201);
}
public function deleteAttachment(int $id, int $attachmentId): JsonResponse
{
$attachment = ServiceAttachment::where('service_id', $id)->findOrFail($attachmentId);
Storage::disk($attachment->disk)->delete($attachment->path);
$attachment->delete();
return response()->json(['error' => false, 'message' => 'Attachment deleted']);
}
public function copyAttachmentToInvoice(Request $request, int $id, int $attachmentId): JsonResponse
{
$service = Service::with('orderItem')->findOrFail($id);
$attachment = ServiceAttachment::where('service_id', $id)->findOrFail($attachmentId);
$invoiceId = (int) $request->validate(['invoice_id' => 'required|integer'])['invoice_id'];
$invoice = Invoice::ofServices([$service])->findOrFail($invoiceId);
$path = "invoice-attachments/{$invoice->id}/" . basename($attachment->path);
if (!Storage::disk('public')->exists($path)) {
Storage::disk('public')->put($path, Storage::disk($attachment->disk)->readStream($attachment->path));
}
$copy = InvoiceAttachment::firstOrCreate(
['invoice_id' => $invoice->id, 'path' => $path],
[
'type' => InvoiceAttachment::TYPE_DEPLOYMENT,
'filename' => $attachment->filename,
'disk' => 'public',
'mime_type' => $attachment->mime_type,
'size' => $attachment->size,
'uploaded_by' => $request->user()?->username ?? $request->user()?->name ?? 'admin',
],
);
return response()->json(['error' => false, 'message' => 'Attachment copied to invoice', 'data' => $copy], 201);
}
}
@@ -3,26 +3,31 @@
namespace App\Http\Controllers\Api\Admin\Service;
use App\Helpers\OrderHelper;
use App\Http\Controllers\Api\Admin\Service\Concerns\HandlesServiceAttachments;
use App\Http\Controllers\Controller;
use App\Jobs\VirtualMachine\Provision\ResendVmCredentialsEmailJob;
use App\Models\ActivityLog;
use App\Models\DomainPricing;
use App\Models\Invoice;
use App\Models\ModuleVmware;
use App\Models\Service;
use App\Services\Customer\CustomerServiceAssignment;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Collection;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class ServiceController extends Controller
{
use HandlesServiceAttachments;
public function __construct(private readonly CustomerServiceAssignment $assignment) {}
public function index(Request $request): JsonResponse
{
$perPage = min((int) ($request->per_page ?? 15), 100);
$query = Service::with(['customer:id,uuid,fullname,email', 'product:id,uuid,name', 'invoice:id,invoice_number', 'vmware:id,name,module_ip_address'])
$query = Service::with(['customer:id,uuid,fullname,email', 'product:id,uuid,name', 'invoice:id,invoice_number', 'vmware:id,name,module_ip_address', 'orderItem:id,order_id', 'orderItem.order:id,order_num'])
->where(fn($q) => $q->whereNull('order_item_id')->orWhereNull('type')->orWhere('type', '!=', 'domain'))
->when($request->filter, fn($q, $v) => $q->where('server_name', 'like', "%{$v}%"))
->when($request->status, fn($q, $v) => $q->where('status', $v))
@@ -30,6 +35,11 @@ class ServiceController extends Controller
->when($request->boolean('unassigned'), fn($q) => $q->whereNull('customer_id'));
$paginator = $query->latest()->paginate($perPage);
$invoices = $this->linkedInvoices($paginator->getCollection());
$paginator->getCollection()->each(fn (Service $service) => $service->setAttribute(
'linked_invoices',
$invoices->filter(fn (Invoice $invoice) => $invoice->belongsToService($service))->values(),
));
return response()->json([
'error' => false,
@@ -72,11 +82,12 @@ class ServiceController extends Controller
public function show(int $id): JsonResponse
{
$service = Service::with(['customer', 'product', 'orderItem', 'invoice', 'vmware.os.osGroup', 'addons', ...Service::HOSTING_ACCOUNT_RELATIONS])
$service = Service::with(['customer', 'product', 'orderItem.order:id,order_num', 'invoice', 'vmware.os.osGroup', 'addons', ...Service::HOSTING_ACCOUNT_RELATIONS])
->findOrFail($id);
ModuleVmware::resolveVirtualMachineIds([$service->vmware]);
$service->setAttribute('linked_invoices', $this->linkedInvoices(collect([$service])));
$service->setAttribute('activity_logs', ActivityLog::where('subject_type', Service::class)
->where('subject_id', $service->id)
->latest('id')
@@ -86,6 +97,15 @@ class ServiceController extends Controller
return response()->json(['error' => false, 'data' => $service]);
}
/** @param Collection<int, Service> $services */
private function linkedInvoices(Collection $services): Collection
{
return Invoice::ofServices($services)
->with('order:id,order_num')
->latest('id')
->get(['id', 'order_id', 'service_id', 'invoice_number', 'invoice_type', 'status', 'total', 'created_at']);
}
public function bulkAction(Request $request): JsonResponse
{
$data = $request->validate([
@@ -8,8 +8,8 @@ use App\Http\Controllers\Controller;
use App\Http\Facade\SignRSA;
use App\Http\Services\Telegram;
use App\Models\Setting;
use App\Support\Cache\CacheKey;
use App\Support\PublicSetting;
use App\Support\MailSettings;
use App\Support\Turnstile;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
@@ -115,8 +115,7 @@ class SettingController extends Controller
['value' => json_encode($merged, JSON_UNESCAPED_UNICODE)]
);
// Flush mail config cache so new SMTP settings take effect immediately
Cache::forget(CacheKey::build('settings', 'mail'));
Cache::forget(MailSettings::cacheKey());
}
if ($request->has('turnstile')) {
@@ -30,7 +30,7 @@ class StaffOnlineController extends Controller
$online = $users->map(fn ($user) => [
'user_id' => $user->id,
'name' => trim($user->firstname . ' ' . $user->lastname),
'name' => $user->name,
'username' => $user->username,
'email' => $user->email,
'last_visited' => $user->staffOnline?->last_visited,
@@ -4,6 +4,7 @@ namespace App\Http\Controllers\Api\Admin\WebDesign;
use App\Enums\WebDesign\WebDesignPlatform;
use App\Enums\WebDesign\WebDesignQuoteStatus;
use App\Exports\WebDesignQuoteSpreadsheet;
use App\Http\Controllers\Controller;
use App\Models\WebDesignQuote;
use App\Services\WebDesignQuotePdfService;
@@ -11,6 +12,7 @@ use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Validation\Rule;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
class WebDesignQuoteController extends Controller
{
@@ -18,7 +20,7 @@ class WebDesignQuoteController extends Controller
{
$perPage = min((int) $request->get('per_page', 15), 100);
$query = WebDesignQuote::with('creator:id,firstname,lastname')
$query = WebDesignQuote::with('creator:id,fullname')
->when($request->get('filter'), fn($q, $f) =>
$q->where(fn($sub) => $sub
->where('quote_number', 'like', "%{$f}%")
@@ -47,7 +49,7 @@ class WebDesignQuoteController extends Controller
public function show(int $id): JsonResponse
{
$quote = WebDesignQuote::with('creator:id,firstname,lastname')->find($id);
$quote = WebDesignQuote::with('creator:id,fullname')->find($id);
if (!$quote) {
return response()->json(['error' => true, 'message' => 'Không tìm thấy báo giá.'], 404);
@@ -92,7 +94,7 @@ class WebDesignQuoteController extends Controller
return response()->json([
'error' => false,
'message' => 'Cập nhật báo giá thành công.',
'data' => $quote->fresh('creator:id,firstname,lastname'),
'data' => $quote->fresh('creator:id,fullname'),
]);
}
@@ -149,6 +151,17 @@ class WebDesignQuoteController extends Controller
]);
}
public function downloadXlsx(int $id, WebDesignQuoteSpreadsheet $spreadsheet): BinaryFileResponse|JsonResponse
{
$quote = WebDesignQuote::find($id);
if (!$quote) {
return response()->json(['error' => true, 'message' => 'Không tìm thấy báo giá.'], 404);
}
return $spreadsheet->download($quote);
}
/**
* Danh sách cấu hình nền tảng cho form báo giá (label, frontend, custom admin, phí bản quyền).
*/