Skip to content

Reporting section schedule - #993

Open
DinuniWork wants to merge 60 commits into
developmentfrom
reporting-section-schedule
Open

DinuniWork wants to merge 60 commits into
developmentfrom
reporting-section-schedule

Conversation

@DinuniWork

@DinuniWork DinuniWork commented Nov 19, 2026 •

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

  • New Features
    • Schedule analytics reports for recurring email delivery with daily, weekly, monthly, yearly, or interval-based timing, configurable recipients and time zones, and PDF, CSV, or Excel formats.
    • View, edit, pause, resume, and remove schedules in the reports area, or open a scheduled report with its saved filters. Scheduling requires the appropriate plan access.
    • Scheduled exports use current report data and can include charts in PDF and Excel files.
  • Improvements
    • Date-range filters are available for project health, budget tracking, and planned-versus-actual reports.
    • Analytics PDF exports now feature consistent branding, charts, KPI summaries, tables, and page numbering.
    • Chart image exports use improved contrast, and scheduling controls and messages are available in multiple languages.

… order

- Adjusted the logic for rendering task status dropdowns to align with the ordered status handling.
- Improved user experience by ensuring consistent display of status options across components.
- Introduced new routes for managing reporting schedules, including listing, retrieving by report, upserting, updating, pausing, and deleting schedules.
- Integrated AnalyticsSchedulesController to handle the new functionalities, enhancing reporting capabilities.
- Introduced support for email attachments in the email request schema, allowing users to send emails with multiple attachments.
- Added new functions to manage analytics report schedules, including listing due schedules and marking schedules as sent.
- Updated cron job initialization to include the new analytics report scheduling job, improving reporting capabilities.
- Introduced new localization strings for scheduling reports, including titles, descriptions, and validation messages.
- Updated analytics component exports to include scheduling-related actions and modal components, enhancing the reporting capabilities.
- Added `ReportPageShellScheduleConfig` type to support scheduling configurations in reports.
- Updated `ReportPageShell` to conditionally render scheduling actions based on the new configuration.
- Integrated scheduling functionality into various reporting pages, allowing users to define schedules for different report types.
- Improved export functionality by including scheduling options across multiple analytics pages.
- Added new localization strings for scheduling actions, including "Edit schedule", "Next send", "Active", and "Paused".
- Integrated `ScheduledReportsHubPanel` into the All Reports page to display scheduled reports, improving user interaction with scheduling functionalities.
- Updated component exports to include the new `ScheduledReportsHubPanel`, enhancing the modularity of the reporting components.
- Enhanced localization strings across multiple languages for scheduling functionalities, including titles, descriptions, and validation messages.
- Updated action labels and added new strings to improve user experience when scheduling reports.
- Added support for SESv2 client to handle email sending with attachments, improving email capabilities.
- Updated email sending logic to utilize SESv2's SendEmailCommand for better attachment management.
- Introduced error handling for SES access denial scenarios, enhancing robustness in email operations.
- Updated package dependencies to include @aws-sdk/client-sesv2 for new functionality.
- Updated `csvToExcelBuffer` and `csvToPdfBuffer` functions to accept an optional chart image buffer, allowing charts to be included in Excel and PDF exports.
- Modified `buildLivePayload` to return chart data alongside CSV for various report kinds, enhancing the export functionality.
- Updated `SchedulePdfDocument` to conditionally render the chart image in the PDF, improving visual representation of data.
- Enhanced styles for better layout of charts and tables in the generated PDF documents.
- Refactored the layout of the ScheduleReportModal to utilize a grid system, improving the organization of form items.
- Added a new TimePicker field for selecting send time, ensuring it is required for scheduling.
- Updated styling for various input fields to ensure consistent width and better alignment within the modal.
- Removed unnecessary Space component to streamline the layout.
- Consolidated TimePicker properties to simplify the component structure.
- Removed redundant minuteStep property to enhance clarity and maintainability.
- Updated loadSchedules function to accept an optional silent parameter, preventing the loading spinner from displaying when refreshing visible rows.
- Adjusted calls to loadSchedules in response to schedule save and removal actions to use the silent option, enhancing user experience by reducing unnecessary loading indicators.
- Introduced new localization strings for the row actions menu across multiple languages, enhancing accessibility.
- Updated the ScheduledReportsHubPanel to utilize a dropdown for row actions, improving user interaction and organization of actions.
- Updated chart rendering functions to support multiple chart images for Excel and PDF exports, improving visual data representation.
- Refactored `csvToExcelBuffer` and `csvToPdfBuffer` to accept arrays of chart images, allowing for flexible chart inclusion.
- Modified `SchedulePdfDocument` to render multiple charts conditionally, enhancing the layout and organization of exported reports.
- Improved styles for better integration of charts within the generated PDF documents.
…andling and filter building

