diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 39ffbf2..79aadb3 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -1,112 +1,84 @@ ## Purpose -This file gives concise, repository-specific guidance to an AI coding agent so it can be productive working on the Docusaurus documentation site in this repo. +This file provides repository-specific guidance to AI coding agents for working effectively on the Docusaurus documentation site in this repository. -## Big picture +## Big Picture -- This project is a Docusaurus site (see `docusaurus.config.js`) using the classic preset. Main content lives under `docs/` and `blog/`. React UI code is in `src/` and static assets in `static/`. -- Primary responsibilities: serve the site locally, author docs/blog posts (Markdown/MDX), update UI components and styles, and build/deploy the static site. +- This project is a Docusaurus v3 site (see `docusaurus.config.js`) using the classic preset. Content is organized into `docs/` (documentation) and `blog/` (posts). React UI components are in `src/`, and static assets are in `static/`. +- Primary responsibilities include running the dev server, authoring docs/blog posts (Markdown/MDX), updating UI components/styles, managing sidebar/category metadata, and building/deploying the site. -## Important files & folders (examples) +## Key Files & Folders -- `package.json` — contains npm/yarn scripts used to run, build, and deploy the site (see `start`, `build`, `deploy`). -- `docusaurus.config.js` — global config: `baseUrl`, `organizationName`, `projectName`, i18n, theme, navbar/footer. -- `sidebars.js` — docs sidebar configuration. When changing doc structure, update this file. -- `docs/` — documentation pages. Subfolders use `_category_.json` for grouping (example: `tutorial-basics/_category_.json`). -- `blog/` — blog posts (Markdown/MDX) and metadata files `authors.yml`, `tags.yml`. -- `src/components/` — custom React components used by pages (example: `src/components/HomepageFeatures/index.js`). -- `static/img/` and `docs/**/img/` — image assets referenced by docs/blog. +- `package.json`: Contains scripts for development (`start`), production builds (`build`), serving builds (`serve`), and deployment (`deploy`). Node >= 20 is required. +- `docusaurus.config.js`: Global site configuration (e.g., `baseUrl`, `organizationName`, `projectName`, `editUrl`, navbar/footer settings). +- `sidebars.js`: Controls the docs sidebar. Update this file when adding/moving docs or categories. +- `docs/`: Markdown/MDX documentation. Subfolders use `_category_.json` for grouping (e.g., `docs/tutorial-basics/_category_.json`). +- `blog/`: Blog posts (Markdown/MDX) with metadata in `authors.yml` and `tags.yml`. +- `src/components/`: Custom React components (e.g., `HomepageFeatures`, `TechStack`, `Portfolio`). +- `src/css/custom.css`: Global styling. Page-specific styles are in `src/pages`. +- `static/img/` and `docs/**/img/`: Image assets. Use `static/img/` for global assets and relative `./img/...` for doc-specific images. -## Development commands (explicit) - -Run locally (recommended, project README uses yarn): -## Purpose - -This file gives concise, repository-specific guidance to an AI coding agent so it can be productive working on this Docusaurus documentation site. - -## Big picture - -- This repo is a Docusaurus v3 site (see `docusaurus.config.js`) using the classic preset. Content is split into `docs/` (documentation) and `blog/` (posts). React UI code lives in `src/` and static assets in `static/`. -- Primary agent responsibilities: run the dev server, add/edit docs & blog posts (MD/MDX), update UI components/styles, manage sidebar and category metadata, build and deploy the site. - -## Key files & folders - -- `package.json` — scripts: `start` (dev), `build` (prod), `serve` (serve build), `deploy` (GitHub Pages). Node >= 20 is required (check `engines`). -- `docusaurus.config.js` — global site config (baseUrl, organizationName, projectName, editUrl, navbar/footer). Verify `organizationName` / `projectName` before changing deploy targets. -- `sidebars.js` — controls docs sidebar. Adding/moving docs often requires updating this file or the sidebar path used by the config. -- `docs/` — markdown/MDX docs. Subfolders use `_category_.json` for grouping (see `docs/tutorial-basics/_category_.json`). -- `blog/` — posts (MD/MDX) and metadata: `authors.yml`, `tags.yml`. Example: `blog/2021-08-01-mdx-blog-post.mdx`. -- `src/components/` — React UI components used by pages (example: `src/components/HomepageFeatures/index.js`). -- `src/css/custom.css` — global styling. Page-specific modules exist under `src/pages`. -- `static/img/` and `docs/**/img/` — image assets. Use `static/img/` for global assets and relative `./img/...` inside docs for doc-scoped images. - -## Quick start (Windows / PowerShell) +## Development Commands 1. Install dependencies: -```powershell -yarn -``` + ```powershell + yarn + ``` -2. Run dev server (hot reload; default port 3000): +2. Run the development server (hot reload; default port 3000): -```powershell -yarn start -``` + ```powershell + yarn start + ``` 3. Build and preview production: -```powershell -yarn build -yarn serve -``` - -4. Deploy to GitHub Pages (as provided in repo): - -```powershell -USE_SSH=true; yarn deploy -# or without SSH -GIT_USER=; yarn deploy -``` + ```powershell + yarn build + yarn serve + ``` -If you prefer npm, replace `yarn` with `npm run` for the named scripts. +4. Deploy to GitHub Pages: -## Project-specific conventions & patterns + ```powershell + USE_SSH=true; yarn deploy + # or without SSH + GIT_USER=; yarn deploy + ``` -- Docs grouping: each docs subfolder may include `_category_.json` that the site relies on. Don't rename or remove them without updating `sidebars.js`. -- Images: place global images in `static/img/` and per-doc images in a `img/` folder next to the doc file; reference via `./img/foo.png` in Markdown. -- UI: small reusable components live in `src/components/`. Use existing styles in `src/css/custom.css` and `src/components/*/styles.module.css` patterns. -- MDX usage: examples exist in `docs/` and `blog/` — prefer MDX when embedding React components inside docs. +## Project-Specific Conventions & Patterns -## Integration points & external dependencies +- **Docs Grouping**: Each `docs/` subfolder may include `_category_.json` for grouping. Update `sidebars.js` if moving docs. +- **Images**: Place global images in `static/img/` and per-doc images in `img/` next to the doc file. Reference them via `./img/foo.png` in Markdown. +- **UI Components**: Reusable components are in `src/components/`. Follow existing patterns in `src/css/custom.css` and `src/components/*/styles.module.css`. +- **MDX Usage**: Use MDX for embedding React components in docs/blogs. Examples are in `docs/` and `blog/`. -- Docusaurus packages (check `package.json`): primary runtime. Avoid adding heavy runtime-only dependencies unless necessary for docs. -- GitHub Pages is the default deploy target (deploy script present). Confirm `docusaurus.config.js` `organizationName` and `projectName` match the repo/org before changing `editUrl` or deploy settings. -- No CI configuration was found in the repo root. If you add CI (GitHub Actions), ensure Node >= 20 and `yarn install && yarn build` steps. +## Integration Points & External Dependencies -## Concrete examples (what to change and where) +- **Docusaurus Packages**: Check `package.json` for dependencies. Avoid adding heavy runtime-only dependencies unless necessary. +- **Deployment**: GitHub Pages is the default deploy target. Ensure `organizationName` and `projectName` in `docusaurus.config.js` match the repo/org. +- **CI/CD**: No CI configuration exists. If adding CI (e.g., GitHub Actions), ensure Node >= 20 and include `yarn install && yarn build` steps. -- Add a doc: create `docs/
/new-doc.md` (or `.mdx`) and add/update `sidebars.js` or rely on the configured automatic sidebar path. -- Add blog post: `blog/YYYY-MM-DD-title.md` with YAML frontmatter (title, tags, authors). Update `blog/authors.yml` for new authors. -- Edit homepage features: modify `src/components/HomepageFeatures/index.js` and `src/components/HomepageFeatures/styles.module.css`, then `yarn start` to hot-reload. +## Examples of Common Changes -## Notes & watch-outs +- **Add a Doc**: Create `docs/
/new-doc.md` (or `.mdx`) and update `sidebars.js` or rely on automatic sidebar paths. +- **Add a Blog Post**: Create `blog/YYYY-MM-DD-title.md` with YAML frontmatter (e.g., `title`, `tags`, `authors`). Update `blog/authors.yml` for new authors. +- **Edit Homepage Features**: Modify `src/components/HomepageFeatures/index.js` and `src/components/HomepageFeatures/styles.module.css`. Use `yarn start` to hot-reload. -- Docusaurus config runs in Node (no browser globals). Keep dynamic code safe for Node execution. -- The repo uses Docusaurus v3 with `future.v4: true` — upgrading to v4 may require breaking changes; test locally. -- Verify `organizationName` / `projectName` in `docusaurus.config.js` before deploying. -- There are no automated tests found in the repo — treat code edits accordingly and do a local build verification (`yarn build && yarn serve`). +## Notes & Watch-Outs -## When editing/PR guidance for an AI agent +- **Node Environment**: Docusaurus config runs in Node.js. Avoid browser-specific code (e.g., `window`, `document`). +- **Version Compatibility**: The repo uses Docusaurus v3 with `future.v4: true`. Test thoroughly before upgrading to v4. +- **Testing**: No automated tests exist. Validate changes locally with `yarn build && yarn serve`. -- Make one small, testable change per PR (e.g., add a doc, update a component). Run `yarn start` or `yarn build` locally to validate. -- Update `sidebars.js` or the relevant `_category_.json` if moving docs between folders. -- For visual changes, include screenshots in the PR description and the `build/` output when applicable. +## Contribution Guidelines -## Contact / Maintainer questions +- Make small, testable changes per PR (e.g., add a doc, update a component). +- Include screenshots for visual changes and verify the `build/` output. +- Update `sidebars.js` or `_category_.json` if moving docs between folders. -- Confirm values for `organizationName` and `projectName` in `docusaurus.config.js` if you plan to change deploy settings. -- If you want CI configuration or GitHub Actions templates, specify Node version and preferred publish flow. +## Contact / Maintainer Questions ---- -If you'd like, I can: (a) add a small GitHub Actions workflow that runs `yarn build` on PRs, or (b) generate a short CONTRIBUTING.md with doc/post guidelines—tell me which and I'll implement it. +- Confirm `organizationName` and `projectName` in `docusaurus.config.js` before changing deploy settings. +- For CI configuration or GitHub Actions templates, specify the Node version and preferred publish flow. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3b07337..0e633a0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -21,13 +21,16 @@ jobs: uses: actions/setup-node@v4 with: node-version: '20' - cache: 'yarn' + cache: 'npm' - name: Install dependencies - run: yarn install --frozen-lockfile + run: npm ci - name: Build site - run: yarn build + run: npm run build + + - name: Run tests + run: npm test - name: Upload build artifact uses: actions/upload-artifact@v4 diff --git a/docs/architecture/_category_.json b/docs/architecture/_category_.json new file mode 100644 index 0000000..31258eb --- /dev/null +++ b/docs/architecture/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Architecture", + "position": 7, + "link": { + "type": "generated-index", + "description": "Technical architecture documentation covering monorepo structure, backend systems, and CI/CD pipelines." + } +} \ No newline at end of file diff --git a/docs/architecture/backend-architecture.md b/docs/architecture/backend-architecture.md new file mode 100644 index 0000000..908cb61 --- /dev/null +++ b/docs/architecture/backend-architecture.md @@ -0,0 +1,1507 @@ +# Backend Architecture + +This document outlines the backend architecture, API design, and infrastructure components used by Monynha Softwares. + +## Backend Overview + +### Technology Stack + +Monynha Softwares uses a modern, scalable backend architecture built on: + +- **Primary Framework**: Node.js with TypeScript +- **Database**: PostgreSQL with Supabase +- **ORM**: Prisma ORM for type-safe database operations +- **API**: RESTful APIs with GraphQL support +- **Authentication**: Supabase Auth with JWT tokens +- **Real-time**: Supabase Realtime for live updates +- **Storage**: Supabase Storage for file uploads +- **Caching**: Redis for session and data caching + +### Architecture Principles + +- **Microservices**: Modular, independently deployable services +- **API-First**: Design APIs before implementing frontend +- **Type Safety**: Full TypeScript coverage across the stack +- **Security First**: Authentication, authorization, and data validation +- **Scalability**: Horizontal scaling with load balancing +- **Observability**: Comprehensive logging and monitoring + +## API Architecture + +### RESTful API Design + +#### Resource-Based URLs + +``` +GET /api/v1/users # List users +POST /api/v1/users # Create user +GET /api/v1/users/:id # Get user by ID +PUT /api/v1/users/:id # Update user +DELETE /api/v1/users/:id # Delete user +GET /api/v1/users/:id/posts # Get user's posts +``` + +#### HTTP Status Codes + +- **200 OK**: Successful request +- **201 Created**: Resource created successfully +- **204 No Content**: Successful request with no response body +- **400 Bad Request**: Invalid request data +- **401 Unauthorized**: Authentication required +- **403 Forbidden**: Insufficient permissions +- **404 Not Found**: Resource not found +- **422 Unprocessable Entity**: Validation errors +- **500 Internal Server Error**: Server error + +#### Request/Response Format + +```json +// Request +{ + "data": { + "name": "John Doe", + "email": "john@example.com" + } +} + +// Response +{ + "success": true, + "data": { + "id": "123", + "name": "John Doe", + "email": "john@example.com", + "createdAt": "2024-01-01T00:00:00Z" + } +} + +// Error Response +{ + "success": false, + "error": { + "code": "VALIDATION_ERROR", + "message": "Invalid email format", + "details": { + "email": "Must be a valid email address" + } + } +} +``` + +### GraphQL API + +#### Schema Definition + +```graphql +type Query { + users(limit: Int, offset: Int): [User!]! + user(id: ID!): User + posts(userId: ID, limit: Int, offset: Int): [Post!]! + post(id: ID!): Post +} + +type Mutation { + createUser(input: CreateUserInput!): User! + updateUser(id: ID!, input: UpdateUserInput!): User! + deleteUser(id: ID!): Boolean! + createPost(input: CreatePostInput!): Post! +} + +type User { + id: ID! + name: String! + email: String! + posts: [Post!]! + createdAt: DateTime! + updatedAt: DateTime! +} + +type Post { + id: ID! + title: String! + content: String! + author: User! + createdAt: DateTime! + updatedAt: DateTime! +} + +input CreateUserInput { + name: String! + email: String! + password: String! +} + +input UpdateUserInput { + name: String + email: String +} +``` + +#### Resolvers Implementation + +```typescript +// User resolvers +export const userResolvers = { + Query: { + users: async (_: any, { limit = 10, offset = 0 }: { limit: number; offset: number }) => { + return await prisma.user.findMany({ + take: limit, + skip: offset, + orderBy: { createdAt: 'desc' } + }); + }, + + user: async (_: any, { id }: { id: string }) => { + return await prisma.user.findUnique({ + where: { id } + }); + } + }, + + Mutation: { + createUser: async (_: any, { input }: { input: CreateUserInput }) => { + const hashedPassword = await bcrypt.hash(input.password, 10); + + return await prisma.user.create({ + data: { + name: input.name, + email: input.email, + password: hashedPassword + } + }); + }, + + updateUser: async (_: any, { id, input }: { id: string; input: UpdateUserInput }) => { + return await prisma.user.update({ + where: { id }, + data: input + }); + } + }, + + User: { + posts: async (user: User) => { + return await prisma.post.findMany({ + where: { authorId: user.id } + }); + } + } +}; +``` + +## Database Architecture + +### PostgreSQL Schema Design + +#### Core Tables + +```sql +-- Users table +CREATE TABLE users ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + email VARCHAR(255) UNIQUE NOT NULL, + name VARCHAR(255) NOT NULL, + password_hash VARCHAR(255), + email_verified BOOLEAN DEFAULT FALSE, + avatar_url VARCHAR(500), + created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() +); + +-- Projects table +CREATE TABLE projects ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + name VARCHAR(255) NOT NULL, + description TEXT, + owner_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + status VARCHAR(50) DEFAULT 'active', + settings JSONB DEFAULT '{}', + created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() +); + +-- Project members +CREATE TABLE project_members ( + project_id UUID NOT NULL REFERENCES projects(id) ON DELETE CASCADE, + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + role VARCHAR(50) DEFAULT 'member', + joined_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + PRIMARY KEY (project_id, user_id) +); + +-- Tasks table +CREATE TABLE tasks ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + project_id UUID NOT NULL REFERENCES projects(id) ON DELETE CASCADE, + title VARCHAR(500) NOT NULL, + description TEXT, + status VARCHAR(50) DEFAULT 'todo', + priority VARCHAR(20) DEFAULT 'medium', + assignee_id UUID REFERENCES users(id), + due_date TIMESTAMP WITH TIME ZONE, + tags TEXT[] DEFAULT '{}', + created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() +); +``` + +#### Indexes and Constraints + +```sql +-- Performance indexes +CREATE INDEX idx_users_email ON users(email); +CREATE INDEX idx_projects_owner_id ON projects(owner_id); +CREATE INDEX idx_project_members_project_id ON project_members(project_id); +CREATE INDEX idx_project_members_user_id ON project_members(user_id); +CREATE INDEX idx_tasks_project_id ON tasks(project_id); +CREATE INDEX idx_tasks_assignee_id ON tasks(assignee_id); +CREATE INDEX idx_tasks_status ON tasks(status); +CREATE INDEX idx_tasks_due_date ON tasks(due_date); + +-- Partial indexes for active records +CREATE INDEX idx_active_projects ON projects(created_at) WHERE status = 'active'; +CREATE INDEX idx_pending_tasks ON tasks(created_at) WHERE status IN ('todo', 'in_progress'); + +-- Unique constraints +ALTER TABLE project_members ADD CONSTRAINT unique_project_user UNIQUE (project_id, user_id); +``` + +### Prisma ORM + +#### Schema Definition + +```prisma +// schema.prisma +generator client { + provider = "prisma-client-js" +} + +datasource db { + provider = "postgresql" + url = env("DATABASE_URL") +} + +model User { + id String @id @default(uuid()) + email String @unique + name String + passwordHash String? + emailVerified Boolean @default(false) + avatarUrl String? + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + // Relations + ownedProjects Project[] @relation("ProjectOwner") + memberships ProjectMember[] + assignedTasks Task[] + + @@map("users") +} + +model Project { + id String @id @default(uuid()) + name String + description String? + ownerId String + status String @default("active") + settings Json @default("{}") + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + // Relations + owner User @relation("ProjectOwner", fields: [ownerId], references: [id], onDelete: Cascade) + members ProjectMember[] + tasks Task[] + + @@map("projects") +} + +model ProjectMember { + projectId String + userId String + role String @default("member") + joinedAt DateTime @default(now()) + + // Relations + project Project @relation(fields: [projectId], references: [id], onDelete: Cascade) + user User @relation(fields: [userId], references: [id], onDelete: Cascade) + + @@unique([projectId, userId]) + @@map("project_members") +} + +model Task { + id String @id @default(uuid()) + projectId String + title String + description String? + status String @default("todo") + priority String @default("medium") + assigneeId String? + dueDate DateTime? + tags String[] + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + // Relations + project Project @relation(fields: [projectId], references: [id], onDelete: Cascade) + assignee User? @relation(fields: [assigneeId], references: [id]) + + @@map("tasks") +} +``` + +#### Database Operations + +```typescript +// User service +export class UserService { + async createUser(data: CreateUserInput): Promise { + const hashedPassword = await bcrypt.hash(data.password, 10); + + return await prisma.user.create({ + data: { + name: data.name, + email: data.email, + passwordHash: hashedPassword + } + }); + } + + async getUserById(id: string): Promise { + return await prisma.user.findUnique({ + where: { id }, + include: { + ownedProjects: true, + memberships: { + include: { + project: true + } + } + } + }); + } + + async updateUser(id: string, data: UpdateUserInput): Promise { + return await prisma.user.update({ + where: { id }, + data + }); + } +} + +// Project service +export class ProjectService { + async createProject(ownerId: string, data: CreateProjectInput): Promise { + return await prisma.project.create({ + data: { + name: data.name, + description: data.description, + ownerId + } + }); + } + + async getProjectWithMembers(projectId: string): Promise { + return await prisma.project.findUnique({ + where: { id: projectId }, + include: { + owner: true, + members: { + include: { + user: true + } + }, + tasks: true + } + }); + } + + async addMember(projectId: string, userId: string, role: string = 'member'): Promise { + await prisma.projectMember.create({ + data: { + projectId, + userId, + role + } + }); + } +} +``` + +## Authentication & Authorization + +### Supabase Auth Integration + +#### Authentication Flow + +```typescript +// Auth service +export class AuthService { + async signUp(email: string, password: string, name: string) { + const { data, error } = await supabase.auth.signUp({ + email, + password, + options: { + data: { + name + } + } + }); + + if (error) throw error; + + // Create user profile in database + if (data.user) { + await prisma.user.create({ + data: { + id: data.user.id, + email: data.user.email!, + name + } + }); + } + + return data; + } + + async signIn(email: string, password: string) { + const { data, error } = await supabase.auth.signInWithPassword({ + email, + password + }); + + if (error) throw error; + return data; + } + + async signOut() { + const { error } = await supabase.auth.signOut(); + if (error) throw error; + } + + async getCurrentUser() { + const { data: { user }, error } = await supabase.auth.getUser(); + if (error) throw error; + return user; + } +} +``` + +#### JWT Token Handling + +```typescript +// JWT middleware +export const authenticateToken = async (req: Request, res: Response, next: NextFunction) => { + const authHeader = req.headers.authorization; + const token = authHeader && authHeader.split(' ')[1]; + + if (!token) { + return res.status(401).json({ error: 'Access token required' }); + } + + try { + const { data: { user }, error } = await supabase.auth.getUser(token); + + if (error || !user) { + return res.status(403).json({ error: 'Invalid token' }); + } + + req.user = user; + next(); + } catch (error) { + return res.status(403).json({ error: 'Token verification failed' }); + } +}; + +// Role-based authorization +export const requireRole = (allowedRoles: string[]) => { + return (req: Request, res: Response, next: NextFunction) => { + if (!req.user) { + return res.status(401).json({ error: 'Authentication required' }); + } + + // Get user role from database + // This would typically be cached or included in JWT + const userRole = req.user.user_metadata?.role || 'user'; + + if (!allowedRoles.includes(userRole)) { + return res.status(403).json({ error: 'Insufficient permissions' }); + } + + next(); + }; +}; +``` + +### Row Level Security (RLS) + +#### RLS Policies + +```sql +-- Enable RLS +ALTER TABLE projects ENABLE ROW LEVEL SECURITY; +ALTER TABLE tasks ENABLE ROW LEVEL SECURITY; + +-- Projects policies +CREATE POLICY "Users can view projects they own or are members of" ON projects + FOR SELECT USING ( + owner_id = auth.uid() OR + id IN ( + SELECT project_id FROM project_members + WHERE user_id = auth.uid() + ) + ); + +CREATE POLICY "Users can create projects" ON projects + FOR INSERT WITH CHECK (owner_id = auth.uid()); + +CREATE POLICY "Project owners can update their projects" ON projects + FOR UPDATE USING (owner_id = auth.uid()); + +-- Tasks policies +CREATE POLICY "Users can view tasks in their projects" ON tasks + FOR SELECT USING ( + project_id IN ( + SELECT id FROM projects WHERE owner_id = auth.uid() + UNION + SELECT project_id FROM project_members WHERE user_id = auth.uid() + ) + ); + +CREATE POLICY "Users can create tasks in their projects" ON tasks + FOR INSERT WITH CHECK ( + project_id IN ( + SELECT id FROM projects WHERE owner_id = auth.uid() + UNION + SELECT project_id FROM project_members WHERE user_id = auth.uid() + ) + ); + +CREATE POLICY "Users can update tasks they are assigned to or in their projects" ON tasks + FOR UPDATE USING ( + assignee_id = auth.uid() OR + project_id IN ( + SELECT id FROM projects WHERE owner_id = auth.uid() + UNION + SELECT project_id FROM project_members WHERE user_id = auth.uid() + ) + ); +``` + +## Real-time Features + +### Supabase Realtime + +#### Real-time Subscriptions + +```typescript +// Real-time task updates +export class RealtimeService { + subscribeToProjectTasks(projectId: string, callback: (payload: any) => void) { + const channel = supabase + .channel(`project-${projectId}-tasks`) + .on( + 'postgres_changes', + { + event: '*', + schema: 'public', + table: 'tasks', + filter: `project_id=eq.${projectId}` + }, + callback + ) + .subscribe(); + + return channel; + } + + subscribeToProjectMembers(projectId: string, callback: (payload: any) => void) { + const channel = supabase + .channel(`project-${projectId}-members`) + .on( + 'postgres_changes', + { + event: '*', + schema: 'public', + table: 'project_members', + filter: `project_id=eq.${projectId}` + }, + callback + ) + .subscribe(); + + return channel; + } + + // Real-time notifications + subscribeToNotifications(userId: string, callback: (payload: any) => void) { + const channel = supabase + .channel(`user-${userId}-notifications`) + .on( + 'postgres_changes', + { + event: 'INSERT', + schema: 'public', + table: 'notifications', + filter: `user_id=eq.${userId}` + }, + callback + ) + .subscribe(); + + return channel; + } +} +``` + +#### WebSocket Implementation + +```typescript +// WebSocket server for real-time collaboration +import { WebSocketServer } from 'ws'; +import { IncomingMessage } from 'http'; + +export class WebSocketService { + private wss: WebSocketServer; + private clients: Map = new Map(); + + constructor(server: any) { + this.wss = new WebSocketServer({ server }); + + this.wss.on('connection', (ws: WebSocket, request: IncomingMessage) => { + const userId = this.getUserIdFromRequest(request); + + if (userId) { + this.clients.set(userId, ws); + + ws.on('message', (message: Buffer) => { + this.handleMessage(userId, message); + }); + + ws.on('close', () => { + this.clients.delete(userId); + }); + } + }); + } + + private getUserIdFromRequest(request: IncomingMessage): string | null { + // Extract user ID from JWT token in request headers + const token = request.headers.authorization?.split(' ')[1]; + if (!token) return null; + + try { + const decoded = jwt.verify(token, process.env.JWT_SECRET!) as any; + return decoded.sub; + } catch { + return null; + } + } + + private async handleMessage(userId: string, message: Buffer) { + try { + const data = JSON.parse(message.toString()); + + switch (data.type) { + case 'task_update': + await this.handleTaskUpdate(userId, data); + break; + case 'cursor_position': + this.broadcastCursorPosition(userId, data); + break; + } + } catch (error) { + console.error('WebSocket message handling error:', error); + } + } + + private broadcastCursorPosition(userId: string, data: any) { + // Broadcast cursor position to other users in the same project + const message = JSON.stringify({ + type: 'cursor_update', + userId, + position: data.position, + timestamp: Date.now() + }); + + this.clients.forEach((client, clientId) => { + if (clientId !== userId && client.readyState === WebSocket.OPEN) { + client.send(message); + } + }); + } +} +``` + +## File Storage & Uploads + +### Supabase Storage + +#### File Upload Service + +```typescript +// File upload service +export class FileUploadService { + private readonly bucket = 'project-files'; + + async uploadFile(file: File, projectId: string, userId: string): Promise { + const fileExt = file.name.split('.').pop(); + const fileName = `${Date.now()}-${Math.random().toString(36).substring(2)}.${fileExt}`; + const filePath = `${projectId}/${userId}/${fileName}`; + + const { data, error } = await supabase.storage + .from(this.bucket) + .upload(filePath, file, { + cacheControl: '3600', + upsert: false + }); + + if (error) throw error; + + // Get public URL + const { data: { publicUrl } } = supabase.storage + .from(this.bucket) + .getPublicUrl(filePath); + + return publicUrl; + } + + async deleteFile(filePath: string): Promise { + const { error } = await supabase.storage + .from(this.bucket) + .remove([filePath]); + + if (error) throw error; + } + + async getFileUrl(filePath: string): Promise { + const { data: { publicUrl } } = supabase.storage + .from(this.bucket) + .getPublicUrl(filePath); + + return publicUrl; + } + + async listProjectFiles(projectId: string): Promise { + const { data, error } = await supabase.storage + .from(this.bucket) + .list(projectId); + + if (error) throw error; + return data || []; + } +} +``` + +#### File Processing Pipeline + +```typescript +// File processing with image optimization +export class FileProcessingService { + async processImage(file: File): Promise { + // Resize and optimize image + const canvas = document.createElement('canvas'); + const ctx = canvas.getContext('2d')!; + const img = new Image(); + + return new Promise((resolve) => { + img.onload = () => { + // Resize to max 1920px width maintaining aspect ratio + const maxWidth = 1920; + const ratio = Math.min(maxWidth / img.width, 1); + canvas.width = img.width * ratio; + canvas.height = img.height * ratio; + + ctx.drawImage(img, 0, 0, canvas.width, canvas.height); + + canvas.toBlob((blob) => { + if (blob) { + const processedFile = new File([blob], file.name, { + type: 'image/jpeg', + lastModified: Date.now() + }); + resolve(processedFile); + } + }, 'image/jpeg', 0.8); + }; + + img.src = URL.createObjectURL(file); + }); + } + + async generateThumbnails(file: File): Promise { + const sizes = [100, 300, 600]; + const thumbnails: File[] = []; + + for (const size of sizes) { + const thumbnail = await this.resizeImage(file, size, size); + thumbnails.push(thumbnail); + } + + return thumbnails; + } + + private async resizeImage(file: File, maxWidth: number, maxHeight: number): Promise { + // Image resizing logic + return file; // Placeholder + } +} +``` + +## Caching Strategy + +### Redis Implementation + +#### Cache Service + +```typescript +// Redis cache service +export class CacheService { + private client: Redis; + + constructor() { + this.client = new Redis(process.env.REDIS_URL); + } + + async get(key: string): Promise { + try { + const data = await this.client.get(key); + return data ? JSON.parse(data) : null; + } catch (error) { + console.error('Cache get error:', error); + return null; + } + } + + async set(key: string, value: any, ttlSeconds?: number): Promise { + try { + const serialized = JSON.stringify(value); + if (ttlSeconds) { + await this.client.setex(key, ttlSeconds, serialized); + } else { + await this.client.set(key, serialized); + } + } catch (error) { + console.error('Cache set error:', error); + } + } + + async delete(key: string): Promise { + try { + await this.client.del(key); + } catch (error) { + console.error('Cache delete error:', error); + } + } + + async invalidatePattern(pattern: string): Promise { + try { + const keys = await this.client.keys(pattern); + if (keys.length > 0) { + await this.client.del(keys); + } + } catch (error) { + console.error('Cache invalidate pattern error:', error); + } + } +} +``` + +#### Cache Keys Strategy + +```typescript +// Cache key constants +export const CACHE_KEYS = { + USER: (id: string) => `user:${id}`, + USER_PROJECTS: (userId: string) => `user:${userId}:projects`, + PROJECT: (id: string) => `project:${id}`, + PROJECT_MEMBERS: (projectId: string) => `project:${projectId}:members`, + PROJECT_TASKS: (projectId: string) => `project:${projectId}:tasks`, + TASK: (id: string) => `task:${id}`, + USER_SESSION: (userId: string) => `session:${userId}`, +}; + +// Cache TTL constants +export const CACHE_TTL = { + USER: 3600, // 1 hour + PROJECT: 1800, // 30 minutes + TASK: 900, // 15 minutes + SESSION: 86400, // 24 hours +}; +``` + +#### Cache-Aside Pattern + +```typescript +// Service with caching +export class CachedUserService { + constructor( + private userService: UserService, + private cache: CacheService + ) {} + + async getUserById(id: string): Promise { + const cacheKey = CACHE_KEYS.USER(id); + + // Try cache first + let user = await this.cache.get(cacheKey); + if (user) { + return user; + } + + // Cache miss - fetch from database + user = await this.userService.getUserById(id); + if (user) { + await this.cache.set(cacheKey, user, CACHE_TTL.USER); + } + + return user; + } + + async updateUser(id: string, data: UpdateUserInput): Promise { + const user = await this.userService.updateUser(id, data); + + // Invalidate cache + const cacheKey = CACHE_KEYS.USER(id); + await this.cache.delete(cacheKey); + + // Cache updated user + await this.cache.set(cacheKey, user, CACHE_TTL.USER); + + return user; + } +} +``` + +## Background Jobs & Queues + +### Job Queue System + +#### Bull Queue Implementation + +```typescript +// Job queue service +import Queue from 'bull'; +import { injectable } from 'inversify'; + +@injectable() +export class QueueService { + private emailQueue: Queue.Queue; + private fileQueue: Queue.Queue; + + constructor() { + this.emailQueue = new Queue('email', process.env.REDIS_URL); + this.fileQueue = new Queue('file-processing', process.env.REDIS_URL); + + this.setupQueues(); + } + + private setupQueues() { + // Email queue processor + this.emailQueue.process(async (job) => { + const { to, subject, template, data } = job.data; + await this.sendEmail(to, subject, template, data); + }); + + // File processing queue processor + this.fileQueue.process(async (job) => { + const { fileId, operations } = job.data; + await this.processFile(fileId, operations); + }); + } + + async addEmailJob(emailData: EmailJobData): Promise { + await this.emailQueue.add(emailData, { + attempts: 3, + backoff: { + type: 'exponential', + delay: 5000 + } + }); + } + + async addFileProcessingJob(fileData: FileJobData): Promise { + await this.fileQueue.add(fileData, { + priority: 1, + delay: 1000 + }); + } + + private async sendEmail(to: string, subject: string, template: string, data: any): Promise { + // Email sending logic + console.log(`Sending email to ${to}: ${subject}`); + } + + private async processFile(fileId: string, operations: string[]): Promise { + // File processing logic + console.log(`Processing file ${fileId} with operations: ${operations.join(', ')}`); + } +} +``` + +#### Scheduled Jobs + +```typescript +// Cron jobs +import cron from 'node-cron'; + +export class ScheduledJobsService { + constructor(private queueService: QueueService) { + this.setupCronJobs(); + } + + private setupCronJobs() { + // Daily cleanup job + cron.schedule('0 2 * * *', async () => { + console.log('Running daily cleanup job'); + await this.runDailyCleanup(); + }); + + // Weekly report generation + cron.schedule('0 9 * * 1', async () => { + console.log('Running weekly report generation'); + await this.generateWeeklyReports(); + }); + + // Monthly analytics + cron.schedule('0 1 1 * *', async () => { + console.log('Running monthly analytics'); + await this.runMonthlyAnalytics(); + }); + } + + private async runDailyCleanup(): Promise { + // Clean up old temporary files + // Remove expired sessions + // Archive old logs + } + + private async generateWeeklyReports(): Promise { + // Generate project progress reports + // Send summary emails to project owners + } + + private async runMonthlyAnalytics(): Promise { + // Calculate monthly metrics + // Generate analytics reports + // Update dashboard data + } +} +``` + +## API Rate Limiting + +### Rate Limiting Implementation + +```typescript +// Rate limiting middleware +import rateLimit from 'express-rate-limit'; +import RedisStore from 'rate-limit-redis'; + +export const createRateLimiter = (windowMs: number, maxRequests: number, message: string) => { + return rateLimit({ + store: new RedisStore({ + client: redisClient, + prefix: 'rl:' + }), + windowMs, + max: maxRequests, + message: { + error: 'Too many requests', + message, + retryAfter: Math.ceil(windowMs / 1000) + }, + standardHeaders: true, + legacyHeaders: false, + skip: (req) => { + // Skip rate limiting for admin users + return req.user?.role === 'admin'; + } + }); +}; + +// API rate limiters +export const authLimiter = createRateLimiter( + 15 * 60 * 1000, // 15 minutes + 5, // 5 attempts + 'Too many authentication attempts, please try again later' +); + +export const apiLimiter = createRateLimiter( + 15 * 60 * 1000, // 15 minutes + 100, // 100 requests + 'Too many API requests, please try again later' +); + +export const fileUploadLimiter = createRateLimiter( + 60 * 60 * 1000, // 1 hour + 10, // 10 uploads + 'Too many file uploads, please try again later' +); +``` + +#### Advanced Rate Limiting + +```typescript +// Custom rate limiter with user-based limits +export class UserRateLimiter { + private cache: CacheService; + + constructor(cache: CacheService) { + this.cache = cache; + } + + async checkLimit(userId: string, action: string, limit: number, windowMs: number): Promise { + const key = `rate_limit:${userId}:${action}`; + const now = Date.now(); + const windowStart = now - windowMs; + + // Get existing requests in window + const requests = await this.cache.get(key) || []; + + // Filter out old requests + const validRequests = requests.filter(timestamp => timestamp > windowStart); + + // Check if under limit + if (validRequests.length >= limit) { + return false; + } + + // Add current request + validRequests.push(now); + + // Store updated requests + await this.cache.set(key, validRequests, Math.ceil(windowMs / 1000)); + + return true; + } + + async getRemainingRequests(userId: string, action: string, limit: number, windowMs: number): Promise { + const key = `rate_limit:${userId}:${action}`; + const requests = await this.cache.get(key) || []; + const now = Date.now(); + const windowStart = now - windowMs; + + const validRequests = requests.filter(timestamp => timestamp > windowStart); + return Math.max(0, limit - validRequests.length); + } +} +``` + +## Error Handling & Logging + +### Global Error Handler + +```typescript +// Global error handling middleware +export const errorHandler = ( + error: Error, + req: Request, + res: Response, + next: NextFunction +): void => { + let statusCode = 500; + let message = 'Internal server error'; + + // Handle specific error types + if (error instanceof ValidationError) { + statusCode = 422; + message = 'Validation failed'; + } else if (error instanceof AuthenticationError) { + statusCode = 401; + message = 'Authentication failed'; + } else if (error instanceof AuthorizationError) { + statusCode = 403; + message = 'Access denied'; + } else if (error instanceof NotFoundError) { + statusCode = 404; + message = 'Resource not found'; + } + + // Log error + logger.error({ + message: error.message, + stack: error.stack, + url: req.url, + method: req.method, + userId: req.user?.id, + ip: req.ip, + userAgent: req.get('User-Agent') + }); + + // Send error response + res.status(statusCode).json({ + success: false, + error: { + message, + ...(process.env.NODE_ENV === 'development' && { stack: error.stack }) + } + }); +}; +``` + +#### Structured Logging + +```typescript +// Logger configuration +import pino from 'pino'; + +export const logger = pino({ + level: process.env.LOG_LEVEL || 'info', + formatters: { + level: (label) => ({ level: label }), + log: (obj) => { + if (obj.err) { + // Handle error objects + return { + ...obj, + err: { + message: obj.err.message, + stack: obj.err.stack, + ...obj.err + } + }; + } + return obj; + } + }, + serializers: { + req: pino.stdSerializers.req, + res: pino.stdSerializers.res, + err: pino.stdSerializers.err + }, + timestamp: pino.stdTimeFunctions.isoTime +}); + +// Request logging middleware +export const requestLogger = (req: Request, res: Response, next: NextFunction) => { + const start = Date.now(); + + res.on('finish', () => { + const duration = Date.now() - start; + + logger.info({ + method: req.method, + url: req.url, + status: res.statusCode, + duration: `${duration}ms`, + ip: req.ip, + userId: req.user?.id, + userAgent: req.get('User-Agent') + }); + }); + + next(); +}; +``` + +## Testing Strategy + +### Unit Testing + +```typescript +// User service unit tests +import { UserService } from '../services/UserService'; +import { mockPrisma } from '../../test/mocks/prisma'; + +describe('UserService', () => { + let userService: UserService; + + beforeEach(() => { + userService = new UserService(mockPrisma); + }); + + describe('createUser', () => { + it('should create a new user', async () => { + const userData = { + name: 'John Doe', + email: 'john@example.com', + password: 'password123' + }; + + mockPrisma.user.create.mockResolvedValue({ + id: '123', + ...userData, + passwordHash: 'hashed_password', + emailVerified: false, + createdAt: new Date(), + updatedAt: new Date() + }); + + const result = await userService.createUser(userData); + + expect(result).toBeDefined(); + expect(result.email).toBe(userData.email); + expect(mockPrisma.user.create).toHaveBeenCalledWith({ + data: expect.objectContaining({ + name: userData.name, + email: userData.email + }) + }); + }); + + it('should throw error for duplicate email', async () => { + mockPrisma.user.create.mockRejectedValue( + new Error('Unique constraint violation') + ); + + await expect(userService.createUser({ + name: 'John Doe', + email: 'existing@example.com', + password: 'password123' + })).rejects.toThrow(); + }); + }); +}); +``` + +### Integration Testing + +```typescript +// API integration tests +import request from 'supertest'; +import { app } from '../app'; +import { prisma } from '../lib/prisma'; + +describe('User API', () => { + beforeEach(async () => { + // Clean up database + await prisma.user.deleteMany(); + }); + + afterAll(async () => { + await prisma.$disconnect(); + }); + + describe('POST /api/v1/users', () => { + it('should create a new user', async () => { + const userData = { + name: 'John Doe', + email: 'john@example.com', + password: 'password123' + }; + + const response = await request(app) + .post('/api/v1/users') + .send(userData) + .expect(201); + + expect(response.body.success).toBe(true); + expect(response.body.data).toMatchObject({ + name: userData.name, + email: userData.email + }); + expect(response.body.data.id).toBeDefined(); + }); + + it('should return validation error for invalid email', async () => { + const response = await request(app) + .post('/api/v1/users') + .send({ + name: 'John Doe', + email: 'invalid-email', + password: 'password123' + }) + .expect(422); + + expect(response.body.success).toBe(false); + expect(response.body.error.message).toContain('validation'); + }); + }); + + describe('GET /api/v1/users/:id', () => { + it('should return user by id', async () => { + const user = await prisma.user.create({ + data: { + name: 'John Doe', + email: 'john@example.com', + passwordHash: 'hashed' + } + }); + + const response = await request(app) + .get(`/api/v1/users/${user.id}`) + .expect(200); + + expect(response.body.success).toBe(true); + expect(response.body.data.id).toBe(user.id); + }); + + it('should return 404 for non-existent user', async () => { + await request(app) + .get('/api/v1/users/non-existent-id') + .expect(404); + }); + }); +}); +``` + +### End-to-End Testing + +```typescript +// E2E tests with database +import { test, expect } from '@playwright/test'; +import { prisma } from '../lib/prisma'; + +test.describe('User Management', () => { + test.beforeEach(async () => { + // Clean database + await prisma.user.deleteMany(); + await prisma.project.deleteMany(); + }); + + test('user can register and create project', async ({ page }) => { + // Navigate to registration + await page.goto('/register'); + + // Fill registration form + await page.fill('[name="name"]', 'John Doe'); + await page.fill('[name="email"]', 'john@example.com'); + await page.fill('[name="password"]', 'password123'); + await page.click('[type="submit"]'); + + // Should redirect to dashboard + await expect(page).toHaveURL('/dashboard'); + + // Create a new project + await page.click('[data-testid="create-project"]'); + await page.fill('[name="projectName"]', 'My Test Project'); + await page.fill('[name="description"]', 'A test project'); + await page.click('[data-testid="submit-project"]'); + + // Should see project in list + await expect(page.locator('text=My Test Project')).toBeVisible(); + }); + + test('user cannot access other user projects', async ({ page, context }) => { + // Create two users and projects + const user1 = await prisma.user.create({ + data: { name: 'User 1', email: 'user1@test.com', passwordHash: 'hash1' } + }); + const user2 = await prisma.user.create({ + data: { name: 'User 2', email: 'user2@test.com', passwordHash: 'hash2' } + }); + + const project1 = await prisma.project.create({ + data: { name: 'Project 1', ownerId: user1.id } + }); + const project2 = await prisma.project.create({ + data: { name: 'Project 2', ownerId: user2.id } + }); + + // Login as user1 + await page.goto('/login'); + await page.fill('[name="email"]', 'user1@test.com'); + await page.fill('[name="password"]', 'password123'); + await page.click('[type="submit"]'); + + // Should see project1 but not project2 + await expect(page.locator(`text=${project1.name}`)).toBeVisible(); + await expect(page.locator(`text=${project2.name}`)).toBeHidden(); + }); +}); +``` + +This backend architecture provides a solid foundation for scalable, secure, and maintainable API services that power the Monynha Softwares platform. \ No newline at end of file diff --git a/docs/architecture/ci-cd.md b/docs/architecture/ci-cd.md new file mode 100644 index 0000000..ec94bd1 --- /dev/null +++ b/docs/architecture/ci-cd.md @@ -0,0 +1,1851 @@ +# CI/CD Architecture & Deployment + +This document outlines the Continuous Integration and Continuous Deployment (CI/CD) architecture, automation pipelines, and deployment strategies used by Monynha Softwares. + +## CI/CD Overview + +### Pipeline Architecture + +Monynha Softwares uses a comprehensive CI/CD pipeline that automates the entire software delivery lifecycle: + +- **Continuous Integration**: Automated testing, linting, and building +- **Continuous Deployment**: Automated deployment to staging and production +- **Infrastructure as Code**: Automated infrastructure provisioning +- **Security Scanning**: Automated security vulnerability detection +- **Performance Monitoring**: Automated performance regression detection + +### Technology Stack + +- **CI/CD Platform**: GitHub Actions +- **Container Registry**: GitHub Container Registry (GHCR) +- **Infrastructure**: AWS with Terraform +- **Container Orchestration**: AWS ECS Fargate +- **Load Balancing**: AWS Application Load Balancer +- **CDN**: AWS CloudFront +- **Monitoring**: AWS CloudWatch + DataDog + +## GitHub Actions Workflows + +### Main CI Pipeline + +```yaml +# .github/workflows/ci.yml +name: CI + +on: + push: + branches: [main, develop] + pull_request: + branches: [main, develop] + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + lint: + name: Lint & Format + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: '20' + cache: 'yarn' + + - name: Install dependencies + run: yarn install --frozen-lockfile + + - name: Run ESLint + run: yarn lint + + - name: Run Prettier + run: yarn format:check + + - name: Run TypeScript check + run: yarn type-check + + test: + name: Test + runs-on: ubuntu-latest + services: + postgres: + image: postgres:15 + env: + POSTGRES_PASSWORD: postgres + options: >- + --health-cmd pg_isready + --health-interval 10s + --health-timeout 5s + --health-retries 5 + ports: + - 5432:5432 + + redis: + image: redis:7-alpine + ports: + - 6379:6379 + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: '20' + cache: 'yarn' + + - name: Install dependencies + run: yarn install --frozen-lockfile + + - name: Run database migrations + run: yarn db:migrate + env: + DATABASE_URL: postgresql://postgres:postgres@localhost:5432/test + + - name: Run unit tests + run: yarn test:unit + env: + DATABASE_URL: postgresql://postgres:postgres@localhost:5432/test + REDIS_URL: redis://localhost:6379 + + - name: Run integration tests + run: yarn test:integration + env: + DATABASE_URL: postgresql://postgres:postgres@localhost:5432/test + REDIS_URL: redis://localhost:6379 + + - name: Upload coverage reports + uses: codecov/codecov-action@v3 + with: + file: ./coverage/lcov.info + + build: + name: Build + runs-on: ubuntu-latest + needs: [lint, test] + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: '20' + cache: 'yarn' + + - name: Install dependencies + run: yarn install --frozen-lockfile + + - name: Build applications + run: yarn build + + - name: Build Docker images + run: | + docker build -t monynha/web:${{ github.sha }} apps/web + docker build -t monynha/api:${{ github.sha }} apps/api + docker build -t monynha/docs:${{ github.sha }} apps/docs + + - name: Login to GitHub Container Registry + uses: docker/login-action@v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Push Docker images + run: | + docker tag monynha/web:${{ github.sha }} ghcr.io/${{ github.repository }}/web:${{ github.sha }} + docker tag monynha/api:${{ github.sha }} ghcr.io/${{ github.repository }}/api:${{ github.sha }} + docker tag monynha/docs:${{ github.sha }} ghcr.io/${{ github.repository }}/docs:${{ github.sha }} + docker push ghcr.io/${{ github.repository }}/web:${{ github.sha }} + docker push ghcr.io/${{ github.repository }}/api:${{ github.sha }} + docker push ghcr.io/${{ github.repository }}/docs:${{ github.sha }} + + security: + name: Security Scan + runs-on: ubuntu-latest + needs: [build] + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Run Trivy vulnerability scanner + uses: aquasecurity/trivy-action@master + with: + scan-type: 'fs' + scan-ref: '.' + format: 'sarif' + output: 'trivy-results.sarif' + + - name: Upload Trivy scan results + uses: github/codeql-action/upload-sarif@v2 + if: always() + with: + sarif_file: 'trivy-results.sarif' + + - name: Run Snyk security scan + uses: snyk/actions/node@master + env: + SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }} + with: + args: --severity-threshold=high + + performance: + name: Performance Test + runs-on: ubuntu-latest + needs: [build] + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: '20' + cache: 'yarn' + + - name: Install dependencies + run: yarn install --frozen-lockfile + + - name: Build for production + run: yarn build + + - name: Run Lighthouse CI + uses: treosh/lighthouse-ci-action@v10 + with: + urls: | + http://localhost:3000 + configPath: .lighthouserc.json + uploadArtifacts: true + temporaryPublicStorage: true + + deploy-staging: + name: Deploy to Staging + runs-on: ubuntu-latest + needs: [build, security, performance] + if: github.ref == 'refs/heads/develop' + environment: staging + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Configure AWS credentials + uses: aws-actions/configure-aws-credentials@v4 + with: + aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }} + aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} + aws-region: us-east-1 + + - name: Deploy to staging + run: | + aws ecs update-service --cluster monynha-staging --service web --force-new-deployment + aws ecs update-service --cluster monynha-staging --service api --force-new-deployment + aws ecs update-service --cluster monynha-staging --service docs --force-new-deployment + + - name: Run staging tests + run: | + npm install -g wait-on + wait-on http://staging.monynha.com/api/health + yarn test:e2e:staging + + deploy-production: + name: Deploy to Production + runs-on: ubuntu-latest + needs: [build, security, performance] + if: github.ref == 'refs/heads/main' + environment: production + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Configure AWS credentials + uses: aws-actions/configure-aws-credentials@v4 + with: + aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }} + aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} + aws-region: us-east-1 + + - name: Deploy to production + run: | + aws ecs update-service --cluster monynha-prod --service web --force-new-deployment + aws ecs update-service --cluster monynha-prod --service api --force-new-deployment + aws ecs update-service --cluster monynha-prod --service docs --force-new-deployment + + - name: Run production smoke tests + run: | + npm install -g wait-on + wait-on https://monynha.com/api/health + yarn test:smoke +``` + +### Pull Request Validation + +```yaml +# .github/workflows/pr-validation.yml +name: PR Validation + +on: + pull_request: + types: [opened, synchronize, reopened] + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number }} + cancel-in-progress: true + +jobs: + pr-checks: + name: PR Checks + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: '20' + cache: 'yarn' + + - name: Install dependencies + run: yarn install --frozen-lockfile + + - name: Run linting + run: yarn lint + + - name: Run type checking + run: yarn type-check + + - name: Run unit tests + run: yarn test:unit + + - name: Check test coverage + run: yarn test:coverage --check-coverage --lines 80 --functions 80 --branches 75 + + - name: Run security audit + run: yarn audit --audit-level high + + - name: Check bundle size + run: yarn build && yarn size-limit + + preview-deployment: + name: Preview Deployment + runs-on: ubuntu-latest + needs: pr-checks + if: github.event.pull_request.head.repo.full_name == github.repository + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: '20' + cache: 'yarn' + + - name: Install dependencies + run: yarn install --frozen-lockfile + + - name: Build preview + run: yarn build:preview + + - name: Deploy to Vercel + uses: amondnet/vercel-action@v25 + with: + vercel-token: ${{ secrets.VERCEL_TOKEN }} + vercel-org-id: ${{ secrets.VERCEL_ORG_ID }} + vercel-project-id: ${{ secrets.VERCEL_PROJECT_ID }} + scope: ${{ secrets.VERCEL_ORG_ID }} + + - name: Comment PR with preview URL + uses: actions/github-script@v7 + with: + script: | + github.rest.issues.createComment({ + issue_number: context.issue.number, + owner: context.repo.owner, + repo: context.repo.repo, + body: `🚀 Preview deployment ready: ${{ steps.vercel.outputs.preview-url }}` + }) +``` + +### Release Management + +```yaml +# .github/workflows/release.yml +name: Release + +on: + push: + tags: + - 'v*' + +jobs: + release: + name: Create Release + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: '20' + cache: 'yarn' + + - name: Install dependencies + run: yarn install --frozen-lockfile + + - name: Build applications + run: yarn build + + - name: Run tests + run: yarn test + + - name: Create GitHub release + uses: actions/create-release@v1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + tag_name: ${{ github.ref }} + release_name: Release ${{ github.ref }} + body: | + ## Changes + + See [CHANGELOG.md](CHANGELOG.md) for details. + + ## Deployment + + This release has been automatically deployed to production. + + - name: Publish to npm + if: contains(github.ref, 'apps/web') || contains(github.ref, 'packages/') + run: | + npm config set //registry.npmjs.org/:_authToken ${{ secrets.NPM_TOKEN }} + yarn publish:packages + + - name: Update documentation + run: | + yarn docs:build + yarn docs:deploy +``` + +## Infrastructure as Code + +### Terraform Configuration + +#### Main Infrastructure + +```hcl +# infrastructure/main.tf +terraform { + required_providers { + aws = { + source = "hashicorp/aws" + version = "~> 5.0" + } + } + + backend "s3" { + bucket = "monynha-terraform-state" + key = "infrastructure.tfstate" + region = "us-east-1" + } +} + +provider "aws" { + region = "us-east-1" +} + +# VPC Configuration +module "vpc" { + source = "./modules/vpc" + + name = "monynha" + cidr = "10.0.0.0/16" + + azs = ["us-east-1a", "us-east-1b", "us-east-1c"] + private_subnets = ["10.0.1.0/24", "10.0.2.0/24", "10.0.3.0/24"] + public_subnets = ["10.0.101.0/24", "10.0.102.0/24", "10.0.103.0/24"] + + enable_nat_gateway = true + single_nat_gateway = true +} + +# ECS Cluster +resource "aws_ecs_cluster" "main" { + name = "monynha-${var.environment}" + + setting { + name = "containerInsights" + value = "enabled" + } +} + +# Application Load Balancer +resource "aws_lb" "main" { + name = "monynha-${var.environment}" + internal = false + load_balancer_type = "application" + security_groups = [aws_security_group.alb.id] + subnets = module.vpc.public_subnets + + enable_deletion_protection = var.environment == "prod" +} + +# ECS Services +module "web_service" { + source = "./modules/ecs-service" + + name = "web" + cluster_id = aws_ecs_cluster.main.id + vpc_id = module.vpc.vpc_id + subnets = module.vpc.private_subnets + alb_arn = aws_lb.main.arn + container_port = 3000 + host_port = 80 + + container_definitions = jsonencode([ + { + name = "web" + image = "${var.container_registry}/web:${var.image_tag}" + + portMappings = [ + { + containerPort = 3000 + hostPort = 3000 + protocol = "tcp" + } + ] + + environment = [ + { name = "NODE_ENV", value = var.environment }, + { name = "API_URL", value = var.api_url } + ] + + secrets = [ + { name = "DATABASE_URL", valueFrom = aws_ssm_parameter.database_url.arn }, + { name = "JWT_SECRET", valueFrom = aws_ssm_parameter.jwt_secret.arn } + ] + + logConfiguration = { + logDriver = "awslogs" + options = { + "awslogs-group" = aws_cloudwatch_log_group.web.name + "awslogs-region" = var.region + "awslogs-stream-prefix" = "web" + } + } + } + ]) +} + +# RDS Database +resource "aws_db_instance" "main" { + identifier = "monynha-${var.environment}" + + engine = "postgres" + engine_version = "15.4" + instance_class = var.db_instance_class + + allocated_storage = var.db_allocated_storage + + db_name = "monynha" + username = var.db_username + password = var.db_password + + vpc_security_group_ids = [aws_security_group.rds.id] + db_subnet_group_name = aws_db_subnet_group.main.name + + backup_retention_period = var.environment == "prod" ? 30 : 7 + backup_window = "03:00-04:00" + maintenance_window = "sun:04:00-sun:05:00" + + multi_az = var.environment == "prod" + skip_final_snapshot = var.environment != "prod" + final_snapshot_identifier = var.environment == "prod" ? "monynha-prod-final" : null + + enabled_cloudwatch_logs_exports = ["postgresql"] +} + +# Redis Cluster +resource "aws_elasticache_cluster" "redis" { + cluster_id = "monynha-${var.environment}" + engine = "redis" + node_type = var.redis_node_type + num_cache_nodes = var.environment == "prod" ? 2 : 1 + port = 6379 + + subnet_group_name = aws_elasticache_subnet_group.main.name + security_group_ids = [aws_security_group.redis.id] + + snapshot_retention_limit = var.environment == "prod" ? 7 : 0 +} + +# CloudFront Distribution +resource "aws_cloudfront_distribution" "main" { + enabled = true + is_ipv6_enabled = true + default_root_object = "index.html" + + origin { + domain_name = aws_lb.main.dns_name + origin_id = "alb" + + custom_origin_config { + http_port = 80 + https_port = 443 + origin_protocol_policy = "https-only" + origin_ssl_protocols = ["TLSv1.2"] + } + } + + default_cache_behavior { + allowed_methods = ["DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT"] + cached_methods = ["GET", "HEAD"] + target_origin_id = "alb" + + forwarded_values { + query_string = true + cookies { + forward = "all" + } + headers = ["*"] + } + + viewer_protocol_policy = "redirect-to-https" + min_ttl = 0 + default_ttl = 0 + max_ttl = 0 + } + + restrictions { + geo_restriction { + restriction_type = "none" + } + } + + viewer_certificate { + acm_certificate_arn = aws_acm_certificate.main.arn + ssl_support_method = "sni-only" + } +} +``` + +#### ECS Service Module + +```hcl +# modules/ecs-service/main.tf +resource "aws_ecs_service" "main" { + name = var.name + cluster = var.cluster_id + task_definition = aws_ecs_task_definition.main.arn + desired_count = var.desired_count + + load_balancer { + target_group_arn = aws_lb_target_group.main.arn + container_name = var.name + container_port = var.container_port + } + + network_configuration { + subnets = var.subnets + security_groups = [aws_security_group.service.id] + } + + depends_on = [aws_lb_listener.main] +} + +resource "aws_ecs_task_definition" "main" { + family = "${var.name}-${var.environment}" + network_mode = "awsvpc" + requires_compatibilities = ["FARGATE"] + cpu = var.cpu + memory = var.memory + execution_role_arn = aws_iam_role.execution.arn + task_role_arn = aws_iam_role.task.arn + + container_definitions = var.container_definitions +} + +resource "aws_lb_target_group" "main" { + name = "${var.name}-${var.environment}" + port = var.host_port + protocol = "HTTP" + vpc_id = var.vpc_id + target_type = "ip" + + health_check { + enabled = true + healthy_threshold = 2 + interval = 30 + matcher = "200" + path = "/health" + port = "traffic-port" + protocol = "HTTP" + timeout = 5 + unhealthy_threshold = 2 + } +} + +resource "aws_lb_listener_rule" "main" { + listener_arn = var.alb_arn + priority = var.priority + + action { + type = "forward" + target_group_arn = aws_lb_target_group.main.arn + } + + condition { + path_pattern { + values = var.path_patterns + } + } +} +``` + +### Environment Management + +#### Staging Environment + +```hcl +# environments/staging/main.tf +module "staging" { + source = "../../infrastructure" + + environment = "staging" + + # Smaller instance sizes for staging + web_cpu = 256 + web_memory = 512 + api_cpu = 512 + api_memory = 1024 + + db_instance_class = "db.t3.micro" + db_allocated_storage = 20 + redis_node_type = "cache.t3.micro" + + # Staging-specific settings + domain_name = "staging.monynha.com" + enable_deletion_protection = false +} +``` + +#### Production Environment + +```hcl +# environments/prod/main.tf +module "prod" { + source = "../../infrastructure" + + environment = "prod" + + # Production instance sizes + web_cpu = 1024 + web_memory = 2048 + api_cpu = 2048 + api_memory = 4096 + + db_instance_class = "db.r6g.large" + db_allocated_storage = 100 + redis_node_type = "cache.r6g.large" + + # Production-specific settings + domain_name = "monynha.com" + enable_deletion_protection = true + + # High availability + multi_az = true +} +``` + +## Deployment Strategies + +### Blue-Green Deployment + +```bash +#!/bin/bash +# deploy-blue-green.sh + +set -e + +ENVIRONMENT=$1 +SERVICE=$2 +IMAGE_TAG=$3 + +if [ -z "$ENVIRONMENT" ] || [ -z "$SERVICE" ] || [ -z "$IMAGE_TAG" ]; then + echo "Usage: $0 " + exit 1 +fi + +CLUSTER_NAME="monynha-$ENVIRONMENT" +SERVICE_NAME="$SERVICE-$ENVIRONMENT" + +# Get current task definition +CURRENT_TASK_DEF=$(aws ecs describe-services \ + --cluster $CLUSTER_NAME \ + --services $SERVICE_NAME \ + --query 'services[0].taskDefinition' \ + --output text) + +# Create new task definition with new image +NEW_TASK_DEF=$(aws ecs register-task-definition \ + --family $SERVICE_NAME \ + --container-definitions "[{ + \"name\": \"$SERVICE\", + \"image\": \"ghcr.io/monynha/monynha/$SERVICE:$IMAGE_TAG\", + \"essential\": true, + \"portMappings\": [{ + \"containerPort\": 3000, + \"hostPort\": 3000, + \"protocol\": \"tcp\" + }], + \"environment\": [ + {\"name\": \"NODE_ENV\", \"value\": \"$ENVIRONMENT\"} + ], + \"logConfiguration\": { + \"logDriver\": \"awslogs\", + \"options\": { + \"awslogs-group\": \"/ecs/$SERVICE-$ENVIRONMENT\", + \"awslogs-region\": \"us-east-1\", + \"awslogs-stream-prefix\": \"ecs\" + } + } + }]" \ + --requires-compatibilities FARGATE \ + --network-mode awsvpc \ + --cpu 256 \ + --memory 512 \ + --execution-role-arn "arn:aws:iam::123456789012:role/ecsTaskExecutionRole" \ + --task-role-arn "arn:aws:iam::123456789012:role/ecsTaskRole" \ + --query 'taskDefinition.taskDefinitionArn' \ + --output text) + +# Update service to use new task definition +aws ecs update-service \ + --cluster $CLUSTER_NAME \ + --service $SERVICE_NAME \ + --task-definition $NEW_TASK_DEF \ + --force-new-deployment + +# Wait for deployment to complete +echo "Waiting for deployment to complete..." +aws ecs wait services-stable \ + --cluster $CLUSTER_NAME \ + --services $SERVICE_NAME + +# Run smoke tests +if [ "$ENVIRONMENT" = "prod" ]; then + echo "Running production smoke tests..." + npm run test:smoke +fi + +# Clean up old task definitions (keep last 5) +OLD_TASK_DEFS=$(aws ecs list-task-definitions \ + --family-prefix $SERVICE_NAME \ + --sort DESC \ + --query 'taskDefinitionArns[5:]' \ + --output text) + +if [ -n "$OLD_TASK_DEFS" ]; then + echo "Cleaning up old task definitions..." + for task_def in $OLD_TASK_DEFS; do + aws ecs deregister-task-definition --task-definition $task_def + done +fi + +echo "Blue-green deployment completed successfully!" +``` + +### Canary Deployment + +```typescript +// canary-deployment.ts +import { ECS, CloudWatch } from 'aws-sdk'; + +export class CanaryDeployment { + private ecs = new ECS(); + private cloudwatch = new CloudWatch(); + + async deployCanary( + clusterName: string, + serviceName: string, + newTaskDefinition: string, + canaryPercentage: number = 10 + ) { + // Get current service configuration + const service = await this.ecs.describeServices({ + cluster: clusterName, + services: [serviceName] + }).promise(); + + const currentDesiredCount = service.services![0].desiredCount!; + + // Calculate canary instance count + const canaryCount = Math.max(1, Math.floor(currentDesiredCount * canaryPercentage / 100)); + + // Create canary service with new task definition + const canaryServiceName = `${serviceName}-canary`; + await this.ecs.createService({ + cluster: clusterName, + serviceName: canaryServiceName, + taskDefinition: newTaskDefinition, + desiredCount: canaryCount, + loadBalancers: service.services![0].loadBalancers, + networkConfiguration: service.services![0].networkConfiguration + }).promise(); + + // Wait for canary to be healthy + await this.waitForServiceHealthy(clusterName, canaryServiceName); + + // Monitor canary metrics + const canaryHealthy = await this.monitorCanaryMetrics(clusterName, canaryServiceName); + + if (canaryHealthy) { + // Gradually increase canary traffic + await this.gradualTrafficShift(clusterName, serviceName, canaryServiceName, currentDesiredCount); + } else { + // Rollback canary + await this.rollbackCanary(clusterName, canaryServiceName); + throw new Error('Canary deployment failed health checks'); + } + } + + private async waitForServiceHealthy(clusterName: string, serviceName: string): Promise { + // Wait for service to reach steady state + await this.ecs.waitFor('servicesStable', { + cluster: clusterName, + services: [serviceName] + }).promise(); + } + + private async monitorCanaryMetrics(clusterName: string, serviceName: string): Promise { + // Monitor error rates, response times, etc. + const endTime = new Date(); + const startTime = new Date(endTime.getTime() - 10 * 60 * 1000); // 10 minutes ago + + const metrics = await this.cloudwatch.getMetricData({ + MetricDataQueries: [ + { + Id: 'errors', + MetricStat: { + Metric: { + Namespace: 'AWS/ECS', + MetricName: 'CPUUtilization', + Dimensions: [ + { Name: 'ClusterName', Value: clusterName }, + { Name: 'ServiceName', Value: serviceName } + ] + }, + Period: 300, + Stat: 'Average' + } + } + ], + StartTime: startTime, + EndTime: endTime + }).promise(); + + // Check if metrics are within acceptable ranges + return this.analyzeMetrics(metrics); + } + + private async gradualTrafficShift( + clusterName: string, + originalService: string, + canaryService: string, + totalCount: number + ): Promise { + // Gradually shift traffic from original to canary + const steps = 5; + for (let i = 1; i <= steps; i++) { + const canaryWeight = Math.floor((i / steps) * 100); + const originalWeight = 100 - canaryWeight; + + // Update load balancer weights + await this.updateLoadBalancerWeights(originalService, canaryService, originalWeight, canaryWeight); + + // Wait and monitor + await new Promise(resolve => setTimeout(resolve, 5 * 60 * 1000)); // 5 minutes + + const healthy = await this.monitorCanaryMetrics(clusterName, canaryService); + if (!healthy) { + await this.rollbackCanary(clusterName, canaryService); + throw new Error(`Canary failed at ${canaryWeight}% traffic`); + } + } + + // Complete migration + await this.ecs.updateService({ + cluster: clusterName, + service: originalService, + taskDefinition: canaryService, // This would be the new task definition + desiredCount: totalCount + }).promise(); + + // Remove canary service + await this.ecs.deleteService({ + cluster: clusterName, + service: canaryService + }).promise(); + } + + private async rollbackCanary(clusterName: string, canaryService: string): Promise { + // Scale down canary to 0 + await this.ecs.updateService({ + cluster: clusterName, + service: canaryService, + desiredCount: 0 + }).promise(); + + // Delete canary service + await this.ecs.deleteService({ + cluster: clusterName, + service: canaryService + }).promise(); + } +} +``` + +## Monitoring & Observability + +### Application Monitoring + +#### CloudWatch Dashboards + +```json +{ + "widgets": [ + { + "type": "metric", + "properties": { + "metrics": [ + ["AWS/ECS", "CPUUtilization", "ClusterName", "monynha-prod", "ServiceName", "web", { "stat": "Average" }], + ["AWS/ECS", "CPUUtilization", "ClusterName", "monynha-prod", "ServiceName", "api", { "stat": "Average" }] + ], + "view": "timeSeries", + "stacked": false, + "region": "us-east-1", + "title": "ECS CPU Utilization", + "period": 300 + } + }, + { + "type": "metric", + "properties": { + "metrics": [ + ["AWS/ECS", "MemoryUtilization", "ClusterName", "monynha-prod", "ServiceName", "web", { "stat": "Average" }], + ["AWS/ECS", "MemoryUtilization", "ClusterName", "monynha-prod", "ServiceName", "api", { "stat": "Average" }] + ], + "view": "timeSeries", + "stacked": false, + "region": "us-east-1", + "title": "ECS Memory Utilization", + "period": 300 + } + }, + { + "type": "metric", + "properties": { + "metrics": [ + ["AWS/ApplicationELB", "RequestCount", "LoadBalancer", "app/monynha-prod/1234567890abcdef", { "stat": "Sum" }], + ["AWS/ApplicationELB", "HTTPCode_Target_5XX_Count", "LoadBalancer", "app/monynha-prod/1234567890abcdef", { "stat": "Sum" }], + ["AWS/ApplicationELB", "HTTPCode_Target_4XX_Count", "LoadBalancer", "app/monynha-prod/1234567890abcdef", { "stat": "Sum" }] + ], + "view": "timeSeries", + "stacked": false, + "region": "us-east-1", + "title": "ALB Request Metrics", + "period": 300 + } + } + ] +} +``` + +#### DataDog Integration + +```typescript +// datadog-monitoring.ts +import { dogapi } from '@datadog/datadog-api-client'; + +export class DataDogMonitoring { + private metrics = new dogapi.MetricsApi(); + private configuration = dogapi.createConfiguration(); + + constructor(apiKey: string, appKey: string) { + this.configuration.apiKey = apiKey; + this.configuration.appKey = appKey; + } + + async submitCustomMetrics(metrics: CustomMetric[]) { + const series = metrics.map(metric => ({ + metric: metric.name, + points: [[Date.now() / 1000, metric.value]], + tags: metric.tags, + type: 1 // gauge + })); + + await this.metrics.submitMetrics({ + body: { series } + }); + } + + async createMonitor(monitor: MonitorConfig) { + const monitorsApi = new dogapi.MonitorsApi(this.configuration); + + await monitorsApi.createMonitor({ + body: { + name: monitor.name, + type: monitor.type, + query: monitor.query, + message: monitor.message, + tags: monitor.tags, + options: { + thresholds: monitor.thresholds, + notifyNoData: true, + noDataTimeframe: 10 + } + } + }); + } + + async sendEvent(event: EventData) { + const eventsApi = new dogapi.EventsApi(this.configuration); + + await eventsApi.createEvent({ + body: { + title: event.title, + text: event.text, + tags: event.tags, + alertType: event.alertType, + priority: event.priority + } + }); + } +} + +// Usage +const monitoring = new DataDogMonitoring(process.env.DD_API_KEY!, process.env.DD_APP_KEY!); + +// Submit custom metrics +await monitoring.submitCustomMetrics([ + { + name: 'monynha.user.registrations', + value: 1, + tags: ['environment:prod', 'service:api'] + }, + { + name: 'monynha.api.response_time', + value: 150, + tags: ['environment:prod', 'endpoint:/api/users'] + } +]); + +// Create monitors +await monitoring.createMonitor({ + name: 'High Error Rate', + type: 'metric alert', + query: 'avg(last_5m):avg:aws.applicationelb.httpcode_target_5xx_count{loadbalancer:monynha-prod} > 10', + message: 'Error rate is above 10 per minute', + tags: ['team:backend', 'service:api'], + thresholds: { + critical: 10, + warning: 5 + } +}); +``` + +### Performance Monitoring + +#### Synthetic Monitoring + +```yaml +# .github/workflows/synthetic-monitoring.yml +name: Synthetic Monitoring + +on: + schedule: + - cron: '*/15 * * * *' # Every 15 minutes + workflow_dispatch: + +jobs: + synthetic-tests: + name: Synthetic Tests + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: '20' + cache: 'yarn' + + - name: Install dependencies + run: yarn install --frozen-lockfile + + - name: Run synthetic tests + run: yarn test:synthetic + env: + BASE_URL: ${{ secrets.BASE_URL }} + API_KEY: ${{ secrets.API_KEY }} + + - name: Upload results to DataDog + if: always() + run: | + yarn datadog:synthetic:upload + env: + DD_API_KEY: ${{ secrets.DD_API_KEY }} + DD_APP_KEY: ${{ secrets.DD_APP_KEY }} +``` + +#### Real User Monitoring (RUM) + +```typescript +// rum-tracking.ts +export class RUMTracker { + private events: RUMEvent[] = []; + + trackPageView(page: string, userId?: string) { + this.trackEvent({ + type: 'page_view', + page, + userId, + timestamp: Date.now(), + userAgent: navigator.userAgent, + url: window.location.href + }); + } + + trackUserAction(action: string, metadata?: Record) { + this.trackEvent({ + type: 'user_action', + action, + metadata, + timestamp: Date.now() + }); + } + + trackError(error: Error, context?: Record) { + this.trackEvent({ + type: 'error', + error: { + message: error.message, + stack: error.stack, + name: error.name + }, + context, + timestamp: Date.now(), + url: window.location.href + }); + } + + trackPerformance(metric: PerformanceMetric) { + this.trackEvent({ + type: 'performance', + metric, + timestamp: Date.now() + }); + } + + private trackEvent(event: RUMEvent) { + this.events.push(event); + + // Batch send events + if (this.events.length >= 10) { + this.flushEvents(); + } + } + + private async flushEvents() { + if (this.events.length === 0) return; + + try { + await fetch('/api/rum/events', { + method: 'POST', + headers: { + 'Content-Type': 'application/json' + }, + body: JSON.stringify({ + events: this.events, + sessionId: this.getSessionId() + }) + }); + + this.events = []; + } catch (error) { + console.error('Failed to send RUM events:', error); + // Keep events for retry + } + } + + private getSessionId(): string { + let sessionId = sessionStorage.getItem('rum_session_id'); + if (!sessionId) { + sessionId = Math.random().toString(36).substring(2); + sessionStorage.setItem('rum_session_id', sessionId); + } + return sessionId; + } +} + +// Initialize RUM tracking +const rumTracker = new RUMTracker(); + +// Track page views +window.addEventListener('load', () => { + rumTracker.trackPageView(window.location.pathname); +}); + +// Track route changes (for SPAs) +if (typeof window.history !== 'undefined') { + const originalPushState = window.history.pushState; + window.history.pushState = function(state, title, url) { + originalPushState.apply(this, arguments); + rumTracker.trackPageView(url || window.location.pathname); + }; +} + +// Track errors +window.addEventListener('error', (event) => { + rumTracker.trackError(new Error(event.message), { + filename: event.filename, + lineno: event.lineno, + colno: event.colno + }); +}); + +// Track performance +window.addEventListener('load', () => { + setTimeout(() => { + const navigation = performance.getEntriesByType('navigation')[0] as PerformanceNavigationTiming; + rumTracker.trackPerformance({ + type: 'navigation', + domContentLoaded: navigation.domContentLoadedEventEnd - navigation.domContentLoadedEventStart, + loadComplete: navigation.loadEventEnd - navigation.loadEventStart, + firstPaint: performance.getEntriesByName('first-paint')[0]?.startTime, + firstContentfulPaint: performance.getEntriesByName('first-contentful-paint')[0]?.startTime + }); + }, 0); +}); +``` + +## Security in CI/CD + +### Secret Management + +#### AWS Secrets Manager Integration + +```typescript +// secrets-manager.ts +import { SecretsManager } from 'aws-sdk'; + +export class SecretsManagerService { + private client = new SecretsManager(); + + async getSecret(secretName: string): Promise { + const response = await this.client.getSecretValue({ + SecretId: secretName + }).promise(); + + if (response.SecretString) { + return response.SecretString; + } + + throw new Error(`Secret ${secretName} not found`); + } + + async getSecretJson(secretName: string): Promise { + const secretString = await this.getSecret(secretName); + return JSON.parse(secretString); + } + + async createSecret(secretName: string, secretValue: string, description?: string) { + await this.client.createSecret({ + Name: secretName, + SecretString: secretValue, + Description: description + }).promise(); + } + + async updateSecret(secretName: string, secretValue: string) { + await this.client.updateSecret({ + SecretId: secretName, + SecretString: secretValue + }).promise(); + } + + async rotateSecret(secretName: string) { + await this.client.rotateSecret({ + SecretId: secretName + }).promise(); + } +} +``` + +#### GitHub Secrets Management + +```yaml +# .github/workflows/rotate-secrets.yml +name: Rotate Secrets + +on: + schedule: + - cron: '0 0 1 * *' # First day of every month + workflow_dispatch: + +jobs: + rotate-secrets: + name: Rotate Secrets + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Configure AWS credentials + uses: aws-actions/configure-aws-credentials@v4 + with: + aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }} + aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} + aws-region: us-east-1 + + - name: Rotate database password + run: | + NEW_PASSWORD=$(openssl rand -base64 32) + aws secretsmanager update-secret \ + --secret-id monynha/db-password \ + --secret-string "$NEW_PASSWORD" + + # Update RDS instance (this would trigger a restart) + aws rds modify-db-instance \ + --db-instance-identifier monynha-prod \ + --master-user-password "$NEW_PASSWORD" \ + --apply-immediately + + - name: Rotate JWT secret + run: | + NEW_JWT_SECRET=$(openssl rand -hex 32) + aws secretsmanager update-secret \ + --secret-id monynha/jwt-secret \ + --secret-string "$NEW_JWT_SECRET" + + # Trigger rolling update of ECS services + aws ecs update-service --cluster monynha-prod --service api --force-new-deployment + + - name: Rotate API keys + run: | + NEW_API_KEY=$(openssl rand -hex 32) + aws secretsmanager update-secret \ + --secret-id monynha/api-key \ + --secret-string "$NEW_API_KEY" + + - name: Send notification + run: | + curl -X POST ${{ secrets.SLACK_WEBHOOK_URL }} \ + -H 'Content-type: application/json' \ + -d '{"text": "🔐 Secrets rotated successfully"}' +``` + +### Security Scanning + +#### Container Image Scanning + +```yaml +# .github/workflows/container-scan.yml +name: Container Security Scan + +on: + push: + branches: [main, develop] + paths: + - 'apps/**/Dockerfile' + - 'packages/**/Dockerfile' + +jobs: + scan: + name: Security Scan + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Build Docker images + run: | + docker build -t monynha/web:scan apps/web + docker build -t monynha/api:scan apps/api + + - name: Scan with Trivy + uses: aquasecurity/trivy-action@master + with: + scan-type: 'image' + scan-ref: 'monynha/web:scan,monynha/api:scan' + format: 'sarif' + output: 'trivy-results.sarif' + severity: 'CRITICAL,HIGH' + + - name: Upload Trivy results + uses: github/codeql-action/upload-sarif@v2 + if: always() + with: + sarif_file: 'trivy-results.sarif' + + - name: Scan with Snyk + uses: snyk/actions/docker@master + env: + SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }} + with: + image: monynha/web:scan + args: --file=Dockerfile --severity-threshold=high + + - name: Fail on critical vulnerabilities + if: failure() + run: | + echo "❌ Critical security vulnerabilities found!" + echo "Please fix the vulnerabilities before merging." + exit 1 +``` + +#### Dependency Vulnerability Scanning + +```yaml +# .github/workflows/dependency-scan.yml +name: Dependency Security Scan + +on: + push: + branches: [main, develop] + pull_request: + branches: [main, develop] + schedule: + - cron: '0 0 * * *' # Daily at midnight + +jobs: + audit: + name: Dependency Audit + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: '20' + cache: 'yarn' + + - name: Install dependencies + run: yarn install --frozen-lockfile + + - name: Run npm audit + run: | + if npm audit --audit-level high; then + echo "✅ No high or critical vulnerabilities found" + else + echo "❌ High or critical vulnerabilities found" + exit 1 + fi + + - name: Run Snyk test + uses: snyk/actions/node@master + env: + SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }} + with: + args: --severity-threshold=high + + - name: Run OWASP Dependency Check + uses: dependency-check/Dependency-Check_Action@main + with: + project: 'Monynha' + path: '.' + format: 'ALL' + args: > + --enableRetired + --enableExperimental + --nvdValidForHours 24 + + - name: Upload dependency check results + uses: actions/upload-artifact@v3 + if: always() + with: + name: dependency-check-report + path: reports/ +``` + +## Rollback Strategies + +### Automated Rollback + +```typescript +// rollback-service.ts +export class RollbackService { + async rollbackDeployment( + environment: string, + service: string, + targetVersion?: string + ) { + const clusterName = `monynha-${environment}`; + const serviceName = `${service}-${environment}`; + + // Get current task definition + const currentService = await this.ecs.describeServices({ + cluster: clusterName, + services: [serviceName] + }).promise(); + + const currentTaskDef = currentService.services![0].taskDefinition!; + + // Find previous stable version + let rollbackTaskDef: string; + + if (targetVersion) { + // Rollback to specific version + rollbackTaskDef = `${serviceName}:${targetVersion}`; + } else { + // Find previous task definition + const taskDefs = await this.ecs.listTaskDefinitions({ + familyPrefix: serviceName, + sort: 'DESC', + maxResults: 10 + }).promise(); + + // Skip current version and find previous stable one + const currentVersion = currentTaskDef.split(':').pop(); + const previousVersions = taskDefs.taskDefinitionArns! + .map(arn => arn.split(':').pop()!) + .filter(version => version !== currentVersion) + .slice(0, 3); // Check last 3 versions + + rollbackTaskDef = `${serviceName}:${previousVersions[0]}`; + } + + // Update service to use rollback task definition + await this.ecs.updateService({ + cluster: clusterName, + service: serviceName, + taskDefinition: rollbackTaskDef, + forceNewDeployment: true + }).promise(); + + // Wait for deployment to complete + await this.ecs.waitFor('servicesStable', { + cluster: clusterName, + services: [serviceName] + }).promise(); + + // Run health checks + const healthy = await this.runHealthChecks(environment, service); + + if (!healthy) { + throw new Error('Rollback failed - service is not healthy'); + } + + // Send notification + await this.sendNotification( + 'rollback', + `Successfully rolled back ${service} in ${environment} to ${rollbackTaskDef}` + ); + + return rollbackTaskDef; + } + + async emergencyRollback(environment: string) { + // Rollback all services to last known good state + const services = ['web', 'api', 'docs']; + + for (const service of services) { + try { + await this.rollbackDeployment(environment, service); + } catch (error) { + console.error(`Failed to rollback ${service}:`, error); + // Continue with other services + } + } + } + + private async runHealthChecks(environment: string, service: string): Promise { + // Implement health checks + const baseUrl = environment === 'prod' ? 'https://monynha.com' : `https://staging.monynha.com`; + + try { + const response = await fetch(`${baseUrl}/health`); + return response.ok; + } catch { + return false; + } + } + + private async sendNotification(type: string, message: string) { + // Send notification to Slack, email, etc. + console.log(`[${type.toUpperCase()}] ${message}`); + } +} +``` + +### Deployment Monitoring + +```typescript +// deployment-monitor.ts +export class DeploymentMonitor { + async monitorDeployment( + environment: string, + service: string, + deploymentId: string + ) { + const metrics = []; + const alerts = []; + + // Monitor deployment progress + const startTime = Date.now(); + + while (true) { + const status = await this.checkDeploymentStatus(environment, service); + + if (status === 'COMPLETED') { + await this.recordSuccessfulDeployment(environment, service, deploymentId, startTime); + break; + } else if (status === 'FAILED') { + await this.handleFailedDeployment(environment, service, deploymentId); + break; + } + + // Check metrics every 30 seconds + const deploymentMetrics = await this.collectDeploymentMetrics(environment, service); + + metrics.push({ + timestamp: Date.now(), + ...deploymentMetrics + }); + + // Check for alerts + const newAlerts = this.analyzeMetricsForAlerts(metrics); + alerts.push(...newAlerts); + + if (alerts.length > 0) { + await this.escalateAlerts(alerts); + } + + await new Promise(resolve => setTimeout(resolve, 30000)); // Wait 30 seconds + } + } + + private async checkDeploymentStatus(environment: string, service: string): Promise { + // Check ECS service deployment status + const clusterName = `monynha-${environment}`; + const serviceName = `${service}-${environment}`; + + const service = await this.ecs.describeServices({ + cluster: clusterName, + services: [serviceName] + }).promise(); + + const deployment = service.services![0].deployments![0]; + + if (deployment.rolloutState === 'COMPLETED') { + return 'COMPLETED'; + } else if (deployment.rolloutState === 'FAILED') { + return 'FAILED'; + } + + return 'IN_PROGRESS'; + } + + private async collectDeploymentMetrics(environment: string, service: string) { + // Collect CPU, memory, error rates, response times + const endTime = new Date(); + const startTime = new Date(endTime.getTime() - 5 * 60 * 1000); // Last 5 minutes + + const metrics = await this.cloudwatch.getMetricData({ + MetricDataQueries: [ + { + Id: 'cpu', + MetricStat: { + Metric: { + Namespace: 'AWS/ECS', + MetricName: 'CPUUtilization', + Dimensions: [ + { Name: 'ClusterName', Value: `monynha-${environment}` }, + { Name: 'ServiceName', Value: `${service}-${environment}` } + ] + }, + Period: 300, + Stat: 'Average' + } + }, + { + Id: 'memory', + MetricStat: { + Metric: { + Namespace: 'AWS/ECS', + MetricName: 'MemoryUtilization', + Dimensions: [ + { Name: 'ClusterName', Value: `monynha-${environment}` }, + { Name: 'ServiceName', Value: `${service}-${environment}` } + ] + }, + Period: 300, + Stat: 'Average' + } + } + ], + StartTime: startTime, + EndTime: endTime + }).promise(); + + return { + cpu: metrics.MetricDataResults?.find(m => m.Id === 'cpu')?.Values?.[0] || 0, + memory: metrics.MetricDataResults?.find(m => m.Id === 'memory')?.Values?.[0] || 0 + }; + } + + private analyzeMetricsForAlerts(metrics: any[]): Alert[] { + const alerts: Alert[] = []; + const recentMetrics = metrics.slice(-5); // Last 5 data points + + // Check for high CPU usage + const avgCpu = recentMetrics.reduce((sum, m) => sum + m.cpu, 0) / recentMetrics.length; + if (avgCpu > 80) { + alerts.push({ + type: 'HIGH_CPU', + message: `CPU usage is ${avgCpu.toFixed(1)}%`, + severity: 'warning' + }); + } + + // Check for high memory usage + const avgMemory = recentMetrics.reduce((sum, m) => sum + m.memory, 0) / recentMetrics.length; + if (avgMemory > 85) { + alerts.push({ + type: 'HIGH_MEMORY', + message: `Memory usage is ${avgMemory.toFixed(1)}%`, + severity: 'warning' + }); + } + + return alerts; + } + + private async escalateAlerts(alerts: Alert[]) { + for (const alert of alerts) { + if (alert.severity === 'critical') { + // Immediate notification + await this.sendCriticalAlert(alert); + } else if (alert.severity === 'warning') { + // Warning notification + await this.sendWarningAlert(alert); + } + } + } +} +``` + +This CI/CD architecture provides a robust, secure, and automated deployment pipeline that ensures high availability, fast feedback, and reliable releases for the Monynha Softwares platform. \ No newline at end of file diff --git a/docs/architecture/monorepo-structure.md b/docs/architecture/monorepo-structure.md new file mode 100644 index 0000000..7fc38bc --- /dev/null +++ b/docs/architecture/monorepo-structure.md @@ -0,0 +1,759 @@ +# Monorepo Structure & Architecture + +This document outlines the monorepo architecture, project organization, and technical infrastructure used by Monynha Softwares. + +## Monorepo Overview + +### Why Monorepo? + +Monynha Softwares uses a monorepo approach to manage multiple related projects: + +- **Code Sharing**: Shared components, utilities, and configurations +- **Atomic Changes**: Changes across multiple packages in single commit +- **Unified Tooling**: Consistent development tools and processes +- **Simplified Dependencies**: Clear dependency relationships +- **Team Collaboration**: Easier collaboration across teams + +### Repository Structure + +```bash +monorepo/ +├── apps/ # Applications +│ ├── docs/ # Documentation site (Docusaurus) +│ ├── web/ # Main web application (Next.js) +│ ├── mobile/ # Mobile application (Flutter) +│ └── api/ # Backend API (Node.js) +├── packages/ # Shared packages +│ ├── ui/ # Shared UI components +│ ├── utils/ # Utility functions +│ ├── config/ # Shared configurations +│ ├── types/ # TypeScript type definitions +│ └── eslint-config/ # ESLint configurations +├── tools/ # Development tools +│ ├── scripts/ # Build and deployment scripts +│ ├── docker/ # Docker configurations +│ └── ci/ # CI/CD configurations +├── docs/ # Documentation +├── .github/ # GitHub configurations +│ ├── workflows/ # GitHub Actions +│ └── ISSUE_TEMPLATE/ # Issue templates +├── package.json # Root package.json +├── yarn.lock # Dependency lock file +├── turbo.json # Turborepo configuration +└── docker-compose.yml # Development environment +``` + +## Application Architecture + +### Web Application (Next.js) + +#### Web App Structure + +``` +apps/web/ +├── app/ # Next.js 13+ app directory +│ ├── (auth)/ # Route groups for auth pages +│ ├── (dashboard)/ # Route groups for dashboard +│ ├── api/ # API routes +│ ├── globals.css # Global styles +│ └── layout.tsx # Root layout +├── components/ # Page-specific components +├── lib/ # Utility functions +├── hooks/ # Custom React hooks +├── types/ # TypeScript definitions +├── public/ # Static assets +└── next.config.js # Next.js configuration +``` + +#### Architecture Patterns + +- **App Router**: Next.js 13+ app directory structure +- **Server Components**: Server-side rendering by default +- **Client Components**: Interactive components with 'use client' +- **Route Groups**: Logical grouping of routes +- **Middleware**: Authentication and routing middleware + +### Mobile Application (Flutter) + +#### Mobile App Structure + +```bash +apps/mobile/ +├── lib/ +│ ├── core/ # Core functionality +│ │ ├── models/ # Data models +│ │ ├── services/ # API services +│ │ ├── utils/ # Utility functions +│ │ └── constants/ # App constants +│ ├── features/ # Feature modules +│ │ ├── auth/ # Authentication feature +│ │ ├── dashboard/ # Dashboard feature +│ │ └── profile/ # User profile feature +│ ├── shared/ # Shared components +│ │ ├── widgets/ # Reusable widgets +│ │ ├── themes/ # App themes +│ │ └── localization/ # Localization files +│ └── main.dart # App entry point +├── test/ # Unit and widget tests +├── integration_test/ # Integration tests +├── android/ # Android-specific code +├── ios/ # iOS-specific code +└── pubspec.yaml # Flutter dependencies +``` + +#### State Management + +- **Provider**: Simple state management for small features +- **Riverpod**: Advanced state management for complex features +- **Bloc Pattern**: Business logic components for predictable state changes + +### Backend API (Node.js) + +#### Backend API Structure + +``` +apps/api/ +├── src/ +│ ├── config/ # Configuration files +│ ├── controllers/ # Route controllers +│ ├── middleware/ # Express middleware +│ ├── models/ # Database models +│ ├── routes/ # API routes +│ ├── services/ # Business logic services +│ ├── utils/ # Utility functions +│ ├── types/ # TypeScript definitions +│ └── app.ts # Express app setup +├── tests/ # API tests +├── migrations/ # Database migrations +├── seeds/ # Database seeds +├── docker/ # Docker configuration +└── package.json # Dependencies +``` + +#### API Architecture + +- **RESTful Design**: Resource-based API endpoints +- **GraphQL**: GraphQL API for complex queries +- **Authentication**: JWT-based authentication +- **Authorization**: Role-based access control +- **Validation**: Request validation with Joi/Zod +- **Error Handling**: Centralized error handling + +### Documentation Site (Docusaurus) + +#### Docs Site Structure + +```bash +apps/docs/ +├── docs/ # Documentation pages +├── blog/ # Blog posts +├── src/ +│ ├── components/ # Custom React components +│ ├── css/ # Custom styles +│ └── pages/ # Custom pages +├── static/ # Static assets +├── docusaurus.config.js # Docusaurus configuration +├── sidebars.js # Documentation sidebar +└── package.json # Dependencies +``` + +## Shared Packages + +### UI Component Library + +#### UI Library Structure + +```bash +packages/ui/ +├── src/ +│ ├── components/ # UI components +│ │ ├── Button/ # Button component +│ │ ├── Input/ # Input component +│ │ ├── Card/ # Card component +│ │ └── Modal/ # Modal component +│ ├── hooks/ # Custom hooks +│ ├── utils/ # Utility functions +│ ├── types/ # TypeScript types +│ └── index.ts # Main exports +├── stories/ # Storybook stories +├── tests/ # Component tests +└── package.json # Package configuration +``` + +#### Component Design + +- **Atomic Design**: Atoms, molecules, organisms +- **TypeScript**: Fully typed component APIs +- **Accessibility**: WCAG 2.1 AA compliance +- **Theming**: Support for multiple themes +- **Storybook**: Interactive component documentation + +### Utility Packages + +#### Common Utilities + +``` +packages/utils/ +├── src/ +│ ├── array/ # Array utilities +│ ├── date/ # Date manipulation +│ ├── string/ # String utilities +│ ├── validation/ # Validation functions +│ ├── formatting/ # Data formatting +│ └── index.ts # Main exports +├── tests/ # Utility tests +└── package.json # Package configuration +``` + +#### Specialized Utilities + +- **API Client**: Centralized HTTP client with interceptors +- **Error Handling**: Consistent error handling utilities +- **Logging**: Structured logging utilities +- **Caching**: Client-side caching utilities + +### Configuration Packages + +#### ESLint Configuration + +```bash +packages/eslint-config/ +├── index.js # Base configuration +├── next.js # Next.js specific rules +├── react.js # React specific rules +└── package.json # Package configuration +``` + +#### TypeScript Configuration + +```bash +packages/types/ +├── src/ +│ ├── api/ # API type definitions +│ ├── ui/ # UI component types +│ ├── domain/ # Domain models +│ └── index.ts # Main exports +└── package.json # Package configuration +``` + +## Development Tools + +### Build System (Turborepo) + +#### Configuration + +```json +// turbo.json +{ + "$schema": "https://turbo.build/schema.json", + "globalDependencies": ["**/.env.*local"], + "tasks": { + "build": { + "dependsOn": ["^build"], + "outputs": ["dist/**", ".next/**", "!.next/cache/**"] + }, + "lint": {}, + "test": {}, + "dev": { + "cache": false, + "persistent": true + } + } +} +``` + +#### Pipeline Optimization + +- **Dependency Graph**: Intelligent task scheduling +- **Caching**: Build artifact caching +- **Parallel Execution**: Parallel task execution +- **Remote Caching**: Shared cache across CI/CD + +### Development Environment + +#### Docker Compose + +```yaml +# docker-compose.yml +version: '3.8' +services: + postgres: + image: postgres:15 + environment: + POSTGRES_DB: monynha_dev + POSTGRES_USER: monynha + POSTGRES_PASSWORD: password + ports: + - "5432:5432" + volumes: + - postgres_data:/var/lib/postgresql/data + + redis: + image: redis:7-alpine + ports: + - "6379:6379" + + supabase: + image: supabase/supabase:latest + ports: + - "3000:3000" + environment: + - POSTGRES_PASSWORD=password + +volumes: + postgres_data: +``` + +#### Local Development + +- **Hot Reload**: Fast development with hot reloading +- **Database Seeding**: Automated test data setup +- **Environment Variables**: Local environment configuration +- **Debugging**: Integrated debugging support + +## Deployment Architecture + +### Infrastructure as Code + +#### Terraform Configuration + +```bash +infrastructure/ +├── main.tf # Main infrastructure +├── variables.tf # Input variables +├── outputs.tf # Output values +├── modules/ # Reusable modules +│ ├── vpc/ # VPC module +│ ├── ecs/ # ECS module +│ └── rds/ # RDS module +└── environments/ # Environment-specific config + ├── dev/ + ├── staging/ + └── prod/ +``` + +#### Cloud Architecture + +- **VPC**: Isolated network environment +- **ECS Fargate**: Container orchestration +- **RDS**: Managed database service +- **CloudFront**: CDN for static assets +- **S3**: Object storage +- **Route 53**: DNS management + +### CI/CD Pipelines + +#### GitHub Actions Workflow + +```yaml +# .github/workflows/deploy.yml +name: Deploy +on: + push: + branches: [main] + pull_request: + branches: [main] + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: '20' + cache: 'yarn' + - name: Install dependencies + run: yarn install --frozen-lockfile + - name: Run tests + run: yarn test + - name: Build + run: yarn build + + deploy: + needs: test + runs-on: ubuntu-latest + if: github.ref == 'refs/heads/main' + steps: + - name: Deploy to production + run: yarn deploy:prod +``` + +#### Deployment Strategy + +- **Blue-Green**: Zero-downtime deployments +- **Canary**: Gradual traffic shifting +- **Rollback**: Automated rollback capabilities +- **Monitoring**: Deployment health monitoring + +## Database Architecture + +### Schema Design + +#### Normalized Structure + +```sql +-- Users table +CREATE TABLE users ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + email VARCHAR(255) UNIQUE NOT NULL, + name VARCHAR(255) NOT NULL, + created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() +); + +-- Projects table +CREATE TABLE projects ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + name VARCHAR(255) NOT NULL, + description TEXT, + owner_id UUID REFERENCES users(id), + created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() +); + +-- Project members (many-to-many) +CREATE TABLE project_members ( + project_id UUID REFERENCES projects(id), + user_id UUID REFERENCES users(id), + role VARCHAR(50) DEFAULT 'member', + joined_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + PRIMARY KEY (project_id, user_id) +); +``` + +#### Indexing Strategy + +- **Primary Keys**: UUID primary keys for scalability +- **Foreign Keys**: Indexed foreign key constraints +- **Query Indexes**: Indexes for common query patterns +- **Partial Indexes**: Conditional indexes for filtered queries + +### Data Migration + +#### Migration Files + +```bash +migrations/ +├── 001_initial_schema.sql +├── 002_add_user_profiles.sql +├── 003_create_projects.sql +├── 004_add_project_members.sql +└── 005_add_audit_logs.sql +``` + +#### Migration Tools + +- **Version Control**: Git-based migration versioning +- **Rollback Support**: Ability to rollback migrations +- **Testing**: Migration testing in CI/CD +- **Documentation**: Migration documentation and rationale + +## Security Architecture + +### Authentication & Authorization + +#### JWT Implementation + +```typescript +// Authentication middleware +export async function authenticate(req: Request, res: Response, next: NextFunction) { + const token = req.headers.authorization?.replace('Bearer ', ''); + + if (!token) { + return res.status(401).json({ error: 'No token provided' }); + } + + try { + const decoded = jwt.verify(token, process.env.JWT_SECRET!) as UserPayload; + req.user = decoded; + next(); + } catch (error) { + return res.status(401).json({ error: 'Invalid token' }); + } +} + +// Authorization middleware +export function authorize(roles: string[]) { + return (req: Request, res: Response, next: NextFunction) => { + if (!req.user) { + return res.status(401).json({ error: 'Not authenticated' }); + } + + if (!roles.includes(req.user.role)) { + return res.status(403).json({ error: 'Not authorized' }); + } + + next(); + }; +} +``` + +#### Security Headers + +```typescript +// Security middleware +app.use((req, res, next) => { + // CORS + res.header('Access-Control-Allow-Origin', process.env.ALLOWED_ORIGINS); + res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS'); + res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization'); + + // Security headers + res.header('X-Content-Type-Options', 'nosniff'); + res.header('X-Frame-Options', 'DENY'); + res.header('X-XSS-Protection', '1; mode=block'); + res.header('Strict-Transport-Security', 'max-age=31536000; includeSubDomains'); + + // CSP + res.header('Content-Security-Policy', "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'"); + + next(); +}); +``` + +## Monitoring & Observability + +### Application Monitoring + +#### Logging + +```typescript +// Structured logging +import pino from 'pino'; + +const logger = pino({ + level: process.env.LOG_LEVEL || 'info', + formatters: { + level: (label) => { + return { level: label }; + }, + }, + timestamp: pino.stdTimeFunctions.isoTime, +}); + +// Usage +logger.info({ userId, action: 'login' }, 'User logged in successfully'); +logger.error({ err, userId }, 'Failed to process payment'); +``` + +#### Metrics + +- **Application Metrics**: Response times, error rates, throughput +- **Business Metrics**: User registrations, conversion rates +- **Performance Metrics**: Memory usage, CPU utilization +- **Custom Metrics**: Domain-specific KPIs + +### Infrastructure Monitoring + +#### Health Checks + +```typescript +// Health check endpoint +app.get('/health', async (req, res) => { + try { + // Database health check + await database.query('SELECT 1'); + + // External service checks + await checkExternalServices(); + + res.json({ + status: 'healthy', + timestamp: new Date().toISOString(), + services: { + database: 'up', + redis: 'up', + externalApi: 'up' + } + }); + } catch (error) { + logger.error('Health check failed', error); + res.status(503).json({ + status: 'unhealthy', + timestamp: new Date().toISOString(), + error: error.message + }); + } +}); +``` + +#### Alerting + +- **Error Rate Alerts**: High error rate notifications +- **Performance Alerts**: Slow response time alerts +- **Infrastructure Alerts**: Server down or resource alerts +- **Security Alerts**: Suspicious activity notifications + +## Performance Optimization + +### Frontend Optimization + +#### Bundle Optimization + +```javascript +// next.config.js +module.exports = { + experimental: { + optimizeCss: true, + }, + webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => { + // Bundle analyzer + if (!dev && process.env.ANALYZE) { + const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer'); + config.plugins.push( + new BundleAnalyzerPlugin({ + analyzerMode: 'static', + openAnalyzer: false, + }) + ); + } + + return config; + }, +}; +``` + +#### Image Optimization + +- **Next.js Image**: Automatic image optimization +- **WebP Format**: Modern image formats +- **Responsive Images**: Multiple sizes for different devices +- **Lazy Loading**: Images load as they enter viewport + +### Backend Optimization + +#### Database Optimization + +- **Query Optimization**: Efficient SQL queries +- **Indexing**: Strategic database indexes +- **Connection Pooling**: Database connection management +- **Caching**: Redis caching for frequently accessed data + +#### API Optimization + +- **Pagination**: Efficient data pagination +- **Compression**: Response compression +- **Rate Limiting**: API rate limiting +- **Caching**: HTTP caching headers + +## Testing Strategy + +### Testing Pyramid + +#### Unit Tests + +```typescript +// Component unit test +import { render, screen } from '@testing-library/react'; +import { Button } from './Button'; + +describe('Button', () => { + it('renders children correctly', () => { + render(); + expect(screen.getByText('Click me')).toBeInTheDocument(); + }); + + it('calls onClick when clicked', () => { + const handleClick = jest.fn(); + render(); + fireEvent.click(screen.getByText('Click me')); + expect(handleClick).toHaveBeenCalledTimes(1); + }); +}); +``` + +#### Integration Tests + +```typescript +// API integration test +describe('User API', () => { + it('creates a new user', async () => { + const userData = { + name: 'John Doe', + email: 'john@example.com', + }; + + const response = await request(app) + .post('/api/users') + .send(userData) + .expect(201); + + expect(response.body).toMatchObject({ + id: expect.any(String), + name: 'John Doe', + email: 'john@example.com', + }); + }); +}); +``` + +#### End-to-End Tests + +```typescript +// E2E test with Playwright +import { test, expect } from '@playwright/test'; + +test('user can register and login', async ({ page }) => { + // Navigate to registration page + await page.goto('/register'); + + // Fill registration form + await page.fill('[name="name"]', 'John Doe'); + await page.fill('[name="email"]', 'john@example.com'); + await page.fill('[name="password"]', 'password123'); + await page.click('[type="submit"]'); + + // Should redirect to dashboard + await expect(page).toHaveURL('/dashboard'); + await expect(page.locator('text=Welcome, John Doe')).toBeVisible(); +}); +``` + +### Test Automation + +#### CI/CD Integration + +- **Automated Testing**: Tests run on every PR and push +- **Parallel Testing**: Tests run in parallel for speed +- **Test Coverage**: Coverage reports generated automatically +- **Quality Gates**: Tests must pass before deployment + +## Disaster Recovery + +### Backup Strategy + +#### Database Backups + +- **Automated Backups**: Daily automated backups +- **Point-in-Time Recovery**: Ability to restore to any point +- **Cross-Region Replication**: Backups stored in multiple regions +- **Backup Testing**: Regular backup restoration testing + +#### Application Backups + +- **Code Repository**: Git-based code backup +- **Configuration Backup**: Infrastructure configuration backup +- **Asset Backup**: Static assets and user uploads backup + +### Recovery Procedures + +#### Incident Response + +1. **Detection**: Automated monitoring detects issues +2. **Assessment**: Team assesses impact and scope +3. **Communication**: Stakeholders notified of incident +4. **Recovery**: Systems restored using backup procedures +5. **Post-mortem**: Incident analysis and improvement implementation + +#### Business Continuity + +- **Redundancy**: Multiple availability zones +- **Failover**: Automatic failover to backup systems +- **Scalability**: Ability to scale during high load +- **Communication**: Clear communication during outages + +This monorepo architecture provides a solid foundation for scalable, maintainable, and efficient development across all Monynha Softwares projects. + + \ No newline at end of file diff --git a/docs/contribution/_category_.json b/docs/contribution/_category_.json new file mode 100644 index 0000000..20a345e --- /dev/null +++ b/docs/contribution/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Contribution & Governance", + "position": 6, + "link": { + "type": "generated-index", + "description": "Guidelines for contributing to Monynha Softwares projects and information about project governance and maintenance." + } +} \ No newline at end of file diff --git a/docs/contribution/contributing.md b/docs/contribution/contributing.md new file mode 100644 index 0000000..482e41b --- /dev/null +++ b/docs/contribution/contributing.md @@ -0,0 +1,628 @@ +# Contributing to Monynha Softwares + +This guide outlines how to contribute to Monynha Softwares projects, whether you're a team member, external contributor, or community member. + +## Getting Started + +### Development Environment Setup + +#### Prerequisites + +- **Node.js**: Version 20.x or later +- **Yarn**: Package manager (preferred over npm) +- **Git**: Version control system +- **VS Code**: Recommended code editor with extensions + +#### Environment Setup + +1. **Clone the Repository** + ```bash + git clone https://github.com/monynha-softwares/project-name.git + cd project-name + ``` + +2. **Install Dependencies** + ```bash + yarn install + ``` + +3. **Environment Configuration** + ```bash + cp .env.example .env.local + # Edit .env.local with your configuration + ``` + +4. **Start Development Server** + ```bash + yarn dev + ``` + +### Project Structure + +``` +project/ +├── docs/ # Documentation +├── src/ # Source code +│ ├── components/ # Reusable UI components +│ ├── pages/ # Page components +│ ├── hooks/ # Custom React hooks +│ ├── utils/ # Utility functions +│ └── styles/ # Styling files +├── public/ # Static assets +├── tests/ # Test files +├── .github/ # GitHub configuration +│ ├── workflows/ # CI/CD pipelines +│ └── ISSUE_TEMPLATE/ # Issue templates +├── package.json # Dependencies and scripts +├── tsconfig.json # TypeScript configuration +└── tailwind.config.js # Tailwind CSS configuration +``` + +## Development Workflow + +### Branching Strategy + +#### Branch Naming Convention + +- **Feature Branches**: `feature/description-of-feature` +- **Bug Fixes**: `fix/description-of-bug` +- **Documentation**: `docs/description-of-docs` +- **Hotfixes**: `hotfix/critical-fix-description` + +#### Example Branch Names + +```bash +# Feature development +git checkout -b feature/user-authentication + +# Bug fixes +git checkout -b fix/login-validation-error + +# Documentation updates +git checkout -b docs/api-reference-update + +# Hotfixes +git checkout -b hotfix/security-vulnerability-patch +``` + +### Commit Guidelines + +#### Commit Message Format + +``` +type(scope): description + +[optional body] + +[optional footer] +``` + +#### Commit Types + +- **feat**: New feature +- **fix**: Bug fix +- **docs**: Documentation changes +- **style**: Code style changes (formatting, etc.) +- **refactor**: Code refactoring +- **test**: Adding or updating tests +- **chore**: Maintenance tasks + +#### Commit Examples + +```bash +# Feature commit +git commit -m "feat(auth): add user registration functionality + +- Implement user registration form +- Add email verification +- Create user profile creation" + +# Bug fix commit +git commit -m "fix(login): resolve validation error on login form + +Fixes issue where empty password field was not properly validated. +Added client-side validation for required fields." + +# Documentation commit +git commit -m "docs(api): update authentication endpoint documentation + +- Add missing parameters +- Include response examples +- Update error codes" +``` + +### Pull Request Process + +#### Creating a Pull Request + +1. **Push Your Branch** + ```bash + git push origin feature/your-feature-name + ``` + +2. **Create PR on GitHub** + - Go to the repository on GitHub + - Click "New Pull Request" + - Select your feature branch + - Fill out the PR template + +#### PR Template + +```markdown +## Description +Brief description of the changes made. + +## Type of Change +- [ ] Bug fix (non-breaking change) +- [ ] New feature (non-breaking change) +- [ ] Breaking change +- [ ] Documentation update + +## Checklist +- [ ] My code follows the project's style guidelines +- [ ] I have performed a self-review of my own code +- [ ] I have commented my code, particularly in hard-to-understand areas +- [ ] I have made corresponding changes to the documentation +- [ ] My changes generate no new warnings +- [ ] I have added tests that prove my fix is effective +- [ ] New and existing unit tests pass locally +- [ ] Any dependent changes have been merged and published + +## Screenshots (if applicable) +Add screenshots to help explain your changes. + +## Additional Notes +Any additional information or context. +``` + +#### PR Review Process + +1. **Automated Checks**: CI/CD pipeline runs automatically +2. **Code Review**: At least one team member reviews the code +3. **Testing**: Reviewer tests the changes locally +4. **Approval**: PR is approved or changes are requested +5. **Merge**: Approved PR is merged to main branch + +## Code Standards + +### TypeScript/JavaScript Standards + +#### Code Style + +```typescript +// Good: Clear, readable code +interface User { + readonly id: string; + readonly name: string; + readonly email: string; + readonly createdAt: Date; +} + +class UserService { + constructor(private readonly apiClient: ApiClient) {} + + async getUserProfile(userId: string): Promise { + try { + const response = await this.apiClient.get(`/users/${userId}`); + return this.mapToUserProfile(response.data); + } catch (error) { + throw new UserServiceError('Failed to fetch user profile', error); + } + } + + private mapToUserProfile(data: any): User { + return { + id: data.id, + name: data.name, + email: data.email, + createdAt: new Date(data.created_at), + }; + } +} + +// Bad: Unclear, hard to maintain code +interface usr { + i: string; + n: string; + e: string; + c: Date; +} + +class usr_svc { + private a: any; + + constructor(a: any) { + this.a = a; + } + + async gup(id: string) { + const r = await this.a.get(`/u/${id}`); + return r.d; + } +} +``` + +#### Key Principles + +- **TypeScript First**: Use TypeScript for all new code +- **Strict Mode**: Enable strict TypeScript configuration +- **Interface Segregation**: Use interfaces to define contracts +- **Error Handling**: Proper error handling with custom error types +- **Async/Await**: Prefer async/await over promises + +### React Best Practices + +#### Component Structure + +```tsx +// Good: Clean component structure +interface UserCardProps { + user: User; + onEdit: (user: User) => void; + onDelete: (user: User) => void; +} + +export function UserCard({ user, onEdit, onDelete }: UserCardProps) { + const handleEdit = useCallback(() => { + onEdit(user); + }, [onEdit, user]); + + const handleDelete = useCallback(() => { + onDelete(user); + }, [onDelete, user]); + + return ( + + + {user.name} + {user.email} + + +

