Professional Frappe Framework v15 development toolkit with multi-layer architecture patterns, DocType scaffolding, REST API v2, and testing

version
1.0.0
GitHub stars
16

Install

/plugin install frappe-dev@bershadsky-claude-tools

Run it inside Claude Code after adding the marketplace with /plugin marketplace add sergio-bershadsky/ai.

Contents

Discovered from source

Skills 5

Frappe REST API Development

Create secure, well-documented REST API endpoints for Frappe Framework v15 following best practices for authentication, permission checking, and input validation.

When to Use

  • Building custom REST API endpoints
  • Exposing service layer methods via HTTP
  • Creating public/private API routes
  • Implementing webhook handlers
  • Building integrations with external systems

Arguments

/frappe-api <endpoint_name> [--doctype <doctype>] [--public]

Examples:

/frappe-api get_dashboard_stats
/frappe-api create_order --doctype "Sales Order"
/frappe-api webhook_handler --public

Procedure

Step 1: Gather API Requirements

Ask the user for:

  1. Endpoint Name (snake_case, e.g., get_dashboard_stats)
  2. HTTP Methods supported (GET, POST, PUT, DELETE)
  3. Authentication Type:
    • Token (API Key + Secret)
    • Session (Cookie-based)
    • OAuth 2.0
    • Public (no auth required - use sparingly)
  4. Parameters - Input parameters with types
  5. Related DocType (if applicable)
  6. Allowed Roles (who can access this endpoint)

Step 2: Design API Contract

Create the API specification:

Endpoint: /api/method/<app>.<module>.api.<endpoint_name>
Methods: GET, POST
Auth: Token | Session
Rate Limit: 100 req/min (if applicable)

Parameters:
  - name: param1
    type: string
    required: true
    description: Description of param1
  - name: param2
    type: integer
    required: false
    default: 10

Response:
  200:
    description: Success
    schema:
      message: object
  400:
    description: Validation Error
  403:
    description: Permission Denied

Step 3: Generate API Module Structure

Create <app>/<module>/api/<endpoint_name>.py:

"""
<Endpoint Name> API

<Brief description of what this API does>

Endpoints:
    GET/POST /api/method/<app>.<module>.api.<endpoint_name>.<method_name>

Authentication:
    Token: Authorization: token api_key:api_secret
    Session: Cookie-based after login

Example:
    curl -X POST "https://site.com/api/method/<app>.<module>.api.<endpoint_name>.create" \
        -H "Authorization: token api_key:api_secret" \
        -H "Content-Type: application/json" \
        -d '{"title": "Test"}'
"""

import frappe
from frappe import _
from frappe.utils import cint, cstr, flt
from typing import Optional, Any
from <app>.<module>.services.<service>_service import <Service>Service


# ──────────────────────────────────────────────────────────────────────────────
# API Endpoints
#
# v15 TYPE ANNOTATION VALIDATION:
# Frappe v15 automatically validates function parameter types based on
# Python type hints. For example, if you declare `limit: int`, passing
# a non-integer will raise a validation error automatically.
#
# TRANSACTION HANDLING:
# Frappe automatically commits on successful POST/PUT requests and
# rolls back on exceptions. Manual frappe.db.commit() is rarely needed.
# ──────────────────────────────────────────────────────────────────────────────

@frappe.whitelist()
def get(name: str) -> dict:
    """
    Get single document by name.

    Args:
        name: Document name/ID

    Returns:
        Document data

    Raises:
        frappe.DoesNotExistError: Document not found
        frappe.PermissionError: No read permission

    Example:
        GET /api/method/<app>.<module>.api.<endpoint>.get?name=DOC-00001
    """
    _check_permission("<DocType>", "read")

    service = <Service>Service()
    return {
        "success": True,
        "data": service.get(name)
    }


@frappe.whitelist()
def get_list(
    status: Optional[str] = None,
    limit: int = 20,
    offset: int = 0
) -> dict:
    """
    Get list of documents with optional filtering.

    Args:
        status: Filter by status
        limit: Maximum records to return (default: 20, max: 100)
        offset: Skip N records for pagination

    Returns:
        List of documents with pagination info

    Example:
        GET /api/method/<app>.<module>.api.<endpoint>.get_list?status=Draft&limit=10
    """
    _check_permission("<DocType>", "read")

    # Validate and sanitize inputs
    limit = min(cint(limit) or 20, 100)  # Cap at 100
    offset = max(cint(offset), 0)

    service = <Service>Service()
    filters = {}
    if status:
        filters["status"] = status

    data = service.repo.get_list(
        filters=filters,
        fields=["name", "title", "status", "date", "modified"],
        limit=limit,
        offset=offset
    )
    total = service.repo.get_count(filters)

    return {
        "success": True,
        "data": data,
        "pagination": {
            "total": total,
            "limit": limit,
            "offset": offset,
            "has_more": (offset + limit) < total
        }
    }


@frappe.whitelist(methods=["POST"])
def create(
    title: str,
    date: Optional[str] = None,
    description: Optional[str] = None
) -> dict:
    """
    Create new document.

    Args:
        title: Document title (required)
        date: Date in YYYY-MM-DD format
        description: Optional description

    Returns:
        Created document data

    Raises:
        frappe.ValidationError: Invalid input data
        frappe.PermissionError: No create permission

    Example:
        POST /api/method/<app>.<module>.api.<endpoint>.create
        Body: {"title": "New Document", "date": "2024-01-15"}
    """
    _check_permission("<DocType>", "create")

    # Validate required fields
    if not title or not cstr(title).strip():
        frappe.throw(_("Title is required"), frappe.ValidationError)

    service = <Service>Service()
    result = service.create({
        "title": cstr(title).strip(),
        "date": date or frappe.utils.today(),
        "description": description
    })

    frappe.db.commit()

    return {
        "success": True,
        "message": _("Document created successfully"),
        "data": result
    }


@frappe.whitelist(methods=["PUT", "POST"])
def update(
    name: str,
    title: Optional[str] = None,
    status: Optional[str] = None,
    description: Optional[str] = None
) -> dict:
    """
    Update existing document.

    Args:
        name: Document name (required)
        title: New title
        status: New status
        description: New description

    Returns:
        Updated document data

    Example:
        PUT /api/method/<app>.<module>.api.<endpoint>.update
        Body: {"name": "DOC-00001", "title": "Updated Title"}
    """
    _check_permission("<DocType>", "write")

    if not name:
        frappe.throw(_("Document name is required"), frappe.ValidationError)

    # Build update data from provided fields
    update_data = {}
    if title is not None:
        update_data["title"] = cstr(title).strip()
    if status is not None:
        update_data["status"] = status
    if description is not None:
        update_data["description"] = description

    if not update_data:
        frappe.throw(_("No fields to update"), frappe.ValidationError)

    service = <Service>Service()
    result = service.update(name, update_data)

    frappe.db.commit()

    return {
        "success": True,
        "message": _("Document updated successfully"),
        "data": result
    }


@frappe.whitelist(methods=["DELETE", "POST"])
def delete(name: str) -> dict:
    """
    Delete document.

    Args:
        name: Document name to delete

    Returns:
        Success confirmation

    Example:
        DELETE /api/method/<app>.<module>.api.<endpoint>.delete?name=DOC-00001
    """
    _check_permission("<DocType>", "delete")

    if not name:
        frappe.throw(_("Document name is required"), frappe.ValidationError)

    service = <Service>Service()
    service.repo.delete(name)

    frappe.db.commit()

    return {
        "success": True,
        "message": _("Document deleted successfully")
    }


@frappe.whitelist(methods=["POST"])
def submit(name: str) -> dict:
    """
    Submit document for processing.

    Args:
        name: Document name to submit

    Returns:
        Submitted document data

    Example:
        POST /api/method/<app>.<module>.api.<endpoint>.submit
        Body: {"name": "DOC-00001"}
    """
    _check_permission("<DocType>", "submit")

    service = <Service>Service()
    result = service.submit(name)

    frappe.db.commit()

    return {
        "success": True,
        "message": _("Document submitted successfully"),
        "data": result
    }


@frappe.whitelist(methods=["POST"])
def cancel(name: str, reason: Optional[str] = None) -> dict:
    """
    Cancel submitted document.

    Args:
        name: Document name to cancel
        reason: Cancellation reason

    Returns:
        Cancelled document data

    Example:
        POST /api/method/<app>.<module>.api.<endpoint>.cancel
        Body: {"name": "DOC-00001", "reason": "Customer request"}
    """
    _check_permission("<DocType>", "cancel")

    service = <Service>Service()
    result = service.cancel(name, reason)

    frappe.db.commit()

    return {
        "success": True,
        "message": _("Document cancelled successfully"),
        "data": result
    }


# ──────────────────────────────────────────────────────────────────────────────
# Bulk Operations
# ──────────────────────────────────────────────────────────────────────────────

@frappe.whitelist(methods=["POST"])
def bulk_update_status(names: list[str], status: str) -> dict:
    """
    Bulk update status for multiple documents.

    Args:
        names: List of document names
        status: New status to set

    Returns:
        Number of documents updated

    Example:
        POST /api/method/<app>.<module>.api.<endpoint>.bulk_update_status
        Body: {"names": ["DOC-001", "DOC-002"], "status": "Completed"}
    """
    _check_permission("<DocType>", "write")

    if not names or not isinstance(names, list):
        frappe.throw(_("Names must be a non-empty list"), frappe.ValidationError)

    valid_statuses = ["Draft", "Pending", "Completed", "Cancelled"]
    if status not in valid_statuses:
        frappe.throw(
            _("Invalid status. Must be one of: {0}").format(", ".join(valid_statuses)),
            frappe.ValidationError
        )

    service = <Service>Service()
    count = service.repo.bulk_update_status(names, status)

    frappe.db.commit()

    return {
        "success": True,
        "message": _("{0} documents updated").format(count),
        "data": {"updated_count": count}
    }


# ──────────────────────────────────────────────────────────────────────────────
# Helper Functions
# ──────────────────────────────────────────────────────────────────────────────

def _check_permission(doctype: str, ptype: str, doc: Any = None) -> None:
    """
    Check if current user has permission.

    Args:
        doctype: DocType to check
        ptype: Permission type (read, write, create, delete, submit, cancel)
        doc: Optional specific document

    Raises:
        frappe.PermissionError: If permission denied
    """
    if not frappe.has_permission(doctype, ptype, doc=doc):
        frappe.throw(
            _("You don't have permission to {0} {1}").format(ptype, doctype),
            frappe.PermissionError
        )


def _validate_request_data(data: dict, required: list[str]) -> None:
    """
    Validate request data has required fields.

    Args:
        data: Request data dict
        required: List of required field names

    Raises:
        frappe.ValidationError: If required fields missing
    """
    missing = [f for f in required if not data.get(f)]
    if missing:
        frappe.throw(
            _("Missing required fields: {0}").format(", ".join(missing)),
            frappe.ValidationError
        )


# ──────────────────────────────────────────────────────────────────────────────
# Public Endpoints (No Auth Required - Use with Caution!)
# ──────────────────────────────────────────────────────────────────────────────

@frappe.whitelist(allow_guest=True)
def ping() -> dict:
    """
    Health check endpoint (public).

    Returns:
        Server status

    Example:
        GET /api/method/<app>.<module>.api.<endpoint>.ping
    """
    return {
        "success": True,
        "message": "pong",
        "timestamp": frappe.utils.now()
    }