- Updated cron job implementations to use a single pooled client for advisory locks, preventing lock contention issues.
- Refactored analytics schedule access functions to ensure proper project ID resolution based on user access.
- Introduced a new utility function to build analytics schedule filters, streamlining filter management across various reporting pages.
- Enhanced CSV export functionality to decode HTML entities, ensuring accurate data representation in exports.
- Updated multiple reporting pages to utilize the new filter building utility, improving consistency and maintainability.
- Added date range filters (date_from and date_to) to ProjectHealthFilters interface for improved analytics.
- Implemented utility functions to handle date parsing and default date ranges.
- Updated parseProjectHealthFilters to incorporate date filtering logic, ensuring projects are filtered based on effective date spans.
- Modified API service and frontend components to support new date filter functionality, enhancing user experience in project health reporting.
- Introduced date range filters (dateFrom and dateTo) to the PlannedVsActualTasksFilters interface for enhanced reporting capabilities.
- Implemented utility functions for date parsing and default date ranges.
- Updated the parsePlannedVsActualTasksFilters function to incorporate date filtering logic, ensuring accurate project filtering based on effective date spans.
- Modified API service and frontend components to support the new date filter functionality, improving user experience in analytics reporting.
…reporting

- Added date range filters (dateFrom and dateTo) to the PlannedVsActualMilestonesFilters interface for improved reporting accuracy.
- Introduced utility functions for date parsing and default date ranges.
- Updated the parsePlannedVsActualMilestonesFilters function to incorporate date filtering logic, ensuring milestones are filtered based on the selected date range.
- Modified API service and frontend components to support the new date filter functionality, enhancing user experience in analytics reporting.
- Introduced date range filters (dateFrom and dateTo) to the BudgetTrackingFilters interface for enhanced reporting capabilities.
- Implemented utility functions for date parsing and default date ranges.
- Updated the parseBudgetTrackingFilters function to incorporate date filtering logic, ensuring accurate project filtering based on effective date spans.
- Modified API service and frontend components to support the new date filter functionality, improving user experience in budget tracking analytics.
- Added a new endpoint to list schedules by report, allowing retrieval of multiple schedules for a given report.
- Updated the analytics schedules controller to handle requests for all schedules, improving flexibility in schedule management.
- Refactored existing functions to support the new listing capabilities and deprecated the single-row retrieval method for better alignment with the new multi-schedule approach.
- Modified frontend components to streamline the scheduling process, ensuring users can create and manage multiple schedules effectively.
- Enhanced the analytics schedule export functionality to include timezone information, allowing for accurate date resolution based on user-defined timezones.
- Updated the buildLivePayload function to apply live schedule date bounds considering the timezone, improving the accuracy of scheduled reports.
- Modified the analytics schedule filters to conditionally freeze date ranges based on the selected date preset, ensuring correct handling of relative and custom date ranges.
- Improved frontend components to accommodate the new timezone and date handling logic, enhancing user experience in scheduling analytics reports.
- Introduced a new ScheduleTable component for rendering tables with fixed headers in PDF exports, ensuring column labels repeat on each page.
- Updated the SchedulePdfDocument to conditionally render charts and tables across multiple pages, improving the organization of exported reports.
- Enhanced styling for table headers and added a message for truncated data rows, improving user experience in report generation.
- Introduced a new function to open scheduled reports, which stashes filters for the selected report before navigation, ensuring users see the correct filters.
- Updated the ScheduledReportsHubPanel to utilize the new function for opening reports, improving user experience.
- Enhanced the usePersistedAnalyticsFilters hook to consume pending schedule filters, allowing for seamless filter restoration when accessing reports from schedules.
- Added the chartsheet dependency to facilitate native Excel chart embedding.
- Enhanced the csvToExcelBuffer function to support native charts, improving the visual representation of data in Excel exports.
- Updated analytics schedule export service to utilize the new charting capabilities, ensuring accurate chart data binding.
- Implemented tests to verify the integration of native charts in Excel exports, enhancing overall reporting functionality.
- Updated the buildEmailHtml function to include a human-readable time range note in scheduled report emails, improving clarity for recipients.
- Introduced the formatScheduleTimeRangeNote function to generate time range descriptions based on report filters and timezone, enhancing the contextual information provided in emails.
- Added tests to verify the correct formatting of time range notes for various preset filters, ensuring accuracy in report communications.
- Updated the usePersistedAnalyticsFilters hook to include explicit project tracking, allowing for better management of user-selected projects.
- Refactored ProjectHealthPage to implement a new state for project overrides, improving the handling of project selections and ensuring accurate data representation in charts.
- Modified project filtering logic to reset manual project selections on series changes, enhancing user experience and data consistency in analytics reporting.
@DinuniWork
DinuniWork requested a review from chamikaJ as a code owner November 19, 2026 03:34
@coderabbitai