{user.bio}

+
+ + + + +
+ ); +} +``` + +#### React Guidelines + +- **Functional Components**: Use functional components with hooks +- **Custom Hooks**: Extract reusable logic into custom hooks +- **Memoization**: Use React.memo, useMemo, and useCallback appropriately +- **Error Boundaries**: Implement error boundaries for error handling +- **Accessibility**: Follow accessibility best practices + +### CSS/Styling Standards + +#### Tailwind CSS + +```tsx +// Good: Consistent Tailwind usage +function UserCard({ user }: UserCardProps) { + return ( +
+
+ {`${user.name} +
+

+ {user.name} +

+

{user.email}

+
+
+

{user.bio}

+
+ ); +} +``` + +#### Styling Guidelines + +- **Utility-First**: Use Tailwind's utility-first approach +- **Responsive Design**: Mobile-first responsive design +- **Consistent Spacing**: Use Tailwind's spacing scale +- **Dark Mode**: Support for dark mode themes +- **Performance**: Optimize CSS for performance + +## Testing Standards + +### Testing Strategy + +#### Test Types + +- **Unit Tests**: Test individual functions and components +- **Integration Tests**: Test component interactions +- **End-to-End Tests**: Test complete user workflows +- **Visual Regression**: Test UI changes with screenshots + +#### Testing Tools + +```typescript +// Component testing with React Testing Library +import { render, screen, fireEvent } from '@testing-library/react'; +import { UserCard } from './UserCard'; + +describe('UserCard', () => { + const mockUser = { + id: '1', + name: 'John Doe', + email: 'john@example.com', + bio: 'Software developer', + }; + + it('renders user information correctly', () => { + render(); + + expect(screen.getByText('John Doe')).toBeInTheDocument(); + expect(screen.getByText('john@example.com')).toBeInTheDocument(); + expect(screen.getByText('Software developer')).toBeInTheDocument(); + }); + + it('calls onEdit when edit button is clicked', () => { + const mockOnEdit = jest.fn(); + render(); + + fireEvent.click(screen.getByText('Edit')); + expect(mockOnEdit).toHaveBeenCalledWith(mockUser); + }); +}); +``` + +### Testing Guidelines + +- **Test Coverage**: Aim for 80%+ code coverage +- **Descriptive Tests**: Write clear, descriptive test names +- **Arrange-Act-Assert**: Follow AAA testing pattern +- **Mock Dependencies**: Mock external dependencies +- **Test Edge Cases**: Test error conditions and edge cases + +## Documentation + +### Code Documentation + +#### JSDoc Comments + +```typescript +/** + * Calculates the total price including tax + * @param {number} price - The base price before tax + * @param {number} taxRate - The tax rate as a decimal (e.g., 0.08 for 8%) + * @returns {number} The total price including tax + * @example + * calculateTotal(100, 0.08) // returns 108 + */ +function calculateTotal(price: number, taxRate: number): number { + return price * (1 + taxRate); +} +``` + +#### TypeScript Types + +```typescript +/** + * Represents a user in the system + */ +interface User { + /** Unique identifier for the user */ + id: string; + /** User's full name */ + name: string; + /** User's email address */ + email: string; + /** When the user account was created */ + createdAt: Date; + /** User's role in the system */ + role: 'admin' | 'user' | 'moderator'; +} +``` + +### Documentation Guidelines + +- **README Files**: Comprehensive project documentation +- **API Documentation**: Document all public APIs +- **Component Documentation**: Document component props and usage +- **Inline Comments**: Explain complex logic, not obvious code +- **Changelog**: Maintain changelog for releases + +## Security Considerations + +### Secure Coding Practices + +#### Input Validation + +```typescript +// Good: Proper input validation +function createUser(userData: CreateUserInput): User { + // Validate required fields + if (!userData.name || userData.name.trim().length === 0) { + throw new ValidationError('Name is required'); + } + + if (!userData.email || !isValidEmail(userData.email)) { + throw new ValidationError('Valid email is required'); + } + + // Sanitize input + const sanitizedName = sanitizeHtml(userData.name); + const sanitizedEmail = userData.email.toLowerCase().trim(); + + // Create user with validated data + return { + id: generateId(), + name: sanitizedName, + email: sanitizedEmail, + createdAt: new Date(), + }; +} +``` + +#### Security Guidelines + +- **Input Sanitization**: Sanitize all user inputs +- **SQL Injection Prevention**: Use parameterized queries +- **XSS Prevention**: Escape output and use CSP headers +- **Authentication**: Secure authentication mechanisms +- **Authorization**: Proper access control checks +- **Secrets Management**: Never commit secrets to version control + +## Performance Optimization + +### Code Performance + +#### Optimization Techniques + +```typescript +// Good: Optimized component with memoization +import React, { memo, useMemo } from 'react'; + +interface UserListProps { + users: User[]; + filter: string; +} + +export const UserList = memo(({ users, filter }) => { + const filteredUsers = useMemo(() => { + return users.filter(user => + user.name.toLowerCase().includes(filter.toLowerCase()) + ); + }, [users, filter]); + + return ( +
+ {filteredUsers.map(user => ( + + ))} +
+ ); +}); +``` + +#### Performance Guidelines + +- **Bundle Splitting**: Split code into smaller chunks +- **Lazy Loading**: Load components and routes lazily +- **Memoization**: Use React.memo, useMemo, and useCallback +- **Virtual Scrolling**: For large lists +- **Image Optimization**: Optimize images for web + +## Issue Tracking + +### Bug Reports + +#### Bug Report Template + +```markdown +## Bug Description +A clear and concise description of the bug. + +## Steps to Reproduce +1. Go to '...' +2. Click on '....' +3. Scroll down to '....' +4. See error + +## Expected Behavior +A clear description of what you expected to happen. + +## Actual Behavior +What actually happened. + +## Screenshots +If applicable, add screenshots to help explain the problem. + +## Environment +- OS: [e.g., Windows 10] +- Browser: [e.g., Chrome 91] +- Version: [e.g., v1.2.3] + +## Additional Context +Any other context about the problem. +``` + +### Feature Requests + +#### Feature Request Template + +```markdown +## Problem Statement +What problem are you trying to solve? + +## Proposed Solution +Describe the solution you'd like to see. + +## Alternative Solutions +Describe any alternative solutions you've considered. + +## Additional Context +Any other context or screenshots about the feature request. + +## Acceptance Criteria +- [ ] Criteria 1 +- [ ] Criteria 2 +- [ ] Criteria 3 +``` + +## Community Guidelines + +### Code of Conduct + +#### Our Standards + +- **Respect**: Treat everyone with respect and kindness +- **Inclusivity**: Welcome people from all backgrounds +- **Collaboration**: Work together constructively +- **Professionalism**: Maintain professional communication +- **Openness**: Be open to different ideas and perspectives + +#### Unacceptable Behavior + +- Harassment or discrimination +- Offensive language or content +- Personal attacks +- Spam or irrelevant content +- Violation of privacy + +### Getting Help + +#### Communication Channels + +- **GitHub Issues**: For bug reports and feature requests +- **GitHub Discussions**: For questions and general discussion +- **Email**: For private matters or sensitive issues +- **Slack/Teams**: For team-internal communication + +#### Response Times + +- **Bug Reports**: Acknowledged within 24 hours +- **Feature Requests**: Reviewed within 1 week +- **Pull Request Reviews**: Reviewed within 2-3 business days +- **General Questions**: Responded to within 48 hours + +## Recognition & Rewards + +### Contribution Recognition + +- **Contributors List**: Recognition in project README +- **GitHub Badges**: Contribution badges on GitHub profile +- **Newsletter**: Feature in company newsletter +- **Events**: Invitation to company events + +### Rewards Program + +- **Bug Bounties**: Rewards for finding and fixing security issues +- **Feature Grants**: Funding for significant feature contributions +- **Hackathons**: Participation in company hackathons +- **Swag**: Company merchandise for contributors + +Thank you for contributing to Monynha Softwares! Your contributions help make our products better for everyone. \ No newline at end of file diff --git a/docs/contribution/governance.md b/docs/contribution/governance.md new file mode 100644 index 0000000..80fb6e1 --- /dev/null +++ b/docs/contribution/governance.md @@ -0,0 +1,368 @@ +# Project Governance + +This document outlines the governance model, decision-making processes, and organizational structure for Monynha Softwares projects. + +## Governance Model + +### Open Governance Principles + +Monynha Softwares follows an open governance model that balances: + +- **Transparency**: Open decision-making and communication +- **Inclusivity**: Participation from diverse contributors +- **Accountability**: Clear responsibilities and accountability +- **Sustainability**: Long-term project health and maintenance +- **Innovation**: Freedom to experiment and innovate + +### Governance Structure + +#### Core Team + +The Core Team consists of experienced contributors who have demonstrated: + +- **Technical Excellence**: Deep understanding of project technologies +- **Community Leadership**: Active participation in community building +- **Reliability**: Consistent, high-quality contributions +- **Mentorship**: Willingness to help and mentor others + +##### Core Team Responsibilities + +- **Technical Direction**: Guide technical decisions and architecture +- **Code Review**: Review and approve significant changes +- **Community Management**: Moderate discussions and resolve conflicts +- **Release Management**: Oversee release process and versioning +- **Security Oversight**: Ensure security standards are maintained + +#### Contributors + +Contributors include anyone who has made a contribution to the project: + +- **Code Contributors**: Developers who submit code changes +- **Documentation Contributors**: Writers who improve documentation +- **Design Contributors**: Designers who contribute to UI/UX +- **Testing Contributors**: Testers who find and report bugs +- **Community Contributors**: Community managers and advocates + +##### Contributor Ladder + +``` +Community Member + ↓ (First contribution) +Contributor + ↓ (Consistent quality contributions) +Active Contributor + ↓ (Leadership and mentorship) +Core Team Member + ↓ (Strategic contributions) +Maintainer +``` + +## Decision-Making Process + +### Consensus-Based Decisions + +#### RFC Process + +For significant changes, we use a Request for Comments (RFC) process: + +1. **Proposal**: Author creates detailed RFC document +2. **Discussion**: Community discusses proposal for 2 weeks +3. **Feedback**: Collect feedback and revise proposal +4. **Voting**: Core team votes on final decision +5. **Implementation**: Approved changes are implemented + +#### RFC Template + +```markdown +# RFC: [Title] + +## Summary +Brief description of the proposed change. + +## Motivation +Why are we doing this? What problem are we solving? + +## Detailed Design +Detailed description of the proposed solution. + +## Alternatives Considered +What other solutions were considered and why were they rejected? + +## Impact +How will this affect existing code, users, and contributors? + +## Implementation Plan +How will this be implemented? What are the steps? + +## Risks +What are the risks and how will they be mitigated? + +## Timeline +Expected timeline for implementation. +``` + +### Voting Process + +#### Voting Rights + +- **Core Team**: Full voting rights on all decisions +- **Active Contributors**: Voting rights on technical decisions +- **Community Members**: Input through comments and discussions + +#### Voting Thresholds + +- **Simple Majority**: For routine decisions +- **Super Majority (2/3)**: For breaking changes +- **Unanimous Consent**: For security-critical changes + +#### Voting Timeline + +- **Discussion Period**: 1-2 weeks for community feedback +- **Voting Period**: 1 week for formal voting +- **Implementation**: 2-4 weeks after approval + +## Project Management + +### Roadmap Planning + +#### Strategic Planning + +- **Vision Setting**: Annual vision and goal setting +- **Roadmap Creation**: Quarterly roadmap planning +- **Milestone Setting**: Monthly milestone definition +- **Progress Tracking**: Weekly progress reviews + +#### Roadmap Categories + +- **Core Features**: Essential functionality +- **Enhancements**: Quality of life improvements +- **Technical Debt**: Infrastructure and maintenance +- **Research**: Experimental features and technologies + +### Release Management + +#### Release Cadence + +- **Major Releases**: 6-12 months, breaking changes allowed +- **Minor Releases**: 1-3 months, new features, backward compatible +- **Patch Releases**: As needed, bug fixes only +- **Pre-releases**: Alpha/beta releases for testing + +#### Release Process + +1. **Feature Freeze**: No new features added +2. **Code Freeze**: Only bug fixes allowed +3. **Testing Phase**: Comprehensive testing and QA +4. **Release Candidate**: Final testing and approval +5. **Release**: Public release and announcement + +### Issue Management + +#### Issue Classification + +- **Bug**: Software defects and errors +- **Feature Request**: New functionality requests +- **Enhancement**: Improvements to existing features +- **Question**: General questions and support +- **Documentation**: Documentation improvements + +#### Issue Lifecycle + +``` +Open → Triaged → Accepted → In Progress → Review → Closed + ↓ ↓ + Duplicate Rejected +``` + +#### Priority Levels + +- **Critical**: System down, security issues, data loss +- **High**: Major functionality broken, urgent user issues +- **Medium**: Important but not urgent issues +- **Low**: Minor issues, nice-to-have improvements + +## Code of Conduct + +### Community Standards + +#### Respect and Inclusion + +- **Inclusive Language**: Use welcoming, inclusive language +- **Respect Differences**: Respect diverse backgrounds and perspectives +- **Professional Communication**: Maintain professional tone +- **Constructive Criticism**: Provide feedback constructively + +#### Unacceptable Behavior + +- **Harassment**: Any form of harassment or discrimination +- **Offensive Content**: Offensive language or content +- **Personal Attacks**: Attacks on individuals or groups +- **Spam**: Irrelevant or repetitive content +- **Privacy Violations**: Sharing private information without consent + +### Enforcement + +#### Reporting Process + +1. **Contact**: Report violations to conduct@monynha.com +2. **Investigation**: Core team investigates reports +3. **Resolution**: Appropriate action taken +4. **Communication**: Outcome communicated to involved parties + +#### Enforcement Actions + +- **Warning**: First offense, formal warning +- **Temporary Ban**: Repeated offenses, temporary suspension +- **Permanent Ban**: Serious violations, permanent removal +- **Legal Action**: Extreme cases, legal action considered + +## Intellectual Property + +### Licensing + +#### Open Source License + +All projects use appropriate open source licenses: + +- **MIT License**: Permissive license for libraries and tools +- **Apache 2.0**: For more complex licensing needs +- **GPL**: For copyleft requirements where appropriate + +#### License Compliance + +- **Dependency Scanning**: Regular scanning of dependencies +- **License Attribution**: Proper attribution in distributed code +- **License Compatibility**: Ensure license compatibility +- **Legal Review**: Legal review for licensing questions + +### Copyright and Trademarks + +#### Copyright Policy + +- **Copyright Notice**: Include copyright notices in source files +- **Copyright Assignment**: Contributors retain copyright unless assigned +- **Fair Use**: Respect fair use guidelines for third-party content +- **DMCA Compliance**: Respond to DMCA takedown requests + +#### Trademark Usage + +- **Brand Guidelines**: Follow established brand guidelines +- **Trademark Notice**: Use ® and ™ symbols appropriately +- **Domain Names**: Protect project domain names +- **Social Media**: Consistent branding across platforms + +## Financial Management + +### Funding Model + +#### Revenue Streams + +- **Commercial Products**: Revenue from commercial software +- **Services**: Consulting and development services +- **Support**: Premium support and training +- **Donations**: Community donations and sponsorships + +#### Budget Allocation + +- **Development**: 60% for core development +- **Operations**: 20% for infrastructure and operations +- **Marketing**: 10% for marketing and community +- **Legal**: 5% for legal and administrative +- **Reserve**: 5% for emergencies and opportunities + +### Sponsorship Program + +#### Sponsor Tiers + +- **Bronze**: $100/month - Logo on website +- **Silver**: $500/month - Logo + social media mention +- **Gold**: $1000/month - Logo + blog post + newsletter feature +- **Platinum**: $5000/month - Logo + dedicated page + strategic input + +#### Sponsor Benefits + +- **Recognition**: Public recognition of sponsorship +- **Input**: Input into roadmap and priorities +- **Early Access**: Early access to new features +- **Support**: Priority support and response times + +## Conflict Resolution + +### Dispute Resolution + +#### Internal Disputes + +1. **Direct Communication**: Attempt to resolve directly +2. **Mediation**: Involve neutral third party +3. **Core Team Review**: Escalate to core team +4. **Final Decision**: Core team makes binding decision + +#### Community Disputes + +1. **Moderation**: Community moderators intervene +2. **Temporary Measures**: Temporary restrictions if needed +3. **Investigation**: Thorough investigation of incident +4. **Resolution**: Appropriate resolution and communication + +### Appeals Process + +#### Appeal Rights + +- **Appeal Period**: 30 days to appeal decisions +- **Appeal Process**: Submit appeal to governance committee +- **Review**: Independent review of original decision +- **Final Resolution**: Final binding decision + +## Metrics and Reporting + +### Project Metrics + +#### Development Metrics + +- **Code Quality**: Test coverage, linting compliance, complexity +- **Velocity**: Story points completed per sprint +- **Reliability**: Uptime, error rates, performance +- **Security**: Vulnerability count, response time + +#### Community Metrics + +- **Contributors**: Number of active contributors +- **Engagement**: Issue resolution time, PR review time +- **Satisfaction**: Contributor and user satisfaction surveys +- **Growth**: Community size and engagement trends + +### Reporting Schedule + +#### Regular Reports + +- **Weekly**: Development progress and blockers +- **Monthly**: Project status and metrics +- **Quarterly**: Strategic review and planning +- **Annually**: Comprehensive annual report + +#### Report Distribution + +- **Internal**: Core team and stakeholders +- **Community**: Public project updates +- **Investors**: Financial and strategic reports +- **Public**: Blog posts and newsletters + +## Evolution of Governance + +### Governance Review + +#### Annual Review + +- **Effectiveness Assessment**: Evaluate governance effectiveness +- **Community Feedback**: Gather community input on governance +- **Process Improvements**: Identify areas for improvement +- **Updates**: Implement governance updates as needed + +#### Adaptation + +- **Scale**: Adapt governance as project scales +- **Technology**: Incorporate new tools and processes +- **Best Practices**: Adopt industry best practices +- **Innovation**: Experiment with new governance approaches + +This governance model ensures that Monynha Softwares projects are managed transparently, inclusively, and sustainably, with clear processes for decision-making and conflict resolution. \ No newline at end of file diff --git a/docs/guidelines/_category_.json b/docs/guidelines/_category_.json new file mode 100644 index 0000000..cd2cf09 --- /dev/null +++ b/docs/guidelines/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Guidelines & Standards", + "position": 4, + "link": { + "type": "generated-index", + "description": "Unified guidelines ensuring quality and consistency across all Monynha Softwares projects, covering UX, accessibility, code conventions, and security." + } +} \ No newline at end of file diff --git a/docs/guidelines/accessibility.md b/docs/guidelines/accessibility.md new file mode 100644 index 0000000..f9886b6 --- /dev/null +++ b/docs/guidelines/accessibility.md @@ -0,0 +1,318 @@ +# 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 diff --git a/docs/guidelines/code-conventions.md b/docs/guidelines/code-conventions.md new file mode 100644 index 0000000..22994da --- /dev/null +++ b/docs/guidelines/code-conventions.md @@ -0,0 +1,574 @@ +# Code Conventions & Standards + +This document outlines the coding standards, conventions, and best practices followed by Monynha Softwares across all development projects. + +## General Principles + +### Code Quality + +#### Readability + +- **Self-Documenting Code**: Code should be readable without extensive comments +- **Consistent Naming**: Use clear, descriptive, and consistent naming conventions +- **Logical Structure**: Organize code in a logical and predictable manner +- **Meaningful Comments**: Use comments to explain complex logic, not obvious code + +#### Maintainability + +- **Modular Design**: Break down complex systems into manageable, reusable modules +- **Single Responsibility**: Each function, class, or module should have one clear purpose +- **DRY Principle**: Don't Repeat Yourself - eliminate code duplication +- **SOLID Principles**: Follow SOLID object-oriented design principles + +#### Performance + +- **Efficient Algorithms**: Use appropriate data structures and algorithms +- **Resource Management**: Properly manage memory, connections, and other resources +- **Lazy Loading**: Load resources only when needed +- **Caching Strategy**: Implement appropriate caching mechanisms + +### Code Organization + +#### File Structure + +- **Logical Grouping**: Group related files and functionality together +- **Consistent Naming**: Use consistent file and directory naming conventions +- **Separation of Concerns**: Separate business logic, presentation, and data layers +- **Configuration Management**: Keep configuration separate from code + +#### Project Structure + +- **Scalable Architecture**: Design for growth and scalability +- **Dependency Management**: Clear dependency relationships and versions +- **Build Process**: Automated, reproducible build processes +- **Deployment Ready**: Code ready for deployment at any time + +## Language-Specific Standards + +### TypeScript/JavaScript + +#### Code Style + +```typescript +// Good: Clear naming and structure +interface UserProfile { + readonly id: string; + readonly name: string; + readonly email: string; + readonly createdAt: Date; +} + +class UserService { + private readonly apiClient: ApiClient; + + constructor(apiClient: ApiClient) { + this.apiClient = apiClient; + } + + async getUserProfile(userId: string): Promise { + try { + const response = await this.apiClient.get(`/users/${userId}`); + return this.mapToUserProfile(response.data); + } catch (error) { + throw new UserServiceError('Failed to fetch user profile', error); + } + } + + private mapToUserProfile(data: any): UserProfile { + return { + id: data.id, + name: data.name, + email: data.email, + createdAt: new Date(data.created_at), + }; + } +} + +// Bad: Unclear naming and poor structure +interface usr { + i: string; + n: string; + e: string; + c: Date; +} + +class usrSvc { + private a: any; + + constructor(a: any) { + this.a = a; + } + + async gup(id: string) { + const r = await this.a.get(`/u/${id}`); + return r.d; + } +} +``` + +#### TypeScript Best Practices + +- **Strict Mode**: Always use strict TypeScript configuration +- **Type Definitions**: Define types for all data structures and function parameters +- **Interface Segregation**: Use interfaces to define contracts clearly +- **Generic Types**: Use generics for reusable, type-safe code +- **Type Guards**: Implement proper type guards for runtime type checking + +#### JavaScript Standards + +- **ES6+ Features**: Use modern JavaScript features appropriately +- **Async/Await**: Prefer async/await over promises for asynchronous code +- **Destructuring**: Use destructuring for cleaner, more readable code +- **Template Literals**: Use template literals instead of string concatenation +- **Arrow Functions**: Use arrow functions for concise function expressions + +### Python + +#### Code Style (PEP 8) + +```python +# Good: PEP 8 compliant +from typing import List, Optional +import requests + +class UserService: + """Service for managing user operations.""" + + def __init__(self, api_base_url: str) -> None: + self.api_base_url = api_base_url + self.session = requests.Session() + + def get_user_profile(self, user_id: str) -> Optional[dict]: + """ + Retrieve user profile by ID. + + Args: + user_id: The unique identifier of the user + + Returns: + User profile data or None if not found + + Raises: + requests.RequestException: If API request fails + """ + try: + response = self.session.get(f"{self.api_base_url}/users/{user_id}") + response.raise_for_status() + return response.json() + except requests.RequestException as e: + logger.error(f"Failed to fetch user profile for {user_id}: {e}") + return None + +# Bad: Poor style and practices +from typing import * +import requests as req + +class usr_svc: + def __init__(self,url): + self.url=url + self.sess=req.Session() + + def get_usr(self,id): + r=self.sess.get(f"{self.url}/u/{id}") + return r.json() +``` + +#### Python Best Practices + +- **Type Hints**: Use type hints for better code documentation and IDE support +- **Docstrings**: Write comprehensive docstrings for all public functions and classes +- **Exception Handling**: Proper exception handling with specific exception types +- **Context Managers**: Use context managers for resource management +- **List Comprehensions**: Use list comprehensions for concise, readable code + +### Dart/Flutter + +#### Flutter Code Style + +```dart +// Good: Flutter best practices +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class UserProfileScreen extends StatelessWidget { + const UserProfileScreen({super.key}); + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: const Text('User Profile'), + ), + body: Consumer( + builder: (context, userProvider, child) { + if (userProvider.isLoading) { + return const Center(child: CircularProgressIndicator()); + } + + if (userProvider.error != null) { + return Center( + child: Text('Error: ${userProvider.error}'), + ); + } + + final user = userProvider.user; + if (user == null) { + return const Center(child: Text('No user data')); + } + + return Padding( + padding: const EdgeInsets.all(16.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'Name: ${user.name}', + style: Theme.of(context).textTheme.headlineSmall, + ), + const SizedBox(height: 8), + Text( + 'Email: ${user.email}', + style: Theme.of(context).textTheme.bodyLarge, + ), + const SizedBox(height: 16), + ElevatedButton( + onPressed: () => _editProfile(context), + child: const Text('Edit Profile'), + ), + ], + ), + ); + }, + ), + ); + } + + void _editProfile(BuildContext context) { + Navigator.of(context).pushNamed('/edit-profile'); + } +} + +// Bad: Poor Flutter practices +import 'package:flutter/material.dart'; + +class usr_scr extends StatelessWidget { + @override + Widget build(ctx) { + return Scaffold( + body: Column( + children: [ + Text("Name: " + user.name), + Text("Email: " + user.email), + FlatButton( // Deprecated widget + onPressed: () => navToEdit(), + child: Text("Edit"), + ), + ], + ), + ); + } +} +``` + +#### Flutter Best Practices + +- **Widget Composition**: Build complex UIs through widget composition +- **State Management**: Use appropriate state management solutions (Provider, Riverpod, Bloc) +- **Performance**: Use const constructors and avoid unnecessary rebuilds +- **Accessibility**: Implement proper semantics and accessibility features +- **Testing**: Write comprehensive widget and integration tests + +## Development Workflow + +### Version Control + +#### Git Standards + +- **Commit Messages**: Write clear, descriptive commit messages +- **Branch Naming**: Use consistent branch naming conventions +- **Pull Requests**: Create focused, well-documented pull requests +- **Code Reviews**: Conduct thorough, constructive code reviews + +#### Commit Message Format + +```text +type(scope): description + +[optional body] + +[optional footer] +``` + +Types: feat, fix, docs, style, refactor, test, chore + +### Code Reviews + +#### Review Process + +- **Automated Checks**: Pass all automated tests and linting before review +- **Self-Review**: Review your own code before requesting review +- **Pair Review**: Have at least one other developer review the code +- **Approval Requirements**: Require approval from relevant team members + +#### Review Guidelines + +- **Constructive Feedback**: Provide specific, actionable feedback +- **Knowledge Sharing**: Explain reasoning and share best practices +- **Respect**: Maintain respectful and professional communication +- **Continuous Learning**: Learn from each code review experience + +### Testing Standards + +#### Test Coverage + +- **Unit Tests**: Test individual functions and classes in isolation +- **Integration Tests**: Test interactions between components +- **End-to-End Tests**: Test complete user workflows +- **Coverage Goals**: Maintain high test coverage (80%+) + +#### Test Quality + +- **Descriptive Names**: Use clear, descriptive test names +- **Arrange-Act-Assert**: Follow the AAA testing pattern +- **Edge Cases**: Test edge cases and error conditions +- **Mocking**: Use appropriate mocking for external dependencies + +## Tooling & Automation + +### Linting & Formatting + +#### ESLint (JavaScript/TypeScript) + +```javascript +// .eslintrc.js +module.exports = { + extends: [ + 'eslint:recommended', + '@typescript-eslint/recommended', + 'prettier', + ], + rules: { + // Custom rules + '@typescript-eslint/no-unused-vars': 'error', + '@typescript-eslint/explicit-function-return-type': 'warn', + }, +}; +``` + +#### Prettier + +```javascript +// .prettierrc +{ + "semi": true, + "trailingComma": "es5", + "singleQuote": true, + "printWidth": 80, + "tabWidth": 2, + "useTabs": false +} +``` + +#### Black (Python) + +```python +# pyproject.toml +[tool.black] +line-length = 88 +target-version = ['py38', 'py39', 'py310'] +include = '\.pyi?$' +extend-exclude = ''' +/( + \.eggs + | \.git + | \.hg + | \.mypy_cache + | \.tox + | \.venv + | _build + | buck-out + | build + | dist +)/ +''' +``` + +### Continuous Integration + +#### GitHub Actions + +```yaml +name: CI +on: + push: + branches: [main, develop] + pull_request: + branches: [main, develop] + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: '20' + cache: 'yarn' + - name: Install dependencies + run: yarn install --frozen-lockfile + - name: Run linting + run: yarn lint + - name: Run tests + run: yarn test:coverage + - name: Build + run: yarn build +``` + +#### Quality Gates + +- **Linting**: All code must pass linting checks +- **Tests**: All tests must pass with required coverage +- **Build**: Code must build successfully +- **Security**: Automated security scanning must pass + +## Documentation Standards + +### Code Documentation + +#### Inline Comments + +- **When to Comment**: Explain why, not what (code should be self-explanatory) +- **TODO Comments**: Use TODO comments for future improvements +- **FIXME Comments**: Use FIXME for known issues that need fixing +- **Comment Style**: Use consistent comment formatting + +#### API Documentation + +- **OpenAPI/Swagger**: Document REST APIs with OpenAPI specifications +- **TypeScript Declarations**: Provide type definitions for libraries +- **README Files**: Comprehensive project documentation +- **Changelog**: Maintain changelog for version releases + +### Project Documentation + +#### README Structure + +- **Project Description**: Clear description of what the project does +- **Installation**: Step-by-step installation instructions +- **Usage**: Basic usage examples and API reference +- **Contributing**: Guidelines for contributing to the project +- **License**: Project license information + +#### Architecture Documentation + +- **System Overview**: High-level system architecture +- **Component Diagrams**: Visual representation of system components +- **Data Flow**: Data flow diagrams and database schemas +- **Deployment**: Deployment architecture and processes + +## Security Standards + +### Secure Coding Practices + +#### Input Validation + +- **Sanitize Input**: Always validate and sanitize user input +- **Parameter Binding**: Use parameterized queries to prevent SQL injection +- **XSS Prevention**: Escape output to prevent cross-site scripting +- **CSRF Protection**: Implement CSRF tokens for state-changing operations + +#### Authentication & Authorization + +- **Secure Passwords**: Use strong password hashing (bcrypt, Argon2) +- **JWT Best Practices**: Proper JWT token handling and validation +- **Session Management**: Secure session handling and timeout +- **Role-Based Access**: Implement proper authorization checks + +### Security Tools + +#### Dependency Scanning + +- **Vulnerability Checks**: Regular dependency vulnerability scanning +- **License Compliance**: Ensure dependency licenses are acceptable +- **Update Management**: Keep dependencies updated and secure +- **Audit Reports**: Regular security audits and penetration testing + +#### Code Security + +- **Static Analysis**: Use security-focused static analysis tools +- **Secrets Management**: Never commit secrets to version control +- **Environment Variables**: Use environment variables for configuration +- **Logging**: Implement secure logging practices + +## Performance Standards + +### Code Performance + +#### Optimization Techniques + +- **Algorithm Complexity**: Choose appropriate algorithms (O(n) considerations) +- **Memory Management**: Avoid memory leaks and optimize memory usage +- **Database Queries**: Optimize database queries and use appropriate indexes +- **Caching**: Implement caching strategies for performance improvement + +#### Monitoring + +- **Performance Metrics**: Monitor application performance metrics +- **Bottleneck Identification**: Identify and resolve performance bottlenecks +- **Load Testing**: Regular load testing to ensure scalability +- **Profiling**: Use profiling tools to identify performance issues + +### Frontend Performance + +#### Web Performance + +- **Bundle Size**: Keep JavaScript bundles small and optimized +- **Image Optimization**: Optimize images for web delivery +- **Lazy Loading**: Implement lazy loading for non-critical resources +- **CDN Usage**: Use CDNs for static asset delivery + +#### Mobile Performance + +- **App Size**: Minimize application bundle size +- **Battery Usage**: Optimize for battery life +- **Memory Usage**: Efficient memory management +- **Network Usage**: Minimize network requests and data usage + +## Error Handling & Logging + +### Error Handling + +#### Exception Management + +- **Specific Exceptions**: Use specific exception types, not generic ones +- **Error Messages**: Provide clear, actionable error messages +- **Graceful Degradation**: Handle errors gracefully without crashing +- **Recovery**: Implement recovery mechanisms where possible + +#### Logging Standards + +- **Log Levels**: Use appropriate log levels (DEBUG, INFO, WARN, ERROR) +- **Structured Logging**: Use structured logging for better searchability +- **Sensitive Data**: Never log sensitive information +- **Performance**: Logging should not impact application performance + +### Monitoring & Alerting + +#### Application Monitoring + +- **Health Checks**: Implement application health check endpoints +- **Metrics Collection**: Collect relevant application metrics +- **Error Tracking**: Use error tracking services (Sentry, etc.) +- **Performance Monitoring**: Monitor application performance + +#### Alerting + +- **Alert Thresholds**: Set appropriate alerting thresholds +- **Escalation**: Implement alert escalation procedures +- **On-call Rotation**: Establish on-call rotation for critical alerts +- **Incident Response**: Define incident response procedures + +These coding standards and conventions ensure that all Monynha Softwares projects maintain high quality, consistency, and maintainability across the entire codebase. + + \ No newline at end of file diff --git a/docs/guidelines/security.md b/docs/guidelines/security.md new file mode 100644 index 0000000..bca62b7 --- /dev/null +++ b/docs/guidelines/security.md @@ -0,0 +1,388 @@ +# Security Guidelines + +This document outlines the security standards, practices, and procedures followed by Monynha Softwares to protect our systems, data, and users. + +## Security Principles + +### Defense in Depth + +Our security approach implements multiple layers of protection: + +- **Perimeter Security**: Network-level protection and access controls +- **Application Security**: Secure coding practices and input validation +- **Data Protection**: Encryption and access controls for sensitive data +- **Monitoring**: Continuous monitoring and threat detection +- **Incident Response**: Prepared response to security incidents + +### Zero Trust Architecture + +- **Never Trust, Always Verify**: Every access request is authenticated and authorized +- **Least Privilege**: Users and systems have minimum required permissions +- **Micro-Segmentation**: Network segmentation to limit breach impact +- **Continuous Monitoring**: Ongoing verification of security posture + +### Security by Design + +- **Secure Development Lifecycle**: Security integrated into all development phases +- **Threat Modeling**: Proactive identification and mitigation of threats +- **Risk Assessment**: Regular evaluation of security risks and controls +- **Compliance**: Adherence to relevant security standards and regulations + +## Authentication & Authorization + +### Authentication Standards + +#### Password Policies + +- **Complexity Requirements**: Minimum 12 characters with mixed case, numbers, and symbols +- **Password History**: Prevent reuse of previous passwords +- **Account Lockout**: Temporary lockout after failed attempts +- **Password Reset**: Secure password reset process with identity verification + +#### Multi-Factor Authentication (MFA) + +- **Required for Privileged Accounts**: MFA mandatory for admin and sensitive accounts +- **Multiple Methods**: Support for TOTP, SMS, email, and hardware tokens +- **Backup Codes**: Emergency access codes for MFA recovery +- **MFA Fatigue Protection**: Protection against MFA bombing attacks + +#### Session Management + +- **Session Timeout**: Automatic logout after period of inactivity +- **Secure Cookies**: HttpOnly, Secure, and SameSite cookie attributes +- **Session Invalidation**: Immediate invalidation on logout or suspicious activity +- **Concurrent Session Limits**: Restrictions on simultaneous sessions + +### Authorization Controls + +#### Role-Based Access Control (RBAC) + +- **Role Definition**: Clear definition of roles and associated permissions +- **Principle of Least Privilege**: Minimum permissions required for job functions +- **Role Separation**: Separation of duties to prevent conflicts of interest +- **Regular Review**: Periodic review and update of role assignments + +#### Attribute-Based Access Control (ABAC) + +- **Dynamic Authorization**: Access decisions based on multiple attributes +- **Context-Aware**: Consideration of time, location, and device factors +- **Fine-Grained Control**: Granular permissions for specific resources +- **Policy Management**: Centralized policy definition and enforcement + +## Data Protection + +### Encryption Standards + +#### Data at Rest + +- **Database Encryption**: Transparent database encryption for sensitive data +- **File Encryption**: Encryption of sensitive files and backups +- **Key Management**: Secure key generation, storage, and rotation +- **Hardware Security Modules**: Use of HSMs for critical key operations + +#### Data in Transit + +- **TLS 1.3**: Minimum TLS version for all communications +- **Certificate Management**: Automated certificate renewal and validation +- **Perfect Forward Secrecy**: PFS for all encrypted connections +- **Protocol Security**: Secure protocols (HTTPS, SFTP, etc.) + +### Data Classification + +#### Classification Levels + +- **Public**: Information that can be freely disclosed +- **Internal**: Information for internal use only +- **Confidential**: Sensitive information requiring protection +- **Restricted**: Highly sensitive information with strict access controls + +#### Handling Procedures + +- **Labeling**: Clear labeling of data classification levels +- **Storage Requirements**: Appropriate storage based on classification +- **Access Controls**: Classification-based access restrictions +- **Retention Policies**: Defined retention periods for different data types + +## Secure Development Practices + +### Input Validation & Sanitization + +#### Input Validation + +- **Whitelist Approach**: Accept only known good input patterns +- **Type Checking**: Strict type validation for all inputs +- **Length Limits**: Reasonable limits on input field lengths +- **Format Validation**: Proper validation of email, phone, and other formats + +#### Output Encoding + +- **Context-Aware Encoding**: Appropriate encoding for different output contexts +- **XSS Prevention**: HTML encoding for web output +- **SQL Injection Prevention**: Parameterized queries and prepared statements +- **Command Injection Prevention**: Input sanitization for system commands + +### Secure Coding Standards + +#### Common Vulnerabilities + +- **Injection Attacks**: Prevention of SQL, NoSQL, and command injection +- **Broken Authentication**: Secure session management and authentication +- **Sensitive Data Exposure**: Proper encryption and access controls +- **XML External Entities**: Disable XXE processing in XML parsers +- **Broken Access Control**: Proper authorization checks +- **Security Misconfiguration**: Secure default configurations +- **Cross-Site Scripting**: Input validation and output encoding +- **Insecure Deserialization**: Safe deserialization practices +- **Vulnerable Components**: Regular dependency updates and vulnerability scanning +- **Insufficient Logging**: Comprehensive security event logging + +#### Code Review Security + +- **Security Checklists**: Automated and manual security code reviews +- **Static Analysis**: Automated vulnerability detection in code +- **Dependency Scanning**: Regular scanning of third-party dependencies +- **Peer Review**: Security-focused code review process + +## Infrastructure Security + +### Network Security + +#### Network Segmentation + +- **DMZ**: Demilitarized zone for public-facing services +- **Internal Networks**: Segregation of internal network zones +- **Micro-Segmentation**: Application-level network isolation +- **Zero Trust Networking**: Identity-based network access + +#### Firewall Configuration + +- **Default Deny**: Default deny policy for all traffic +- **Rule Management**: Regular review and cleanup of firewall rules +- **Intrusion Prevention**: IPS/IDS for threat detection +- **Logging**: Comprehensive firewall logging and monitoring + +### Cloud Security + +#### Cloud Configuration + +- **Secure Defaults**: Use of secure cloud service configurations +- **Access Management**: Proper IAM configuration and least privilege +- **Encryption**: Encryption of data at rest and in transit +- **Monitoring**: Cloud security monitoring and alerting + +#### Container Security + +- **Image Scanning**: Vulnerability scanning of container images +- **Runtime Security**: Container runtime protection and monitoring +- **Secrets Management**: Secure handling of sensitive configuration +- **Network Policies**: Container network segmentation and policies + +## Application Security + +### API Security + +#### REST API Security + +- **Authentication**: Proper API authentication mechanisms +- **Authorization**: API-level access control and rate limiting +- **Input Validation**: Comprehensive API input validation +- **Error Handling**: Secure error messages without information disclosure + +#### GraphQL Security + +- **Query Complexity**: Protection against complex query attacks +- **Introspection**: Controlled access to schema introspection +- **Rate Limiting**: API rate limiting and abuse prevention +- **Authentication**: Proper authentication for GraphQL operations + +### Web Application Security + +#### Content Security Policy (CSP) + +- **Strict CSP**: Implementation of strict content security policies +- **Nonce Usage**: Use of nonces for inline script authorization +- **Report-Only Mode**: Testing CSP changes in report-only mode +- **Violation Monitoring**: Monitoring and responding to CSP violations + +#### Cross-Origin Resource Sharing (CORS) + +- **Minimal Origins**: Restrict allowed origins to necessary domains +- **Credentials**: Careful handling of credentials in CORS requests +- **Preflight Requests**: Proper handling of CORS preflight requests +- **Security Headers**: Implementation of security-related HTTP headers + +## Monitoring & Incident Response + +### Security Monitoring + +#### Log Management + +- **Centralized Logging**: Aggregation of logs from all systems +- **Log Retention**: Appropriate retention periods for security logs +- **Log Analysis**: Automated analysis of security events +- **Integrity**: Protection of log integrity and availability + +#### Intrusion Detection + +- **Network IDS**: Network-based intrusion detection systems +- **Host IDS**: Host-based intrusion detection and prevention +- **Behavioral Analysis**: Detection of anomalous behavior +- **Threat Intelligence**: Integration of threat intelligence feeds + +### Incident Response + +#### Incident Response Plan + +- **Preparation**: Defined roles, responsibilities, and communication plans +- **Identification**: Processes for detecting and assessing security incidents +- **Containment**: Strategies for containing incident impact +- **Eradication**: Methods for removing threats and vulnerabilities +- **Recovery**: Procedures for restoring systems and services +- **Lessons Learned**: Post-incident analysis and improvement + +#### Incident Communication + +- **Internal Communication**: Clear communication within the organization +- **External Communication**: Appropriate communication with external parties +- **Regulatory Reporting**: Compliance with breach notification requirements +- **Stakeholder Management**: Managing communication with affected parties + +## Compliance & Auditing + +### Regulatory Compliance + +#### GDPR Compliance + +- **Data Protection**: Protection of personal data and privacy rights +- **Consent Management**: Proper consent collection and management +- **Data Subject Rights**: Implementation of data subject access rights +- **Breach Notification**: Timely notification of data breaches + +#### Industry Standards + +- **ISO 27001**: Information security management systems +- **SOC 2**: Trust services criteria for service organizations +- **PCI DSS**: Payment card industry data security standards +- **HIPAA**: Health information privacy and security + +### Security Auditing + +#### Internal Audits + +- **Regular Assessments**: Periodic security assessments and audits +- **Control Testing**: Testing of security controls effectiveness +- **Gap Analysis**: Identification of security gaps and weaknesses +- **Remediation**: Tracking and verification of remediation actions + +#### External Audits + +- **Third-Party Audits**: Independent security assessments +- **Penetration Testing**: Ethical hacking and vulnerability assessments +- **Compliance Audits**: Verification of regulatory compliance +- **Certification**: Achievement and maintenance of security certifications + +## Security Training & Awareness + +### Employee Training + +#### Security Awareness + +- **Regular Training**: Ongoing security awareness training for all employees +- **Phishing Awareness**: Training on recognizing and reporting phishing attempts +- **Password Security**: Education on password best practices +- **Social Engineering**: Awareness of social engineering tactics + +#### Role-Specific Training + +- **Developer Security**: Secure coding training for developers +- **Administrator Training**: System administration security training +- **Executive Training**: Security awareness for management +- **Specialized Training**: Domain-specific security training + +### Security Culture + +#### Communication + +- **Security Newsletters**: Regular security updates and reminders +- **Incident Sharing**: Sharing lessons learned from security incidents +- **Best Practices**: Promotion of security best practices +- **Recognition**: Recognition of security-conscious behavior + +#### Continuous Improvement + +- **Feedback Mechanisms**: Channels for reporting security concerns +- **Suggestion Programs**: Programs for security improvement suggestions +- **Metrics Tracking**: Monitoring of security awareness metrics +- **Culture Assessment**: Regular assessment of security culture + +## Third-Party Risk Management + +### Vendor Assessment + +#### Due Diligence + +- **Security Questionnaires**: Assessment of vendor security practices +- **References**: Checking vendor references and past performance +- **Certifications**: Verification of security certifications and compliance +- **Contractual Requirements**: Security requirements in vendor contracts + +#### Ongoing Monitoring + +- **Performance Monitoring**: Monitoring of vendor security performance +- **Contract Compliance**: Regular verification of contractual obligations +- **Incident Reporting**: Monitoring vendor security incidents +- **Relationship Management**: Ongoing management of vendor relationships + +### Supply Chain Security + +#### Dependency Management + +- **Vulnerability Scanning**: Regular scanning of third-party dependencies +- **Update Management**: Timely application of security updates +- **License Compliance**: Verification of open source license compliance +- **Alternative Sources**: Identification of alternative suppliers + +#### Software Bill of Materials (SBOM) + +- **SBOM Generation**: Creation of software bill of materials +- **Vulnerability Tracking**: Tracking vulnerabilities in software components +- **Transparency**: Sharing SBOM with customers when required +- **Automation**: Automated SBOM generation and updates + +## Security Tools & Technologies + +### Security Tooling + +#### Vulnerability Management + +- **Automated Scanning**: Continuous vulnerability scanning +- **Risk Prioritization**: Prioritization of vulnerabilities by risk +- **Remediation Tracking**: Tracking of vulnerability remediation +- **Compliance Reporting**: Vulnerability management reporting + +#### Security Information and Event Management (SIEM) + +- **Log Aggregation**: Centralized collection of security events +- **Correlation Analysis**: Analysis of related security events +- **Alert Generation**: Automated generation of security alerts +- **Incident Investigation**: Tools for security incident investigation + +### Emerging Technologies + +#### Zero Trust Tools + +- **Identity Governance**: Tools for identity and access management +- **Network Access Control**: Zero trust network access solutions +- **Endpoint Protection**: Advanced endpoint protection platforms +- **Secure Access Service Edge**: SASE security implementations + +#### AI/ML Security + +- **Threat Detection**: AI-powered threat detection and response +- **Anomaly Detection**: Machine learning for anomaly identification +- **Automated Response**: Automated incident response capabilities +- **Predictive Analytics**: Predictive security analytics and forecasting + +This comprehensive security framework ensures that Monynha Softwares maintains the highest standards of security across all systems, processes, and personnel, protecting our organization, customers, and partners from security threats. + + \ No newline at end of file diff --git a/docs/guidelines/ux-guidelines.md b/docs/guidelines/ux-guidelines.md new file mode 100644 index 0000000..ba1f81d --- /dev/null +++ b/docs/guidelines/ux-guidelines.md @@ -0,0 +1,245 @@ +# UX Guidelines + +This document outlines the user experience principles and guidelines followed by Monynha Softwares across all digital products. + +## Design Philosophy + +### User-Centered Design + +Our design approach prioritizes user needs and experiences above all else: + +- **Empathy First**: Understanding user pain points and motivations +- **Inclusive Design**: Accessibility and usability for diverse user groups +- **Iterative Process**: Continuous improvement based on user feedback +- **Data-Driven Decisions**: User research and analytics inform design choices + +### Core Principles + +#### Simplicity + +- **Clarity Over Complexity**: Simple, intuitive interfaces that users understand immediately +- **Progressive Disclosure**: Information revealed gradually to avoid overwhelming users +- **Minimalist Aesthetics**: Clean, uncluttered designs focusing on essential elements + +#### Consistency + +- **Visual Consistency**: Unified design language across all products +- **Interaction Patterns**: Predictable behaviors and familiar interaction models +- **Brand Alignment**: Consistent representation of Monynha's brand identity + +#### Accessibility + +- **WCAG 2.1 AA Compliance**: Meeting international accessibility standards +- **Inclusive Design**: Considering users with diverse abilities and needs +- **Universal Usability**: Designs that work for everyone, regardless of context + +## User Research & Testing + +### Research Methods + +#### Qualitative Research + +- **User Interviews**: In-depth conversations to understand user needs and behaviors +- **Usability Testing**: Observing users interact with prototypes and products +- **Contextual Inquiry**: Studying users in their natural environment +- **Diary Studies**: Long-term tracking of user experiences and pain points + +#### Quantitative Research + +- **Analytics Review**: Analyzing user behavior data and conversion metrics +- **A/B Testing**: Comparing design variations to determine optimal solutions +- **Surveys**: Gathering feedback from large user groups +- **Heat Maps**: Visualizing user interaction patterns + +### Testing Protocols + +- **Test Planning**: Clear objectives and success criteria for each test +- **Participant Recruitment**: Diverse user groups representing target audiences +- **Test Execution**: Structured testing sessions with observation and note-taking +- **Findings Analysis**: Identifying patterns and actionable insights +- **Iteration Planning**: Translating findings into design improvements + +## Information Architecture + +### Content Organization + +#### Hierarchy & Structure + +- **Clear Information Hierarchy**: Logical organization of content and features +- **Card Sorting**: User-driven content categorization and labeling +- **Content Inventory**: Comprehensive cataloging of all content elements +- **User Flow Mapping**: Visualization of user journeys through the product + +#### Navigation Design + +- **Intuitive Navigation**: Easy-to-understand navigation patterns +- **Search Functionality**: Powerful search capabilities for content discovery +- **Breadcrumb Navigation**: Clear indication of user's current location +- **Progressive Disclosure**: Layered information presentation + +### Content Strategy + +- **Content Audit**: Regular review and optimization of content +- **User-Centric Copy**: Clear, concise, and user-friendly language +- **Multilingual Support**: Content adaptation for different languages and cultures +- **Content Governance**: Guidelines for content creation and maintenance + +## Interaction Design + +### Interface Patterns + +#### Form Design + +- **Progressive Forms**: Multi-step forms to reduce cognitive load +- **Smart Defaults**: Intelligent default values based on user context +- **Inline Validation**: Real-time feedback on form input +- **Error Prevention**: Design patterns that prevent user errors + +#### Feedback & Communication + +- **Loading States**: Clear indication of system status and progress +- **Success/Error Messages**: Informative feedback for user actions +- **Micro-interactions**: Subtle animations and feedback for user engagement +- **Status Indicators**: Clear communication of system and content states + +### Gesture & Motion + +- **Meaningful Motion**: Animations that enhance understanding and usability +- **Performance Optimization**: Smooth 60fps animations without jank +- **Reduced Motion**: Respecting user preferences for motion sensitivity +- **Contextual Animations**: Animations that provide meaningful feedback + +## Visual Design System + +### Design Tokens + +#### Color Palette + +- **Primary Colors**: Brand colors for primary actions and elements +- **Secondary Colors**: Supporting colors for secondary elements +- **Semantic Colors**: Colors for success, warning, error, and info states +- **Neutral Colors**: Grayscale palette for text, backgrounds, and borders + +#### Typography Scale + +- **Typeface Selection**: Carefully chosen fonts for readability and brand expression +- **Font Sizes**: Hierarchical scale from headings to body text +- **Line Heights**: Optimal line spacing for readability +- **Font Weights**: Appropriate weight variations for hierarchy + +#### Spacing System + +- **Spacing Scale**: Consistent spacing units throughout the design system +- **Grid System**: Underlying grid for layout consistency +- **Component Spacing**: Standardized spacing within and between components + +### Component Library + +- **Atomic Design**: Building complex interfaces from simple, reusable components +- **Component Variants**: Different states and configurations for each component +- **Usage Guidelines**: Clear documentation for proper component implementation +- **Accessibility Compliance**: All components meet accessibility standards + +## Responsive Design + +### Mobile-First Approach + +- **Progressive Enhancement**: Starting with mobile and enhancing for larger screens +- **Touch-Friendly Design**: Appropriate touch target sizes and gestures +- **Performance Optimization**: Fast loading and smooth interactions on mobile +- **Context-Aware Design**: Adapting to mobile usage patterns and contexts + +### Cross-Device Consistency + +- **Unified Experience**: Consistent functionality across all device types +- **Adaptive Layouts**: Fluid layouts that work on any screen size +- **Content Prioritization**: Important content remains accessible on small screens +- **Touch vs Mouse**: Appropriate interaction patterns for different input methods + +## Accessibility Standards + +### WCAG 2.1 Guidelines + +#### Perceivable + +- **Text Alternatives**: Alt text for images and meaningful content for screen readers +- **Time-based Media**: Captions and audio descriptions for multimedia content +- **Adaptable Content**: Content that can be presented in different ways +- **Distinguishable**: Sufficient color contrast and sensory characteristics + +#### Operable + +- **Keyboard Accessible**: All functionality available via keyboard navigation +- **Enough Time**: Adjustable time limits and no flashing content +- **Seizure Prevention**: Avoiding content that could cause seizures +- **Navigable**: Clear navigation and focus management + +#### Understandable + +- **Readable**: Clear language and reading level appropriate for audience +- **Predictable**: Consistent navigation and behavior patterns +- **Input Assistance**: Clear labels, instructions, and error messages + +#### Robust + +- **Compatible**: Content works with current and future user agents +- **Assistive Technology**: Proper support for screen readers and other AT + +### Implementation Practices + +- **Semantic HTML**: Proper use of HTML elements for screen reader compatibility +- **ARIA Labels**: Appropriate use of ARIA attributes when needed +- **Focus Management**: Clear focus indicators and logical tab order +- **Color Independence**: Design works without relying on color alone + +## Performance & Optimization + +### User Experience Performance + +- **Perceived Performance**: Optimizing for how fast the experience feels to users +- **Progressive Loading**: Content loads progressively to maintain user engagement +- **Skeleton Screens**: Placeholder content during loading states +- **Optimistic Updates**: Immediate UI feedback for user actions + +### Technical Performance + +- **Core Web Vitals**: Optimizing for Google's performance metrics +- **Bundle Optimization**: Efficient code splitting and lazy loading +- **Image Optimization**: Appropriate image formats and responsive images +- **Caching Strategy**: Effective caching for improved performance + +## Testing & Quality Assurance + +### Usability Testing + +- **Heuristic Evaluation**: Expert review against usability principles +- **Cognitive Walkthrough**: Step-by-step evaluation of user tasks +- **Accessibility Testing**: Automated and manual accessibility audits +- **Cross-Browser Testing**: Ensuring consistent experience across browsers + +### User Acceptance Testing + +- **Beta Testing**: Real user testing in production-like environments +- **A/B Testing**: Comparative testing of design variations +- **Multivariate Testing**: Testing multiple variables simultaneously +- **Longitudinal Testing**: Tracking user experience over time + +## Documentation & Governance + +### Design System Documentation + +- **Component Documentation**: Detailed usage guidelines for each component +- **Pattern Library**: Common design patterns and their applications +- **Style Guide**: Visual standards and brand guidelines +- **Code Examples**: Implementation examples for developers + +### Design Review Process + +- **Design Critiques**: Regular review sessions for design work +- **Stakeholder Alignment**: Ensuring design decisions align with business goals +- **User Validation**: Testing designs with real users before implementation +- **Iterative Refinement**: Continuous improvement based on feedback and data + +These UX guidelines ensure that all Monynha Softwares products deliver exceptional, accessible, and user-centered experiences that meet the highest standards of design and usability. + + \ No newline at end of file diff --git a/docs/identity/_category_.json b/docs/identity/_category_.json new file mode 100644 index 0000000..ffdce56 --- /dev/null +++ b/docs/identity/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Visual Identity & UI Components", + "position": 5, + "link": { + "type": "generated-index", + "description": "Monynha Softwares brand guidelines, visual identity, and UI component library documentation." + } +} \ No newline at end of file diff --git a/docs/identity/brand-guidelines.md b/docs/identity/brand-guidelines.md new file mode 100644 index 0000000..4abaf65 --- /dev/null +++ b/docs/identity/brand-guidelines.md @@ -0,0 +1,386 @@ +# Brand Guidelines + +This document outlines the visual identity, brand standards, and usage guidelines for Monynha Softwares. + +## Brand Overview + +### Mission & Values + +**Mission**: Empowering businesses through innovative, accessible, and user-centered digital solutions. + +**Values**: +- **Innovation**: Pushing boundaries with cutting-edge technology +- **Accessibility**: Creating inclusive solutions for everyone +- **Quality**: Delivering excellence in every product and service +- **Collaboration**: Building strong partnerships with clients and communities +- **Sustainability**: Developing responsible and environmentally conscious solutions + +### Brand Personality + +- **Approachable**: Friendly and easy to work with +- **Professional**: Reliable and trustworthy +- **Innovative**: Forward-thinking and creative +- **Inclusive**: Welcoming and diverse +- **Sustainable**: Responsible and future-oriented + +## Logo Usage + +### Primary Logo + +#### Logo Variations + +- **Full Color Logo**: For use on light backgrounds +- **White Logo**: For use on dark backgrounds +- **Black Logo**: For use on light backgrounds or formal documents +- **Monochrome Logo**: For single-color applications + +#### Logo Clear Space + +The logo must always have adequate clear space around it: + +- **Minimum Clear Space**: Equal to the height of the "M" in "Monynha" +- **No Elements**: No other elements should intrude into this clear space +- **Background Interference**: Ensure background doesn't interfere with logo readability + +#### Logo Scaling + +- **Minimum Size**: Logo should never be smaller than 24px height on digital platforms +- **Maximum Size**: No maximum size restriction, but maintain proportions +- **Aspect Ratio**: Always maintain the original aspect ratio when resizing + +### Logo Don'ts + +- **Don't Modify**: Never alter the logo design, colors, or proportions +- **Don't Rotate**: Don't rotate or tilt the logo +- **Don't Outline**: Don't add outlines, shadows, or effects to the logo +- **Don't Combine**: Don't combine with other logos or graphics +- **Don't Stretch**: Don't distort the logo shape +- **Don't Place Poorly**: Don't place on busy backgrounds that reduce legibility + +## Color Palette + +### Primary Colors + +#### Monynha Blue + +- **Hex**: #2563EB +- **RGB**: 37, 99, 235 +- **CMYK**: 85, 55, 0, 0 +- **Usage**: Primary brand color, headings, call-to-action buttons + +#### Monynha Green + +- **Hex**: #10B981 +- **RGB**: 16, 185, 129 +- **CMYK**: 70, 0, 50, 0 +- **Usage**: Success states, growth indicators, environmental messaging + +### Secondary Colors + +#### Monynha Purple + +- **Hex**: #8B5CF6 +- **RGB**: 139, 92, 246 +- **CMYK**: 45, 70, 0, 0 +- **Usage**: Innovation, creativity, secondary actions + +#### Monynha Orange + +- **Hex**: #F59E0B +- **RGB**: 245, 158, 11 +- **CMYK**: 0, 35, 95, 0 +- **Usage**: Warnings, highlights, energy + +### Neutral Colors + +#### Text Colors + +- **Primary Text**: #111827 (Dark Gray) +- **Secondary Text**: #6B7280 (Medium Gray) +- **Tertiary Text**: #9CA3AF (Light Gray) + +#### Background Colors + +- **Primary Background**: #FFFFFF (White) +- **Secondary Background**: #F9FAFB (Light Gray) +- **Tertiary Background**: #F3F4F6 (Medium Light Gray) + +### Color Usage Guidelines + +#### Contrast Requirements + +- **Text on Background**: Minimum 4.5:1 contrast ratio (WCAG AA) +- **Interactive Elements**: Minimum 3:1 contrast ratio +- **Large Text**: Minimum 3:1 contrast ratio for large text (18pt+ or 14pt+ bold) + +#### Color Accessibility + +- **Color Blindness**: Ensure information is not conveyed by color alone +- **High Contrast Mode**: Support for high contrast display preferences +- **Dark Mode**: Provide appropriate color schemes for dark mode + +## Typography + +### Primary Typeface + +#### Inter (Primary) +- **Weights**: Regular (400), Medium (500), Semi-Bold (600), Bold (700) +- **Usage**: Body text, UI elements, digital platforms +- **Why Inter**: Highly legible, modern, and optimized for screens + +#### Source Serif Pro (Headlines) +- **Weights**: Regular (400), Semi-Bold (600), Bold (700) +- **Usage**: Headlines, display text, print materials +- **Why Source Serif**: Elegant, readable, complements Inter well + +### Type Scale + +#### Digital Platforms +- **H1**: 2.25rem (36px) / Line height: 2.5rem / Weight: 700 +- **H2**: 1.875rem (30px) / Line height: 2.25rem / Weight: 700 +- **H3**: 1.5rem (24px) / Line height: 2rem / Weight: 600 +- **H4**: 1.25rem (20px) / Line height: 1.75rem / Weight: 600 +- **Body Large**: 1.125rem (18px) / Line height: 1.75rem / Weight: 400 +- **Body**: 1rem (16px) / Line height: 1.5rem / Weight: 400 +- **Body Small**: 0.875rem (14px) / Line height: 1.25rem / Weight: 400 +- **Caption**: 0.75rem (12px) / Line height: 1rem / Weight: 400 + +#### Print Materials +- **H1**: 48pt / Line height: 56pt / Weight: 700 +- **H2**: 36pt / Line height: 44pt / Weight: 700 +- **H3**: 24pt / Line height: 32pt / Weight: 600 +- **Body**: 11pt / Line height: 16pt / Weight: 400 + +### Typography Guidelines + +#### Text Hierarchy +- **Clear Structure**: Use consistent heading levels for content structure +- **Visual Hierarchy**: Size and weight should reflect information importance +- **Spacing**: Appropriate line spacing for readability +- **Alignment**: Left-aligned text for optimal readability + +#### Readability +- **Line Length**: Optimal line length of 45-75 characters +- **Line Spacing**: Adequate line spacing (1.4-1.6x font size) +- **Color Contrast**: Sufficient contrast between text and background +- **Font Loading**: Optimize font loading for web performance + +## Visual Elements + +### Iconography + +#### Icon Style +- **Consistent Style**: Outline icons with consistent stroke width (2px) +- **Grid System**: Icons designed on 24x24px grid +- **Scalability**: Icons scale well from 16px to 48px +- **Meaningful**: Icons should be intuitive and universally understood + +#### Icon Usage +- **Context**: Use icons to support, not replace, text +- **Consistency**: Use from approved icon library +- **Accessibility**: Provide text alternatives for screen readers +- **Color**: Icons inherit text color or use semantic colors + +### Photography + +#### Photo Style +- **Authentic**: Real people, genuine situations +- **Diverse**: Representation of diverse backgrounds and abilities +- **High Quality**: Professional quality, well-lit images +- **Relevant**: Images that support the content and brand message + +#### Usage Guidelines +- **People**: Diverse representation, natural expressions +- **Technology**: Modern, clean technology imagery +- **Environments**: Bright, well-lit, professional settings +- **Composition**: Balanced, uncluttered compositions + +### Illustrations + +#### Illustration Style +- **Modern**: Clean lines, minimal design +- **Friendly**: Approachable, not intimidating +- **Consistent**: Unified style across all illustrations +- **Scalable**: Vector-based for all sizes + +#### Usage Guidelines +- **Explain Concepts**: Use to explain complex technical concepts +- **Break Content**: Visual breaks in long-form content +- **Onboarding**: Guide users through processes +- **Empty States**: Friendly illustrations for empty states + +## Layout & Spacing + +### Grid System + +#### 8px Grid +- **Base Unit**: 8px base unit for all spacing and sizing +- **Consistency**: All elements align to 8px grid +- **Scalability**: Easy scaling across different screen sizes +- **Efficiency**: Faster design and development process + +#### Spacing Scale +- **4px**: Minimal spacing (borders, small elements) +- **8px**: Small spacing (component padding) +- **16px**: Medium spacing (section spacing) +- **24px**: Large spacing (major section breaks) +- **32px**: Extra large spacing (page sections) +- **48px+**: Custom spacing for special cases + +### Component Spacing + +#### Cards +- **Padding**: 24px internal padding +- **Margins**: 16px between cards +- **Shadows**: Subtle shadows for depth +- **Borders**: 1px borders with 8px border radius + +#### Forms +- **Field Spacing**: 16px between form fields +- **Label Spacing**: 8px between label and field +- **Button Spacing**: 24px above submit buttons +- **Error Spacing**: 8px below fields for error messages + +## Digital Platforms + +### Web Design + +#### Responsive Design +- **Mobile First**: Design for mobile, enhance for larger screens +- **Breakpoints**: Consistent breakpoints across all projects +- **Flexible Layouts**: Fluid layouts that work on all screen sizes +- **Touch Targets**: Minimum 44px touch targets + +#### Component Library +- **Reusable Components**: Consistent components across projects +- **Design Tokens**: Centralized design values (colors, spacing, typography) +- **Documentation**: Comprehensive component documentation +- **Versioning**: Version control for component updates + +### Mobile Applications + +#### iOS Guidelines +- **Human Interface Guidelines**: Follow Apple's HIG +- **Safe Areas**: Respect device safe areas and notches +- **Navigation**: Use native navigation patterns +- **Gestures**: Support standard iOS gestures + +#### Android Guidelines +- **Material Design**: Follow Material Design principles +- **Navigation**: Use standard Android navigation patterns +- **Adaptive Icons**: Provide adaptive icon assets +- **Dark Mode**: Support system dark mode + +## Print Materials + +### Business Cards +- **Size**: Standard 3.5" x 2" size +- **Layout**: Name, title, contact information +- **Bleed**: 0.125" bleed on all sides +- **Safe Area**: 0.25" safe area from edges + +### Letterhead +- **Header**: Logo and contact information +- **Footer**: Legal information and page numbers +- **Margins**: 1" margins on all sides +- **Typography**: Consistent with brand typography + +### Presentations +- **Templates**: Standardized slide templates +- **Color Usage**: Limited color palette usage +- **Typography**: Consistent heading and body styles +- **Branding**: Logo placement and brand colors + +## Brand Voice & Messaging + +### Tone of Voice + +#### Professional yet Approachable +- **Clear**: Use simple, straightforward language +- **Confident**: Show expertise without arrogance +- **Helpful**: Focus on solving customer problems +- **Inclusive**: Use welcoming, inclusive language + +#### Key Phrases +- **Innovation**: "Pushing the boundaries of what's possible" +- **Accessibility**: "Making technology accessible to everyone" +- **Quality**: "Crafted with attention to detail" +- **Collaboration**: "Building together for better solutions" + +### Content Guidelines + +#### Writing Style +- **Active Voice**: Use active voice for clarity +- **Short Sentences**: Keep sentences concise and readable +- **Bullet Points**: Use bullets for lists and key points +- **Headings**: Use descriptive, benefit-focused headings + +#### Content Types +- **Website Copy**: Clear, benefit-focused messaging +- **Technical Documentation**: Accurate, comprehensive information +- **Marketing Materials**: Engaging, solution-oriented content +- **Social Media**: Conversational, community-focused posts + +## Brand Governance + +### Approval Process + +#### Brand Usage Approval +- **Logo Usage**: All logo usage requires approval +- **New Materials**: New marketing materials need brand review +- **Partnerships**: Co-branding requires legal and brand approval +- **Modifications**: Any brand element modifications need approval + +#### Review Process +- **Brand Team Review**: Initial review by brand team +- **Stakeholder Approval**: Final approval from relevant stakeholders +- **Legal Review**: Legal review for contracts and partnerships +- **Quality Assurance**: Final quality check before publication + +### Brand Monitoring + +#### Usage Monitoring +- **Regular Audits**: Periodic review of brand usage +- **Quality Control**: Ensure consistent brand application +- **Corrections**: Address brand misuse promptly +- **Updates**: Keep brand guidelines current + +#### Brand Protection +- **Trademark Protection**: Protect brand trademarks legally +- **Domain Monitoring**: Monitor domain name usage +- **Social Media**: Monitor social media for brand mentions +- **Competitive Analysis**: Track competitor brand strategies + +## Implementation Resources + +### Design Resources + +#### Digital Assets +- **Logo Files**: Vector and raster logo files +- **Color Palettes**: Design software color swatches +- **Font Files**: Licensed font files for designers +- **Icon Library**: Approved icon set + +#### Templates +- **Presentation Templates**: PowerPoint and Google Slides templates +- **Document Templates**: Word and Google Docs templates +- **Email Templates**: Email signature and newsletter templates +- **Social Media Templates**: Image and video templates + +### Tools & Software + +#### Design Tools +- **Figma**: Primary design and prototyping tool +- **Adobe Creative Suite**: For print and advanced design work +- **Sketch**: Alternative design tool for some projects +- **InVision**: Prototyping and design handoff + +#### Collaboration Tools +- **Slack**: Team communication and brand discussions +- **Google Workspace**: Document collaboration and storage +- **Notion**: Internal documentation and knowledge base +- **Miro**: Visual collaboration and brainstorming + +This comprehensive brand guidelines document ensures consistent, professional representation of Monynha Softwares across all touchpoints and communications. + + \ No newline at end of file diff --git a/docs/identity/ui-components.md b/docs/identity/ui-components.md new file mode 100644 index 0000000..9e93e28 --- /dev/null +++ b/docs/identity/ui-components.md @@ -0,0 +1,526 @@ +# UI Components + +This document outlines the user interface components and design system used by Monynha Softwares across all digital products. + +## Component Architecture + +### Design System Structure + +Our design system follows atomic design principles: + +- **Atoms**: Basic HTML elements (buttons, inputs, labels) +- **Molecules**: Simple combinations of atoms (form fields, cards) +- **Organisms**: Complex combinations of molecules (navigation, forms) +- **Templates**: Page-level layouts with placeholder content +- **Pages**: Specific instances of templates with real content + +### Component Library + +#### Core Components + +- **Button**: Primary, secondary, and tertiary action buttons +- **Input**: Text inputs, textareas, select dropdowns +- **Card**: Content containers with consistent padding and shadows +- **Modal**: Overlay dialogs for focused interactions +- **Navigation**: Header, sidebar, and breadcrumb navigation +- **Table**: Data display with sorting and pagination +- **Form**: Structured form layouts with validation + +#### Specialized Components + +- **Data Visualization**: Charts, graphs, and data displays +- **Media**: Image galleries, video players, audio controls +- **Feedback**: Loading spinners, progress bars, notifications +- **Layout**: Grids, containers, and spacing utilities +- **Typography**: Text styles and heading hierarchies + +## Component Specifications + +### Button Component + +#### Variants + +```jsx +// Primary Button + + +// Secondary Button + + +// Ghost Button + +``` + +#### States + +- **Default**: Normal button state +- **Hover**: Mouse over state with visual feedback +- **Active**: Pressed state during interaction +- **Disabled**: Non-interactive state with reduced opacity +- **Loading**: Loading state with spinner and disabled interaction +- **Focus**: Keyboard focus state with visible focus ring + +#### Accessibility + +- **Keyboard Navigation**: Full keyboard accessibility +- **Screen Reader**: Proper ARIA labels and descriptions +- **Color Contrast**: Minimum 4.5:1 contrast ratio +- **Touch Targets**: Minimum 44px touch targets on mobile + +### Form Components + +#### Input Field + +```jsx +// Text Input + + +// Email Input + +``` + +#### Form Validation + +- **Real-time Validation**: Immediate feedback on input +- **Error States**: Clear error messages and visual indicators +- **Success States**: Positive feedback for valid inputs +- **Progressive Disclosure**: Show additional fields based on input + +#### Field Types + +- **Text**: Single-line text input +- **Textarea**: Multi-line text input +- **Select**: Dropdown selection +- **Checkbox**: Multiple selection options +- **Radio**: Single selection from options +- **File Upload**: File selection and upload +- **Date Picker**: Date selection with calendar +- **Password**: Masked password input with visibility toggle + +### Navigation Components + +#### Header Navigation + +```jsx +
+ + + Products + Solutions + About + + +
+``` + +#### Sidebar Navigation + +```jsx + + + } href="/dashboard"> + Dashboard + + } href="/projects"> + Projects + + + + } href="/settings"> + Settings + + + +``` + +#### Breadcrumb Navigation + +```jsx + + Home + Products + Software + Monynha Docs + +``` + +### Data Display Components + +#### Table Component + +```jsx + handleSort(column, direction)} + onRowClick={(row) => handleRowClick(row)} +/> +``` + +#### Card Component + +```jsx + + + Project Overview + + Summary of current project status and metrics + + + +
+ + +
+
+ + + +
+``` + +### Feedback Components + +#### Loading States + +```jsx +// Spinner + + +// Skeleton Loading + + + + + +// Progress Bar + +``` + +#### Notifications + +```jsx +// Toast Notification + + +// Alert Banner + + Your subscription will expire in 3 days. + + +// Modal Dialog + + + Confirm Action + + + Are you sure you want to delete this project? + + + + + + +``` + +## Responsive Design + +### Breakpoint System + +#### Breakpoints + +- **Mobile**: 320px - 767px +- **Tablet**: 768px - 1023px +- **Desktop**: 1024px - 1439px +- **Large Desktop**: 1440px+ + +#### Responsive Utilities + +```jsx +// Responsive Grid +
+
Item 1
+
Item 2
+
Item 3
+
+ +// Responsive Typography +