Step 4: Generate API v2 Endpoints (Optional)

For v2 REST API pattern, create custom routes in hooks.py:

# hooks.py

# Override standard DocType REST endpoints
override_doctype_dashboards = {
    "<DocType>": "<app>.<module>.api.<endpoint>.get_doctype_dashboard"
}

# Custom website routes for cleaner URLs
website_route_rules = [
    {"from_route": "/api/v2/<app>/<endpoint>", "to_route": "<app>.<module>.api.<endpoint>.handle_v2"},
]

Step 5: Generate API Tests

Create <app>/<module>/api/test_<endpoint_name>.py:

"""
Tests for <Endpoint Name> API
"""

import frappe
from frappe.tests import IntegrationTestCase


class TestAPI<EndpointName>(IntegrationTestCase):
    """API integration tests."""

    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        cls.test_user = cls._create_test_user()
        cls.test_doc = cls._create_test_document()

    @classmethod
    def _create_test_user(cls):
        """Create test user with API access."""
        if frappe.db.exists("User", "test_api@example.com"):
            return frappe.get_doc("User", "test_api@example.com")

        user = frappe.get_doc({
            "doctype": "User",
            "email": "test_api@example.com",
            "first_name": "Test",
            "last_name": "API User",
            "send_welcome_email": 0
        }).insert(ignore_permissions=True)
        user.add_roles("System Manager")
        return user

    @classmethod
    def _create_test_document(cls):
        """Create test document."""
        return frappe.get_doc({
            "doctype": "<DocType>",
            "title": "API Test Document",
            "date": frappe.utils.today()
        }).insert()

    def test_get_returns_document(self):
        """Test GET endpoint returns document."""
        from <app>.<module>.api.<endpoint_name> import get

        frappe.set_user(self.test_user.name)
        result = get(self.test_doc.name)

        self.assertTrue(result.get("success"))
        self.assertIsNotNone(result.get("data"))

    def test_get_list_with_pagination(self):
        """Test GET list with pagination."""
        from <app>.<module>.api.<endpoint_name> import get_list

        frappe.set_user(self.test_user.name)
        result = get_list(limit=5, offset=0)

        self.assertTrue(result.get("success"))
        self.assertIn("pagination", result)
        self.assertLessEqual(len(result["data"]), 5)

    def test_create_validates_input(self):
        """Test CREATE validates required fields."""
        from <app>.<module>.api.<endpoint_name> import create

        frappe.set_user(self.test_user.name)

        with self.assertRaises(frappe.ValidationError):
            create(title="")  # Empty title should fail

    def test_create_returns_document(self):
        """Test CREATE returns new document."""
        from <app>.<module>.api.<endpoint_name> import create

        frappe.set_user(self.test_user.name)
        result = create(title="New Test Doc", date=frappe.utils.today())

        self.assertTrue(result.get("success"))
        self.assertIsNotNone(result["data"].get("name"))

    def test_unauthorized_access_denied(self):
        """Test unauthenticated access is denied."""
        from <app>.<module>.api.<endpoint_name> import get

        frappe.set_user("Guest")

        with self.assertRaises(frappe.PermissionError):
            get(self.test_doc.name)

    def test_ping_public_access(self):
        """Test ping endpoint is publicly accessible."""
        from <app>.<module>.api.<endpoint_name> import ping

        frappe.set_user("Guest")
        result = ping()

        self.assertTrue(result.get("success"))
        self.assertEqual(result.get("message"), "pong")

Step 6: Show API Documentation Preview

## API Endpoint Preview

**Module:** <app>.<module>.api.<endpoint_name>
**Base URL:** /api/method/<app>.<module>.api.<endpoint_name>

### Endpoints:

| Method | Endpoint | Auth | Description |
|--------|----------|------|-------------|
| GET | .get | Token/Session | Get single document |
| GET | .get_list | Token/Session | List with pagination |
| POST | .create | Token/Session | Create document |
| PUT | .update | Token/Session | Update document |
| DELETE | .delete | Token/Session | Delete document |
| POST | .submit | Token/Session | Submit for processing |
| POST | .cancel | Token/Session | Cancel document |
| POST | .bulk_update_status | Token/Session | Bulk status update |
| GET | .ping | Public | Health check |

### Authentication:

```bash
# Token auth (recommended for integrations)
curl -H "Authorization: token api_key:api_secret" \
     https://site.com/api/method/<endpoint>

# Session auth (for browser clients)
# First login, then use session cookie

Files to Create:

📁 /api/ ├── 📄 init.py ├── 📄 <endpoint_name>.py └── 📄 test_<endpoint_name>.py


Create this API module?


### Step 7: Execute and Verify

After approval, create files and run tests:

```bash
bench --site <site> run-tests --module "<app>.<module>.api.test_<endpoint_name>"

Output Format

## API Created

**Module:** <app>.<module>.api.<endpoint_name>
**Endpoints:** 9

### Files Created:
- ✅ <endpoint_name>.py (API endpoints)
- ✅ test_<endpoint_name>.py (API tests)
- ✅ Updated __init__.py

### cURL Examples:

