update lisensi prosess
tests / ci (push) Has been cancelled

This commit is contained in:
Wian Drs
2026-08-25 13:43:55 +07:00
parent 1e80be180e
commit 60946ddf37
58 changed files with 2903 additions and 165 deletions
+42 -4
View File
@@ -4,8 +4,13 @@ namespace App\Actions\Fortify;
use App\Concerns\PasswordValidationRules;
use App\Concerns\ProfileValidationRules;
use App\Models\BillingOrder;
use App\Models\Tenant;
use App\Models\User;
use App\Services\TenantProvisioningService;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use Laravel\Fortify\Contracts\CreatesNewUsers;
class CreateNewUser implements CreatesNewUsers
@@ -17,17 +22,50 @@ class CreateNewUser implements CreatesNewUsers
*
* @param array<string, string> $input
*/
public function __construct(private readonly TenantProvisioningService $provisioning) {}
public function create(array $input): User
{
Validator::make($input, [
'tenant_name' => ['required', 'string', 'max:255'],
...$this->profileRules(),
'password' => $this->passwordRules(),
'deployment_type' => ['required', Rule::in(['managed_cloud', 'self_hosted'])],
'deployment_domain' => ['nullable', 'string', 'max:255'],
'plan_code' => ['required', Rule::in(array_keys(config('billing.plans')))],
])->validate();
return User::create([
'name' => $input['name'],
'email' => $input['email'],
'password' => $input['password'],
abort_unless(config('deployment.mode') === 'managed_cloud', 403);
$baseSlug = Str::slug($input['tenant_name']) ?: 'tenant';
$slug = $baseSlug;
$suffix = 2;
while (Tenant::where('slug', $slug)->exists()) {
$slug = $baseSlug.'-'.$suffix++;
}
$tenant = $this->provisioning->createWithOwner([
'name' => $input['tenant_name'],
'slug' => $slug,
'owner_name' => $input['name'],
'owner_email' => $input['email'],
'owner_password' => $input['password'],
'deployment_type' => $input['deployment_type'],
'deployment_domain' => $input['deployment_domain'] ?? null,
'plan_code' => $input['plan_code'],
'email_verified' => false,
'activate_license' => false,
]);
$plan = config("billing.plans.{$input['plan_code']}");
if ($plan['price'] > 0) {
$gateway = config('billing.default_gateway');
$order = BillingOrder::withoutGlobalScope('tenant')->create([
'tenant_id' => $tenant->id, 'plan_code' => $input['plan_code'], 'gateway' => $gateway,
'status' => 'pending', 'subtotal' => $plan['price'], 'tax' => 0, 'total' => $plan['price'], 'currency' => 'IDR', 'expires_at' => now()->addDay(),
]);
}
return User::withoutGlobalScope('tenant')->where('email', $input['email'])->firstOrFail();
}
}
+23
View File
@@ -0,0 +1,23 @@
<?php
namespace App\Billing\Contracts;
use App\Models\BillingOrder;
interface PaymentGateway
{
/** @return array<int,array{code:string,name:string,fee:int}> */
public function paymentMethods(BillingOrder $order): array;
/** @return array{external_id:?string,checkout_url:?string,metadata:array<string,mixed>} */
public function createCheckout(BillingOrder $order): array;
/** @param array<string,mixed> $payload */
public function verifyWebhook(array $payload, array $headers = []): bool;
/** @param array<string,mixed> $payload */
public function statusFromWebhook(array $payload): string;
/** @param array<string,mixed> $payload */
public function externalIdFromWebhook(array $payload): ?string;
}
@@ -0,0 +1,112 @@
<?php
namespace App\Billing\Gateways;
use App\Billing\Contracts\PaymentGateway;
use App\Models\BillingOrder;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Support\Facades\Http;
use RuntimeException;
class DuitkuPaymentGateway implements PaymentGateway
{
public function paymentMethods(BillingOrder $order): array
{
[$merchant, $key] = $this->credentials();
$amount = (int) $order->total;
$dateTime = now('Asia/Jakarta')->format('Y-m-d H:i:s');
$response = $this->http()->post(
$this->baseUrl().'/webapi/api/merchant/paymentmethod/getpaymentmethod',
[
'merchantcode' => $merchant,
'amount' => $amount,
'datetime' => $dateTime,
'signature' => hash_hmac('sha256', $merchant.$amount.$dateTime, $key),
]
);
if (! $response->successful() || ! is_array($response->json('paymentFee'))) {
throw new RuntimeException('PAYMENT_METHODS_REJECTED: '.($response->json('responseMessage') ?: 'Daftar kanal pembayaran Duitku tidak tersedia.'));
}
return collect($response->json('paymentFee'))->map(fn (array $method): array => [
'code' => (string) $method['paymentMethod'],
'name' => (string) $method['paymentName'],
'fee' => (int) ($method['totalFee'] ?? 0),
])->values()->all();
}
public function createCheckout(BillingOrder $order): array
{
[$merchant, $key] = $this->credentials();
if (! $order->payment_method) {
throw new RuntimeException('PAYMENT_METHOD_REQUIRED: Pilih kanal pembayaran terlebih dahulu.');
}
$externalId = 'RNDM-'.$order->uuid;
$user = $order->tenant->users()->where('is_active', true)->oldest()->firstOrFail();
$amount = (int) $order->total;
$payload = [
'merchantCode' => $merchant, 'paymentAmount' => $amount, 'merchantOrderId' => $externalId,
'paymentMethod' => $order->payment_method,
'productDetails' => 'Lisensi bulanan RADIQ NDM '.config("billing.plans.{$order->plan_code}.name"),
'email' => $user->email, 'customerVaName' => $user->name,
'callbackUrl' => route('payments.webhook', ['gateway' => 'duitku']),
'returnUrl' => route('checkout.return', $order->uuid), 'expiryPeriod' => 1440,
'signature' => hash_hmac('sha256', $merchant.$externalId.$amount, $key),
];
$response = $this->http()->post($this->baseUrl().'/webapi/api/merchant/v2/inquiry', $payload);
if (! $response->successful() || ! $response->json('paymentUrl')) {
throw new RuntimeException('PAYMENT_GATEWAY_REJECTED: '.($response->json('Message') ?: $response->json('message') ?: 'Duitku tidak menghasilkan URL pembayaran.'));
}
return ['external_id' => $externalId, 'checkout_url' => $response->json('paymentUrl'), 'metadata' => ['reference' => $response->json('reference')]];
}
public function verifyWebhook(array $payload, array $headers = []): bool
{
$merchant = (string) ($payload['merchantCode'] ?? '');
$amount = (string) ($payload['amount'] ?? '');
$orderId = (string) ($payload['merchantOrderId'] ?? '');
$signature = (string) ($payload['signature'] ?? '');
$expected = hash_hmac('sha256', $merchant.$amount.$orderId, (string) config('billing.duitku.api_key'));
return $merchant !== '' && hash_equals((string) config('billing.duitku.merchant_code'), $merchant) && hash_equals($expected, $signature);
}
public function statusFromWebhook(array $payload): string
{
return ($payload['resultCode'] ?? null) === '00' ? 'paid' : 'failed';
}
public function externalIdFromWebhook(array $payload): ?string
{
return isset($payload['merchantOrderId']) ? (string) $payload['merchantOrderId'] : null;
}
/** @return array{string,string} */
private function credentials(): array
{
$merchant = (string) config('billing.duitku.merchant_code');
$key = (string) config('billing.duitku.api_key');
if ($merchant === '' || $key === '') {
throw new RuntimeException('PAYMENT_GATEWAY_NOT_CONFIGURED: Merchant Code atau API Key Duitku belum diisi.');
}
return [$merchant, $key];
}
private function baseUrl(): string
{
return config('billing.duitku.sandbox') ? 'https://sandbox.duitku.com' : 'https://passport.duitku.com';
}
private function http(): PendingRequest
{
$request = Http::asJson()->acceptJson()->timeout(20);
$caBundle = config('billing.duitku.ca_bundle');
return is_string($caBundle) && $caBundle !== ''
? $request->withOptions(['verify' => $caBundle])
: $request;
}
}
@@ -0,0 +1,34 @@
<?php
namespace App\Billing\Gateways;
use App\Billing\Contracts\PaymentGateway;
use App\Models\BillingOrder;
class ManualPaymentGateway implements PaymentGateway
{
public function paymentMethods(BillingOrder $order): array
{
return [];
}
public function createCheckout(BillingOrder $order): array
{
return ['external_id' => 'MANUAL-'.$order->uuid, 'checkout_url' => null, 'metadata' => ['instruction' => 'Hubungi RADIQ untuk instruksi pembayaran. Aktivasi dilakukan setelah pembayaran diverifikasi.']];
}
public function verifyWebhook(array $payload, array $headers = []): bool
{
return false;
}
public function statusFromWebhook(array $payload): string
{
return 'pending';
}
public function externalIdFromWebhook(array $payload): ?string
{
return null;
}
}
+20
View File
@@ -0,0 +1,20 @@
<?php
namespace App\Billing;
use App\Billing\Contracts\PaymentGateway;
use InvalidArgumentException;
class PaymentGatewayManager
{
public function driver(?string $name = null): PaymentGateway
{
$name ??= config('billing.default_gateway');
$class = config("billing.gateways.{$name}");
if (! $class || ! is_a($class, PaymentGateway::class, true)) {
throw new InvalidArgumentException("Payment gateway [{$name}] tidak tersedia.");
}
return app($class);
}
}
@@ -0,0 +1,30 @@
<?php
namespace App\Http\Controllers\Administration;
use App\Http\Controllers\Controller;
use App\Models\BillingOrder;
use App\Services\BillingService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;
class BillingOrderController extends Controller
{
public function index(Request $request): Response
{
abort_unless($request->user()->is_platform_admin, 403);
return Inertia::render('administration/billing/index', ['orders' => BillingOrder::withoutGlobalScope('tenant')->with('tenant:id,name')->latest()->paginate(30)]);
}
public function approve(Request $request, BillingOrder $order, BillingService $billing): RedirectResponse
{
abort_unless($request->user()->is_platform_admin, 403);
abort_unless($order->status === 'pending', 422, 'Order sudah diproses.');
$billing->activate($order, $request->user()->id);
return back()->with('success', 'Pembayaran dikonfirmasi dan lisensi diperpanjang satu bulan.');
}
}
@@ -7,6 +7,7 @@ use App\Http\Requests\Administration\StoreTenantRequest;
use App\Http\Requests\Administration\UpdateTenantRequest;
use App\Models\Tenant;
use App\Models\User;
use App\Services\LicenseEntitlementService;
use App\Services\TenantProvisioningService;
use Illuminate\Http\RedirectResponse;
use Inertia\Inertia;
@@ -21,6 +22,7 @@ class TenantController extends Controller
$tenants = Tenant::query()
->withCount('users')
->with('installations:id,tenant_id,deployment_type,domain,status,last_seen_at')
->with(['licenses' => fn ($query) => $query->latest('created_at')])
->orderBy('name')
->paginate(15)
->withQueryString();
@@ -32,12 +34,12 @@ class TenantController extends Controller
{
$this->authorize('create', Tenant::class);
return Inertia::render('administration/tenants/create');
return Inertia::render('administration/tenants/create', ['plans' => config('billing.plans')]);
}
public function store(StoreTenantRequest $request, TenantProvisioningService $service): RedirectResponse
{
$tenant = $service->createWithOwner($request->validated());
$tenant = $service->createWithOwner($request->validated() + ['activate_license' => true, 'issued_by' => $request->user()->id]);
return to_route('administration.tenants.edit', $tenant)
->with('success', 'Tenant dan Tenant Owner berhasil dibuat.');
@@ -57,6 +59,8 @@ class TenantController extends Controller
'tenant' => $tenant,
'users' => $users,
'installation' => $tenant->installations()->first(['id', 'deployment_type', 'domain', 'status', 'last_seen_at']),
'license' => $tenant->licenses()->latest('created_at')->first(),
'plans' => config('billing.plans'),
]);
}
@@ -71,6 +75,12 @@ class TenantController extends Controller
'domain' => $data['deployment_domain'] ?? null,
]);
}
$currentLicense = $tenant->licenses()->latest('created_at')->first();
if (! empty($data['plan_code']) && $currentLicense?->plan !== $data['plan_code']) {
$installation = $tenant->installations()->firstOrFail();
$tenant->licenses()->whereIn('status', ['active', 'grace'])->update(['status' => 'revoked']);
app(LicenseEntitlementService::class)->provisionInitial($tenant, $installation, $data['plan_code'], true, $request->user()->id);
}
return back()->with('success', 'Tenant berhasil diperbarui.');
}
@@ -9,6 +9,7 @@ use App\Http\Requests\Administration\StoreUserRequest;
use App\Http\Requests\Administration\UpdateUserRequest;
use App\Models\Tenant;
use App\Models\User;
use App\Services\LicenseEntitlementService;
use Illuminate\Http\RedirectResponse;
use Inertia\Inertia;
use Inertia\Response;
@@ -33,11 +34,12 @@ class UserController extends Controller
{
abort_unless(request()->user()->can('user.create'), 403);
return Inertia::render('administration/users/create', ['tenant' => $tenant]);
return Inertia::render('administration/users/create', ['tenant' => $tenant, 'canManageRoles' => request()->user()->is_platform_admin]);
}
public function store(StoreUserRequest $request, Tenant $tenant): RedirectResponse
{
app(LicenseEntitlementService::class)->assertCanAddUser($tenant->id);
$data = $request->validated();
$user = User::create([
'tenant_id' => $tenant->id,
@@ -47,7 +49,8 @@ class UserController extends Controller
'is_active' => $data['is_active'] ?? true,
]);
$user->forceFill(['email_verified_at' => now()])->save();
$user->assignRole(SystemRole::TenantUser->value);
$role = $request->user()->is_platform_admin ? ($data['role'] ?? SystemRole::TenantUser->value) : SystemRole::TenantUser->value;
$user->assignRole($role);
return to_route('administration.users.index', $tenant)->with('success', 'User berhasil dibuat.');
}
@@ -60,6 +63,7 @@ class UserController extends Controller
return Inertia::render('administration/users/edit', [
'tenant' => $tenant,
'managedUser' => $user->load('roles:id,name'),
'canManageRoles' => request()->user()->is_platform_admin,
]);
}
@@ -68,6 +72,9 @@ class UserController extends Controller
$this->ensureManageableUser($tenant, $user);
$data = $request->validated();
$user->update(['name' => $data['name'], 'email' => $data['email']]);
if ($request->user()->is_platform_admin && isset($data['role'])) {
$user->syncRoles([$data['role']]);
}
return back()->with('success', 'User berhasil diperbarui.');
}
@@ -0,0 +1,56 @@
<?php
namespace App\Http\Controllers;
use App\Enums\SystemRole;
use App\Models\BillingOrder;
use App\Models\DeploymentInstallation;
use App\Services\LicenseEntitlementService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Inertia\Inertia;
use Inertia\Response;
class BillingController extends Controller
{
public function index(Request $request, LicenseEntitlementService $entitlements): Response
{
abort_unless($request->user()->hasRole(SystemRole::TenantAdmin->value), 403);
$installation = DeploymentInstallation::query()->firstOrFail();
$license = $entitlements->current($request->user()->tenant_id);
return Inertia::render('billing/index', [
'installation' => ['deployment_type' => $installation->deployment_type->value, 'status' => $installation->status],
'license' => $license ? ['plan' => $license->plan, 'status' => $license->status->value, 'max_devices' => $license->max_devices, 'max_users' => $license->max_users, 'expires_at' => $license->expires_at?->toIso8601String(), 'grace_until' => $license->grace_until?->toIso8601String()] : null,
'plans' => collect(config('billing.plans'))->filter(fn ($plan) => $plan['deployment'] === $installation->deployment_type->value)->map(fn ($plan, $code) => ['code' => $code, ...$plan])->values(),
'orders' => BillingOrder::query()->latest()->limit(20)->get(['uuid', 'plan_code', 'gateway', 'status', 'total', 'currency', 'checkout_url', 'created_at', 'expires_at']),
'pendingOrder' => BillingOrder::query()->where('status', 'pending')->where('expires_at', '>', now())->latest()->first(['uuid', 'plan_code', 'total', 'currency', 'expires_at']),
'gateways' => [config('billing.default_gateway')],
]);
}
public function store(Request $request): RedirectResponse
{
abort_unless($request->user()->hasRole(SystemRole::TenantAdmin->value), 403);
$data = $request->validate([
'plan_code' => ['required', Rule::in(array_keys(config('billing.plans')))],
'gateway' => ['required', Rule::in(array_keys(config('billing.gateways')))],
]);
$plan = config("billing.plans.{$data['plan_code']}");
$installation = DeploymentInstallation::query()->firstOrFail();
abort_unless($plan['deployment'] === $installation->deployment_type->value, 422, 'Paket tidak sesuai dengan deployment tenant.');
abort_if($plan['price'] === 0, 422, 'Paket gratis tidak membutuhkan checkout.');
BillingOrder::query()->where('status', 'pending')->where('expires_at', '<=', now())->update(['status' => 'expired']);
$pending = BillingOrder::query()->where('status', 'pending')->where('expires_at', '>', now())->latest()->first();
if ($pending) {
return to_route('checkout.show', $pending->uuid)->with('info', 'Selesaikan pembayaran yang masih pending sebelum membuat perpanjangan baru.');
}
$order = BillingOrder::create([
'tenant_id' => $request->user()->tenant_id, 'plan_code' => $data['plan_code'], 'gateway' => $data['gateway'],
'status' => 'pending', 'subtotal' => $plan['price'], 'tax' => 0, 'total' => $plan['price'], 'currency' => 'IDR', 'expires_at' => now()->addDay(),
]);
return to_route('checkout.show', $order->uuid);
}
}
@@ -0,0 +1,70 @@
<?php
namespace App\Http\Controllers;
use App\Billing\PaymentGatewayManager;
use App\Models\BillingOrder;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;
use Throwable;
class CheckoutController extends Controller
{
public function show(string $order): Response
{
return $this->render($order);
}
public function returned(string $order): Response
{
return $this->render($order);
}
public function retry(Request $request, string $order, PaymentGatewayManager $gateways): RedirectResponse
{
$billingOrder = BillingOrder::withoutGlobalScope('tenant')->where('uuid', $order)->where('status', 'pending')->firstOrFail();
try {
$driver = $gateways->driver($billingOrder->gateway);
$methods = collect($driver->paymentMethods($billingOrder));
if ($methods->isNotEmpty()) {
$data = $request->validate(['payment_method' => ['required', 'string']]);
abort_unless($methods->contains('code', $data['payment_method']), 422, 'Kanal pembayaran tidak tersedia.');
$billingOrder->update(['payment_method' => $data['payment_method']]);
}
$billingOrder->update($driver->createCheckout($billingOrder->fresh()));
$billingOrder->update(['metadata' => collect($billingOrder->metadata ?? [])->except('gateway_error')->all()]);
} catch (Throwable $exception) {
report($exception);
return back()->withErrors(['payment' => str($exception->getMessage())->after(':')->trim()->toString() ?: 'Gateway pembayaran belum siap.']);
}
return redirect()->away($billingOrder->checkout_url);
}
private function render(string $uuid): Response
{
$order = BillingOrder::withoutGlobalScope('tenant')->where('uuid', $uuid)->firstOrFail();
$plan = config("billing.plans.{$order->plan_code}");
$methods = [];
$gatewayError = null;
if ($order->status === 'pending' && ! $order->checkout_url) {
try {
$methods = app(PaymentGatewayManager::class)->driver($order->gateway)->paymentMethods($order);
} catch (Throwable $exception) {
report($exception);
$gatewayError = str($exception->getMessage())->after(':')->trim()->toString();
}
}
return Inertia::render('checkout/show', ['order' => [
'uuid' => $order->uuid, 'plan' => $plan['name'], 'status' => $order->status,
'total' => $order->total, 'currency' => $order->currency, 'checkout_url' => $order->checkout_url,
'expires_at' => $order->expires_at?->toIso8601String(), 'gateway' => $order->gateway,
'payment_method' => $order->payment_method, 'payment_methods' => $methods,
'gateway_error' => $gatewayError,
]]);
}
}
@@ -39,6 +39,8 @@ class DashboardController extends Controller
return Inertia::render('dashboard', [
'role' => $role,
'tenant' => $user->tenant?->only(['id', 'name', 'slug', 'is_active']),
'installation' => DeploymentInstallation::query()->first()?->only(['deployment_type', 'domain', 'status', 'activated_at']),
'license' => License::query()->latest('created_at')->first()?->only(['plan', 'status', 'max_devices', 'max_users', 'expires_at', 'grace_until']),
'stats' => [
'users' => User::count(),
'activeUsers' => User::where('is_active', true)->count(),
@@ -11,6 +11,7 @@ use App\Models\DeviceModel;
use App\Models\DeviceType;
use App\Models\DeviceVendor;
use App\Models\TenantDevicePolicy;
use App\Services\LicenseEntitlementService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
@@ -54,6 +55,7 @@ class DeviceController extends Controller
public function store(StoreDeviceRequest $request): RedirectResponse
{
$this->authorizeCreate();
app(LicenseEntitlementService::class)->assertCanAddDevice($request->user()->tenant_id);
$this->validateModelCombination($request);
$data = $request->validated();
$username = $data['initial_username'];
@@ -0,0 +1,30 @@
<?php
namespace App\Http\Controllers;
use App\Billing\PaymentGatewayManager;
use App\Models\BillingOrder;
use App\Services\BillingService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class PaymentWebhookController extends Controller
{
public function __invoke(string $gateway, Request $request, PaymentGatewayManager $gateways, BillingService $billing): JsonResponse
{
$driver = $gateways->driver($gateway);
$payload = $request->all();
abort_unless($driver->verifyWebhook($payload, $request->headers->all()), 401, 'Invalid payment signature.');
$externalId = $driver->externalIdFromWebhook($payload);
$order = BillingOrder::withoutGlobalScope('tenant')->where('gateway', $gateway)->where('external_id', $externalId)->firstOrFail();
abort_unless((int) ($payload['amount'] ?? 0) === (int) $order->total, 422, 'Payment amount mismatch.');
$status = $driver->statusFromWebhook($payload);
if ($status === 'paid') {
$billing->activate($order);
} elseif ($order->status === 'pending') {
$order->update(['status' => $status]);
}
return response()->json(['success' => true]);
}
}
@@ -0,0 +1,33 @@
<?php
namespace App\Http\Middleware;
use App\Enums\LicenseStatus;
use App\Models\License;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;
class EnsureTenantLicense
{
public function handle(Request $request, Closure $next): Response
{
$user = $request->user();
if (! $user || $user->is_platform_admin || ! $user->tenant_id) {
return $next($request);
}
$license = License::withoutGlobalScope('tenant')->where('tenant_id', $user->tenant_id)->latest('created_at')->first();
$allowed = $license && in_array($license->status->value, [LicenseStatus::Active->value, LicenseStatus::Grace->value], true)
&& ($license->grace_until ?? $license->expires_at)->isFuture();
if (! $allowed) {
Auth::guard('web')->logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
return to_route('login')->with('status', 'Lisensi tenant telah berakhir. Hubungi Master Admin RADIQ untuk perpanjangan.');
}
return $next($request);
}
}
@@ -32,6 +32,7 @@ class StoreTenantRequest extends FormRequest
'owner_password' => ['required', 'confirmed', Password::min(12)->mixedCase()->numbers()->symbols()],
'deployment_type' => ['sometimes', 'in:managed_cloud,self_hosted'],
'deployment_domain' => ['nullable', 'string', 'max:255'],
'plan_code' => ['sometimes', 'string', 'in:cloud_free,cloud_micro,cloud_isp,local_micro,local_isp'],
];
}
}
@@ -28,6 +28,7 @@ class StoreUserRequest extends FormRequest
'email' => ['required', 'email', 'max:255', 'unique:users,email'],
'password' => ['required', 'confirmed', Password::min(12)->mixedCase()->numbers()->symbols()],
'is_active' => ['sometimes', 'boolean'],
'role' => ['sometimes', 'in:TENANT ADMIN,TENANT USER'],
];
}
}
@@ -28,6 +28,7 @@ class UpdateTenantRequest extends FormRequest
'is_active' => ['required', 'boolean'],
'deployment_type' => ['sometimes', 'in:managed_cloud,self_hosted'],
'deployment_domain' => ['nullable', 'string', 'max:255'],
'plan_code' => ['nullable', 'string', 'in:cloud_free,cloud_micro,cloud_isp,local_micro,local_isp'],
];
}
}
@@ -26,6 +26,7 @@ class UpdateUserRequest extends FormRequest
return [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'email', 'max:255', Rule::unique('users', 'email')->ignore($this->route('user')->id)],
'role' => ['sometimes', 'in:TENANT ADMIN,TENANT USER'],
];
}
}
+25
View File
@@ -0,0 +1,25 @@
<?php
namespace App\Http\Responses;
use App\Models\BillingOrder;
use Illuminate\Support\Facades\Auth;
use Laravel\Fortify\Contracts\RegisterResponse as RegisterResponseContract;
class RegisterResponse implements RegisterResponseContract
{
public function toResponse($request)
{
$user = $request->user();
$order = $user?->tenant_id ? BillingOrder::withoutGlobalScope('tenant')->where('tenant_id', $user->tenant_id)->latest()->first() : null;
if ($order) {
Auth::guard('web')->logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
return redirect()->route('checkout.show', $order->uuid);
}
return redirect()->intended(config('fortify.home'));
}
}
+6
View File
@@ -15,6 +15,7 @@ use App\Network\Drivers\Hisfocus\HisfocusOltDriver;
use App\Network\Drivers\Hsgq\HsgqOltDriver;
use App\Network\Drivers\Mikrotik\MikrotikDriver;
use App\Network\Drivers\Zte\ZteC3xxDriver;
use App\Services\LicenseEntitlementService;
use App\Support\TenantContext;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
@@ -39,6 +40,11 @@ class SyncDeviceBaseCredential implements ShouldQueue
$context->set($this->tenantId);
setPermissionsTeamId($this->tenantId);
try {
if (! app(LicenseEntitlementService::class)->allowsUse($this->tenantId)) {
Device::withoutGlobalScope('tenant')->whereKey($this->deviceId)->update(['base_sync_status' => 'pending', 'base_sync_error_code' => 'LICENSE_INACTIVE', 'base_sync_message' => 'Menunggu lisensi tenant aktif.']);
return;
}
$device = Device::with(['vendor', 'model', 'credentials'])->find($this->deviceId);
$setting = TenantDeviceSetting::where('tenant_id', $this->tenantId)->first();
if (! $device || ! $setting) {
+6
View File
@@ -15,6 +15,7 @@ use App\Network\Drivers\Hisfocus\HisfocusOltDriver;
use App\Network\Drivers\Hsgq\HsgqOltDriver;
use App\Network\Drivers\Mikrotik\MikrotikDriver;
use App\Network\Drivers\Zte\ZteC3xxDriver;
use App\Services\LicenseEntitlementService;
use App\Support\TenantContext;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
@@ -33,6 +34,11 @@ class SyncDeviceUser implements ShouldQueue
$context->set($this->tenantId);
setPermissionsTeamId($this->tenantId);
try {
if (! app(LicenseEntitlementService::class)->allowsUse($this->tenantId)) {
DeviceUserAssignment::withoutGlobalScope('tenant')->whereKey($this->assignmentId)->update(['sync_status' => 'pending', 'error_code' => 'LICENSE_INACTIVE', 'message' => 'Menunggu lisensi tenant aktif.']);
return;
}
$assignment = DeviceUserAssignment::with(['device.vendor', 'device.credentials', 'accessUser'])->find($this->assignmentId);
if (! $assignment || $assignment->tenant_id !== $this->tenantId) {
return;
+30
View File
@@ -0,0 +1,30 @@
<?php
namespace App\Models;
use App\Models\Concerns\BelongsToTenant;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Str;
class BillingOrder extends Model
{
use BelongsToTenant;
protected $fillable = ['tenant_id', 'license_id', 'plan_code', 'gateway', 'payment_method', 'external_id', 'status', 'subtotal', 'tax', 'total', 'currency', 'checkout_url', 'metadata', 'expires_at', 'paid_at'];
protected static function booted(): void
{
static::creating(fn (self $order) => $order->uuid ??= (string) Str::uuid());
}
protected function casts(): array
{
return ['metadata' => 'array', 'expires_at' => 'immutable_datetime', 'paid_at' => 'immutable_datetime'];
}
public function license(): BelongsTo
{
return $this->belongsTo(License::class);
}
}
+12 -2
View File
@@ -4,7 +4,9 @@ namespace App\Providers;
use App\Actions\Fortify\CreateNewUser;
use App\Actions\Fortify\ResetUserPassword;
use App\Http\Responses\RegisterResponse;
use App\Models\User;
use App\Services\LicenseEntitlementService;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
@@ -13,6 +15,7 @@ use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Str;
use Illuminate\Validation\Rules\Password;
use Inertia\Inertia;
use Laravel\Fortify\Contracts\RegisterResponse as RegisterResponseContract;
use Laravel\Fortify\Features;
use Laravel\Fortify\Fortify;
@@ -23,7 +26,7 @@ class FortifyServiceProvider extends ServiceProvider
*/
public function register(): void
{
//
$this->app->singleton(RegisterResponseContract::class, RegisterResponse::class);
}
/**
@@ -44,7 +47,9 @@ class FortifyServiceProvider extends ServiceProvider
Fortify::authenticateUsing(function (Request $request): ?User {
$user = User::query()->withoutGlobalScope('tenant')->where('email', $request->string('email'))->first();
return $user && $user->is_active && Hash::check($request->string('password'), $user->password)
$licenseValid = ! $user || $user->is_platform_admin || app(LicenseEntitlementService::class)->allowsUse($user->tenant_id);
return $user && $user->is_active && $licenseValid && Hash::check($request->string('password'), $user->password)
? $user
: null;
});
@@ -60,9 +65,14 @@ class FortifyServiceProvider extends ServiceProvider
{
Fortify::loginView(fn (Request $request) => Inertia::render('auth/login', [
'canResetPassword' => Features::enabled(Features::resetPasswords()),
'canRegister' => Features::enabled(Features::registration()),
'status' => $request->session()->get('status'),
]));
Fortify::registerView(fn () => Inertia::render('auth/register', [
'passwordRules' => Password::defaults()->toPasswordRulesString(),
]));
Fortify::resetPasswordView(fn (Request $request) => Inertia::render('auth/reset-password', [
'email' => $request->email,
'token' => $request->route('token'),
+39
View File
@@ -0,0 +1,39 @@
<?php
namespace App\Services;
use App\Enums\LicenseStatus;
use App\Models\BillingOrder;
use App\Models\DeploymentInstallation;
use App\Models\License;
use Illuminate\Support\Facades\DB;
class BillingService
{
public function activate(BillingOrder $order, ?int $issuerId = null): License
{
return DB::transaction(function () use ($order, $issuerId): License {
$order = BillingOrder::withoutGlobalScope('tenant')->lockForUpdate()->findOrFail($order->id);
if ($order->status === 'paid' && $order->license) {
return $order->license;
}
$plan = config("billing.plans.{$order->plan_code}");
abort_unless($plan, 422, 'Paket lisensi tidak tersedia.');
$installation = DeploymentInstallation::withoutGlobalScope('tenant')->where('tenant_id', $order->tenant_id)->firstOrFail();
$current = License::withoutGlobalScope('tenant')->where('tenant_id', $order->tenant_id)
->whereIn('status', [LicenseStatus::Active->value, LicenseStatus::Grace->value])->latest('created_at')->first();
$startsAt = $current && $current->plan !== 'cloud_free' && $current->expires_at->isFuture() ? $current->expires_at : now();
$current?->update(['status' => LicenseStatus::Revoked]);
$license = License::withoutGlobalScope('tenant')->create([
'tenant_id' => $order->tenant_id, 'deployment_installation_id' => $installation->id,
'license_key_hash' => hash('sha256', random_bytes(32)), 'plan' => $order->plan_code,
'status' => LicenseStatus::Active, 'max_devices' => $plan['max_devices'], 'max_users' => $plan['max_users'],
'features' => ['device_access_management'], 'starts_at' => $startsAt, 'expires_at' => $startsAt->addMonth(),
'grace_until' => $startsAt->addMonth()->addDays(7), 'issued_by' => $issuerId,
]);
$order->update(['license_id' => $license->id, 'status' => 'paid', 'paid_at' => now()]);
return $license;
});
}
}
@@ -0,0 +1,77 @@
<?php
namespace App\Services;
use App\Enums\LicenseStatus;
use App\Models\DeploymentInstallation;
use App\Models\Device;
use App\Models\License;
use App\Models\Tenant;
use App\Models\User;
class LicenseEntitlementService
{
public function allowsUse(int $tenantId): bool
{
$license = $this->current($tenantId);
return $license !== null && ($license->grace_until ?? $license->expires_at)->isFuture();
}
public function provisionInitial(Tenant $tenant, DeploymentInstallation $installation, string $planCode, bool $activate = false, ?int $issuerId = null): License
{
$plan = config("billing.plans.{$planCode}");
abort_unless($plan && $plan['deployment'] === $installation->deployment_type->value, 422, 'Paket tidak sesuai deployment tenant.');
$isFree = $plan['price'] === 0;
$startsAt = now();
return License::withoutGlobalScope('tenant')->create([
'tenant_id' => $tenant->id, 'deployment_installation_id' => $installation->id,
'license_key_hash' => hash('sha256', random_bytes(32)), 'plan' => $planCode,
'status' => $activate || $isFree ? LicenseStatus::Active : LicenseStatus::Pending,
'max_devices' => $plan['max_devices'], 'max_users' => $plan['max_users'], 'features' => ['device_access_management'],
'starts_at' => $startsAt, 'expires_at' => $isFree ? $startsAt->copy()->addYears(10) : $startsAt->copy()->addMonth(),
'grace_until' => $isFree ? null : $startsAt->copy()->addMonth()->addDays(7),
'issued_by' => $issuerId,
]);
}
public function current(int $tenantId): ?License
{
$license = License::withoutGlobalScope('tenant')->where('tenant_id', $tenantId)
->whereIn('status', [LicenseStatus::Active->value, LicenseStatus::Grace->value])
->latest('created_at')->first();
if ($license) {
return $license;
}
if (License::withoutGlobalScope('tenant')->where('tenant_id', $tenantId)->exists()) {
return null;
}
$installation = DeploymentInstallation::withoutGlobalScope('tenant')->where('tenant_id', $tenantId)->first();
if (! $installation || $installation->deployment_type->value !== 'managed_cloud') {
return null;
}
$plan = config('billing.plans.cloud_free');
return License::withoutGlobalScope('tenant')->create([
'tenant_id' => $tenantId, 'deployment_installation_id' => $installation->id,
'license_key_hash' => hash('sha256', random_bytes(32)), 'plan' => 'cloud_free',
'status' => LicenseStatus::Active, 'max_devices' => $plan['max_devices'], 'max_users' => $plan['max_users'],
'features' => ['device_access_management'], 'starts_at' => now(), 'expires_at' => now()->addYears(10),
]);
}
public function assertCanAddDevice(int $tenantId): void
{
$license = $this->current($tenantId);
abort_unless($license, 402, 'Lisensi tenant belum aktif.');
abort_if($license->max_devices !== null && Device::withoutGlobalScope('tenant')->where('tenant_id', $tenantId)->count() >= $license->max_devices, 422, 'Batas perangkat paket tercapai. Upgrade paket melalui menu Lisensi & Tagihan.');
}
public function assertCanAddUser(int $tenantId): void
{
$license = $this->current($tenantId);
abort_unless($license, 402, 'Lisensi tenant belum aktif.');
abort_if($license->max_users !== null && User::withoutGlobalScope('tenant')->where('tenant_id', $tenantId)->count() >= $license->max_users, 422, 'Batas user aplikasi paket tercapai. Upgrade paket melalui menu Lisensi & Tagihan.');
}
}
+10 -2
View File
@@ -29,7 +29,7 @@ class TenantProvisioningService
TenantDevicePolicy::create(['tenant_id' => $tenant->id]);
app(TenantEnvelopeEncryption::class)->ensureKey($tenant->id);
$deploymentType = $data['deployment_type'] ?? 'managed_cloud';
DeploymentInstallation::create([
$installation = DeploymentInstallation::create([
'tenant_id' => $tenant->id,
'name' => $deploymentType === 'self_hosted' ? 'Server Tenant' : 'RADIQ Managed Cloud',
'deployment_type' => $deploymentType,
@@ -38,6 +38,14 @@ class TenantProvisioningService
'status' => $deploymentType === 'managed_cloud' ? 'active' : 'pending',
'activated_at' => $deploymentType === 'managed_cloud' ? now() : null,
]);
$defaultPlan = $deploymentType === 'managed_cloud' ? 'cloud_free' : 'local_micro';
app(LicenseEntitlementService::class)->provisionInitial(
$tenant,
$installation,
$data['plan_code'] ?? $defaultPlan,
(bool) ($data['activate_license'] ?? true),
$data['issued_by'] ?? null,
);
$this->context->set($tenant->id);
setPermissionsTeamId($tenant->id);
@@ -52,7 +60,7 @@ class TenantProvisioningService
'password' => $data['owner_password'],
'is_active' => true,
]);
$owner->forceFill(['email_verified_at' => now()])->save();
$owner->forceFill(['email_verified_at' => ($data['email_verified'] ?? true) ? now() : null])->save();
$owner->assignRole($roles[SystemRole::TenantAdmin->value]);
} finally {
$this->context->clear();