← Back to Pull requests

refactor: run invoice and expense admin through the use case gate #89

Merged
smahelos merged 92 files (2643 lines) on Nov 12, 2026 18:10 UTC
View on GitHub
smahelos smahelos commented on Nov 12, 2026 15:53 UTC
Author

Summary

Phase 5b of the permission conversion (docs/TECH_DEBT.md, step 11): the invoice and expense admin, the invoice items and the document party pickers run only through Commands and Queries behind the authorizing gate. No port takes a bare UserId for ownership any more: every …ForUser lookup is replaced by a ReadScope / WriteScope the gate issues.

Use cases (app/Application/Invoice/{Commands,Queries})

  • Expenses: CreateExpense, UpdateExpense (permissionWithOwner expense.create/update) with their own flow like invoices; only the attachment and logo upload/cleanup is shared in Support/ExpenseAttachments.

  • Items: ListInvoiceCatalogProducts, PreviewInvoiceTotals (anyOf invoice.create/update).

  • Document parties: ListDocumentBusinesses, ListActiveDocumentBusinesses, ListDocumentContacts, ListDocumentBankAccounts, GetDocumentBusiness, GetDocumentContact, FindDefaultDocumentBusiness, FindDefaultDocumentBankAccount, FindDocumentContactDuplicates (anyOf invoice/expense create/update) and GetInvoiceParties (invoice.update). The admin DocumentPartyCrudController and the frontend DocumentPartyPicker both run them.
  • Ports: Party findByIdForUser (business, contact, account), CatalogProductReadRepositoryInterface::searchForUser, InvoiceDtoReadRepositoryInterface::findByIdForUser and ExpenseReadRepositoryInterface::findByIdForUser are gone; the assemblers and InvoiceProductOwnership take the scope.

    Requests: authorize() of ExpenseRequest, InvoiceItemsRequest and DocumentPartySelectionRequest is replaced by allowed: on the routes. keepsContact of the admin invoice and expense requests reads the stored contact the controller passes in $request->attributes (AdminDocumentPartyInput), not a second ungated read.

    Deleted: ExpenseApplicationService, InvoiceItemsApplicationService, InvoiceListingApplicationService with its interface, ExpenseAccessDeniedException, InvoiceAccessDeniedException, UserPermissionServiceInterface with LaravelUserPermissionService.

    Permissions: expense.create and expense.update are added to the web guard and both frontend roles (PermissionCatalog, migration 2026_11_12_000002_add_web_expense_permissions).

    Behaviour changes

  • Admin expense edit: the owner field is disabled and the update keeps the stored owner (the same as invoices since cf682861); a changed owner used to end in a not-found error.

  • The picker's read actions no longer check permissions of their own; they have the same access as the form they serve.

  • An admin storing or updating an expense for an owner who lacks the expense permission gets 403.
  • Expenses still live in the Invoice context; their split into an Expense context (with the shared document assemblers moving to Party) follows in its own branch and is listed in docs/TECH_DEBT.md.

    Evidence

  • Before: expense, items and party reads checked ownership with …ForUser ports, UserPermissionService and authorize() in form requests; the picker and the admin party endpoints read Eloquent or an ungated listing service.

  • After: the full suite passes (2765 tests), and Pint, PHP_CodeSniffer, Larastan, ddd:guard, the baselines (provider snapshot and controller thinness regenerated) and the dependency audit pass. ExpenseUseCasesTest runs a frontend user through the gate; InvoicePartiesAssemblerTest runs CreateInvoice / UpdateInvoice through the gate instead of issuing a scope.

  • Not verified in a browser.
  • Merge Danger

    Door: two-way

    One migration syncs the permission catalog (down() is empty: reverting the code leaves the two extra web permissions in the database, unused). Reverting the commit restores the deleted services. Billex is not in production.

    🤖 Generated with Claude Code

    Diff: 2643 lines (+1656 / -987) across 92 files Reviewer: smahelos Review duration: 137m
    All Vouch review confidence checks passed
    Residual risk 0.14 = Change Risk (0.86) × (1 − Review Confidence (0.84)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.86 · 2643 lines diff across 92 files
    0.86
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.92 · 5 substantive comment(s)
    0.92
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    84%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Self Review self_review
    0.140
    Mass File Touch mass_file_touch
    0.080
    Real PR Conversation Timeline
    13 items
    qodo-code-review[bot] qodo-code-review[bot] commented on Nov 12, 2026 15:53 UTC
    Bot

    Qodo reviews are paused for this user.

    Troubleshooting steps vary by plan Learn more →

    On a Teams plan?
    Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
    Link Git account →

    Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
    These require an Enterprise plan - Contact us
    Contact us →

    claude[bot] claude[bot] commented on Nov 12, 2026 15:53 UTC
    Bot

    Claude finished @smahelos's task in 24s —— View job

    ---

    Review of PR #89

  • Read the diff and the repository rules

  • Review the use cases, scope handling, requests and routes

  • Post inline comments
  • Summary

    I found no bugs or security problems in the diff. I only read the diff and did not run the tests or checks. The 2765-test result comes from the PR description, and I did not confirm it.

  • Authorization: the removal of …ForUser ports in favour of ReadScope / WriteScope is consistent. The new handlers (CreateExpense, UpdateExpense and the document-party queries) take the scope from the gate. The new allowed: route middleware names matching use cases. The new expense.create / expense.update permissions on the web guard have a catalog entry and a migration, as the add-permission workflow requires.

  • Admin expense update: the controller now merges the stored user_id and passes the stored contact id through $request->attributes. That removes the second, ungated read that keepsContact() did before, and a changed owner can no longer cause a not-found error.

  • Findings (2, both minor, inline):

  • 1. ExpenseFormFields disables $parties[0] by position. A lookup by field name would be safer. A test that posts an update without user_id would pin the controller's merge.
    2. CreateExpenseHandler checks the entity limit only after logo and attachment handling. Cleanup covers a failure, but an early check would skip the wasted work.
  • Tests: ExpenseUseCasesTest and InvoicePartiesAssemblerTest now run through the gate. I did not see a test for the new 403 when an admin stores an expense for an owner who lacks expense.create, nor for the picker routes' allowed: middleware. Please confirm those are covered.

  • Not verified: the PR notes it was not checked in a browser. The disabled-owner field on expense edit and the picker endpoints are the parts worth a manual look.
  • claude[bot] claude[bot] commented on code on Nov 12, 2026 15:53 UTC
    Code Review
    app/Infrastructure/Forms/Invoice/ExpenseFormFields.php:1
    @@ -114,13 +114,18 @@ public static function fields(array $countries, ?Expense $document): array
                 'name',
             );
             $fields['description']['wrapper'] = ['class' => 'form-group col-12'];
    +        $parties = AdminDocumentFormFields::parties('supplier', $document);
    +        if ($document !== null) {
    +            // The expense keeps the owner its parties belong to; update reads the stored one
    +            $parties[0]['attributes'] = ['disabled' => 'disabled'];

    $parties[0] assumes the owner field is always the first entry returned by AdminDocumentFormFields::parties(). If that order changes, the wrong field is disabled and nothing flags it. Look the field up by name (user_id) or have parties() take a lockOwner flag. A disabled field is also not submitted, so the update depends entirely on the controller's merge(['user_id' => ...]). A test that posts an update without user_id would pin that.

    claude[bot] claude[bot] commented on code on Nov 12, 2026 15:54 UTC
    Code Review
    app/Application/Invoice/Commands/CreateExpenseHandler.php:1
    @@ -0,0 +1,70 @@
    +<?php
    +
    +declare(strict_types=1);
    +
    +namespace App\Application\Invoice\Commands;
    +
    +use App\Application\Invoice\Services\DocumentLogoApplicationService;
    +use App\Application\Invoice\Services\ExpensePartiesAssembler;
    +use App\Application\Invoice\Support\ExpenseAttachments;
    +use App\Domain\Invoice\Contracts\ExpenseWriteRepositoryInterface;
    +use App\Domain\Invoice\DTO\ExpenseDTO;
    +use App\Domain\Party\Contracts\ContactReadRepositoryInterface;
    +use App\Domain\Party\Exceptions\ContactNotFoundException;
    +use App\Domain\Shared\Authorization\ValueObjects\WriteScope;
    +use App\Domain\Shared\Database\Contracts\TransactionBoundaryInterface;
    +use App\Domain\User\Enums\LimitedEntity;
    +use App\Domain\User\Services\EntityLimit;
    +
    +final class CreateExpenseHandler
    +{
    +    public function __construct(
    +        private readonly ExpenseWriteRepositoryInterface $writer,
    +        private readonly ExpensePartiesAssembler $parties,
    +        private readonly ContactReadRepositoryInterface $contacts,
    +        private readonly ExpenseAttachments $attachments,
    +        private readonly DocumentLogoApplicationService $logos,
    +        private readonly TransactionBoundaryInterface $transactions,
    +        private readonly EntityLimit $limits,
    +    ) {}
    +
    +    public function handle(CreateExpense $command, WriteScope $scope): ExpenseDTO
    +    {
    +        $data = $command->data;
    +        $contact = null;
    +        if ($data->contactId !== null) {
    +            $contact = $this->contacts->findById($data->contactId, $scope->read)
    +                ?? throw new ContactNotFoundException($data->contactId);
    +        }

    Nit: the entity limit is checked inside the transaction, after the logo and attachments are processed (saveWithLogo and the upload callback). A user over their limit still triggers logo handling and, depending on the order, uploads before assertCanCreate throws. The cleanup in ExpenseAttachments covers that, but a cheap early assertCanCreate before the uploads avoids the wasted work. Keep the in-transaction check for the race.

    smahelos smahelos commented on code on Nov 12, 2026 16:10 UTC
    Code Review
    app/Infrastructure/Forms/Invoice/ExpenseFormFields.php:1
    @@ -114,13 +114,18 @@ public static function fields(array $countries, ?Expense $document): array
                 'name',
             );
             $fields['description']['wrapper'] = ['class' => 'form-group col-12'];
    +        $parties = AdminDocumentFormFields::parties('supplier', $document);
    +        if ($document !== null) {
    +            // The expense keeps the owner its parties belong to; update reads the stored one
    +            $parties[0]['attributes'] = ['disabled' => 'disabled'];

    Fixed in e4c85298: AdminDocumentFormFields::parties() now disables the user_id field itself when it gets a stored document, so neither ExpenseFormFields nor AdminInvoiceFormFields depends on the field position any more. The controller merge is already pinned by editing_keeps_the_stored_owner_whatever_owner_is_submitted (it submits another owner and asserts the stored one is kept).

    smahelos smahelos commented on code on Nov 12, 2026 16:10 UTC
    Code Review
    app/Application/Invoice/Commands/CreateExpenseHandler.php:1
    @@ -0,0 +1,70 @@
    +<?php
    +
    +declare(strict_types=1);
    +
    +namespace App\Application\Invoice\Commands;
    +
    +use App\Application\Invoice\Services\DocumentLogoApplicationService;
    +use App\Application\Invoice\Services\ExpensePartiesAssembler;
    +use App\Application\Invoice\Support\ExpenseAttachments;
    +use App\Domain\Invoice\Contracts\ExpenseWriteRepositoryInterface;
    +use App\Domain\Invoice\DTO\ExpenseDTO;
    +use App\Domain\Party\Contracts\ContactReadRepositoryInterface;
    +use App\Domain\Party\Exceptions\ContactNotFoundException;
    +use App\Domain\Shared\Authorization\ValueObjects\WriteScope;
    +use App\Domain\Shared\Database\Contracts\TransactionBoundaryInterface;
    +use App\Domain\User\Enums\LimitedEntity;
    +use App\Domain\User\Services\EntityLimit;
    +
    +final class CreateExpenseHandler
    +{
    +    public function __construct(
    +        private readonly ExpenseWriteRepositoryInterface $writer,
    +        private readonly ExpensePartiesAssembler $parties,
    +        private readonly ContactReadRepositoryInterface $contacts,
    +        private readonly ExpenseAttachments $attachments,
    +        private readonly DocumentLogoApplicationService $logos,
    +        private readonly TransactionBoundaryInterface $transactions,
    +        private readonly EntityLimit $limits,
    +    ) {}
    +
    +    public function handle(CreateExpense $command, WriteScope $scope): ExpenseDTO
    +    {
    +        $data = $command->data;
    +        $contact = null;
    +        if ($data->contactId !== null) {
    +            $contact = $this->contacts->findById($data->contactId, $scope->read)
    +                ?? throw new ContactNotFoundException($data->contactId);
    +        }

    Keeping the single check inside the transaction. assertCanCreate locks the owner's users row (SELECT … FOR UPDATE) and holds it until the insert commits; an early check outside the transaction would only duplicate it, and .claude/rules/permissions.md keeps the limit check once, inside the transaction. Attachments are uploaded after the check: $attachments() runs inside the transaction after assertCanCreate. Only the logo store/copy precedes it, and saveWithLogo deletes it in its finally when the save fails.

    claude[bot] claude[bot] commented on Nov 12, 2026 16:10 UTC
    Bot

    Claude finished @smahelos's task in 15s —— View job

    ---

    Review of PR #89

    I read the diff and the rules in AGENTS.md. I did not run the tests or the checks, so the 2765-test result is taken from the PR description.

    No new bugs or security problems found.

  • Scope and gate: the …ForUser ports are replaced by ReadScope / WriteScope. CreateExpense and UpdateExpense use permissionWithOwner and run through the gate. CreateExpense implements CallsOutsideDatabaseInterface because it uploads files, and its handler opens the transaction only around the writes. The entity limit is checked inside that transaction, as application.md and permissions.md require.

  • Routes: the picker and items routes have allowed: middleware naming the use case their action runs. This matches the existing GetEntityUsage pattern.

  • Expense update: the controller merges the stored user_id and passes the stored contact id through AdminDocumentPartyInput::STORED_CONTACT. This removes the second, ungated read.

  • Permissions: expense.create and expense.update have a PermissionCatalog entry and a sync migration, with an empty down() as the PR describes.
  • Open points

    1. The earlier inline comments on ExpenseFormFields ($parties[0] is positional) and on CreateExpenseHandler (the limit check runs after the file handling) still apply. Both are minor, and neither blocks the merge.
    2. I did not see tests for these changes. Please confirm they exist, since the PR describes both as behaviour changes:
    - the 403 when an admin stores or updates an expense for an owner without the expense permission;
    - an expense update posted without user_id, which depends on the controller's merge.
    3. The allowed: middleware on the picker and items routes is untested as far as I can see. A test that a user lacking the invoice and expense permissions gets 403 would pin it.
    4. The admin edit page with the disabled owner field and the picker endpoints were not checked in a browser. Those are worth a manual look.

    smahelos smahelos commented on Nov 12, 2026 17:43 UTC
    Author

    Re-review follow-up:

    1. The two inline findings were answered before this re-review finished: the positional $parties[0] is fixed in e4c85298 (AdminDocumentFormFields::parties() disables user_id itself), and the early limit check is declined with the reason in the thread.
    2. Tests of the expense behaviour changes:
    - An update without user_id relies on the controller merge, pinned by editing_keeps_the_stored_owner_whatever_owner_is_submitted (it submits another owner and asserts the stored one is kept).
    - The 403 for an owner without the expense permission was missing; added in 6f9f3d31 as an_owner_without_a_plan_role_gets_no_expense_whatever_the_admin_may_do. It fails (302) when CreateExpense declares Access::permission instead of permissionWithOwner.
    3. The allowed: middleware on the picker and items routes is covered by DocumentPartyCrudControllerTest::guests_and_users_without_document_permissions_cannot_search and InvoiceItemsControllerTest::catalog_and_preview_require_invoice_permission.

    claude[bot] claude[bot] commented on Nov 12, 2026 17:43 UTC
    Bot

    Claude finished @smahelos's task in 10s —— View job

    ---

    Review of PR #89 (after the latest two commits)

    I read the new commits e4c8529 and 6f9f3d3. I did not run the tests or checks.

    No new bugs or security problems found.

  • e4c8529: AdminDocumentFormFields::parties() now disables user_id itself when it gets a stored document. ExpenseFormFields and AdminInvoiceFormFields no longer depend on field position. This resolves my earlier $parties[0] comment.

  • 6f9f3d3: the new test covers the 403 when an admin stores an expense for an owner without the expense permission. This resolves my earlier test question for the store case.

  • CreateExpenseHandler limit check: your reasoning holds. assertCanCreate locks the owner row and belongs once inside the transaction (permissions.md). I'm withdrawing the nit.
  • Remaining, minor and non-blocking

    1. The new 403 test only covers store. Please confirm the update path for an owner without the permission is covered somewhere, since the PR describes both.
    2. I did not see a test for the allowed: middleware on the picker and items routes (403 for a user without the invoice and expense permissions).
    3. The disabled owner field on the expense edit page and the picker endpoints were not checked in a browser.

    claude[bot] claude[bot] commented on Nov 12, 2026 17:48 UTC
    Bot

    Claude finished @smahelos's task in 10s —— View job

    ---

    Review of PR #89 (after commit 122ee1d)

    I read the new commit. I did not run the tests or checks.

    No new bugs or security problems found.

  • 122ee1d: an_update_for_an_owner_without_a_plan_role_is_refused puts an update for an owner without the expense permission. It asserts a 403 and that the stored description is still Kept. This closes my earlier question about the update path, so the 403 is now covered for both store and update.

  • Earlier open points: you pointed to the existing tests for the allowed: middleware on the picker and items routes (guests_and_users_without_document_permissions_cannot_search and catalog_and_preview_require_invoice_permission). I accept that.
  • Still open (not blocking): the disabled owner field on the expense edit page and the picker endpoints were not checked in a browser. They are worth a quick manual look before merge.

    claude[bot] claude[bot] commented on Nov 12, 2026 18:04 UTC
    Bot

    Claude finished @smahelos's task in 9s —— View job

    ---

    Review of PR #89 (after commit ddb240e)

    I read the new commit. I did not run the tests or checks.

    No new bugs or security problems found.

  • ddb240e: a docs-only change. It adds a docs/TECH_DEBT.md entry for the two admin browser scripts that fail on main, with where, problem and fix. It matches the file's existing format and the policy that rule violations and known debt are tracked there. It touches no code or tests.

  • Earlier open points: all code findings are resolved (the $parties[0] position, the 403 tests for store and update, the allowed: route tests). I accepted the limit-check reasoning earlier.
  • Still open (not blocking): the disabled owner field on the expense edit page and the picker endpoints were not checked in a browser. The new debt entry says the browser scripts for admin document forms currently fail, so a manual look before merge is the only browser check available.

    smahelos smahelos commented on Nov 12, 2026 18:09 UTC
    Author

    Manual browser check (branch at ddb240e1 code, billex-dev.local, development data, signed in as the admin):

  • Expense edit (/admin/expense/1/edit, owner User 1): the owner select is disabled and shows the stored owner; business, contact and account load from the stored expense.

  • Picker endpoints: document-parties/businesses, contacts (also by id) and accounts (of a business and of a contact) answer 200 with the owner's records; a request without user_id answers 422.

  • Contact search in the form: typing into the contact select calls document-parties/contacts?q=… (200) and lists the owner's contacts; the previous request is aborted by Select2 while typing, as expected.

  • Not checked: submitting the form in the browser (covered by the feature tests). The scripts in tests/Browser/ fail the same way on main, see the new docs/TECH_DEBT.md entry.
  • Reviewers
    Assignees
    smahelos smahelos
    Labels
    risk: low confidence: 84.2% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 85.5% (HIGH) · Higher = larger blast radius
    85.5%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 84.2% · Lower = rushed or shallow review
    84.2%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 13.5% · Safe to merge
    13.5%