```bash
# Get document
curl -X GET "https://site.com/api/method/<app>.<module>.api.<endpoint>.get?name=DOC-001" \
     -H "Authorization: token api_key:api_secret"

# Create document
curl -X POST "https://site.com/api/method/<app>.<module>.api.<endpoint>.create" \
     -H "Authorization: token api_key:api_secret" \
     -H "Content-Type: application/json" \
     -d '{"title": "New Document"}'

Next Steps:

  1. Create API keys: Setup > User > API Access
  2. Test endpoints with curl or Postman
  3. Run API tests: bench --site <site> run-tests --module <test_module>

## Rules

1. **Always Check Permissions** — Every endpoint must call `_check_permission()` first
2. **Validate All Input** — Never trust user input, validate and sanitize everything
3. **Type Annotations** — Use Python type hints for v15 auto-validation
4. **Transaction Handling** — Frappe auto-commits on successful requests; manual `frappe.db.commit()` rarely needed except in background jobs
5. **Public Endpoints** — Use `allow_guest=True` sparingly, only for truly public data
6. **Error Handling** — Use `frappe.throw()` with appropriate exception types
7. **Documentation** — Every endpoint must have docstring with Args/Returns/Example
8. **ALWAYS Confirm** — Never create files without explicit user approval

Frappe App Scaffolding

Create a professional Frappe Framework v15 application with multi-layer architecture following enterprise best practices.

When to Use

  • Starting a new Frappe/ERPNext custom application
  • Need production-ready app structure with proper separation of concerns
  • Want multi-layer architecture (Controller → Service → Repository)
  • Building apps that require clean, maintainable code organization

Arguments

/frappe-app <app_name> [--module <module_name>]

Examples:

/frappe-app inventory_management
/frappe-app hr_extension --module Human Resources

Procedure

Step 1: Gather Requirements

Ask the user for:

  1. App name (snake_case, e.g., inventory_pro)
  2. App title (human-readable, e.g., "Inventory Pro")
  3. Primary module name (e.g., "Inventory", "HR", "Sales")
  4. Brief description of the app's purpose

Verify the current working directory is within a frappe-bench/apps folder:

pwd
ls -la

Step 2: Generate App Structure

Create the following multi-layer architecture:

<app_name>/
├── <app_name>/
│   ├── __init__.py
│   ├── hooks.py                    # App hooks and integrations
│   ├── modules.txt                 # Module definitions
│   ├── patches.txt                 # Database migrations
│   ├── <module_name>/              # Primary module
│   │   ├── __init__.py
│   │   ├── doctype/               # DocType definitions
│   │   │   └── __init__.py
│   │   ├── api/                   # REST API endpoints (v2)
│   │   │   └── __init__.py
│   │   ├── services/              # Business logic layer
│   │   │   └── __init__.py
│   │   ├── repositories/          # Data access layer
│   │   │   └── __init__.py
│   │   └── report/                # Custom reports
│   │       └── __init__.py
│   ├── public/
│   │   ├── css/
│   │   └── js/
│   ├── templates/
│   │   ├── includes/
│   │   └── pages/
│   ├── www/                       # Portal pages
│   └── tests/
│       ├── __init__.py
│       └── test_utils.py
├── pyproject.toml
├── README.md
└── license.txt

Step 3: Create Core Files

pyproject.toml
[project]
name = "<app_name>"
version = "0.0.1"
description = "<description>"
authors = [
    {name = "<author>", email = "<email>"}
]
requires-python = ">=3.10"
readme = "README.md"
license = {text = "MIT"}

dependencies = [
    "frappe>=15.0.0"
]

[project.optional-dependencies]
dev = [
    "pytest>=7.0.0",
    "pytest-cov>=4.0.0",
]

[build-system]
requires = ["flit_core>=3.9"]
build-backend = "flit_core.buildapi"

[tool.pytest.ini_options]
testpaths = ["<app_name>/tests"]
python_files = "test_*.py"
hooks.py
app_name = "<app_name>"
app_title = "<App Title>"
app_publisher = "<Author>"
app_description = "<Description>"
app_email = "<email>"
app_license = "MIT"

# Required Frappe version
required_apps = ["frappe"]

# v15: Enable type annotations in controllers
export_python_type_annotations = True

# Includes in <head>
# app_include_css = "/assets/<app_name>/css/<app_name>.css"
# app_include_js = "/assets/<app_name>/js/<app_name>.js"

# Document Events - prefer controller methods over hooks when possible
# doc_events = {
#     "DocType Name": {
#         "validate": "<app_name>.<module>.services.validation.validate_document",
#         "on_submit": "<app_name>.<module>.services.workflow.on_submit",
#     }
# }

# Scheduled Tasks
# scheduler_events = {
#     "daily": [
#         "<app_name>.<module>.tasks.daily_cleanup"
#     ],
#     "cron": {
#         "0 9 * * *": [
#             "<app_name>.<module>.tasks.morning_report"
#         ]
#     }
# }

# Permissions - override for custom logic
# has_permission = {
#     "DocType Name": "<app_name>.<module>.permissions.has_permission"
# }

# Fixtures - data to export/import
# fixtures = [
#     {"dt": "Custom Field", "filters": [["module", "=", "<module_name>"]]},
#     {"dt": "Property Setter", "filters": [["module", "=", "<module_name>"]]},
# ]

# User Data Protection
# user_data_fields = [
#     {"doctype": "DocType Name", "match_field": "owner", "personal_fields": ["email", "phone"]}
# ]
Base Service Class

Create <app_name>/<module>/services/base.py:

"""
Base service class providing common functionality for all services.
Services contain business logic and orchestrate operations.
"""

import frappe
from frappe import _
from typing import TYPE_CHECKING, Optional, Any

if TYPE_CHECKING:
    from frappe.model.document import Document


class BaseService:
    """
    Base class for all service layer classes.

    Services should:
    - Contain business logic
    - Coordinate between repositories
    - Handle transactions
    - Validate business rules
    """

    def __init__(self, user: Optional[str] = None):
        self.user = user or frappe.session.user

    def check_permission(
        self,
        doctype: str,
        ptype: str = "read",
        doc: Optional["Document"] = None,
        throw: bool = True
    ) -> bool:
        """Check if current user has permission."""
        return frappe.has_permission(
            doctype=doctype,
            ptype=ptype,
            doc=doc,
            user=self.user,
            throw=throw
        )

    def validate_mandatory(self, data: dict, fields: list[str]) -> None:
        """Validate that mandatory fields are present."""
        missing = [f for f in fields if not data.get(f)]
        if missing:
            frappe.throw(
                _("Missing required fields: {0}").format(", ".join(missing))
            )

    def log_activity(
        self,
        doctype: str,
        docname: str,
        action: str,
        details: Optional[dict] = None
    ) -> None:
        """Log service activity for audit trail."""
        frappe.get_doc({
            "doctype": "Comment",
            "comment_type": "Info",
            "reference_doctype": doctype,
            "reference_name": docname,
            "content": f"{action}: {details}" if details else action
        }).insert(ignore_permissions=True)
Base Repository Class

Create <app_name>/<module>/repositories/base.py:

"""
Base repository class for data access operations.
Repositories handle all database interactions.
"""

import frappe
from frappe.query_builder import DocType
from typing import TYPE_CHECKING, Optional, Any, TypeVar, Generic

if TYPE_CHECKING:
    from frappe.model.document import Document

T = TypeVar("T", bound="Document")


class BaseRepository(Generic[T]):
    """
    Base class for all repository layer classes.

    Repositories should:
    - Handle all database operations
    - Provide clean data access interface
    - Abstract SQL/ORM details
    - Never contain business logic

    Performance Notes:
    - Use get_cached() for repeated reads of same document
    - Use get_value() when you only need 1-2 fields (faster than get_doc)
    - get_list() applies user permissions; use get_all() to bypass (internal use only)
    """

    doctype: str = ""

    def __init__(self):
        if not self.doctype:
            raise ValueError("Repository must define doctype attribute")

    def get(self, name: str, for_update: bool = False) -> Optional[T]:
        """
        Get document by name. Fetches ALL fields and child tables.

        For better performance when reading 1-2 fields, use get_value() instead.
        For repeated reads of same document, use get_cached() instead.
        """
        if not frappe.db.exists(self.doctype, name):
            return None
        return frappe.get_doc(self.doctype, name, for_update=for_update)

    def get_cached(self, name: str) -> Optional[T]:
        """
        Get document with caching. Use for repeated reads within same request.

        Returns cached version if available, otherwise fetches and caches.
        Cache is automatically invalidated when document is saved.
        Can provide 10000x+ performance improvement for repeated reads.
        """
        if not frappe.db.exists(self.doctype, name):
            return None
        return frappe.get_cached_doc(self.doctype, name)

    def get_or_throw(self, name: str, for_update: bool = False) -> T:
        """Get document by name or throw if not found."""
        doc = self.get(name, for_update=for_update)
        if not doc:
            frappe.throw(f"{self.doctype} {name} not found")
        return doc

    def exists(self, name: str) -> bool:
        """Check if document exists."""
        return frappe.db.exists(self.doctype, name)

    def get_list(
        self,
        filters: Optional[dict] = None,
        fields: Optional[list[str]] = None,
        order_by: str = "modified desc",
        limit: int = 20,
        offset: int = 0
    ) -> list[dict]:
        """
        Get list of documents with user permission filtering.

        Note: This applies user permissions automatically.
        For internal/admin queries without permission checks, use get_all().
        """
        return frappe.get_list(
            self.doctype,
            filters=filters,
            fields=fields or ["name"],
            order_by=order_by,
            limit_page_length=limit,
            limit_start=offset
        )

    def get_all(
        self,
        filters: Optional[dict] = None,
        fields: Optional[list[str]] = None,
        order_by: str = "modified desc",
        limit: int = 20,
        offset: int = 0
    ) -> list[dict]:
        """
        Get list of documents WITHOUT permission filtering.

        WARNING: Use only for internal/system operations.
        For user-facing queries, use get_list() instead.
        """
        return frappe.get_all(
            self.doctype,
            filters=filters,
            fields=fields or ["name"],
            order_by=order_by,
            limit_page_length=limit,
            limit_start=offset
        )

    def get_count(self, filters: Optional[dict] = None) -> int:
        """Get count of documents matching filters."""
        return frappe.db.count(self.doctype, filters=filters)

    def create(self, data: dict) -> T:
        """Create new document."""
        doc = frappe.get_doc({"doctype": self.doctype, **data})
        doc.insert()
        return doc

    def update(self, name: str, data: dict) -> T:
        """Update existing document."""
        doc = self.get_or_throw(name, for_update=True)
        doc.update(data)
        doc.save()
        return doc

    def delete(self, name: str) -> None:
        """Delete document."""
        frappe.delete_doc(self.doctype, name)

    def get_value(
        self,
        name: str,
        fieldname: str | list[str]
    ) -> Any:
        """Get specific field value(s) from document."""
        return frappe.db.get_value(self.doctype, name, fieldname)

    def set_value(self, name: str, fieldname: str, value: Any) -> None:
        """
        Set specific field value directly in database.

        WARNING: This bypasses controller validations and hooks.
        Use doc.save() if you need validations to run.
        """
        frappe.db.set_value(self.doctype, name, fieldname, value)

Step 4: Create Test Utilities

Create <app_name>/tests/test_utils.py:

"""
Test utilities and fixtures for <app_name>.
"""

import frappe
from frappe.tests import IntegrationTestCase, UnitTestCase


class <AppName>TestCase(IntegrationTestCase):
    """
    Base test case for <app_name> integration tests.

    Usage:
        class TestMyFeature(<AppName>TestCase):
            def test_something(self):
                # Test with full database access
                pass
    """

    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        # Setup test data

    @classmethod
    def tearDownClass(cls):
        # Cleanup test data
        super().tearDownClass()

    def create_test_user(self, email: str, roles: list[str] = None) -> str:
        """Create a test user with specified roles."""
        if frappe.db.exists("User", email):
            return email

        user = frappe.get_doc({
            "doctype": "User",
            "email": email,
            "first_name": "Test",
            "last_name": "User",
            "send_welcome_email": 0
        })
        user.insert(ignore_permissions=True)

        for role in (roles or []):
            user.add_roles(role)

        return email


class <AppName>UnitTestCase(UnitTestCase):
    """
    Base test case for <app_name> unit tests (no database).
    """
    pass

Step 5: Show Summary and Confirm

Present the complete structure to user:

## App Structure Preview

**App:** <app_name>
**Title:** <App Title>
**Module:** <Module Name>

### Files to Create:

📁 <app_name>/
├── 📁 <app_name>/
│   ├── 📄 __init__.py
│   ├── 📄 hooks.py
│   ├── 📄 modules.txt
│   ├── 📄 patches.txt
│   ├── 📁 <module>/
│   │   ├── 📁 api/
│   │   ├── 📁 services/
│   │   │   └── 📄 base.py
│   │   ├── 📁 repositories/
│   │   │   └── 📄 base.py
│   │   └── 📁 doctype/
│   ├── 📁 public/
│   ├── 📁 templates/
│   └── 📁 tests/
│       └── 📄 test_utils.py
├── 📄 pyproject.toml
├── 📄 README.md
└── 📄 license.txt

### Architecture Layers:

1. **Controllers** (doctype/) - Handle HTTP requests, call services
2. **Services** (services/) - Business logic, validation, orchestration
3. **Repositories** (repositories/) - Data access, database queries

---
Create this app structure?

Wait for user confirmation.

Step 6: Execute Creation

After approval:

  1. Create all directories
  2. Create all files with proper content
  3. Replace all placeholders with actual values

Step 7: Verify and Guide

ls -la <app_name>/

Provide next steps:

## App Created Successfully

**Next Steps:**

1. Install the app:
   ```bash
   bench get-app /path/to/<app_name>
   bench --site <site> install-app <app_name>
  1. Create your first DocType:

    /frappe-doctype <doctype_name>
    
  2. Add API endpoints:

    /frappe-api <endpoint_name>
    
  3. Run tests:

    bench --site <site> run-tests --app <app_name>
    

Documentation:


## Rules

1. **v15 Compatibility** — All generated code must be compatible with Frappe Framework v15
2. **Type Annotations** — Use Python type hints for all function signatures
3. **Multi-Layer Architecture** — Enforce Controller → Service → Repository pattern
4. **No Business Logic in Controllers** — Controllers should only call services
5. **ALWAYS Confirm** — Never create files without explicit user approval
6. **snake_case** — App names must be snake_case
7. **Module Organization** — Each module should be self-contained with its own services/repositories

Frappe DocType Creation

Create a production-ready Frappe v15 DocType with complete controller implementation, service layer integration, repository pattern, and test coverage.

When to Use

  • Creating a new DocType for a Frappe application
  • Need proper controller with lifecycle hooks
  • Want service layer for business logic separation
  • Require repository for clean data access
  • Building submittable/amendable documents

Arguments

/frappe-doctype <doctype_name> [--module <module>] [--submittable] [--child]

Examples:

/frappe-doctype Sales Order
/frappe-doctype Invoice Item --child
/frappe-doctype Purchase Request --submittable

Procedure

Step 1: Gather DocType Requirements

