Skip to content

Commit 9dd5d19

Browse files
mkleszczzczarnecki
andauthored
release/5.0.0 (#685)
* refactor: Update authentication components to use new UI library and improve layout - Replaced button and typography components in login, signup, and password reset forms with new UI components. - Enhanced layout with card components for better visual structure. - Updated form handling to utilize new form components and improved error messaging. - Adjusted storybook configurations for fullscreen layout in authentication stories. - Ensured consistent styling and accessibility across all forms. * style: Update color variables and enhance authentication component layout - Adjusted CSS color variables for improved contrast and accessibility. - Integrated AuthLogo and FloatingThemeToggle components into login, signup, password reset, and OTP validation forms for a consistent user experience. - Enhanced layout structure across authentication components for better visual appeal and usability. * style: Refine authentication components for improved layout and accessibility - Updated layout of the SignupForm component for better alignment and spacing. - Enhanced FormLabel component with improved styling for better readability and accessibility. - Modified social login buttons to use new button styles and sizes for consistency across the UI. * docs: Enhance admin panel documentation with access details and security notes - Added sections on accessing the admin panel in local development and default credentials setup. - Included security recommendations for production environments regarding default passwords. - Improved clarity on environment variable configurations for the superuser account. * feat: Implement sidebar collapse functionality and enhance layout components - Added state management for sidebar collapse in Layout component. - Updated LayoutContext to include sidebar collapse state and toggle function. - Refactored Sidebar component to support dynamic width based on collapse state. - Enhanced Header component to integrate UserMenu and improve layout. - Updated notifications components for better styling and accessibility. - Improved overall layout structure for better user experience. * refactor: Update layout components and enhance sidebar functionality - Refactored layout tests to improve clarity and accuracy in menu visibility assertions. - Updated sidebar component to include static page items and manage sidebar collapse state. - Enhanced header component stories to better reflect user states and interactions. - Improved notification components for better styling and user experience. - Adjusted notification hooks for more robust state management. * refactor: Clean up authentication component layouts and improve code structure - Refactored layout of Login, Signup, Password Reset, and Password Reset Confirm components for better alignment and spacing. - Enhanced readability by restructuring JSX elements and removing unnecessary whitespace. - Updated test cases for Password Reset Confirm to reflect changes in form field labels. - Improved import organization in various components for better maintainability. * refactor: Enhance layout and structure of home and profile components - Updated Home component to utilize card layouts for dashboard items, improving visual hierarchy and user experience. - Refactored Profile component to implement card structures for user information, enhancing readability and organization. - Improved form layouts in authentication components for better alignment and spacing. - Enhanced error handling and messaging in forms for improved user feedback. - Updated imports and component organization for better maintainability across the application. * test: Enhance Home and Profile component tests for improved coverage - Updated Home component tests to check for specific headings and feature cards visibility based on user roles. - Refactored Profile component tests to verify individual role badges instead of combined role text, improving clarity in assertions. * refactor: Enhance UI components and improve layout structure across finance routes - Updated Home component alert styling for better visibility and consistency. - Refactored StripePaymentForm and EditPaymentMethod components to improve error message display. - Enhanced CancelSubscription component layout with card structures for better organization and user experience. - Improved EditSubscription and SubscriptionPlans components with better navigation and layout. - Updated TransactionHistory and PaymentConfirm components to utilize card layouts for improved visual hierarchy. - Refactored various subscription-related components to enhance readability and maintainability. * refactor: Update SaaS Ideas component with enhanced chat interface and new dependencies - Integrated lucide-react for improved iconography in the SaaS Ideas component. - Refactored the chat interface to utilize card layouts for better organization and user experience. - Added state management for user messages and AI responses, enhancing interactivity. - Updated form handling to support keyword input and example prompts for generating SaaS ideas. - Improved scrolling behavior for message display and added typing indicators for better user feedback. - Included new dependencies in package.json for enhanced functionality. * refactor: Update OpenAI integration and enhance SaaS Ideas generation - Refactored OpenAI client to improve error handling and logging for API interactions. - Updated the SaaS Ideas mutation to return a structured response instead of a list of ideas. - Enhanced the GenerateSaasIdeasMutation to accommodate the new response format. - Improved UI components for better user experience, including card layouts and responsive design. - Updated dependencies in the project to ensure compatibility with the latest OpenAI SDK. - Adjusted tests to reflect changes in the OpenAI client and mutation response structure. * refactor: Revamp Home component layout and enhance feature presentation - Updated Home component to improve layout structure, utilizing a two-column design for better organization. - Added new sections for "Getting Started" and "Available Features" with detailed descriptions and development commands. - Introduced additional icons from lucide-react for enhanced visual representation. - Replaced the previous alert with a more informative version, emphasizing customization of the SaaS Boilerplate. - Improved responsiveness and spacing for a better user experience across different screen sizes. * refactor: run prettier * feat: Add SidebarLogo component with signet badge for collapsed state - Extract signet from full logo as separate SVG icon - Create SidebarLogo component with expanded/collapsed states - Show full logo when expanded, signet badge with border and hover effects when collapsed - Add Cursor AI development rules for consistent codebase conventions * chore: Upgrade Storybook to 8.6.14 and regenerate GraphQL types - Upgrade Storybook dependencies from 8.1.x/8.5.x to 8.6.14 - Remove deprecated @storybook/client-api package - Regenerate GraphQL types with updated codegen output format - Reduce generated types file size by removing inline AST data * fix: Update tests to match UI changes and add top Cursor AI rules - Fix tenantDangerZone tests to use "Delete organization" button text - Update saasIdeas tests for new chat interface with placeholder and icon button - Fix membershipEntry tests with proper async waiting for dropdown elements - Fix crudDemoItemDetails test to handle multiple text matches - Fix cancelSubscription tests with proper async dialog button waiting - Update tenantMembersList snapshot for new UI - Add comprehensive top-rules.mdc for Cursor AI-Agent development guidelines * refactor: Update Add Organization form with card-based layout - Restyle AddTenantForm to match TenantGeneralSettings card layout - Add Building2 icon and descriptive card header/description - Extend TenantForm with submitLabel, cancelUrl, and hideCancel props - Change submit button from "Save changes" to "Create organization" - Remove redundant PageHeadline and Cancel button for cleaner UI - Add Storybook stories for CreateMode and HiddenCancel variants - Update tests to match new button text * feat: Enhance toast notification system with semantic variants and icons - Add new toast variants: success, warning, info (in addition to default/destructive) - Add contextual icons to each variant (CheckCircle, AlertCircle, AlertTriangle, Info) - Improve toast styling with colored left border accents and themed backgrounds - Make close button always visible with variant-aware styling - Remove emojis from toast messages - icons now provide visual feedback - Update all toast calls across the codebase to use appropriate variants - Update Storybook stories to showcase all toast variants - Update Cursor AI rules with toast notification guidelines - Update all related tests to match new message formats * feat: Restyle Contentful demo pages with Card-based UI and graceful error handling - Update Content Items list with Card styling matching CRUD demo - Add loading skeleton component for better UX - Add graceful "Not Configured" state when Contentful is not set up - Show friendly setup instructions instead of blocking errors - Add error handling with toast notifications for favorite toggle - Update detail page with Card-based layout and back navigation - Add isLoading state to useFavoriteDemoItem hook - Update tests and stories for new component structure * feat: Redesign Documents page with Card-based UI and fix RelativeDate error handling - Redesign Documents page to match consistent app layout patterns with hero section, Card-based upload and list sections, and proper empty/loading states - Add error handling to RelativeDate component for invalid dates to prevent crashes - Update Document card with modern hover effects and improved UX - Fix duplicate CSS class in skeleton component - Remove styled-components from stories, use Tailwind instead - Add multiple story variants (Default, Empty, ManyDocuments, MaxDocuments) - Update tests to match new UI text changes * feat: Redesign SubscriptionPlanItem with visual distinctions and add Badge component - Add new Badge UI component with multiple semantic variants (success, warning, info, muted) - Completely redesign subscription plan cards with distinct styling for Free, Monthly, and Yearly plans - Add visual indicators: icons (Gift/Zap/Crown), badges, "Best value" ribbon for yearly plans - Include trial eligibility notice, savings badge, and color-coded feature checkmarks - Update stories with comprehensive documentation and comparison views - Update tests to match new component behavior * feat: Overhaul PLOP code generation system with new generators and full-stack support This comprehensive update transforms the PLOP code generation system into a top-tier developer experience tool with 12 generators, entity templates, and automation utilities. New Generators: - page: Page/route with navigation, skeleton, and optional data fetching - form: Multi-field form with validation, types, and entity templates - modal: Modal/dialog (confirm, form, info, custom variants) with state hook - table: Data table with pagination, search, row actions, and skeleton - context: React Context provider (state, reducer, store patterns) - backend: Django app with model, serializers, GraphQL schema, admin, and tests Enhanced Generators: - component: Now supports optional GraphQL and hook file generation - hook: Added 6 hook type templates (state, effect, callback, query, mutation, custom) - crud: Added full-stack mode (frontend + backend), entity templates, tenant support Core Infrastructure: - lib/postActions.js: Automation for format, codegen, restart, open IDE - lib/fieldBuilder.js: Interactive field builder with type support - lib/entityTemplates.js: 9 predefined templates (Product, BlogPost, Task, etc.) - lib/preview.js: File tree preview before generation - lib/conflictChecker.js: Conflict detection for files, routes, Django apps - config.js: Centralized configuration for all automation options UX Improvements: - Color-coded welcome message with categorized generators - Comprehensive success messages with next steps - Updated documentation with all generators and examples * fix: Correct initialData syntax in editItem and itemForm component tests - Update editItem component to use whitespace trimming in initialData binding - Fix itemForm test to properly render initialData with correct syntax * feat: Add pixel-art styled 404 Not Found page with glitch effects - Redesign NotFound page with lo-fi pixel art aesthetic - Add animated 404 with RGB glitch, falling pixels, and corruption effects - Implement retro game-style buttons with pixel shadow press effect - Add catch-all route for tenant paths to properly display 404 - Add custom keyframe animations (float, glitch, shooting-star) to tailwind - Include comprehensive test coverage for the new component * feat: Add resend invitation button for pending tenant members - Add ResendTenantInvitationMutation to resend invitation emails for pending members - Display "Resend" button with refresh icon next to "No" in invitation accepted column - Button shows loading spinner while resending and displays toast on success/error - Fix typo: rename invotationForm to invitationForm - Update .cursor/rules with backend patterns, mutation testing, and inline action button patterns * style: Add trailing newlines to files * fix: Align page header icons with sidebar navigation icons - Dashboard: Change header icon from Sparkles to LayoutDashboard - Payments: Change header icon from CreditCard to Wallet * feat: Add data-driven dashboard with charts and statistics - Add recharts library for data visualization - Create reusable chart components (StatCard, ChartContainer, ChartGradients, ChartTooltip) - Add dashboard statistics query to fetch real data from CRUD items, documents, notifications, and team members - Display interactive statistics cards with accent colors per metric - Add activity overview area chart showing notifications over last 7 days - Add data distribution bar chart showing breakdown of stored data types - Add team roles pie chart for admins/owners showing role distribution - Add quick actions section with common tasks and resources - Fix pagination issue by adding first parameter to GraphQL queries - Update tests to handle multiple matching text elements * style: Update dashboard charts to use brand gradient colors - Replace generic chart colors with brand palette (#FFFE25 → #42F272) - Add brandYellow, brandYellowGreen, brandLimeGreen, brandGreen colors - Update all chart gradients to use brand colors - Update stat card accent colors to match brand palette - Update pie chart, bar chart, and area chart colors * style: Update stat cards with colored icon backgrounds and black icons - Change icon containers to use accent color as background - Set icon color to black for better contrast on colored backgrounds - Increase background accent blur opacity for better visibility * style: Add brand gradient to badges and enhance chart tooltips - Add gradient variant to Badge component using brand colors (#FFFE25 → #42F272) - Update dashboard "Live" badge to use brand gradient - Add multiple gradient definitions for charts (bar, pie, mixed) - Fix chart tooltips by wrapping custom content in recharts Tooltip component - Improve tooltip styling with cleaner design and conditional color indicators - Apply gradient fills to area chart and bar chart * style: Improve dashboard Quick Actions and 2FA modal UX Dashboard: - Revert bar chart to solid brand colors instead of gradients - Improve Quick Actions layout with 2 columns and cleaner styling - Remove underlines from Quick Action links Two-Factor Auth Modal: - Complete UX overhaul with numbered steps and better visual hierarchy - Add copyable secret key with one-click copy button - Improve QR code presentation with loading state - Add sticky header and footer with scrollable content area - Update input to use numeric keyboard and proper autocomplete - Update tests to match new placeholder and button text * docs: Improve email and Mailcatcher documentation - Fix broken link in _start-app.mdx (was linking to Sentry instead of Mailcatcher) - Expand mailcatcher.mdx with required configuration, both backend options (console vs SMTP), and troubleshooting guide - Add local development setup tips to send-email.mdx with both email backend options - Update _backend_email.mdx to mention all three backend options - Add info callout to features/emails.mdx linking to Mailcatcher configuration * docs: Enhance documentation with new components and modern styling Add reusable documentation components (FeatureCard, FeatureGrid, Badge, Steps, TechStack, QuickLink, Highlight, Icon) for consistent UI across documentation pages. Update index pages with improved layouts and visual hierarchy. Add extensive custom CSS for modern documentation styling including cards, gradients, and responsive design. * docs: Redesign documentation hero section with premium styling - Add animated hero section with grid pattern and gradient glows - Update brand colors to yellow-green gradient throughout - Add floating badge, modern buttons, and tech stack pills - Add enhanced feature cards with hover effects - Add quick start section with styled code block - Add CTA section with gradient background - Hide default title and TOC for cleaner hero display * feat(webapp): Refactor sidebar with organized menu sections - Group menu items into logical sections (Overview, Billing, AI & Demo, etc.) - Add separators between sections for better visual hierarchy - Add Scale icon import for legal/terms section * docs: Fix documentation accuracy issues and improve developer experience - Fix incorrect migration reference in create-role.mdx (0006 -> 0001_initial) - Fix composeMockedListQueryResult typename parameter in component-with-query.mdx - Fix shadcn CLI package path (webapp-core -> webapp-libs/webapp-core) - Add missing useApiForm imports in form-with-mutation.mdx examples - Add missing model import in backend tests documentation - Fix GraphQL query syntax in update-schema.mdx (remove erroneous parentheses) - Add helpful tips and warnings for migration dependencies - Improve code examples with proper imports and type references * fix(cli): Correct description for down command The down command description incorrectly stated "Starts both backend and frontend" when it should say "Stops backend and frontend services". * feat(contentful): redesign Terms and Privacy pages with error handling - Add consistent page styling with hero sections matching other pages - Add loading skeletons during content fetch - Add comprehensive error handling for Contentful configuration: - Step-by-step setup instructions for developers - Environment variable examples with exact paths - Links to documentation - Retry functionality - Add empty content state when Contentful is configured but content missing - Add GraphQL error state with technical details - Update tests for all states (loading, content, empty, errors) - Add Storybook stories for all states - Fix Privacy Policy icon to match sidebar (FileText) * feat(admin): beautify admin page with RBAC documentation - Add brand gradient hero section with shield icon - Use grey/muted styling for feature cards and icons - Add code examples for route protection and conditional rendering - Add new 'Extending Roles' section explaining how to add custom roles - Include file locations for both app-level and tenant-level auth - Add documentation links and 'How This Page Works' explanation - Update tests to handle multiple matching elements * chore: add trailing newlines to files for consistent formatting * fix(docs): prevent horizontal overflow on html element * docs: overhaul documentation with improved structure and styling - Add new reusable MDX components (Badge, FeatureCard, FeatureGrid, Icon, Steps, TechStack, etc.) - Restructure sidebar with logical groupings and clearer hierarchy - Add new documentation pages for prerequisites, deployment verification, costs - Improve AWS deployment documentation with step-by-step guides - Add coding standards pages for ESLint and Prettier - Create index pages for tests, emails, GraphQL, dev-tools, and async-workers sections - Update introduction pages with enhanced visual presentation - Improve Docusaurus configuration with better prism theme colors - Minor fixes to webapp components (badge stories, tests, dropdown menu) * feat: Add Enterprise SSO, Passkeys, and Active Sessions management - Enterprise SSO (Single Sign-On): - Add OIDC/SAML provider support for tenant-level SSO configuration - Add SSO discovery flow with email domain detection - Add SSO callback and error handling routes - Add tenant security settings with SSO connection management - Add webapp-sso library with SSO components - Passkeys (WebAuthn): - Add passkey registration and authentication components - Add passkey login button component - Add passkey management form in profile settings - Active Sessions: - Add active sessions management component - Allow users to view and revoke sessions - Backend changes: - Add new SSO app with OIDC service and authentication - Add tenant member migration for SSO support - Update JWT handling for SSO tokens - Update schema and settings for SSO configuration - Documentation: - Add comprehensive Enterprise SSO documentation - Update authentication features documentation - Add environment variables documentation for SSO * fix(audit-logs): fix 401 errors and improve UI - Add setupStoreInterceptors() to enable JWT token refresh on 401 errors - Export setupStoreInterceptors from webapp-api-client/api - Add missing event types (session/device events) to audit log filters - Move Failed badge to right side of log entry header - Move results count from header to filters section with proper pluralization * feat(security): improve UI/UX consistency across security settings cards - Redesign SSO Connection Card with dropdown actions, status badges, tooltips - Update Directory Sync Card UI to match SSO Card patterns - Update Audit Log Card UI with consistent header, empty states, and log items - Fix modal border overflow issue (2px borders outside rounded corners) - Add comprehensive tests for TenantSecuritySettings component - Add comprehensive tests for SSOConnectionCard component Components updated: - ssoConnectionCard.tsx: Dropdown menu, status badges, stats row with tooltips - directorySyncCard.tsx: Consistent header, empty states, token cards with actions - auditLogCard.tsx: Consistent header, filter panel, log entry cards - addSSOConnectionModal.tsx: Fixed overflow with sm:rounded-lg - addPasskeyModal.tsx: Fixed overflow with sm:rounded-lg - addTwoFactorAuth.component.tsx: Fixed overflow with sm:rounded-lg - passkeysForm.component.tsx: Fixed overflow with sm:rounded-lg Tests added: - tenantSecuritySettings.component.spec.tsx (6 tests) - ssoConnectionCard.component.spec.tsx (15 tests) * feat: add dynamic translations system with remote loading Backend: - Add translations Django app with Locale, Translation, TranslationFile models - Add GraphQL schema for querying available locales and translation files - Add management commands for syncing and publishing translations - Add AI translation service integration for automated translations - Add admin interface with AI translation actions - Add S3 publishing for translation files with CloudFront CDN support - Add ACL policies for translation access Frontend: - Add DynamicIntlProvider for loading translations from remote sources - Add useRemoteTranslations hook for fetching translations from API/CDN - Add useAvailableLocales hook for providing available locale list - Add DefaultLocaleRedirect component for locale-aware routing - Add LanguageSwitcher component to header with flag icons - Enhance FloatingThemeToggle with language switching on auth pages - Add translation files for German, Spanish, French languages - Add master.json template for translation extraction Scripts & Tools: - Add generateMasterTranslations.js for extracting translatable strings - Add syncTranslations.js for syncing with backend API Infrastructure: - Add translations infrastructure component for S3/CloudFront setup Documentation: - Add feature documentation for translations system - Add how-to guides for managing translations and AI translation * Update translations admin template and SSO admin configuration * chore(release): 4.2.0 * chore: finalize release 4.2.0 with all pending changes - Update SSO and translations implementations - Update docker-compose configurations - Update GraphQL schema and generated types - Update test files and fixtures - Add migration files - Update documentation - Update dependencies and lock files - Add release planning documentation * chore: improve testing infrastructure and translations sync - Update Storybook configuration and add proper package.json for dependencies - Enhance translation sync script with improved fetching and error handling - Fix GraphQL codegen to remove duplicate types and improve Apollo client setup - Update auth component hooks and tests to align with latest patterns - Improve test utilities and fixtures for better testing experience - Update environment configurations across packages - Add proper mocks for apollo-upload-client in tests - Update component stories to use new storybook utilities * fix: resolve blank page issue after login/logout - Add explicit navigation to home page after successful login instead of relying on AnonymousRoute redirect - Remove invalidateApolloStore() calls that were clearing user data and causing the CommonQuery component to render nothing - Fix OTP validation form to navigate after successful verification - Replace FormattedMessage render prop with useIntl hook to fix React key warning * fix: resolve GraphQL type collision and improve 2FA UX - Fix RenamePasskeyMutation duplicate type error by renaming mutation operation - Upgrade react-markdown to v10 for React 19 compatibility - Update ReactMarkdown usage to wrap in div (className prop removed in v10) - Redesign Two-factor Authentication panel with better UX: - Add status indicators with enabled/disabled visual states - Add confirmation dialog for disabling 2FA - Improve styling to match Passkeys component pattern - Update tests to match new UI text * fix: improve UX for language switcher and subscription empty states - Fix language switcher flash: show skeleton placeholder instead of uppercase locale code (e.g., "DE") during brief reload when switching languages - Improve subscription empty states with centered icons and helpful descriptions - Add developer hints for configuring Stripe subscription plans - Update admin panel credentials display to show env variable names with instructions on where to find/configure them - Stop tracking .nx/workspace-data files (already in .gitignore) * fix: try token refresh before redirecting to login on 401 errors Previously, 401 network errors caused immediate redirect to login without attempting to refresh the token first. This caused users to be logged out after just 5 minutes of inactivity (access token lifetime). Changes: - On 401 errors, attempt token refresh first before redirecting - Only redirect to login if the refresh token itself fails - Add request queueing to prevent multiple simultaneous refresh attempts - Remove immediate redirect from retryLink (let refreshTokenLink handle it) This fixes the issue where users were logged out after short periods of tab inactivity, even though their refresh token (7 days) was still valid. * fix: resolve LocalStack S3 configuration for local development - Add s3 service to LocalStack SERVICES list to enable S3 functionality - Configure AWS_S3_CUSTOM_DOMAIN to use localhost:4566 for browser-accessible URLs - Add AWS_S3_URL_PROTOCOL setting to use http:// instead of https:// - Replace AWS CLI with boto3 for S3 bucket creation to avoid CLI compatibility issues This fixes avatar upload and image loading issues when running locally with LocalStack. * feat: add unread notifications count and improve admin features Notifications: - Add unreadNotificationsCount field to GraphQL schema - Display notification count badge on notifications button - Include hasUnreadNotifications in mark all read mutation response Admin: - Add sync action for Stripe Product and Price models - Fix HTML template formatting in translation admin pages * fix: resolve Jest ESM compatibility and test assertion issues - Add apollo-upload-client mock for Jest ESM compatibility - Add react-markdown mock for components using Markdown rendering - Fix usePaginatedQuery hook to properly cleanup on unmount and handle aborted requests - Update test assertions from .newData to .result (matches composeMockedQueryResult pattern) - Fix form value assertions to use toHaveValue() instead of getAttribute('value') - Update React 19 compatibility for function component second argument (undefined vs {}) - Fix mock ordering and waitForApolloMocks timing in Stripe payment tests - Update snapshot for tenantMembersList component All 424 webapp tests now pass across 11 packages. * fix: resolve ruff linting issues and improve code quality - Fix nx project name for backend (add explicit "name": "backend" to project.json) - Use defusedxml instead of xml.etree.ElementTree for SAML parsing (S314) - Add HTTP_BAD_REQUEST constant to avoid magic values (PLR2004) - Reorder Django model methods per style guide (DJ012) - Add __str__ method to WebAuthnChallenge model (DJ008) - Simplify conditionals with ternary operators (SIM108, SIM103) - Use dict.get() instead of if/else blocks (SIM401) - Move imports to top of file (E402) - Fix line length issues (E501) - Run black formatter on all backend files * fix: prevent blank page on session expiration and improve auth error handling - Handle expired JWT tokens gracefully in backend authentication - Return None instead of raising exception for invalid tokens - Allows AllowAny endpoints to work with expired cookies (login page) - Improve Apollo client auth error recovery - Clear Apollo cache before redirecting to login - Consolidate redirectToLogin as single source of truth - Limit WebSocket reconnection attempts to prevent infinite loops - Add CommonQuery error handling to prevent blank pages - Detect auth errors and trigger fallback redirect - Return empty context instead of null on errors - Improve error boundary with recovery options - Add "Refresh Page", "Clear Cache & Refresh", "Go to Login" buttons - Fix key prop warning on login page * chore: upgrade Storybook to v10 and fix compatibility issues - Upgrade Storybook packages from 8.x to 10.x - Remove unused storybook-react-router and storybook-dark-mode packages - Update .storybook/main.ts for ESM compatibility (__dirname → import.meta.url) - Add stubs for @storybook/addon-actions, msw/browser, msw/core/http - Fix stories glob pattern to exclude node_modules duplicates - Remove deprecated @storybook/addon-essentials (now built into core) * fix: resolve email template React warnings and story issues - Add tbody wrapper to table in layout component (fixes hydration error) - Replace align attr with text-align CSS in layout styles (fixes unknown prop warning) - Destructure linkTo prop in button to prevent DOM prop leakage - Add required token/tenantMembershipId args to TenantInvitation story - Update story to CSF3 format for consistency * feat(emails): overhaul email templates with modern design system - Add email-specific theme with colors, spacing, fonts, and layout constants - Create new base components: Preheader, Footer, Divider, Heading, Text - Enhance Button with bulletproof pattern, variants (primary/secondary/outline), and inline mode - Refactor Layout with header/body/footer structure and dark mode support - Add mobile-responsive styles with CSS media queries - Update all 7 email templates with preheader text and footer - Add responsive card-based mobile view for UserExportAdmin table - Update Storybook stories with proper args and mobile viewport variants - Sync translations with new email message IDs * copy(emails): improve email copy for better user experience - Rewrite all 7 email templates with warmer, conversational tone - Use action-oriented CTAs with first-person language ("Verify my email") - Add reassuring language for security-related emails - Create value-focused messaging with appropriate urgency - Make preheaders complement subjects instead of repeating them - Sync translations with updated message keys * feat: add user preferred language and password strength validation - Add language preference to user profile (stored in DB) - Send emails in user's preferred language with dynamic translations - Add password strength indicator and requirements to signup, reset password, and change password forms - Show concise password requirements with proper empty state handling - Frontend validation mirrors Django's password validators (min length, common passwords, numeric-only) * feat: SB improvements * chore: Comment render deployment * fix: Update github runners * deps: Update GH actions nodejs versions * fix: Fix Sonarcube scans * fix: Fix ruff formating * fix: Reformat files * fix: Add missing migration * fix: Fix tests * fix: Fix tests * fix: Fix tests * fix: Fix sonar issue * fix: Fix CDK issue * feat: Replace pdm with uv in workers * feat: Replace pdm with uv in backend * fix: Fix workers tests * fix: Increase the nodejs memory to fix docs build * fix: Update docusaurus and fix docs build * fix: Remove not used MentionEditor component * chore: Tidy components and add tests * fix: Exclude setup.py from test coverage * chore: Increase code coverage in webapp-tenants * chore: Add some backend tests * fix: Increase test coverage for the webapp crud demo package * fix: Increase test coverage for the webapp core package * fix: Increase test coverage for the webapp tenants package * fix: Increase test coverage for the webapp notification package * fix: Fix failing snapshot * fix: Increase test coverage for the webapp notifications package * fix: Increase test coverage for the webapp package * fix: Increase test coverage for the webapp tenants package * fix: tenant removal, fix for status, fix token refresh mechanism * fix tenant removal * dont display overdue if invoiced * fix refreshing token after access token lifetime expiration * chore: Regenerate graphql schema * chore: Add tests in webapp tenants package * fix: Fix accessibility issues * fix: Backend tests * chore: Add tests * chore: Exclude files from sonar cloud * Fix: Fix sonar cloud finding * chore: Increase test coverage in webapp emails package * chore: Increase test coverage in webapp notifications package * chore: Add coverage to .gitignore * chore: Increase backend test coverage * chore: Increase code coverage in webapp contentful package * chore: Refactor contentful changes * chore: Increase test coverage in webapp tenants package * chore: Increase test coverage * feat: Refactor SSO API * refactor: Refactor scripts and run migrations in proper way * feat: Refactor AI assistant * Updates for release 5.0.0 (#689) * fix: Decimal conversion * fix: Notifications list fixes, ACL checks fixes * feat: Tenant XML backup * fix: Fix RBAC role check * refactor: Refactor Markdown and Mention Editors to Enhance Mention Rendering * feat: Remove legacy and use RBAC for personal tenant * fix: SSO fixes * chore: Reformat files * chore: Update uv.lock * fix: Fix formatting issues and missing migrations * fix: Fix typing issues * fix: Fix tests * fix: Fix tests * chore: Regenerate graphql * fix: Fix webapp tests * fix: Fix webapp tests * chore: Move mcp server to the correct directory --------- Co-authored-by: Zbigniew Czarnecki <zczarnecki@apptension.com>
1 parent 3c7cf6e commit 9dd5d19

File tree

1,392 files changed

+240909
-28957
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

1,392 files changed

+240909
-28957
lines changed

.cursor/rules/backend.mdc

Lines changed: 341 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,341 @@
1+
---
2+
description: Backend Python/Django patterns and best practices
3+
globs: ["**/*.py"]
4+
alwaysApply: false
5+
---
6+
7+
# Backend Development Patterns
8+
9+
## Imports
10+
11+
**Avoid inline imports.** Place all imports at the top of the file.
12+
13+
```python
14+
# ❌ WRONG - Inline import inside function/method
15+
def test_something(self):
16+
from ..models import TenantMembershipRole
17+
...
18+
19+
# ✅ CORRECT - Import at module top
20+
from ..models import TenantMembership, TenantMembershipRole
21+
22+
def test_something(self):
23+
...
24+
```
25+
26+
Exceptions: circular import workarounds (e.g. in migrations using `apps.get_model`) or lazy imports inside `TYPE_CHECKING` blocks.
27+
28+
## GraphQL Mutation with Serializer
29+
30+
Create a serializer-based mutation in three steps:
31+
32+
### 1. Create the Serializer (`serializers.py`)
33+
34+
```python
35+
from rest_framework import serializers, exceptions
36+
from hashid_field import rest as hidrest
37+
from graphql_relay import to_global_id
38+
39+
class MyFeatureSerializer(serializers.Serializer):
40+
"""
41+
Docstring describing what this serializer does.
42+
"""
43+
id = hidrest.HashidSerializerCharField(
44+
source_field="myapp.MyModel.id",
45+
write_only=True
46+
)
47+
tenant_id = serializers.CharField(write_only=True)
48+
ok = serializers.BooleanField(read_only=True)
49+
50+
def validate(self, attrs):
51+
# Get tenant from request context
52+
tenant = self.context["request"].tenant
53+
54+
# Find the object
55+
obj = MyModel.objects.filter(pk=attrs["id"], tenant=tenant).first()
56+
57+
if not obj:
58+
raise exceptions.NotFound(_("Object not found."))
59+
60+
# Store for use in create()
61+
attrs["obj"] = obj
62+
return super().validate(attrs)
63+
64+
def create(self, validated_data):
65+
obj = validated_data["obj"]
66+
67+
# Perform the action
68+
# ...
69+
70+
return {"ok": True}
71+
```
72+
73+
### 2. Create the Mutation (`schema.py`)
74+
75+
```python
76+
from graphql_relay import from_global_id
77+
from common.graphql import mutations
78+
79+
class MyFeatureMutation(mutations.SerializerMutation):
80+
ok = graphene.Boolean()
81+
82+
class Meta:
83+
serializer_class = serializers.MyFeatureSerializer
84+
85+
@classmethod
86+
def mutate_and_get_payload(cls, root, info, **input):
87+
# Convert global ID to local ID
88+
if "id" in input:
89+
_, input["id"] = from_global_id(input["id"])
90+
return super().mutate_and_get_payload(root, info, **input)
91+
```
92+
93+
### 3. Register in Mutation Class
94+
95+
```python
96+
@permission_classes(policies.IsTenantOwnerAccess)
97+
class TenantOwnerMutation(graphene.ObjectType):
98+
my_feature = MyFeatureMutation.Field()
99+
```
100+
101+
## Sending Emails from Serializers
102+
103+
```python
104+
from common import emails
105+
106+
class MyEmailNotification(emails.Email):
107+
name = 'MY_EMAIL_TYPE'
108+
serializer_class = email_serializers.MyEmailSerializer
109+
110+
# In serializer.create():
111+
def create(self, validated_data):
112+
obj = validated_data["obj"]
113+
114+
MyEmailNotification(
115+
to=obj.user.email,
116+
data={'object_id': global_id, 'token': token},
117+
).send()
118+
119+
return {"ok": True}
120+
```
121+
122+
## Sending In-App Notifications
123+
124+
```python
125+
from apps.notifications import sender
126+
from . import constants
127+
128+
def send_my_notification(obj, obj_id: str):
129+
if obj.user:
130+
sender.send_notification(
131+
user=obj.user,
132+
type=constants.Notification.MY_NOTIFICATION_TYPE.value,
133+
data={
134+
"id": obj_id,
135+
"name": obj.name,
136+
},
137+
issuer=obj.creator,
138+
)
139+
```
140+
141+
## Token Generation for Secure Actions
142+
143+
```python
144+
from .tokens import my_token_generator
145+
146+
# Generate token
147+
token = my_token_generator.make_token(
148+
user_email=email,
149+
obj=obj
150+
)
151+
global_id = to_global_id("MyObjectType", obj.id)
152+
153+
# Validate token
154+
if not my_token_generator.check_token(email, token, obj):
155+
raise exceptions.ValidationError(_("Invalid token"))
156+
```
157+
158+
## Backend Test Patterns
159+
160+
### CRITICAL: Use pytest fixtures, NOT django.test.TestCase
161+
162+
```python
163+
# ❌ WRONG - Can cause DB connection issues (InterfaceError: connection already closed)
164+
from django.test import TestCase
165+
166+
class MyTests(TestCase):
167+
def test_something(self):
168+
pass
169+
170+
# ✅ CORRECT - Use pytest fixtures
171+
import pytest
172+
173+
pytestmark = pytest.mark.django_db
174+
175+
class TestMyFeature:
176+
def test_something(self, user_factory, tenant_factory):
177+
pass
178+
```
179+
180+
### Testing Serializers
181+
182+
```python
183+
import pytest
184+
from unittest.mock import Mock
185+
186+
pytestmark = pytest.mark.django_db
187+
188+
class TestMySerializer:
189+
def test_success_case(self, mocker, user_factory, tenant_factory):
190+
# Mock external calls
191+
mocker.patch("apps.myapp.tokens.TokenGenerator.make_token", return_value="token")
192+
mock_send_email = mocker.patch("apps.myapp.serializers.MyEmail")
193+
194+
# Setup
195+
tenant = tenant_factory(name="Test", type=TenantType.ORGANIZATION)
196+
197+
data = {
198+
"id": obj.id,
199+
"tenant_id": str(tenant.id),
200+
}
201+
202+
serializer = MySerializer(
203+
data=data,
204+
context={'request': Mock(tenant=tenant, user=user)}
205+
)
206+
assert serializer.is_valid()
207+
208+
result = serializer.create(serializer.validated_data)
209+
210+
assert result['ok']
211+
mock_send_email.assert_called_once()
212+
213+
def test_not_found(self, tenant_factory):
214+
tenant = tenant_factory()
215+
216+
data = {"id": "nonexistent", "tenant_id": str(tenant.id)}
217+
serializer = MySerializer(
218+
data=data,
219+
context={'request': Mock(tenant=tenant)}
220+
)
221+
222+
assert not serializer.is_valid()
223+
```
224+
225+
### Testing API Views with Authentication
226+
227+
```python
228+
import pytest
229+
from rest_framework.test import APIClient
230+
231+
pytestmark = pytest.mark.django_db
232+
233+
class TestMyAPIView:
234+
def test_authenticated_request(self, user_factory, tenant_factory):
235+
user = user_factory()
236+
tenant = tenant_factory()
237+
238+
client = APIClient()
239+
client.force_authenticate(user=user)
240+
241+
response = client.post(
242+
f"/api/my-endpoint/{tenant.id}/",
243+
{"key": "value"},
244+
format="json"
245+
)
246+
247+
assert response.status_code == 200
248+
249+
def test_streaming_response(self, user_factory, tenant_factory):
250+
"""Testing StreamingHttpResponse views"""
251+
user = user_factory()
252+
tenant = tenant_factory()
253+
254+
client = APIClient()
255+
client.force_authenticate(user=user)
256+
257+
response = client.post(
258+
f"/api/streaming-endpoint/{tenant.id}/",
259+
{"message": "test"},
260+
format="json"
261+
)
262+
263+
# For streaming responses, read content as bytes
264+
assert response.status_code == 200
265+
content = b"".join(response.streaming_content)
266+
assert b"expected_data" in content
267+
```
268+
269+
### Factory Boy: Avoiding Duplicate Creation
270+
271+
```python
272+
from factory.django import DjangoModelFactory
273+
import factory
274+
275+
class OrganizationSettingsFactory(DjangoModelFactory):
276+
class Meta:
277+
model = OrganizationSettings
278+
# CRITICAL: Prevents duplicate creation errors
279+
django_get_or_create = ("tenant",)
280+
281+
tenant = factory.SubFactory(TenantFactory)
282+
```
283+
284+
## Permission Patterns
285+
286+
Use decorators for permission control:
287+
288+
```python
289+
from common.acl import policies
290+
from common.graphql.acl.decorators import permission_classes
291+
292+
# Owner-only mutations
293+
@permission_classes(policies.IsTenantOwnerAccess)
294+
class TenantOwnerMutation(graphene.ObjectType):
295+
sensitive_action = SensitiveMutation.Field()
296+
297+
# Admin or owner mutations
298+
@permission_classes(policies.IsTenantAdminAccess)
299+
class TenantAdminMutation(graphene.ObjectType):
300+
admin_action = AdminMutation.Field()
301+
```
302+
303+
## GraphQL Schema Workflow
304+
305+
When adding new GraphQL mutations or queries, follow this workflow:
306+
307+
1. **Update Backend Schema** (`packages/backend/apps/<app>/schema.py`)
308+
- Create mutation class with Arguments, return types, and mutate method
309+
- Register in appropriate Mutation class (TenantOwnerMutation, etc.)
310+
311+
2. **Download Updated Schema** (backend must be running!)
312+
```bash
313+
pnpm nx run webapp-api-client:graphql:download-schema
314+
```
315+
316+
3. **Add Frontend GraphQL Operations** (`packages/webapp-libs/webapp-<lib>/src/.../feature.graphql.ts`)
317+
```typescript
318+
export const myMutation = gql(/* GraphQL */ `
319+
mutation MyMutation($tenantId: ID!, $input: SomeInput!) {
320+
myMutation(tenantId: $tenantId, input: $input) {
321+
success
322+
result { id }
323+
}
324+
}
325+
`);
326+
```
327+
328+
4. **Generate TypeScript Types**
329+
```bash
330+
pnpm nx run webapp-api-client:graphql:generate-types
331+
```
332+
333+
5. **Use in Components**
334+
```typescript
335+
import { useMutation } from '@apollo/client';
336+
import { myMutation } from './feature.graphql';
337+
338+
const [commitMutation, { loading }] = useMutation(myMutation);
339+
```
340+
341+
**Important**: The backend server must be running (`pnpm saas up`) for schema download to work!

0 commit comments

Comments
 (0)