refactor: adopt modular domain architecture (#747)

* refactor: stabilize model identities for domain migration

* refactor: extract module platform context

* refactor: assign models to domain contexts

* refactor: extract ai platform context

* refactor: extract storage platform context

* refactor: extract mail platform context

* refactor: extract pdf platform context

* refactor: extract operations platform context

* refactor: move installation into operations platform

* refactor: extract money domain context

* refactor: extract taxation domain context

* refactor: extract catalog domain context

* refactor: extract metadata domain context

* refactor: extract reporting domain context

* refactor: extract purchases domain context

* refactor: extract receivables domain context

* refactor: extract accounts domain context

* refactor: complete reporting statement boundary

* refactor: extract contacts domain context

* refactor: extract sales domain context

* refactor: remove legacy application layers

* fix: migrate legacy bouncer role identities
This commit is contained in:
Darko Gjorgjijoski
2026-08-05 17:40:03 +02:00
committed by GitHub
parent a34bf0909f
commit 5ef7804e60
878 changed files with 8997 additions and 5707 deletions
@@ -0,0 +1,97 @@
<?php
namespace App\Platform\Modules\Http\Controllers\Admin;
use App\Platform\Http\Controller;
use App\Platform\Modules\Marketplace\MarketplaceClient;
use App\Platform\Modules\Models\MarketplaceCredential;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Crypt;
class MarketplacePairingController extends Controller
{
public function __construct(private MarketplaceClient $client) {}
public function start(): JsonResponse
{
$this->authorize('manage modules');
$response = $this->client->beginPairing();
$data = $response->json();
if (! $response->successful() || ! is_array($data) || ! is_string($data['device_code'] ?? null)) {
return response()->json(['error' => 'marketplace_unavailable'], 503);
}
$ttl = max(60, (int) ($data['expires_in'] ?? 600));
Cache::put($this->cacheKey(), $data['device_code'], now()->addSeconds($ttl));
return response()->json([
'device_code' => $data['device_code'],
'user_code' => $data['user_code'] ?? null,
'verification_uri' => $data['verification_uri'] ?? $data['verification_uri_complete'] ?? null,
'verification_uri_complete' => $data['verification_uri_complete'] ?? null,
'expires_in' => $ttl,
'interval' => max(1, (int) ($data['interval'] ?? 5)),
], 201);
}
public function poll(): JsonResponse
{
$this->authorize('manage modules');
$deviceCode = Cache::get($this->cacheKey());
if (! is_string($deviceCode)) {
return response()->json(['error' => 'pairing_expired'], 422);
}
$response = $this->client->pollPairing($deviceCode);
$data = $response->json();
if ($response->status() === 428 || ($data['error'] ?? null) === 'authorization_pending') {
return response()->json(['status' => 'pending']);
}
if (! $response->successful() || ! is_array($data) || ! is_string($data['installation_token'] ?? null)) {
return response()->json(['error' => 'pairing_failed'], 422);
}
MarketplaceCredential::query()->delete();
MarketplaceCredential::query()->create([
'credential' => Crypt::encryptString($data['installation_token']),
'device_id' => is_scalar($data['installation']['id'] ?? null) ? (string) $data['installation']['id'] : null,
'paired_at' => now(),
]);
Cache::forget($this->cacheKey());
return response()->json(['status' => 'paired']);
}
public function status(): JsonResponse
{
$this->authorize('manage modules');
$credential = MarketplaceCredential::query()->latest('id')->first();
return response()->json([
'paired' => $credential !== null,
'expired' => $credential?->expires_at?->isPast() ?? false,
'paired_at' => $credential?->paired_at?->toIso8601String(),
]);
}
public function disconnect(): JsonResponse
{
$this->authorize('manage modules');
if (MarketplaceCredential::query()->exists()) {
// Revocation releases any entitlement activation tied to this
// installation. Local disconnect still succeeds if the control
// plane is temporarily unavailable.
$this->client->revokeInstallation();
}
MarketplaceCredential::query()->delete();
Cache::forget($this->cacheKey());
return response()->json(['success' => true]);
}
private function cacheKey(): string
{
return 'marketplace.device-pairing';
}
}
@@ -0,0 +1,45 @@
<?php
namespace App\Platform\Modules\Http\Controllers\Admin;
use App\Platform\Http\Controller;
use App\Platform\Modules\Http\Requests\InstallMarketplaceModuleRequest;
use App\Platform\Modules\Http\Requests\UninstallMarketplaceModuleRequest;
use App\Platform\Modules\Marketplace\MarketplaceInstaller;
use App\Platform\Modules\Marketplace\MarketplaceUninstaller;
use Illuminate\Http\JsonResponse;
class ModuleInstallationController extends Controller
{
public function install(InstallMarketplaceModuleRequest $request, MarketplaceInstaller $installer): JsonResponse
{
$this->authorize('manage modules');
$response = $installer->install(
$request->string('slug')->toString(),
$request->string('version')->toString(),
$request->string('channel')->toString() ?: (string) config('invoiceshelf.marketplace.channel', 'stable'),
);
return response()->json($response, $response['success'] ? 200 : 422);
}
public function uninstall(string $module, UninstallMarketplaceModuleRequest $request, MarketplaceUninstaller $uninstaller): JsonResponse
{
$this->authorize('manage modules');
$response = $uninstaller->uninstall(
$module,
$request->boolean('remove_data'),
$request->string('confirmation')->toString() ?: null,
);
$status = match ($response['error'] ?? null) {
'module_not_installed' => 404,
'operation_in_progress', 'module_runtime_missing', 'dependent_modules_installed' => 409,
default => $response['success'] ? 200 : 422,
};
return response()->json($response, $status);
}
}
@@ -0,0 +1,114 @@
<?php
namespace App\Platform\Modules\Http\Controllers\Admin;
use App\Platform\Http\Controller;
use App\Platform\Modules\Events\ModuleDisabledEvent;
use App\Platform\Modules\Events\ModuleEnabledEvent;
use App\Platform\Modules\Http\Resources\ModuleResource;
use App\Platform\Modules\Marketplace\MarketplaceClient;
use App\Platform\Modules\Models\Module as ModelsModule;
use App\Platform\Modules\Runtime\DatabaseActivator;
use Illuminate\Http\JsonResponse;
use Nwidart\Modules\Facades\Module;
class ModulesController extends Controller
{
public function index(MarketplaceClient $client)
{
$this->authorize('manage modules');
$response = $client->catalog();
$body = $response->json();
$modules = is_array($body) ? ($body['modules'] ?? $body['data'] ?? null) : null;
if (! $response->successful() || ! is_array($modules)) {
return response()->json(['error' => 'marketplace_unavailable'], 503);
}
return ModuleResource::collection(collect($modules));
}
public function show(string $module, MarketplaceClient $client)
{
$this->authorize('manage modules');
$response = $client->module($module);
$body = $response->json();
if ($response->status() === 404) {
return response()->json(['error' => 'not_found'], 404);
}
if (! $response->successful() || ! is_array($body) || ! is_array($body['module'] ?? null)) {
return response()->json(['error' => 'marketplace_unavailable'], 503);
}
return (new ModuleResource($body['module']))
->additional(['meta' => [
'modules' => ModuleResource::collection(
collect($body['meta']['modules'] ?? [])
),
]]);
}
public function enable(string $module): JsonResponse
{
$this->authorize('manage modules');
$module = ModelsModule::query()
->where('name', $module)
->where('installed', true)
->firstOrFail();
$installedModule = Module::find($module->name);
if ($installedModule === null) {
$this->markRuntimeMissing($module);
return response()->json([
'success' => false,
'error' => 'module_runtime_missing',
], 409);
}
$installedModule->enable();
$module->refresh();
ModuleEnabledEvent::dispatch($module);
return response()->json(['success' => true]);
}
public function disable(string $module, DatabaseActivator $activator): JsonResponse
{
$this->authorize('manage modules');
$module = ModelsModule::query()
->where('name', $module)
->where('installed', true)
->firstOrFail();
$activator->setActiveByName($module->name, false);
if (Module::find($module->name) === null) {
$this->markRuntimeMissing($module);
} else {
$module->refresh();
}
ModuleDisabledEvent::dispatch($module);
return response()->json(['success' => true]);
}
private function markRuntimeMissing(ModelsModule $module): void
{
$module->update([
'installed' => false,
'enabled' => false,
'state' => 'failed',
'last_error' => 'module_runtime_missing',
'last_failed_at' => now(),
]);
}
}
@@ -0,0 +1,48 @@
<?php
namespace App\Platform\Modules\Http\Controllers\Assets;
use App\Platform\Http\Controller;
use App\Platform\Modules\Runtime\ModuleAssetVersion;
use DateTime;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use InvoiceShelf\Modules\Registry as ModuleRegistry;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class ScriptController extends Controller
{
/**
* Serve the requested module-registered script.
*
* Modules call \InvoiceShelf\Modules\Registry::registerScript($name, $path)
* from their ServiceProvider::boot() to inject custom JS into the host app.
*
* @throws NotFoundHttpException
*/
public function __invoke(Request $request, string $script): Response
{
$path = ModuleRegistry::scriptFor($script);
abort_if($path === null || ! is_file($path), 404);
$contents = file_get_contents($path);
abort_if(! is_string($contents), 404);
$version = ModuleAssetVersion::forContents($contents);
$cacheControl = is_string($request->query('v')) && hash_equals($version, $request->query('v'))
? 'public, max-age=31536000, immutable'
: 'no-store';
$response = response(
$contents,
200,
[
'Content-Type' => 'application/javascript',
]
)->setLastModified(DateTime::createFromFormat('U', (string) filemtime($path)));
$response->headers->set('Cache-Control', $cacheControl);
return $response;
}
}
@@ -0,0 +1,48 @@
<?php
namespace App\Platform\Modules\Http\Controllers\Assets;
use App\Platform\Http\Controller;
use App\Platform\Modules\Runtime\ModuleAssetVersion;
use DateTime;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use InvoiceShelf\Modules\Registry as ModuleRegistry;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class StyleController extends Controller
{
/**
* Serve the requested module-registered stylesheet.
*
* Modules call \InvoiceShelf\Modules\Registry::registerStyle($name, $path)
* from their ServiceProvider::boot() to inject custom CSS into the host app.
*
* @throws NotFoundHttpException
*/
public function __invoke(Request $request, string $style): Response
{
$path = ModuleRegistry::styleFor($style);
abort_if($path === null || ! is_file($path), 404);
$contents = file_get_contents($path);
abort_if(! is_string($contents), 404);
$version = ModuleAssetVersion::forContents($contents);
$cacheControl = is_string($request->query('v')) && hash_equals($version, $request->query('v'))
? 'public, max-age=31536000, immutable'
: 'no-store';
$response = response(
$contents,
200,
[
'Content-Type' => 'text/css',
]
)->setLastModified(DateTime::createFromFormat('U', (string) filemtime($path)));
$response->headers->set('Cache-Control', $cacheControl);
return $response;
}
}
@@ -0,0 +1,76 @@
<?php
namespace App\Platform\Modules\Http\Controllers\Company;
use App\Platform\Http\Controller;
use App\Platform\Modules\Models\Module;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Str;
use InvoiceShelf\Modules\Registry as ModuleRegistry;
/**
* Read-only company-context Active Modules index.
*
* Lists every module the super admin has activated on this instance
* (Module::enabled = true) and reports whether each one has registered a
* settings schema. The frontend uses this to render the company-context
* "Modules" landing page with a Settings button per active module.
*
* Activation is instance-global; per-company customization happens through
* settings (per CompanySetting under the module.{slug}.* prefix).
*
* Slug convention: nwidart stores the module's PascalCase class name in
* `modules.name` (e.g. "SalesTaxUs"), but URLs and registry keys use the
* kebab-case form ("sales-tax-us") for readability. We normalize via
* Str::kebab() so module authors can call Registry::registerMenu('sales-tax-us')
* naturally without thinking about the storage format.
*/
class CompanyModulesController extends Controller
{
public function index(): JsonResponse
{
$this->authorize('manage module settings');
$modules = Module::query()
->where('enabled', true)
->get()
->map(function (Module $module) {
$slug = Str::kebab($module->name);
$menu = ModuleRegistry::menuFor($slug);
$translatedMenuTitle = $this->translateMenuTitle($menu['title'] ?? null);
$displayName = $translatedMenuTitle ?? Str::headline($module->name);
return [
'slug' => $slug,
'name' => $module->name,
'display_name' => $displayName,
'version' => $module->version,
'has_settings' => ModuleRegistry::settingsFor($slug) !== null,
'menu' => $menu === null
? null
: [
...$menu,
'title' => $translatedMenuTitle ?? $menu['title'],
],
];
})
->values();
return response()->json(['data' => $modules]);
}
private function translateMenuTitle(?string $title): ?string
{
if ($title === null) {
return null;
}
$translatedTitle = __($title);
if (! is_string($translatedTitle) || $translatedTitle === $title) {
return null;
}
return $translatedTitle;
}
}
@@ -0,0 +1,178 @@
<?php
namespace App\Platform\Modules\Http\Controllers\Company;
use App\Platform\Http\Controller;
use App\Platform\Modules\Contracts\ModuleSettingsStore;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use InvoiceShelf\Modules\Registry as ModuleRegistry;
use InvoiceShelf\Modules\Settings\Schema;
/**
* Schema-driven module settings backend.
*
* Each active module's ServiceProvider::boot() calls
* Registry::registerSettings($slug, $schema) once at app boot. This controller
* exposes that schema to the frontend, validates submitted values against the
* schema's per-field rules, and persists per-company values into CompanySetting
* under the key prefix `module.{slug}.{field_key}`.
*
* Activation is instance-global, but settings are per-company — two companies
* on the same instance can configure the same activated module differently.
*/
class ModuleSettingsController extends Controller
{
public function __construct(private ModuleSettingsStore $settings) {}
public function show(Request $request, string $slug): JsonResponse
{
$this->authorize('manage module settings');
$schema = ModuleRegistry::settingsFor($slug);
if ($schema === null) {
abort(404, "Module '{$slug}' has not registered a settings schema.");
}
$values = collect($schema->fields())
->mapWithKeys(fn (array $field) => [
$field['key'] => $this->settings->get(
"module.{$slug}.{$field['key']}",
$request->header('company')
) ?? $field['default'],
])
->all();
return response()->json([
'schema' => $this->translateSchema($schema->toArray()),
'values' => $values,
]);
}
public function update(Request $request, string $slug): JsonResponse
{
$this->authorize('manage module settings');
$schema = ModuleRegistry::settingsFor($slug);
if ($schema === null) {
abort(404, "Module '{$slug}' has not registered a settings schema.");
}
$rules = $this->buildRules($schema);
$allowedKeys = array_keys($rules);
$validated = $request->validate($rules);
$companyId = $request->header('company');
// Only persist keys the schema knows about — silently drop unknown keys
// rather than letting modules write arbitrary settings.
$settingsToWrite = [];
foreach ($allowedKeys as $key) {
if (array_key_exists($key, $validated)) {
$settingsToWrite["module.{$slug}.{$key}"] = $this->normalizeForStorage($validated[$key]);
}
}
if ($settingsToWrite !== []) {
$this->settings->put($settingsToWrite, $companyId);
}
return response()->json(['success' => true]);
}
/**
* Convert a Schema's field rule arrays into a flat Laravel validator rules array.
*
* Field rules are passed through verbatim — a field declared as
* `'rules' => ['required', 'string', 'max:255']` becomes
* `['my_field' => ['required', 'string', 'max:255']]`. The frontend's
* BaseSchemaForm.vue understands a subset of these for client-side validation;
* the backend validator is the source of truth.
*
* @return array<string, array<int, string>>
*/
private function buildRules(Schema $schema): array
{
$rules = [];
foreach ($schema->fields() as $field) {
$rules[$field['key']] = $this->withTypeRule($field);
}
return $rules;
}
/**
* Prepend a sensible per-type validation rule so booleans must be booleans,
* numbers must be numeric, etc., even if the module didn't declare it.
*
* @param array<string, mixed> $field
* @return array<int, string>
*/
private function withTypeRule(array $field): array
{
/** @var array<int, string> $declared */
$declared = $field['rules'] ?? [];
$typeRule = match ($field['type']) {
'switch' => 'boolean',
'number' => 'numeric',
'multiselect' => 'array',
default => 'nullable',
};
// Avoid duplicating the type rule if the module already declared it
if (in_array($typeRule, $declared, true)) {
return $declared;
}
return array_merge([$typeRule], $declared);
}
/**
* CompanySetting stores everything as strings. Cast booleans, ints, and
* arrays to a representation that round-trips through getSetting/setSetting
* without losing information. Reads happen in show() above and naturally
* return strings; the frontend handles re-coercion in BaseSchemaForm.vue.
*/
/**
* Translate section titles and field labels in the schema so the
* frontend receives ready-to-display strings instead of Laravel
* translation keys it cannot resolve (e.g. `sales_tax_us::settings.greeting`).
*
* @param array{sections: list<array<string, mixed>>} $schema
* @return array{sections: list<array<string, mixed>>}
*/
private function translateSchema(array $schema): array
{
foreach ($schema['sections'] as &$section) {
if (isset($section['title'])) {
$section['title'] = __($section['title']);
}
foreach ($section['fields'] as &$field) {
if (isset($field['label'])) {
$field['label'] = __($field['label']);
}
}
}
return $schema;
}
private function normalizeForStorage(mixed $value): string
{
if (is_bool($value)) {
return $value ? '1' : '0';
}
if (is_array($value)) {
return json_encode($value, JSON_UNESCAPED_SLASHES) ?: '[]';
}
return (string) ($value ?? '');
}
}