Ask the user for:

  1. DocType Name (Title Case, e.g., "Sales Order")
  2. Module (which module this belongs to)
  3. DocType Type:
    • Standard (regular CRUD document)
    • Submittable (has workflow: Draft → Submitted → Cancelled)
    • Child Table (embedded in parent documents)
    • Single (configuration/settings document)
  4. Key Fields (at least the primary fields needed)
  5. Naming Pattern:
    • Autoname (series like SO-.YYYY.-.#####)
    • Field-based (use a specific field value)
    • Prompt (user enters name)

Step 2: Analyze and Design

Based on requirements, determine:

  • Field types and properties
  • Link relationships to other DocTypes
  • Required indexes for performance
  • Permission model (roles that can access)
  • Workflow requirements

Step 3: Generate DocType JSON

Create the DocType definition <doctype_folder>/<doctype_name>.json:

{
  "name": "<DocType Name>",
  "module": "<Module>",
  "doctype": "DocType",
  "naming_rule": "By \"Naming Series\" field",
  "autoname": "naming_series:",
  "is_submittable": 0,
  "is_tree": 0,
  "istable": 0,
  "editable_grid": 1,
  "track_changes": 1,
  "track_seen": 1,
  "engine": "InnoDB",
  "fields": [
    {
      "fieldname": "naming_series",
      "fieldtype": "Select",
      "label": "Series",
      "options": "<PREFIX>-.YYYY.-.#####",
      "reqd": 1,
      "in_list_view": 0
    },
    {
      "fieldname": "title",
      "fieldtype": "Data",
      "label": "Title",
      "reqd": 1,
      "in_list_view": 1,
      "in_standard_filter": 1
    },
    {
      "fieldname": "status",
      "fieldtype": "Select",
      "label": "Status",
      "options": "\nDraft\nPending\nCompleted\nCancelled",
      "default": "Draft",
      "in_list_view": 1,
      "in_standard_filter": 1
    },
    {
      "fieldname": "column_break_1",
      "fieldtype": "Column Break"
    },
    {
      "fieldname": "date",
      "fieldtype": "Date",
      "label": "Date",
      "default": "Today",
      "reqd": 1,
      "in_list_view": 1
    },
    {
      "fieldname": "section_break_details",
      "fieldtype": "Section Break",
      "label": "Details"
    },
    {
      "fieldname": "description",
      "fieldtype": "Text Editor",
      "label": "Description"
    },
    {
      "fieldname": "amended_from",
      "fieldtype": "Link",
      "label": "Amended From",
      "no_copy": 1,
      "options": "<DocType Name>",
      "print_hide": 1,
      "read_only": 1
    }
  ],
  "permissions": [
    {
      "role": "System Manager",
      "read": 1,
      "write": 1,
      "create": 1,
      "delete": 1,
      "submit": 0,
      "cancel": 0,
      "amend": 0
    }
  ],
  "sort_field": "modified",
  "sort_order": "DESC",
  "title_field": "title"
}

Step 4: Generate Controller with v15 Type Annotations

Create <doctype_folder>/<doctype_name>.py:

# Copyright (c) <year>, <author> and contributors
# For license information, please see license.txt

import frappe
from frappe import _
from frappe.model.document import Document
from frappe.model.docstatus import DocStatus  # v15: Helper for docstatus checks
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from frappe.types import DF
    # Import child table types if needed
    # from <app>.<module>.doctype.<child_doctype>.<child_doctype> import <ChildDocType>


class <DocTypeName>(Document):
    """
    <DocType Name> - <brief description>

    Lifecycle:
        Draft → (validate) → Saved → (submit) → Submitted → (cancel) → Cancelled
    """

    # begin: auto-generated types
    # This section is auto-generated by Frappe. Do not modify manually.
    if TYPE_CHECKING:
        amended_from: DF.Link | None
        date: DF.Date
        description: DF.TextEditor | None
        naming_series: DF.Literal["<PREFIX>-.YYYY.-.#####"]
        status: DF.Literal["", "Draft", "Pending", "Completed", "Cancelled"]
        title: DF.Data
    # end: auto-generated types

    def before_validate(self) -> None:
        """Auto-set default values before validation."""
        self._set_defaults()

    def validate(self) -> None:
        """Validate document before save. Throw exception to prevent saving."""
        self._validate_business_rules()

    def before_save(self) -> None:
        """Called before document is saved to database."""
        self._update_status()

    def after_insert(self) -> None:
        """Called after new document is inserted."""
        self._notify_creation()

    def on_update(self) -> None:
        """Called when existing document is updated."""
        pass

    def before_submit(self) -> None:
        """Called before document submission. Validate submission requirements."""
        self._validate_submit_conditions()

    def on_submit(self) -> None:
        """Called after document submission. Create dependent records."""
        self._process_submission()

    def before_cancel(self) -> None:
        """Validate cancellation conditions."""
        self._validate_cancel_conditions()

    def on_cancel(self) -> None:
        """Handle cancellation cleanup."""
        self._process_cancellation()

    def on_trash(self) -> None:
        """Called when document is deleted. Cleanup related data."""
        pass

    # ──────────────────────────────────────────────────────────────────────────
    # Private Methods
    # ──────────────────────────────────────────────────────────────────────────

    def _set_defaults(self) -> None:
        """Set default values for fields."""
        if not self.date:
            self.date = frappe.utils.today()

    def _validate_business_rules(self) -> None:
        """Validate business rules specific to this DocType."""
        if not self.title:
            frappe.throw(_("Title is required"))

    def _update_status(self) -> None:
        """Update status based on document state using DocStatus helper."""
        # v15: Use DocStatus helper for readable status checks
        if self.docstatus.is_draft() and not self.status:
            self.status = "Draft"

    def _notify_creation(self) -> None:
        """Send notifications after creation."""
        # frappe.publish_realtime("new_<doctype>", {"name": self.name})
        pass

    def _validate_submit_conditions(self) -> None:
        """Check all conditions required for submission."""
        pass

    def _process_submission(self) -> None:
        """Process document submission - create GL entries, update stocks, etc."""
        self.db_set("status", "Completed")

    def _validate_cancel_conditions(self) -> None:
        """Check if document can be cancelled."""
        pass

    def _process_cancellation(self) -> None:
        """Reverse submission effects."""
        self.db_set("status", "Cancelled")

    # ──────────────────────────────────────────────────────────────────────────
    # Public API Methods (call from services or whitelisted methods)
    # ──────────────────────────────────────────────────────────────────────────

    def get_summary(self) -> dict:
        """Return document summary for API responses."""
        return {
            "name": self.name,
            "title": self.title,
            "status": self.status,
            "date": str(self.date)
        }


# ──────────────────────────────────────────────────────────────────────────────
# Whitelisted Methods (accessible via REST API)
# ──────────────────────────────────────────────────────────────────────────────

@frappe.whitelist()
def get_<doctype_snake>_summary(name: str) -> dict:
    """
    Get document summary.

    Args:
        name: Document name

    Returns:
        Document summary dict
    """
    doc = frappe.get_doc("<DocType Name>", name)
    doc.check_permission("read")
    return doc.get_summary()

Step 5: Generate Service Layer

Create <app>/<module>/services/<doctype_snake>_service.py:

"""
<DocType Name> Service

Business logic for <DocType Name> operations.
"""

import frappe
from frappe import _
from typing import Optional
from <app>.<module>.services.base import BaseService
from <app>.<module>.repositories.<doctype_snake>_repository import <DocTypeName>Repository


class <DocTypeName>Service(BaseService):
    """
    Service class for <DocType Name> business logic.

    All business rules and complex operations should be implemented here,
    not in the DocType controller.
    """

    def __init__(self):
        super().__init__()
        self.repo = <DocTypeName>Repository()

    def create(self, data: dict) -> dict:
        """
        Create a new <DocType Name>.

        Args:
            data: Document data

        Returns:
            Created document summary

        Raises:
            frappe.ValidationError: If validation fails
        """
        self.check_permission("<DocType Name>", "create", throw=True)
        self.validate_mandatory(data, ["title", "date"])

        doc = self.repo.create(data)
        self.log_activity("<DocType Name>", doc.name, "Created")

        return doc.get_summary()

    def update(self, name: str, data: dict) -> dict:
        """
        Update existing <DocType Name>.

        Args:
            name: Document name
            data: Fields to update

        Returns:
            Updated document summary
        """
        doc = self.repo.get_or_throw(name, for_update=True)
        self.check_permission("<DocType Name>", "write", doc=doc, throw=True)

        # Business validation
        if doc.status == "Completed":
            frappe.throw(_("Cannot modify completed documents"))

        doc.update(data)
        doc.save()
        self.log_activity("<DocType Name>", name, "Updated", data)

        return doc.get_summary()

    def submit(self, name: str) -> dict:
        """
        Submit document for processing.

        Args:
            name: Document name

        Returns:
            Submitted document summary
        """
        doc = self.repo.get_or_throw(name, for_update=True)
        self.check_permission("<DocType Name>", "submit", doc=doc, throw=True)

        # Pre-submit validation
        self._validate_submission(doc)

        doc.submit()
        return doc.get_summary()

    def cancel(self, name: str, reason: Optional[str] = None) -> dict:
        """
        Cancel submitted document.

        Args:
            name: Document name
            reason: Cancellation reason

        Returns:
            Cancelled document summary
        """
        doc = self.repo.get_or_throw(name, for_update=True)
        self.check_permission("<DocType Name>", "cancel", doc=doc, throw=True)

        if reason:
            frappe.db.set_value("<DocType Name>", name, "cancellation_reason", reason)

        doc.cancel()
        self.log_activity("<DocType Name>", name, "Cancelled", {"reason": reason})

        return doc.get_summary()

    def get_dashboard_stats(self) -> dict:
        """Get statistics for dashboard."""
        return {
            "total": self.repo.get_count(),
            "draft": self.repo.get_count({"status": "Draft"}),
            "pending": self.repo.get_count({"status": "Pending"}),
            "completed": self.repo.get_count({"status": "Completed"})
        }

    def _validate_submission(self, doc) -> None:
        """Validate all requirements for submission."""
        if doc.docstatus != 0:
            frappe.throw(_("Document must be in draft state to submit"))

Step 6: Generate Repository

Create <app>/<module>/repositories/<doctype_snake>_repository.py:

"""
<DocType Name> Repository

Data access layer for <DocType Name>.
"""

import frappe
from frappe.query_builder import DocType
from typing import Optional
from <app>.<module>.repositories.base import BaseRepository
from <app>.<module>.doctype.<doctype_folder>.<doctype_snake> import <DocTypeName>


class <DocTypeName>Repository(BaseRepository[<DocTypeName>]):
    """
    Repository for <DocType Name> database operations.
    """

    doctype = "<DocType Name>"

    def get_by_status(
        self,
        status: str,
        limit: int = 20,
        offset: int = 0
    ) -> list[dict]:
        """Get documents by status."""
        return self.get_list(
            filters={"status": status},
            fields=["name", "title", "date", "status", "owner"],
            order_by="date desc",
            limit=limit,
            offset=offset
        )

    def get_recent(self, days: int = 7) -> list[dict]:
        """Get documents created in the last N days."""
        from_date = frappe.utils.add_days(frappe.utils.today(), -days)
        return self.get_list(
            filters={"creation": [">=", from_date]},
            fields=["name", "title", "date", "status", "creation"],
            order_by="creation desc"
        )

    def search(
        self,
        query: str,
        filters: Optional[dict] = None,
        limit: int = 20
    ) -> list[dict]:
        """Full-text search on title and description."""
        base_filters = filters or {}
        base_filters["title"] = ["like", f"%{query}%"]

        return self.get_list(
            filters=base_filters,
            fields=["name", "title", "date", "status"],
            limit=limit
        )

    def get_with_related(self, name: str) -> dict:
        """Get document with related data."""
        doc = self.get_or_throw(name)
        return {
            **doc.as_dict(),
            # Add related data here
            # "items": self._get_items(name),
            # "comments": self._get_comments(name)
        }

    def bulk_update_status(self, names: list[str], status: str) -> int:
        """Bulk update status for multiple documents."""
        dt = DocType(self.doctype)
        return (
            frappe.qb.update(dt)
            .set(dt.status, status)
            .set(dt.modified, frappe.utils.now())
            .set(dt.modified_by, frappe.session.user)
            .where(dt.name.isin(names))
            .run()
        )

Step 7: Generate Test File

Create <doctype_folder>/test_<doctype_snake>.py:

# Copyright (c) <year>, <author> and contributors
# For license information, please see license.txt

import frappe
from frappe.tests import IntegrationTestCase, UnitTestCase
from <app>.<module>.services.<doctype_snake>_service import <DocTypeName>Service


class Test<DocTypeName>(IntegrationTestCase):
    """Integration tests for <DocType Name>."""

    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        cls.service = <DocTypeName>Service()

    def test_create_document(self):
        """Test document creation via service."""
        data = {
            "title": "Test Document",
            "date": frappe.utils.today()
        }
        result = self.service.create(data)

        self.assertIsNotNone(result.get("name"))
        self.assertEqual(result.get("title"), "Test Document")

    def test_create_requires_mandatory_fields(self):
        """Test that mandatory fields are validated."""
        with self.assertRaises(frappe.ValidationError):
            self.service.create({})

    def test_submit_document(self):
        """Test document submission."""
        # Create draft
        doc = frappe.get_doc({
            "doctype": "<DocType Name>",
            "title": "Submit Test",
            "date": frappe.utils.today()
        }).insert()

        # Submit via service
        result = self.service.submit(doc.name)
        self.assertEqual(result.get("status"), "Completed")

    def test_cannot_modify_completed(self):
        """Test that completed documents cannot be modified."""
        doc = frappe.get_doc({
            "doctype": "<DocType Name>",
            "title": "Completed Test",
            "date": frappe.utils.today(),
            "status": "Completed"
        }).insert()

        with self.assertRaises(frappe.ValidationError):
            self.service.update(doc.name, {"title": "New Title"})

    def test_get_dashboard_stats(self):
        """Test dashboard statistics."""
        stats = self.service.get_dashboard_stats()

        self.assertIn("total", stats)
        self.assertIn("draft", stats)
        self.assertIn("completed", stats)


class Unit<DocTypeName>(UnitTestCase):
    """Unit tests for <DocType Name> (no database)."""

    def test_validation_logic(self):
        """Test validation without database."""
        pass

Step 8: Show Preview and Confirm

## DocType Creation Preview

**DocType:** <DocType Name>
**Module:** <Module>
**Type:** Standard | Submittable | Child Table

### Files to Create:

📁 <module>/doctype/<doctype_folder>/
├── 📄 <doctype_snake>.json       # DocType definition
├── 📄 <doctype_snake>.py         # Controller with hooks
├── 📄 <doctype_snake>.js         # Client-side script
└── 📄 test_<doctype_snake>.py    # Test cases

📁 <module>/services/
└── 📄 <doctype_snake>_service.py # Business logic

📁 <module>/repositories/
└── 📄 <doctype_snake>_repository.py # Data access

### Fields:

| Field | Type | Required |
|-------|------|----------|
| naming_series | Select | Yes |
| title | Data | Yes |
| status | Select | No |
| date | Date | Yes |
| description | Text Editor | No |

---
Create this DocType with all layers?

Step 9: Execute and Verify

After approval, create all files and run:

bench --site <site> migrate
bench --site <site> run-tests --doctype "<DocType Name>"

Output Format

## DocType Created

**Name:** <DocType Name>
**Path:** <app>/<module>/doctype/<doctype_folder>/

### Files Created:
- ✅ <doctype_snake>.json
- ✅ <doctype_snake>.py (controller)
- ✅ <doctype_snake>.js (client)
- ✅ test_<doctype_snake>.py
- ✅ <doctype_snake>_service.py
- ✅ <doctype_snake>_repository.py

### Next Steps:
1. Run `bench --site <site> migrate` to create database table
2. Add permissions in DocType settings
3. Create any child tables needed
4. Run tests: `bench --site <site> run-tests --doctype "<DocType Name>"`

Rules

  1. v15 Type Annotations — Always include TYPE_CHECKING block with type hints
  2. Multi-Layer Pattern — Create service and repository for every DocType
  3. No Business Logic in Controller — Controllers call services, services implement logic
  4. Comprehensive Tests — Every DocType must have test coverage
  5. Proper Naming — DocType folder/file names must be snake_case
  6. ALWAYS Confirm — Never create files without explicit user approval
  7. Index Planning — Add indexes for frequently filtered fields

Frappe Service Layer Design

Create well-structured service layer classes that encapsulate business logic, coordinate between repositories, and provide clean interfaces for controllers and APIs.

When to Use

  • Implementing complex business logic
  • Coordinating operations across multiple DocTypes
  • Creating reusable business operations
  • Separating concerns between controllers and data access
  • Building transaction-aware operations

Arguments

/frappe-service <service_name> [--doctype <doctype>] [--operations <op1,op2>]

Examples:

/frappe-service OrderProcessing --doctype "Sales Order"
/frappe-service InventoryManagement --operations allocate,release,transfer
/frappe-service PaymentGateway

Procedure

Step 1: Gather Service Requirements

Ask the user for:

  1. Service Name (PascalCase, e.g., OrderProcessingService)
  2. Primary DocType (if applicable)
  3. Key Operations to implement
  4. External Integrations (APIs, payment gateways, etc.)
  5. Transaction Requirements (atomic operations, rollback needs)

Step 2: Design Service Architecture

Determine the service pattern:

PatternUse CaseExample
CRUD ServiceBasic DocType operationsCustomerService
Workflow ServiceState transitions, approvalsApprovalService
Integration ServiceExternal API callsPaymentGatewayService
Orchestration ServiceMulti-DocType coordinationOrderFulfillmentService
Batch ServiceBulk operationsBulkImportService

Step 3: Generate Service Class

Create <app>/<module>/services/<service_name>.py:

"""
<Service Name> Service

<Detailed description of what this service handles>

Responsibilities:
    - <Responsibility 1>
    - <Responsibility 2>
    - <Responsibility 3>

Usage:
    from <app>.<module>.services.<service_name> import <ServiceName>Service

    service = <ServiceName>Service()
    result = service.process_order(order_data)
"""

import frappe
from frappe import _
from frappe.utils import now, today, flt, cint, cstr
from typing import TYPE_CHECKING, Optional, Any, Callable
from contextlib import contextmanager
from functools import wraps

from <app>.<module>.services.base import BaseService
from <app>.<module>.repositories.<doctype>_repository import <DocType>Repository

if TYPE_CHECKING:
    from frappe.model.document import Document


# ──────────────────────────────────────────────────────────────────────────────
# Decorators
# ──────────────────────────────────────────────────────────────────────────────

def require_permission(doctype: str, ptype: str = "read"):
    """Decorator to check permission before method execution."""
    def decorator(func: Callable):
        @wraps(func)
        def wrapper(self, *args, **kwargs):
            if not frappe.has_permission(doctype, ptype):
                frappe.throw(
                    _("Permission denied: {0} {1}").format(ptype, doctype),
                    frappe.PermissionError
                )
            return func(self, *args, **kwargs)
        return wrapper
    return decorator


def with_transaction(func: Callable):
    """Decorator to wrap method in database transaction."""
    @wraps(func)
    def wrapper(self, *args, **kwargs):
        try:
            result = func(self, *args, **kwargs)
            frappe.db.commit()
            return result
        except Exception:
            frappe.db.rollback()
            raise
    return wrapper


def log_operation(operation_name: str):
    """Decorator to log service operation."""
    def decorator(func: Callable):
        @wraps(func)
        def wrapper(self, *args, **kwargs):
            frappe.logger().info(f"[{operation_name}] Starting...")
            try:
                result = func(self, *args, **kwargs)
                frappe.logger().info(f"[{operation_name}] Completed successfully")
                return result
            except Exception as e:
                frappe.logger().error(f"[{operation_name}] Failed: {str(e)}")
                raise
        return wrapper
    return decorator


# ──────────────────────────────────────────────────────────────────────────────
# Service Implementation
# ──────────────────────────────────────────────────────────────────────────────

class <ServiceName>Service(BaseService):
    """
    Service for <description>.

    This service handles:
        - <Operation 1>
        - <Operation 2>
        - <Operation 3>

    Architecture:
        Controller/API → Service → Repository → Database

    Example:
        service = <ServiceName>Service()
        order = service.create_order(customer="CUST-001", items=[...])
        service.submit_order(order.name)
    """

    def __init__(self, user: Optional[str] = None):
        super().__init__(user)
        self.repo = <DocType>Repository()
        # Initialize other repositories as needed
        # self.item_repo = ItemRepository()
        # self.customer_repo = CustomerRepository()

    # ──────────────────────────────────────────────────────────────────────────
    # Public Operations (Business Logic)
    # ──────────────────────────────────────────────────────────────────────────

    @require_permission("<DocType>", "create")
    @with_transaction
    @log_operation("create_<doctype>")
    def create(self, data: dict) -> dict:
        """
        Create a new <DocType>.

        Args:
            data: Document data containing:
                - title (str): Required title
                - date (str): Date in YYYY-MM-DD format
                - description (str): Optional description

        Returns:
            Created document summary

        Raises:
            frappe.ValidationError: If validation fails
            frappe.PermissionError: If user lacks permission

        Example:
            service.create({
                "title": "New Order",
                "date": "2024-01-15"
            })
        """
        # 1. Validate input
        self._validate_create_data(data)

        # 2. Apply business rules
        data = self._apply_defaults(data)
        data = self._apply_business_rules(data)

        # 3. Create via repository
        doc = self.repo.create(data)

        # 4. Post-creation actions
        self._on_create(doc)

        # 5. Return summary
        return doc.get_summary()

    @require_permission("<DocType>", "write")
    @with_transaction
    def update(self, name: str, data: dict) -> dict:
        """
        Update existing <DocType>.

        Args:
            name: Document name
            data: Fields to update

        Returns:
            Updated document summary
        """
        doc = self.repo.get_or_throw(name, for_update=True)

        # Validate update is allowed
        self._validate_can_update(doc)

        # Apply update
        doc.update(data)
        doc.save()

        return doc.get_summary()

    @require_permission("<DocType>", "submit")
    @with_transaction
    @log_operation("submit_<doctype>")
    def submit(self, name: str) -> dict:
        """
        Submit document for processing.

        This triggers:
            1. Pre-submission validation
            2. Document submission
            3. Post-submission actions (e.g., stock updates, GL entries)

        Args:
            name: Document name

        Returns:
            Submitted document summary

        Raises:
            frappe.ValidationError: If submission requirements not met
        """
        doc = self.repo.get_or_throw(name, for_update=True)

        # Pre-submission checks
        self._validate_submission(doc)

        # Submit
        doc.submit()

        # Post-submission processing
        self._on_submit(doc)

        return doc.get_summary()

    @require_permission("<DocType>", "cancel")
    @with_transaction
    @log_operation("cancel_<doctype>")
    def cancel(self, name: str, reason: Optional[str] = None) -> dict:
        """
        Cancel submitted document.

        Args:
            name: Document name
            reason: Cancellation reason (recommended)

        Returns:
            Cancelled document summary
        """
        doc = self.repo.get_or_throw(name, for_update=True)

        # Validate cancellation
        self._validate_cancellation(doc)

        # Store reason
        if reason:
            doc.db_set("cancellation_reason", reason, update_modified=False)

        # Cancel
        doc.cancel()

        # Post-cancellation processing
        self._on_cancel(doc)

        return doc.get_summary()

    # ──────────────────────────────────────────────────────────────────────────
    # Complex Business Operations
    # ──────────────────────────────────────────────────────────────────────────

    @with_transaction
    def process_workflow(
        self,
        name: str,
        action: str,
        comment: Optional[str] = None
    ) -> dict:
        """
        Process workflow action on document.

        Args:
            name: Document name
            action: Workflow action (e.g., "Approve", "Reject")
            comment: Optional comment for the action

        Returns:
            Updated document with new workflow state
        """
        doc = self.repo.get_or_throw(name, for_update=True)

        # Validate action is allowed
        allowed_actions = self._get_allowed_workflow_actions(doc)
        if action not in allowed_actions:
            frappe.throw(
                _("Action '{0}' not allowed. Allowed: {1}").format(
                    action, ", ".join(allowed_actions)
                )
            )

        # Apply workflow action
        from frappe.model.workflow import apply_workflow
        apply_workflow(doc, action)

        # Add comment
        if comment:
            doc.add_comment("Workflow", f"{action}: {comment}")

        return doc.get_summary()

    def calculate_totals(self, name: str) -> dict:
        """
        Calculate and update document totals.

        Args:
            name: Document name

        Returns:
            Calculated totals
        """
        doc = self.repo.get_or_throw(name)

        subtotal = sum(
            flt(item.qty) * flt(item.rate)
            for item in doc.get("items", [])
        )

        tax_amount = flt(subtotal) * flt(doc.tax_rate or 0) / 100
        grand_total = flt(subtotal) + flt(tax_amount)

        return {
            "subtotal": subtotal,
            "tax_amount": tax_amount,
            "grand_total": grand_total
        }

    def bulk_operation(
        self,
        names: list[str],
        operation: str,
        **kwargs
    ) -> dict:
        """
        Perform bulk operation on multiple documents.

        Args:
            names: List of document names
            operation: Operation to perform (update_status, submit, cancel)
            **kwargs: Operation-specific arguments

        Returns:
            Results summary
        """
        results = {"success": [], "failed": []}

        for name in names:
            try:
                if operation == "update_status":
                    self.update(name, {"status": kwargs.get("status")})
                elif operation == "submit":
                    self.submit(name)
                elif operation == "cancel":
                    self.cancel(name, kwargs.get("reason"))

                results["success"].append(name)
            except Exception as e:
                results["failed"].append({
                    "name": name,
                    "error": str(e)
                })

        return results

    # ──────────────────────────────────────────────────────────────────────────
    # Query Methods
    # ──────────────────────────────────────────────────────────────────────────

    def get_pending_items(self, limit: int = 50) -> list[dict]:
        """Get items pending action."""
        return self.repo.get_list(
            filters={"status": "Pending", "docstatus": 0},
            fields=["name", "title", "date", "owner", "creation"],
            order_by="creation asc",
            limit=limit
        )

    def get_statistics(self, period: str = "month") -> dict:
        """
        Get statistics for dashboard.

        Args:
            period: Time period (day, week, month, year)

        Returns:
            Statistics dict
        """
        from frappe.utils import add_days, add_months, get_first_day

        today_date = today()

        if period == "day":
            from_date = today_date
        elif period == "week":
            from_date = add_days(today_date, -7)
        elif period == "month":
            from_date = get_first_day(today_date)
        else:  # year
            from_date = add_months(get_first_day(today_date), -12)

        return {
            "total": self.repo.get_count(),
            "period_total": self.repo.get_count(
                {"creation": [">=", from_date]}
            ),
            "by_status": self._get_counts_by_status(),
            "period": period,
            "from_date": from_date
        }

    # ──────────────────────────────────────────────────────────────────────────
    # Private Methods (Internal Logic)
    # ──────────────────────────────────────────────────────────────────────────

    def _validate_create_data(self, data: dict) -> None:
        """Validate data for document creation."""
        self.validate_mandatory(data, ["title"])

        # Custom validations
        if data.get("date") and data["date"] < today():
            frappe.throw(_("Date cannot be in the past"))

    def _validate_can_update(self, doc: "Document") -> None:
        """Validate document can be updated."""
        if doc.docstatus == 2:
            frappe.throw(_("Cannot update cancelled document"))

        if doc.status == "Completed":
            frappe.throw(_("Cannot update completed document"))

    def _validate_submission(self, doc: "Document") -> None:
        """Validate all requirements for submission."""
        if doc.docstatus != 0:
            frappe.throw(_("Document is not in draft state"))

        # Add more validations as needed
        # if not doc.get("items"):
        #     frappe.throw(_("Cannot submit without items"))

    def _validate_cancellation(self, doc: "Document") -> None:
        """Validate document can be cancelled."""
        if doc.docstatus != 1:
            frappe.throw(_("Only submitted documents can be cancelled"))

        # Check for linked documents
        # linked = self._get_linked_submitted_docs(doc.name)
        # if linked:
        #     frappe.throw(_("Cannot cancel. Linked documents exist: {0}").format(linked))

    def _apply_defaults(self, data: dict) -> dict:
        """Apply default values to data."""
        if not data.get("date"):
            data["date"] = today()

        if not data.get("status"):
            data["status"] = "Draft"

        return data

    def _apply_business_rules(self, data: dict) -> dict:
        """Apply business rules to data."""
        # Example: Set posting date to today if not specified
        # Example: Calculate derived fields
        return data

    def _on_create(self, doc: "Document") -> None:
        """Post-creation hook for additional processing."""
        # Send notification
        # frappe.publish_realtime("new_document", {"name": doc.name})
        pass

    def _on_submit(self, doc: "Document") -> None:
        """Post-submission processing."""
        # Create linked records (GL entries, stock ledger, etc.)
        # Update inventory
        # Send notifications
        pass

    def _on_cancel(self, doc: "Document") -> None:
        """Post-cancellation processing."""
        # Reverse linked records
        # Update inventory
        pass

    def _get_allowed_workflow_actions(self, doc: "Document") -> list[str]:
        """Get allowed workflow actions for document."""
        from frappe.model.workflow import get_transitions
        return [t.action for t in get_transitions(doc)]

    def _get_counts_by_status(self) -> dict:
        """Get document counts grouped by status."""
        result = frappe.db.sql("""
            SELECT status, COUNT(*) as count
            FROM `tab<DocType>`
            WHERE docstatus < 2
            GROUP BY status
        """, as_dict=True)

        return {row.status: row.count for row in result}


# ──────────────────────────────────────────────────────────────────────────────
# Service Factory (for dependency injection)
# ──────────────────────────────────────────────────────────────────────────────

def get_<service_name>_service(user: Optional[str] = None) -> <ServiceName>Service:
    """
    Factory function for <ServiceName>Service.

    Use this instead of direct instantiation for easier testing/mocking.

    Args:
        user: Optional user context

    Returns:
        Service instance
    """
    return <ServiceName>Service(user=user)

Step 4: Generate Integration Service Pattern (Optional)

For services that integrate with external APIs:

"""
External Integration Service

Handles communication with external APIs with retry logic,
error handling, and response normalization.
"""

import frappe
from frappe import _
from typing import Optional, Any
import requests
from tenacity import retry, stop_after_attempt, wait_exponential


class <Integration>Service:
    """
    Service for integrating with <External Service>.

    Configuration:
        - API Key: System Settings > <Integration> API Key
        - Base URL: System Settings > <Integration> Base URL
    """

    def __init__(self):
        self.api_key = frappe.db.get_single_value("System Settings", "<integration>_api_key")
        self.base_url = frappe.db.get_single_value("System Settings", "<integration>_base_url")

        if not self.api_key:
            frappe.throw(_("<Integration> API key not configured"))

    @retry(
        stop=stop_after_attempt(3),
        wait=wait_exponential(multiplier=1, min=2, max=10)
    )
    def _make_request(
        self,
        method: str,
        endpoint: str,
        data: Optional[dict] = None
    ) -> dict:
        """
        Make HTTP request with retry logic.

        Args:
            method: HTTP method (GET, POST, PUT, DELETE)
            endpoint: API endpoint
            data: Request payload

        Returns:
            Response data

        Raises:
            frappe.ValidationError: On API error
        """
        url = f"{self.base_url}/{endpoint}"
        headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json"
        }

        try:
            response = requests.request(
                method=method,
                url=url,
                json=data,
                headers=headers,
                timeout=30
            )
            response.raise_for_status()
            return response.json()

        except requests.exceptions.Timeout:
            frappe.throw(_("Request timed out. Please try again."))

        except requests.exceptions.HTTPError as e:
            error_msg = self._parse_error_response(e.response)
            frappe.throw(_("API Error: {0}").format(error_msg))

        except requests.exceptions.RequestException as e:
            frappe.throw(_("Connection error: {0}").format(str(e)))

    def _parse_error_response(self, response) -> str:
        """Parse error message from API response."""
        try:
            data = response.json()
            return data.get("message") or data.get("error") or response.text
        except Exception:
            return response.text

    # Public API methods
    def create_external_record(self, data: dict) -> dict:
        """Create record in external system."""
        return self._make_request("POST", "records", data)

    def get_external_record(self, external_id: str) -> dict:
        """Get record from external system."""
        return self._make_request("GET", f"records/{external_id}")

    def sync_records(self) -> dict:
        """Sync records with external system."""
        # Implementation
        pass