+ Responsive Heading +

+ +// Responsive Spacing +
+ Responsive Padding +
+``` + +### Mobile-First Approach + +#### Touch Interactions + +- **Touch Targets**: Minimum 44px touch targets +- **Swipe Gestures**: Support for swipe navigation +- **Tap States**: Clear visual feedback for touch interactions +- **Accessibility**: Screen reader support for touch interfaces + +#### Mobile Navigation + +- **Bottom Navigation**: Tab-based navigation for mobile +- **Hamburger Menu**: Collapsible navigation for smaller screens +- **Swipe Gestures**: Touch-friendly navigation patterns +- **Thumb Zone**: Content positioned for one-handed use + +## Accessibility Features + +### Keyboard Navigation + +#### Focus Management + +- **Visible Focus**: Clear focus indicators for keyboard users +- **Logical Order**: Tab order follows reading order +- **Focus Trapping**: Appropriate focus management in modals +- **Skip Links**: Skip to main content links + +#### Keyboard Shortcuts + +```jsx +// Keyboard Shortcuts +useKeyboardShortcut('ctrl+s', () => saveDocument()); +useKeyboardShortcut('ctrl+z', () => undo()); +useKeyboardShortcut('escape', () => closeModal()); +``` + +### Screen Reader Support + +#### ARIA Attributes + +```jsx +// Button with ARIA + + + Saves the current document to your account + + +// Form with ARIA +
+ + + Enter keywords to search the site + +
+``` + +#### Semantic HTML + +- **Proper Headings**: Hierarchical heading structure (h1-h6) +- **Landmarks**: Header, nav, main, aside, footer landmarks +- **Lists**: Proper use of ul, ol, dl elements +- **Tables**: Proper table structure with headers + +### Color and Contrast + +#### Contrast Requirements + +- **Text Contrast**: 4.5:1 minimum for normal text +- **Large Text**: 3:1 minimum for large text (18pt+ or 14pt+ bold) +- **Interactive Elements**: 3:1 minimum for buttons and links +- **Non-text Content**: 3:1 minimum for icons and graphics + +#### Color Independence + +- **Not Color Only**: Information not conveyed by color alone +- **Color Patterns**: Use patterns, shapes, or text with color +- **High Contrast**: Support for high contrast mode +- **Dark Mode**: Proper dark mode color schemes + +## Component Documentation + +### Storybook Integration + +#### Component Stories + +```jsx +// Button.stories.jsx +import { Button } from './Button'; + +export default { + title: 'Components/Button', + component: Button, + parameters: { + docs: { + description: { + component: 'A versatile button component with multiple variants and states.' + } + } + } +}; + +export const Primary = { + args: { + variant: 'primary', + children: 'Primary Button', + size: 'medium' + } +}; + +export const Secondary = { + args: { + variant: 'secondary', + children: 'Secondary Button', + size: 'medium' + } +}; + +export const Disabled = { + args: { + variant: 'primary', + children: 'Disabled Button', + disabled: true + } +}; +``` + +#### Documentation + +- **Usage Examples**: Practical examples of component usage +- **Props Documentation**: Complete prop definitions and types +- **Accessibility Notes**: Accessibility considerations and requirements +- **Design Guidelines**: When and how to use each component + +### Design Tokens + +#### CSS Custom Properties + +```css +/* Color Tokens */ +:root { + --color-primary: #2563eb; + --color-secondary: #10b981; + --color-text-primary: #111827; + --color-text-secondary: #6b7280; + --color-background: #ffffff; + --color-surface: #f9fafb; +} + +/* Spacing Tokens */ +:root { + --space-1: 0.25rem; /* 4px */ + --space-2: 0.5rem; /* 8px */ + --space-3: 0.75rem; /* 12px */ + --space-4: 1rem; /* 16px */ + --space-6: 1.5rem; /* 24px */ + --space-8: 2rem; /* 32px */ +} + +/* Typography Tokens */ +:root { + --font-family-primary: 'Inter', system-ui, sans-serif; + --font-size-xs: 0.75rem; /* 12px */ + --font-size-sm: 0.875rem; /* 14px */ + --font-size-base: 1rem; /* 16px */ + --font-size-lg: 1.125rem; /* 18px */ + --font-size-xl: 1.25rem; /* 20px */ + --font-size-2xl: 1.5rem; /* 24px */ +} +``` + +#### Component Variants + +- **Size Variants**: Small, medium, large component sizes +- **Color Variants**: Different color schemes for different contexts +- **State Variants**: Default, hover, active, disabled, loading states +- **Layout Variants**: Different layout options for various use cases + +## Implementation Guidelines + +### Component Development + +#### Code Standards + +- **TypeScript**: Strongly typed component props and state +- **Clean Code**: Readable, maintainable component code +- **Performance**: Optimized rendering and minimal re-renders +- **Testing**: Comprehensive unit and integration tests + +#### Component Composition + +```jsx +// Composition over inheritance +function UserCard({ user, onEdit, onDelete }) { + return ( + + + +
+ {user.name} + {user.email} +
+
+ +

