From d538cfab4590eb0995e3c271dfcfc362b6999928 Mon Sep 17 00:00:00 2001 From: marcelo-m7 Date: Sun, 9 Nov 2025 11:53:02 +0000 Subject: [PATCH 1/5] docs: update accessibility guidelines and project descriptions for clarity --- docs/guidelines/accessibility.md | 651 +++++++++++++++-------------- docs/projects/sweet-price/index.md | 51 +-- docs/repositories/index.mdx | 64 +-- 3 files changed, 365 insertions(+), 401 deletions(-) diff --git a/docs/guidelines/accessibility.md b/docs/guidelines/accessibility.md index f9886b6..ca802c7 100644 --- a/docs/guidelines/accessibility.md +++ b/docs/guidelines/accessibility.md @@ -1,318 +1,333 @@ -# Accessibility Guidelines - -This document outlines the accessibility standards and practices followed by Monynha Softwares to ensure our digital products are usable by everyone, including people with disabilities. - -## Accessibility Principles - -### Universal Design - -Our approach to accessibility is guided by universal design principles: - -- **Equitable Use**: The design is useful and marketable to people with diverse abilities -- **Flexibility in Use**: The design accommodates a wide range of individual preferences and abilities -- **Simple and Intuitive Use**: Use of the design is easy to understand, regardless of the user's experience -- **Perceptible Information**: The design communicates necessary information effectively -- **Tolerance for Error**: The design minimizes hazards and the adverse consequences of accidental or unintended actions -- **Low Physical Effort**: The design can be used efficiently and comfortably with a minimum of fatigue -- **Size and Space for Approach and Use**: Appropriate size and space is provided for approach, reach, manipulation, and use - -### Legal Compliance - -We adhere to international accessibility standards: - -- **WCAG 2.1 AA**: Web Content Accessibility Guidelines 2.1 Level AA compliance -- **Section 508**: United States federal accessibility standards -- **EN 301 549**: European accessibility requirements for public procurement -- **Local Regulations**: Compliance with accessibility laws in target markets - -## Web Accessibility Standards - -### WCAG 2.1 Success Criteria - -#### Level A (Minimum Requirements) - -- **1.1.1 Non-text Content**: All non-text content has text alternatives -- **1.3.1 Info and Relationships**: Information and relationships are conveyed through presentation -- **1.3.2 Meaningful Sequence**: The reading sequence is logical and meaningful -- **1.4.1 Use of Color**: Color is not used as the only visual means of conveying information -- **2.1.1 Keyboard**: All functionality is available from a keyboard -- **2.1.2 No Keyboard Trap**: Keyboard focus is never trapped in a component -- **2.4.1 Bypass Blocks**: A mechanism is available to bypass blocks of content -- **2.4.2 Page Titled**: Web pages have descriptive titles -- **3.1.1 Language of Page**: The default human language is identified -- **4.1.1 Parsing**: Markup is used properly and elements have complete start and end tags - -#### Level AA (Target Requirements) - -- **1.2.4 Captions (Live)**: Captions are provided for all live audio content -- **1.2.5 Audio Description (Prerecorded)**: Audio description is provided for prerecorded video -- **1.3.4 Orientation**: Content does not restrict its view and operation to a single display orientation -- **1.3.5 Identify Input Purpose**: The purpose of input fields is programmatically determinable -- **1.4.3 Contrast (Minimum)**: Text and images of text have a contrast ratio of at least 4.5:1 -- **1.4.4 Resize text**: Text can be resized without assistive technology up to 200% without loss of content -- **1.4.10 Reflow**: Content can be presented without loss of information or functionality at width of 320 CSS pixels -- **1.4.11 Non-text Contrast**: Non-text content has a contrast ratio of at least 3:1 -- **1.4.12 Text Spacing**: No loss of content or functionality when text spacing is modified -- **1.4.13 Content on Hover or Focus**: Additional content on hover/focus can be dismissed and is hoverable -- **2.4.5 Multiple Ways**: More than one way is available to locate a web page -- **2.4.6 Headings and Labels**: Headings and labels are descriptive -- **2.4.7 Focus Visible**: Any keyboard operable user interface has a mode of operation where the keyboard focus indicator is visible -- **3.1.2 Language of Parts**: The human language of each passage is identified -- **3.2.3 Consistent Navigation**: Navigational mechanisms that are repeated on multiple web pages occur in the same relative order -- **3.2.4 Consistent Identification**: Components with the same functionality are identified consistently -- **3.3.3 Error Suggestion**: If an input error is automatically detected, suggestions are provided -- **3.3.4 Error Prevention (Legal, Financial, Data)**: Submissions can be reversed for legal/financial/data errors - -## Implementation Guidelines - -### Semantic HTML - -#### Document Structure - -- **Proper Heading Hierarchy**: Use h1-h6 elements in logical order -- **Semantic Elements**: Use header, nav, main, section, article, aside, footer appropriately -- **Landmarks**: Implement ARIA landmarks for screen reader navigation -- **Document Outline**: Ensure logical document structure for assistive technologies - -#### Form Accessibility - -- **Label Association**: All form controls have associated labels -- **Fieldsets and Legends**: Group related form controls with fieldsets -- **Error Identification**: Clearly identify form errors and provide suggestions -- **Required Fields**: Indicate required fields both visually and programmatically - -### Keyboard Navigation - -#### Focus Management - -- **Logical Tab Order**: Tab order follows logical reading order -- **Focus Indicators**: Visible focus indicators for all interactive elements -- **Focus Trapping**: Appropriate use of focus trapping in modals and menus -- **Skip Links**: Provide skip navigation links for keyboard users - -#### Keyboard Shortcuts - -- **Standard Shortcuts**: Support common keyboard shortcuts where appropriate -- **Custom Shortcuts**: Document any custom keyboard shortcuts -- **Shortcut Conflicts**: Avoid conflicts with assistive technology shortcuts -- **Shortcut Customization**: Allow users to customize or disable shortcuts - -### Color and Contrast - -#### Color Usage - -- **Color Independence**: Information is not conveyed by color alone -- **Color Contrast**: Minimum 4.5:1 contrast ratio for normal text, 3:1 for large text -- **Color Blindness**: Design works for all types of color vision deficiency -- **High Contrast Mode**: Support for high contrast display modes - -#### Visual Design - -- **Text Alternatives**: Meaningful alt text for all images -- **Icon Alternatives**: Text alternatives for icon-only buttons -- **Color Coding**: Use patterns, shapes, or text in addition to color -- **Focus Indicators**: High contrast focus indicators - -### Multimedia Accessibility - -#### Audio Content - -- **Transcripts**: Provide transcripts for audio-only content -- **Captions**: Synchronized captions for video content -- **Audio Description**: Descriptive narration for video content -- **Volume Control**: User control over audio volume - -#### Video Content - -- **Sign Language**: Provide sign language interpretation where appropriate -- **Descriptive Audio**: Audio description tracks for visual content -- **Text Transcripts**: Full text transcripts for video content -- **Media Controls**: Accessible media player controls - -### Motion and Animation - -#### Motion Sensitivity - -- **Reduced Motion**: Respect user's motion preferences (prefers-reduced-motion) -- **Animation Controls**: Provide controls to pause or disable animations -- **Essential Motion**: Only use motion for essential functionality -- **Motion Duration**: Keep animations short and non-distracting - -#### Animation Guidelines - -- **Smooth Transitions**: Use easing functions for natural motion -- **Animation Triggers**: Avoid unexpected animations -- **Loading Animations**: Provide alternatives for loading states -- **Parallax Effects**: Use cautiously and provide alternatives - -## Assistive Technology Support - -### Screen Readers - -#### Screen Reader Compatibility - -- **Semantic Markup**: Proper use of headings, lists, and landmarks -- **ARIA Attributes**: Appropriate use of ARIA labels, descriptions, and states -- **Live Regions**: Use ARIA live regions for dynamic content updates -- **Form Labels**: Explicit association between labels and form controls - -#### Content Presentation - -- **Reading Order**: Logical reading order for screen reader users -- **Context Preservation**: Maintain context when content changes -- **Status Messages**: Announce status changes and errors -- **Navigation Landmarks**: Clear navigation structure for screen readers - -### Voice Control - -#### Voice Commands - -- **Standard Commands**: Support common voice control commands -- **Custom Commands**: Document any custom voice commands -- **Command Clarity**: Use clear, unambiguous command names -- **Feedback**: Provide audio feedback for voice interactions - -#### Voice Interface Design - -- **Natural Language**: Support natural language input -- **Confirmation**: Confirm voice commands before execution -- **Error Handling**: Clear error messages for voice input failures -- **Privacy**: Respect user privacy in voice interactions - -### Alternative Input Devices - -#### Switch Devices - -- **Switch Access**: Support for switch control devices -- **Scanning**: Implement appropriate scanning patterns -- **Activation**: Clear activation methods for switch users -- **Timing**: Adjustable timing for switch activation - -#### Head Pointers and Eye Tracking - -- **Large Targets**: Sufficient target sizes for imprecise pointing -- **Dwell Time**: Appropriate dwell times for activation -- **Calibration**: Support for device calibration -- **Accuracy**: Design for varying levels of input accuracy - -## Testing and Validation - -### Automated Testing - -#### Accessibility Testing Tools - -- **Lighthouse**: Google's accessibility auditing tool -- **axe-core**: Automated accessibility testing library -- **WAVE**: Web accessibility evaluation tool -- **Color Contrast Analyzers**: Automated contrast ratio checking - -#### Code Quality Tools - -- **ESLint Accessibility**: Linting rules for accessibility issues -- **Stylelint**: CSS linting for accessibility concerns -- **HTML Validators**: Markup validation for semantic correctness -- **Automated Regression Testing**: Continuous accessibility monitoring - -### Manual Testing - -#### User Testing - -- **Screen Reader Testing**: Testing with actual screen readers (NVDA, JAWS, VoiceOver) -- **Keyboard Testing**: Complete keyboard-only navigation testing -- **Assistive Technology Testing**: Testing with various assistive technologies -- **User Feedback**: Gathering feedback from users with disabilities - -#### Expert Review - -- **Accessibility Audits**: Professional accessibility audits -- **Heuristic Evaluation**: Expert review against accessibility guidelines -- **Code Review**: Peer review of accessibility implementation -- **Standards Compliance**: Verification of WCAG compliance - -### Ongoing Monitoring - -#### Continuous Integration - -- **Automated Checks**: Accessibility checks in CI/CD pipelines -- **Regression Prevention**: Automated detection of accessibility regressions -- **Performance Monitoring**: Tracking accessibility metrics over time -- **Issue Tracking**: Systematic tracking and resolution of accessibility issues - -#### User Feedback Integration - -- **Feedback Mechanisms**: Ways for users to report accessibility issues -- **Issue Prioritization**: Prioritizing accessibility issues based on impact -- **Resolution Tracking**: Tracking resolution of reported accessibility problems -- **Improvement Metrics**: Measuring accessibility improvements over time - -## Documentation and Training - -### Accessibility Documentation - -#### Developer Guidelines - -- **Coding Standards**: Accessibility requirements in coding standards -- **Code Examples**: Accessible code examples and patterns -- **Testing Procedures**: Accessibility testing procedures for developers -- **Review Checklists**: Accessibility checklists for code reviews - -#### Content Author Guidelines - -- **Content Standards**: Accessibility standards for content creation -- **Image Guidelines**: Alt text and image accessibility guidelines -- **Document Standards**: Accessibility standards for documents and PDFs -- **Multimedia Guidelines**: Accessibility requirements for multimedia content - -### Team Training - -#### Accessibility Training - -- **Developer Training**: Technical accessibility training for developers -- **Designer Training**: Accessibility principles for designers -- **Content Training**: Accessibility training for content authors -- **Testing Training**: Accessibility testing and evaluation training - -#### Awareness Programs - -- **Accessibility Champions**: Designated accessibility advocates in teams -- **Regular Workshops**: Ongoing accessibility education and updates -- **External Resources**: Access to accessibility learning resources -- **Community Engagement**: Participation in accessibility communities - -## Tools and Resources - -### Development Tools - -#### Accessibility Tools - -- **Browser Extensions**: WAVE, axe, Accessibility Insights -- **Development Tools**: Chrome DevTools accessibility features -- **Color Pickers**: Contrast ratio checking tools -- **Screen Reader Emulators**: Tools for testing screen reader behavior - -#### Design Tools - -- **Accessibility Checkers**: Built-in accessibility features in design tools -- **Color Contrast Tools**: Real-time contrast ratio checking -- **Simulation Tools**: Tools for simulating various disabilities -- **Pattern Libraries**: Accessible component libraries and patterns - -### Reference Materials - -#### Standards and Guidelines - -- **WCAG 2.1**: Complete Web Content Accessibility Guidelines -- **WAI-ARIA**: Accessible Rich Internet Applications specifications -- **Section 508**: Federal accessibility standards and guidelines -- **International Standards**: Accessibility standards from various countries - -#### Best Practices - -- **Accessibility Patterns**: Established patterns for common accessibility challenges -- **Case Studies**: Real-world examples of accessible design -- **Research Papers**: Latest research in accessibility and inclusive design -- **Community Resources**: Accessibility blogs, forums, and communities - -This comprehensive approach to accessibility ensures that all Monynha Softwares products are inclusive, usable, and compliant with the highest accessibility standards, providing equal access to digital experiences for everyone. - - \ No newline at end of file +# Accessibility Guidelines + +This document outlines the accessibility standards and practices followed by Monynha Softwares to ensure our digital products are usable by everyone, including people with disabilities. + +## Accessibility Principles + +### Universal Design + +Our approach to accessibility is guided by universal design principles: + +- **Equitable Use**: The design is useful and marketable to people with diverse abilities +- **Flexibility in Use**: The design accommodates a wide range of individual preferences and abilities +- **Simple and Intuitive Use**: Use of the design is easy to understand, regardless of the user's experience +- **Perceptible Information**: The design communicates necessary information effectively +- **Tolerance for Error**: The design minimizes hazards and the adverse consequences of accidental or unintended actions +- **Low Physical Effort**: The design can be used efficiently and comfortably with a minimum of fatigue +- **Size and Space for Approach and Use**: Appropriate size and space is provided for approach, reach, manipulation, and use + +### Legal Compliance + +We adhere to international accessibility standards: + +- **WCAG 2.1 AA**: Web Content Accessibility Guidelines 2.1 Level AA compliance +- **Section 508**: United States federal accessibility standards +- **EN 301 549**: European accessibility requirements for public procurement +- **Local Regulations**: Compliance with accessibility laws in target markets + +## Web Accessibility Standards + +### WCAG 2.1 Success Criteria + +#### Level A (Minimum Requirements) + +- **1.1.1 Non-text Content**: All non-text content has text alternatives +- **1.3.1 Info and Relationships**: Information and relationships are conveyed through presentation +- **1.3.2 Meaningful Sequence**: The reading sequence is logical and meaningful +- **1.4.1 Use of Color**: Color is not used as the only visual means of conveying information +- **2.1.1 Keyboard**: All functionality is available from a keyboard +- **2.1.2 No Keyboard Trap**: Keyboard focus is never trapped in a component +- **2.4.1 Bypass Blocks**: A mechanism is available to bypass blocks of content +- **2.4.2 Page Titled**: Web pages have descriptive titles +- **3.1.1 Language of Page**: The default human language is identified +- **4.1.1 Parsing**: Markup is used properly and elements have complete start and end tags + +#### Level AA (Target Requirements) + +- **1.2.4 Captions (Live)**: Captions are provided for all live audio content +- **1.2.5 Audio Description (Prerecorded)**: Audio description is provided for prerecorded video +- **1.3.4 Orientation**: Content does not restrict its view and operation to a single display orientation +- **1.3.5 Identify Input Purpose**: The purpose of input fields is programmatically determinable +- **1.4.3 Contrast (Minimum)**: Text and images of text have a contrast ratio of at least 4.5:1 +- **1.4.4 Resize text**: Text can be resized without assistive technology up to 200% without loss of content +- **1.4.10 Reflow**: Content can be presented without loss of information or functionality at width of 320 CSS pixels +- **1.4.11 Non-text Contrast**: Non-text content has a contrast ratio of at least 3:1 +- **1.4.12 Text Spacing**: No loss of content or functionality when text spacing is modified +- **1.4.13 Content on Hover or Focus**: Additional content on hover/focus can be dismissed and is hoverable +- **2.4.5 Multiple Ways**: More than one way is available to locate a web page +- **2.4.6 Headings and Labels**: Headings and labels are descriptive +- **2.4.7 Focus Visible**: Any keyboard operable user interface has a mode of operation where the keyboard focus indicator is visible +- **3.1.2 Language of Parts**: The human language of each passage is identified +- **3.2.3 Consistent Navigation**: Navigational mechanisms that are repeated on multiple web pages occur in the same relative order +- **3.2.4 Consistent Identification**: Components with the same functionality are identified consistently +- **3.3.3 Error Suggestion**: If an input error is automatically detected, suggestions are provided +- **3.3.4 Error Prevention (Legal, Financial, Data)**: Submissions can be reversed for legal/financial/data errors + +## Implementation Guidelines + +### Semantic HTML + +#### Document Structure + +- **Proper Heading Hierarchy**: Use h1-h6 elements in logical order +- **Semantic Elements**: Use header, nav, main, section, article, aside, footer appropriately +- **Landmarks**: Implement ARIA landmarks for screen reader navigation +- **Document Outline**: Ensure logical document structure for assistive technologies + +#### Form Accessibility + +- **Label Association**: All form controls have associated labels +- **Fieldsets and Legends**: Group related form controls with fieldsets +- **Error Identification**: Clearly identify form errors and provide suggestions +- **Required Fields**: Indicate required fields both visually and programmatically + +### Keyboard Navigation + +#### Focus Management + +- **Logical Tab Order**: Tab order follows logical reading order +- **Focus Indicators**: Visible focus indicators for all interactive elements +- **Focus Trapping**: Appropriate use of focus trapping in modals and menus +- **Skip Links**: Provide skip navigation links for keyboard users + +#### Keyboard Shortcuts + +- **Standard Shortcuts**: Support common keyboard shortcuts where appropriate +- **Custom Shortcuts**: Document any custom keyboard shortcuts +- **Shortcut Conflicts**: Avoid conflicts with assistive technology shortcuts +- **Shortcut Customization**: Allow users to customize or disable shortcuts + +### Color and Contrast + +#### Color Usage + +- **Color Independence**: Information is not conveyed by color alone +- **Color Contrast**: Minimum 4.5:1 contrast ratio for normal text, 3:1 for large text +- **Color Blindness**: Design works for all types of color vision deficiency +- **High Contrast Mode**: Support for high contrast display modes + +#### Visual Design + +- **Text Alternatives**: Meaningful alt text for all images +- **Icon Alternatives**: Text alternatives for icon-only buttons +- **Color Coding**: Use patterns, shapes, or text in addition to color +- **Focus Indicators**: High contrast focus indicators + +### Multimedia Accessibility + +#### Audio Content + +- **Transcripts**: Provide transcripts for audio-only content +- **Captions**: Synchronized captions for video content +- **Audio Description**: Descriptive narration for video content +- **Volume Control**: User control over audio volume + +#### Video Content + +- **Sign Language**: Provide sign language interpretation where appropriate +- **Descriptive Audio**: Audio description tracks for visual content +- **Text Transcripts**: Full text transcripts for video content +- **Media Controls**: Accessible media player controls + +### Motion and Animation + +#### Motion Sensitivity + +- **Reduced Motion**: Respect user's motion preferences (prefers-reduced-motion) +- **Animation Controls**: Provide controls to pause or disable animations +- **Essential Motion**: Only use motion for essential functionality +- **Motion Duration**: Keep animations short and non-distracting + +#### Animation Guidelines + +- **Smooth Transitions**: Use easing functions for natural motion +- **Animation Triggers**: Avoid unexpected animations +- **Loading Animations**: Provide alternatives for loading states +- **Parallax Effects**: Use cautiously and provide alternatives + +## Assistive Technology Support + +### Screen Readers + +#### Screen Reader Compatibility + +- **Semantic Markup**: Proper use of headings, lists, and landmarks +- **ARIA Attributes**: Appropriate use of ARIA labels, descriptions, and states +- **Live Regions**: Use ARIA live regions for dynamic content updates +- **Form Labels**: Explicit association between labels and form controls + +#### Content Presentation + +- **Reading Order**: Logical reading order for screen reader users +- **Context Preservation**: Maintain context when content changes +- **Status Messages**: Announce status changes and errors +- **Navigation Landmarks**: Clear navigation structure for screen readers + +### Voice Control + +#### Voice Commands + +- **Standard Commands**: Support common voice control commands +- **Custom Commands**: Document any custom voice commands +- **Command Clarity**: Use clear, unambiguous command names +- **Feedback**: Provide audio feedback for voice interactions + +#### Voice Interface Design + +- **Natural Language**: Support natural language input +- **Confirmation**: Confirm voice commands before execution +- **Error Handling**: Clear error messages for voice input failures +- **Privacy**: Respect user privacy in voice interactions + +### Alternative Input Devices + +#### Switch Devices + +- **Switch Access**: Support for switch control devices +- **Scanning**: Implement appropriate scanning patterns +- **Activation**: Clear activation methods for switch users +- **Timing**: Adjustable timing for switch activation + +#### Head Pointers and Eye Tracking + +- **Large Targets**: Sufficient target sizes for imprecise pointing +- **Dwell Time**: Appropriate dwell times for activation +- **Calibration**: Support for device calibration +- **Accuracy**: Design for varying levels of input accuracy + +## Testing and Validation + +### Automated Testing + +#### Accessibility Testing Tools + +- **Lighthouse**: Google's accessibility auditing tool +- **axe-core**: Automated accessibility testing library +- **WAVE**: Web accessibility evaluation tool +- **Color Contrast Analyzers**: Automated contrast ratio checking + +#### Code Quality Tools + +- **ESLint Accessibility**: Linting rules for accessibility issues +- **Stylelint**: CSS linting for accessibility concerns +- **HTML Validators**: Markup validation for semantic correctness +- **Automated Regression Testing**: Continuous accessibility monitoring + +### Manual Testing + +#### User Testing + +- **Screen Reader Testing**: Testing with actual screen readers (NVDA, JAWS, VoiceOver) +- **Keyboard Testing**: Complete keyboard-only navigation testing +- **Assistive Technology Testing**: Testing with various assistive technologies +- **User Feedback**: Gathering feedback from users with disabilities + +#### Expert Review + +- **Accessibility Audits**: Professional accessibility audits +- **Heuristic Evaluation**: Expert review against accessibility guidelines +- **Code Review**: Peer review of accessibility implementation +- **Standards Compliance**: Verification of WCAG compliance + +### Ongoing Monitoring + +#### Continuous Integration + +- **Automated Checks**: Accessibility checks in CI/CD pipelines +- **Regression Prevention**: Automated detection of accessibility regressions +- **Performance Monitoring**: Tracking accessibility metrics over time +- **Issue Tracking**: Systematic tracking and resolution of accessibility issues + +#### User Feedback Integration + +- **Feedback Mechanisms**: Ways for users to report accessibility issues +- **Issue Prioritization**: Prioritizing accessibility issues based on impact +- **Resolution Tracking**: Tracking resolution of reported accessibility problems +- **Improvement Metrics**: Measuring accessibility improvements over time + +## Documentation and Training + +### Accessibility Documentation + +#### Developer Guidelines + +- **Coding Standards**: Accessibility requirements in coding standards +- **Code Examples**: Accessible code examples and patterns +- **Testing Procedures**: Accessibility testing procedures for developers +- **Review Checklists**: Accessibility checklists for code reviews + +#### Content Author Guidelines + +- **Content Standards**: Accessibility standards for content creation +- **Image Guidelines**: Alt text and image accessibility guidelines +- **Document Standards**: Accessibility standards for documents and PDFs +- **Multimedia Guidelines**: Accessibility requirements for multimedia content + +### Team Training + +#### Accessibility Training + +- **Developer Training**: Technical accessibility training for developers +- **Designer Training**: Accessibility principles for designers +- **Content Training**: Accessibility training for content authors +- **Testing Training**: Accessibility testing and evaluation training + +#### Awareness Programs + +- **Accessibility Champions**: Designated accessibility advocates in teams +- **Regular Workshops**: Ongoing accessibility education and updates +- **External Resources**: Access to accessibility learning resources +- **Community Engagement**: Participation in accessibility communities + +## Tools and Resources + +### Development Tools + +#### Accessibility Tools + +- **Browser Extensions**: WAVE, axe, Accessibility Insights +- **Development Tools**: Chrome DevTools accessibility features +- **Color Pickers**: Contrast ratio checking tools +- **Screen Reader Emulators**: Tools for testing screen reader behavior + +#### Design Tools + +- **Accessibility Checkers**: Built-in accessibility features in design tools +- **Color Contrast Tools**: Real-time contrast ratio checking +- **Simulation Tools**: Tools for simulating various disabilities +- **Pattern Libraries**: Accessible component libraries and patterns + +### Reference Materials + +#### Standards and Guidelines + +- **WCAG 2.1**: Complete Web Content Accessibility Guidelines +- **WAI-ARIA**: Accessible Rich Internet Applications specifications +- **Section 508**: Federal accessibility standards and guidelines +- **International Standards**: Accessibility standards from various countries + +#### Best Practices + +- **Accessibility Patterns**: Established patterns for common accessibility challenges +- **Case Studies**: Real-world examples of accessible design +- **Research Papers**: Latest research in accessibility and inclusive design +- **Community Resources**: Accessibility blogs, forums, and communities + +This comprehensive approach to accessibility ensures that all Monynha Softwares products are inclusive, usable, and compliant with the highest accessibility standards, providing equal access to digital experiences for everyone. + +## Quick smoke checks for docs contributors + +Run the site locally to verify accessibility-sensitive pages visually. On Windows use PowerShell; on macOS/Linux the same commands work in POSIX shells. + +```powershell +# Install dependencies +yarn install + +# Build and preview +yarn build +yarn serve +``` + +Use the axe browser extension or Lighthouse in Chrome DevTools for a quick automated audit. + +In PRs that change UI or content, add a short note in the PR description indicating the accessibility checks you ran (keyboard testing, screen reader check, or axe/Lighthouse results). \ No newline at end of file diff --git a/docs/projects/sweet-price/index.md b/docs/projects/sweet-price/index.md index 5b829a9..9a53943 100644 --- a/docs/projects/sweet-price/index.md +++ b/docs/projects/sweet-price/index.md @@ -1,47 +1,24 @@ # Sweet Price -## Overview +## Description -Sweet Price is a mobile and web application that helps shoppers in Portugal compare supermarket prices in real time. The product targets budget-conscious households and small businesses that need to optimise purchases across multiple retailers. +Supermarket price comparison app in Portugal. Currently supports: Pingo Doce and Continente supermarkets. -## Problem statement +## Technologies -- Supermarket prices vary significantly between regions and loyalty programs. -- Shoppers lack transparent insights into promotions, bundles, and substitutions. -- Manual price tracking is time consuming and quickly outdated. +- Node.js (backend services and data processing) +- Puppeteer or Cheerio (web scraping / price extraction) +- PostgreSQL (or another relational DB) for product/price storage +- React (or any modern frontend) for the web UI +- Docker for local development and deployment -## Product capabilities +Note: The exact stack may vary by repository — check the project README at the linked GitHub repository for implementation details. -1. **Price comparison engine** – Aggregates offers from Pingo Doce, Continente, and other retailers via public APIs and scraping pipelines. -2. **Shopping lists** – Users create lists, set budgets, and receive store-specific totals. -3. **Alerts** – Notify shoppers when favourite items drop below threshold prices. -4. **Insights dashboard** – Visualise savings, seasonal trends, and substitution recommendations. +## Repository -## Technology stack +[GitHub: Sweet-Price](https://github.com/Monynha-Softwares/Sweet-Price) -- **Mobile**: React Native app targeting iOS and Android, sharing UI components with the web client. -- **Web**: Next.js frontend for desktop users and admin tooling. -- **Backend**: Node.js + Convex for realtime data sync and background jobs. -- **Data ingestion**: Scheduled scrapers running on GitHub Actions with fallback manual upload scripts. -- **Storage**: PostgreSQL for transactional data, Redis for caching, Supabase storage for media. +## Features -## Data governance - -- Respect retailer terms of service; review legal guidance before adding new data sources. -- Store only aggregated price data—avoid personal information beyond hashed user IDs. -- Anonymise analytics and comply with GDPR consent requirements for tracking. - -## Roadmap - -| Initiative | Description | Status | -| --- | --- | --- | -| Loyalty program integration | Import Pingo Doce & Continente loyalty card data for personalised pricing. | Development | -| Receipt scanner | OCR-based feature to ingest receipts and enrich price database. | Discovery | -| Meal planning | Suggest weekly menus aligned with user budgets and preferences. | Planned | - -## Contribution guidelines - -- Keep scraping scripts idempotent and resilient to layout changes; add unit tests for parsers. -- Provide PT and EN copy for notifications and UI labels. -- Share performance benchmarks when touching the comparison algorithms. -- Document any new environment variables in `.env.example` and update infrastructure diagrams if relevant. +- Price comparison for Portuguese supermarkets +- Support for Pingo Doce and Continente diff --git a/docs/repositories/index.mdx b/docs/repositories/index.mdx index 104dd06..960d613 100644 --- a/docs/repositories/index.mdx +++ b/docs/repositories/index.mdx @@ -4,65 +4,37 @@ sidebar_position: 8 --- import Repositories from '@site/src/components/Repositories'; + import React from 'react'; # Repositories -This page lists repositories published by the GitHub user `marcelo-m7` and the organisation `Monynha-Softwares`. The data is fetched client-side so it always reflects the latest public information. - -## Filters and URL parameters +This page lists repositories discovered from the GitHub user `marcelo-m7` and the organization `Monynha-Softwares`. The fetching is done entirely in the browser using the public GitHub REST API. -You can control the dataset through query parameters: +The page accepts optional query parameters in the URL: -- `mode`: `user`, `org`, or `both` (default) to choose which GitHub accounts to load. -- `showForks`: `1`/`true` to include forks alongside source repositories. +- `mode`: `user` (show only user repos), `org` (show only organization repos), or `both` (default) +- `showForks`: `1` or `true` to include forked repos Examples: -- `/docs/repositories?mode=user` — list only `marcelo-m7` repositories. -- `/docs/repositories?mode=org&showForks=1` — show organisational repositories including forks. - -## Authentication and rate limits - -The component uses the public GitHub REST API. Anonymous requests are limited to 60 per hour. When iterating on this page locally you can raise the limit by creating a [fine-grained personal access token](https://github.com/settings/tokens) and providing it at runtime: - -```bash -GITHUB_TOKEN=ghp_yourtoken npm run start -``` - -The token is read from `process.env.GITHUB_TOKEN` and never persisted in the browser. Do **not** commit secrets—document them in `.env.example` if new variables are required. - -## Caching strategy - -- Responses are cached in `localStorage` for six hours to reduce API calls. -- Cache keys include the selected `mode` and `showForks` values to avoid stale mixes. -- Use the “force refresh” button in the component (or clear local storage manually) after making repository changes that must appear immediately. - -## Accessibility considerations - -- All interactive controls meet WCAG AA contrast ratios and are reachable via keyboard. -- Loading states announce progress through `aria-live` regions. -- Repository cards expose headings, descriptions, and primary language details for screen-reader navigation. +- `/docs/repositories?mode=user` — show only `marcelo-m7` repos +- `/docs/repositories?mode=org&showForks=1` — show only `Monynha-Softwares` repos including forks export function RepositoryPageWrapper() { - const params = typeof window !== 'undefined' ? new URLSearchParams(window.location.search) : new URLSearchParams(''); - const mode = params.get('mode') || 'both'; - const showForks = params.get('showForks') === '1' || params.get('showForks') === 'true'; - - let user = 'marcelo-m7'; - let org = 'Monynha-Softwares'; - if (mode === 'org') user = null; - if (mode === 'user') org = null; - - return ; + const params = typeof window !== 'undefined' ? new URLSearchParams(window.location.search) : new URLSearchParams(''); + const mode = params.get('mode') || 'both'; + const showForks = params.get('showForks') === '1' || params.get('showForks') === 'true'; + let user = 'marcelo-m7'; + let org = 'Monynha-Softwares'; + if (mode === 'org') user = null; + if (mode === 'user') org = null; + return ; } -## Troubleshooting - -- If GitHub rate limits are reached, authenticate with a token or wait for the hourly window to reset. -- Check browser console logs for API errors; the component surfaces detailed messages for 4xx/5xx responses. -- When repositories are missing, confirm they are public and not archived. +Notes: -For the legacy static list, see the [archived page](./index.md). +- Data is cached in `localStorage` for 6 hours to reduce requests and avoid hitting anonymous API rate limits. +- If you need higher rate limits, provide a GitHub personal access token, but do not embed secrets in client-side code. From f5a3982721920a456deccccbe7edfc034210beee Mon Sep 17 00:00:00 2001 From: marcelo-m7 Date: Sun, 9 Nov 2025 12:10:56 +0000 Subject: [PATCH 2/5] ci: enhance CI workflow with Node.js setup and build steps --- .github/workflows/ci.yml | 40 +++++++++++++++ .mona/CODEBASE_ANALYSIS.md | 99 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 139 insertions(+) create mode 100644 .mona/CODEBASE_ANALYSIS.md diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0e633a0..f6531b1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,5 +1,45 @@ name: CI +on: + push: + branches: [ dev, main ] + pull_request: + branches: [ dev, main ] + +jobs: + build-and-test: + name: Build and Test + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Use Node.js 20 + uses: actions/setup-node@v4 + with: + node-version: '20' + cache: 'yarn' + + - name: Install dependencies + run: | + corepack enable + corepack prepare yarn@stable --activate + yarn install --frozen-lockfile + + - name: Run build + run: yarn build + + - name: Run tests (node --test scripts) + run: yarn test + + - name: Upload build artifacts (optional) + if: success() + uses: actions/upload-artifact@v4 + with: + name: site-build + path: build +name: CI + on: pull_request: # run on PRs targeting main branches used in this repo diff --git a/.mona/CODEBASE_ANALYSIS.md b/.mona/CODEBASE_ANALYSIS.md new file mode 100644 index 0000000..fbf23a4 --- /dev/null +++ b/.mona/CODEBASE_ANALYSIS.md @@ -0,0 +1,99 @@ +## Análise do Codebase — MonaDocs + +Autor: AI assistant (análise automatizada) +Data: 2025-11-09 + +Resumo executivo +----------------- + +Este repositório é um site de documentação construído com Docusaurus v3. A estrutura é clara e segue convenções típicas de sites de docs: pasta `docs/` para conteúdo, `blog/` para posts, `src/components/` para componentes React reutilizáveis, e `static/` para ativos estáticos. O projeto requer Node >= 20 e usa `yarn` como gerenciador. O objetivo deste documento é registrar padrões, convenções e recomendações acionáveis. + +Contrato da análise (inputs/outputs) +----------------------------------- +- Inputs: código-fonte do repositório (arquivos principais lidos: `package.json`, `docusaurus.config.js`, `sidebars.js`, `README.md`, `docs/intro.md`). +- Output: este arquivo de análise com padrões identificados, riscos e recomendações. +- Critério de sucesso: documento legível e acionável, cobrindo stack, arquitetura, convenções de docs e sugestões práticas. +- Modos de falha esperados: arquivos ausentes/inconsistentes (não ocorreu), referências a runtime de browser no SSR (risco comum e documentado abaixo). + +Resumo técnico e stack +---------------------- +- Framework: Docusaurus v3 (preset `classic`). +- Node: engines.node >= 20. +- Package manager: yarn (scripts no `package.json`). +- React: 19.x (dependência declarada). +- MDX/MD: suporte via `@mdx-js/react` e arquivos `.md` / `.mdx` em `docs/` e `blog/`. +- Syntax highlighting: `prism-react-renderer`. + +Estrutura e padrões observados +------------------------------ +- `docusaurus.config.js`: configura navbar, footer, presets, i18n (apenas `en` configurado) e opções de build. `editUrl` aponta para a branch `dev` no GitHub. +- `sidebars.js`: gerador programático de sidebar. Padrão: + - TOP_FOLDERS explícito: `['projects','repositories','technologies','guidelines','identity','contribution','architecture']`. + - Lógica: lê `docs/`; prioriza `index.md`/`index.mdx`; deduplica entradas e ordena (index primeiro, depois alfabético). + - Usa `_category_.json` quando presente para rótulos e descrições. +- Docs: estrutura por subpastas (projects, technologies, etc.). Convenção recomendada observada: ter apenas um `index.md`/`index.mdx` por pasta. +- Componentes: `src/components/` armazena componentes reusáveis usados nas páginas/MDX (ex.: `HomepageFeatures`, `Repositories`, `TechStack`). + +Padrões de desenvolvimento e riscos conhecidos +------------------------------------------- +- SSR vs browser APIs: o README e o código alertam para não usar `window`/`localStorage` diretamente em arquivos que executam em SSR (config e sidebars rodam em Node). A prática certa (já mencionada no README) é acessar APIs de browser dentro de `useEffect` ou com `typeof window !== 'undefined'`. +- Duplicidade de documentação: ter `index.md` e `index.mdx` na mesma pasta pode gerar entradas duplicadas na sidebar. `sidebars.js` tenta deduplicar, mas é melhor manter um único arquivo índice por pasta. +- Componentes que fazem fetch (ex.: `Repositories`) usam cache em localStorage com TTL — atenção a rate limits e comportamento em CI/SSG (deve haver fallback gracioso quando não autorizado ou em ambiente sem `window`). + +Scripts e fluxo de desenvolvedor +-------------------------------- +- scripts principais (`package.json`): + - `start` -> `docusaurus start` (dev server) + - `build` -> `docusaurus build` + - `serve` -> `docusaurus serve` (preview da build) + - `deploy` -> `docusaurus deploy` (GitHub Pages) + - `favicon:generate` -> `node scripts/generate-favicons.js` + - `test` -> `node --test scripts` +- Observação: `test` executa testes via Node e `scripts/` contém alguns testes utilitários (`homepage.test.js`). Não há um pipeline de CI padronizado no repositório (a ser recomendado). + +Conveções de conteúdo (docs/blog) +--------------------------------- +- Uso de `_category_.json` para metadados de categoria na pasta `docs/`. +- Nomes de arquivos/URLs: usar `YYYY-MM-DD-title.md` para posts e frontmatter para metadata no blog. +- Imagens locais para docs: conventiona é colocar imagens dentro da pasta da seção e referenciar como `./img/foo.png` quando aplicável. + +Observações sobre configuração dinâmica do sidebar +------------------------------------------------- +- O `sidebars.js` é programático e depende de `TOP_FOLDERS`. Isso facilita organização automática, mas: + - Fornece menos controle manual sobre ordem fina dentro de categorias; para casos especiais pode-se substituir por uma sidebar manual para aquela categoria. + - Mudanças estruturais em `docs/` podem alterar a sidebar automaticamente — bom para produtividade, exige revisão de PRs que mexam em pastas. + +Recomendações (priorizadas) +--------------------------- +1) Adicionar CI básico (GitHub Actions) que execute: + - `yarn` e `yarn build` (garante que o site constrói em Node >= 20) + - `yarn test` (executa `node --test scripts`) + - um passo opcional de checagem de links (link checker) e checagem de acessibilidade básica. +2) Adicionar linter/formatador (ESLint + Prettier) nas partes de JS/TS/MDX para consistência e evitar erros de runtime (ex.: uso inadvertido de APIs de browser). +3) Criar arquivo `CODEOWNERS` ou documento de manutenção (quem aprova PRs por área: docs, components, infra). +4) Documentar claramente no README/CONTRIBUTING as regras de SSR e patterns para components (ex.: usar `useEffect` para localStorage). Link para exemplos. +5) Padronizar um único `index.md`/`index.mdx` por pasta e adicionar uma checagem de CI que falhe quando detectar ambos (script simples que procura pares duplicados). +6) Opcional: adicionar um pequeno smoke test Playwright/puppeteer que carregue a rota `/` e confirme 200/markup básico após `yarn build`. + +Edge cases e riscos +------------------- +- Ambientes de build sem `window` (SSG) — componentes que acessam localStorage sem guarda podem quebrar `yarn build`. +- Limites de API ao consumir GitHub public endpoints sem autenticação — componentes devem degradar graciosamente. +- Mudanças automáticas na estrutura de `docs/` podem alterar a ordem do sidebar inesperadamente; rever PRs que adicionem pastas. + +Próximos passos sugeridos (curto prazo) +------------------------------------- +1. Merge deste arquivo em `.mona` (feito). Use-o como ponto de referência para PRs sobre infra. +2. Criar workflow GitHub Actions mínimo (build + test + link-check). +3. Adicionar `CONTRIBUTING.md` com checklist rápido (build local, lint, testes manuais). +4. Implementar checagem simples para duplicação index.md/index.mdx em CI. + +Referências (arquivos lidos) +--------------------------- +- `package.json` — scripts, engines, dependências. +- `docusaurus.config.js` — configuração global (navbar, footer, presets, theme). +- `sidebars.js` — gerador dinâmico de sidebar; TOP_FOLDERS e lógica de leitura. +- `README.md` — instruções de dev, build e deploy, boas práticas e pitfalls. +- `docs/intro.md` — exemplo de conteúdo e frontmatter. + +Fim da análise. From f812aef9c0a5e0b877a8af41ab51de5ab91ce4a1 Mon Sep 17 00:00:00 2001 From: marcelo-m7 Date: Sun, 9 Nov 2025 12:14:29 +0000 Subject: [PATCH 3/5] docs: enhance Boteco Pro documentation with detailed architecture, patterns, and templates --- docs/projects/boteco-pro.md | 158 ++++++++++++++++++++++++++++-------- 1 file changed, 126 insertions(+), 32 deletions(-) diff --git a/docs/projects/boteco-pro.md b/docs/projects/boteco-pro.md index dd7b8fc..480208e 100644 --- a/docs/projects/boteco-pro.md +++ b/docs/projects/boteco-pro.md @@ -5,48 +5,142 @@ sidebar_position: 1 # Boteco Pro -## Overview +This document summarizes the Boteco Pro project with a focus on frontend, content, UI/UX, and engineering patterns discovered in the project repository. It follows a standardized format so the same template can be reused for other projects. -Boteco Pro is Monynha Softwares' flagship hospitality management platform. It consolidates point-of-sale, inventory, reservations, and loyalty experiences into a single suite tailored for bars and restaurants in Portugal and beyond. +## Quick facts -## Customer outcomes +- Source repository: https://github.com/Monynha-Softwares/BotecoPro +- Primary frontend: Flutter (Web / Mobile / Desktop) +- Authentication: Clerk (frontend-managed via ClerkAuth) +- Persistence: client-side persistence via localStorage (JSON) +- Build output (web): ~3.8 MB (optimized release) -- Reduce manual reconciliation by synchronising sales, stock, and accounting data. -- Increase table turnover with smart reservations, waitlist management, and QR ordering. -- Grow repeat business through integrated loyalty programs and segmented campaigns. +## Summary -## Product modules +Boteco Pro is a Flutter-based hospitality management application for bars and restaurants. The project is architected as a single-page Flutter Web app with mobile and desktop support. The codebase follows clear separation between core/business logic and presentation, uses Provider-style state management, and centralizes persistence through a `DatabaseService` that serializes objects to JSON and writes to `localStorage`. -1. **Point of Sale** – Multi-terminal POS with offline mode, receipt customisation, and tipping. -2. **Inventory & Procurement** – Supplier catalogues, purchase orders, and automated stock alerts. -3. **Reservations & Floor Management** – Table layouts, pacing controls, and guest communications. -4. **Loyalty & Marketing** – Tiered rewards, email/SMS campaigns, and customer analytics dashboards. -5. **Insights** – Real-time KPI cockpit covering revenue, labour costs, and menu performance. +## Frontend architecture & patterns -## Technology landscape +- Project layout (conventions): + - `lib/main.dart` — application entry point and responsive navigation wiring. + - `lib/theme.dart` — centralized theme and design tokens. + - `lib/core/` — models, providers, services (business logic and persistence). + - `lib/presentation/pages/` — page widgets named `*_page.dart` (e.g., `products_page.dart`). + - `lib/presentation/widgets/` — shared, reusable UI components (e.g., `bottom_navigation.dart`, `shared_widgets.dart`). -- **Mobile**: Flutter app for in-venue operations and tablet ordering. -- **Backend**: Convex for realtime data synchronisation, complemented by serverless functions for heavy processing. -- **Integrations**: Fiscal printers, payment gateways, delivery platforms, and accounting tools (TIC, Sage, Xero). -- **Infrastructure**: Containerised services orchestrated via Coolify with GitHub Actions CI/CD. +- Page & widgets pattern: + - Pages are `StatefulWidget`s following a predictable lifecycle (`initState`, async data load, `setState`). + - Reusable visual primitives live in `shared_widgets.dart` to avoid duplication. -## Deployment model +- State management & services: + - `DatabaseService` acts as the single persistence gateway (singleton-like) and exposes CRUD methods. + - Providers wrap stateful services (e.g., `AuthProvider`, `DatabaseProvider`) and notify UI via `ChangeNotifier`. + - Caching and in-memory stores are used for performance; code includes fixes to ensure caches use correct types (List vs Map). -- Tenants are provisioned per venue with region-aware configurations (currency, tax rules). -- Multi-environment setup: `production`, `staging`, `sandbox` for demos. -- Automated backups and migration scripts maintained in the `infra/` directory of the main repository. +- Theming & tokens: + - Material 3 theme with centralized colors in `theme.dart`. + - Primary token palette: Primary Wine `#8B1E3F`, Secondary Mustard `#B3701A`, Accent Beige `#F1DDAD`, Brown `#4F3222`. + - Fonts: preferred system fonts to avoid remote font fetches that harm performance. -## Roadmap +- Responsive & navigation patterns: + - Breakpoints: Mobile (<600px), Tablet (600–800px), Desktop (>=800px), Large Desktop (>=1200px). + - Mobile: BottomNavigationBar and single-column layouts. + - Desktop: NavigationRail (sidebar) and multi-column grids. -| Milestone | Description | Status | -| --- | --- | --- | -| Analytics v1.1 | Expand dashboards with labour cost tracking and anomaly detection. | In QA | -| Loyalty 2.0 | Introduce card-linked offers and partner marketplace integrations. | Development | -| Delivery Hub | Unified view for delivery platforms (Uber Eats, Glovo, Bolt Food). | Discovery | +## Content & documentation patterns -## Contribution workflow +- Documentation is thorough and role-oriented (DOCUMENTATION_INDEX.md provides role-based reading paths for managers, developers, and DevOps). +- Docs structure is consistent: concise README, architecture pages, deployment guides, and quick summary audit files. +- In-app content patterns: + - Use short, consistent labels (singular nouns for entities: Product, Order, Table). + - Model serialization methods `toJson()` / `fromJson()` for predictable storage and migration. + - Localization uses `intl`; code updates keep compatibility with packages (e.g., `intl: ^0.20.2`). -1. Review open issues labelled `feature`, `bug`, or `research` before picking up work. -2. Ensure database migrations include backward-compatibility notes. -3. Add end-to-end tests for mission-critical flows (orders, reservations, loyalty redemption). -4. Provide bilingual release notes (PT/EN) summarising changes for venue managers. +## UI/UX patterns & accessibility + +- Accessibility: + - Prefer accessible components (Clerk-provided auth UI is used for accessibility benefits). + - Maintain color-contrast ratios with the selected palette. + - Keyboard navigable forms and clear focus states are recommended. + +- Form patterns: + - Validate inputs client-side and show inline error messages. + - Use consistent loading indicators and disabled states for submit buttons. + - Follow progressive disclosure: show only necessary fields and allow expansion for advanced options. + +- Performance & UX: + - Avoid remote fonts and large assets to keep `main.dart.js` small. + - Use service worker caching for offline support and faster subsequent loads. + +## Data persistence & offline patterns + +- Persistence pattern: + - `DatabaseService` serializes domain objects and stores them under well-known `localStorage` keys (e.g., `products`, `orders`, `tables`). + - On app init, the service loads and deserializes these keys to restore state. + +- Caching & concurrency: + - Write locks and debouncing are applied for bulk writes to avoid thrashing localStorage. + - In-memory caches reduce read overhead; caches must be kept typed (List vs Map). + +- Security & constraints: + - Do not store sensitive PII or secrets in localStorage (design notes explicitly list what should NOT be stored). + +## Authentication & session management + +- Clerk is used as the primary authentication provider via `ClerkAuth` and `ClerkAuthBuilder`. +- Recommended configuration: provide `CLERK_PUBLISHABLE_KEY` via `.env` and validate key presence at runtime. +- Auth flows replace legacy login/signup pages and provide accessible, production-ready forms. + +## Testing & CI + +- Testing patterns: + - Unit tests for data models (`test/models_test.dart`). + - Widget/integration tests for UI flows (`testWidgets` with `pumpWidget`). + - E2E via webdriver/puppeteer for critical flows (add table, create order, payment). + +- CI/CD suggestions (pattern used in repo docs): + - Use GitHub Actions with a Flutter action to run `flutter analyze`, `flutter test`, `flutter build web --release`, then deploy (Firebase/Netlify). + - Provide secrets via GitHub Secrets (Clerk keys, Firebase service account) and avoid committing `.env`. + +## Deployment + +- Preferred option in repo: Firebase Hosting (with service worker and PWA support). Alternative options: Netlify, GitHub Pages, AWS S3. +- Build step: `flutter build web --release` → serve `build/web`. + +## Design tokens (reference) + +- Colors: + - Primary: #8B1E3F (Wine) + - Secondary: #B3701A (Mustard) + - Accent: #F1DDAD (Beige) + - Dark: #4F3222 (Brown) + +- Spacing scale: use 4px baseline (4, 8, 12, 16, 24, 32) +- Typography: system fonts for web performance; scale for Mobile/Tablet/Desktop + +## Reusable project documentation template + +Use this section as a template for other projects. Each project doc should include: + +1. Quick facts (repo link, frontend, auth, persistence) +2. One-paragraph executive summary +3. Frontend architecture & file layout +4. Content & documentation conventions +5. UI/UX patterns (accessibility, breakpoints, navigation) +6. Data & persistence patterns (services, cache, localStorage keys) +7. Auth and security notes (env variables, secrets handling) +8. Testing & CI (commands and required secrets) +9. Deployment (commands and common providers) +10. Design tokens (colors, spacing, typography) +11. Links to detailed docs (README, WEB_ARCHITECTURE.md, FIREBASE_DEPLOYMENT_GUIDE.md) + +## Links & references + +- BotecoPro README: https://github.com/Monynha-Softwares/BotecoPro/blob/dev/README.md +- Architecture & docs: https://github.com/Monynha-Softwares/BotecoPro/tree/dev/docs + +## Next steps + +1. Review this page and merge to `dev` so maintainers can iterate. +2. Apply the same template to other projects under `docs/projects/`. +3. Optionally add a short checklist and automation to validate project docs follow this template (CI check). From 3073675b623deb582d05d73c0902b8bcd36a084e Mon Sep 17 00:00:00 2001 From: marcelo-m7 Date: Sun, 9 Nov 2025 12:27:06 +0000 Subject: [PATCH 4/5] docs: add comprehensive architecture rationale, advanced CI/CD patterns, enforcement tooling, and security incident playbook --- docs/architecture/architecture-rationale.md | 56 ++++++++++++++++++ docs/architecture/ci-cd-advanced.md | 64 ++++++++++++++++++++ docs/guidelines/enforcement-tooling.md | 65 +++++++++++++++++++++ docs/guidelines/security-playbook.md | 64 ++++++++++++++++++++ 4 files changed, 249 insertions(+) create mode 100644 docs/architecture/architecture-rationale.md create mode 100644 docs/architecture/ci-cd-advanced.md create mode 100644 docs/guidelines/enforcement-tooling.md create mode 100644 docs/guidelines/security-playbook.md diff --git a/docs/architecture/architecture-rationale.md b/docs/architecture/architecture-rationale.md new file mode 100644 index 0000000..e8b9077 --- /dev/null +++ b/docs/architecture/architecture-rationale.md @@ -0,0 +1,56 @@ +## Architecture Rationale & Tradeoffs + +Purpose +------- +This short document explains the rationale and tradeoffs behind the primary architecture choices in the Monynha platform. It is intended for engineers and architects who need to make consistent design decisions across products. + +1. Node.js + TypeScript (API layer) +---------------------------------- +- Rationale: Node.js provides fast developer iteration, broad ecosystem, and excellent support for JSON-first APIs. TypeScript enforces type-safety and reduces runtime bugs, especially in a polyglot team. +- Tradeoffs: Node's single-threaded model requires careful handling of CPU-bound tasks. For heavy background processing, we recommend offloading to worker processes (e.g., AWS Fargate tasks, serverless functions, or a dedicated worker pool in Go/Java). +- When to choose otherwise: Use a compiled language (Go, Rust) when strict latency, lower memory footprint, or predictable concurrency are top priorities. + +2. PostgreSQL + Prisma (Primary Data Store) +------------------------------------------- +- Rationale: PostgreSQL is battle-tested, supports complex queries, transactional integrity, and is well-supported by managed services (RDS, Supabase). Prisma provides productivity gains (type-safe client, migrations). +- Tradeoffs: Prisma's generated client increases build-time and requires careful migration sequences for large schemas. For extremely large-scale, consider a more explicit SQL-first approach and careful indexing strategies. + +3. Supabase for Realtime & Storage +---------------------------------- +- Rationale: Supabase provides a convenient, integrated feature set (Realtime, Auth, Storage) that accelerates MVP and prototype development. +- Tradeoffs: Vendor lock-in risk and feature limits for enterprise workloads. For long-term scale, plan migration paths (e.g., replace Realtime with Redis Streams / WebSockets; replace Auth with self-hosted OIDC provider). + +4. Client-Side Persistence (localStorage for web apps) +--------------------------------------------------- +- Rationale: For offline-first UX and low-infrastructure MVPs, localStorage provides immediate persistence with zero server cost. +- Tradeoffs: localStorage is not secure for sensitive data and has size limits (~50MB). For multi-device sync and scale, migrate to a backend store (Firestore, Postgres with WebSockets) and implement robust conflict resolution. + +5. Monorepo (Turborepo) vs Multi-Repo +------------------------------------- +- Rationale: Monorepo simplifies cross-project changes, version alignment, and shared tooling. Turborepo (or equivalent) provides caching and task orchestration. +- Tradeoffs: Requires CI investment (caching, focused builds) and governance around package boundaries. If teams grow into many independent products, evaluate splitting into smaller repos or a hybrid approach. + +6. Containerization & Orchestration +----------------------------------- +- Rationale: Containers (Docker) + orchestrators (ECS/Fargate) deliver portability and predictable deployments for services. +- Tradeoffs: Orchestration adds operational complexity. For small services, serverless functions (AWS Lambda) may be more cost-effective. + +Operational guidance & patterns +------------------------------ +- Observability: instrument APIs with structured logs (JSON), distributed tracing (OpenTelemetry), metrics (Prometheus) and alerts (PagerDuty/Teams). +- Backups & DR: schedule regular logical backups for Postgres and test restores periodically. Store immutable backups offsite. +- Security: enforce least-privilege IAM roles and rotate secrets regularly. Use a secrets manager (AWS Secrets Manager / HashiCorp Vault). +- Cost control: use autoscaling with sensible minimums and on-demand scheduled scaling for predictable traffic. + +Decision checklist (quick) +------------------------- +Before adopting a new technology, answer: +1. Does it reduce developer time-to-value significantly? +2. Are there production-grade libraries and community support? +3. Is operational cost and complexity acceptable? +4. Is there a clear migration or rollback plan? + +Links & references +------------------ +- Architecture discussions and RFCs: `docs/architecture/rfcs/` (create RFCs there for major changes). +- Observability starter: `docs/operations/observability.md` (recommended next addition). diff --git a/docs/architecture/ci-cd-advanced.md b/docs/architecture/ci-cd-advanced.md new file mode 100644 index 0000000..386b1c7 --- /dev/null +++ b/docs/architecture/ci-cd-advanced.md @@ -0,0 +1,64 @@ +## Advanced CI/CD Patterns + +This page documents advanced CI/CD patterns recommended for the Monynha monorepo. It complements `ci-cd.md` by providing operational recipes, secrets handling, remote caching guidance, and release strategies suitable for experienced engineers. + +1) Secrets & Credentials Management +---------------------------------- +- Store secrets in a dedicated secrets manager (GitHub Actions Secrets for short-lived values; AWS Secrets Manager or HashiCorp Vault for production secrets). Do not store secrets in repo or artifacts. +- Rotate secrets on a regular schedule; implement automated rotation for short-lived tokens where possible. +- Example pattern (GitHub Actions + AWS Secrets Manager): + - CI reads short-lived deploy token from AWS Secrets Manager using an IAM role with limited scope. + - The role is provided to the runner via OpenID Connect (OIDC) to avoid long-lived credentials. + +2) Reproducible Builds & Artifact Signing +---------------------------------------- +- Use lockfiles (`yarn.lock`, `pnpm-lock.yaml`) and pinned base images to ensure reproducible builds. +- Produce signed artifacts: sign Docker images (cosign) and generated JS/CSS bundles where applicable. Store signatures alongside artifacts in registry. +- Example: build → cosign sign ghcr.io//web: → push signature to OCI registry. + +3) Remote Caching for Monorepo (Turborepo) +------------------------------------------ +- Enable remote caching in CI so repeated builds only run changed tasks. Use an S3-compatible bucket or remote cache service. +- Cache keys should include Node version, lockfile checksum, and repo SHA to avoid cache poisoning. +- Example turbo.json snippet: + +```json +{"pipeline": {"build": {"cache": true}}} +``` + +4) Test Matrices & Isolation +---------------------------- +- Split tests into lightweight unit tests (fast), integration tests (database-backed), and E2E (slow). Run unit tests on every PR and gate integration/E2E on merge to main or on demand. +- Use ephemeral databases (Postgres containers) and separate credentials per workflow run to avoid state bleed. + +5) Preview Environments & PR Previews +------------------------------------ +- Deploy preview builds for PRs using a hosting provider (Vercel, Netlify) or ephemeral environments on Kubernetes/ECS. +- Provide a bot comment with the preview URL; include an automated accessibility and Lighthouse report for each preview. + +6) Deployment Strategies & Rollbacks +----------------------------------- +- Blue/Green or Canary deployments are preferred for services with live traffic. +- Implement health checks and automated rollback: if new deployment fails health checks, rollback to the previous revision automatically. +- Store deployment metadata and release tags to facilitate rollbacks and audits. + +7) Secrets for Third-Party Integrations +-------------------------------------- +- When integrating with external providers (Clerk, Firebase, payment gateways), treat their API keys as secrets and scope them to the minimum necessary privileges. +- Prefer server-side proxies for sensitive operations and keep frontend keys public-only where intended. + +8) Observability & CI Signals +----------------------------- +- Fail CI on: lint/type-check failures, unit test regressions, critical vulnerability scans (high/critical), bundle-size increases beyond threshold. +- Record CI metrics (build time, test duration, failure rates) and use them for performance SLAs on developer productivity. + +9) Governance & Change Control +------------------------------ +- For infra changes (Terraform, deployment scripts), require at least two approvals and run `terraform plan` in CI, posting plan output to the PR for review. +- Automate drift detection and schedule regular infra audits. + +References & recipes +-------------------- +- OIDC with GitHub Actions: https://docs.github.com/actions/deployment/security-hardening-your-deployments/about-security-hardening-with-openid-connect +- cosign for image signing: https://github.com/sigstore/cosign +- Turborepo remote caching: https://turborepo.org/docs/features/remote-caching diff --git a/docs/guidelines/enforcement-tooling.md b/docs/guidelines/enforcement-tooling.md new file mode 100644 index 0000000..6c0c5f7 --- /dev/null +++ b/docs/guidelines/enforcement-tooling.md @@ -0,0 +1,65 @@ +--- +title: Enforcement & Tooling +sidebar_position: 3 +--- + +# Enforcement & Tooling + +This page complements `code-conventions.md` with practical, repository-level enforcement patterns: pre-commit hooks, CI gates, and dependency/security automation. These are focused on reducing friction while ensuring high code quality for experienced developers. + +1. Pre-commit (local) vs CI enforcement +-------------------------------------- +- Local: fast feedback with `husky` + `lint-staged` to catch style and simple errors before commits. +- CI: authoritative checks (type-check, full test suite, security scans). CI must be green before merges. + +2. Recommended developer stack (JS/TS projects) +---------------------------------------------- +- Husky for Git hooks (pre-commit, commit-msg). +- lint-staged to run linters/formatters on staged files. +- commitlint to enforce Conventional Commits. + +Example package.json snippets + +```json +{ + "husky": { + "hooks": { + "pre-commit": "lint-staged", + "commit-msg": "commitlint -E HUSKY_GIT_PARAMS" + } + }, + "lint-staged": { + "*.{ts,tsx,js,jsx}": ["yarn lint:fix", "yarn test:unit --findRelatedTests"], + "*.{md,json}": ["prettier --write"] + } +} +``` + +3. CI Gate (PR checks) +----------------------- +- Minimal required checks: + - lint (ESLint) + - type-check (tsc --noEmit) + - unit tests + - vulnerability scan (Snyk/Trivy) +- Optional but recommended: coverage check, bundle-size check, and preview deployment. + +4. Dependency & Security Automation +---------------------------------- +- Dependabot for dependency update PRs. +- Scheduled vulnerability scans and fail builds on critical issues. + +5. Enforcing in monorepo +------------------------ +- Use per-package scripts and a root task orchestrator (Turborepo). Keep PR checks focused: only run affected package tests where possible to reduce CI time. + +6. Onboarding checklist for new repositories +------------------------------------------- +1. Add `pre-commit` hooks (husky) +2. Add `PR checks` workflow with lint/type/test +3. Configure Dependabot +4. Add Code Owners and Reviewers + +Notes +----- +- These patterns are minimal and intentionally pragmatic: they provide the highest ROI for developer productivity and code quality without heavy gating. Repositories may opt into stricter enforcement for security-sensitive components. diff --git a/docs/guidelines/security-playbook.md b/docs/guidelines/security-playbook.md new file mode 100644 index 0000000..b5007b4 --- /dev/null +++ b/docs/guidelines/security-playbook.md @@ -0,0 +1,64 @@ +# Security Incident Playbook (Practical) + +This playbook provides a concise, actionable incident response runbook tailored for development and on-call teams. It is a practical companion to `security.md` and is written for engineers who must respond to incidents quickly and safely. + +1. Detection & Triage +---------------------- +- Triage the alert: collect the alert source (SIEM, Sentry, CloudWatch), timestamps, affected services, and initial severity. +- Quickly determine scope: which services, regions, customers, or data stores are affected. +- Assign an incident lead and communicate a dedicated incident channel (Slack/Teams) and bridge. + +2. Containment +-------------- +- Short-term containment: apply network rules or scaling actions to limit blast radius (e.g., restrict ingress/IP, disable public endpoints, scale down worker concurrency). +- Credential containment: rotate compromised keys immediately using Secrets Manager; revoke tokens and sessions for affected services. + +3. Investigation +---------------- +- Preserve evidence: export logs, tracer spans, and relevant DB snapshots to an isolated storage location. +- Identify initial root cause: review recent deployments, config changes, and secret rotations. +- Use tooling: run `grep` across recent commits, check CI job logs, and inspect audit trails in the cloud provider. + +4. Eradication +-------------- +- Remove malicious actors or faulty code: rollback to last known good release or patch the offending code path. +- Patch vulnerabilities: upgrade dependencies, fix input validation, or adjust firewall rules as required. + +5. Recovery +----------- +- Bring services back to normal using blue/green or canary deployments. +- Validate with smoke tests and automated health checks before full traffic cutover. + +6. Post-Incident Review +----------------------- +- Run a blameless postmortem with timelines, root cause, actions taken, and follow-ups. +- Track follow-ups as issues with owners and deadlines. + +Quick containment commands (examples) +------------------------------------- +- Revoke AWS access key (example): + - aws iam update-access-key --user-name X --access-key-id AKIA... --status Inactive +- Rotate secret in AWS Secrets Manager (example): + - aws secretsmanager rotate-secret --secret-id arn:aws:secretsmanager:... --rotation-lambda-arn arn:aws:lambda:... +- Emergency rollback (example): + - aws ecs update-service --cluster my-cluster --service my-service --force-new-deployment --task-definition my-task:42 + +Checklist: What to log +---------------------- +- Alert ID, timestamps, services, owner, and channel +- Short description and initial impact estimate +- Evidence collected (logs, snapshots) +- Actions taken and by whom +- Final resolution and follow-up items + +Escalation matrix (example) +--------------------------- +- Level 1: On-call engineer (first 15 minutes) +- Level 2: Service owner / Tech lead (15–60 minutes) +- Level 3: Engineering manager + Security lead (60+ minutes) + +References +---------- +- NIST Computer Security Incident Handling Guide (SP 800-61) +- OWASP Incident Response Recommendations +- Internal `security.md` for standards and policies From bbb27c756ef46f2437842f63e476dedf664d195c Mon Sep 17 00:00:00 2001 From: marcelo-m7 Date: Sun, 9 Nov 2025 12:47:45 +0000 Subject: [PATCH 5/5] docs: add comprehensive guides for schema migrations and observability practices --- docs/architecture/migrations-and-backups.md | 110 +++++++++++++++ docs/architecture/observability.md | 143 ++++++++++++++++++++ 2 files changed, 253 insertions(+) create mode 100644 docs/architecture/migrations-and-backups.md create mode 100644 docs/architecture/observability.md diff --git a/docs/architecture/migrations-and-backups.md b/docs/architecture/migrations-and-backups.md new file mode 100644 index 0000000..48d6975 --- /dev/null +++ b/docs/architecture/migrations-and-backups.md @@ -0,0 +1,110 @@ +--- +title: Schema migrations and backups +description: Practical guide for schema migrations, zero-downtime patterns, backups and restore runbooks. +--- + +## Purpose + +This guide documents recommended workflows for schema migrations (Prisma-based examples), safe deployment practices, backup schedules and a short recovery runbook for PostgreSQL-based projects (including Supabase-managed instances). + +## Principles + +- Prefer backward-compatible changes when migrating (expand-contract pattern). +- Make schema changes in two steps where required: add new columns/objects, deploy code that writes to both old and new shapes, then migrate and remove old fields later. +- Always have tested backups and a practiced restore procedure. + +## Prisma migrations (recommended workflow) + +1. Create a small, focused migration with `prisma migrate dev --name your_change` during development. +2. Review the SQL produced under `prisma/migrations`. +3. In CI, use `prisma migrate deploy` against the target DB for deterministic application. + +CI job example (simplified): + +```yaml +name: apply-migrations +on: push +jobs: + migrate: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - name: Setup Node + uses: actions/setup-node@v4 + with: + node-version: 20 + - name: Install + run: yarn install --frozen-lockfile + - name: Apply Prisma Migrations + env: + DATABASE_URL: ${{ secrets.PROD_DATABASE_URL }} + run: npx prisma migrate deploy +``` + +### Local dev sanity check + +- Run `npx prisma migrate dev` and `npx prisma db push` for quick iterations, but rely on `migrate deploy` for CI/production. + +## Zero-downtime migration patterns + +- Non-destructive changes first: add columns, add new tables, populate/transform data in background jobs. +- Backfill and make application code write to both fields (feature-flag the readback switch). +- Run a short read-compare test before deleting old fields. + +Example: renaming a column `full_name` -> `display_name` + +1. Add `display_name` column (nullable). +2. Deploy code that writes both `full_name` and `display_name`. +3. Backfill existing rows with a one-off job. +4. Flip reads to use `display_name` behind a feature flag. +5. After monitoring, issue migration to drop `full_name`. + +## Backups + +### Simple logical backup (pg_dump) + +Run daily logical backups with `pg_dump` and store them offsite (object storage). Example command: + +```bash +pg_dump -Fc -h -p -U -d -f backup-$(date +%F).dump +``` + +Notes: + +- Use compressed/custom format (`-Fc`) for efficient storage. +- Keep 7-30 days of daily backups and weekly/monthly longer-term snapshots depending on retention policy. + +### Physical backups and WAL (for large DBs / production) + +- Use base backups + continuous WAL shipping (pg_basebackup + WAL archive) for point-in-time recovery (PITR). +- Managed Postgres (Supabase, RDS) provide automated PITR snapshots — follow provider docs and preserve backup retention settings. + +## Restore runbook (high level) + +1. Identify most recent good backup file. +2. Provision an isolated restore target (new DB instance) to avoid affecting production. +3. Restore the dump: `pg_restore -d backup-file.dump`. +4. Run sanity checks (smoke tests, application health checks) against the restored DB. +5. If you need to rollback production, point the application to the restored DB after coordination and maintenance windows. + +## Emergency rollback strategy + +- Rolling back code that depends on schema removal is easier when schema was migrated in a backward-compatible way. +- If a destructive migration was already applied and must be reverted, restore the latest backup into a new instance and perform a cutover. + +## Testing migrations + +- Add a small test job that applies migrations to a fresh DB and runs the test suite (fast smoke tests) in CI before applying migrations to production. + +## Operational checklist before applying migrations to prod + +1. Ensure a fresh successful backup is available. +2. Verify migration SQL and review for destructive operations. +3. Run migrations in a staging environment that mirrors production. +4. Deploy application changes that are compatible with both old and new schema. +5. Monitor application metrics and error rates during/after migration. + +## References + +- Prisma Migrate docs: [Prisma Migrate](https://www.prisma.io/docs/concepts/components/prisma-migrate) +- PostgreSQL backup & restore: official documentation diff --git a/docs/architecture/observability.md b/docs/architecture/observability.md new file mode 100644 index 0000000..530ba13 --- /dev/null +++ b/docs/architecture/observability.md @@ -0,0 +1,143 @@ +--- +title: Observability +description: Tracing, metrics, and logging guidance for services and client apps. +--- + +## Purpose + +This document gives practical guidance to add observability to services and frontends used across Monynha projects: tracing, metrics, and logs. It focuses on implementable recipes (OpenTelemetry, Prometheus, Grafana, Jaeger/Loki) and short examples for Node/TypeScript services and client apps. + +## Goals + +- Provide reproducible instrumentation steps for traces, metrics and logs. +- Show minimal local dev setup (Docker) and production export patterns (OTLP, Prometheus remote_write). +- Recommend alerting and retention defaults. + +## Overview + +- Traces: OpenTelemetry (OTel) -> OTLP -> backend (Jaeger/Tempo/OTLP collector) +- Metrics: Prometheus exposition (/metrics) or OTLP remote_write -> Prometheus/Gateway +- Logs: Structured JSON logs -> Loki/ELK/Cloud logging + +## Quick architecture (recommended) + +1. Instrument code with OpenTelemetry for traces and metrics. +2. Export traces/metrics via OTLP to an OpenTelemetry Collector. +3. Collector forwards traces to Tempo/Jaeger, metrics to Prometheus remote write or a metrics backend, and logs to Loki/ELK. + +## Node / TypeScript (minimal trace + metrics) + +Install the SDK and instrumentations (example): + +```bash +yarn add @opentelemetry/sdk-node @opentelemetry/auto-instrumentations-node @opentelemetry/exporter-trace-otlp-http @opentelemetry/exporter-metrics-otlp-http +``` + +Create an `otel.js` bootstrap that runs before your app (or use `node --require`). Minimal example: + +```js +// otel.js +const { NodeSDK } = require('@opentelemetry/sdk-node'); +const { OTLPTraceExporter } = require('@opentelemetry/exporter-trace-otlp-http'); +const { OTLPMetricExporter } = require('@opentelemetry/exporter-metrics-otlp-http'); +const { getNodeAutoInstrumentations } = require('@opentelemetry/auto-instrumentations-node'); + +const traceExporter = new OTLPTraceExporter({ url: process.env.OTEL_EXPORTER_OTLP_TRACES || 'http://localhost:4318/v1/traces' }); +const metricExporter = new OTLPMetricExporter({ url: process.env.OTEL_EXPORTER_OTLP_METRICS || 'http://localhost:4318/v1/metrics' }); + +const sdk = new NodeSDK({ + traceExporter, + metricExporter, + instrumentations: [getNodeAutoInstrumentations()], +}); + +sdk.start() + .then(() => console.log('OpenTelemetry initialized')) + .catch((err) => console.error('OTEL init error', err)); + +process.on('SIGTERM', () => { + sdk.shutdown().then(() => console.log('OTEL shutdown complete')).catch(()=>{}); +}); +``` + +Start your service with `node -r ./otel.js server.js` or add the bootstrap into your start script. + +### Prisma: add spans to DB calls + +Use a Prisma middleware to create spans around queries (example using @opentelemetry/api): + +```js +const { trace } = require('@opentelemetry/api'); +prisma.$use(async (params, next) => { + const tracer = trace.getTracer('prisma'); + return tracer.startActiveSpan(`prisma.${params.model}.${params.action}`, async (span) => { + try { + return await next(params); + } finally { + span.end(); + } + }); +}); +``` + +## Frontend / Flutter (traces & metrics) + +- Mobile & web frontends should emit telemetry relevant to UX flows (navigation, API latency, feature toggles). Use lightweight sampling (e.g., 1-5%) for production by default. +- For Flutter, use community OpenTelemetry Dart packages (or the project's preferred vendor SDK). Export traces to an OTLP collector via gRPC/HTTP. + +Minimal Flutter snippet (conceptual): create spans for top-level routes and for network requests. Refer to the chosen Dart OTel package docs for exact APIs. + +## Local dev (docker-compose) + +Use the OpenTelemetry Collector and a Prometheus + Grafana + Jaeger stack locally. Example components: + +- otel-collector +- prometheus +- grafana +- jaeger/tempo + +Keep the Collector config minimal in dev (receive OTLP, export to Jaeger & Prometheus receiver). + +## Metrics: naming and conventions + +- Use a predictable naming scheme: `service...` (e.g. `service.api.request_duration_seconds`). +- Distinguish counters vs gauges vs histograms. Use labels/tags sparingly and with cardinality limits. + +## Dashboards and alerts + +- Create a small set of standard dashboards: API latency (p50/p95/p99), error rate, request rate, DB query time, CPU/memory, queue backlog. +- Suggested alert thresholds (examples): + - Error rate > 1% sustained for 5m + - p95 latency > X ms (service specific) + - Prometheus target down or scrape failing + +## Sampling & cost control + +- Use client and server side sampling. For high-volume endpoints prefer head-based sampling with deterministic rules. +- Consider exporting only sampled traces to long-term storage and sending metrics for every request. + +## Logs + +- Prefer structured logs (JSON) with a small set of fields: timestamp, level, service, env, trace_id, span_id, message, error. +- Correlate logs with traces using trace_id/span_id. + +## Retention & storage recommendations + +- Traces: keep raw traces for ~7-14 days; store aggregated traces longer if needed. +- Metrics: Prometheus TSDB retention depends on capacity; consider remote_write to managed long-term storage for historical metrics. +- Logs: retention 30-90 days depending on compliance and cost. + +## Operational checklist + +Before shipping observability changes to prod: + +1. Verify traces/metrics are visible in dev environment (local Collector → Jaeger/Grafana). +2. Confirm labels cardinality is bounded. +3. Add at least one dashboard and alert for the changed service. +4. Run a short load test and confirm ingestion and storage behave as expected. + +## References & further reading + +- OpenTelemetry docs: [OpenTelemetry](https://opentelemetry.io) +- Prometheus best practices: [Prometheus naming guidelines](https://prometheus.io/docs/practices/naming/) +- Grafana dashboards: create small, actionable views first.