Step 5: Show Service Design and Confirm

## Service Layer Preview

**Service:** <ServiceName>Service
**Module:** <app>.<module>.services.<service_name>

### Architecture:

┌─────────────────────┐ │ Controller/API │ └──────────┬──────────┘ │ ▼ ┌─────────────────────┐ │ │ ← Business Logic │ Service │ └──────────┬──────────┘ │ ▼ ┌─────────────────────┐ │ │ ← Data Access │ Repository │ └──────────┬──────────┘ │ ▼ ┌─────────────────────┐ │ Database │ └─────────────────────┘


### Operations:

| Method | Permission | Description |
|--------|------------|-------------|
| create() | create | Create new document |
| update() | write | Update document |
| submit() | submit | Submit for processing |
| cancel() | cancel | Cancel document |
| process_workflow() | write | Execute workflow action |
| get_statistics() | read | Dashboard stats |

### Features:

- ✅ Permission decorators
- ✅ Transaction management
- ✅ Operation logging
- ✅ Validation layer
- ✅ Business rules separation
- ✅ Factory function for DI

---
Create this service?

Step 6: Execute and Verify

After approval, create service file and run tests.

Output Format

## Service Created

**Name:** <ServiceName>Service
**Path:** <app>/<module>/services/<service_name>.py

