# Project conventions

Mfuko: SACCO membership, savings, lending, shares and accounting, built on Larabase, a modular Laravel 13 + Inertia 3 +
React 19 platform (Tailwind 4 + ReUI). Every feature is a Laravel package under `packages/rutatiina/*`; the application
root is thin. Read README.md for the architecture; its first section lists how Mfuko differs from the template.

## Mfuko

- Keep `packages/rutatiina/*` identical to Larabase so template upgrades apply cleanly. Put Mfuko behaviour in
  `packages/nugsoft/*` (Composer `nugsoft/<module>`, npm `@nugsoft/<module>`, PHP `Nugsoft\<Module>\`, config
  `nugsoft.<module>`; providers set `protected string $vendor = 'nugsoft';`), and branding in the application
  (`resources/css/app.css`, `public/media/app`, `.env`). If a template module needs a change, make it general-purpose
  and list it under "Template packages changed" in README.md so it can go upstream.
- Nugsoft modules may use any rutatiina module; rutatiina modules never refer to nugsoft. Module names are unique
  across both vendors (they are the page and translation namespaces). Register each new module in
  `NUGSOFT_LEVELS` / `NUGSOFT_NAMESPACES` in `tests/Unit/ModuleBoundaryTest.php`; README.md, "Mfuko modules", has the
  full checklist.
- The demo module is removed. Do not reintroduce demo data or demo accounts.
- Money is UGX and must never be stored or summed as floating point; display every amount with its currency and every
  figure with its scope (branch, as-of date or period).
- Never commit the legacy or production SQL exports, `.env`, or member data. Seeders and tests use synthetic data only.

The rest of this file is the template's own guidance; "Purpose and scope" describes Larabase itself.

## Purpose and scope

Larabase is a reusable template: the starting point for new Laravel applications. It should ship the functionality
most systems need, ready to use, so a new project only adds its own domain packages on top. Features in the template
must therefore be general-purpose, configurable through config/settings rather than hardcoded, and removable as a
module. Anything specific to one product belongs in that product's packages, not here.

Common features and the module that owns each:

| Feature                                                                                       | Module          |
| --------------------------------------------------------------------------------------------- | --------------- |
| Sign in / up, email verification, password reset, 2FA, passkeys, Google sign-in, reCAPTCHA    | `auth`          |
| Current sessions (sign out devices)                                                           | `auth`          |
| Users: invite, edit, trash/restore, impersonate; my account (profile, avatar, account delete) | `users`         |
| Roles and permissions (per organization)                                                      | `authorization` |
| Organizations, memberships, invitations, switcher; tenancy (teams / database / single)        | `organizations` |
| Activity log and security log                                                                 | `activity-log`  |
| System settings                                                                               | `settings`      |
| Database notifications, the topbar inbox, notification preferences and defaults               | `notifications` |
| API keys, versioned API routes (`/api/v1`), rate limits, OpenAPI docs (`/docs/api`)           | `api`           |
| Private messaging                                                                             | `messaging`     |
| Layouts (demo1 sidebar / demo7 header / demo9 navbar), auth layouts, error pages              | `themes`        |
| Media library and file manager (folders, uploads, preview, picker); message attachments       | `media`         |
| System: health checks, backups, failed jobs, log viewer, maintenance mode                     | `system`        |
| Global search (topbar): pages and the records modules declare                                 | `search`        |
| Real-time updates (Reverb / Pusher): live inbox and messages, polling as the fallback         | `realtime`      |
| Feature flags (Pennant): on or off for everyone or per user                                   | `features`      |
| Outgoing webhooks: signed, retried deliveries of the events modules declare, delivery log     | `webhooks`      |
| Personal data download (my account); terms and privacy policy acceptance                      | `privacy`       |
| Security headers and Content-Security-Policy (spatie/laravel-csp)                             | `core`          |
| DataGrid CSV / Excel export (queued for large exports)                                        | `core`          |

Uploads go through `Rutatiina\Core\Support\Upload` (`store()`, `url($value, 'thumb')`, `delete()`), never straight
to a disk. Core stores them on the `config('rutatiina.core.uploads.disk')` disk (`public` or S3-compatible); `media`
replaces that file store with spatie/laravel-medialibrary. A stored value is always a path on the uploads disk, so it
keeps working when `media` is removed. Pass `shared: true` for account-level files (avatars). Modules that let users
pick an existing file render the `media-picker` component by name (`getComponent('media-picker')`).

Deliberately not included (README, "Not included"): billing (a recipe on Laravel Cashier) and DataGrid import.

When adding a missing common feature:

- Build it as its own module (`packages/rutatiina/<name>`) and place it in the dependency order below, so projects that
  do not need it can remove it.
- Base it on an established, maintained package before writing custom code (e.g. evaluate
  `spatie/laravel-medialibrary` for media).
- Contribute its menus, permissions, roles, settings and shared props through the provider hooks, add a settings page
  or enable switch where admins should control it (as `messaging` does), and add tests.
- Update the module tree, the dependency order and the feature list in README.md and in this file.

## Commands

```bash
composer setup                     # install, key:generate, migrate --seed, storage:link, npm install & build
composer dev                       # server, queue, logs and Vite (php artisan dev)
composer test                      # config:clear, Pint --test, Larastan level 7, then php artisan test
composer ci:check                  # what CI runs: npm run check, npm run types:check, composer test
composer lint                      # Pint, fixing in place

php artisan test --filter=ImpersonationTest        # one test class
php artisan test --filter=test_owners_can_not_be_impersonated
php artisan test --testsuite=Packages              # Unit | Feature | Packages (packages/rutatiina/*/tests)
php artisan test packages/rutatiina/users/tests    # one module's tests

npm run check                      # Vite+ lint (oxlint, warnings fail) and format check
npm run check:fix                  # apply lint/format fixes
npm run types:check                # tsc across the app and every module
npm run build

php artisan modules:list           # installed modules
php artisan migrate:fresh --seed   # reset; seeds the owner from OWNER_EMAIL / OWNER_PASSWORD
```

`resources/js/{actions,routes,wayfinder}` are generated by the Wayfinder Vite plugin and gitignored. After adding or
renaming routes, run `npm run build` (or keep `composer dev` running) before `npm run types:check`.

## Modules

- Dependency order: `core → ui → themes → activity-log → authorization → users → { organizations, media, system, search, realtime, features, auth, settings, api, webhooks, privacy } → { notifications, messaging }`.
  A module may only use modules below it. `tests/Unit/ModuleBoundaryTest.php` enforces this for PHP and TypeScript.
- Providers extend `Rutatiina\Core\PackageServiceProvider` and declare what they contribute through the hooks
  `navigation()`, `permissions()`, `roles()`, `shared()`, `seeders()`, `middleware()`, `consoleCommands()`,
  `vendorConfig()`, `schedule()`, `notificationTypes()`, `searchables()`, `features()`, `webhookEvents()`, `personalData()`. A module schedules
  housekeeping for the data it owns in `schedule()`, declares every notification it sends in `notificationTypes()`
  (users choose their channels in `notifications`; mark channels that must always go out, such as links people need,
  as `mandatory`), the records people should find from the topbar in `searchables()` (the model uses Scout's
  `Searchable`), and the feature flags it checks in `features()` (`Flags::active()` in PHP, `useFeature()` in React;
  never call Pennant from a module below `features`), and the events it sends to webhooks in `webhookEvents()`
  (`Webhooks::dispatch()` from core; a no-op without `webhooks`). A module that keeps data about people declares it
  in `personalData()` (mark organization-owned sources `'organization' => true`), so their download is complete.
  `register()` and `boot()` are final; use `registerPackage()` / `bootPackage()` for anything else.
- The base provider merges `config/<name>.php`, loads migrations and translations, adds `resources/js/pages` as the
  `<name>::` Inertia namespace, and registers `routes/web.php` (`web` group) and `routes/api.php` (`api` group, `/api`
  prefix) after the app has booted, so a package can override a route another package (e.g. Fortify) declared first.
- Config is merged as `config('rutatiina.<module>')`. Never read another module's config upward.
- A module configures the vendor package it wraps in its provider's `vendorConfig()`, never in the root `config/`
  (which holds only Laravel's own files). Keys a project's own config file defines win over the module's values.
- The root application owns `app/Models/User.php`, which composes capability traits and contracts from the modules
  (`Authenticates`, `HasApiKeys`, …). Removing a module means removing its concern from that model too.
- A new module also needs its `@rutatiina/<name>/*` alias in `tsconfig.json` (Vite resolves the alias by pattern).
- `php artisan modules:list` shows what is installed.

## Backend

- Prefer first-party / established packages already installed (Fortify, Socialite, Sanctum, spatie/laravel-permission,
  spatie/laravel-activitylog, spatie/laravel-settings, spatie/laravel-query-builder, lab404/laravel-impersonate).
- Controllers render namespaced Inertia pages (`Inertia::render('users::index')`); validation lives in FormRequests;
  authorization in policies or permission gates (`user.view`, `settings.manage`, …). Owners pass permission gates,
  policies still apply. Register policies explicitly with `Gate::policy()` — package policies are not auto-discovered.
- Permissions and roles are written to the database by `rutatiina/authorization`'s seeder; role grants from different
  modules merge.
- Never reference `App\Models\User` from a package. Use `Rutatiina\Users\Users::model()` / `Users::query()` and
  type-hint `Rutatiina\Users\Models\User` or a capability contract (`AuthenticatesUser`, `ApiUser`, `AuthorizableUser`).
- Flash toasts with `Inertia::flash('toast', ['type' => 'success', 'message' => __('…')])`.
- DataGrid endpoints: `QueryBuilder` + `TableQuery::perPage()` / `TableQuery::state()` + API resources. A grid that
  people may download builds its query in a `TableExport` subclass (core) and answers `TableExport::requested()` with
  `$export->response($request)`; render `DataGridExport` with `useInertiaTable`'s `exportUrl`.
- To update a user's open pages at once, call `Realtime::signal($userId, '<module>.<event>', [...])` (core); it is a
  no-op unless `realtime` is installed and broadcasting is on. Never depend on `realtime` from another module.
- Pages are served under a Content-Security-Policy (core, spatie/laravel-csp). Inline scripts need `@cspNonce`; a
  module whose pages load from another host adds it with `ContentSecurityPolicy::allow()` / `preset()` in
  `bootPackage()`, and a vendor page that brings its own markup is exempted with `ContentSecurityPolicy::except()`.
- Security-relevant events go to the `security` activity log (`Rutatiina\ActivityLog\Support\SecurityLog`).
- Tenancy (see README, "Organizations and tenancy"): organization-owned models use core's `BelongsToOrganization` and an
  `organization_id` column, with migrations in `database/migrations/organization` (no foreign keys to central tables).
  Central models use `UsesCentralConnection`; validation rules on central tables name the model, not the table. Only
  Eloquent is scoped: `DB` queries filter on `organization_id` themselves, unique indexes include it, and
  `Tenancy::unique()` / `Tenancy::exists()` scope validation. Account-level notifications implement
  `AccountNotification`; platform-wide permissions are marked `'platform' => true`. Never reference
  `rutatiina/organizations` from a module below it; use core's `Tenancy` facade.
- Localization: write user-facing strings in English through `__('…')` (PHP and `@rutatiina/ui/lib/translations` in
  TS) and add each one, with menu titles and notification labels, to the module's `lang/en.json`
  (`tests/Feature/LocalizationTest.php` checks). Languages are `rutatiina.core.locales`; core's `SetLocale` applies the
  user's, then the organization's, then the app's language and timezone. Store dates in the app timezone; format them
  for display with `formatDate` / `formatDateTime`. Laravel's own messages come from `laravel-lang/lang`
  (`php artisan lang:add <code>`, `lang:update`).
- Package routes live in the package's `routes/web.php` and are registered inside the `web` group after boot. API
  routes go in `routes/api.php` under a version (`Route::prefix('v1')->name('api.v1.')`), return API resources and
  take a docblock summary, which `/docs/api` (dedoc/scramble) shows.
- Tests run in every tenancy mode (`TENANCY_MODE=database php artisan test`; CI runs teams, database and single).
  Database tests run inside a test organization; `tests/Concerns/InteractsWithOrganizations.php` makes organizations
  and switches a user between them.
- Tests: class-style PHPUnit, SQLite in memory. Suites (`phpunit.xml`): `Unit` and `Feature` under `tests/`, and
  `Packages` for `packages/rutatiina/*/tests` under `Rutatiina\<Module>\Tests\`. Cross-module tests live in `tests/`;
  `tests/Concerns/CreatesUsers.php` is shared. A test creates the roles it needs.
- Run `composer test` (Pint, Larastan level 7 over `app/` and every module's `src/`, Pest).

## Frontend

- `resources/js/app.tsx` eagerly loads every module's `resources/js/module.ts`, then resolves pages:
  `'name'` → `resources/js/pages/name/page.tsx`, `'<module>::<name>'` → `<module>/resources/js/pages/<name>/page.tsx`.
  A page picks its layout with `export const layout = …` (or `null` for none); otherwise it gets the user's layout
  (default `LARABASE_LAYOUT`). Keep the existing markup/classes intact.
- Imports: a module refers to its own files by its own alias (`@rutatiina/users/...`) and to other modules only
  downward. `@/actions`, `@/routes`, `@/wayfinder` are the application's Wayfinder output and are always allowed.
  `resources/js/app.tsx` imports nothing but `@rutatiina/ui`.
- Use `@rutatiina/ui/components/common/link` for links, `@rutatiina/ui/lib/navigation` for pathname/router hooks,
  `useInertiaForm` for forms, `useInertiaTable` for server-side DataGrids, `notify` for toasts, `useCan` for
  permission-based UI, `useHasModule('<name>')` for content that only makes sense while a module is installed,
  `useRealtime` + `usePollUnlessLive` (`@rutatiina/ui/lib/realtime`) for data that should update live.
- `@rutatiina/ui/components/ui` are ReUI components; do not replace them with shadcn CLI output. They are excluded
  from lint and formatting.
- Menus come from the server on the `navigation` prop, filtered by the user's permissions. Never hardcode a menu:
  register entries in the provider's `navigation()` and the icons in the module's `module.ts` (`registerIcons`).
- A module adds UI to a layout through `registerSlot`, context through `registerProvider`, and named components
  through `registerComponent` — all from its `module.ts`, which `app.tsx` loads eagerly.
- Each module augments `SharedData` in its own `resources/js/inertia.d.ts`. Do not name that file `types.d.ts`
  next to a `types.ts`: TypeScript would treat it as that file's declaration output and ignore the augmentation.
- Formatting: 2 spaces, single quotes (Vite+ formatter). Type-check with `npm run types:check`.

## Demo area

- Removed from Mfuko (`rutatiina/demo`). Template modules still gate optional demo content with
  `useHasModule('demo')`; leave those checks in place, they are inert.
