feat: add private business intake review and reserved objects
This commit is contained in:
@@ -0,0 +1,82 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\ExistingBusiness;
|
||||
use App\Models\ExistingBusinessObject;
|
||||
use App\Services\ExistingBusinessDrafts;
|
||||
use App\Services\ExistingBusinessIntake;
|
||||
use App\Services\ExistingBusinessObjects;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
|
||||
class ExistingBusinessController extends Controller
|
||||
{
|
||||
public function index(Request $request): Response|JsonResponse
|
||||
{
|
||||
$management = $request->is('management/*', 'api/v1/existing-business/review*');
|
||||
$query = ExistingBusiness::query();
|
||||
if ($management) {
|
||||
Gate::authorize('reviewQueue', ExistingBusiness::class);
|
||||
$query->where('owner_user_id', '<>', $request->user()->id)->whereIn('status', ['submitted', 'in_review', 'needs_information']);
|
||||
} else {
|
||||
$query->where('owner_user_id', $request->user()->id);
|
||||
}
|
||||
$props = ['records' => $query->orderByDesc('updated_at')->paginate(20)->through(fn ($row) => $this->record($row)),
|
||||
'management' => $management, 'modalities' => ExistingBusinessDrafts::MODALITIES];
|
||||
|
||||
return $request->expectsJson() ? response()->json($props) : Inertia::render('investment/businesses', $props);
|
||||
}
|
||||
|
||||
public function show(Request $request, string $id): Response|JsonResponse
|
||||
{
|
||||
$business = ExistingBusiness::findOrFail($id);
|
||||
Gate::authorize('view', $business);
|
||||
$props = ['record' => $this->record($business), 'canEdit' => $request->user()->can('update', $business),
|
||||
'owner' => $request->user()->can('owns', $business), 'canReview' => $request->user()->can('review', $business),
|
||||
'modalities' => ExistingBusinessDrafts::MODALITIES,
|
||||
'objectKinds' => ExistingBusinessObjects::KINDS,
|
||||
'objects' => ExistingBusinessObject::where('business_id', $id)->orderBy('created_at')->get()->map(fn ($object) => [
|
||||
...$object->only(['id', 'kind', 'verification_status']), 'payload' => $object->payload]),
|
||||
'history' => DB::table('existing_business_revisions')->where('business_id', $id)->orderByDesc('version_no')->limit(50)
|
||||
->get(['version_no', 'action', 'created_at', 'reason'])->map(fn ($row) => ['version_no' => $row->version_no,
|
||||
'action' => $row->action, 'created_at' => $row->created_at, 'note' => Crypt::decryptString($row->reason)])];
|
||||
|
||||
return $request->expectsJson() ? response()->json($props) : Inertia::render('investment/business', $props);
|
||||
}
|
||||
|
||||
public function save(Request $request, ExistingBusinessDrafts $drafts, ?string $id = null): JsonResponse
|
||||
{
|
||||
$business = $drafts->save($request->user(), $request->all(), $id);
|
||||
|
||||
return response()->json($this->record($business), $id ? 200 : 201);
|
||||
}
|
||||
|
||||
public function transition(Request $request, ExistingBusinessIntake $intake, string $id): JsonResponse
|
||||
{
|
||||
$data = $request->validate(['version_no' => ['required', 'integer', 'min:1'], 'action' => ['required', 'string'],
|
||||
'note' => ['required', 'string'], 'review_consent' => ['nullable', 'boolean']]);
|
||||
$business = $intake->transition($request->user(), $id, $data['version_no'], $data['action'], $data['note'], (bool) ($data['review_consent'] ?? false));
|
||||
|
||||
return response()->json($this->record($business));
|
||||
}
|
||||
|
||||
public function saveObject(Request $request, ExistingBusinessObjects $objects, string $id, ?string $object = null): JsonResponse
|
||||
{
|
||||
$saved = $objects->save($request->user(), $id, $request->all(), $object);
|
||||
|
||||
return response()->json(['id' => $saved->id, 'verification_status' => 'pending',
|
||||
'version_no' => ExistingBusiness::findOrFail($id)->version_no], $object ? 200 : 201);
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
private function record(ExistingBusiness $business): array
|
||||
{
|
||||
return [...$business->only(['id', 'code', 'modality', 'status', 'classification', 'version_no']), 'payload' => $business->payload];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class ExistingBusinessEnabled
|
||||
{
|
||||
/** @param Closure(Request): Response $next */
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
abort_unless(config('existing-business.enabled'), 404);
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
@@ -40,6 +40,7 @@ class HandleInertiaRequests extends Middleware
|
||||
'name' => config('app.name'),
|
||||
'educationEnabled' => (bool) config('education.enabled', false),
|
||||
'aiEnabled' => (bool) config('investmoz_ai.enabled', false),
|
||||
'existingBusinessEnabled' => (bool) config('existing-business.enabled', false),
|
||||
'flash' => ['success' => fn () => $request->session()->get('success')],
|
||||
'auth' => [
|
||||
'user' => $request->user(),
|
||||
|
||||
@@ -14,16 +14,34 @@ class ExistingBusinessPolicy
|
||||
|
||||
public function update(User $user, ExistingBusiness $business): bool
|
||||
{
|
||||
return $user->hasVerifiedEmail() && $business->owner_user_id === $user->id && ! $business->trashed();
|
||||
return $this->owns($user, $business) && in_array($business->status, ['draft', 'needs_information'], true);
|
||||
}
|
||||
|
||||
public function view(User $user, ExistingBusiness $business): bool
|
||||
{
|
||||
return $this->update($user, $business);
|
||||
return $this->owns($user, $business) || $this->review($user, $business);
|
||||
}
|
||||
|
||||
public function delete(User $user, ExistingBusiness $business): bool
|
||||
{
|
||||
return $this->update($user, $business);
|
||||
}
|
||||
|
||||
public function owns(User $user, ExistingBusiness $business): bool
|
||||
{
|
||||
return $user->hasVerifiedEmail() && $business->owner_user_id === $user->id && ! $business->trashed();
|
||||
}
|
||||
|
||||
public function review(User $user, ExistingBusiness $business): bool
|
||||
{
|
||||
return ! $business->trashed() && $business->owner_user_id !== $user->id
|
||||
&& in_array($business->status, ['submitted', 'in_review', 'needs_information'], true)
|
||||
&& $this->reviewQueue($user);
|
||||
}
|
||||
|
||||
public function reviewQueue(User $user): bool
|
||||
{
|
||||
return $user->can('manage-portal') && (bool) $user->two_factor_confirmed_at && (bool) $user->two_factor_secret
|
||||
&& in_array(strtolower($user->email), config('existing-business.reviewers', []), true);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\ExistingBusiness;
|
||||
use App\Models\ExistingBusinessObject;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
@@ -69,9 +70,12 @@ final class ExistingBusinessDrafts
|
||||
});
|
||||
}
|
||||
|
||||
private function snapshot(ExistingBusiness $business, User $actor, string $action, string $reason): void
|
||||
public function snapshot(ExistingBusiness $business, User $actor, string $action, string $reason): void
|
||||
{
|
||||
$snapshot = json_encode(['record' => $business->attributesToArray(), 'payload' => $business->payload], JSON_THROW_ON_ERROR);
|
||||
$snapshot = json_encode(['record' => $business->attributesToArray(), 'payload' => $business->payload,
|
||||
'objects' => ExistingBusinessObject::where('business_id', $business->id)->orderBy('id')->get()
|
||||
->map(fn ($object) => [...$object->attributesToArray(), 'payload' => $object->payload])->all(),
|
||||
], JSON_THROW_ON_ERROR);
|
||||
DB::table('existing_business_revisions')->insert(['id' => (string) Str::uuid(), 'business_id' => $business->id,
|
||||
'version_no' => $business->version_no, 'actor_id' => $actor->id, 'action' => $action,
|
||||
'reason' => Crypt::encryptString($reason), 'snapshot' => Crypt::encryptString($snapshot), 'sha256' => hash('sha256', $snapshot)]);
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\ExistingBusiness;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
final class ExistingBusinessIntake
|
||||
{
|
||||
public function transition(User $actor, string $id, int $version, string $action, string $note, bool $consent = false): ExistingBusiness
|
||||
{
|
||||
Validator::make(compact('action', 'note'), [
|
||||
'action' => ['required', 'in:submitted,in_review,needs_information,withdrawn'],
|
||||
'note' => ['required', 'string', 'min:10', 'max:2000'],
|
||||
])->validate();
|
||||
|
||||
return DB::transaction(function () use ($actor, $id, $version, $action, $note, $consent) {
|
||||
$business = ExistingBusiness::whereKey($id)->lockForUpdate()->firstOrFail();
|
||||
Gate::forUser($actor)->authorize(in_array($action, ['submitted', 'withdrawn'], true) ? 'owns' : 'review', $business);
|
||||
abort_unless($business->version_no === $version, 409, 'Versão desactualizada.');
|
||||
$allowed = ['submitted' => ['draft', 'needs_information'], 'in_review' => ['submitted'],
|
||||
'needs_information' => ['in_review'], 'withdrawn' => ['draft', 'submitted', 'in_review', 'needs_information']];
|
||||
abort_unless(in_array($business->status, $allowed[$action], true), 409, 'Transição indisponível neste estado.');
|
||||
if ($action === 'submitted') {
|
||||
Validator::make([...$business->payload, 'consent' => $consent], [
|
||||
'description' => ['required', 'string', 'min:30'], 'source_reference' => ['required', 'string', 'min:10'],
|
||||
'valid_until' => ['required', 'date_format:Y-m-d', 'after_or_equal:today'], 'consent' => ['accepted'],
|
||||
])->validate();
|
||||
}
|
||||
$business->status = $action;
|
||||
$business->version_no++;
|
||||
$business->save();
|
||||
DB::table('existing_business_reviews')->insert(['id' => (string) Str::uuid(), 'business_id' => $id, 'actor_id' => $actor->id,
|
||||
'version_no' => $business->version_no, 'action' => $action,
|
||||
'note' => Crypt::encryptString(json_encode(['note' => $note, 'review_consent' => $action === 'submitted' ? $consent : null], JSON_THROW_ON_ERROR))]);
|
||||
app(ExistingBusinessDrafts::class)->snapshot($business, $actor, $action, $note);
|
||||
|
||||
return $business;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\ExistingBusiness;
|
||||
use App\Models\ExistingBusinessObject;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
|
||||
final class ExistingBusinessObjects
|
||||
{
|
||||
public const KINDS = ['company', 'participation', 'asset', 'property', 'unit', 'improvement', 'agricultural_investment', 'land_right', 'contract', 'license', 'authorization', 'encumbrance', 'valuation', 'capital_request'];
|
||||
|
||||
/** @return array<string,array<int,string>> */
|
||||
public static function fields(): array
|
||||
{
|
||||
return [
|
||||
'label' => ['required', 'string', 'max:200'],
|
||||
'declared_holder' => ['nullable', 'string', 'max:500'],
|
||||
'document_reference' => ['nullable', 'string', 'max:1000'],
|
||||
'source_reference' => ['required', 'string', 'min:10', 'max:2000'],
|
||||
'competent_entity' => ['nullable', 'string', 'max:500'],
|
||||
'purpose' => ['nullable', 'string', 'max:2000'],
|
||||
'location_description' => ['nullable', 'string', 'max:2000'],
|
||||
'boundaries_description' => ['nullable', 'string', 'max:2000'],
|
||||
'occupancy' => ['nullable', 'string', 'max:2000'],
|
||||
'condition' => ['nullable', 'string', 'max:2000'],
|
||||
'encumbrances' => ['nullable', 'string', 'max:4000'],
|
||||
'restrictions' => ['nullable', 'string', 'max:4000'],
|
||||
'required_authorizations' => ['nullable', 'string', 'max:4000'],
|
||||
'transfer_condition' => ['nullable', 'string', 'max:4000'],
|
||||
'contract_type' => ['nullable', 'in:purchase,sale,lease,operation,management,other'],
|
||||
'valid_from' => ['nullable', 'date_format:Y-m-d'],
|
||||
'valid_until' => ['nullable', 'date_format:Y-m-d'],
|
||||
'area' => ['nullable', 'string', 'regex:/^\d{1,12}(\.\d{1,4})?$/', 'numeric', 'gt:0'],
|
||||
'area_unit' => ['nullable', 'required_with:area', 'in:m2,ha,km2'],
|
||||
'amount' => ['nullable', 'string', 'regex:/^\d{1,15}(\.\d{1,2})?$/', 'numeric', 'min:0'],
|
||||
'currency' => ['nullable', 'required_with:amount', 'regex:/^[A-Z]{3}$/'],
|
||||
'value_kind' => ['nullable', 'required_with:amount', 'in:asking,indicative,appraised,proposed,negotiated,confirmed'],
|
||||
'participation_percent' => ['nullable', 'numeric', 'between:0,100'],
|
||||
];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input */
|
||||
public function save(User $actor, string $businessId, array $input, ?string $objectId = null): ExistingBusinessObject
|
||||
{
|
||||
$rules = self::fields();
|
||||
if (! empty($input['payload']['valid_from'])) {
|
||||
$rules['valid_until'][] = 'after_or_equal:valid_from';
|
||||
}
|
||||
$data = Validator::make($input, ['version_no' => ['required', 'integer', 'min:1'],
|
||||
'kind' => ['required', 'in:'.implode(',', self::KINDS)], 'reason' => ['required', 'string', 'min:10', 'max:1000'],
|
||||
'payload' => ['required', 'array:'.implode(',', array_keys($rules))],
|
||||
])->validate();
|
||||
// Cross-field rules operate on the payload itself, rather than sibling root fields.
|
||||
Validator::make($data['payload'], $rules)->validate();
|
||||
|
||||
return DB::transaction(function () use ($actor, $businessId, $objectId, $data) {
|
||||
$business = ExistingBusiness::whereKey($businessId)->lockForUpdate()->firstOrFail();
|
||||
Gate::forUser($actor)->authorize('update', $business);
|
||||
abort_unless($business->version_no === $data['version_no'], 409, 'Versão desactualizada.');
|
||||
abort_if(! $objectId && ExistingBusinessObject::where('business_id', $businessId)->count() >= 100, 422, 'Máximo de 100 elementos por negócio.');
|
||||
$object = $objectId ? ExistingBusinessObject::where('business_id', $businessId)->whereKey($objectId)->firstOrFail() : new ExistingBusinessObject;
|
||||
if ($objectId) {
|
||||
abort_unless($object->kind === $data['kind'], 422, 'Crie outro elemento para uma natureza diferente.');
|
||||
}
|
||||
$object->fill(['business_id' => $businessId, 'kind' => $data['kind'], 'classification' => 'restricted', 'verification_status' => 'pending', 'payload' => $data['payload']]);
|
||||
$object->save();
|
||||
$business->version_no++;
|
||||
$business->save();
|
||||
app(ExistingBusinessDrafts::class)->snapshot($business, $actor, $objectId ? 'object_updated' : 'object_added', $data['reason']);
|
||||
|
||||
return $object;
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user