### Features:
- ✅ Base service inheritance
- ✅ Repository integration
- ✅ Permission checking
- ✅ Transaction management
- ✅ Business logic methods
- ✅ Factory function

### Usage:

```python
from <app>.<module>.services.<service_name> import <ServiceName>Service

service = <ServiceName>Service()

# Create
result = service.create({"title": "New Record"})

# Submit
service.submit(result["name"])

# Get statistics
stats = service.get_statistics(period="month")

## Rules

1. **Single Responsibility** — Each service handles one domain/aggregate
2. **Use Repositories** — Services call repositories for data access; repositories handle `frappe.db`/`frappe.get_doc`
3. **Transaction Awareness** — Frappe auto-commits on success; use `@with_transaction` only for explicit rollback needs
4. **Permission Checks** — Always check permissions at service boundary
5. **Validation First** — Validate before any business logic
6. **Factory Pattern** — Use factory function for easier testing/mocking
7. **ALWAYS Confirm** — Never create files without explicit user approval

## Security Guidelines

1. **SQL Injection Prevention** — Use `frappe.db.sql()` with parameterized queries:
   ```python
   # CORRECT: Parameterized
   frappe.db.sql("SELECT name FROM tabUser WHERE email=%s", [email])

   # WRONG: String formatting (SQL injection risk)
   frappe.db.sql(f"SELECT name FROM tabUser WHERE email='{email}'")
  1. Avoid eval/exec — Never use eval() or exec() with user input. Use frappe.safe_eval() if code evaluation is absolutely required.

  2. Permission Bypass Awareness — frappe.db.set_value() and frappe.get_all() bypass permissions. Use only for system operations, never for user-facing code.

  3. Input Sanitization — Validate and sanitize all user inputs. Use type annotations for automatic v15 validation.

