feat: nạp tiền thủ công mã 30 phút, gia hạn trừ số dư, đồng bộ domain từ Plesk
- Nạp tiền: mã thanh toán sống 30 phút (ManualDepositDraft), khôi phục/huỷ mã, lệnh dọn mã hết hạn; total_pending chỉ tính giao dịch đã nộp chứng từ, admin duyệt/từ chối/xoá giao dịch - Gia hạn dịch vụ: phát hành invoice gia hạn trên order gốc và trừ số dư ngay - Đồng bộ domain từ Plesk theo server, ServiceOrderRecorder tạo order/invoice cho dịch vụ admin dựng - Danh sách dịch vụ trả field theo loại (service_plan, dns_records_count), đếm dịch vụ theo loại Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
10af41c5cf
commit
c5115b52dd
@@ -4,7 +4,11 @@ namespace App\Http\Controllers\Api\Admin\Customer\Concerns;
|
||||
|
||||
use App\Models\DnsDomain;
|
||||
use App\Models\DnsRecord;
|
||||
use App\Models\Service;
|
||||
use App\Services\Domain\CustomerDomainServiceSync;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
trait ManagesCustomerDomains
|
||||
@@ -21,6 +25,7 @@ trait ManagesCustomerDomains
|
||||
public function getDnsDomains(string $uuid): JsonResponse
|
||||
{
|
||||
$customer = $this->resolveCustomer($uuid);
|
||||
$domainServices = $this->customerDomainServices($customer->id);
|
||||
|
||||
$domains = DnsDomain::query()
|
||||
->with(['server:id,name,ip_address', 'registrar:id,name,short_name,website'])
|
||||
@@ -30,6 +35,7 @@ trait ManagesCustomerDomains
|
||||
->get()
|
||||
->map(fn($d) => [
|
||||
'id' => $d->id,
|
||||
'service_id' => $domainServices->get($this->domainKey($d->domain_name))?->id,
|
||||
'domain_name' => $d->domain_name,
|
||||
'is_created' => (int) $d->is_created,
|
||||
'plesk_id' => $d->plesk_id,
|
||||
@@ -46,6 +52,7 @@ trait ManagesCustomerDomains
|
||||
'short_name' => $d->registrar->short_name,
|
||||
'website' => $d->registrar->website,
|
||||
] : null,
|
||||
'expires_at' => $domainServices->get($this->domainKey($d->domain_name))?->expires_at,
|
||||
'created_at' => $d->created_at,
|
||||
'updated_at' => $d->updated_at,
|
||||
]);
|
||||
@@ -53,6 +60,84 @@ trait ManagesCustomerDomains
|
||||
return response()->json(['error' => false, 'data' => $domains]);
|
||||
}
|
||||
|
||||
public function updateDnsDomain(string $uuid, int $domainId, Request $request): JsonResponse
|
||||
{
|
||||
$domain = $this->resolveCustomerDnsDomain($uuid, $domainId);
|
||||
|
||||
$data = $request->validate([
|
||||
'is_created' => 'required|integer|in:0,1,2,3',
|
||||
'created_at' => 'required|date',
|
||||
'expires_at' => 'nullable|date',
|
||||
]);
|
||||
|
||||
$customer = $this->resolveCustomer($uuid);
|
||||
|
||||
DB::transaction(function () use ($domain, $customer, $data) {
|
||||
$domain->forceFill(['is_created' => $data['is_created'], 'created_at' => $data['created_at']])->save();
|
||||
app(CustomerDomainServiceSync::class)->updateCustomerDomain($domain, $customer->id, $data['expires_at']);
|
||||
});
|
||||
|
||||
return response()->json(['error' => false, 'message' => 'Cập nhật domain thành công']);
|
||||
}
|
||||
|
||||
public function detachDnsDomain(string $uuid, int $domainId): JsonResponse
|
||||
{
|
||||
$customer = $this->resolveCustomer($uuid);
|
||||
$domain = $this->resolveCustomerDnsDomain($uuid, $domainId);
|
||||
|
||||
$remainingCustomerIds = $domain->customer()->pluck('customers.id')->reject(
|
||||
fn ($customerId) => (int) $customerId === (int) $customer->id,
|
||||
)->all();
|
||||
app(CustomerDomainServiceSync::class)->syncCustomers($domain, $remainingCustomerIds);
|
||||
|
||||
return response()->json(['error' => false, 'message' => 'Đã gỡ domain khỏi khách hàng']);
|
||||
}
|
||||
|
||||
public function assignDnsDomain(string $uuid, Request $request): JsonResponse
|
||||
{
|
||||
$customer = $this->resolveCustomer($uuid);
|
||||
$data = $request->validate([
|
||||
'domain_id' => ['required', 'integer', 'exists:dns_manager_domain,id'],
|
||||
'service_id' => ['required', 'integer', 'exists:services,id'],
|
||||
]);
|
||||
|
||||
abort_unless(
|
||||
Service::query()->whereKey($data['service_id'])->where('customer_id', $customer->id)->exists(),
|
||||
422,
|
||||
'Dịch vụ không thuộc khách hàng này',
|
||||
);
|
||||
|
||||
$domain = DnsDomain::query()->findOrFail($data['domain_id']);
|
||||
$customerIds = $domain->customer()->pluck('customers.id')->push($customer->id)->all();
|
||||
app(CustomerDomainServiceSync::class)->syncCustomers($domain, $customerIds);
|
||||
|
||||
return response()->json(['error' => false, 'message' => 'Gán domain thành công']);
|
||||
}
|
||||
|
||||
private function customerDomainServices(int $customerId): Collection
|
||||
{
|
||||
return Service::query()
|
||||
->where('customer_id', $customerId)
|
||||
->where('type', 'domain')
|
||||
->orderBy('id')
|
||||
->get()
|
||||
->keyBy(fn(Service $service) => $this->domainKey($service->server_name));
|
||||
}
|
||||
|
||||
private function domainKey(?string $domainName): string
|
||||
{
|
||||
return mb_strtolower(trim((string) $domainName));
|
||||
}
|
||||
|
||||
private function resolveCustomerDnsDomain(string $uuid, int $domainId): DnsDomain
|
||||
{
|
||||
$customer = $this->resolveCustomer($uuid);
|
||||
|
||||
return DnsDomain::query()
|
||||
->whereHas('customer', fn($q) => $q->where('customers.id', $customer->id))
|
||||
->findOrFail($domainId);
|
||||
}
|
||||
|
||||
public function getDnsDomainRecords(string $uuid, int $domainId): JsonResponse
|
||||
{
|
||||
$customer = $this->resolveCustomer($uuid);
|
||||
|
||||
@@ -10,6 +10,7 @@ use App\Jobs\DnsManager\SyncDnsFromPlesk;
|
||||
use App\Repositories\DnsManager\Domain\DnsDomainRepositoryInterface;
|
||||
use App\Repositories\DnsManager\Record\DnsRecordRepositoryInterface;
|
||||
use App\Services\ServerService;
|
||||
use App\Services\Domain\CustomerDomainServiceSync;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
@@ -32,6 +33,7 @@ class DomainController extends Controller
|
||||
private readonly DnsDomainRepositoryInterface $domainRepository,
|
||||
private readonly DnsRecordRepositoryInterface $recordRepository,
|
||||
private readonly ServerService $serverService,
|
||||
private readonly CustomerDomainServiceSync $customerDomainServiceSync,
|
||||
) {}
|
||||
|
||||
// ─── Domains ─────────────────────────────────────────────────────────────
|
||||
@@ -114,7 +116,7 @@ class DomainController extends Controller
|
||||
]);
|
||||
|
||||
if (!empty($request->customer_ids)) {
|
||||
$domain->customer()->sync($request->customer_ids);
|
||||
$this->customerDomainServiceSync->syncCustomers($domain, $request->customer_ids);
|
||||
}
|
||||
|
||||
DB::commit();
|
||||
@@ -153,6 +155,7 @@ class DomainController extends Controller
|
||||
|
||||
DB::beginTransaction();
|
||||
try {
|
||||
$previousDomainName = $domain->domain_name;
|
||||
$this->domainRepository->update($id, $request->only([
|
||||
'domain_name',
|
||||
'dns_manager_server_id',
|
||||
@@ -161,8 +164,19 @@ class DomainController extends Controller
|
||||
]));
|
||||
|
||||
// Sync customers (empty array = detach all)
|
||||
$freshDomain = $domain->fresh();
|
||||
if ($request->has('customer_ids')) {
|
||||
$domain->customer()->sync($request->customer_ids ?? []);
|
||||
$this->customerDomainServiceSync->syncCustomers(
|
||||
$freshDomain,
|
||||
$request->customer_ids ?? [],
|
||||
$previousDomainName,
|
||||
);
|
||||
} elseif ($previousDomainName !== $freshDomain->domain_name) {
|
||||
$this->customerDomainServiceSync->syncCustomers(
|
||||
$freshDomain,
|
||||
$freshDomain->customer()->pluck('customers.id')->all(),
|
||||
$previousDomainName,
|
||||
);
|
||||
}
|
||||
|
||||
DB::commit();
|
||||
@@ -270,9 +284,13 @@ class DomainController extends Controller
|
||||
|
||||
// ─── Sync from Plesk ─────────────────────────────────────────────────────
|
||||
|
||||
public function syncDns(): JsonResponse
|
||||
public function syncDns(Request $request): JsonResponse
|
||||
{
|
||||
dispatch(new SyncDnsFromPlesk());
|
||||
$validated = $request->validate([
|
||||
'dns_manager_server_id' => ['nullable', 'integer', 'exists:dns_manager_servers,id'],
|
||||
]);
|
||||
|
||||
dispatch(new SyncDnsFromPlesk($validated['dns_manager_server_id'] ?? null));
|
||||
|
||||
return response()->json([
|
||||
'error' => false,
|
||||
|
||||
@@ -373,6 +373,7 @@ class AdminDomainOrderController extends Controller
|
||||
'refunded_at' => $service->refunded_at?->toIso8601String(),
|
||||
'cancelled_at' => $service->cancelled_at?->toIso8601String(),
|
||||
'created_at' => $service->created_at?->toIso8601String(),
|
||||
'updated_at' => $service->updated_at?->toIso8601String(),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,8 +84,12 @@ class ProductCategoryController extends Controller
|
||||
'name' => 'required|string|max:255',
|
||||
'parent_id' => 'nullable|integer|exists:product_categories,id',
|
||||
'is_active' => 'boolean',
|
||||
'sort_order' => 'nullable|integer',
|
||||
'sort_order' => 'required|integer|min:0',
|
||||
'type' => 'nullable|string',
|
||||
], [
|
||||
'sort_order.required' => 'Vui lòng nhập thứ tự hiển thị (sort_order).',
|
||||
'sort_order.integer' => 'Thứ tự hiển thị phải là số nguyên.',
|
||||
'sort_order.min' => 'Thứ tự hiển thị không được âm.',
|
||||
]);
|
||||
|
||||
$validated['slug'] = Str::slug($validated['name']);
|
||||
@@ -119,8 +123,12 @@ class ProductCategoryController extends Controller
|
||||
'name' => 'sometimes|required|string|max:255',
|
||||
'parent_id' => 'nullable|integer|exists:product_categories,id',
|
||||
'is_active' => 'boolean',
|
||||
'sort_order' => 'nullable|integer',
|
||||
'sort_order' => 'sometimes|required|integer|min:0',
|
||||
'type' => 'nullable|string',
|
||||
], [
|
||||
'sort_order.required' => 'Vui lòng nhập thứ tự hiển thị (sort_order).',
|
||||
'sort_order.integer' => 'Thứ tự hiển thị phải là số nguyên.',
|
||||
'sort_order.min' => 'Thứ tự hiển thị không được âm.',
|
||||
]);
|
||||
|
||||
if (isset($validated['name']) && $validated['name'] !== $category->name) {
|
||||
|
||||
@@ -2,8 +2,10 @@
|
||||
|
||||
namespace App\Http\Controllers\Api\Admin\Service;
|
||||
|
||||
use App\Helpers\OrderHelper;
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Jobs\VirtualMachine\Provision\ResendVmCredentialsEmailJob;
|
||||
use App\Models\DomainPricing;
|
||||
use App\Models\ModuleVmware;
|
||||
use App\Models\Service;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
@@ -16,6 +18,7 @@ class ServiceController extends Controller
|
||||
$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'])
|
||||
->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))
|
||||
->when($request->customer_id, fn($q, $v) => $q->where('customer_id', $v));
|
||||
@@ -34,6 +37,33 @@ class ServiceController extends Controller
|
||||
]);
|
||||
}
|
||||
|
||||
public function domainQuote(Request $request): JsonResponse
|
||||
{
|
||||
$data = $request->validate([
|
||||
'domain' => 'required|string|max:255',
|
||||
'billing_cycle' => 'nullable|in:monthly,quarterly,semi_annually,annually,biennially,triennially',
|
||||
]);
|
||||
|
||||
$pricing = DomainPricing::matchDomain($data['domain']);
|
||||
if (!$pricing) {
|
||||
return response()->json(['error' => false, 'data' => null]);
|
||||
}
|
||||
|
||||
$years = DomainPricing::yearsForMonths(OrderHelper::cycleToMonths($data['billing_cycle'] ?? 'annually'));
|
||||
|
||||
return response()->json([
|
||||
'error' => false,
|
||||
'data' => [
|
||||
'tld' => $pricing->tld,
|
||||
'setup_fee' => is_numeric($pricing->setup_fee) ? (int) $pricing->setup_fee : 0,
|
||||
'first_year' => (int) $pricing->first_year,
|
||||
'renewal' => (int) $pricing->recurring_fee,
|
||||
'years' => $years,
|
||||
'price' => $pricing->orderPrice($years),
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
public function show(int $id): JsonResponse
|
||||
{
|
||||
$service = Service::with(['customer', 'product', 'orderItem', 'invoice', 'vmware.os.osGroup', 'addons', ...Service::HOSTING_ACCOUNT_RELATIONS])
|
||||
|
||||
@@ -137,8 +137,7 @@ class AdminTransactionController extends Controller
|
||||
$creditEarned = Customer::creditFor($received);
|
||||
$customer->total += $received;
|
||||
$customer->credit += $creditEarned;
|
||||
// Trừ pending theo số khách khai — đó chính là số đã được giữ chỗ lúc tạo yêu cầu.
|
||||
$customer->total_pending = max(0, $customer->total_pending - $declared);
|
||||
$this->releasePending($customer, $transaction, $declared);
|
||||
$customer->save();
|
||||
|
||||
Log::create([
|
||||
@@ -158,7 +157,7 @@ class AdminTransactionController extends Controller
|
||||
'type' => 'deposit_success',
|
||||
'title' => 'Nạp tiền thành công',
|
||||
'body' => 'Giao dịch ' . $transaction->public_code . ' đã được duyệt.',
|
||||
'link' => '/lich-su-giao-dich/' . $transaction->id,
|
||||
'link' => '/lich-su-giao-dich/' . $transaction->uuid,
|
||||
'data' => [
|
||||
'transaction_uuid' => $transaction->uuid,
|
||||
'amount' => $received,
|
||||
@@ -231,7 +230,7 @@ class AdminTransactionController extends Controller
|
||||
$transaction->update(['status' => TransactionStatus::FAILED->value]);
|
||||
|
||||
$customer = Customer::where('id', $transaction->customer_id)->lockForUpdate()->first();
|
||||
$customer->total_pending = max(0, $customer->total_pending - $transaction->amount);
|
||||
$this->releasePending($customer, $transaction, (int) $transaction->amount);
|
||||
$customer->save();
|
||||
|
||||
Log::create([
|
||||
@@ -288,6 +287,57 @@ class AdminTransactionController extends Controller
|
||||
]);
|
||||
}
|
||||
|
||||
public function destroy(string $uuid): JsonResponse
|
||||
{
|
||||
$transaction = DB::transaction(function () use ($uuid) {
|
||||
$transaction = Transaction::where('uuid', $uuid)
|
||||
->where('type', 'manual')
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if (! $transaction) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ((int) $transaction->status === TransactionStatus::PENDING->value) {
|
||||
$customer = Customer::where('id', $transaction->customer_id)->lockForUpdate()->first();
|
||||
if ($customer) {
|
||||
$this->releasePending($customer, $transaction, (int) $transaction->amount);
|
||||
$customer->save();
|
||||
}
|
||||
}
|
||||
|
||||
$transaction->delete();
|
||||
|
||||
Log::create([
|
||||
'agent' => 'admin',
|
||||
'client_ip' => request()->ip(),
|
||||
'description' => sprintf(
|
||||
'Admin xoá giao dịch nạp tiền thủ công %s: %s VNĐ (%s)',
|
||||
$transaction->public_code,
|
||||
number_format($transaction->amount),
|
||||
TransactionStatus::from((int) $transaction->status)->label(),
|
||||
),
|
||||
'customer_id' => $transaction->customer_id,
|
||||
]);
|
||||
|
||||
return $transaction;
|
||||
});
|
||||
|
||||
if (! $transaction) {
|
||||
return response()->json(['error' => true, 'message' => 'Giao dịch không tồn tại'], 404);
|
||||
}
|
||||
|
||||
return response()->json(['error' => false, 'message' => 'Đã xoá giao dịch']);
|
||||
}
|
||||
|
||||
private function releasePending(Customer $customer, Transaction $transaction, int $amount): void
|
||||
{
|
||||
if ($transaction->proof_image) {
|
||||
$customer->total_pending = max(0, $customer->total_pending - $amount);
|
||||
}
|
||||
}
|
||||
|
||||
public function proofImage(Transaction $transaction, int $index = 0)
|
||||
{
|
||||
abort_unless($transaction->proof_image, 404);
|
||||
|
||||
@@ -91,7 +91,7 @@ class ClientController extends Controller
|
||||
return response()->json([
|
||||
'error' => false,
|
||||
'data' => [
|
||||
'client' => new ClientResource(auth('client')->user()->loadCount(['vps', 'hosting', 'domain'])),
|
||||
'client' => new ClientResource(auth('client')->user()),
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -53,7 +53,7 @@ trait HandlesClientAuthentication
|
||||
return response()->json([
|
||||
'error' => false,
|
||||
'data' => [
|
||||
'client' => new ClientResource($client->loadCount(['vps', 'hosting', 'domain'])),
|
||||
'client' => new ClientResource($client),
|
||||
'token' => $result['token'],
|
||||
'refresh_token' => $result['refresh_token'],
|
||||
'expires_in' => config('jwt.ttl', 60) * 60, // seconds
|
||||
@@ -136,7 +136,7 @@ trait HandlesClientAuthentication
|
||||
return response()->json([
|
||||
'error' => false,
|
||||
'data' => [
|
||||
'client' => new ClientResource($client->loadCount(['vps', 'hosting', 'domain'])),
|
||||
'client' => new ClientResource($client),
|
||||
'token' => $result['token'],
|
||||
'refresh_token' => $result['refresh_token'],
|
||||
'expires_in' => config('jwt.ttl', 60) * 60,
|
||||
@@ -252,7 +252,7 @@ trait HandlesClientAuthentication
|
||||
'token' => $result['token'],
|
||||
'refresh_token' => $result['refresh_token'],
|
||||
'expires_in' => config('jwt.ttl', 60) * 60,
|
||||
'client' => new ClientResource($result['client']->loadCount(['vps', 'hosting', 'domain'])),
|
||||
'client' => new ClientResource($result['client']),
|
||||
],
|
||||
]);
|
||||
} catch (\Illuminate\Validation\ValidationException $e) {
|
||||
|
||||
@@ -30,7 +30,7 @@ trait ManagesClientProfile
|
||||
'error' => false,
|
||||
'message' => 'Cập nhật thông tin thành công',
|
||||
'data' => [
|
||||
'client' => new ClientResource($user->loadCount(['vps', 'hosting', 'domain'])),
|
||||
'client' => new ClientResource($user),
|
||||
],
|
||||
]);
|
||||
}
|
||||
@@ -64,7 +64,7 @@ trait ManagesClientProfile
|
||||
'error' => false,
|
||||
'message' => 'Cập nhật chứng minh thư thành công',
|
||||
'data' => [
|
||||
'client' => new ClientResource($user->loadCount(['vps', 'hosting', 'domain'])),
|
||||
'client' => new ClientResource($user),
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -36,6 +36,22 @@ class ServiceController extends Controller
|
||||
$this->activityLogger = $activityLogger;
|
||||
}
|
||||
|
||||
public function index(Request $request): JsonResponse
|
||||
{
|
||||
$customer = $request->user();
|
||||
|
||||
$services = $this->serviceClientService->getActiveServices($customer->id, null, null);
|
||||
$this->serviceClientService->attachDnsRecordCounts($services, $customer->id);
|
||||
|
||||
return (new VpsServiceCollection($services))
|
||||
->additional([
|
||||
'error' => false,
|
||||
'message' => 'Lấy dữ liệu thành công',
|
||||
'page_type' => 'services',
|
||||
])
|
||||
->response();
|
||||
}
|
||||
|
||||
public function indexVps(Request $request): JsonResponse
|
||||
{
|
||||
$perPage = min((int) $request->get('per_page', 15), 100);
|
||||
@@ -123,6 +139,7 @@ class ServiceController extends Controller
|
||||
$customerId = (int) $request->user()->id;
|
||||
|
||||
$services = $this->serviceClientService->getActiveServices($customerId, null, 5);
|
||||
$this->serviceClientService->attachDnsRecordCounts($services, $customerId);
|
||||
$invoices = $orderQueryService->getCustomerInvoices($customerId)->take(5);
|
||||
|
||||
return response()->json([
|
||||
@@ -131,6 +148,7 @@ class ServiceController extends Controller
|
||||
'data' => [
|
||||
'services' => (new VpsServiceCollection($services))->collection,
|
||||
'invoices' => InvoiceSummaryResource::collection($invoices),
|
||||
'counts' => $this->serviceClientService->countByType($customerId),
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -337,12 +337,15 @@ class OrderControllerRefactor extends Controller
|
||||
{
|
||||
$result = $this->orderQueryService->renewService(
|
||||
$id,
|
||||
(int) $request->user()->id,
|
||||
$request->user(),
|
||||
(int) $request->validated()['months'],
|
||||
);
|
||||
|
||||
if (!$result['ok']) {
|
||||
return response()->json(['success' => false, 'message' => $result['message']], $result['code']);
|
||||
return response()->json(
|
||||
['success' => false, 'message' => $result['message'], 'data' => $result['data'] ?? null],
|
||||
$result['code'],
|
||||
);
|
||||
}
|
||||
|
||||
return response()->json(['success' => true, 'message' => $result['message'], 'data' => $result['data']]);
|
||||
|
||||
@@ -5,6 +5,7 @@ namespace App\Http\Controllers\Api\Service;
|
||||
use App\Enums\Product\ProductTypeEnums;
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Resources\Api\Service\ProductCategoryResource;
|
||||
use App\Http\Resources\Api\Service\ServiceResource;
|
||||
use App\Models\Product;
|
||||
use App\Models\ProductCategories;
|
||||
use Illuminate\Http\Request;
|
||||
@@ -161,11 +162,12 @@ class ProductCategoryController extends Controller
|
||||
->with([
|
||||
'osVersions.osGroup',
|
||||
'category',
|
||||
'servicePlan',
|
||||
'pricings' => fn($q) => $q->where('is_active', 1)
|
||||
])
|
||||
->get();
|
||||
|
||||
$productResources = $products->map(fn($product) => $this->formatProduct($product));
|
||||
$productResources = ServiceResource::collection($products)->resolve();
|
||||
|
||||
$categoryArray = $category->toArray();
|
||||
$categoryArray['products'] = $productResources;
|
||||
@@ -265,11 +267,12 @@ class ProductCategoryController extends Controller
|
||||
->with([
|
||||
'osVersions.osGroup',
|
||||
'category',
|
||||
'servicePlan',
|
||||
'pricings' => fn($q) => $q->where('is_active', 1)
|
||||
])
|
||||
->get();
|
||||
|
||||
$productResources = $products->map(fn($product) => $this->formatProduct($product));
|
||||
$productResources = ServiceResource::collection($products)->resolve();
|
||||
|
||||
$childArray = $child->toArray();
|
||||
$childArray['parent'] = $child->parent ? $child->parent->toArray() : null;
|
||||
@@ -281,81 +284,4 @@ class ProductCategoryController extends Controller
|
||||
'data' => $childArray,
|
||||
]);
|
||||
}
|
||||
|
||||
private function formatProduct($product): array
|
||||
{
|
||||
$billingCycleLabels = [
|
||||
'monthly' => 'Hàng tháng',
|
||||
'quarterly' => 'Hàng quý',
|
||||
'semi_annually' => 'Nửa năm',
|
||||
'annually' => 'Hàng năm',
|
||||
'biennially' => '2 năm',
|
||||
'triennially' => '3 năm',
|
||||
'onetime' => 'Một lần',
|
||||
];
|
||||
|
||||
$periodMonths = [
|
||||
'monthly' => 1,
|
||||
'quarterly' => 3,
|
||||
'semi_annually' => 6,
|
||||
'annually' => 12,
|
||||
'biennially' => 24,
|
||||
'triennially' => 36,
|
||||
'onetime' => 0,
|
||||
];
|
||||
|
||||
$periodUnits = [
|
||||
'monthly' => 'month',
|
||||
'quarterly' => 'quarter',
|
||||
'semi_annually' => 'semi_year',
|
||||
'annually' => 'year',
|
||||
'biennially' => 'biennially',
|
||||
'triennially' => 'triennially',
|
||||
'onetime' => 'none',
|
||||
];
|
||||
|
||||
return [
|
||||
'uuid' => $product->uuid,
|
||||
'name' => $product->name,
|
||||
'slug' => $product->slug,
|
||||
'short_description' => $product->short_description,
|
||||
'description' => $product->description,
|
||||
'thumbnail' => $product->thumbnail ? asset($product->thumbnail) : null,
|
||||
'product_type' => $product->product_type,
|
||||
'specs' => [
|
||||
'cpu' => (int) $product->cpu,
|
||||
'ram' => (int) $product->ram,
|
||||
'disk' => (int) $product->disk,
|
||||
'bandwidth' => (int) $product->bandwidth,
|
||||
'gpu' => $product->gpu,
|
||||
],
|
||||
'stock' => $product->stock,
|
||||
'price' => (int) $product->price,
|
||||
'price_sale' => $product->price_sale ? (int) $product->price_sale : null,
|
||||
'group' => $product->category->name ?? null,
|
||||
'os' => $product->osVersions->groupBy('os_group_id')->map(function ($versions) {
|
||||
$group = $versions->first()->osGroup;
|
||||
return [
|
||||
'name' => $group?->name,
|
||||
'thumbnail' => $group?->thumbnail,
|
||||
'versions' => $versions->map(fn($os) => [
|
||||
'id' => $os->id,
|
||||
'version' => $os->version,
|
||||
'name' => $os->name,
|
||||
])->values(),
|
||||
];
|
||||
})->values(),
|
||||
'pricing' => $product->pricings
|
||||
->sortBy(fn($p) => $periodMonths[$p->billing_cycle] ?? 999)
|
||||
->values()
|
||||
->map(fn($p) => [
|
||||
'id' => $p->id,
|
||||
'name' => $billingCycleLabels[$p->billing_cycle] ?? $p->billing_cycle,
|
||||
'price' => (int) $p->price,
|
||||
'price_sale' => $p->price_sale ? (int) $p->price_sale : null,
|
||||
'period' => $periodMonths[$p->billing_cycle] ?? 1,
|
||||
'period_unit' => $periodUnits[$p->billing_cycle] ?? 'month',
|
||||
]),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -156,7 +156,8 @@ class ServiceController extends Controller
|
||||
'osVersions.osGroup',
|
||||
'category',
|
||||
'pricings' => fn($q) => $q->where('is_active', 1),
|
||||
'addons'
|
||||
'addons',
|
||||
'servicePlan',
|
||||
]);
|
||||
|
||||
return response()->json([
|
||||
|
||||
@@ -12,6 +12,7 @@ use App\Models\Log;
|
||||
use App\Models\Setting;
|
||||
use App\Models\Transaction;
|
||||
use App\Services\ActivityLogger;
|
||||
use App\Support\ManualDepositDraft;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
@@ -77,28 +78,17 @@ class ManualDepositController extends Controller
|
||||
], 422);
|
||||
}
|
||||
|
||||
// Huỷ transaction prepare cũ (chưa có proof) nếu còn tồn tại
|
||||
$old = Transaction::where('customer_id', $user->id)
|
||||
->where('type', 'manual')
|
||||
->where('status', TransactionStatus::PENDING->value)
|
||||
->whereNull('proof_image')
|
||||
->latest()
|
||||
->first();
|
||||
|
||||
if ($old) {
|
||||
DB::transaction(function () use ($old, $user) {
|
||||
$user->total_pending = max(0, $user->total_pending - $old->amount);
|
||||
$user->save();
|
||||
$old->forceDelete();
|
||||
});
|
||||
}
|
||||
ManualDepositDraft::query()
|
||||
->where('customer_id', $user->id)
|
||||
->get()
|
||||
->each(fn (Transaction $draft) => ManualDepositDraft::discard($draft));
|
||||
|
||||
$uuid = Str::uuid()->toString();
|
||||
$publicCode = Transaction::newPublicCode('MAN');
|
||||
|
||||
DB::beginTransaction();
|
||||
try {
|
||||
Transaction::create([
|
||||
$draft = Transaction::create([
|
||||
'uuid' => $uuid,
|
||||
'public_code' => $publicCode,
|
||||
'trans' => 'MAN' . time(),
|
||||
@@ -108,9 +98,6 @@ class ManualDepositController extends Controller
|
||||
'status' => TransactionStatus::PENDING->value,
|
||||
]);
|
||||
|
||||
$user->total_pending += $request->amount;
|
||||
$user->save();
|
||||
|
||||
DB::commit();
|
||||
} catch (\Exception) {
|
||||
DB::rollBack();
|
||||
@@ -126,13 +113,43 @@ class ManualDepositController extends Controller
|
||||
|
||||
return response()->json([
|
||||
'error' => false,
|
||||
'data' => [
|
||||
'uuid' => $uuid,
|
||||
'public_code' => $publicCode,
|
||||
],
|
||||
'data' => $this->draftPayload($draft),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /v1/transaction/manual-deposit/{uuid}
|
||||
*/
|
||||
public function show(Request $request, string $uuid): JsonResponse
|
||||
{
|
||||
$draft = ManualDepositDraft::query()
|
||||
->where('uuid', $uuid)
|
||||
->where('customer_id', $request->user()->id)
|
||||
->first();
|
||||
|
||||
if (! $draft) {
|
||||
return response()->json(['error' => true, 'message' => 'Mã thanh toán không tồn tại'], 404);
|
||||
}
|
||||
|
||||
if (ManualDepositDraft::isExpired($draft)) {
|
||||
ManualDepositDraft::discard($draft);
|
||||
|
||||
return response()->json(['error' => true, 'message' => 'Mã thanh toán đã hết hạn, vui lòng tạo mã mới'], 410);
|
||||
}
|
||||
|
||||
return response()->json(['error' => false, 'data' => $this->draftPayload($draft)]);
|
||||
}
|
||||
|
||||
private function draftPayload(Transaction $draft): array
|
||||
{
|
||||
return [
|
||||
'uuid' => $draft->uuid,
|
||||
'public_code' => $draft->public_code,
|
||||
'amount' => (int) $draft->amount,
|
||||
'expires_at' => ManualDepositDraft::expiresAt($draft)->toISOString(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* DELETE /v1/transaction/manual-deposit/{uuid}/cancel
|
||||
* Huỷ transaction đang prepare (chưa có proof, chưa submit).
|
||||
@@ -142,21 +159,15 @@ class ManualDepositController extends Controller
|
||||
{
|
||||
$user = $request->user();
|
||||
|
||||
$transaction = Transaction::where('uuid', $uuid)
|
||||
$transaction = ManualDepositDraft::query()
|
||||
->where('uuid', $uuid)
|
||||
->where('customer_id', $user->id)
|
||||
->where('type', 'manual')
|
||||
->where('status', TransactionStatus::PENDING->value)
|
||||
->whereNull('proof_image')
|
||||
->firstOrFail();
|
||||
|
||||
$amount = $transaction->amount;
|
||||
$publicCode = $transaction->public_code;
|
||||
|
||||
DB::transaction(function () use ($transaction, $user) {
|
||||
$user->total_pending = max(0, $user->total_pending - $transaction->amount);
|
||||
$user->save();
|
||||
$transaction->forceDelete();
|
||||
});
|
||||
ManualDepositDraft::discard($transaction);
|
||||
|
||||
$this->activityLogger->log(
|
||||
event: 'deposit_cancel',
|
||||
@@ -194,22 +205,30 @@ class ManualDepositController extends Controller
|
||||
], 422);
|
||||
}
|
||||
|
||||
$transaction = Transaction::where('uuid', $request->uuid)
|
||||
->where('customer_id', $user->id)
|
||||
->where('type', 'manual')
|
||||
->where('status', TransactionStatus::PENDING->value)
|
||||
->whereNull('proof_image')
|
||||
->first();
|
||||
$transaction = DB::transaction(function () use ($request, $user) {
|
||||
$draft = ManualDepositDraft::query()
|
||||
->where('uuid', $request->uuid)
|
||||
->where('customer_id', $user->id)
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if (! $draft || ManualDepositDraft::isExpired($draft)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$draft->update(['proof_image' => $request->proof_image]);
|
||||
$user->newQuery()->whereKey($user->getKey())->increment('total_pending', $draft->amount);
|
||||
|
||||
return $draft;
|
||||
});
|
||||
|
||||
if (!$transaction) {
|
||||
return response()->json([
|
||||
'error' => true,
|
||||
'message' => 'Giao dịch không hợp lệ hoặc đã được xử lý',
|
||||
'message' => 'Mã thanh toán đã hết hạn hoặc đã được xử lý, vui lòng tạo mã mới',
|
||||
], 422);
|
||||
}
|
||||
|
||||
$transaction->update(['proof_image' => $request->proof_image]);
|
||||
|
||||
try {
|
||||
(new Telegram())->SendManualDepositPendingApproval($user, $transaction);
|
||||
$this->sendManualDepositAdminEmail($user, $transaction, $request);
|
||||
|
||||
@@ -266,12 +266,11 @@ class TransactionController extends Controller
|
||||
'type' => 'deposit',
|
||||
'public_code' => $t->public_code,
|
||||
'trans' => $t->trans,
|
||||
'description' => 'Nạp tiền vào tài khoản',
|
||||
'description' => $t->typeLabel(),
|
||||
'amount' => (float) $t->amount,
|
||||
'status' => $t->status,
|
||||
'status_label' => TransactionStatus::from((int) $t->status)->label(),
|
||||
'reference_id' => null,
|
||||
'reference_num'=> null,
|
||||
'detail_key' => $t->uuid,
|
||||
'created_at' => $t->created_at?->toISOString(),
|
||||
]);
|
||||
|
||||
@@ -287,8 +286,7 @@ class TransactionController extends Controller
|
||||
'amount' => (float) $inv->total,
|
||||
'status' => $inv->status,
|
||||
'status_label' => \App\Enums\Invoice\InvoiceStatus::tryFrom((int) $inv->status)?->label() ?? '-',
|
||||
'reference_id' => $inv->order?->id,
|
||||
'reference_num'=> $inv->order?->order_num,
|
||||
'detail_key' => $inv->order?->order_num,
|
||||
'created_at' => $inv->created_at?->toISOString(),
|
||||
]);
|
||||
|
||||
@@ -303,6 +301,37 @@ class TransactionController extends Controller
|
||||
]);
|
||||
}
|
||||
|
||||
public function getClientTransactionDetail(Request $request, string $uuid): JsonResponse
|
||||
{
|
||||
$transaction = Transaction::query()
|
||||
->where('uuid', $uuid)
|
||||
->where('customer_id', $request->user()->id)
|
||||
->first();
|
||||
|
||||
if (! $transaction) {
|
||||
return response()->json(['error' => true, 'message' => 'Giao dịch không tồn tại'], 404);
|
||||
}
|
||||
|
||||
return response()->json([
|
||||
'error' => false,
|
||||
'data' => [
|
||||
'uuid' => $transaction->uuid,
|
||||
'public_code' => $transaction->public_code,
|
||||
'trans' => $transaction->trans,
|
||||
'type' => $transaction->type,
|
||||
'type_label' => $transaction->typeLabel(),
|
||||
'direction' => $transaction->direction,
|
||||
'amount' => (int) $transaction->amount,
|
||||
'received_amount' => $transaction->received_amount !== null ? (int) $transaction->received_amount : null,
|
||||
'status' => (int) $transaction->status,
|
||||
'status_label' => TransactionStatus::from((int) $transaction->status)->label(),
|
||||
'has_proof' => $transaction->proof_image !== null,
|
||||
'created_at' => $transaction->created_at?->toISOString(),
|
||||
'updated_at' => $transaction->updated_at?->toISOString(),
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
public function getByPublicCode(Request $request)
|
||||
{
|
||||
$code = $request->query('code');
|
||||
|
||||
Reference in New Issue
Block a user