Peso SaaS Monorepo Development Rules
Comprehensive development guidelines for maintaining consistency across the Peso SaaS monorepo project.
Architecture Overview
This skill enforces best practices for a multi-component monorepo with:
**Backend**: FastAPI/Python with SQLAlchemy**Frontend**: Vue.js 3 with Composition API**Mobile**: React Native/Ionic**Infrastructure**: Docker, AWS, TerraformGeneral Rules
Monorepo Structure
1. Maintain strict separation: `backend/`, `frontend/`, `mobile-app/`, `infra/`
2. Each module must be autonomous with its own dependencies
3. Use relative imports between modules
4. Clear separation of responsibilities
Naming Conventions
**Python files**: snake_case (e.g., `user_service.py`)**JavaScript/Vue files**: camelCase or PascalCase (e.g., `userService.js`, `WeightEntry.vue`)**Folders**: kebab-case (e.g., `mobile-app/`, `weight-entries/`)**Modals**: Always in `components/Modal/` directory**Variables**: snake_case (Python), camelCase (JavaScript)**Constants**: UPPER_SNAKE_CASE**Classes**: PascalCase in all languagesDocumentation
All comments in **English**Document all public functions with docstringsMaintain README.md files in each directoryUse emojis for documentation readabilityBackend (FastAPI/Python)
Import Order
```python
1. Standard library
import os
from typing import Optional
2. Third-party packages
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
3. Local imports
from app.core.database import get_db
from app.models.user import User
```
SQLAlchemy Models
Always inherit from BaseAdd indexes on frequently searched fieldsDefine `nullable=False` for required fieldsUse relationship() for associationsPydantic Schemas
Separate schemas: Create, Update, ResponseAll Update fields must be OptionalUse `from_attributes = True` for SQLAlchemy 2.0 compatibilityValidate email with EmailStrService Layer
Business logic belongs in services, not routesServices receive db session in __init__Return domain models, not dictionariesValidate business rules before database operationsAPI Routes
Use consistent prefixes (e.g., `/api/v1/users`)Specify response_model and status_codeUse dependencies for authenticationTag routes appropriatelyError Handling
Use HTTPException with appropriate status codesProvide clear, user-friendly error messagesLog internal errors server-sideNever expose sensitive data in error responsesTesting
Structure tests: Arrange, Act, AssertUse fixtures for test dataTest client from fastapi.testclientTest both success and failure casesAlembic Migrations
Create migrations for all schema changesUse descriptive migration namesReview auto-generated migrations before applyingFrontend (Vue.js)
Component Structure
```vue
<template>
<!-- Template first -->
</template>
<script>
// Script second (Composition API)
</script>
<style scoped>
/* Styles last, always scoped */
</style>
```
Pinia Stores
Use Composition API syntaxState as ref()Getters as computed()Actions as async functionsReturn all public propertiesAPI Services
Centralize API calls in service filesUse axios with base configurationImplement request/response interceptorsHandle authentication tokens automaticallyVue Router
Use lazy loading for route componentsImplement navigation guards for authDefine meta fields for route requirementsUse named routesReusable Components
Always validate props with typesUse validator functions for constrained valuesDocument emitted eventsProvide sensible defaultsModal Structure
Place modals in `components/Modal/`Standard structure: header, body, actionsEmit close and submit eventsHandle overlay click to closeStyling
Use Tailwind CSS utility classesScoped styles for component-specific CSSConsistent spacing and color paletteMobile-first responsive designMobile (React Native)
Component Structure
Use functional components with hooksExtract logic into custom hooksStyleSheet.create for stylesConditional rendering for loading statesCustom Hooks
Prefix with "use"Return object with data, loading, errorImplement refetch functionalityHandle cleanup with useEffectNavigation
React Navigation for routingStack, Tab, or Drawer navigatorsConfigure screen optionsType-safe navigation paramsLocal Storage
Use AsyncStorage for persistenceWrap in utility functionsHandle errors gracefullyClear sensitive data on logoutInfrastructure
Dockerfiles
Multi-stage builds to minimize image sizeUse alpine variants when possibleCopy only necessary filesSet appropriate working directoryDocker Compose
Define health checks for all servicesUse depends_on with conditionsEnvironment variables for configurationNamed volumes for persistenceEnvironment Variables
Prefix with service nameProvide secure defaultsNever commit secretsDocument all variablesTerraform
Use reusable modulesTag all resources with environment and projectUse variables for configurable valuesMaintain state files securelyTesting
Backend Tests (Pytest)
Use fixtures for test dataTest both success and error casesMock external dependenciesAim for high coverageFrontend Tests (Vitest)
Unit tests for componentsTest user interactionsMock API callsTest computed properties and watchersSecurity
Authentication
JWT with expirationRefresh token mechanismServer-side token validationHTTPS in productionData Validation
Validate all user inputsPydantic for backend validationSanitize before storageUse parameterized queries (SQLAlchemy ORM)Secret Management
Never commit secretsUse environment variablesBcrypt for password hashingUse secret managers in productionGit Workflow
Commit Messages
Format: `type(scope): description`Types: feat, fix, docs, style, refactor, test, choreKeep under 72 charactersReference issues when applicableBranch Strategy
main: production-ready codedevelop: integration branchfeature/*: new featuresfix/*: bug fixeshotfix/*: urgent production fixesInstructions
1. **Before making changes**: Review relevant section of these rules
2. **Code structure**: Follow the patterns shown in examples
3. **Naming**: Apply appropriate naming convention for language/framework
4. **Testing**: Write tests for new functionality
5. **Documentation**: Update README files and add docstrings
6. **Security**: Validate inputs, handle secrets properly
7. **Commits**: Use conventional commit format
8. **Review**: Check code matches project conventions before committing
Common Patterns
Adding a New API Endpoint
1. Define Pydantic schemas (Create, Update, Response)
2. Create or update SQLAlchemy model
3. Implement service method with business logic
4. Add route with proper dependencies
5. Write tests for success and error cases
6. Update API documentation
Creating a New Vue Component
1. Define component in appropriate directory
2. Use Composition API with setup()
3. Validate props with types
4. Add scoped styles or Tailwind classes
5. Document emitted events
6. Write unit tests
Database Schema Changes
1. Modify SQLAlchemy model in schema.ts
2. Generate migration: `alembic revision --autogenerate -m "description"`
3. Review migration file
4. Apply migration: `alembic upgrade head`
5. Update Pydantic schemas if needed
Notes
All code comments must be in EnglishMaintain consistency within each modulePrefer composition over inheritanceKeep functions small and focusedTest edge cases and error conditionsDocument non-obvious decisionsReview security implications of changes