Frappe Testing Suite

Create comprehensive test coverage for Frappe v15 applications using pytest-compatible test classes, fixtures, and factory patterns.

When to Use

  • Adding test coverage to existing code
  • Creating tests for new DocTypes/APIs/Services
  • Setting up test fixtures and factories
  • Writing integration tests with database access
  • Creating unit tests without database dependency

Arguments

/frappe-test <target> [--type <unit|integration|e2e>] [--coverage]

Examples:

/frappe-test SalesOrder
/frappe-test inventory_service --type unit
/frappe-test api.orders --type integration --coverage

Procedure

Step 1: Analyze Test Target

Identify what needs to be tested:

  1. DocType — Controller lifecycle hooks, validation, business rules
  2. Service — Business logic, orchestration, error handling
  3. Repository — Data access patterns, queries
  4. API — Endpoints, authentication, input validation
  5. Utility — Helper functions, formatters

Step 2: Determine Test Strategy

Based on target, determine appropriate test types:

ComponentUnit TestIntegration TestE2E Test
DocType Controller✓ (hooks)✓ (full lifecycle)—
Service Layer✓ (logic)✓ (with DB)—
Repository—✓ (queries)—
API Endpoint✓ (validation)✓ (full request)✓
Utility Functions✓——

Step 3: Generate Test Structure

Create test directory structure:

<app>/tests/
├── __init__.py
├── conftest.py           # Pytest fixtures
├── factories/            # Test data factories
│   ├── __init__.py
│   └── <doctype>_factory.py
├── unit/                 # Unit tests (no DB)
│   ├── __init__.py
│   └── test_<module>.py
├── integration/          # Integration tests (with DB)
│   ├── __init__.py
│   └── test_<module>.py
└── e2e/                  # End-to-end tests
    └── test_workflows.py

Step 4: Generate conftest.py (Pytest Configuration)

"""
Pytest configuration and fixtures for <app>.

Usage:
    bench --site test_site run-tests --app <app>
    bench --site test_site run-tests --app <app> -k "test_name"
"""

import pytest
import frappe
from frappe.tests import IntegrationTestCase
from typing import Generator, Any


# ──────────────────────────────────────────────────────────────────────────────
# Session-scoped Fixtures (run once per test session)
# ──────────────────────────────────────────────────────────────────────────────

@pytest.fixture(scope="session")
def app_context():
    """Initialize Frappe app context for testing."""
    # Frappe handles this automatically, but explicit setup can be added here
    yield
    # Cleanup after all tests


@pytest.fixture(scope="session")
def test_admin_user() -> str:
    """Get or create admin user for tests."""
    return "Administrator"


# ──────────────────────────────────────────────────────────────────────────────
# Module-scoped Fixtures (run once per test module)
# ──────────────────────────────────────────────────────────────────────────────

@pytest.fixture(scope="module")
def test_user() -> Generator[str, None, None]:
    """
    Create a test user for the module.

    Yields:
        User email/name
    """
    email = "test_user@example.com"

    if not frappe.db.exists("User", email):
        user = frappe.get_doc({
            "doctype": "User",
            "email": email,
            "first_name": "Test",
            "last_name": "User",
            "send_welcome_email": 0
        })
        user.insert(ignore_permissions=True)
        user.add_roles("System Manager")

    yield email

    # Cleanup: optionally delete user after module tests
    # frappe.delete_doc("User", email, force=True)


@pytest.fixture(scope="module")
def api_credentials(test_user: str) -> Generator[dict, None, None]:
    """
    Generate API credentials for test user.

    Yields:
        Dict with api_key and api_secret
    """
    user = frappe.get_doc("User", test_user)

    # Generate API keys if not exists
    api_key = user.api_key or frappe.generate_hash(length=15)
    api_secret = frappe.generate_hash(length=15)

    if not user.api_key:
        user.api_key = api_key
        user.api_secret = api_secret
        user.save(ignore_permissions=True)

    yield {
        "api_key": api_key,
        "api_secret": api_secret,
        "authorization": f"token {api_key}:{api_secret}"
    }


# ──────────────────────────────────────────────────────────────────────────────
# Function-scoped Fixtures (run for each test)
# ──────────────────────────────────────────────────────────────────────────────

@pytest.fixture
def as_user(test_user: str) -> Generator[str, None, None]:
    """
    Run test as specific user.

    Usage:
        def test_something(as_user):
            # Test runs as test_user
            pass
    """
    original_user = frappe.session.user
    frappe.set_user(test_user)
    yield test_user
    frappe.set_user(original_user)


@pytest.fixture
def as_guest() -> Generator[str, None, None]:
    """Run test as Guest user."""
    original_user = frappe.session.user
    frappe.set_user("Guest")
    yield "Guest"
    frappe.set_user(original_user)


@pytest.fixture
def rollback_db():
    """
    Rollback database after test.

    Useful for tests that modify data but shouldn't persist changes.
    """
    frappe.db.begin()
    yield
    frappe.db.rollback()


# ──────────────────────────────────────────────────────────────────────────────
# Test Data Fixtures
# ──────────────────────────────────────────────────────────────────────────────

@pytest.fixture
def sample_<doctype>(rollback_db) -> Generator[Any, None, None]:
    """
    Create sample <DocType> for testing.

    Yields:
        <DocType> document instance
    """
    from <app>.tests.factories.<doctype>_factory import <DocType>Factory

    doc = <DocType>Factory.create()
    yield doc
    # Cleanup handled by rollback_db


# ──────────────────────────────────────────────────────────────────────────────
# Assertion Helpers
# ──────────────────────────────────────────────────────────────────────────────

@pytest.fixture
def assert_doc_exists():
    """Helper to assert document existence."""
    def _assert(doctype: str, name: str, should_exist: bool = True):
        exists = frappe.db.exists(doctype, name)
        if should_exist:
            assert exists, f"{doctype} {name} should exist but doesn't"
        else:
            assert not exists, f"{doctype} {name} should not exist but does"
    return _assert


@pytest.fixture
def assert_permission():
    """Helper to assert permission checks."""
    def _assert(
        doctype: str,
        ptype: str,
        user: str,
        should_have: bool = True,
        doc: Any = None
    ):
        frappe.set_user(user)
        has_perm = frappe.has_permission(doctype, ptype, doc=doc)
        frappe.set_user("Administrator")

        if should_have:
            assert has_perm, f"{user} should have {ptype} permission on {doctype}"
        else:
            assert not has_perm, f"{user} should not have {ptype} permission on {doctype}"
    return _assert

Step 5: Generate Factory Pattern

Create <app>/tests/factories/<doctype>_factory.py:

"""
Factory for creating <DocType> test data.

Usage:
    from <app>.tests.factories.<doctype>_factory import <DocType>Factory

    # Create with defaults
    doc = <DocType>Factory.create()

    # Create with custom values
    doc = <DocType>Factory.create(title="Custom Title", status="Completed")

    # Create without saving (for unit tests)
    doc = <DocType>Factory.build()

    # Create multiple
    docs = <DocType>Factory.create_batch(5)
"""

import frappe
from frappe.utils import today, random_string
from typing import Optional, Any
from dataclasses import dataclass, field


@dataclass
class <DocType>Factory:
    """Factory for <DocType> test documents."""

    # Default values
    title: str = field(default_factory=lambda: f"Test {random_string(8)}")
    date: str = field(default_factory=today)
    status: str = "Draft"
    description: Optional[str] = None

    # Related data (Links)
    # customer: Optional[str] = None

    @classmethod
    def build(cls, **kwargs) -> Any:
        """
        Build document instance without saving.

        Returns:
            Unsaved Document instance
        """
        factory = cls(**kwargs)
        return frappe.get_doc({
            "doctype": "<DocType>",
            "title": factory.title,
            "date": factory.date,
            "status": factory.status,
            "description": factory.description,
        })

    @classmethod
    def create(cls, **kwargs) -> Any:
        """
        Create and save document.

        Returns:
            Saved Document instance
        """
        doc = cls.build(**kwargs)
        doc.insert(ignore_permissions=True)
        return doc

    @classmethod
    def create_batch(cls, count: int, **kwargs) -> list[Any]:
        """
        Create multiple documents.

        Args:
            count: Number of documents to create
            **kwargs: Common attributes for all documents

        Returns:
            List of created documents
        """
        return [cls.create(**kwargs) for _ in range(count)]

    @classmethod
    def create_submitted(cls, **kwargs) -> Any:
        """
        Create and submit document (for submittable DocTypes).

        Returns:
            Submitted Document instance
        """
        doc = cls.create(**kwargs)
        doc.submit()
        return doc

    @classmethod
    def create_with_items(
        cls,
        item_count: int = 3,
        **kwargs
    ) -> Any:
        """
        Create document with child table items.

        Args:
            item_count: Number of items to add
            **kwargs: Document attributes

        Returns:
            Document with child items
        """
        doc = cls.build(**kwargs)

        # Add child items
        for i in range(item_count):
            doc.append("items", {
                "item_code": f"ITEM-{i:03d}",
                "qty": i + 1,
                "rate": 100.0 * (i + 1)
            })

        doc.insert(ignore_permissions=True)
        return doc


# ──────────────────────────────────────────────────────────────────────────────
# Sequence Generator for Unique Values
# ──────────────────────────────────────────────────────────────────────────────

class Sequence:
    """Generate unique sequential values for tests."""

    _counters: dict[str, int] = {}

    @classmethod
    def next(cls, name: str = "default") -> int:
        """Get next value in sequence."""
        cls._counters[name] = cls._counters.get(name, 0) + 1
        return cls._counters[name]

    @classmethod
    def reset(cls, name: Optional[str] = None) -> None:
        """Reset sequence counter(s)."""
        if name:
            cls._counters[name] = 0
        else:
            cls._counters.clear()

Step 6: Generate Integration Tests

Create <app>/tests/integration/test_<target>.py:

"""
Integration tests for <Target>.

These tests require database access and test full workflows.

Run with:
    bench --site test_site run-tests --app <app> --module <app>.tests.integration.test_<target>
"""

import pytest
import frappe
from frappe.tests import IntegrationTestCase
from <app>.<module>.services.<target>_service import <Target>Service
from <app>.tests.factories.<doctype>_factory import <DocType>Factory


class Test<Target>Integration(IntegrationTestCase):
    """Integration tests for <Target>."""

    @classmethod
    def setUpClass(cls):
        """Set up test fixtures once for all tests in class."""
        super().setUpClass()
        cls.service = <Target>Service()

    def setUp(self):
        """Set up before each test."""
        frappe.set_user("Administrator")

    def tearDown(self):
        """Clean up after each test."""
        frappe.db.rollback()

    # ──────────────────────────────────────────────────────────────────────────
    # CRUD Operations
    # ──────────────────────────────────────────────────────────────────────────

    def test_create_document(self):
        """Test creating a new document through service."""
        data = {
            "title": "Integration Test Document",
            "date": frappe.utils.today(),
            "description": "Created via integration test"
        }

        result = self.service.create(data)

        self.assertIsNotNone(result.get("name"))
        self.assertEqual(result.get("title"), data["title"])

        # Verify in database
        self.assertTrue(
            frappe.db.exists("<DocType>", result["name"])
        )

    def test_create_validates_mandatory_fields(self):
        """Test that mandatory field validation works."""
        with self.assertRaises(frappe.ValidationError) as context:
            self.service.create({})

        self.assertIn("required", str(context.exception).lower())

    def test_update_document(self):
        """Test updating existing document."""
        doc = <DocType>Factory.create()

        result = self.service.update(doc.name, {"title": "Updated Title"})

        self.assertEqual(result["title"], "Updated Title")

        # Verify in database
        db_value = frappe.db.get_value("<DocType>", doc.name, "title")
        self.assertEqual(db_value, "Updated Title")

    def test_update_nonexistent_raises_error(self):
        """Test updating non-existent document raises error."""
        with self.assertRaises(Exception):
            self.service.update("NONEXISTENT-001", {"title": "Test"})

    def test_delete_document(self):
        """Test deleting document."""
        doc = <DocType>Factory.create()
        name = doc.name

        self.service.repo.delete(name)

        self.assertFalse(frappe.db.exists("<DocType>", name))

    # ──────────────────────────────────────────────────────────────────────────
    # Business Logic
    # ──────────────────────────────────────────────────────────────────────────

    def test_submit_workflow(self):
        """Test document submission workflow."""
        doc = <DocType>Factory.create()

        result = self.service.submit(doc.name)

        self.assertEqual(result["status"], "Completed")

        # Verify docstatus
        docstatus = frappe.db.get_value("<DocType>", doc.name, "docstatus")
        self.assertEqual(docstatus, 1)

    def test_cancel_reverses_submission(self):
        """Test cancellation reverses submission effects."""
        doc = <DocType>Factory.create_submitted()

        result = self.service.cancel(doc.name, reason="Test cancellation")

        self.assertEqual(result["status"], "Cancelled")

    def test_cannot_modify_completed_documents(self):
        """Test that completed documents cannot be modified."""
        doc = <DocType>Factory.create(status="Completed")

        with self.assertRaises(frappe.ValidationError):
            self.service.update(doc.name, {"title": "Should Fail"})

    # ──────────────────────────────────────────────────────────────────────────
    # Permissions
    # ──────────────────────────────────────────────────────────────────────────

    def test_unauthorized_user_cannot_create(self):
        """Test that unauthorized users cannot create documents."""
        # Create user without create permission
        test_email = "no_create@example.com"
        if not frappe.db.exists("User", test_email):
            frappe.get_doc({
                "doctype": "User",
                "email": test_email,
                "first_name": "No Create",
                "send_welcome_email": 0
            }).insert(ignore_permissions=True)

        frappe.set_user(test_email)

        with self.assertRaises(frappe.PermissionError):
            self.service.create({"title": "Should Fail"})

    def test_owner_can_read_own_document(self):
        """Test that document owner can read their own document."""
        test_email = "owner_test@example.com"
        if not frappe.db.exists("User", test_email):
            user = frappe.get_doc({
                "doctype": "User",
                "email": test_email,
                "first_name": "Owner",
                "send_welcome_email": 0
            }).insert(ignore_permissions=True)
            user.add_roles("System Manager")

        frappe.set_user(test_email)
        doc = <DocType>Factory.create()

        # Should not raise
        result = self.service.repo.get(doc.name)
        self.assertIsNotNone(result)

    # ──────────────────────────────────────────────────────────────────────────
    # Query & List Operations
    # ──────────────────────────────────────────────────────────────────────────

    def test_get_list_returns_paginated_results(self):
        """Test list retrieval with pagination."""
        # Create test data
        <DocType>Factory.create_batch(15)

        results = self.service.repo.get_list(limit=10, offset=0)

        self.assertLessEqual(len(results), 10)

    def test_get_list_filters_by_status(self):
        """Test filtering list by status."""
        <DocType>Factory.create(status="Draft")
        <DocType>Factory.create(status="Completed")
        <DocType>Factory.create(status="Completed")

        results = self.service.repo.get_by_status("Completed")

        for result in results:
            self.assertEqual(result.get("status"), "Completed")

    def test_search_finds_matching_documents(self):
        """Test search functionality."""
        <DocType>Factory.create(title="Unique Search Term XYZ")
        <DocType>Factory.create(title="Another Document")

        results = self.service.repo.search("Unique Search")

        self.assertTrue(len(results) >= 1)
        self.assertTrue(
            any("Unique" in r.get("title", "") for r in results)
        )

    def test_get_dashboard_stats(self):
        """Test dashboard statistics."""
        <DocType>Factory.create(status="Draft")
        <DocType>Factory.create(status="Completed")

        stats = self.service.get_dashboard_stats()

        self.assertIn("total", stats)
        self.assertIn("draft", stats)
        self.assertIn("completed", stats)
        self.assertGreaterEqual(stats["total"], 2)

Step 7: Generate Unit Tests

Create <app>/tests/unit/test_<target>.py:

"""
Unit tests for <Target>.

These tests do NOT require database access.
They test pure logic and validation functions.

Run with:
    bench --site test_site run-tests --app <app> --module <app>.tests.unit.test_<target>
"""

import pytest
from unittest.mock import Mock, patch, MagicMock
from frappe.tests import UnitTestCase


class Test<Target>Unit(UnitTestCase):
    """Unit tests for <Target> (no database)."""

    def test_validate_mandatory_fields(self):
        """Test mandatory field validation logic."""
        from <app>.<module>.services.base import BaseService

        service = BaseService()

        # Should raise for missing fields
        with self.assertRaises(Exception):
            service.validate_mandatory({}, ["title", "date"])

        # Should pass with all fields
        service.validate_mandatory(
            {"title": "Test", "date": "2024-01-01"},
            ["title", "date"]
        )

    def test_document_summary_format(self):
        """Test document summary returns correct format."""
        # Mock the document
        mock_doc = Mock()
        mock_doc.name = "TEST-001"
        mock_doc.title = "Test Document"
        mock_doc.status = "Draft"
        mock_doc.date = "2024-01-01"

        mock_doc.get_summary = lambda: {
            "name": mock_doc.name,
            "title": mock_doc.title,
            "status": mock_doc.status,
            "date": str(mock_doc.date)
        }

        summary = mock_doc.get_summary()

        self.assertEqual(summary["name"], "TEST-001")
        self.assertIn("title", summary)
        self.assertIn("status", summary)

    @patch("frappe.db.exists")
    def test_repository_exists_check(self, mock_exists):
        """Test repository existence check."""
        from <app>.<module>.repositories.base import BaseRepository

        class TestRepo(BaseRepository):
            doctype = "Test DocType"

        repo = TestRepo()

        # Test when exists
        mock_exists.return_value = True
        self.assertTrue(repo.exists("TEST-001"))

        # Test when not exists
        mock_exists.return_value = False
        self.assertFalse(repo.exists("TEST-002"))

    def test_status_validation(self):
        """Test status values are valid."""
        valid_statuses = ["Draft", "Pending", "Completed", "Cancelled"]
        invalid_status = "InvalidStatus"

        self.assertIn("Draft", valid_statuses)
        self.assertNotIn(invalid_status, valid_statuses)

    def test_date_formatting(self):
        """Test date formatting utilities."""
        from frappe.utils import getdate, formatdate

        date_str = "2024-01-15"
        date_obj = getdate(date_str)

        self.assertEqual(date_obj.year, 2024)
        self.assertEqual(date_obj.month, 1)
        self.assertEqual(date_obj.day, 15)


class Test<Target>Validation(UnitTestCase):
    """Unit tests for validation logic."""

    def test_title_cannot_be_empty(self):
        """Test that empty titles are rejected."""
        invalid_titles = ["", "   ", None]

        for title in invalid_titles:
            with self.subTest(title=title):
                is_valid = bool(title and str(title).strip())
                self.assertFalse(is_valid)

    def test_valid_title_accepted(self):
        """Test that valid titles are accepted."""
        valid_titles = ["Test", "Test Title", "A", "123"]

        for title in valid_titles:
            with self.subTest(title=title):
                is_valid = bool(title and str(title).strip())
                self.assertTrue(is_valid)

Step 8: Show Test Plan and Confirm

## Test Suite Preview

**Target:** <Target>
**Coverage Goal:** >80%

### Test Structure:

📁 <app>/tests/
├── 📄 conftest.py (fixtures)
├── 📁 factories/
│   └── 📄 <doctype>_factory.py
├── 📁 unit/
│   └── 📄 test_<target>.py (12 tests)
└── 📁 integration/
    └── 📄 test_<target>.py (15 tests)

### Test Coverage:

| Category | Tests | Description |
|----------|-------|-------------|
| CRUD | 5 | Create, Read, Update, Delete |
| Business Logic | 4 | Submit, Cancel, Workflows |
| Permissions | 3 | Role-based access control |
| Queries | 3 | List, Filter, Search |
| Validation | 5 | Input validation, edge cases |
| Unit | 7 | Pure logic, no database |

### Commands:

```bash
# Run all tests
bench --site test_site run-tests --app <app>

# Run specific module
bench --site test_site run-tests --module <app>.tests.integration.test_<target>

# Run with coverage
bench --site test_site run-tests --app <app> --coverage

Create this test suite?


### Step 9: Execute and Verify

After approval, create files and run tests:

```bash
bench --site test_site run-tests --app <app> -v

Output Format

## Test Suite Created

**Target:** <Target>
**Files:** 4

### Files Created:
- ✅ conftest.py (pytest fixtures)
- ✅ factories/<doctype>_factory.py
- ✅ unit/test_<target>.py (7 tests)
- ✅ integration/test_<target>.py (15 tests)

### Run Tests:

```bash
# All tests
bench --site test_site run-tests --app <app>

# With verbose output
bench --site test_site run-tests --app <app> -v

# Specific test
bench --site test_site run-tests --app <app> -k "test_create"

Coverage Report:

Run bench --site test_site run-tests --app <app> --coverage for coverage report.


## Rules

1. **Test Isolation** — Each test should be independent, use `rollback_db` fixture
2. **Factory Pattern** — Use factories for test data, never hardcode values
3. **Meaningful Names** — Test names should describe what is being tested
4. **AAA Pattern** — Arrange, Act, Assert structure for each test
5. **Unit vs Integration** — Unit tests = no DB, Integration tests = with DB
6. **Permission Tests** — Always test both authorized and unauthorized access
7. **Edge Cases** — Test empty values, nulls, large inputs, special characters
8. **ALWAYS Confirm** — Never create files without explicit user approval

## Mocking Best Practices

**Mock `frappe.db.commit`** — If code under test calls `frappe.db.commit`, mock it to prevent partial commits:
```python
@patch("myapp.mymodule.frappe.db.commit", new=MagicMock)
def test_something(self):
    # commits are mocked, won't persist to DB
    pass

Use frappe.flags.in_test — Check if running in test context:

if frappe.flags.in_test:  # or frappe.in_test in newer versions
    # Skip external API calls, notifications, etc.
    pass

Test Site Naming — Run tests on sites starting with test_ to avoid accidental data loss:

bench --site test_mysite run-tests --app myapp

Sponsors

Details

Marketplace
sergio-bershadsky/ai
Source
plugins/frappe-dev
Category
Development

More from sergio-bershadsky/ai

All 13