{user.bio}

+
+ + + + +
+ ); +} +``` + +### Maintenance & Updates + +#### Versioning + +- **Semantic Versioning**: Major.minor.patch version scheme +- **Breaking Changes**: Major version for breaking API changes +- **Deprecation**: Clear deprecation warnings for old APIs +- **Migration Guides**: Documentation for upgrading between versions + +#### Change Management + +- **Change Requests**: Formal process for component modifications +- **Impact Assessment**: Assessment of changes on existing implementations +- **Testing Requirements**: Required testing for component changes +- **Documentation Updates**: Updated documentation for changes + +This comprehensive UI component system ensures consistent, accessible, and maintainable user interfaces across all Monynha Softwares products. + + \ No newline at end of file diff --git a/docs/projects/_category_.json b/docs/projects/_category_.json new file mode 100644 index 0000000..968afa9 --- /dev/null +++ b/docs/projects/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Projects", + "position": 2, + "link": { + "type": "generated-index", + "description": "Documentation for all Monynha Softwares projects, including overviews, tech stacks, features, and contribution guidelines." + } +} \ No newline at end of file diff --git a/docs/projects/boteco-pro.md b/docs/projects/boteco-pro.md new file mode 100644 index 0000000..26c1db9 --- /dev/null +++ b/docs/projects/boteco-pro.md @@ -0,0 +1,301 @@ +--- +title: "Boteco Pro — Project Overview" +sidebar_position: 1 +--- + +Boteco Pro is a management system for bars and restaurants. It centralizes orders, inventory, staff, and financial operations while providing real-time insights and integrations with common hospitality services. + +## Target audience + +- Bar and restaurant owners +- Small to medium-sized hospitality businesses +- Hospitality professionals looking to digitize operations + +## Problem solved + +Boteco Pro addresses common hospitality pain points: + +- Manual order tracking and inventory mistakes +- Inefficient or delayed financial reporting +- Lack of real-time business metrics and insights +- Fragmented integrations with POS and payment systems + +## Tech stack & architecture + +### Core technologies + +- **Frontend**: Flutter (cross-platform mobile) +- **Backend**: Convex (real-time services and sync) +- **Database**: Convex built-in/document-store features +- **State management**: Provider pattern (Flutter) + +### Architecture overview + +- Mobile app (Flutter) communicates with Convex for real-time updates. +- Offline-first design with local persistence and background sync. +- RESTful APIs for third-party integrations (payment gateways, POS, analytics). + +## Integration points + +- Payment gateways (consider PCI/security requirements). +- POS systems (inventory / orders synchronization). +- Analytics and reporting tools. + +## Features & roadmap + +### Current (v1.0) + +- Real-time order management +- Inventory control with low-stock alerts +- Financial summaries (daily/weekly/monthly) +- Customer profiles and order history +- Basic staff/role management + +### Planned + +- Advanced analytics dashboards +- Loyalty / rewards system +- Multi-location management +- Web-based ordering integration + +## Development status + +- Current phase: Beta testing with select partners +- Next milestone: v1.1 (enhanced reporting) +- Target for full v1.0: Q1 2026 + +## Setup & local development + +### Prerequisites + +- Flutter SDK (3.x+) +- Dart SDK (2.19+) +- Convex account / project setup + +### Quick start + +1. Clone the repository + +```bash +git clone https://github.com/Monynha-Softwares/Boteco-Pro.git +cd boteco-pro +``` + +1. Install dependencies + +```bash +flutter pub get +``` + +1. Configure Convex (example) + +```bash +npx convex dev --once +``` + +1. Run the app + +```bash +flutter run +``` + +### Environment + +Create a `.env` (or use your preferred env method): + +```bash +CONVEX_URL=your_convex_deployment_url +API_KEY=your_api_key +``` + +## Contributing + +Follow the general Monynha contribution guidelines and testing requirements. For repository-level notes, see the [general contribution guidelines](../contribution/contributing.md). + +# Boteco Pro – Project Overview------ + + + +Boteco Pro is a comprehensive management system designed for bars and restaurants, providing complete control over orders, inventory, and financial operations.sidebar_position: 1sidebar_position: 1 + + + +## Target Audience------ + + + +- Bar and restaurant owners + +- Small to medium-sized hospitality businesses + +- Hospitality industry professionals seeking digital transformation# Boteco Pro – Project Overview# Boteco Pro – Project Overview + + + +## Problem Solved + + + +Boteco Pro addresses the common challenges faced by hospitality businesses:Boteco Pro is a comprehensive management system designed for bars and restaurants, providing complete control over orders, inventory, and financial operations.Boteco Pro is a comprehensive management system designed for bars and restaurants, providing complete control over orders, inventory, and financial operations. + + + +- Manual order tracking and inventory management + +- Inefficient financial reporting + +- Lack of real-time business insights## Target Audience## Target Audience + +- Difficulty in managing customer relationships + + + +## Tech Stack & Architecture + +- Bar and restaurant owners- Bar and restaurant owners + +### Core Technologies + +- Small to medium-sized hospitality businesses- Small to medium-sized hospitality businesses + +- **Frontend**: Flutter for cross-platform mobile application + +- **Backend**: Convex for real-time backend services- Hospitality industry professionals seeking digital transformation- Hospitality industry professionals seeking digital transformation + +- **Database**: Integrated database solutions within Convex + +- **State Management**: Provider pattern with Flutter + + + +### Architecture Components## Problem Solved## Problem Solved + + + +- **Mobile App**: Cross-platform Flutter application for iOS and Android + +- **Real-time Backend**: Convex handles real-time data synchronization + +- **Offline Support**: Local data persistence for offline operationsBoteco Pro addresses the common challenges faced by hospitality businesses:Boteco Pro addresses the common challenges faced by hospitality businesses: + +- **API Integration**: RESTful APIs for third-party integrations + +- Manual order tracking and inventory management + +### Integration Points + +- Manual order tracking and inventory management- Inefficient financial reporting + +--- +title: "Boteco Pro — Project Overview" +sidebar_position: 1 +--- + +Boteco Pro is a management system for bars and restaurants. It aims to centralize orders, inventory, staff and financial operations while providing real-time insights and integrations with common hospitality services. + +## Target audience + +- Bar and restaurant owners +- Small to medium-sized hospitality businesses +- Hospitality professionals looking to digitize operations + +## Problem solved + +Boteco Pro addresses common hospitality pain points: + +- Manual order tracking and inventory mistakes +- Inefficient or delayed financial reporting +- Lack of real-time business metrics and insights +- Fragmented integrations with POS and payment systems + +## Tech stack & architecture + +### Core technologies + +- **Frontend**: Flutter (cross-platform mobile) +- **Backend**: Convex (real-time services and sync) +- **Database**: Convex built-in/document-store features +- **State management**: Provider pattern (Flutter) + +### Architecture overview + +- Mobile app (Flutter) communicates with Convex for real-time updates +- Offline-first design with local persistence and background sync +- RESTful APIs for third-party integrations (payment gateways, POS, analytics) + +## Integration points + +- Payment gateways (PCI considerations) +- POS systems (inventory / orders sync) +- Analytics and reporting tools + +## Features & roadmap + +### Current (v1.0) + +- Real-time order management +- Inventory control with low-stock alerts +- Financial summaries (daily/weekly/monthly) +- Customer profiles and order history +- Basic staff/role management + +### Planned + +- Advanced analytics dashboards +- Loyalty / rewards system +- Multi-location management +- Web-based ordering integration + +## Development status + +- Current phase: Beta testing with select partners +- Next milestone: v1.1 (enhanced reporting) +- Target for full v1.0: Q1 2026 + +## Setup & local development + +### Prerequisites + +- Flutter SDK (3.x+) +- Dart SDK (2.19+) +- Convex account / project setup + +### Quick start + +1. Clone the repository + +```bash +git clone https://github.com/Monynha-Softwares/Boteco-Pro.git +cd boteco-pro +``` + +2. Install dependencies + +```bash +flutter pub get +``` + +3. Configure Convex (example) + +```bash +npx convex dev --once +``` + +4. Run the app + +```bash +flutter run +``` + +### Environment + +Create a `.env` (or otherwise set env vars): + +``` +CONVEX_URL=your_convex_deployment_url +API_KEY=your_api_key +``` + +## Contributing + +Follow the general Monynha contribution guidelines and testing requirements. For repository-level notes, see the [general contribution guidelines](../contribution/contributing.md). diff --git a/docs/technologies/_category_.json b/docs/technologies/_category_.json new file mode 100644 index 0000000..622f6f6 --- /dev/null +++ b/docs/technologies/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Technologies & Stack", + "position": 3, + "link": { + "type": "generated-index", + "description": "Comprehensive overview of the technology stacks used by Monynha Softwares, including frontend, backend, and DevOps tools." + } +} \ No newline at end of file diff --git a/docs/technologies/backend-stack.md b/docs/technologies/backend-stack.md new file mode 100644 index 0000000..9ffebab Binary files /dev/null and b/docs/technologies/backend-stack.md differ diff --git a/docs/technologies/devops-tools.md b/docs/technologies/devops-tools.md new file mode 100644 index 0000000..3e65d5c --- /dev/null +++ b/docs/technologies/devops-tools.md @@ -0,0 +1,253 @@ +# DevOps Tools & Infrastructure + +This document covers the DevOps tools and infrastructure used by Monynha Softwares for development, deployment, and operations. + +## Version Control & Collaboration + +### Git & GitHub + +#### Repository Management + +- **Monorepo Structure**: Single repository containing all projects and shared code +- **Branching Strategy**: Git Flow with feature branches, develop, and main branches +- **Pull Request Workflow**: Code review requirements and automated checks +- **Issue Tracking**: GitHub Issues for bug tracking and feature requests + +#### Automation + +- **GitHub Actions**: CI/CD pipelines for automated testing and deployment +- **CodeQL**: Security vulnerability scanning in pull requests +- **Dependabot**: Automated dependency updates and security patches +- **Protected Branches**: Branch protection rules for main branches + +## Continuous Integration & Deployment + +### GitHub Actions Workflows + +#### CI Pipeline + +```yaml +name: CI +on: + push: + branches: [ main, develop ] + pull_request: + branches: [ main, develop ] + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: '20' + cache: 'yarn' + - name: Install dependencies + run: yarn install --frozen-lockfile + - name: Run linting + run: yarn lint + - name: Run tests + run: yarn test + - name: Build + run: yarn build +``` + +#### Deployment Pipeline + +- **Staging Deployment**: Automatic deployment to staging on develop branch merges +- **Production Deployment**: Manual approval required for production releases +- **Environment Configuration**: Separate configurations for dev, staging, and prod +- **Rollback Strategy**: Quick rollback capabilities for failed deployments + +## Infrastructure as Code + +### Terraform + +For cloud infrastructure management: + +- **Infrastructure Definition**: Declarative infrastructure configuration +- **State Management**: Remote state storage and locking +- **Module Organization**: Reusable infrastructure components +- **Environment Separation**: Isolated infrastructure per environment + +### Docker & Containerization + +#### Container Strategy + +- **Multi-stage Builds**: Optimized Docker images for different environments +- **Docker Compose**: Local development environment orchestration +- **Container Registry**: GitHub Container Registry for image storage +- **Security Scanning**: Automated vulnerability scanning of container images + +#### Development Environment + +```yaml +version: '3.8' +services: + app: + build: + context: . + dockerfile: Dockerfile.dev + ports: + - "3000:3000" + volumes: + - .:/app + - /app/node_modules + environment: + - NODE_ENV=development +``` + +## Monitoring & Observability + +### Application Monitoring + +#### Sentry + +- **Error Tracking**: Real-time error monitoring and alerting +- **Performance Monitoring**: Application performance metrics and traces +- **Release Tracking**: Deployment tracking and regression detection +- **User Feedback**: User-reported issues and feedback collection + +#### Application Metrics + +- **Custom Metrics**: Business-specific KPIs and performance indicators +- **Health Checks**: Application and service health monitoring +- **Logging**: Structured logging with correlation IDs +- **Distributed Tracing**: Request tracing across microservices + +### Infrastructure Monitoring + +#### Uptime Monitoring + +- **Service Availability**: External monitoring of service endpoints +- **SSL Certificate Monitoring**: Certificate expiration alerts +- **Domain Monitoring**: DNS and domain health checks +- **Third-party Integrations**: Monitoring of external service dependencies + +## Security & Compliance + +### Security Scanning + +#### Code Security + +- **SAST (Static Application Security Testing)**: Code vulnerability scanning +- **Dependency Scanning**: Third-party library vulnerability detection +- **Secret Detection**: Prevention of secret leaks in code +- **License Compliance**: Open source license compliance checking + +#### Infrastructure Security + +- **Vulnerability Management**: Regular security updates and patching +- **Access Control**: Principle of least privilege for infrastructure access +- **Network Security**: Firewall rules and network segmentation +- **Encryption**: Data encryption at rest and in transit + +### Compliance Automation + +- **Audit Logging**: Comprehensive audit trails for compliance +- **Data Retention**: Automated data lifecycle management +- **Backup Verification**: Regular backup integrity testing +- **Disaster Recovery**: Automated failover and recovery procedures + +## Development Tools + +### Code Quality + +#### ESLint & Prettier + +- **Code Standards**: Consistent code formatting and style +- **Custom Rules**: Project-specific linting rules +- **Pre-commit Hooks**: Automated code quality checks +- **IDE Integration**: Real-time feedback in development environments + +#### Testing Framework + +- **Unit Testing**: Jest for component and utility testing +- **Integration Testing**: API and database integration tests +- **End-to-End Testing**: Playwright for browser automation +- **Visual Regression**: Screenshot comparison for UI changes + +### Documentation + +#### Automated Documentation + +- **API Documentation**: OpenAPI/Swagger for API documentation +- **Component Documentation**: Storybook for UI component documentation +- **Architecture Diagrams**: Automated diagram generation from code +- **Changelog Generation**: Automated release notes from commits + +## Cloud Platform Management + +### Vercel + +For frontend and full-stack deployments: + +- **Automatic Scaling**: Serverless scaling based on traffic +- **Preview Deployments**: Pull request preview environments +- **Edge Network**: Global CDN for optimal performance +- **Analytics Integration**: Built-in performance and usage analytics + +### Supabase + +For backend and database operations: + +- **Database Management**: PostgreSQL database administration +- **Real-time Monitoring**: Database performance and usage metrics +- **Backup Management**: Automated database backups and recovery +- **Edge Functions**: Serverless function deployment and monitoring + +## Local Development Environment + +### Development Tools Setup + +#### VS Code Configuration + +- **Extensions**: Recommended extensions for the project +- **Settings**: Project-specific editor configuration +- **Tasks**: Automated development tasks and scripts +- **Debugging**: Integrated debugging configurations + +#### Environment Management + +- **Environment Variables**: Secure environment variable management +- **Local Services**: Local database and service orchestration +- **Hot Reloading**: Fast development feedback loops +- **Cross-platform Support**: Consistent development experience across OS + +## Performance Optimization + +### Build Optimization + +- **Bundle Analysis**: Webpack bundle size analysis and optimization +- **Code Splitting**: Dynamic imports and lazy loading +- **Asset Optimization**: Image compression and font optimization +- **Caching Strategy**: Aggressive caching for static assets + +### Runtime Performance + +- **Performance Budgets**: Defined performance thresholds +- **Core Web Vitals**: Monitoring of Google's Core Web Vitals metrics +- **Memory Management**: Memory leak detection and optimization +- **Database Query Optimization**: Query performance monitoring and tuning + +## Disaster Recovery + +### Backup Strategy + +- **Database Backups**: Automated daily backups with retention policies +- **Code Repository**: Git-based version control as ultimate backup +- **Configuration Backups**: Infrastructure and configuration versioning +- **Documentation**: Runbooks and recovery procedures + +### Recovery Procedures + +- **RTO/RPO Definition**: Recovery time and point objectives +- **Failover Automation**: Automated failover for critical services +- **Communication Plan**: Incident response and communication procedures +- **Post-mortem Process**: Incident analysis and improvement implementation + +This DevOps infrastructure ensures reliable, secure, and efficient development and deployment processes while maintaining high standards of code quality and system performance. + + \ No newline at end of file diff --git a/docs/technologies/frontend-stack.md b/docs/technologies/frontend-stack.md new file mode 100644 index 0000000..e211db6 Binary files /dev/null and b/docs/technologies/frontend-stack.md differ diff --git a/docusaurus.config.js b/docusaurus.config.js index be91f22..922a1b6 100644 --- a/docusaurus.config.js +++ b/docusaurus.config.js @@ -10,9 +10,11 @@ import {themes as prismThemes} from 'prism-react-renderer'; /** @type {import('@docusaurus/types').Config} */ const config = { - title: 'My Site', - tagline: 'Dinosaurs are cool', - favicon: 'img/favicon.ico', + title: 'MonaDocs', + tagline: 'Documentação Central da Monynha Softwares', + // Use an SVG favicon for crisp rendering on modern browsers + // If you need .ico for legacy support, add `static/img/favicon.ico` and update this line. + favicon: 'img/favicon.svg', // Future flags, see https://docusaurus.io/docs/api/docusaurus-config#future future: { @@ -20,15 +22,15 @@ const config = { }, // Set the production url of your site here - url: 'https://your-docusaurus-site.example.com', + url: 'https://docs.monynha.com', // Set the // pathname under which your site is served // For GitHub pages deployment, it is often '//' baseUrl: '/', // GitHub pages deployment config. // If you aren't using GitHub pages, you don't need these. - organizationName: 'facebook', // Usually your GitHub org/user name. - projectName: 'docusaurus', // Usually your repo name. + organizationName: 'Monynha-Softwares', // Usually your GitHub org/user name. + projectName: 'MonaDocs', // Usually your repo name. onBrokenLinks: 'throw', @@ -50,7 +52,7 @@ const config = { // Please change this to your repo. // Remove this to remove the "edit this page" links. editUrl: - 'https://github.com/facebook/docusaurus/tree/main/packages/create-docusaurus/templates/shared/', + 'https://github.com/Monynha-Softwares/MonaDocs/edit/dev/', }, blog: { showReadingTime: true, @@ -61,7 +63,7 @@ const config = { // Please change this to your repo. // Remove this to remove the "edit this page" links. editUrl: - 'https://github.com/facebook/docusaurus/tree/main/packages/create-docusaurus/templates/shared/', + 'https://github.com/Monynha-Softwares/MonaDocs/edit/dev/', // Useful options to enforce blogging best practices onInlineTags: 'warn', onInlineAuthors: 'warn', @@ -83,21 +85,39 @@ const config = { respectPrefersColorScheme: true, }, navbar: { - title: 'My Site', + title: 'MonaDocs', logo: { - alt: 'My Site Logo', + alt: 'Monynha Softwares Logo', src: 'img/logo.svg', }, items: [ + // Explicit dropdown exposing main documentation areas so the mobile menu + // shows all relevant links (projects, technologies, guidelines, etc.). { - type: 'docSidebar', - sidebarId: 'tutorialSidebar', + label: 'Documentação', position: 'left', - label: 'Tutorial', + items: [ + { to: '/docs/intro', label: 'Introdução' }, + { to: '/docs/projects/boteco-pro', label: 'Projetos' }, + { to: '/docs/technologies/frontend-stack', label: 'Tecnologias' }, + { to: '/docs/guidelines/ux-guidelines', label: 'Guidelines' }, + { to: '/docs/identity/brand-guidelines', label: 'Identidade' }, + { to: '/docs/contribution/contributing', label: 'Contribuição' }, + { to: '/docs/architecture/backend-architecture', label: 'Arquitetura' }, + ], + }, + { to: '/blog', label: 'Blog', position: 'left' }, + { + label: 'Empresa', + position: 'right', + items: [ + { label: 'Monynha.com', href: 'https://monynha.com' }, + { label: 'Projetos', href: 'https://monynha.com/projetos' }, + { label: 'Portfólio', href: 'https://marcelo.monynha.com/portifolio' }, + ], }, - {to: '/blog', label: 'Blog', position: 'left'}, { - href: 'https://github.com/facebook/docusaurus', + href: 'https://github.com/Monynha-Softwares', label: 'GitHub', position: 'right', }, @@ -107,33 +127,41 @@ const config = { style: 'dark', links: [ { - title: 'Docs', + title: 'Documentação', items: [ { - label: 'Tutorial', + label: 'Introdução', to: '/docs/intro', }, + { + label: 'Projetos', + to: '/docs/projetos/boteco-pro', + }, + { + label: 'Tecnologias', + to: '/docs/tecnologias/typescript', + }, ], }, { - title: 'Community', + title: 'Empresa', items: [ { - label: 'Stack Overflow', - href: 'https://stackoverflow.com/questions/tagged/docusaurus', + label: 'Monynha.com', + href: 'https://monynha.com', }, { - label: 'Discord', - href: 'https://discordapp.com/invite/docusaurus', + label: 'Projetos', + href: 'https://monynha.com/projetos', }, { - label: 'X', - href: 'https://x.com/docusaurus', + label: 'Portfólio', + href: 'https://marcelo.monynha.com/portifolio', }, ], }, { - title: 'More', + title: 'Comunidade', items: [ { label: 'Blog', @@ -141,12 +169,16 @@ const config = { }, { label: 'GitHub', - href: 'https://github.com/facebook/docusaurus', + href: 'https://github.com/Monynha-Softwares', + }, + { + label: 'Monynha Online', + href: 'https://monynha.online', }, ], }, ], - copyright: `Copyright © ${new Date().getFullYear()} My Project, Inc. Built with Docusaurus.`, + copyright: `Copyright © ${new Date().getFullYear()} Monynha Softwares. Construído com Docusaurus.`, }, prism: { theme: prismThemes.github, diff --git a/package.json b/package.json index 17e2556..3109556 100644 --- a/package.json +++ b/package.json @@ -11,7 +11,8 @@ "clear": "docusaurus clear", "serve": "docusaurus serve", "write-translations": "docusaurus write-translations", - "write-heading-ids": "docusaurus write-heading-ids" + "write-heading-ids": "docusaurus write-heading-ids", + "test": "node --test scripts" }, "dependencies": { "@docusaurus/core": "3.9.2", diff --git a/scripts/homepage.test.js b/scripts/homepage.test.js new file mode 100644 index 0000000..f090822 --- /dev/null +++ b/scripts/homepage.test.js @@ -0,0 +1,38 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); + +const repoRoot = path.resolve(__dirname, '..'); + +function readSource(relativePath) { + const filePath = path.join(repoRoot, relativePath); + return fs.readFileSync(filePath, 'utf8'); +} + +test('homepage imports TechStack and Portfolio components', () => { + const homepageSource = readSource('src/pages/index.js'); + + assert.match( + homepageSource, + /import\s+TechStack\s+from\s+'@site\/src\/components\/TechStack';/, + 'Homepage should import the TechStack component' + ); + + assert.match( + homepageSource, + /import\s+Portfolio\s+from\s+'@site\/src\/components\/Portfolio';/, + 'Homepage should import the Portfolio component' + ); +}); + +test('tech stack component defines technology cards', () => { + const techStackSource = readSource('src/components/TechStack/index.js'); + + assert.match( + techStackSource, + /const\s+techStack\s*=\s*\[/, + 'TechStack component should define the techStack array' + ); +}); + diff --git a/sidebars.js b/sidebars.js index f77355c..f817f98 100644 --- a/sidebars.js +++ b/sidebars.js @@ -15,8 +15,85 @@ @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */ const sidebars = { - // By default, Docusaurus generates a sidebar from the docs folder structure - tutorialSidebar: [{type: 'autogenerated', dirName: '.'}], + // Custom sidebar with proper ordering + tutorialSidebar: [ + 'intro', + { + type: 'category', + label: 'Projects', + link: { + type: 'generated-index', + description: 'Documentation for all Monynha Softwares projects, including overviews, tech stacks, features, and contribution guidelines.', + }, + items: [ + 'projects/boteco-pro' + ] + }, + { + type: 'category', + label: 'Technologies', + link: { + type: 'generated-index', + description: 'Technology stack documentation covering frontend, backend, DevOps tools, and development practices.', + }, + items: [ + 'technologies/frontend-stack', + 'technologies/backend-stack', + 'technologies/devops-tools' + ] + }, + { + type: 'category', + label: 'Guidelines', + link: { + type: 'generated-index', + description: 'Development guidelines including UX principles, accessibility standards, code conventions, and security practices.', + }, + items: [ + 'guidelines/ux-guidelines', + 'guidelines/accessibility', + 'guidelines/code-conventions', + 'guidelines/security' + ] + }, + { + type: 'category', + label: 'Identity', + link: { + type: 'generated-index', + description: 'Visual identity and UI component documentation including brand guidelines and component libraries.', + }, + items: [ + 'identity/brand-guidelines', + 'identity/ui-components' + ] + }, + { + type: 'category', + label: 'Contribution', + link: { + type: 'generated-index', + description: 'Contribution guidelines, development workflow, and governance model for the Monynha Softwares community.', + }, + items: [ + 'contribution/contributing', + 'contribution/governance' + ] + }, + { + type: 'category', + label: 'Architecture', + link: { + type: 'generated-index', + description: 'Technical architecture documentation covering monorepo structure, backend systems, and CI/CD pipelines.', + }, + items: [ + 'architecture/monorepo-structure', + 'architecture/backend-architecture', + 'architecture/ci-cd' + ] + } + ], // But you can create a sidebar manually /* diff --git a/src/components/HomepageFeatures/index.js b/src/components/HomepageFeatures/index.js index acc7621..b89dd1a 100644 --- a/src/components/HomepageFeatures/index.js +++ b/src/components/HomepageFeatures/index.js @@ -4,32 +4,32 @@ import styles from './styles.module.css'; const FeatureList = [ { - title: 'Easy to Use', + title: 'Projetos Inovadores', Svg: require('@site/static/img/undraw_docusaurus_mountain.svg').default, description: ( <> - Docusaurus was designed from the ground up to be easily installed and - used to get your website up and running quickly. + Explore nossa documentação completa de projetos, desde sistemas de gestão + para bares e restaurantes até plataformas educacionais e soluções web modernas. ), }, { - title: 'Focus on What Matters', + title: 'Tecnologias Avançadas', Svg: require('@site/static/img/undraw_docusaurus_tree.svg').default, description: ( <> - Docusaurus lets you focus on your docs, and we'll do the chores. Go - ahead and move your docs into the docs directory. + Conheça as tecnologias que utilizamos: TypeScript, Flutter, Convex, Coolify, + Docker e muito mais. Guias práticos e melhores práticas incluídas. ), }, { - title: 'Powered by React', + title: 'Padrões e Qualidade', Svg: require('@site/static/img/undraw_docusaurus_react.svg').default, description: ( <> - Extend or customize your website layout by reusing React. Docusaurus can - be extended while reusing the same header and footer. + Acesse nossos padrões internos de desenvolvimento, guias de contribuição + e práticas recomendadas para manter a qualidade em todos os projetos. ), }, diff --git a/src/components/Portfolio/index.js b/src/components/Portfolio/index.js new file mode 100644 index 0000000..3bc50bb --- /dev/null +++ b/src/components/Portfolio/index.js @@ -0,0 +1,149 @@ +import React from 'react'; +import clsx from 'clsx'; +import Link from '@docusaurus/Link'; +import styles from './styles.module.css'; + +const projects = [ + { + title: 'Boteco Pro', + description: 'Sistema completo de gestão para bares e restaurantes com controle de pedidos, estoque e financeiro.', + technologies: ['Flutter', 'TypeScript', 'Convex'], + status: 'Em Desenvolvimento', + link: '/docs/projetos/boteco-pro', + icon: '🍺', + color: '#FF6B35' + }, + { + title: 'Plataforma Educacional', + description: 'Sistema de ensino online com cursos interativos, acompanhamento de progresso e certificação.', + technologies: ['React', 'TypeScript', 'Docker'], + status: 'Planejado', + link: '/docs/intro', + icon: '🎓', + color: '#4F46E5' + }, + { + title: 'Sistema de Gestão Empresarial', + description: 'Suite completa para gestão empresarial com módulos de RH, financeiro e operações.', + technologies: ['TypeScript', 'Coolify', 'Docker'], + status: 'Em Planejamento', + link: '/docs/intro', + icon: '🏢', + color: '#10B981' + } +]; + +const testimonials = [ + { + name: 'Cliente Satisfeito', + role: 'Proprietário de Bar', + content: 'O Boteco Pro revolucionou a gestão do meu estabelecimento. Interface intuitiva e funcionalidades completas.', + avatar: '👤' + }, + { + name: 'Parceiro Tecnológico', + role: 'Desenvolvedor', + content: 'Excelente trabalho em equipe e qualidade de código. Tecnologias modernas e boas práticas implementadas.', + avatar: '👨‍💻' + } +]; + +function ProjectCard({ project }) { + return ( +
+
+
+ {project.icon} +
+
+ {project.status} +
+
+ +

{project.title}

+

{project.description}

+ +
+ {project.technologies.map((tech) => ( + + {tech} + + ))} +
+ + + Ver Detalhes → + +
+ ); +} + +function TestimonialCard({ testimonial }) { + return ( +
+
+ "{testimonial.content}" +
+
+
+ {testimonial.avatar} +
+
+
{testimonial.name}
+
{testimonial.role}
+
+
+
+ ); +} + +export default function Portfolio() { + return ( +
+
+ {/* Projects Section */} +
+

+ Nossos Projetos +

+

+ Soluções inovadoras desenvolvidas com as melhores tecnologias +

+
+ +
+ {projects.map((project) => ( + + ))} +
+ + {/* Testimonials Section */} +
+

+ O que dizem sobre nós +

+
+ +
+ {testimonials.map((testimonial, index) => ( + + ))} +
+ + {/* CTA Section */} +
+

Pronto para inovar com a gente?

+

Entre em contato e vamos discutir seu próximo projeto

+
+ + Falar com a Equipe + + + Ver Documentação + +
+
+
+
+ ); +} \ No newline at end of file diff --git a/src/components/Portfolio/styles.module.css b/src/components/Portfolio/styles.module.css new file mode 100644 index 0000000..9315cc8 --- /dev/null +++ b/src/components/Portfolio/styles.module.css @@ -0,0 +1,257 @@ +.portfolio { + padding: 4rem 0; + background: white; +} + +.sectionTitle { + font-size: 2.5rem; + font-weight: 700; + margin-bottom: 0.5rem; + color: var(--ifm-color-primary); +} + +.sectionSubtitle { + font-size: 1.2rem; + color: var(--ifm-color-emphasis-600); + margin-bottom: 2rem; +} + +.projectsGrid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(350px, 1fr)); + gap: 2rem; + margin-bottom: 4rem; +} + +.projectCard { + background: #f8fafc; + border-radius: 16px; + padding: 2rem; + border: 1px solid #e2e8f0; + transition: all 0.3s ease; + position: relative; + overflow: hidden; +} + +.projectCard::before { + content: ''; + position: absolute; + top: 0; + left: 0; + right: 0; + height: 4px; + background: linear-gradient(90deg, var(--ifm-color-primary), var(--ifm-color-primary-light)); +} + +.projectCard:hover { + transform: translateY(-5px); + box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1); + border-color: var(--ifm-color-primary-light); +} + +.projectHeader { + display: flex; + justify-content: space-between; + align-items: center; + margin-bottom: 1.5rem; +} + +.projectIcon { + width: 50px; + height: 50px; + border-radius: 12px; + display: flex; + align-items: center; + justify-content: center; + font-size: 1.5rem; + color: white; +} + +.projectStatus { + background: var(--ifm-color-primary); + color: white; + padding: 0.25rem 0.75rem; + border-radius: 20px; + font-size: 0.8rem; + font-weight: 600; +} + +.projectTitle { + font-size: 1.5rem; + font-weight: 700; + margin-bottom: 1rem; + color: var(--ifm-color-emphasis-800); +} + +.projectDescription { + color: var(--ifm-color-emphasis-600); + line-height: 1.6; + margin-bottom: 1.5rem; +} + +.projectTech { + display: flex; + flex-wrap: wrap; + gap: 0.5rem; + margin-bottom: 1.5rem; +} + +.techTag { + background: var(--ifm-color-primary-lightest); + color: var(--ifm-color-primary); + padding: 0.25rem 0.75rem; + border-radius: 20px; + font-size: 0.8rem; + font-weight: 500; +} + +.projectLink { + color: var(--ifm-color-primary); + font-weight: 600; + text-decoration: none; + transition: all 0.3s ease; +} + +.projectLink:hover { + color: var(--ifm-color-primary-dark); + text-decoration: underline; +} + +.testimonialsGrid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); + gap: 2rem; + margin-bottom: 4rem; +} + +.testimonialCard { + background: linear-gradient(135deg, #f8fafc 0%, #ffffff 100%); + border-radius: 16px; + padding: 2rem; + border: 1px solid #e2e8f0; + position: relative; +} + +.testimonialCard::before { + content: '"'; + position: absolute; + top: 1rem; + left: 1.5rem; + font-size: 4rem; + color: var(--ifm-color-primary-light); + opacity: 0.3; + font-family: Georgia, serif; +} + +.testimonialQuote { + font-style: italic; + color: var(--ifm-color-emphasis-700); + line-height: 1.6; + margin-bottom: 1.5rem; + padding-left: 2rem; +} + +.testimonialAuthor { + display: flex; + align-items: center; + gap: 1rem; +} + +.authorAvatar { + width: 50px; + height: 50px; + border-radius: 50%; + background: var(--ifm-color-primary); + display: flex; + align-items: center; + justify-content: center; + font-size: 1.5rem; + color: white; +} + +.authorInfo { + flex: 1; +} + +.authorName { + font-weight: 600; + color: var(--ifm-color-emphasis-800); + margin-bottom: 0.25rem; +} + +.authorRole { + font-size: 0.9rem; + color: var(--ifm-color-emphasis-600); +} + +.ctaSection { + background: linear-gradient(135deg, var(--ifm-color-primary) 0%, var(--ifm-color-primary-dark) 100%); + border-radius: 16px; + padding: 3rem 2rem; + text-align: center; + color: white; +} + +.ctaSection h3 { + font-size: 2rem; + font-weight: 700; + margin-bottom: 1rem; +} + +.ctaSection p { + font-size: 1.1rem; + margin-bottom: 2rem; + opacity: 0.9; +} + +.ctaButtons { + display: flex; + gap: 1rem; + justify-content: center; + flex-wrap: wrap; +} + +.ctaSection .button--outline { + border-color: rgba(255, 255, 255, 0.8); + color: white; +} + +.ctaSection .button--outline:hover { + background: rgba(255, 255, 255, 0.1); + border-color: white; +} + +@media screen and (max-width: 768px) { + .sectionTitle { + font-size: 2rem; + } + + .projectsGrid { + grid-template-columns: 1fr; + } + + .testimonialsGrid { + grid-template-columns: 1fr; + } + + .projectCard { + padding: 1.5rem; + } + + .testimonialCard { + padding: 1.5rem; + } + + .ctaSection { + padding: 2rem 1.5rem; + } + + .ctaSection h3 { + font-size: 1.5rem; + } + + .ctaButtons { + flex-direction: column; + align-items: center; + } +} \ No newline at end of file diff --git a/src/components/TechStack/index.js b/src/components/TechStack/index.js new file mode 100644 index 0000000..b8a69ee --- /dev/null +++ b/src/components/TechStack/index.js @@ -0,0 +1,102 @@ +import React, { useState } from 'react'; +import clsx from 'clsx'; +import styles from './styles.module.css'; + +const techStack = [ + { + name: 'TypeScript', + icon: '🔷', + description: 'Linguagem tipada para desenvolvimento robusto', + color: '#3178c6' + }, + { + name: 'Flutter', + icon: '📱', + description: 'Framework para desenvolvimento mobile multiplataforma', + color: '#02569B' + }, + { + name: 'Convex', + icon: '⚡', + description: 'Backend-as-a-Service para aplicações realtime', + color: '#FF6B35' + }, + { + name: 'Coolify', + icon: '🚀', + description: 'Plataforma de deploy e gerenciamento de aplicações', + color: '#4F46E5' + }, + { + name: 'Docker', + icon: '🐳', + description: 'Containerização para ambientes consistentes', + color: '#2496ED' + }, + { + name: 'React', + icon: '⚛️', + description: 'Biblioteca para interfaces web interativas', + color: '#61DAFB' + } +]; + +function TechCard({ tech, isActive, onClick }) { + return ( +
+
+ {tech.icon} +
+

{tech.name}

+ {isActive && ( +

{tech.description}

+ )} +
+ ); +} + +export default function TechStack() { + const [activeTech, setActiveTech] = useState(0); + + return ( +
+
+
+

+ Nossa Stack Tecnológica +

+

+ Tecnologias modernas que impulsionam nossas soluções +

+
+ +
+ {techStack.map((tech, index) => ( + setActiveTech(index)} + /> + ))} +
+ +
+
+
+ {techStack[activeTech].icon} +
+
+

{techStack[activeTech].name}

+

{techStack[activeTech].description}

+
+
+
+
+
+ ); +} \ No newline at end of file diff --git a/src/components/TechStack/styles.module.css b/src/components/TechStack/styles.module.css new file mode 100644 index 0000000..205be0a --- /dev/null +++ b/src/components/TechStack/styles.module.css @@ -0,0 +1,166 @@ +.techStack { + padding: 4rem 0; + background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%); +} + +.sectionTitle { + font-size: 2.5rem; + font-weight: 700; + margin-bottom: 0.5rem; + color: var(--ifm-color-primary); +} + +.sectionSubtitle { + font-size: 1.2rem; + color: var(--ifm-color-emphasis-600); + margin-bottom: 2rem; +} + +.techGrid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); + gap: 1.5rem; + margin-bottom: 3rem; +} + +.techCard { + background: white; + border-radius: 12px; + padding: 1.5rem; + text-align: center; + cursor: pointer; + transition: all 0.3s ease; + box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); + border: 2px solid transparent; + position: relative; + overflow: hidden; +} + +.techCard::before { + content: ''; + position: absolute; + top: 0; + left: 0; + right: 0; + bottom: 0; + background: linear-gradient(135deg, var(--tech-color), transparent); + opacity: 0; + transition: opacity 0.3s ease; +} + +.techCard:hover { + transform: translateY(-5px); + box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15); +} + +.techCard:hover::before { + opacity: 0.1; +} + +.techCard.active { + border-color: var(--tech-color); + box-shadow: 0 8px 25px rgba(0, 0, 0, 0.2); +} + +.techCard.active::before { + opacity: 0.15; +} + +.techIcon { + font-size: 2.5rem; + margin-bottom: 1rem; + transition: transform 0.3s ease; +} + +.techCard:hover .techIcon { + transform: scale(1.1); +} + +.techName { + font-size: 1.2rem; + font-weight: 600; + margin-bottom: 0.5rem; + color: var(--ifm-color-emphasis-800); +} + +.techDescription { + font-size: 0.9rem; + color: var(--ifm-color-emphasis-600); + margin: 0; + opacity: 0; + animation: fadeIn 0.3s ease forwards; +} + +@keyframes fadeIn { + from { + opacity: 0; + transform: translateY(10px); + } + to { + opacity: 1; + transform: translateY(0); + } +} + +.activeTechDisplay { + display: flex; + justify-content: center; +} + +.activeTechCard { + background: white; + border-radius: 16px; + padding: 2rem; + display: flex; + align-items: center; + gap: 2rem; + box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1); + border: 2px solid var(--ifm-color-primary); + max-width: 600px; + width: 100%; +} + +.activeTechIcon { + font-size: 3rem; + flex-shrink: 0; +} + +.activeTechInfo h3 { + font-size: 1.5rem; + font-weight: 700; + margin-bottom: 0.5rem; + color: var(--ifm-color-primary); +} + +.activeTechInfo p { + font-size: 1rem; + color: var(--ifm-color-emphasis-600); + margin: 0; + line-height: 1.5; +} + +@media screen and (max-width: 768px) { + .sectionTitle { + font-size: 2rem; + } + + .techGrid { + grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); + gap: 1rem; + } + + .techCard { + padding: 1rem; + } + + .activeTechCard { + flex-direction: column; + text-align: center; + gap: 1rem; + padding: 1.5rem; + } + + .activeTechIcon { + font-size: 2.5rem; + } +} \ No newline at end of file diff --git a/src/css/custom.css b/src/css/custom.css index 2bc6a4c..24e1d37 100644 --- a/src/css/custom.css +++ b/src/css/custom.css @@ -6,25 +6,239 @@ /* You can override the default Infima variables here. */ :root { - --ifm-color-primary: #2e8555; - --ifm-color-primary-dark: #29784c; - --ifm-color-primary-darker: #277148; - --ifm-color-primary-darkest: #205d3b; - --ifm-color-primary-light: #33925d; - --ifm-color-primary-lighter: #359962; - --ifm-color-primary-lightest: #3cad6e; + --ifm-color-primary: #4f46e5; + --ifm-color-primary-dark: #4338ca; + --ifm-color-primary-darker: #3b32a4; + --ifm-color-primary-darkest: #2d2478; + --ifm-color-primary-light: #6366f1; + --ifm-color-primary-lighter: #7c3aed; + --ifm-color-primary-lightest: #a78bfa; --ifm-code-font-size: 95%; --docusaurus-highlighted-code-line-bg: rgba(0, 0, 0, 0.1); } /* For readability concerns, you should choose a lighter palette in dark mode. */ [data-theme='dark'] { - --ifm-color-primary: #25c2a0; - --ifm-color-primary-dark: #21af90; - --ifm-color-primary-darker: #1fa588; - --ifm-color-primary-darkest: #1a8870; - --ifm-color-primary-light: #29d5b0; - --ifm-color-primary-lighter: #32d8b4; - --ifm-color-primary-lightest: #4fddbf; + --ifm-color-primary: #818cf8; + --ifm-color-primary-dark: #6366f1; + --ifm-color-primary-darker: #4f46e5; + --ifm-color-primary-darkest: #3730a3; + --ifm-color-primary-light: #a5b4fc; + --ifm-color-primary-lighter: #c7d2fe; + --ifm-color-primary-lightest: #e0e7ff; --docusaurus-highlighted-code-line-bg: rgba(0, 0, 0, 0.3); } + +/* Custom animations and effects */ +@keyframes fadeInUp { + from { + opacity: 0; + transform: translateY(30px); + } + to { + opacity: 1; + transform: translateY(0); + } +} + +@keyframes pulse { + 0%, 100% { + transform: scale(1); + } + 50% { + transform: scale(1.05); + } +} + +@keyframes gradientShift { + 0% { + background-position: 0% 50%; + } + 50% { + background-position: 100% 50%; + } + 100% { + background-position: 0% 50%; + } +} + +.hero--primary { + background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); + background-size: 400% 400%; + animation: gradientShift 8s ease infinite; + position: relative; + overflow: hidden; +} + +.hero--primary::before { + content: ''; + position: absolute; + top: 0; + left: 0; + right: 0; + bottom: 0; + background: url('data:image/svg+xml,'); + opacity: 0.3; + pointer-events: none; +} + +.hero__title { + animation: fadeInUp 1s ease-out; + font-weight: 700; + text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3); +} + +.hero__subtitle { + animation: fadeInUp 1s ease-out 0.2s both; + opacity: 0.9; +} + +.button--secondary { + animation: fadeInUp 1s ease-out 0.4s both; + transition: all 0.3s ease; + box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2); +} + +.button--secondary:hover { + transform: translateY(-2px); + box-shadow: 0 6px 20px rgba(0, 0, 0, 0.3); +} + +.features { + animation: fadeInUp 1s ease-out 0.6s both; +} + +.featureSvg { + transition: transform 0.3s ease; +} + +.featureSvg:hover { + transform: scale(1.1) rotate(5deg); +} + +.navbar__logo { + transition: transform 0.3s ease; +} + +.navbar__logo:hover { + transform: scale(1.05); +} + +/* Custom gradient text effect */ +.gradient-text { + background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); + -webkit-background-clip: text; + -webkit-text-fill-color: transparent; + background-clip: text; + animation: gradientShift 3s ease infinite; +} + +/* Modern card hover effects */ +.card { + transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); + border-radius: 12px; +} + +.card:hover { + transform: translateY(-4px); + box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1); +} + +/* Enhanced button styles */ +.button { + border-radius: 8px; + font-weight: 600; + transition: all 0.3s ease; + position: relative; + overflow: hidden; +} + +.button::before { + content: ''; + position: absolute; + top: 0; + left: -100%; + width: 100%; + height: 100%; + background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent); + transition: left 0.5s; +} + +.button:hover::before { + left: 100%; +} + +/* Glass morphism effect */ +.glass-effect { + background: rgba(255, 255, 255, 0.1); + backdrop-filter: blur(10px); + border: 1px solid rgba(255, 255, 255, 0.2); +} + +/* Floating animation */ +@keyframes float { + 0%, 100% { + transform: translateY(0px); + } + 50% { + transform: translateY(-10px); + } +} + +.float-animation { + animation: float 3s ease-in-out infinite; +} + +/* Pulse glow effect */ +@keyframes pulseGlow { + 0%, 100% { + box-shadow: 0 0 20px rgba(79, 70, 229, 0.3); + } + 50% { + box-shadow: 0 0 30px rgba(79, 70, 229, 0.6); + } +} + +.glow-effect { + animation: pulseGlow 2s ease-in-out infinite; +} + +/* Modern scrollbar */ +::-webkit-scrollbar { + width: 8px; +} + +::-webkit-scrollbar-track { + background: #f1f5f9; +} + +::-webkit-scrollbar-thumb { + background: linear-gradient(135deg, #4f46e5, #7c3aed); + border-radius: 4px; +} + +::-webkit-scrollbar-thumb:hover { + background: linear-gradient(135deg, #3730a3, #581c87); +} + +/* Enhanced focus states */ +*:focus { + outline: 2px solid var(--ifm-color-primary); + outline-offset: 2px; +} + +/* Loading animation */ +@keyframes shimmer { + 0% { + background-position: -200px 0; + } + 100% { + background-position: calc(200px + 100%) 0; + } +} + +.shimmer { + background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%); + background-size: 200px 100%; + animation: shimmer 1.5s infinite; +} diff --git a/src/pages/index.js b/src/pages/index.js index a8c61f2..b9c8df8 100644 --- a/src/pages/index.js +++ b/src/pages/index.js @@ -3,6 +3,8 @@ import Link from '@docusaurus/Link'; import useDocusaurusContext from '@docusaurus/useDocusaurusContext'; import Layout from '@theme/Layout'; import HomepageFeatures from '@site/src/components/HomepageFeatures'; +import TechStack from '@site/src/components/TechStack'; +import Portfolio from '@site/src/components/Portfolio'; import Heading from '@theme/Heading'; import styles from './index.module.css'; @@ -13,14 +15,28 @@ function HomepageHeader() {
- {siteConfig.title} + Bem-vindo à MonaDocs -

{siteConfig.tagline}

+

+ Documentação central da Monynha Softwares - Inovando com tecnologia +

+
+

+ Explore nossa documentação completa sobre projetos inovadores, + tecnologias avançadas e padrões de desenvolvimento que impulsionam + soluções digitais de ponta. +

+
- Docusaurus Tutorial - 5min ⏱️ + 🚀 Explorar Documentação + + + 🌐 Visitar Website
@@ -32,11 +48,13 @@ export default function Home() { const {siteConfig} = useDocusaurusContext(); return ( + title={`MonaDocs - Documentação Monynha Softwares`} + description="Documentação central contendo guias, padrões e informações sobre projetos, tecnologias e processos da Monynha Softwares">
+ +
); diff --git a/src/pages/index.module.css b/src/pages/index.module.css index 9f71a5d..9486550 100644 --- a/src/pages/index.module.css +++ b/src/pages/index.module.css @@ -3,6 +3,7 @@ * and scoped locally. */ +/* Refactored CSS for better readability and maintainability */ .heroBanner { padding: 4rem 0; text-align: center; @@ -10,14 +11,46 @@ overflow: hidden; } +.heroDescription { + max-width: 600px; + margin: 1.5rem auto; + font-size: 1.1rem; + line-height: 1.6; + opacity: 0.9; +} + +.heroDescription p { + margin-bottom: 0; +} + @media screen and (max-width: 996px) { .heroBanner { padding: 2rem; } + + .heroDescription { + font-size: 1rem; + margin: 1rem auto; + } } .buttons { display: flex; align-items: center; justify-content: center; + gap: 1rem; + flex-wrap: wrap; +} + +.button--outline { + border: 2px solid rgba(255, 255, 255, 0.8); + color: white; + background: transparent; + transition: all 0.3s ease; +} + +.button--outline:hover { + background: rgba(255, 255, 255, 0.1); + border-color: white; + transform: translateY(-2px); } diff --git a/static/img/favicon.svg b/static/img/favicon.svg new file mode 100644 index 0000000..a7176e8 --- /dev/null +++ b/static/img/favicon.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/static/img/logo.svg b/static/img/logo.svg index 9db6d0d..c034809 100644 --- a/static/img/logo.svg +++ b/static/img/logo.svg @@ -1 +1,17 @@ - \ No newline at end of file +