coderabbitai Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • Resume reviews
  • Trigger review
Walkthrough

This change adds recurring analytics report schedules, schedule management, live CSV, Excel, and PDF exports, and email delivery. It adds frontend scheduling controls and scheduled-report management. It also adds date-range filters to selected analytics reports and passes saved schedule filters when opening reports.

Changes: Analytics report scheduling

Layer / File(s) Summary
Schedule storage and recurrence
worklenz-backend/database/pg-migrations/*, worklenz-backend/src/services/reporting-analytics/analytics-schedules.service.ts, worklenz-backend/src/services/reporting-analytics/analytics-schedule-next-send.ts, worklenz-frontend/src/types/reporting/analytics-schedules.types.ts
Adds the schedules table, schedule types and validation, lifecycle operations, and timezone-aware recurrence calculations. Follow-up migrations allow multiple schedules per report and store multiple output formats.
Schedule API and interface
worklenz-backend/src/controllers/reporting-analytics/analytics-schedules-controller.ts, worklenz-backend/src/routes/apis/*, worklenz-frontend/src/api/reporting/analytics-schedules.api.service.ts, worklenz-frontend/src/components/reporting/analytics/*, worklenz-frontend/src/pages/reporting/analytics/AllReportsPage.tsx, worklenz-frontend/src/lib/reporting/analytics-schedule-open.ts, worklenz-frontend/src/hooks/usePersistedAnalyticsFilters.ts, worklenz-frontend/public/locales/*/reporting-analytics.json
Adds authenticated schedule endpoints, frontend schedule controls and a scheduled-reports panel. Saved filters are handed off once when a scheduled report is opened.
Live report exports and delivery
worklenz-backend/src/services/reporting-analytics/analytics-schedule-*, worklenz-backend/src/cron_jobs/*, worklenz-backend/src/shared/email.ts, worklenz-backend/src/json_schemas/email-request-schema.ts, worklenz-backend/src/tests/*, worklenz-backend/src/chartsheet.d.ts, worklenz-backend/package.json
Adds owner project-access resolution and CSV, Excel, and PDF generation. A cron job processes due schedules and emails export attachments. Email attachment validation and SMTP/SES support are added. The digest scheduler uses one pooled client for advisory-lock acquisition and release.
Analytics date filters and branded exports
worklenz-backend/src/services/reporting-analytics/{budget-tracking,planned-vs-actual-*,project-health}.service.ts, worklenz-frontend/src/pages/reporting/analytics/*, worklenz-frontend/src/api/reporting/*, worklenz-frontend/src/types/reporting/*, worklenz-frontend/src/lib/reporting/*
Adds date bounds to selected analytics filters and queries. Report pages build schedule filter payloads from selected filters and custom date ranges. Analytics pages use shared branded PDF export helpers, and chart PNG exports temporarily apply light colors.

Estimated code review effort: 5 (Critical) | ~90 minutes

Change: Feature

Sequence Diagram(s)

sequenceDiagram
  participant ReportPage
  participant AnalyticsScheduleAction
  participant ScheduleReportModal
  participant AnalyticsSchedulesApi
  participant AnalyticsSchedulesController
  participant AnalyticsSchedulesService
  ReportPage->>AnalyticsScheduleAction: provide report details and filters
  AnalyticsScheduleAction->>ScheduleReportModal: open schedule form
  ScheduleReportModal->>AnalyticsSchedulesApi: submit schedule payload
  AnalyticsSchedulesApi->>AnalyticsSchedulesController: send schedule request
  AnalyticsSchedulesController->>AnalyticsSchedulesService: validate and persist schedule
Loading
Merge Risk: High · previous review c5955

Recurring report scheduling and export has an open compile error in the backend PDF renderer, schedule state races, permission gaps, and exports that drop table rows or settings. Resolve the build-blocking and data-integrity issues before merging.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title "Reporting section schedule" is partially related to the changeset. The PR adds recurring scheduled analytics report emails, including backend schedule services, cron job, migrations, API ro…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title "Reporting section schedule" is partially related to the changeset. The PR adds recurring scheduled analytics report emails, including backend schedule services, cron job, migrations, API routes, and frontend schedule modal and hub panel. The title names the right feature area but is broad and does not say what the schedule does (scheduled report delivery by email). It is not vague or generic enough to be inconclusive, and it is not misleading.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@superagent-security superagent-security Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Superagent found 2 security concern(s).


router.post(
"/schedules",
requireAnalyticsAccess,

@superagent-security superagent-security Bot Nov 19, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: Schedule create/update routes omit the View finance and finance_module gates, letting a user email themselves financial reports they cannot open directly

Schedule routes only check View reports + advanced_reporting; cron can email budget/project-health financial data without View finance.

Gate finance report kinds on create/update with viewFinanceValidator + finance_module, and recheck owner permissions and entitlements in the cron before export.

AI prompt
Check if this security scanner issue is valid. If so, understand the root cause and fix it. If appropriate, update or add tests. Keep the change focused and preserve intended behavior.

<file name="worklenz-backend/src/routes/apis/reporting-analytics-api-router.ts">
<violation number="1" location="worklenz-backend/src/routes/apis/reporting-analytics-api-router.ts:344">
<priority>P1</priority>
<title>Schedule create/update routes omit the View finance and finance_module gates, letting a user email themselves financial reports they cannot open directly</title>
<evidence>The added schedule routes (added lines 327-368) are guarded only by requireAnalyticsAccess (viewReportsValidator: View reports plus a paid plan) and requireFeature("advanced_reporting"); the POST /schedules handler at added line 344 is one example. upsertSchedule accepts every ANALYTICS_REPORT_KINDS value (service lines 545-552), which includes "project-health" and "budget-tracking" (src/shared/reporting-analytics.constants.ts:41-52). By contrast, the direct project-health and budget-tracking data routes add an independent per-user boundary that the schedule routes omit: /project-health/series and /project-health/export/csv require viewFinanceValidator plus requireFeature("finance_module") (router lines 147-167), as do /budget-tracking/series and /budget-tracking/export/csv (router lines 260-280). At send time the new cron calls buildLiveScheduleExports (cron_jobs/analytics-report-schedule-job.ts:134), whose buildLivePayload calls getProjectHealthSeries/getBudgetTrackingSeries directly (analytics-schedule-export.service.ts:180-210) without rechecking View finance, finance_module, advanced_reporting or View reports. The generated CSV/PDF/Excel includes budget, budget_used_pct, spent, remaining and burn data (project-health.service.ts:255-351, 384-410; budget-tracking.service.ts:327-352) and is emailed to the schedule recipients (up to 25 addresses). resolveScheduleOwnerAccessibleProjectIds only reloads team/project membership (analytics-schedule-access.ts:43-120) and never consults organization permissions or plan entitlements. A member with View reports and Business advanced_reporting but no View finance can therefore create or retain a financial-report schedule and receive data that the equivalent direct endpoint returns 403 for.</evidence>
<recommendation>Apply the same per-report authorization as the underlying data routes: when report_kind is "project-health" or "budget-tracking", require viewFinanceValidator and requireFeature("finance_module") on schedule create/update and reject the request otherwise. Re-evaluate the schedule owner's View reports, View finance, advanced_reporting, finance_module and active team membership inside onAnalyticsReportScheduleTick before building or emailing each export, and stop/disable the schedule after access or entitlement is revoked. Add regression tests for a View-reports-only principal receiving 403 for finance schedules and for a revoked schedule no longer sending.</recommendation>
</violation>
</file>

*/
exports.up = async (pgm) => {
pgm.sql(`
DROP INDEX IF EXISTS idx_analytics_report_schedules_owner_kind_builtin;

@superagent-security superagent-security Bot Nov 19, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Removing schedule uniqueness without a per-owner cap lets one member enqueue unbounded recurring export and email work

The migration removes schedule uniqueness and no per-owner cap is added, so one member can queue unlimited recurring exports and emails.

Enforce a per-owner/per-team schedule cap under a lock, rate-limit schedule creation, and give the cron a per-tenant fair-share budget.

AI prompt
Check if this security scanner issue is valid. If so, understand the root cause and fix it. If appropriate, update or add tests. Keep the change focused and preserve intended behavior.

<file name="worklenz-backend/database/pg-migrations/1794400000000_allow_multiple_analytics_report_schedules.js">
<violation number="1" location="worklenz-backend/database/pg-migrations/1794400000000_allow_multiple_analytics_report_schedules.js:15">
<priority>P2</priority>
<title>Removing schedule uniqueness without a per-owner cap lets one member enqueue unbounded recurring export and email work</title>
<evidence>The added migration drops the only uniqueness constraints on schedules (added line 15 drops idx_analytics_report_schedules_owner_kind_builtin and line 16 drops idx_analytics_report_schedules_owner_template, both UNIQUE in the preceding added migration) and replaces them with non-unique indexes (lines 18-23). upsertSchedule always performs a fresh INSERT (analytics-schedules.service.ts:597-653) and neither the service nor the controller enforces a per-owner, per-team or per-report schedule count. The only request-wide bound is the global 1,000 requests/minute limiter (app.ts:48-53), while each schedule may have MAX_RECIPIENTS = 25 recipients (analytics-schedules.service.ts:20) and up to three export formats. The added cron processes at most MAX_PER_TICK schedules per minute (default 10, maximum 50; cron_jobs/analytics-report-schedule-job.ts:17-21) under one global advisory lock, and processSchedule runs buildLiveScheduleExports (full analytics series queries plus chart rendering through chartjs-to-image/QuickChart, react-pdf/Excel generation) and then sends an email per recipient with attachments (analytics-report-schedule-job.ts:133-172). listDueSchedules selects due rows globally ordered by next_send_at with a LIMIT and no tenant fair share (analytics-schedules.service.ts:777-789), so one tenant's backlog delays every other tenant's due reports. Analytics templates have a per-user cap (MAX_ANALYTICS_TEMPLATES_PER_USER in src/shared/reporting-analytics.constants.ts:55-58), but schedules have no analogous cap.</evidence>
<recommendation>Enforce and validate a per-owner and per-team cap on active schedules under a transaction or advisory lock and reject creation above the cap. Add a dedicated rate limit to the schedule create/update routes and give the cron a per-tenant budget or fair-share queue so one member cannot monopolize the shared worker, QuickChart calls or SES quota. Bound total active schedules and recipients per tenant instead of relying on the global request limiter.</recommendation>
</violation>
</file>

DinuniWork and others added 20 commits November 19, 2026 15:02
- Modified the analytics PDF generation scripts to enhance the layout and styling of KPI cards, ensuring better visual representation.
- Removed redundant styles and adjusted the structure of KPI card components for clarity and consistency.
- Updated the header row styling in tables to improve readability and alignment in generated PDFs.
- Introduced a constant for KPI card fill color to maintain consistency across PDF exports.can i  re
…neration styles

- Updated google-auth-library dependency from version 11.3.3 to 11.3.4 for improved functionality.
- Refactored PDF generation styles in analytics-schedule-pdf.tsx to enhance layout consistency and readability.
- Added CalendarOutlined icon to the AnalyticsScheduleAction button for improved visual clarity.
- Introduced a new CSS class for analytics actions to standardize styling across components.
- Updated ReportPageShell to render actions conditionally, enhancing the layout and user experience.
- Implemented side-by-side rendering of bar and donut charts in the Project Health PDF report for improved visual clarity.
- Updated PDF generation logic to accommodate an optional secondary chart, allowing for a more comprehensive data presentation.
- Refactored styles in analytics-schedule-pdf.tsx to support the new layout, ensuring consistent formatting across reports.
- Added tests to verify the correct rendering of Project Health reports with the new chart configuration.
- Added a new constant for donut chart size to standardize export dimensions.
- Enhanced the toPngDataUrl method to adjust legend display and chart dimensions dynamically for better export quality.
- Updated PDF generation logic to ensure proper layout and sizing of charts in the exported documents.
- Updated the Project Health Donut Chart to improve export aesthetics by adding white slice borders and a dark legend on a white background.
- Adjusted legend label colors for better visibility in exported PDFs.
- Implemented logic to restore previous chart settings after export adjustments, ensuring consistent chart behavior.
…h reports

- Updated chart dimensions and styles for better visual clarity in exported PDFs, ensuring aspect ratios are preserved.
- Introduced functions to read PNG pixel sizes and fit images within specified dimensions, enhancing the sharpness of chart text.
- Refactored PDF generation logic to accommodate dynamic sizing of charts, improving layout consistency across reports.
- Eliminated the exportedOn parameter from ScheduleHeader and drawHeader functions to simplify the PDF generation logic.
- Updated relevant calls to these functions to reflect the removal, ensuring consistency across PDF exports.
- Adjusted text positioning in the header for improved layout and readability.
- Added functionality to include a compact filter summary in PDF headers, detailing time ranges and selected projects, teams, and members.
- Introduced chart titles for better context in exported PDFs, allowing for clearer identification of data visualizations.
- Updated relevant components and functions to support these new features, ensuring consistency across various reporting pages.
- Enhanced styling for chart cards in PDFs to improve visual clarity and presentation.
- Integrated functionality to apply custom cell colors in exported Excel and PDF reports, improving visual differentiation of data.
- Updated relevant functions and interfaces to accommodate new tableCellColors parameter, allowing for dynamic styling based on data values.
- Refactored components to ensure consistent application of color logic across various reporting formats, enhancing overall report clarity and usability.
- Introduced a new function to format variance days labels for improved clarity in reports, displaying values like "+3 days" and "-1.5 days".
- Updated relevant components and services to utilize the new formatting function, ensuring consistent presentation across various reporting formats.
- Enhanced the isNumericCellValue function to recognize formatted day values, improving data validation in analytics.
- Translated the "scheduleReportDescription" and "scheduleName" fields into various languages, including Albanian, German, Spanish, French, Italian, Polish, Portuguese, and Chinese.
- Enhanced user experience by providing localized content for scheduling reports, ensuring clarity and accessibility for diverse users.
…and recipient resolution

- Introduced functions for escaping HTML to ensure safe email content and for generating display names from email addresses.
- Enhanced the email building logic to greet recipients by name and include custom messages in scheduled report emails.
- Implemented recipient name resolution from the database, improving personalization in email communications.
- Updated the PDF generation logic to support multi-page tables with consistent column headers across pages, enhancing report clarity.
- Added tests for new functionalities, ensuring robust validation of email formatting and table chunking behavior.
…F exports

- Introduced optional hints and legends for charts in PDF exports, improving context and readability.
- Updated the analytics-schedule-charts service to build and retrieve chart legends based on project health data.
- Enhanced the PDF generation logic to incorporate hints and legends under each chart, ensuring better presentation.
- Adjusted chart dimensions and styles for improved layout consistency across reports.
- Added tests to validate the new hint and legend functionalities in PDF exports.
@superagent-security

superagent-security Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

Superagent Supply Chain Scan

Superagent found 1 policy-blocking dependency introduced by this pull request.

High risk: chartsheet@0.3.2

  • Change: added 0.3.2
  • Dependency path: worklenz-backend/package-lock.json → chartsheet
  • Correlated risks: 2
  • Why flagged: Package uses dynamic code execution (e.g., eval()), which is a dangerous practice. Assessment: The package exhibits multiple critical supply chain and runtime risks, including dynamic code execution via 'eval()', accessing environment variables (potential credential theft), and containing unauthorized URL strings.
  • Risk score: 80.0/100
  • Policy action: error

View Superagent Supply Chain Scan

DinuniWork and others added 6 commits November 20, 2026 15:06
- Updated report card navigation to handle business and finance plan restrictions, providing appropriate feedback to users.
- Enhanced aria-labels for buttons to improve accessibility based on user permissions.
- Refactored report card title and description rendering for better localization support.
- Improved layout consistency by adjusting card footer visibility based on report access status.
…and ensuring proper localization for finance permission hints.
- Added checks to ensure that only users with the View finance permission and finance_module access can create or send finance-related report schedules.
- Introduced new utility functions to validate user permissions for finance schedules.
- Updated relevant components to handle finance permission requirements in the frontend, providing user feedback when permissions are lacking.
- Enhanced backend logic to enforce schedule creation limits based on user roles and permissions.

@superagent-security superagent-security Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Superagent found 1 security concern(s).


async function processSchedule(schedule: AnalyticsScheduleRow): Promise<boolean> {
// Do not email finance exports if the owner lost View finance / finance_module.
if (isFinanceAnalyticsReportKind(schedule.report_kind)) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Scheduled report email keeps sending after the owner loses View reports or the Business plan

Cron only rechecks finance; non-finance schedules keep emailing analytics exports after View reports/Business access is revoked.

Revalidate View reports and advanced_reporting for the owner at send time, and pause schedules on revocation.

AI prompt
Check if this security scanner issue is valid. If so, understand the root cause and fix it. If appropriate, update or add tests. Keep the change focused and preserve intended behavior.

<file name="worklenz-backend/src/cron_jobs/analytics-report-schedule-job.ts">
<violation number="1" location="worklenz-backend/src/cron_jobs/analytics-report-schedule-job.ts:137">
<priority>P2</priority>
<title>Scheduled report email keeps sending after the owner loses View reports or the Business plan</title>
<evidence>processSchedule only re-authorizes finance report kinds: the guard at lines 136-147 calls canOwnerAccessFinanceSchedules when isFinanceAnalyticsReportKind(report_kind) is true. For every other kind it proceeds to buildLiveScheduleExports (line 149) and sendEmail with the generated PDF/CSV/Excel (lines 149-190) without checking the owner's View reports permission or the Business `advanced_reporting` entitlement. resolveScheduleOwnerAccessibleProjectIds (analytics-schedule-access.ts:69-137) only reloads active team/project membership, and canOwnerAccessFinanceSchedules (analytics-schedule-access.ts:55-63) is the only send-time organization-permission check. In contrast, every in-app analytics route revalidates at request time: base /velocity/series requires requireAnalyticsAccess (viewReportsValidator) plus requireFeature("advanced_reporting") (repository-base/src/routes/apis/reporting-analytics-api-router.ts:66-77), and /time-report/series requires View reports (head router:246-252). The new schedule create/list/update/delete routes do enforce those gates (head router:328-368), but a stored schedule is not rechecked by the worker. A member who created a time-report, velocity, cumulative-flow or time-in-status schedule while authorized continues to receive recurring exports containing live project and member data at addresses they chose after View reports is revoked or the team downgrades from Business. Because list/patch/delete also require those gates, the affected user may no longer be able to delete the schedule through the API either. (The finance-specific prior finding b61cd2c3 is addressed by the current finance rechecks; this is the remaining general-gate gap for non-finance kinds.)</evidence>
<recommendation>Before building and sending a scheduled export, reconstruct the owner's session and require canViewAnalyticsReports(owner, team) and, for advanced_reporting-only report kinds, teamCanUseFeature(team_id, "advanced_reporting")/paid-plan status. When a schedule owner loses View reports or the plan, pause the schedule (so it can be cleaned up) or skip the send. Add an admin-accessible cleanup path that does not depend on the revoked user's own analytics entitlement.</recommendation>
</violation>
</file>

- Replaced the finance-specific access check with a more generalized permission validation for sending schedules.
- Introduced a new function, canOwnerSendSchedule, to handle permission checks for various report kinds, ensuring that revoked access prevents unauthorized schedule sending.
- Updated the cron job logic to utilize the new permission validation, enhancing security and maintainability.

@superagent-security superagent-security Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Superagent found 1 security concern(s).

tm.id AS team_member_id,
r.name AS role_name,
COALESCE(r.owner, FALSE) AS is_owner,
COALESCE(r.admin_role, FALSE) AS is_admin_role

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Scheduled report worker reconstructs the owner without the team guest flag, so a guest-downgraded member keeps receiving reports after live access is revoked

Send-time session omits team_members.is_guest, so a guest-downgraded Member is re-authorized with Member grants and keeps receiving reports.

Load tm.is_guest into the reconstructed session (or reuse the request session loader) so scheduled sends use Guest grants after a guest downgrade.

AI prompt
Check if this security scanner issue is valid. If so, understand the root cause and fix it. If appropriate, update or add tests. Keep the change focused and preserve intended behavior.

<file name="worklenz-backend/src/services/reporting-analytics/analytics-schedule-access.ts">
<violation number="1" location="worklenz-backend/src/services/reporting-analytics/analytics-schedule-access.ts:29">
<priority>P2</priority>
<title>Scheduled report worker reconstructs the owner without the team guest flag, so a guest-downgraded member keeps receiving reports after live access is revoked</title>
<evidence>The new loadScheduleOwnerSession SELECT (lines 24-49) reads tm.id, r.name, r.owner and r.admin_role, but never reads team_members.is_guest, and the returned IPassportSession at lines 42-49 has no is_guest. The cron re-authorization path canOwnerSendSchedule (lines 71-90) calls hasOrganizationPermission(session, VIEW_REPORTS) with that reconstructed session, and resolveScheduleOwnerAccessibleProjectIds (lines 96+) uses the same session for project scope. hasOrganizationPermission derives the scheme role through getSchemeRoleName (worklenz-backend/src/shared/organization-permissions.ts:103-108), which only maps a Member to Guest when user.is_guest is true; live requests receive that flag from worklenz-backend/src/controllers/deserialize.sql.sql:168-170. The database sets team_members.is_guest for any member holding GUEST-level access on any team project (worklenz-backend/database/pg-migrations/1787306400000_add_team_guest_status.js:8-33). Consequently, a Member who was granted View reports and later becomes guest-flagged (for example by being added as a guest to one client project) is evaluated as Guest by the live analytics routes, but the cron rebuilds them as a full Member. If the Member scheme still grants View reports, canOwnerSendSchedule returns true, the project resolver also uses Member-level scope (including all team projects when the Member grant includes View all projects), and the worker builds and emails the scheduled export.</evidence>
<recommendation>Select team_members.is_guest in loadScheduleOwnerSession and include is_guest in the reconstructed IPassportSession (or reuse the same session loader used by request authentication). This makes the send-time View reports, View finance and finance_module checks apply Guest grants to guest-flagged members, exactly like the live routes. Also apply the same guest-aware role when resolving accessible project IDs, and add a regression test where a Member with a View reports grant becomes guest-flagged and the scheduled send is denied.</recommendation>
</violation>
</file>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants