Commit Graph
37 Commits
Author SHA1 Message Date
Adam DaleyandCopilot Autofix powered by AI c4c648c2a6 Fixes for 2 code quality findings in Twig EdgeCaseRendering tests (#3916)
* Apply suggested fix to tests/Unit/FOSSBilling/Twig/EdgeCaseRenderingTest.php from Copilot Autofix

Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com>

* Apply suggested fix to tests/Unit/FOSSBilling/Twig/EdgeCaseRenderingTest.php from Copilot Autofix

Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com>

---------

Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com>
2026-07-06 23:44:59 +01:00
Adam Daley d144dfdc07 Attach PDF invoices to invoice emails (#3913)
* Attach PDF invoices to invoice emails (#1724)

Adds generic file-attachment support to the email pipeline (Mail, QueuedEmail,
Email\Service) and wires it into invoice notifications via a new
"Attach PDF Copy to Invoice Emails" setting, so clients who pay by bank
transfer can view the invoice without logging in.

Also carries the same attachment into the sent-email activity log so a
later "resend" (client or admin) reattaches the PDF instead of dropping it.

* Address PR review: avoid blob hydration in email history list, fix checkbox uncheck

- ActivityClientEmailRepository::getSearchQueryBuilder() now selects a partial
  entity that excludes attachment_content, so the paginated admin/client email
  history list no longer hydrates every PDF into memory just to render
  has_attachment. Verified against a real Doctrine EntityManager that the DQL
  parses, the generated SQL excludes the blob column, and toApiArray() still
  works correctly on the partial entity.
- mod_invoice_settings.html.twig: add the hidden-input-before-checkbox pattern
  already used elsewhere in this codebase (e.g. mod_client_new_form.html.twig),
  so unchecking "Attach PDF Copy to Invoice Emails" actually persists as
  disabled instead of being silently dropped from the form submission.
2026-07-06 23:32:12 +01:00
Adam Daley c8cd721e49 Fix cron settings defaults (#3911) 2026-07-06 22:08:46 +01:00
Adam Daley 800a7456d8 Stop mapping timers before debugbar collection (#3907)
* Stop mapping timers before debugbar collection

* Fix DebugBar timing PHPStan type

* Refactor timing measure stop checks in Box_App
2026-07-06 19:55:33 +01:00
Adam Daley 9ea2095ce1 Allow admins to edit ticket replies, with edit history (#3906)
* Allow admins to edit ticket replies, with edit history (#2317)

Admins previously had no way to fix a typo or correct a reply without
editing the database directly. Adds an Edit action to admin-authored
messages in the admin ticket view; client-authored messages remain
uneditable so an admin can never alter a client's own words.

Every edit snapshots the message's prior content into a new
support_ticket_message_history table before overwriting it, so the
original wording sent to a client is never silently lost. Admins can
view a message's revision history via a lazy-loaded modal.

Also fixes ticket_message_update, which existed but was never wired
into any UI and skipped the markdown sanitization that ticket_reply
already applies.

* Bump fresh-install last_patch to 83

Fresh installs seed last_patch from content.sql so the patcher doesn't
try to reapply migrations already baked into structure.sql. Missed
bumping this when patch83 (support_ticket_message_history) was added.

* Fix message history modal getting stuck on Loading... after a failed fetch

dataset.loaded was set before the API call resolved, so a failed
request left the modal permanently stuck on "Loading..." with no way
to retry short of a page reload. Move the flag to the success
callback and add an error handler that shows a retryable message.

* Make support_ticket_message_history.support_ticket_message_id required

A history row is meaningless without the message it snapshots; allowing
NULL let orphaned rows exist. Tightened the column in patch84,
structure.sql, and the entity's JoinColumn to NOT NULL.

* Delete message edit history when a ticket is removed

Service::rm() explicitly removes a ticket's notes and messages rather
than relying on the entity mapping's onDelete: CASCADE, because this
schema has no real FK constraints anywhere (referential integrity is
handled at the application layer throughout this codebase). History
rows were missed by that pattern and were left orphaned after a ticket
delete. Now removed alongside their message, following the same
explicit-cleanup convention as notes/messages.

Also cache SupportTicketMessageHistoryRepository via setDi(), matching
every other repository on this service, and add direct coverage for
getMessageHistory().
2026-07-06 19:01:45 +01:00
Adam DaleyandCopilot Autofix powered by AI 3763246051 Fixes for 2 code quality findings in Twig FOSSBillingExtension tests (#3904)
* Apply suggested fix to tests/Unit/FOSSBilling/Twig/Extension/FOSSBillingExtensionTest.php from Copilot Autofix

Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com>

* Apply suggested fix to tests/Unit/FOSSBilling/Twig/Extension/FOSSBillingExtensionTest.php from Copilot Autofix

Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com>

---------

Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com>
2026-07-06 17:33:35 +01:00
Adam DaleyandCopilot Autofix powered by AI d90ff52052 Fix for 1 code quality finding in i18n tests (#3903)
Apply suggested fix to tests/Unit/FOSSBilling/i18nTest.php from Copilot Autofix

Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com>
2026-07-06 17:25:16 +01:00
Adam DaleyandCopilot Autofix powered by AI 114dc23714 Fixes for 2 code quality findings in i18n tests (#3901)
* Apply suggested fix to tests/Unit/FOSSBilling/i18nTest.php from Copilot Autofix

Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com>

* Apply suggested fix to tests/Unit/FOSSBilling/i18nTest.php from Copilot Autofix

Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com>

---------

Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com>
2026-07-05 04:29:38 +01:00
Adam Daley 85fa3dc1b2 Refactor HTTP helpers and inject Filesystem via DI (#3900)
* Remove redundant HTTP helper wrappers

* Inject Filesystem via DI across services

* Fix constructor and Theme DI wiring
2026-07-05 04:07:54 +01:00
Adam DaleyandCopilot Autofix powered by AI d96d6646e7 Fix for 1 code quality finding in i18n tests (#3898)
Apply suggested fix to tests/Unit/FOSSBilling/i18nTest.php from Copilot Autofix

Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com>
2026-07-05 03:07:55 +01:00
Adam DaleyandCopilot Autofix powered by AI 8d0c068b8b Fixes for 2 code quality findings in i18n tests (#3897)
* Apply suggested fix to tests/Unit/FOSSBilling/i18nTest.php from Copilot Autofix

Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com>

* Apply suggested fix to tests/Unit/FOSSBilling/i18nTest.php from Copilot Autofix

Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com>

---------

Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com>
2026-07-05 02:54:28 +01:00
Adam Daley fcae50dbc5 Add per-user timezone support across the app (#3895)
* Add per-user timezone support across app

* Bump install DB last_patch to 81

* Address timezone review findings

* Fix uninitialized variable warnings in Email

* Consolidate validation and fix PHPStan variable init

- Hoist the template parse above the recipient dispatch so
  $subject/$content are always defined before use (CI PHPStan
  caught them as potentially undefined in the elseif branches).
- Address timezone review feedback
2026-07-05 02:42:38 +01:00
Adam DaleyandCopilot Autofix powered by AI 9b35d576d7 Apply suggested fixes from Copilot Autofix across multiple files (#3896)
* Apply suggested fix to src/modules/Invoice/tests/Unit/ServiceTest.php from Copilot Autofix

Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com>

* Apply suggested fix to src/modules/Invoice/tests/Unit/ServiceTest.php from Copilot Autofix

Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com>

* Apply suggested fix to src/modules/Massmailer/Service.php from Copilot Autofix

Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com>

* Apply suggested fix to src/modules/Staff/tests/Unit/Api/AdminTest.php from Copilot Autofix

Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com>

* Apply suggested fix to tests/Unit/FOSSBilling/ResponseFactoryTest.php from Copilot Autofix

Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com>

* Fix file/download response content disposition

---------

Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com>
2026-07-05 02:32:47 +01:00
Adam Daley 102e97bd61 Modernize HTTP routing and response handling (#3892)
* Modernize Box app HTTP routing

* Use response factory for module redirects

* Clean up IPN response handling
2026-07-05 00:54:07 +01:00
Adam Daley d7f0ed20a5 Refactor HTTP helpers and centralize response handling (#3877)
* Refactor API request/response HTTP helpers

* Centralize exception and response handling

* Use ResponseEmitter in installer entrypoints

* Add HTTP ResponseFactory and refactor Box_App

* Extract route matching into HTTP matcher

* Fix route param parsing and remove UrlHelper

* Fix exception status code crash and clean up refactor leftovers

ApiResponseFactory::getStatusCode() required an int code, but
Throwable::getCode() can return a string (e.g. PDOException's SQLSTATE),
so any non-FOSSBilling exception with a non-integer code crashed API
error handling with a TypeError instead of returning a JSON error.
Numeric-string codes are normalized to int to preserve prior loose-
comparison behavior; non-numeric codes fall back to the default status.

Also removes now-dead ErrorPage::generatePage(), redundant manual
requires of ResponseEmitter (already covered by composer's classmap
autoload), and duplicate emitResponse() calls in exceptionHandler().
2026-07-02 22:20:10 +01:00
Adam Daley 1efffee98b Handle Twig render failures as 500 errors (#3874)
* Handle Twig render failures as 500 errors

* Fix nested Twig loader error handling

* Fix AppClient missing page test stub
2026-07-02 11:48:08 +01:00
FOSSBilling BotandFOSSBilling Bot ff38258781 Apply PHP Code Styling & Quality Changes (#3858)
Co-authored-by: FOSSBilling Bot <fossbilling-bot>
2026-06-28 20:36:07 +01:00
Adam Daley 719d002005 Handle Stripe invoice paid webhook and normalize currencies (#3857)
* Handle Stripe invoice.paid webhook and normalize currencies

* Handle Stripe webhooks asynchronously

* Update cspell.json

* Handle all Stripe webhook event types

* Handle Stripe invoice subscription changes

* Handle Stripe subscription race conditions

* Filter Stripe webhook noise

* Handle Stripe subscription races safely

* Improve Stripe subscription creation

* Add 4/5-year periods and new tx statuses

* Harden Stripe dedup for redirect/webhook races

* Address code review findings in Stripe webhook and IPN handler

- Fix: handlePaymentIntentFailedWebhook and handleSetupIntentFailedWebhook
  now return true so error transactions are kept rather than written and
  immediately deleted; processWebhookEvent guards against overwriting an
  existing STATUS_ERROR with STATUS_PROCESSED
- Fix: processInitialSubscriptionPayment reloads the invoice from the DB
  before the already-paid guard, consistent with applyOneTimePayment and
  narrowing the TOCTOU race window
- Fix: handleInvoicePaymentSucceeded merges two sequential findOne queries
  for the same invoice into one, using the result for both the already-paid
  check and the billing_reason fallback
- Fix: ipn.php extracts $isJsonWebhook at first evaluation, removing the
  duplicate str_contains() expression inside the try block
- Fix: handleSubscriptionCreated casts invoice_id to int, matching all
  other handlers; test assertion updated from string '5' to int 5

* Fix double-processing and over-broad exception catch in Stripe adapter

- handleInvoicePaymentSucceeded: set txn_id to the Stripe invoice ID and
  check for an existing PROCESSING/PROCESSED transaction with that key so
  that when Stripe fires both invoice.payment_succeeded and invoice.paid
  for the same payment, the second event is silently skipped rather than
  double-crediting the client balance or generating a duplicate renewal
  invoice
- processSetupIntent, handleSetupIntentSucceededWebhook: narrow the
  ApiErrorException catch to idempotency_key_in_use only; rethrow all
  other failures (card declined, auth errors, network issues) so they are
  not silently swallowed and processed against an unrelated subscription

* Fix missing Transaction findOne mock in StripeTest fallback test

The handleInvoicePaymentSucceeded dedup check now queries for an
existing Transaction by Stripe invoice ID before processing. The
'falls back to treating unpaid original invoice as initial payment'
test only mocked the Invoice findOne, so the new Transaction query
had no handler and threw NoMatchingExpectationException in CI.

* Fix spellcheck: replace 'Dedup' with 'Duplicate-event' in comment
2026-06-28 20:01:05 +01:00
Adam DaleyandCopilot Autofix powered by AI c5a6c56d4b Fix for 1 code quality finding in Twig tests (#3855)
Apply suggested fix to tests/Unit/FOSSBilling/Twig/StrictVariablesTest.php from Copilot Autofix

Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com>
2026-06-28 09:56:01 +01:00
Adam DaleyandCopilot Autofix powered by AI e01b33ccfe Fixes for 5 code quality findings in Servicehosting (#3854)
* Apply suggested fix to src/modules/Servicehosting/tests/Unit/ServiceTest.php from Copilot Autofix

Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com>

* Apply suggested fix to src/modules/Servicehosting/tests/Unit/ServiceTest.php from Copilot Autofix

Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com>

* Apply suggested fix to src/modules/Servicehosting/tests/Unit/ServiceTest.php from Copilot Autofix

Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com>

* Apply suggested fix to src/modules/Servicehosting/tests/Unit/ServiceTest.php from Copilot Autofix

Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com>

* Apply suggested fix to src/modules/Servicehosting/tests/Unit/ServiceTest.php from Copilot Autofix

Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com>

* Fix hosting service creation test

* Simplify strict variable test assertions

---------

Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com>
2026-06-28 09:33:05 +01:00
Adam DaleyandClaude Sonnet 4.6 aefaa01db6 Preserve < and > in ticket/KB messages by using Markdown-safe sanitization (#3830)
* fix(support): preserve < and > in ticket/KB messages by using Markdown-safe sanitization

The WYSIWYG editor (CKEditor) uses the Markdown plugin, so ticket replies
and KB article bodies are stored as Markdown, not HTML. Calling the Symfony
HTML Sanitizer on Markdown content silently corrupts it: when a user types
text containing an unknown tag-like string such as `<World>`, the sanitizer
treats it as an unknown HTML element, drops it, and—because there is no
closing tag—also drops everything that follows, causing the rest of the
message to disappear.

Fix by introducing `Tools::sanitizeMarkdownContent()`, which only strips
null bytes and trims whitespace. XSS protection is already provided at
render time by the `|markdown_to_html` Twig filter, whose underlying
CommonMark converter is configured with `html_input: escape`—any raw HTML
inside the stored Markdown is therefore escaped before it reaches the
browser.

Affected endpoints (all now use the new helper):
- Admin: ticket_reply, ticket_create, kb_article_create, kb_article_update
- Client: ticket_create, ticket_reply
- Guest: ticket_create, ticket_reply

Fixes #3827

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LBnxaZxj968uFFbgoSocLZ

* fix(spellcheck): use American English spelling "unrecognized"

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LBnxaZxj968uFFbgoSocLZ

* fix(support): apply markdown-body styling to admin ticket and client KB article views

The admin ticket conversation and client KB article content were rendered
with |markdown_to_html but without the markdown.css stylesheet or the
markdown-body CSS class required by github-markdown-css.  This caused
inline code, fenced code blocks, and other Markdown elements to appear
unstyled (admin) or miscontainerised in a list-group div (client KB).

- Admin ticket: load markdown.css in <head> and wrap message content in
  <article class="markdown-body bg-transparent text-reset">
- Client KB article: load markdown.css in <head> and replace the
  list-group wrapper with <article class="markdown-body bg-transparent
  text-reset">

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LBnxaZxj968uFFbgoSocLZ

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-23 19:22:41 +02:00
Yağızhan Burak YakarandAdam Daley 7ade5bbdf3 Unify public tickets with client tickets (#3799)
* Merge public ticket logic into regular client tickets

* Unified email templates

* Unified events and listeners

* Remove passthrough service methods

* Corrected phpDocs

* Create a combined `author` array to replace `client`, `client_id`, `author_name`, `author_email`

* Switch to using "Author" instead of "Requester"

* Switch to using a single endpoint and single template for client and guest tickets

Also left a redirect behind to make sure previously sent emails still have a working link

* Add author_role parameter to onBeforeClientOpenTicket

* Adjusted rate limit ordering

* Update Twig templates and the update patcher

* "Public ticket" -> "Guest ticket"

* Addressed code review comments

* Address code review comments

* Also purge old pticket email templates

* Fix email sending

* Support: enforce auth, fix guest email links

* Migrate mod_support config key name

---------

Co-authored-by: Adam Daley <admdly@users.noreply.github.com>
2026-06-19 19:01:52 +01:00
Adam Daley febec281a6 Migrate product models and enhance promo redemption functionality (#3587)
* Migrate product models; add `promo_redemption`

* Add DomainPricing & ProductOrder repositories

* Use Promo entity typehints and update tests

* Use DI logger, validate order config, update tests

* Replace `error_log` with logger; use stubs in tests

* Use attachOrderConfig and tighten service checks

* Clarify domain defaults and remove deprecated doc tag

* Add missing indexes to `promo_redemption` table

* Enrich promo API arrays and add redemption filters

* Various UI/JS fixes and template cleanups

* Log invoice issues as warnings; expose form_id

* Normalize spelling in UpdatePatcher comment

* Remove checkLimits production method and clean up stale test mocks

* Use getConfig() and add promo permission

* Use container logger directly, remove helpers

* Use defaults for optional Twig settings

* Import macro_functions into admin template

* Compensate promo redemptions on checkout failure

* 🐛 Fix product category and add-on availability handling
2026-06-18 17:56:14 +01:00
Adam Daley a56767e1fc Fix API permission identity forwarding and IPN subscription/deposit payment handling (#3788)
* Add AbstractApi::checkPermissions and patch71

* Bump last_patch setting to 71

* Add tests for AbstractApi::checkPermissions

* Handle subscription renewals and validate payments

* Add overpayments to cspell word list

* Treat null transaction amounts as 0

* Mark deposit invoices as paid; add unit test

* Test overpayment warnings in validatePaymentAmount
2026-06-16 20:33:47 +01:00
FOSSBilling BotandFOSSBilling Bot 638d8a5015 Apply PHP Code Styling & Quality Changes (#3771)
Co-authored-by: FOSSBilling Bot <fossbilling-bot>
2026-06-14 14:15:33 +01:00
Adam Daley fbfb7746f4 Render email example and add tests for Twig tags (#3764)
* Render email example verbatim and add test

* Fix typo and prevent raw Twig apply tags in sample

* Update cspell.json
2026-06-13 02:57:32 +01:00
Adam DaleyandCopilot Autofix powered by AI b73e4ce09c Replace legacy icons and standardize SVG icon markup (#3758)
* Replace legacy icons and add icon sprite generator

* Update package-lock.json

* Standardize SVG icon markup and fallback

* Render client email as plain text

* Fix for pull request finding 'Unused variable, import, function or class'

Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com>

* Add dedicated email signature for templates

* Fix Huraga SVG sprite theme resolution (#3760)

🐛 Fix SVG sprite theme resolution

---------

Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com>
2026-06-12 02:14:40 +01:00
Adam Daley c50725cd3a Persist selected period in product configuration (#3754)
* Persist selected period in product config

* Add period default to edgeCaseRequest
2026-06-11 19:44:50 +01:00
Adam Daley 219ad9c79a Enhance email templates and Twig templates with defaults (#3753)
* Quote avatar data URI; add .db-avatar styles

* Pagination partial - require url & append hash

* Use defaults in email templates; add delay msg

* Guard Twig template vars with default()

* Replace arrow fn with static closure in test

* Add defaults to email templates and Twig policy

* Guard Twig templates with default filters

* Assert no strict-variable findings with toBeEmpty

* Guard email templates against missing order data

* Make activated_at null-safe in email templates

* 🐛 Use admin recipient in staff reset emails
2026-06-11 19:19:12 +01:00
FOSSBilling BotandFOSSBilling Bot 3c6ab0bd4f Apply PHP Code Styling & Quality Changes (#3739)
Co-authored-by: FOSSBilling Bot <fossbilling-bot>
2026-06-09 19:17:44 +01:00
Adam Daley 5ecfeb335e Harden templates and API responses against missing data (#3730)
* Guard Activity index template against missing client/staff nested data

The activity log API at Activity/Api/Admin.php:38-49 only injects a
nested 'client' or 'staff' key when the corresponding *_id is set
(via isset() which returns false for null). System events and
client-only events therefore have no 'client' key, while staff-only
events have no 'client' key.

Under strict_variables, '{% if event.client %}' (line 191) throws
"Key 'client' ... does not exist" for any event without a client.

Switch the conditional to event.client_id / event.staff_id (always
present as SQL columns) and add '|default("")' to the nested
event.client.email / event.client.name / event.staff.email / event.staff.name
accesses so deleted-but-referenced records render gracefully.

* Guard Security iplookup template against empty country/asn data

When the GeoIP or ASN lookup fails (IncompleteRecord from MaxMind), the
Service catches and substitutes [] for the missing data. Under
strict_variables, the empty mapping at record.asn / record.country
causes line 48 to throw "sequence/mapping is empty".

Twig's |default filter on a GetAttrExpression compiles to a safe
is-defined check, so it correctly falls through to the placeholder
when the underlying array is empty or the key is missing.

Verified:
- /admin/security/iplookup?ip=192.168.1.1 (private IP, empty asn)
  renders the row with 'Unknown' ASN cells.
- /admin/security/iplookup?ip=8.8.8.8 still renders
  '15169' / 'GOOGLE' / 'United States'.

* Initialize notes/rel arrays in Support toApiArray so templates render without errors

Two related issues surfaced under strict_variables on the admin support
ticket page:

1. toApiArray only set $data['notes'] inside the foreach loop over
   ticket notes. Tickets without any notes therefore had no 'notes' key
   and 'ticket.notes|length' in mod_support_ticket.html.twig:42 threw
   'Key "notes" does not exist'.

2. _getRelDetails returned [] (empty array) when a ticket has no
   related entity. mod_support_ticket.html.twig sets {% set task =
   ticket.rel %} and then accesses task.task, task.type, task.status
   etc. on the next lines. Any access into an empty mapping throws
   under strict_variables.

Fixes:
- Service::toApiArray: always initialize $data['notes'] = [] for admin
  identity so the key is present even when empty.
- Service::_getRelDetails: always return the base structure with all
  fields (id, type, task, new_value, status) set to null when there
  is no related entity. Skip the DB lookups for the non-rel case.

Template hardening (defense-in-depth, in case other code paths return
a different shape):
- mod_support_ticket.html.twig:42: 'ticket.notes|length' -> 'is defined and
  ticket.notes|length'.
- mod_support_ticket.html.twig:222: 'ticket.notes' -> 'ticket.notes|default([])'.
- mod_support_tickets.html.twig:238: same is defined guard.

Verified on dev:
- /admin/support/ticket/1 renders without errors.
- API now returns rel as {id: null, type: null, ...} and notes: [] for
  tickets without related data.
- 1777 local tests pass, PHPStan clean.

* Harden tests and add Twig/ToApi linters

* Remove redundant setAccessible calls in tests

* Update cspell.json word list

* Add UrlAwarePermissiveContainer & trim errors

* Add geoip stub and fix ParserFactory usage

* Enforce and apply parentheses for new expressions
2026-06-06 18:32:19 +01:00
Adam Daley e8db6000ad Simplify tests and suppress notices in renderer (#3729) 2026-06-06 10:49:59 +01:00
Adam DaleyandCopilot Autofix powered by AI 7baa28e22f Enhance Twig strict variables handling and improve test coverage (#3721)
* Import template macros and fix invoices tab id

* Handle nulls in Twig extensions and add tests

* Enable Twig strict_variables and add tests

* Improve Twig strict-variables test harness

Fix several undefined-variable issues in admin templates and harden the strict-variables test harness.

- Templates: guard against missing variables by using default() for order_actions and checking header/type in partial_extensions.twig.
- Loader: CombinedTwigLoader now registers theme and module template paths with namespaces (module_area), and includes email template directories.
- Variable collection: VariableCollectorVisitor now collects keys passed via {% embed %} and {% include %} with { ... } so embedded templates get proper stubs.
- Renderer: StrictTemplateRenderer gains better relative template naming for module templates, additional logging for kb_article parsing, and broader classification of render errors as test-infra (typed-return mismatches, NumberFormatter issues, callable/iterable errors, loader quirks) to reduce false positives.
- Tests: add baseline marker files for strict findings, adjust StrictVariablesTest to treat infra findings as informational while failing on real-bug findings, and write findings JSON for review.

Overall these changes reduce noise from the render-everything harness and make the strict-variables suite more robust and actionable.

* Bump test memory limit to 2G via ini_set in bootstrap

The strict-variables render-everything harness parses every FOSSBilling
template and allocates many stubs and AST nodes, which exceeds the
default 128M limit and causes the pest process to exit with 255
mid-suite. Setting the limit in tests/Pest.php means it applies to both
local 'composer test' and CI 'pest --ci' invocations without needing
to modify the workflow file.

* Fix for pull request finding

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* Fix for pull request finding

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* Fix for pull request finding

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* Fix for pull request finding

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* Fix for pull request finding

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* Fix for pull request finding

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* Fix for pull request finding

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* Scope error_reporting suppression to the render-everything harness

* Replace unsupported 'now' Twig global with 'now'|date filter

The reserved 'now' Twig global is only defined in some contexts and is
not present in the install or admin email-template environments. Under
strict_variables it throws a fatal 'Variable "now" does not exist'
error, which crashes the installer and the email template playground.

Both call sites use the date filter to format the current year, so the
correct fix is to feed the filter a string literal: 'now'|date('Y').
This is the same pattern we used for the admin_default and huraga theme
layouts.

Discovered by hitting the install page on the dev instance after the
strict_variables rollout.

* Make sitemap tolerant of missing product.updated_at

The product guest API (Box\Mod\Product\Service::toApiArray) returns
updated_at only for admin requests, not for guests. The sitemap uses
the guest API, so product.updated_at was always undefined for it.

Before strict_variables this was harmless: the date filter silently
returned null and the template rendered. With strict_variables enabled,
the missing key throws 'Key updated_at does not exist', which
get_custom_page catches and converts to a 404.

Pipe through |default('now') so we fall back to the current date when
the field is missing, while still using the real value when present.

Discovered by the live test 'urls return ok status' failing on sitemap.xml
in CI.

* Remove stray blank line in StrictTemplateRenderer

* Fix four templates for strict_variables Cypress failures

The Cypress tests run against a fresh install with strict_variables
enabled, which catches undefined key access in templates that the
non-strict mode silently allowed.

1. mod_invoice_index.html.twig:432
   productId is a JavaScript variable, not a Twig variable. The
   Twig expression tried to evaluate it server-side and threw
   'Variable productId does not exist'. Build the URL with JS
   template literal interpolation instead.

2. mod_client_profile.html.twig:158
   guest.client_custom_fields is not a real field in the guest
   API response. The current lookup threw 'sequence/mapping is
   empty' when no custom fields exist. Default to an empty
   mapping, then null, and add a truthy guard.

3. mod_support_ticket.html.twig:60
   ticket.rel_type is only populated for tickets linked to an
   order; the guest response omits it otherwise. Default to
   empty string so the comparison still works.

4. mod_support_ticket.html.twig:80
   message.author exposes only name and role for client-side
   messages, no email. Pass through |default('') so the avatar
   function gets a string and renders its fallback.

* Fix client invoice page for strict_variables

The tab labels on the client invoice index reference
unpaid_invoices.total and paid_invoices.total on lines 33/37
to show count badges, but the corresponding {% set %} calls
sit inside the table bodies on lines 53/85. Under
strict_variables this throws 'Variable unpaid_invoices does
not exist' before the lists are ever fetched.

Move both fetches to the top of the content block so the
variables are defined when first read.

* Allow guest checkout rendering under strict vars

* Rename test helper and tweak test expectations

* Guard optional adapter form fields in gateway and build_form templates

The admin payment gateway edit page and the domain registrar build_form
macro both test element[1].description directly in an if condition,
and both read gateway.config[name] / values[name] without a default.
Built-in adapters (Stripe, PayPalEmail, Custom, the Custom registrar)
define form fields with only a label and sometimes validators or
required_when, so on a fresh install the page throws:

  Key 'description' for sequence/mapping with keys 'label, validators'
  does not exist in 'mod_invoice_gateway.html.twig' at line 115.

The outer '?? ''' on the inner expression does not help: the
exception is thrown when evaluating the if condition, not when
rendering the markdown. With strict_variables on, that becomes a 500.

Replace each 'if element[1].description' with the short-circuit
'is defined and ...' pattern already used in the same file for
required_when, and drop the now-redundant '?? ''' from the inner
expression. Guard the gateway.config[name] / values[name] reads
with |default('') (or |default([]) for the iterable check) so
fields that have not been configured yet do not throw on a fresh
or upgraded install.

Verified on the dev instance:
  /admin/invoice/gateway/{1,2}        HTTP 200
  /admin/servicedomain/registrar/{1,2} HTTP 200
PayPal gateway form save+reload round-trips correctly.

* Fix for pull request finding

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* Fix for pull request finding

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

---------

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-06-06 08:53:52 +01:00
CopilotandAdam Daley ad3a4fe3f4 Fix ApiResponse DRY violation, tighten wasSuccessful() check, and wire email test to Validate class (#3711)
* Initial plan

* Fix duplicate getHttpCode/getStatusCode, improve wasSuccessful result check, and test email validation via Validate class

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: Adam Daley <admdly@users.noreply.github.com>
2026-06-03 16:20:16 +01:00
83949ce8f0 Apply PHP Code Styling & Quality Changes (#3705)
Co-authored-by: FOSSBilling Bot <fossbilling-bot>
Co-authored-by: Adam Daley <admdly@users.noreply.github.com>
2026-06-03 11:31:36 +01:00
29a3a6a692 Fix typos in tests and update cspell.json (#3703)
* Fix typos in tests and update cspell.json

* Fix for pull request finding

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* Fix Myanma typo: correct to Myanmar in currency test, remove from cspell ignoreWords

* chore: remove unused cspell typo token

* Fix typo allowlist feedback in cspell review thread

---------

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
2026-06-02 08:20:28 +01:00
Adam Daley dd3dcbfd52 Enhance type safety, authentication checks, and testing framework (#3701)
* Improve type safety, auth checks and PHPStan fixes (#3250)

* Improve type safety, auth checks and PHPStan fixes

* Remove @phpstan-ignore annotations

* Improve type safety, auth checks and PHPStan fixes

* Remove @phpstan-ignore annotations

* Remove redundant @phpstan-ignore comment

* Improve code robustness and reliability (#3248)

* Harden code against null/undefined values

* Update dependency lockfiles

* Sanitize ticket input and use IDs in email list

* Restructure tests and add test utilities

* Move E2E tests to `Library\E2E` namespace

* Update `php-build` action ref in workflows

* Switch tests to Pest and add test scaffolding

* Refactor E2E tests to Pest-style tests

m

Skip E2E tests when env not configured

* Refactor Unit tests and update test config

Add test datasets and refine test helpers

* Add DEBUG guard, fix API JSON decode, update tests

* Refactor tests: add types and Mockery expectations

* Adjust tests, phpstan config, and composer script

* Instantiate test APIs locally, remove beforeEach

* Refactor runtime checks, types & logging

* Apply PHP Code Styling Changes

m

* Add PHPStan ignores, test renames & small fixes

* Enable Pest tests in CI workflow

* Remove legacy tests; add new unit tests/config

* Avoid undefined index in fingerprint comparison

* Ignore properties absent in both fingerprints

* Remove public_ticket_create API method

* Add Fingerprint unit tests

* Remove em dash from fingerprint test name

* Switch to Pest; assorted bug fixes & refactors

* Prefer getDi() and guard DEBUG define

* Refactor tests: DBAL, Antispam rename, helpers

* Refactor email tests to use Doctrine entities

* Update tests, use DBAL mocks & improve Formbuilder admin

* Validate plan_id and update unit tests

* Replace error_log with DI logger and update tests

* Expect db->store in Invoice Service test

* Use DI logger instead of error_log; fix tests

* Fix typo in Hook Service test

* Fix Staff test spelling fixture

* Complete Pest test migration

* Fix Product test spelling fixtures

* Fix Product test spelling fixtures

* Run live tests with Pest and load helpers

* Migrate tests to ApiClient; remove legacy APIHelper

* Fix Email test spelling

* Remove unused PHPUnit bridge

* Organize Cypress end-to-end tests

* Document Pest test directory root

* Remove noisy Pest comments
2026-06-02 07:43:01 +01:00