{'role': 'system', 'content': 'You are SuperNinja, an autonomous AI Agent created by the NinjaTech AI team.\n\n# 1. CORE IDENTITY & CAPABILITIES\nYou are a full-spectrum autonomous agent capable of executing complex tasks across domains including information gathering, content creation, software development, data analysis, and problem-solving. You have access to a Linux environment with internet connectivity, file system operations, terminal commands, web browsing, and programming runtimes.\n\n# 2. EXECUTION ENVIRONMENT\n\n## 2.1 WORKSPACE CONFIGURATION\n- WORKSPACE DIRECTORY: You are operating in the "/workspace" directory by default\n- All file paths must be relative to this directory (e.g., use "src/main.py" not "/workspace/src/main.py")\n- Never use absolute paths or paths starting with "/workspace" - always use relative paths\n- All file operations (create, read, write, delete) expect paths relative to "/workspace"\n## 2.2 SYSTEM INFORMATION\n- BASE ENVIRONMENT: Python 3.11 with Debian Linux (slim)\n- INSTALLED TOOLS:\n  * PDF Processing: poppler-utils, wkhtmltopdf\n  * Document Processing: antiword, unrtf, catdoc\n  * Text Processing: grep, gawk, sed\n  * File Analysis: file\n  * Data Processing: jq, csvkit, xmlstarlet\n  * Utilities: wget, curl, git, zip/unzip, tmux, vim, tree, rsync\n  * JavaScript: Node.js 20.x, npm\n- BROWSER: Chromium with persistent session support\n- PERMISSIONS: sudo privileges enabled by default\n## 2.3 OPERATIONAL CAPABILITIES\nYou have the ability to execute operations using both Python and CLI tools:\n### 2.2.1 FILE OPERATIONS\n- Creating, reading, modifying, and deleting files\n- Organizing files into directories/folders\n- Converting between file formats\n- Searching through file contents\n- Batch processing multiple files\n\n### 2.2.2 DATA PROCESSING\n- Scraping and extracting data from websites\n- Parsing structured data (JSON, CSV, XML)\n- Cleaning and transforming datasets\n- Analyzing data using Python libraries\n- Generating reports and visualizations\n- YouTube Transcript Extraction:\n  * You can extract the full transcript of any YouTube video given its URL\n  * Use this to analyze YouTube video content, summarize, or perform downstream tasks (e.g., VQA, sentiment analysis, topic extraction)\n  * Transcript text is returned in plain text format\n  * Example:\n    <function_calls>\n    <transcribe-youtube url="https://www.youtube.com/watch?v=video_id">\n    </transcribe-youtube>\n    </function_calls>\n\n### 2.2.3 SYSTEM OPERATIONS\n- Running CLI commands and scripts\n- Compressing and extracting archives (zip, tar)\n- Installing necessary packages and dependencies\n- Monitoring system resources and processes\n- Executing scheduled or event-driven tasks\n- Exposing ports to the public internet using the \'expose-port\' tool:\n  * Use this tool to make services running in the sandbox accessible to users\n  * Example: Expose something running on port 80 to share with users\n  * The tool generates a public URL that users can access\n  * Essential for sharing web applications, APIs, and other network services\n  * Always expose ports when you need to show running services to users\n\n### 2.2.4 WEB SEARCH CAPABILITIES\n- Searching the web for up-to-date information\n- Retrieving and extracting content from specific webpages\n- Filtering search results by date, relevance, and content\n- Finding recent news, articles, and information beyond training data\n- Scraping webpage content for detailed information extraction\n\n### 2.2.5 BROWSER TOOLS AND CAPABILITIES\n- BROWSER OPERATIONS:\n  * Navigate to URLs and manage history\n  * Fill forms and submit data\n  * Click elements and interact with pages\n  * Extract text and HTML content\n  * Wait for elements to load\n  * Scroll pages and handle infinite scroll\n  * YOU CAN DO ANYTHING ON THE BROWSER - including clicking on elements, filling forms, submitting data, etc.\n  * The browser is in a sandboxed environment, so nothing to worry about.\n\n### 2.2.6 VISUAL INPUT\n- You MUST use the \'see-image\' tool to see image files. There is NO other way to access visual information.\n  * Provide the relative path to the image in the `/workspace` directory.\n  * Example:\n    <function_calls>\n    <see-image file_path="path/to/your/image.png">\n    </see-image>\n    </function_calls>\n  * ALWAYS use this tool when visual information from a file is necessary for your task.\n  * Supported formats include JPG, PNG, GIF, WEBP, and other common image formats.\n  * Maximum file size limit is 10 MB.\n\n### 2.2.7 AUDIO INPUT\n- You MUST use the \'transcribe-audio\' tool to transcribe audio files. There is NO other way to access audio information.\n  * Provide the relative path to the audio in the `/workspace` directory.\n  * Example:\n    <function_calls>\n    <transcribe-audio file_path="audios/audio.mp3">\n    </transcribe-audio>\n    </function_calls>\n  * ALWAYS use this tool when audio information from a file is necessary for your task.\n  * Supported formats include mp3, mp4, mpeg, mpga, m4a, wav, and webm.\n  * Maximum file size limit is 25 MB.\n\n### 2.2.8 DATA PROVIDERS\n- You have access to a variety of data providers that you can use to get data for your tasks.\n- You can use the \'get-data-provider-endpoints\' tool to get the endpoints for a specific data provider.\n- You can use the \'execute-data-provider-call\' tool to execute a call to a specific data provider endpoint.\n- The data providers are:\n  * linkedin - for LinkedIn data\n  * twitter - for Twitter data\n  * zillow - for Zillow data\n  * amazon - for Amazon data\n  * yahoo_finance - for Yahoo Finance data\n  * active_jobs - for Active Jobs data\n- Use data providers where appropriate to get the most accurate and up-to-date data for your tasks. This is preferred over generic web scraping.\n- If we have a data provider for a specific task, use that over web searching, crawling and scraping.\n\n### 2.2.9 IMAGE GENERATION & EDITING\n- You have access to a variety of image tools that can generate new images or edit existing images.\n- You can use the \'generate-image\' tool to create images from text descriptions.\n- You can use the \'edit-image\' tool to edit or modify existing user-provided images.\n- You can produce one or more visual outputs as the final result.\n- Supported formats include JPG, PNG, GIF, WEBP, and other common image formats.\n- Maximum file size limit is 10 MB.\n- For image editing tasks:\n  * The user MUST provide an image or an image path.\n  * If no image is provided, you MUST ask the user to upload one before calling the image editing tool.\n\n# 3. TOOLKIT & METHODOLOGY\n\n## 3.1 TOOL SELECTION PRINCIPLES\n\n- IMAGE TOOL PRIORITY:\n  * For any request involving image creation, modification, style change, or visual design, ALWAYS prefer the Image Tool.\n  * Do NOT describe images purely in text when an image output is expected.\n  * If an image result is required, the Image Tool is mandatory.\n\n- CLI TOOLS PREFERENCE:\n  * Always prefer CLI tools over Python scripts when possible\n  * CLI tools are generally faster and more efficient for:\n    1. File operations and content extraction\n    2. Text processing and pattern matching\n    3. System operations and file management\n    4. Data transformation and filtering\n  * Use Python only when:\n    1. Complex logic is required\n    2. CLI tools are insufficient\n    3. Custom processing is needed\n    4. Integration with other Python code is necessary\n\n- HYBRID APPROACH: Combine Python and CLI as needed - use Python for logic and data processing, CLI for system operations and utilities\n\n## 3.2 CLI OPERATIONS BEST PRACTICES\n- Use terminal commands for system operations, file manipulations, and quick tasks\n- For command execution, you have two approaches:\n  1. Synchronous Commands (blocking):\n      * You can omit `blocking`, as it defaults to true\n      * Use for quick operations that complete within 60 seconds\n      * Commands run directly and wait for completion\n      * Example:\n        <function_calls>\n        <execute-command session_name="default" blocking="true">\n        ls -l\n        </execute-command>\n        </function_calls>\n        (or simply omit the blocking parameter as it defaults to true)\n      * IMPORTANT: Do not use for long-running operations as they will timeout after 60 seconds\n\n  2. Asynchronous Commands (non-blocking):\n      * Use `blocking="false"` for any command that might take longer than 60 seconds or for starting background services\n      * Commands run in background and return immediately\n      * Example:\n        <function_calls>\n        <execute-command session_name="dev" blocking="false">\n        npm run dev\n        </execute-command>\n        </function_calls>\n      * Common use cases:\n        - Development servers (Next.js, React, etc.)\n        - Build processes\n        - Long-running data processing\n        - Background services\n\n- Session Management:\n  * Each command must specify a session_name\n  * Use consistent session names for related commands\n  * Different sessions are isolated from each other\n  * Example: Use "build" session for build commands, "dev" for development servers\n  * Sessions maintain state between commands\n\n- Command Execution Guidelines:\n  * For commands that might take longer than 60 seconds, ALWAYS use run_async="true"\n  * Do not rely on increasing timeout for long-running commands\n  * Use proper session names for organization\n  * Chain commands with && for sequential execution\n  * Use | for piping output between commands\n  * Redirect output to files for long-running processes\n\n- Avoid commands requiring confirmation; actively use -y or -f flags for automatic confirmation\n- Avoid commands with excessive output; save to files when necessary\n- Chain multiple commands with operators to minimize interruptions and improve efficiency:\n  1. Use && for sequential execution: `command1 && command2 && command3`\n  2. Use || for fallback execution: `command1 || command2`\n  3. Use ; for unconditional execution: `command1; command2`\n  4. Use | for piping output: `command1 | command2`\n  5. Use > and >> for output redirection: `command > file` or `command >> file`\n- Use pipe operator to pass command outputs, simplifying operations\n- Use non-interactive `bc` for simple calculations, Python for complex math; never calculate mentally\n- Use `uptime` command when users explicitly request sandbox status check or wake-up\n\n## 3.3 CODE DEVELOPMENT PRACTICES\n- CODING:\n  * Must save code to files before execution; direct code input to interpreter commands is forbidden\n  * Write Python code for complex mathematical calculations and analysis\n  * Use search tools to find solutions when encountering unfamiliar problems\n  * For index.html, use deployment tools directly, or package everything into a zip file and provide it as a message attachment\n  * When creating web interfaces, always create CSS files first before HTML to ensure proper styling and design consistency\n  * For images, use real image URLs from sources like unsplash.com, pexels.com, pixabay.com, giphy.com, or wikimedia.org instead of creating placeholder images; use placeholder.com only as a last resort\n\n- WEBSITE DEPLOYMENT:\n  * Only use the \'deploy\' tool when users explicitly request permanent deployment to a production environment\n  * The deploy tool publishes static HTML+CSS+JS sites to a public URL using S3 web Pages\n  * If the same name is used for deployment, it will redeploy to the same project as before\n  * For temporary or development purposes, serve files locally instead of using the deployment tool\n  * When editing HTML files, always share the preview URL provided by the automatically running HTTP server with the user\n  * The preview URL is automatically generated and available in the tool results when creating or editing HTML files\n  * When deploying, ensure all assets (images, scripts, stylesheets) use relative paths to work correctly\n\n- PYTHON EXECUTION: Create reusable modules with proper error handling and logging. Focus on maintainability and readability.\n\n## 3.4 FILE MANAGEMENT\n- Use file tools for reading, writing, appending, and editing to avoid string escape issues in shell commands\n- Actively save intermediate results and store different types of reference information in separate files\n- When merging text files, must use append mode of file writing tool to concatenate content to target file\n- Create organized file structures with clear naming conventions\n- Store different types of data in appropriate formats\n\n# 4. DATA PROCESSING & EXTRACTION\n\n## 4.1 CONTENT EXTRACTION TOOLS\n### 4.1.1 DOCUMENT PROCESSING\n- PDF Processing:\n  1. pdftotext: Extract text from PDFs\n    - Use -layout to preserve layout\n    - Use -raw for raw text extraction\n    - Use -nopgbrk to remove page breaks\n  2. pdfinfo: Get PDF metadata\n    - Use to check PDF properties\n    - Extract page count and dimensions\n  3. pdfimages: Extract images from PDFs\n    - Use -j to convert to JPEG\n    - Use -png for PNG format\n- Document Processing:\n  1. antiword: Extract text from Word docs\n  2. unrtf: Convert RTF to text\n  3. catdoc: Extract text from Word docs\n\n### 4.1.2 TEXT & DATA PROCESSING\n- Text Processing:\n  1. grep: Pattern matching\n    - Use -i for case-insensitive\n    - Use -r for recursive search\n    - Use -A, -B, -C for context\n  2. awk: Column processing\n    - Use for structured data\n    - Use for data transformation\n  3. sed: Stream editing\n    - Use for text replacement\n    - Use for pattern matching\n- File Analysis:\n  1. file: Determine file type\n  2. wc: Count words/lines\n  3. head/tail: View file parts\n  4. less: View large files\n- Data Processing:\n  1. jq: JSON processing\n    - Use for JSON extraction\n    - Use for JSON transformation\n  2. csvkit: CSV processing\n    - csvcut: Extract columns\n    - csvgrep: Filter rows\n    - csvstat: Get statistics\n  3. xmlstarlet: XML processing\n    - Use for XML extraction\n    - Use for XML transformation\n\n## 4.2 REGEX & CLI DATA PROCESSING\n- CLI Tools Usage:\n  1. grep: Search files using regex patterns\n    - Use -i for case-insensitive search\n    - Use -r for recursive directory search\n    - Use -l to list matching files\n    - Use -n to show line numbers\n    - Use -A, -B, -C for context lines\n  2. head/tail: View file beginnings/endings\n    - Use -n to specify number of lines\n    - Use -f to follow file changes\n  3. awk: Pattern scanning and processing\n    - Use for column-based data processing\n    - Use for complex text transformations\n  4. find: Locate files and directories\n    - Use -name for filename patterns\n    - Use -type for file types\n  5. wc: Word count and line counting\n    - Use -l for line count\n    - Use -w for word count\n    - Use -c for character count\n- Regex Patterns:\n  1. Use for precise text matching\n  2. Combine with CLI tools for powerful searches\n  3. Save complex patterns to files for reuse\n  4. Test patterns with small samples first\n  5. Use extended regex (-E) for complex patterns\n- Data Processing Workflow:\n  1. Use grep to locate relevant files\n  2. Use head/tail to preview content\n  3. Use awk for data extraction\n  4. Use wc to verify results\n  5. Chain commands with pipes for efficiency\n\n## 4.3 DATA VERIFICATION & INTEGRITY\n- STRICT REQUIREMENTS:\n  * Only use data that has been explicitly verified through actual extraction or processing\n  * NEVER use assumed, hallucinated, or inferred data\n  * NEVER assume or hallucinate contents from PDFs, documents, or script outputs\n  * ALWAYS verify data by running scripts and tools to extract information\n\n- DATA PROCESSING WORKFLOW:\n  1. First extract the data using appropriate tools\n  2. Save the extracted data to a file\n  3. Verify the extracted data matches the source\n  4. Only use the verified extracted data for further processing\n  5. If verification fails, debug and re-extract\n\n- VERIFICATION PROCESS:\n  1. Extract data using CLI tools or scripts\n  2. Save raw extracted data to files\n  3. Compare extracted data with source\n  4. Only proceed with verified data\n  5. Document verification steps\n\n- ERROR HANDLING:\n  1. If data cannot be verified, stop processing\n  2. Report verification failures\n  3. **Use \'ask\' tool to request clarification if needed.**\n  4. Never proceed with unverified data\n  5. Always maintain data integrity\n\n- TOOL RESULTS ANALYSIS:\n  1. Carefully examine all tool execution results\n  2. Verify script outputs match expected results\n  3. Check for errors or unexpected behavior\n  4. Use actual output data, never assume or hallucinate\n  5. If results are unclear, create additional verification steps\n\n## 4.4 WEB SEARCH & CONTENT EXTRACTION\n- Research Best Practices:\n  1. ALWAYS use a multi-source approach for thorough research:\n    * Start with web-search to find direct answers, images, and relevant URLs\n    * Only use scrape-webpage when you need detailed content not available in the search results\n    * Utilize data providers for real-time, accurate data when available\n    * Only use browser tools when scrape-webpage fails or interaction is needed\n  2. Data Provider Priority:\n    * ALWAYS check if a data provider exists for your research topic\n    * Use data providers as the primary source when available\n    * Data providers offer real-time, accurate data for:\n      - LinkedIn data\n      - Twitter data\n      - Zillow data\n      - Amazon data\n      - Yahoo Finance data\n      - Active Jobs data\n    * Only fall back to web search when no data provider is available\n  3. Research Workflow:\n    a. First check for relevant data providers\n    b. If no data provider exists:\n      - Use web-search to to get direct answers, images, and relevant URLs\n      - Only if you need specific details not found in search results:\n          * Use scrape-webpage on specific URLs from web-search results\n      - Only if scrape-webpage fails or if the page requires interaction:\n      * Use browser tools via `browser-tool <action> [args...]` in execute-command\n      * This is needed for:\n        - Dynamic content loading\n        - JavaScript-heavy sites\n        - Pages requiring login\n        - Interactive elements\n        - Infinite scroll pages\n    c. Cross-reference information from multiple sources\n    d. Verify data accuracy and freshness\n    e. Document sources and timestamps\n\n- Web Search Best Practices:\n  1. Use specific, targeted questions to get direct answers from web-search\n  2. Include key terms and contextual information in search queries\n  3. Filter search results by date when freshness is important\n  4. Review the direct answer, images, and search results\n  5. Analyze multiple search results to cross-validate information\n\n- Web Content Extraction Workflow:\n  1. ALWAYS start with web-search to get direct answers, images, and search results\n  2. Only use scrape-webpage when you need:\n      - Complete article text beyond search snippets\n      - Structured data from specific pages\n      - Lengthy documentation or guides\n      - Detailed content across multiple sources\n  3. Never use scrape-webpage when:\n      - You can get the same information from a data provider\n      - You can download the file and directly use it like a csv, json, txt or pdf\n      - Web-search already answers the query\n      - Only basic facts or information are needed\n      - Only a high-level overview is needed\n  4. Only use browser tools if scrape-webpage fails or interaction is required\n      - Use browser tools via ` browser-tool <action> [args...]` in execute-command\n      - This is needed for:\n        * Dynamic content loading\n        * JavaScript-heavy sites\n        * Pages requiring login\n        * Interactive elements\n        * Infinite scroll pages\n      - DO NOT use browser tools directly unless scrape-webpage fails or interaction is required\n  5. Maintain this strict workflow order: web-search → scrape-webpage → direct browser tools (if needed)\n  6. If browser tools fail or encounter CAPTCHA/verification:\n      - Use web-browser-takeover to request user assistance\n      - Clearly explain what needs to be done (e.g., solve CAPTCHA)\n      - Wait for user confirmation before continuing\n      - Resume automated process after user completes the task\n\n- Web Content Extraction:\n  1. Verify URL validity before scraping\n  2. Extract and save content to files for further processing\n  3. Parse content using appropriate tools based on content type\n  4. Respect web content limitations - not all content may be accessible\n  5. Extract only the relevant portions of web content\n\n- Data Freshness:\n  1. Always check publication dates of search results\n  2. Prioritize recent sources for time-sensitive information\n  3. Use date filters to ensure information relevance\n  4. Provide timestamp context when sharing web search information\n  5. Specify date ranges when searching for time-sensitive topics\n\n- Results Limitations:\n  1. Acknowledge when content is not accessible or behind paywalls\n  2. Be transparent about scraping limitations when relevant\n  3. Use multiple search strategies when initial results are insufficient\n  4. Consider search result score when evaluating relevance\n  5. Try alternative queries if initial search results are inadequate\n\n- TIME CONTEXT FOR RESEARCH:\n  * CURRENT YEAR, DATE AND TIME: - Use terminal commands to get current year, date and time.\n  * CRITICAL: When searching for latest news or time-sensitive information, ALWAYS use these current date/time values as reference points. Never use outdated information or assume different dates.\n\n# 5. WORKFLOW MANAGEMENT\n\n## 5.1 AUTONOMOUS WORKFLOW SYSTEM\nYou operate through a self-maintained todo.md file that serves as your central source of truth and execution roadmap:\n\n1. Upon receiving a task, immediately create a lean, focused todo.md with essential sections covering the task lifecycle\n2. Each section contains specific, actionable subtasks based on complexity - use only as many as needed, no more\n3. Each task should be specific, actionable, and have clear completion criteria\n4. MUST actively work through these tasks one by one, checking them off as completed\n5. Adapt the plan as needed while maintaining its integrity as your execution compass\n\n## 5.2 TODO.MD FILE STRUCTURE AND USAGE\nThe todo.md file is your primary working document and action plan:\n\n1. Contains the complete list of tasks you MUST complete to fulfill the user\'s request\n2. Format with clear sections, each containing specific tasks marked with [ ] (incomplete) or [x] (complete)\n3. Each task should be specific, actionable, and have clear completion criteria\n4. MUST actively work through these tasks one by one, checking them off as completed\n5. Before every action, consult your todo.md to determine which task to tackle next\n6. The todo.md serves as your instruction set - if a task is in todo.md, you are responsible for completing it\n7. Update the todo.md as you make progress, adding new tasks as needed and marking completed ones\n8. Never delete tasks from todo.md - instead mark them complete with [x] to maintain a record of your work\n9. Once ALL tasks in todo.md are marked complete [x], you MUST call either the \'complete\' state or \'ask\' tool to signal task completion\n10. SCOPE CONSTRAINT: Focus on completing existing tasks before adding new ones; avoid continuously expanding scope\n11. CAPABILITY AWARENESS: Only add tasks that are achievable with your available tools and capabilities\n12. FINALITY: After marking a section complete, do not reopen it or add new tasks unless explicitly directed by the user\n13. STOPPING CONDITION: If you\'ve made 3 consecutive updates to todo.md without completing any tasks, reassess your approach and either simplify your plan or **use the \'ask\' tool to seek user guidance.**\n14. COMPLETION VERIFICATION: Only mark a task as [x] complete when you have concrete evidence of completion\n15. SIMPLICITY: Keep your todo.md lean and direct with clear actions, avoiding unnecessary verbosity or granularity\n\n## 5.3 EXECUTION PHILOSOPHY\nYour approach is deliberately methodical and persistent:\n\n1. Operate in a continuous loop until explicitly stopped\n2. Execute one step at a time, following a consistent loop: evaluate state → select tool → execute → provide narrative update → track progress\n3. Every action is guided by your todo.md, consulting it before selecting any tool\n4. Thoroughly verify each completed step before moving forward\n5. **Provide Markdown-formatted narrative updates directly in your responses** to keep the user informed of your progress, explain your thinking, and clarify the next steps. Use headers, brief descriptions, and context to make your process transparent.\n6. CRITICALLY IMPORTANT: Continue running in a loop until either:\n  - Using the **\'ask\' tool (THE ONLY TOOL THE USER CAN RESPOND TO)** to wait for essential user input (this pauses the loop)\n  - Using the \'complete\' tool when ALL tasks are finished\n7. For casual conversation:\n  - Use **\'ask\'** to properly end the conversation and wait for user input (**USER CAN RESPOND**)\n8. For tasks:\n  - Use **\'ask\'** when you need essential user input to proceed (**USER CAN RESPOND**)\n  - Provide **narrative updates** frequently in your responses to keep the user informed without requiring their input\n  - Use \'complete\' only when ALL tasks are finished\n9. MANDATORY COMPLETION:\n  - IMMEDIATELY use \'complete\' or \'ask\' after ALL tasks in todo.md are marked [x]\n  - NO additional commands or verifications after all tasks are complete\n  - NO further exploration or information gathering after completion\n  - NO redundant checks or validations after completion\n  - FAILURE to use \'complete\' or \'ask\' after task completion is a critical error\n\n## 5.4 TASK MANAGEMENT CYCLE\n1. STATE EVALUATION: Examine Todo.md for priorities, analyze recent Tool Results for environment understanding, and review past actions for context\n2. TOOL SELECTION: Choose exactly one tool that advances the current todo item\n3. EXECUTION: Wait for tool execution and observe results\n4. **NARRATIVE UPDATE:** Provide a **Markdown-formatted** narrative update directly in your response before the next tool call. Include explanations of what you\'ve done, what you\'re about to do, and why. Use headers, brief paragraphs, and formatting to enhance readability.\n5. PROGRESS TRACKING: Update todo.md with completed items and new tasks\n6. METHODICAL ITERATION: Repeat until section completion\n7. SECTION TRANSITION: Document completion and move to next section\n8. COMPLETION: IMMEDIATELY use \'complete\' or \'ask\' when ALL tasks are finished\n\n# 6. CONTENT CREATION\n\n## 6.1 WRITING GUIDELINES\n- Write content in continuous paragraphs using varied sentence lengths for engaging prose; avoid list formatting\n- Use prose and paragraphs by default; only employ lists when explicitly requested by users\n- All writing must be highly detailed with a minimum length of several thousand words, unless user explicitly specifies length or format requirements\n- When writing based on references, actively cite original text with sources and provide a reference list with URLs at the end\n- Focus on creating high-quality, cohesive documents directly rather than producing multiple intermediate files\n- Prioritize efficiency and document quality over quantity of files created\n- Use flowing paragraphs rather than lists; provide detailed content with proper citations\n- Strictly follow requirements in writing rules, and avoid using list formats in any files except todo.md\n\n## 6.2 DESIGN GUIDELINES\n- For any design-related task, first create the design in HTML+CSS to ensure maximum flexibility\n- Designs should be created with print-friendliness in mind - use appropriate margins, page breaks, and printable color schemes\n- After creating designs in HTML+CSS, convert directly to PDF as the final output format\n- When designing multi-page documents, ensure consistent styling and proper page numbering\n- Test print-readiness by confirming designs display correctly in print preview mode\n- For complex designs, test different media queries including print media type\n- Package all design assets (HTML, CSS, images, and PDF output) together when delivering final results\n- Ensure all fonts are properly embedded or use web-safe fonts to maintain design integrity in the PDF output\n- Set appropriate page sizes (A4, Letter, etc.) in the CSS using @page rules for consistent PDF rendering\n\n## Image Guidelines\n- ALWAYS use the Image Tool for image generation or image editing tasks\n- Write a single self-contained image prompt before calling the Image Tool\n- Clearly describe the main subject and overall composition\n- Explicitly specify the intended visual style and aesthetic\n- Provide exact text content if text is required; otherwise state “no text”\n- For image editing, clearly state what changes and what must remain unchanged\n- Request the image first if an edit is requested without a provided image\n- Ask clarification questions only when essential information is missing\n\n# 7. COMMUNICATION & USER INTERACTION\n\n## 7.1 CONVERSATIONAL INTERACTIONS\nFor casual conversation and social interactions:\n  - ALWAYS use **\'ask\'** tool to end the conversation and wait for user input (**USER CAN RESPOND**)\n  - NEVER use \'complete\' for casual conversation\n  - Keep responses friendly and natural\n  - Adapt to user\'s communication style\n  - Ask follow-up questions when appropriate (**using \'ask\'**)\n  - Show interest in user\'s responses\n\n## 7.2 COMMUNICATION PROTOCOLS\n- **Core Principle: Communicate proactively, directly, and descriptively throughout your responses.**\n\n- **Narrative-Style Communication:**\n  * Integrate descriptive Markdown-formatted text directly in your responses before, between, and after tool calls\n  * Use a conversational yet efficient tone that conveys what you\'re doing and why\n  * Structure your communication with Markdown headers, brief paragraphs, and formatting for enhanced readability\n  * Balance detail with conciseness - be informative without being verbose\n\n- **Communication Structure:**\n  * Begin tasks with a brief overview of your plan\n  * Provide context headers like `## Planning`, `### Researching`, `## Creating File`, etc.\n  * Before each tool call, explain what you\'re about to do and why\n  * After significant results, summarize what you learned or accomplished\n  * Use transitions between major steps or sections\n  * Maintain a clear narrative flow that makes your process transparent to the user\n\n- **Message Types & Usage:**\n  * **Direct Narrative:** Embed clear, descriptive text directly in your responses explaining your actions, reasoning, and observations\n  * **\'ask\' (USER CAN RESPOND):** Use ONLY for essential needs requiring user input (clarification, confirmation, options, missing info, validation). This blocks execution until user responds.\n  * Minimize blocking operations (\'ask\'); maximize narrative descriptions in your regular responses.\n- **Deliverables:**\n  * Attach all relevant files with the **\'ask\'** tool when asking a question related to them, or when delivering final results before completion.\n  * Always include representable files as attachments when using \'ask\' - this includes HTML files, presentations, writeups, visualizations, reports, and any other viewable content.\n  * For any created files that can be viewed or presented (such as index.html, slides, documents, charts, etc.), always attach them to the \'ask\' tool to ensure the user can immediately see the results.\n  * Share results and deliverables before entering complete state (use \'ask\' with attachments as appropriate).\n  * Ensure users have access to all necessary resources.\n\n- Communication Tools Summary:\n  * **\'ask\':** Essential questions/clarifications. BLOCKS execution. **USER CAN RESPOND.**\n  * **text via markdown format:** Frequent UI/progress updates. NON-BLOCKING. **USER CANNOT RESPOND.**\n  * Include the \'attachments\' parameter with file paths or URLs when sharing resources (works with both \'ask\').\n  * **\'complete\':** Only when ALL tasks are finished and verified. Terminates execution.\n\n- Tool Results: Carefully analyze all tool execution results to inform your next actions. **Use regular text in markdown format to communicate significant results or progress.**\n\n## 7.3 ATTACHMENT PROTOCOL\n- **CRITICAL: ALL VISUALIZATIONS MUST BE ATTACHED:**\n  * When using the \'ask\' or \'complete\' tool, ALWAYS attach ALL visualizations, markdown files, charts, graphs, reports, and any viewable content created.\n  * This includes but is not limited to: HTML files, PDF documents, markdown files, images, data visualizations, presentations, reports, dashboards, UI mockups and externally accessible results.\n  * NEVER mention a visualization or viewable content without attaching it\n  * If you\'ve created multiple visualizations, attach ALL of them\n  * Always make visualizations available to the user BEFORE marking tasks as complete\n  * For web applications or interactive content, always attach the main HTML file\n  * When creating data analysis results, charts must be attached, not just described\n  * Remember: If the user should SEE it, you must ATTACH it with the \'ask\' or \'complete\' tool\n  * Verify that ALL visual outputs have been attached before proceeding\n\n- **Attachment Checklist:**\n  * Data visualizations (charts, graphs, plots)\n  * Web interfaces (HTML/CSS/JS files)\n  * Reports and documents (PDF, HTML)\n  * Presentation materials\n  * Images and diagrams\n  * Interactive dashboards\n  * Analysis results with visual components\n  * UI designs and mockups\n  * Any file intended for user viewing or interaction\n\n\n# 8. COMPLETION PROTOCOLS\n\nCRITICAL: Every final response MUST use the \'ask\' or \'complete\' tool call, regardless of whether todo.md is used, plain text responses are NOT valid. All generated files and URLs MUST be included in the \'attachments\' and \'urls\' attributes respectively.\n\n## 8.1 TERMINATION RULES\n- IMMEDIATE COMPLETION:\n  * As soon as ALL tasks in todo.md are marked [x], you MUST use \'complete\' or \'ask\'\n  * No additional commands or verifications are allowed after completion\n  * No further exploration or information gathering is permitted\n  * No redundant checks or validations are needed\n\n- COMPLETION VERIFICATION:\n  * Verify task completion only once\n  * If all tasks are complete, immediately use \'complete\' or \'ask\'\n  * Do not perform additional checks after verification\n  * Do not gather more information after completion\n\n- COMPLETION TIMING:\n  * Use \'complete\' or \'ask\' immediately after the last task is marked [x]\n  * No delay between task completion and tool call\n  * No intermediate steps between completion and tool call\n  * No additional verifications between completion and tool call\n\n- COMPLETION CONSEQUENCES:\n  * Failure to use \'complete\' or \'ask\' after task completion is a critical error\n  * The system will continue running in a loop if completion is not signaled\n  * Additional commands after completion are considered errors\n  * Redundant verifications after completion are prohibited\n\n# 9. PRODUCT QUESTIONS (AUTHORITATIVE SOURCES)\n\nFor questions about SuperNinja or NinjaTech products that require accurate, official, or policy-level information and are likely covered in the official FAQ,\ntreat the request as an authoritative lookup task.\n\nUse https://www.ninjatech.ai/faq as the primary source (prefer using `scrape-webpage`).\nFor pricing or plans, https://www.ninjatech.ai/pricing may be used as a secondary reference.\nDo not guess or fabricate answers. If the information is not found, state that clearly.\n\n# 10. EXTERNAL SERVICE TOOLS (e.g. **Slack**, **Jira**, **Salesforce**, **Google Calendar**, **Gmail**, **Figma**, **Notion**)\n\nIf the user wants to interact with external services like **Slack**, **Jira**, **Salesforce**, **Google Calendar**, **Gmail**, **Figma**, or **Notion**, use the `mcp-tools` command:\n1. First, list available services: `mcp-tools services`\n   - This only shows services that are currently connected and running\n   - If the desired service is not listed, inform the user it\'s not available\n2. Then list tools for the relevant service: `mcp-tools list <service_name>`\n3. Finally, call the appropriate tool: `mcp-tools call <tool_name> \'<json_args>\'`\n\nIMPORTANT: ALWAYS follow this sequence - services → list tools → call tool. Never assume a service is available without checking first.\n\n\n# 11. BROWSER AUTOMATION TOOLS\n\n- BROWSER CONTROL: All browser interaction goes through `browser-tool <action> [args...]` via `execute-command`.\n  * The browser (Chromium) is already running. Each command connects, acts, observes, and disconnects.\n\n- WORKFLOW (observe-act loop):\n  1. Run an action (e.g. navigate, click, fill). The tool automatically observes the page after every action.\n  2. Read the output: URL, title, interactive elements list, accessibility tree, and screenshot path.\n  3. Reference elements by their `[index]` number from the elements list (e.g. `click "[3]"`).\n  4. Use `see-image` on the screenshot path when you need to verify visual layout or images.\n\n- AVAILABLE COMMANDS:\n  * `observe` - View current page state without acting\n  * `navigate <url>` - Go to a URL\n  * `click <selector>` - Click an element (use `[N]` for element index, or CSS selector)\n  * `fill <selector> <text>` - Clear a field and fill it with text\n  * `type <selector> <text>` - Type text character by character\n  * `press <key>` - Press a key (Enter, Tab, Escape, etc.)\n  * `select <selector> <value>` - Select a dropdown option\n  * `scroll_down [px]` / `scroll_up [px]` - Scroll (default 500px)\n  * `scroll_to_text <text>` - Scroll until text is visible\n  * `go_back` - Navigate back\n  * `wait [seconds]` - Wait (default 2s)\n  * `extract_text [selector]` - Extract text content from page or element\n  * `extract_links [selector]` - Extract all links\n  * `screenshot [filename]` - Take a manual screenshot\n  * `dismiss_overlay` - Dismiss cookie banners or modals\n  * `js <script>` - Execute JavaScript on the page\n\n- CAPTCHA / HUMAN ASSISTANCE: If you encounter a CAPTCHA, verification, or any situation where automated interaction is stuck, MUST use `web-browser-takeover` to hand control to the user.\n\n# 12. CHAT MODE\n\nYou should check the **latest** user message to check if chat mode is enabled. If the user is using "/chat" tag in the latest message, that means the chat mode is activated and the user wants you to use **ONLY** <ask> tool in your **IMMEDIATE** response to that specific query. No other tools are allowed in the response right after the query with "/chat". If the latest user\'s input doesn\'t contain "/chat" - you are in **agentic** mode, you can use all other tools as well.\n\nIMPORTANT:\n- if the user is asking to use other tools while in chat mode - ask the user to disable chat mode first. Do not use any other tools.\n- if the task user sends requires using other than <ask> tools - tell the user to disable chat mode first. Do not tell the user about the <ask> tool, but you can mention to the user what kind of tools you can use in agentic mode to solve the user\'s task (after the user disables the chat mode).\n- to disable the chat mode the user should switch the toggle in the bottom left of the text input area in the UI. "/chat" tag is being added automatically when the toggle is in chat mode position.\n- pay attention only to the latest user\'s input. If there is no "/chat" tag in the latest input - you are allowed to use all the tools.\n\n--- XML TOOL CALLING ---\n\nIn this environment you have access to a set of tools you can use to answer the user\'s question. The tools are specified in XML format.\nFormat your tool calls using the specified XML tags. Place parameters marked as \'attribute\' within the opening tag (e.g., `<tag attribute=\'value\'>`). Place parameters marked as \'content\' between the opening and closing tags. Place parameters marked as \'element\' within their own child tags (e.g., `<tag><element>value</element></tag>`). Refer to the examples provided below for the exact structure of each tool.\nString and scalar parameters should be specified as attributes, while content goes between tags.\nNote that spaces for string values are not stripped. The output is parsed with regular expressions.\nIMPORTANT: All tool calls MUST be wrapped in <function_calls> and </function_calls> tags.\n\nHere are the XML tools available with examples:\n<slides-generation-mode>\nExample: \n        <!-- Activate slides generation mode in case the user is asking to create slides -->\n        <function_calls>\n        <slides-generation-mode>\n        </slides-generation-mode>\n        </function_calls>\n        \n<transcribe-audio>\nExample: \n        <function_calls>\n        <!-- Example: Request to transcribe an audio file named \'audio.mp3\' inside the \'audios\' folder -->\n        <transcribe-audio file_path="audios/audio.mp3"></transcribe-audio>\n        </function_calls>\n        \n<edit-image>\nExample: \n        <!-- Edit an existing image -->\n        <function_calls>\n        <edit-image\n            file_path="docs/diagram.png"\n            size="1024x1024"\n            n="1">\n        Edit instructions:\n        - Remove the background and replace it with a pure white background.\n        - Keep the main subject unchanged.\n        - Improve sharpness slightly, avoid over-smoothing.\n        - Do not add any text or watermark.\n        </edit-image>\n        </function_calls>\n\n        <!-- Edit can be also helpful in creating images similar to the reference image (image to edit), for example when creating slides and set of icons, infographics to maintain same objects or styles on different images. -->\n        <function_calls>\n        <edit-image\n            file_path="docs/diagram.png"\n            size="1536x1024"\n            n="2">\n        Create similar to the reference image following the instructions:\n        - Similar colours, layout, style, but about different object\n        - The same object as on the provided image, but in different color, style.\n        </edit-image>\n        </function_calls>\n        \n<generate-image>\nExample: \n        <!--\n        Generate a new image from a text prompt.\n        When generating images pay attention to allowed sizes (especially when doing slides, presentations). Possible sizes are: "1024x1024", "1536x1024", "1024x1536"\n        -->\n        <function_calls>\n        <generate-image\n            size="1024x1024"\n            n="1">\n        A clean, modern product hero image of a sleek smart speaker on a wooden desk, minimal composition, soft natural lighting, no watermark, no text.\n        </generate-image>\n        </function_calls>\n\n        <!-- Generate multiple variants -->\n        <function_calls>\n        <generate-image\n            size="1536x1024"\n            n="3">\n        A simple flat-style illustration of a kangaroo holding a laptop, friendly corporate tone, minimal shapes, high contrast, no text.\n        </generate-image>\n        </function_calls>\n        \n<see-image>\nExample: \n        <!-- Example: Request to see an image named \'diagram.png\' inside the \'docs\' folder -->\n        <function_calls>\n        <see-image file_path="docs/diagram.png">\n        </see-image>\n        </function_calls>\n        \n<transcribe-youtube>\nExample: \n        <function_calls>\n        <transcribe-youtube url="https://www.youtube.com/watch?v=video_id">\n        </transcribe-youtube>\n        </function_calls>\n        \n<execute-command>\nExample: \n        <!-- BLOCKING COMMANDS (Direct Execution) -->\n        <!-- Example 1: Basic Command Execution -->\n        <function_calls>\n        <execute-command>\n        ls -la\n        </execute-command>\n        </function_calls>\n\n        <!-- Example 2: Running in Specific Directory -->\n        <function_calls>\n        <execute-command folder="src">\n        npm install\n        </execute-command>\n        </function_calls>\n\n        <!-- Example 3: Long-running Process with Extended Timeout -->\n        <function_calls>\n        <execute-command timeout="300">\n        npm run build\n        </execute-command>\n        </function_calls>\n\n        <!-- Example 4: Complex Command with Environment Variables -->\n        <function_calls>\n        <execute-command>\n        export NODE_ENV=production && npm run preview\n        </execute-command>\n        </function_calls>\n\n        <!-- Example 5: Command with Output Redirection -->\n        <function_calls>\n        <execute-command>\n        npm run build > build.log 2>&1\n        </execute-command>\n        </function_calls>\n\n        <!-- NON-BLOCKING COMMANDS (Background Execution) -->\n        <!-- Example 1: Run a HTTP server -->\n        <function_calls>\n        <execute-command blocking="false">\n        python -m http.server 8050\n        </execute-command>\n        </function_calls>\n\n        <!-- Example 2: Run a long-running java program -->\n        <function_calls>\n        <execute-command blocking="false">\n        java -jar target/app.jar\n        </execute-command>\n        </function_calls>\n\n        <!-- Example 3: Start a Vite Development Server -->\n        <function_calls>\n        <execute-command blocking="false">\n        cd /workspace && npm run dev\n        </execute-command>\n        </function_calls>\n\n        <!-- Example 4: Start a Vite Build Process -->\n        <function_calls>\n        <execute-command blocking="false">\n        tmux new-session -d -s vite_build "cd /workspace && npm run build"\n        </execute-command>\n        </function_calls>\n        \n<create-file>\nExample: \n        <function_calls>\n        <create-file file_path="src/main.py">\n        # This is the file content\n        def main():\n            print("Hello, World!")\n        if __name__ == "__main__":\n            main()\n        </create-file>\n        </function_calls>\n        \n<delete-file>\nExample: \n        <function_calls>\n        <delete-file file_path="src/main.py">\n        </delete-file>\n        </function_calls>\n        \n<full-file-rewrite>\nExample: \n        <function_calls>\n        <full-file-rewrite file_path="src/main.py">\n        This completely replaces the entire file content.\n        Use when making major changes to a file or when the changes are too extensive for str-replace.\n        All previous content will be lost and replaced with this text.\n        </full-file-rewrite>\n        </function_calls>\n        \n<str-replace>\nExample: \n        <function_calls>\n        <str-replace file_path="src/main.py">\n            <old_str>text to replace (must appear exactly once in the file)</old_str>\n            <new_str>replacement text that will be inserted instead</new_str>\n        </str-replace>\n        </function_calls>\n        \n<ask>\nExample: \n        Ask user a question and wait for response. Use this tool when user input is required to proceed, including: 1) Clarifying ambiguous requirements, 2) Confirming high-impact changes, 3) Gathering missing or critical information, 4) Offering options and requesting user preference, 5) Validating assumptions that affect task success.\n\n        IMPORTANT:\n        - Use this tool only when user input, review, or confirmation is required.\n        - Provide clear context and concrete options whenever applicable.\n        - When this tool is used at the end of a task, it represents the final delivery point for all user-facing results produced so far.\n        - All generated files MUST be in the \'attachments\' attribute and all generated URLs MUST be in the \'urls\' attribute. The first element in the attachment list should be the most important artifact.\n\n        <function_calls>\n        <ask attachments="recipes/chocolate_cake.txt,photos/cake_examples.jpg" urls="https://example-link">\n            I\'m planning to bake the chocolate cake for your birthday party. The recipe mentions "rich frosting" but doesn\'t specify what type. Could you clarify your preferences? For example:\n            1. Would you prefer buttercream or cream cheese frosting?\n            2. Do you want any specific flavor added to the frosting (vanilla, coffee, etc.)?\n            3. Should I add any decorative toppings like sprinkles or fruit?\n            4. Do you have any dietary restrictions I should be aware of?\n\n            This information will help ensure the final result meets your expectations.\n        </ask>\n        </function_calls>\n        \n<complete>\nExample: \n        Use this tool only when all tasks are fully finished and no user input is required, including: 1) the user\'s original request has been fully addressed, 2) All required tasks and validations are completed, 3) All outputs and results are ready for delivery, 4) There are no pending actions or follow-ups.\n\n        IMPORTANT:\n        - This tool represents the authoritative final output of the session.\n        - All final user-facing results must be delivered when this tool is used. All generated files MUST be in the \'attachments\' attribute and all generated URLs MUST be in the \'urls\' attribute.\n\n        <function_calls>\n        <complete attachments="output.txt" urls="https://example-link">\n            The task has been completed successfully.\n            All final results are included above.\n        </complete>\n        </function_calls>\n        \n<web-browser-takeover>\nExample: \n        <function_calls>\n        <web-browser-takeover>\n            I\'ve encountered a CAPTCHA verification on the page. Please solve it and let me know when you\'re done.\n        </web-browser-takeover>\n        </function_calls>\n        \n<scrape-webpage>\nExample: \n        <!--\n        The scrape-webpage tool extracts the complete text content from web pages using Firecrawl.\n        IMPORTANT WORKFLOW RULES:\n        1. ALWAYS use web-search first to find relevant URLs\n        2. Then use scrape-webpage on URLs from web-search results\n        3. Only if scrape-webpage fails or if the page requires interaction:\n           - Use `browser-tool <action> [args...]` via execute-command\n           - This is needed for dynamic content, JavaScript-heavy sites, or pages requiring interaction\n\n        Firecrawl Features:\n        - Converts web pages into clean markdown\n        - Handles dynamic content and JavaScript-rendered sites\n        - Manages proxies, caching, and rate limits\n        - Supports PDFs and images\n        - Outputs clean markdown\n        -->\n\n        <!-- Example workflow: -->\n        <!-- 1. First search for relevant content -->\n        <function_calls>\n        <web-search query="latest AI research papers" num_results="5">\n        </web-search>\n        </function_calls>\n\n        <!-- 2. Then scrape specific URLs from search results -->\n        <function_calls>\n        <scrape-webpage url="https://example.com/research/ai-paper-2024">\n        </scrape-webpage>\n        </function_calls>\n        \n<web-search>\nExample: \n        <!--\n        The web-search tool allows you to search the internet for real-time information.\n        Use this tool when you need to find current information, research topics, or verify facts.\n\n        The tool returns information including:\n        - Titles of relevant web pages\n        - URLs for accessing the pages\n        - Published dates (when available)\n        -->\n\n        <!-- Simple search example -->\n        <function_calls>\n        <web-search query="current weather in New York City" num_results="20">\n        </web-search>\n        </function_calls>\n\n        <!-- Another search example -->\n        <function_calls>\n        <web-search query="current weather in New York City" num_results="20">\n        </web-search>\n        </function_calls>\n        \n<expose-port>\nExample: \n        <!-- Example 1: Expose a web server running on port 80 -->\n        <!-- This will generate a public URL that users can access to view the web application -->\n        <function_calls>\n        <expose-port>\n        80\n        </expose-port>\n        </function_calls>\n\n        <!-- Example 2: Expose an API service running on port 3000 -->\n        <!-- This allows users to interact with the API endpoints from their browser -->\n        <function_calls>\n        <expose-port>\n        3000\n        </expose-port>\n        </function_calls>\n\n        <!-- Example 3: Expose a development server running on port 5173 -->\n        <!-- This is useful for sharing a development environment with users -->\n        <function_calls>\n        <expose-port>\n        5173\n        </expose-port>\n        </function_calls>\n        \n<deploy>\nExample: \n        <!--\n        IMPORTANT: Only use this tool when:\n        1. The user explicitly requests permanent deployment to production\n        2. You have a complete, ready-to-deploy directory\n\n        NOTE: If the same name is used, it will redeploy to the same project as before\n        -->\n\n        <function_calls>\n        <deploy name="my-site" directory_path="website">\n        </deploy>\n        </function_calls>\n\n        <!-- Example: Deploy a website with a custom homepage file -->\n        <function_calls>\n        <deploy name="customer-portal" directory_path="customer-dashboard" homepage_filename="dashboard.html">\n        </deploy>\n        </function_calls>\n        \n'}
{'role': 'user', 'content': 'Do tool calling warmup'}
{'role': 'assistant', 'content': 'Let me create an empty todo file to use further as a warmup.\n<function_calls>\n<create-file file_path="todo.md">\n\n</create-file>\n</function_calls>'}
{'role': 'user', 'content': 'This session is being continued from a previous conversation that ran out of context. The summary below covers the earlier portion of the conversation.\n\nAnalysis:\nLet me chronologically analyze the conversation:\n\n1. Initial Setup:\n- User mentioned they are from NinjaTech AI, a US startup based in Palo Alto\n- User requested a warmup, and I created an empty todo.md file\n\n2. Main Task Request:\n- User provided an extremely detailed specification for building "SAMMS ENTERPRISE SOVEREIGN OPERATING SYSTEM (SESOS v6 OMEGA CONSTRAINED)"\n- This is a comprehensive enterprise software system with:\n  - 27 core modules (Company Management, Accounting, Treasury, HR, Tax, etc.)\n  - UI/UX system with 15 components\n  - AI system with 5 features\n  - Full ERP functionality\n  - Security with JWT, RBAC/ABAC\n  - Event-driven architecture\n\n3. Technical Stack Specified:\n- Backend: FastAPI (Python)\n- Frontend: Next.js (React)\n- Database: PostgreSQL\n- Cache/Event Bus: Redis\n- APIs: REST + GraphQL\n- Infrastructure: Docker + Kubernetes\n- Architecture: DDD, Modular monolith, Event-driven, CQRS-compatible\n\n4. My Actions:\n- Created folder structure for backend and frontend\n- Built core backend configuration files\n- Created database models for all major modules\n- Started creating Pydantic schemas\n\n5. Files Created:\n- todo.md - Task tracking\n- backend/app/core/config.py - Configuration\n- backend/app/core/database.py - Database setup\n- backend/app/core/redis_client.py - Redis client\n- backend/app/core/security.py - Security/JWT/RBAC\n- backend/app/core/events.py - Event system\n- backend/app/core/exceptions.py - Custom exceptions\n- backend/app/core/__init__.py - Core module exports\n- backend/app/models/base.py - Base model classes\n- backend/app/models/company.py - Company models\n- backend/app/models/user.py - User/permission models\n- backend/app/models/accounting.py - Accounting models\n- backend/app/models/treasury.py - Treasury/banking models\n- backend/app/models/invoice.py - Invoice/billing models\n- backend/app/models/hr.py - HR/payroll models\n- backend/app/models/tax.py - Tax engine models\n- backend/app/models/workflow.py - Workflow/automation models\n- backend/app/models/legal.py - Legal/contract models\n- backend/app/models/reports.py - Reports module models\n- backend/app/models/consolidation.py - Consolidation models\n- backend/app/models/asset.py - Fixed asset models\n- backend/app/models/ai.py - AI/analytics models\n- backend/app/models/__init__.py - Models module exports\n- backend/app/schemas/base.py - Base Pydantic schemas\n\n6. Current State:\n- Just created the base schemas file\n- Need to continue with more schemas, services, API endpoints, and frontend\n\n7. No errors encountered so far - all files created successfully\n\n8. Pending work from todo.md:\n- Complete backend schemas\n- Create services layer\n- Create API endpoints\n- Create frontend\n- Create tests\n- Create infrastructure configs\n\n\n\n\nSummary:\n1. Primary Request and Intent:\n   The user requested building a complete enterprise-grade software system called "SAMMS ENTERPRISE SOVEREIGN OPERATING SYSTEM (SESOS v6 OMEGA CONSTRAINED)" with:\n   - 27 core modules including Company Management, Accounting (double-entry), Treasury, HR/Payroll, Tax Engine, Legal/Contracts, Workflow Engine, Consolidation, AI/Analytics, etc.\n   - Full ERP functionality with CRUD operations on all pages\n   - Multi-company hierarchy with holding/subsidiary support\n   - AI-driven features: anomaly detection, cash flow forecasting, contract analysis, recommendations\n   - Visual workflow builder with triggers like "invoice overdue → send email"\n   - Fixed Asset Registry with depreciation and automated journal entries\n   - Tax nexus engine with cross-jurisdictional calculations\n   - Intercompany reconciliation with automatic matching entries\n   - PDF report generation for financial statements\n   - World-class UI/UX with Command Center, Dashboard Builder, AI Copilot\n   - Full security: JWT, RBAC+ABAC, field-level permissions, audit logs\n   - Event-driven architecture with versioning/time machine\n   - Zero stats throughout the app initially\n\n2. Key Technical Concepts:\n   - FastAPI (Python) backend\n   - Next.js (React) frontend\n   - PostgreSQL database with SQLAlchemy async\n   - Redis for caching and event bus\n   - REST + GraphQL APIs\n   - Domain-Driven Design (DDD)\n   - Event-driven architecture with event sourcing\n   - CQRS-compatible design\n   - JWT authentication with RBAC/ABAC\n   - Double-entry bookkeeping\n   - Multi-tenancy with company scoping\n   - Soft delete and versioning patterns\n   - AI/ML integration for anomaly detection and forecasting\n\n3. Files and Code Sections:\n\n   - **backend/app/core/config.py** - Central configuration with 100+ settings for database, Redis, security, AI, localization, feature flags\n   \n   - **backend/app/core/database.py** - Async SQLAlchemy engine, session management, Base declarative model\n   \n   - **backend/app/core/redis_client.py** - Redis client for caching, events, sessions, rate limiting, distributed locks\n   \n   - **backend/app/core/security.py** - Password hashing, JWT tokens, Permission/Role classes with 50+ permissions, permission checking dependencies\n   \n   - **backend/app/core/events.py** - Event system with EventType enum (30+ events), Event dataclass, EventBus, EventStore, EventBuilder\n   \n   - **backend/app/core/exceptions.py** - 20+ custom exception classes for different error scenarios\n   \n   - **backend/app/models/base.py** - BaseModel with UUID, timestamps, soft delete, versioning, audit fields\n   \n   - **backend/app/models/company.py** - Company, CompanyGroup, CompanySetting, CompanyDocument models with hierarchy support\n   \n   - **backend/app/models/user.py** - User, Role, Permission, UserSession, UserActivityLog with many-to-many relationships\n   \n   - **backend/app/models/accounting.py** - Account, JournalEntry, JournalEntryLine, FiscalYear, FiscalPeriod, AccountBalance, Budget models\n   \n   - **backend/app/models/treasury.py** - BankAccount, TreasuryTransaction, BankReconciliation, CashFlowForecast, PaymentTerm models\n   \n   - **backend/app/models/invoice.py** - Contact, Product, Invoice, InvoiceLine, Payment, Subscription, RecurringInvoice models\n   \n   - **backend/app/models/hr.py** - Department, Position, Employee, Payroll, PayrollItem, TimeEntry, LeaveRequest, Benefit models\n   \n   - **backend/app/models/tax.py** - TaxRate, TaxCode, TaxTransaction, TaxFiling, TaxNexusRule, ExchangeRate models\n   \n   - **backend/app/models/workflow.py** - Workflow, WorkflowExecution, AutomationRule, Notification, ApprovalWorkflow models\n   \n   - **backend/app/models/legal.py** - LegalEntity, Contract, Document, LegalMatter, IntellectualProperty models\n   \n   - **backend/app/models/reports.py** - ReportDefinition, GeneratedReport, Dashboard, KPI, FinancialStatement models\n   \n   - **backend/app/models/consolidation.py** - ConsolidationGroup, ConsolidationPeriod, IntercompanyTransaction, IntercompanyReconciliation models\n   \n   - **backend/app/models/asset.py** - FixedAsset, DepreciationSchedule, AssetTransfer, AssetMaintenance, AssetDisposal models\n   \n   - **backend/app/models/ai.py** - AIModel, AnomalyDetection, CashFlowForecast, AIRecommendation, ContractAnalysis models\n   \n   - **backend/app/schemas/base.py** - Base Pydantic schemas with PaginationParams, PaginatedResponse, validation patterns\n\n4. Errors and fixes:\n   - No errors encountered during this session. All files created successfully.\n\n5. Problem Solving:\n   - Successfully designed a comprehensive data model covering all 27+ modules\n   - Implemented proper relationships between entities (foreign keys, many-to-many)\n   - Created base classes with common functionality (timestamps, soft delete, versioning)\n   - Designed event-driven architecture with proper event types and event sourcing\n\n6. All user messages:\n   - "Do tool calling warmup"\n   - "Before we begin, here is some context about me from our previous interactions: 1. User is from NinjaTech AI, a US startup based in Palo Alto"\n   - [Long detailed specification for SAMMS ENTERPRISE SOVEREIGN OPERATING SYSTEM with all modules, UI/UX requirements, AI features, accounting requirements, security requirements, and specific instructions about consolidation, reports, workflow builder, anomaly detection, PDF generation, fixed assets, cash flow forecasting, tax nexus engine, dashboard builder, contract analysis, and intercompany reconciliation]\n\n7. Pending Tasks:\n   - Complete backend schemas for all entities\n   - Create repository layer for data access\n   - Create service layer with business logic\n   - Create API endpoints (REST and GraphQL)\n   - Build complete frontend with Next.js\n   - Create all UI components (Command Center, Dashboard Builder, etc.)\n   - Create tests (unit, integration, frontend)\n   - Create Docker/Kubernetes configurations\n   - Create CI/CD pipelines\n   - Verify all CRUD operations work on all pages\n\n8. Current Work:\n   Just completed creating `backend/app/schemas/base.py` with base Pydantic schemas including:\n   - BaseResponseModel\n   - PaginationParams\n   - PaginatedResponse\n   - SuccessResponse/ErrorResponse\n   - FilterParams\n   - UserContext\n   - Address, ContactInfo schemas\n   - Various mixins\n\n9. Optional Next Step:\n   Continue creating Pydantic schemas for specific entities (Company, User, Accounting, etc.) then move to creating the services layer. The user explicitly stated "You MUST: generate full code, follow exact order, complete each module fully before next" and to not skip files.\n\n   From the specification: "Generate EVERY file sequentially... Each file MUST include: full imports, full implementation, no placeholders"\n\n   The immediate next file should be entity-specific schemas for Company, User, etc., followed by service implementations.\n\n\nIf you need specific details from before compaction (like exact code snippets, error messages, or content you generated), read the full transcript at: /workspace/summarized_conversations/original_conversation_1775076843_1625.txt'}
{'role': 'assistant', 'content': 'I\'ll continue building the SAMMS ENTERPRISE SOVEREIGN OPERATING SYSTEM from where we left off. Let me first check the current state of the project and then continue with the schemas.\n\n<function_calls>\n<execute-command>\nfind . -type f -name "*.py" | head -50\n</execute-command>\n</function_calls>'}
{'role': 'user', 'content': '<tool_result> <execute-command> ToolResult(success=True, output=\'{\\n  "output": "./backend/app/schemas/base.py\\\\n./backend/app/core/__init__.py\\\\n./backend/app/core/security.py\\\\n./backend/app/core/redis_client.py\\\\n./backend/app/core/exceptions.py\\\\n./backend/app/core/config.py\\\\n./backend/app/core/database.py\\\\n./backend/app/core/events.py\\\\n./backend/app/models/ai.py\\\\n./backend/app/models/asset.py\\\\n./backend/app/models/__init__.py\\\\n./backend/app/models/invoice.py\\\\n./backend/app/models/base.py\\\\n./backend/app/models/legal.py\\\\n./backend/app/models/accounting.py\\\\n./backend/app/models/user.py\\\\n./backend/app/models/company.py\\\\n./backend/app/models/consolidation.py\\\\n./backend/app/models/hr.py\\\\n./backend/app/models/treasury.py\\\\n./backend/app/models/reports.py\\\\n./backend/app/models/tax.py\\\\n./backend/app/models/workflow.py\\\\n./.agent_hooks/shutdown/00_track_processes_on_ports.py\\\\n./.agent_hooks/run_all_hooks.py\\\\n",\\n  "exit_code": 0,\\n  "cwd": "/workspace"\\n}\') </execute-command> </tool_result>'}
{'role': 'assistant', 'content': '\n<function_calls>\n<execute-command>\ncat todo.md\n</execute-command>\n</function_calls>'}
{'role': 'user', 'content': '<tool_result> <execute-command> ToolResult(success=True, output=\'{\\n  "output": "# SAMMS ENTERPRISE SOVEREIGN OPERATING SYSTEM - BUILD TRACKER\\\\n\\\\n## Phase 1: Project Setup & Infrastructure\\\\n- [ ] Create folder structure\\\\n- [ ] Backend core setup (FastAPI)\\\\n- [ ] Frontend core setup (Next.js)\\\\n- [ ] Database configuration\\\\n- [ ] Docker & Kubernetes configs\\\\n\\\\n## Phase 2: Core Backend Modules\\\\n- [ ] Company Management\\\\n- [ ] Dynamic Schema Builder\\\\n- [ ] Organizational Structure Engine\\\\n- [ ] Accounting System (double-entry)\\\\n- [ ] Treasury + Banking\\\\n- [ ] Revenue + Billing\\\\n- [ ] HR + Payroll\\\\n- [ ] Tax Engine\\\\n- [ ] Legal + Contract Lifecycle Management\\\\n- [ ] Governance + Policy Engine\\\\n- [ ] Workflow + Automation Engine\\\\n- [ ] Consolidation Engine\\\\n- [ ] Integration Hub\\\\n- [ ] Document + Data Room System\\\\n- [ ] Analytics + AI Engine\\\\n- [ ] Permissions + Security\\\\n- [ ] Event System\\\\n- [ ] Versioning + Time Machine\\\\n- [ ] Plugin System\\\\n- [ ] Simulation Engine\\\\n- [ ] Internal Marketplace\\\\n- [ ] Dashboard System\\\\n- [ ] Audit System\\\\n- [ ] Feature Flag System\\\\n- [ ] Localization\\\\n- [ ] SDK Generator\\\\n- [ ] CLI / Admin Terminal\\\\n- [ ] Reports Module\\\\n- [ ] Fixed Asset Registry\\\\n- [ ] Cash Flow Forecasting\\\\n- [ ] Tax Nexus Engine\\\\n- [ ] Intercompany Reconciliation\\\\n\\\\n## Phase 3: Frontend UI/UX System\\\\n- [ ] Command Center Dashboard\\\\n- [ ] Global Search + Command Palette\\\\n- [ ] Company Switcher\\\\n- [ ] Action-based UI\\\\n- [ ] Embedded AI Copilot\\\\n- [ ] Drag-and-drop Dashboard Builder\\\\n- [ ] Workflow Builder (visual)\\\\n- [ ] Smart Forms System\\\\n- [ ] Decision Engine UI\\\\n- [ ] Company Graph Visualization\\\\n- [ ] Notification System\\\\n- [ ] Time Machine UI\\\\n- [ ] Permission Visualizer\\\\n- [ ] Sandbox / Simulation Mode\\\\n- [ ] Internal App Builder\\\\n\\\\n## Phase 4: AI System\\\\n- [ ] Natural language commands\\\\n- [ ] Anomaly detection\\\\n- [ ] Forecasting\\\\n- [ ] Decision recommendations\\\\n- [ ] Explainability layer\\\\n- [ ] Contract analysis tool\\\\n\\\\n## Phase 5: Testing & DevOps\\\\n- [ ] Unit tests\\\\n- [ ] Integration tests\\\\n- [ ] Frontend tests\\\\n- [ ] CI/CD pipelines\\\\n\\\\n## Phase 6: Final Verification\\\\n- [ ] Verify all modules complete\\\\n- [ ] Verify all CRUD operations\\\\n- [ ] Verify all integrations\\\\n- [ ] Final system test",\\n  "exit_code": 0,\\n  "cwd": "/workspace"\\n}\') </execute-command> </tool_result>'}
{'role': 'assistant', 'content': 'Good, I can see the project structure and todo.md. Let me update the todo.md to reflect the current progress and then continue with creating the remaining Pydantic schemas.\n\n\n<function_calls><str-replace file_path="todo.md"><old_str># SAMMS ENTERPRISE SOVEREIGN OPERATING SYSTEM - BUILD TRACKER\n\n## Phase 1: Project Setup &amp; Infrastructure\n- [ ] Create folder structure\n- [ ] Backend core setup (FastAPI)\n- [ ] Frontend core setup (Next.js)\n- [ ] Database configuration\n- [ ] Docker &amp; Kubernetes configs\n\n## Phase 2: Core Backend Modules</old_str><new_str># SAMMS ENTERPRISE SOVEREIGN OPERATING SYSTEM - BUILD TRACKER\n\n## Phase 1: Project Setup &amp; Infrastructure\n- [x] Create folder structure\n- [x] Backend core setup (FastAPI)\n- [ ] Frontend core setup (Next.js)\n- [x] Database configuration\n- [ ] Docker &amp; Kubernetes configs\n\n## Phase 1.5: Backend Schemas (Pydantic)\n- [x] Base schemas\n- [ ] Company schemas\n- [ ] User schemas\n- [ ] Accounting schemas\n- [ ] Treasury schemas\n- [ ] Invoice schemas\n- [ ] HR schemas\n- [ ] Tax schemas\n- [ ] Workflow schemas\n- [ ] Legal schemas\n- [ ] Reports schemas\n- [ ] Consolidation schemas\n- [ ] Asset schemas\n- [ ] AI schemas\n\n## Phase 2: Core Backend Modules</new_str></str-replace></function_calls>'}
{'role': 'user', 'content': "<tool_result> <str-replace> ToolResult(success=True, output='Replacement successful.') </str-replace> </tool_result>"}
{'role': 'assistant', 'content': 'Now let me create the Company schemas:\n\n\n<function_calls><create-file file_path="backend/app/schemas/company.py">"""\nCompany Management Schemas for SAMMS ENTERPRISE SOVEREIGN OPERATING SYSTEM\nHandles multi-company hierarchy, company groups, settings, and documents\n"""\nfrom datetime import datetime, date\nfrom typing import Optional, List, Dict, Any, Union\nfrom uuid import UUID\nfrom decimal import Decimal\nfrom enum import Enum\n\nfrom pydantic import Field, field_validator, model_validator\n\nfrom .base import (\n    BaseResponseModel,\n    PaginationParams,\n    PaginatedResponse,\n    SuccessResponse,\n    ErrorResponse,\n    Address,\n    ContactInfo,\n    TimestampMixin,\n    IDMixin,\n)\n\n\nclass CompanyType(str, Enum):\n    """Company type enumeration"""\n    HOLDING = "holding"\n    OPERATING = "operating"\n    SUBSIDIARY = "subsidiary"\n    BRANCH = "branch"\n    DIVISION = "division"\n    JOINT_VENTURE = "joint_venture"\n    PARTNERSHIP = "partnership"\n    SOLE_PROPRIETORSHIP = "sole_proprietorship"\n    NON_PROFIT = "non_profit"\n    GOVERNMENT = "government"\n\n\nclass CompanyStatus(str, Enum):\n    """Company status enumeration"""\n    ACTIVE = "active"\n    INACTIVE = "inactive"\n    PENDING = "pending"\n    SUSPENDED = "suspended"\n    LIQUIDATION = "liquidation"\n    ACQUIRED = "acquired"\n    MERGED = "merged"\n    DISSOLVED = "dissolved"\n\n\nclass OwnershipType(str, Enum):\n    """Ownership type enumeration"""\n    PUBLIC = "public"\n    PRIVATE = "private"\n    GOVERNMENT_OWNED = "government_owned"\n    EMPLOYEE_OWNED = "employee_owned"\n    FAMILY_OWNED = "family_owned"\n    MIXED = "mixed"\n\n\nclass IndustrySector(str, Enum):\n    """Industry sector enumeration"""\n    AGRICULTURE = "agriculture"\n    MINING = "mining"\n    MANUFACTURING = "manufacturing"\n    CONSTRUCTION = "construction"\n    WHOLESALE = "wholesale"\n    RETAIL = "retail"\n    TRANSPORTATION = "transportation"\n    INFORMATION = "information"\n    FINANCE = "finance"\n    REAL_ESTATE = "real_estate"\n    PROFESSIONAL = "professional"\n    MANAGEMENT = "management"\n    ADMINISTRATIVE = "administrative"\n    EDUCATIONAL = "educational"\n    HEALTHCARE = "healthcare"\n    ARTS = "arts"\n    ENTERTAINMENT = "entertainment"\n    HOSPITALITY = "hospitality"\n    FOOD_SERVICE = "food_service"\n    OTHER = "other"\n\n\nclass DocumentType(str, Enum):\n    """Company document type enumeration"""\n    CERTIFICATE_OF_INCORPORATION = "certificate_of_incorporation"\n    ARTICLES_OF_ASSOCIATION = "articles_of_association"\n    BYLAWS = "bylaws"\n    SHAREHOLDER_AGREEMENT = "shareholder_agreement"\n    BUSINESS_LICENSE = "business_license"\n    TAX_REGISTRATION = "tax_registration"\n    BANK_RESOLUTION = "bank_resolution"\n    BOARD_RESOLUTION = "board_resolution"\n    AUDIT_REPORT = "audit_report"\n    FINANCIAL_STATEMENT = "financial_statement"\n    ANNUAL_REPORT = "annual_report"\n    OTHER = "other"\n\n\nclass CompanySettingsCategory(str, Enum):\n    """Company settings category enumeration"""\n    GENERAL = "general"\n    ACCOUNTING = "accounting"\n    TAX = "tax"\n    HR = "hr"\n    PAYROLL = "payroll"\n    INVENTORY = "inventory"\n    SALES = "sales"\n    PURCHASING = "purchasing"\n    TREASURY = "treasury"\n    LEGAL = "legal"\n    WORKFLOW = "workflow"\n    NOTIFICATION = "notification"\n    INTEGRATION = "integration"\n    SECURITY = "security"\n    UI = "ui"\n\n\n# ============================================\n# Company Group Schemas\n# ============================================\n\nclass CompanyGroupBase(BaseResponseModel):\n    """Base schema for company group"""\n    name: str = Field(..., min_length=1, max_length=200, description="Group name")\n    code: str = Field(..., min_length=1, max_length=50, description="Unique group code")\n    description: Optional[str] = Field(None, max_length=2000, description="Group description")\n    parent_group_id: Optional[UUID] = Field(None, description="Parent group ID for hierarchy")\n    settings: Optional[Dict[str, Any]] = Field(default_factory=dict, description="Group-level settings")\n    metadata: Optional[Dict[str, Any]] = Field(default_factory=dict, description="Additional metadata")\n\n\nclass CompanyGroupCreate(CompanyGroupBase):\n    """Schema for creating a company group"""\n    pass\n\n\nclass CompanyGroupUpdate(BaseResponseModel):\n    """Schema for updating a company group"""\n    name: Optional[str] = Field(None, min_length=1, max_length=200)\n    code: Optional[str] = Field(None, min_length=1, max_length=50)\n    description: Optional[str] = Field(None, max_length=2000)\n    parent_group_id: Optional[UUID] = None\n    settings: Optional[Dict[str, Any]] = None\n    metadata: Optional[Dict[str, Any]] = None\n    is_active: Optional[bool] = None\n\n\nclass CompanyGroupResponse(CompanyGroupBase, TimestampMixin, IDMixin):\n    """Schema for company group response"""\n    is_active: bool = Field(default=True, description="Whether the group is active")\n    level: int = Field(default=0, description="Hierarchy level (0 = root)")\n    path: str = Field(default="", description="Full path in hierarchy")\n    company_count: int = Field(default=0, description="Number of companies in group")\n    child_groups: List["CompanyGroupResponse"] = Field(default_factory=list, description="Child groups")\n\n    class Config:\n        from_attributes = True\n\n\n# ============================================\n# Company Schemas\n# ============================================\n\nclass CompanyBase(BaseResponseModel):\n    """Base schema for company"""\n    name: str = Field(..., min_length=1, max_length=200, description="Company name")\n    legal_name: Optional[str] = Field(None, max_length=200, description="Legal/registered name")\n    code: str = Field(..., min_length=1, max_length=20, description="Unique company code")\n    registration_number: Optional[str] = Field(None, max_length=50, description="Business registration number")\n    tax_id: Optional[str] = Field(None, max_length=50, description="Tax identification number")\n    company_type: CompanyType = Field(..., description="Type of company")\n    industry_sector: Optional[IndustrySector] = Field(None, description="Industry sector")\n    ownership_type: OwnershipType = Field(default=OwnershipType.PRIVATE, description="Ownership type")\n    \n    # Parent company (for hierarchy)\n    parent_company_id: Optional[UUID] = Field(None, description="Parent company ID")\n    company_group_id: Optional[UUID] = Field(None, description="Company group ID")\n    \n    # Contact Information\n    address: Optional[Address] = Field(None, description="Primary address")\n    contact_info: Optional[ContactInfo] = Field(None, description="Contact information")\n    \n    # Dates\n    incorporation_date: Optional[date] = Field(None, description="Date of incorporation")\n    fiscal_year_start: Optional[int] = Field(None, ge=1, le=12, description="Fiscal year start month")\n    fiscal_year_end: Optional[int] = Field(None, ge=1, le=12, description="Fiscal year end month")\n    \n    # Currency and locale\n    base_currency: str = Field(default="USD", min_length=3, max_length=3, description="Base currency code")\n    timezone: str = Field(default="UTC", description="Company timezone")\n    locale: str = Field(default="en_US", description="Company locale")\n    \n    # Additional info\n    website: Optional[str] = Field(None, max_length=500, description="Company website")\n    logo_url: Optional[str] = Field(None, max_length=1000, description="Logo URL")\n    description: Optional[str] = Field(None, max_length=5000, description="Company description")\n    \n    # Metadata\n    metadata: Optional[Dict[str, Any]] = Field(default_factory=dict, description="Additional metadata")\n    tags: List[str] = Field(default_factory=list, description="Tags for categorization")\n\n\nclass CompanyCreate(CompanyBase):\n    """Schema for creating a company"""\n    settings: Optional[Dict[str, Any]] = Field(default_factory=dict, description="Company settings")\n    \n    @field_validator(\'code\')\n    @classmethod\n    def validate_code(cls, v: str) -> str:\n        """Validate company code format"""\n        if not v.isalnum():\n            raise ValueError(\'Company code must be alphanumeric\')\n        return v.upper()\n    \n    @model_validator(mode=\'after\')\n    def validate_fiscal_year(self) -> \'CompanyCreate\':\n        """Validate fiscal year start and end"""\n        if self.fiscal_year_start and self.fiscal_year_end:\n            if self.fiscal_year_start == self.fiscal_year_end:\n                raise ValueError(\'Fiscal year start and end months cannot be the same\')\n        return self\n\n\nclass CompanyUpdate(BaseResponseModel):\n    """Schema for updating a company"""\n    name: Optional[str] = Field(None, min_length=1, max_length=200)\n    legal_name: Optional[str] = Field(None, max_length=200)\n    code: Optional[str] = Field(None, min_length=1, max_length=20)\n    registration_number: Optional[str] = Field(None, max_length=50)\n    tax_id: Optional[str] = Field(None, max_length=50)\n    company_type: Optional[CompanyType] = None\n    industry_sector: Optional[IndustrySector] = None\n    ownership_type: Optional[OwnershipType] = None\n    parent_company_id: Optional[UUID] = None\n    company_group_id: Optional[UUID] = None\n    address: Optional[Address] = None\n    contact_info: Optional[ContactInfo] = None\n    incorporation_date: Optional[date] = None\n    fiscal_year_start: Optional[int] = Field(None, ge=1, le=12)\n    fiscal_year_end: Optional[int] = Field(None, ge=1, le=12)\n    base_currency: Optional[str] = Field(None, min_length=3, max_length=3)\n    timezone: Optional[str] = None\n    locale: Optional[str] = None\n    website: Optional[str] = Field(None, max_length=500)\n    logo_url: Optional[str] = Field(None, max_length=1000)\n    description: Optional[str] = Field(None, max_length=5000)\n    metadata: Optional[Dict[str, Any]] = None\n    tags: Optional[List[str]] = None\n    status: Optional[CompanyStatus] = None\n    is_active: Optional[bool] = None\n\n\nclass CompanyResponse(CompanyBase, TimestampMixin, IDMixin):\n    """Schema for company response"""\n    status: CompanyStatus = Field(default=CompanyStatus.ACTIVE, description="Company status")\n    is_active: bool = Field(default=True, description="Whether the company is active")\n    \n    # Hierarchy info\n    level: int = Field(default=0, description="Hierarchy level (0 = root)")\n    full_path: str = Field(default="", description="Full path in company hierarchy")\n    \n    # Statistics\n    subsidiary_count: int = Field(default=0, description="Number of subsidiaries")\n    employee_count: int = Field(default=0, description="Number of employees")\n    user_count: int = Field(default=0, description="Number of users")\n    \n    # Relationships\n    parent_company: Optional["CompanyResponse"] = None\n    company_group: Optional[CompanyGroupResponse] = None\n    subsidiaries: List["CompanyResponse"] = Field(default_factory=list)\n    \n    class Config:\n        from_attributes = True\n\n\nclass CompanyListResponse(BaseResponseModel):\n    """Schema for company list item"""\n    id: UUID\n    name: str\n    legal_name: Optional[str]\n    code: str\n    company_type: CompanyType\n    status: CompanyStatus\n    is_active: bool\n    parent_company_id: Optional[UUID]\n    company_group_id: Optional[UUID]\n    base_currency: str\n    created_at: datetime\n    \n    class Config:\n        from_attributes = True\n\n\nclass CompanyHierarchyResponse(BaseResponseModel):\n    """Schema for company hierarchy tree"""\n    id: UUID\n    name: str\n    code: str\n    company_type: CompanyType\n    status: CompanyStatus\n    level: int\n    children: List["CompanyHierarchyResponse"] = Field(default_factory=list)\n    \n    class Config:\n        from_attributes = True\n\n\n# ============================================\n# Company Settings Schemas\n# ============================================\n\nclass CompanySettingBase(BaseResponseModel):\n    """Base schema for company setting"""\n    category: CompanySettingsCategory = Field(..., description="Setting category")\n    key: str = Field(..., min_length=1, max_length=100, description="Setting key")\n    value: Dict[str, Any] = Field(..., description="Setting value (JSON)")\n    data_type: str = Field(default="json", description="Data type: string, number, boolean, json")\n    description: Optional[str] = Field(None, max_length=1000, description="Setting description")\n    is_encrypted: bool = Field(default=False, description="Whether value is encrypted")\n    is_public: bool = Field(default=False, description="Whether visible to all users")\n\n\nclass CompanySettingCreate(CompanySettingBase):\n    """Schema for creating a company setting"""\n    company_id: UUID = Field(..., description="Company ID")\n\n\nclass CompanySettingUpdate(BaseResponseModel):\n    """Schema for updating a company setting"""\n    value: Optional[Dict[str, Any]] = None\n    description: Optional[str] = Field(None, max_length=1000)\n    is_encrypted: Optional[bool] = None\n    is_public: Optional[bool] = None\n\n\nclass CompanySettingResponse(CompanySettingBase, TimestampMixin, IDMixin):\n    """Schema for company setting response"""\n    company_id: UUID\n    updated_by: Optional[UUID] = None\n    \n    class Config:\n        from_attributes = True\n\n\n# ============================================\n# Company Document Schemas\n# ============================================\n\nclass CompanyDocumentBase(BaseResponseModel):\n    """Base schema for company document"""\n    document_type: DocumentType = Field(..., description="Type of document")\n    name: str = Field(..., min_length=1, max_length=200, description="Document name")\n    description: Optional[str] = Field(None, max_length=2000, description="Document description")\n    document_date: Optional[date] = Field(None, description="Document date")\n    expiry_date: Optional[date] = Field(None, description="Expiry date for time-sensitive documents")\n    file_path: Optional[str] = Field(None, max_length=1000, description="File storage path")\n    file_name: Optional[str] = Field(None, max_length=255, description="Original file name")\n    file_size: Optional[int] = Field(None, ge=0, description="File size in bytes")\n    file_type: Optional[str] = Field(None, max_length=100, description="MIME type")\n    metadata: Optional[Dict[str, Any]] = Field(default_factory=dict, description="Additional metadata")\n    tags: List[str] = Field(default_factory=list, description="Tags for categorization")\n\n\nclass CompanyDocumentCreate(CompanyDocumentBase):\n    """Schema for creating a company document"""\n    company_id: UUID = Field(..., description="Company ID")\n\n\nclass CompanyDocumentUpdate(BaseResponseModel):\n    """Schema for updating a company document"""\n    document_type: Optional[DocumentType] = None\n    name: Optional[str] = Field(None, min_length=1, max_length=200)\n    description: Optional[str] = Field(None, max_length=2000)\n    document_date: Optional[date] = None\n    expiry_date: Optional[date] = None\n    file_path: Optional[str] = Field(None, max_length=1000)\n    file_name: Optional[str] = Field(None, max_length=255)\n    file_size: Optional[int] = Field(None, ge=0)\n    file_type: Optional[str] = Field(None, max_length=100)\n    metadata: Optional[Dict[str, Any]] = None\n    tags: Optional[List[str]] = None\n\n\nclass CompanyDocumentResponse(CompanyDocumentBase, TimestampMixin, IDMixin):\n    """Schema for company document response"""\n    company_id: UUID\n    uploaded_by: Optional[UUID] = None\n    is_verified: bool = Field(default=False, description="Whether document is verified")\n    verified_by: Optional[UUID] = None\n    verified_at: Optional[datetime] = None\n    \n    class Config:\n        from_attributes = True\n\n\n# ============================================\n# Company Query Parameters\n# ============================================\n\nclass CompanyFilterParams(PaginationParams):\n    """Filter parameters for company queries"""\n    name: Optional[str] = Field(None, description="Filter by name (partial match)")\n    code: Optional[str] = Field(None, description="Filter by code")\n    company_type: Optional[List[CompanyType]] = Field(None, description="Filter by company types")\n    status: Optional[List[CompanyStatus]] = Field(None, description="Filter by status")\n    industry_sector: Optional[List[IndustrySector]] = Field(None, description="Filter by industry")\n    ownership_type: Optional[List[OwnershipType]] = Field(None, description="Filter by ownership")\n    parent_company_id: Optional[UUID] = Field(None, description="Filter by parent company")\n    company_group_id: Optional[UUID] = Field(None, description="Filter by company group")\n    is_active: Optional[bool] = Field(None, description="Filter by active status")\n    base_currency: Optional[str] = Field(None, description="Filter by base currency")\n    search: Optional[str] = Field(None, description="Search in name, code, legal_name")\n    created_after: Optional[datetime] = Field(None, description="Created after date")\n    created_before: Optional[datetime] = Field(None, description="Created before date")\n    tags: Optional[List[str]] = Field(None, description="Filter by tags (any match)")\n\n\nclass CompanyGroupFilterParams(PaginationParams):\n    """Filter parameters for company group queries"""\n    name: Optional[str] = Field(None, description="Filter by name (partial match)")\n    code: Optional[str] = Field(None, description="Filter by code")\n    parent_group_id: Optional[UUID] = Field(None, description="Filter by parent group")\n    is_active: Optional[bool] = Field(None, description="Filter by active status")\n    search: Optional[str] = Field(None, description="Search in name and code")\n\n\n# ============================================\n# Bulk Operations\n# ============================================\n\nclass CompanyBulkCreate(BaseResponseModel):\n    """Schema for bulk creating companies"""\n    companies: List[CompanyCreate] = Field(..., min_length=1, max_length=100)\n\n\nclass CompanyBulkUpdate(BaseResponseModel):\n    """Schema for bulk updating companies"""\n    ids: List[UUID] = Field(..., min_length=1)\n    updates: CompanyUpdate\n\n\nclass CompanyBulkDelete(BaseResponseModel):\n    """Schema for bulk deleting companies"""\n    ids: List[UUID] = Field(..., min_length=1)\n    hard_delete: bool = Field(default=False, description="Permanently delete")\n\n\nclass CompanyBulkOperationResult(BaseResponseModel):\n    """Schema for bulk operation results"""\n    successful: List[UUID] = Field(default_factory=list, description="Successfully processed IDs")\n    failed: List[Dict[str, Any]] = Field(default_factory=list, description="Failed items with errors")\n    total_processed: int = Field(default=0, description="Total items processed")\n    success_count: int = Field(default=0, description="Number of successful operations")\n    failure_count: int = Field(default=0, description="Number of failed operations")\n\n\n# ============================================\n# Company Statistics\n# ============================================\n\nclass CompanyStatistics(BaseResponseModel):\n    """Schema for company statistics"""\n    total_companies: int = Field(default=0)\n    active_companies: int = Field(default=0)\n    inactive_companies: int = Field(default=0)\n    by_type: Dict[str, int] = Field(default_factory=dict)\n    by_industry: Dict[str, int] = Field(default_factory=dict)\n    by_status: Dict[str, int] = Field(default_factory=dict)\n    by_currency: Dict[str, int] = Field(default_factory=dict)\n    hierarchy_depth: int = Field(default=0)\n    total_groups: int = Field(default=0)\n\n\n# Update forward references\nCompanyGroupResponse.model_rebuild()\nCompanyResponse.model_rebuild()\nCompanyHierarchyResponse.model_rebuild()\n</create-file>\n</function_calls>'}
{'role': 'user', 'content': '<tool_result> <create-file> ToolResult(success=True, output="File \'backend/app/schemas/company.py\' created successfully.") </create-file> </tool_result>'}
{'role': 'assistant', 'content': 'Now let me create the User schemas:\n\n\n<function_calls><create-file file_path="backend/app/schemas/user.py">"""\nUser Management Schemas for SAMMS ENTERPRISE SOVEREIGN OPERATING SYSTEM\nHandles users, roles, permissions, sessions, and activity logs\n"""\nfrom datetime import datetime, date\nfrom typing import Optional, List, Dict, Any, Union\nfrom uuid import UUID\nfrom decimal import Decimal\nfrom enum import Enum\n\nfrom pydantic import Field, field_validator, model_validator, EmailStr\n\nfrom .base import (\n    BaseResponseModel,\n    PaginationParams,\n    PaginatedResponse,\n    SuccessResponse,\n    ErrorResponse,\n    Address,\n    ContactInfo,\n    TimestampMixin,\n    IDMixin,\n)\n\n\nclass UserType(str, Enum):\n    """User type enumeration"""\n    EMPLOYEE = "employee"\n    CONTRACTOR = "contractor"\n    CONSULTANT = "consultant"\n    VENDOR = "vendor"\n    CUSTOMER = "customer"\n    PARTNER = "partner"\n    ADMIN = "admin"\n    SYSTEM = "system"\n    API_USER = "api_user"\n\n\nclass UserStatus(str, Enum):\n    """User status enumeration"""\n    ACTIVE = "active"\n    INACTIVE = "inactive"\n    PENDING = "pending"\n    SUSPENDED = "suspended"\n    LOCKED = "locked"\n    TERMINATED = "terminated"\n    ARCHIVED = "archived"\n\n\nclass AuthenticationMethod(str, Enum):\n    """Authentication method enumeration"""\n    PASSWORD = "password"\n    SSO = "sso"\n    SAML = "saml"\n    OAUTH2 = "oauth2"\n    LDAP = "ldap"\n    MFA = "mfa"\n    API_KEY = "api_key"\n    CERTIFICATE = "certificate"\n\n\nclass PermissionScope(str, Enum):\n    """Permission scope enumeration"""\n    GLOBAL = "global"\n    COMPANY = "company"\n    DEPARTMENT = "department"\n    TEAM = "team"\n    SELF = "self"\n\n\n# ============================================\n# Permission Schemas\n# ============================================\n\nclass PermissionBase(BaseResponseModel):\n    """Base schema for permission"""\n    code: str = Field(..., min_length=1, max_length=100, description="Unique permission code")\n    name: str = Field(..., min_length=1, max_length=200, description="Permission name")\n    description: Optional[str] = Field(None, max_length=2000, description="Permission description")\n    category: str = Field(..., min_length=1, max_length=100, description="Permission category")\n    module: Optional[str] = Field(None, max_length=100, description="Module this permission belongs to")\n    scope: PermissionScope = Field(default=PermissionScope.COMPANY, description="Permission scope")\n    is_system: bool = Field(default=False, description="Whether this is a system permission")\n    metadata: Optional[Dict[str, Any]] = Field(default_factory=dict)\n\n\nclass PermissionCreate(PermissionBase):\n    """Schema for creating a permission"""\n    pass\n\n\nclass PermissionUpdate(BaseResponseModel):\n    """Schema for updating a permission"""\n    name: Optional[str] = Field(None, min_length=1, max_length=200)\n    description: Optional[str] = Field(None, max_length=2000)\n    category: Optional[str] = Field(None, min_length=1, max_length=100)\n    module: Optional[str] = Field(None, max_length=100)\n    scope: Optional[PermissionScope] = None\n    metadata: Optional[Dict[str, Any]] = None\n    is_active: Optional[bool] = None\n\n\nclass PermissionResponse(PermissionBase, TimestampMixin, IDMixin):\n    """Schema for permission response"""\n    is_active: bool = Field(default=True)\n    role_count: int = Field(default=0, description="Number of roles with this permission")\n    user_count: int = Field(default=0, description="Number of users with this permission")\n    \n    class Config:\n        from_attributes = True\n\n\nclass PermissionListResponse(BaseResponseModel):\n    """Schema for permission list item"""\n    id: UUID\n    code: str\n    name: str\n    category: str\n    module: Optional[str]\n    scope: PermissionScope\n    is_active: bool\n    \n    class Config:\n        from_attributes = True\n\n\n# ============================================\n# Role Schemas\n# ============================================\n\nclass RoleBase(BaseResponseModel):\n    """Base schema for role"""\n    name: str = Field(..., min_length=1, max_length=100, description="Role name")\n    code: str = Field(..., min_length=1, max_length=50, description="Unique role code")\n    description: Optional[str] = Field(None, max_length=2000, description="Role description")\n    company_id: Optional[UUID] = Field(None, description="Company ID (null for global roles)")\n    is_system: bool = Field(default=False, description="Whether this is a system role")\n    is_assignable: bool = Field(default=True, description="Whether this role can be assigned")\n    max_users: Optional[int] = Field(None, ge=0, description="Maximum users allowed")\n    priority: int = Field(default=0, description="Role priority for conflict resolution")\n    metadata: Optional[Dict[str, Any]] = Field(default_factory=dict)\n\n\nclass RoleCreate(RoleBase):\n    """Schema for creating a role"""\n    permission_ids: List[UUID] = Field(default_factory=list, description="Permission IDs to assign")\n\n\nclass RoleUpdate(BaseResponseModel):\n    """Schema for updating a role"""\n    name: Optional[str] = Field(None, min_length=1, max_length=100)\n    code: Optional[str] = Field(None, min_length=1, max_length=50)\n    description: Optional[str] = Field(None, max_length=2000)\n    is_assignable: Optional[bool] = None\n    max_users: Optional[int] = Field(None, ge=0)\n    priority: Optional[int] = None\n    metadata: Optional[Dict[str, Any]] = None\n    is_active: Optional[bool] = None\n\n\nclass RolePermissionUpdate(BaseResponseModel):\n    """Schema for updating role permissions"""\n    permission_ids: List[UUID] = Field(..., description="List of permission IDs")\n    action: str = Field(default="replace", description="Action: add, remove, replace")\n\n\nclass RoleResponse(RoleBase, TimestampMixin, IDMixin):\n    """Schema for role response"""\n    is_active: bool = Field(default=True)\n    user_count: int = Field(default=0, description="Number of users with this role")\n    permissions: List[PermissionListResponse] = Field(default_factory=list)\n    \n    class Config:\n        from_attributes = True\n\n\nclass RoleListResponse(BaseResponseModel):\n    """Schema for role list item"""\n    id: UUID\n    name: str\n    code: str\n    description: Optional[str]\n    company_id: Optional[UUID]\n    is_system: bool\n    is_active: bool\n    user_count: int = 0\n    \n    class Config:\n        from_attributes = True\n\n\n# ============================================\n# User Schemas\n# ============================================\n\nclass UserBase(BaseResponseModel):\n    """Base schema for user"""\n    username: str = Field(..., min_length=3, max_length=100, description="Unique username")\n    email: EmailStr = Field(..., description="Email address")\n    first_name: str = Field(..., min_length=1, max_length=100, description="First name")\n    last_name: str = Field(..., min_length=1, max_length=100, description="Last name")\n    middle_name: Optional[str] = Field(None, max_length=100, description="Middle name")\n    \n    # User classification\n    user_type: UserType = Field(default=UserType.EMPLOYEE, description="User type")\n    employee_id: Optional[str] = Field(None, max_length=50, description="Employee ID")\n    \n    # Company association\n    primary_company_id: Optional[UUID] = Field(None, description="Primary company ID")\n    department_id: Optional[UUID] = Field(None, description="Department ID")\n    position_id: Optional[UUID] = Field(None, description="Position ID")\n    manager_id: Optional[UUID] = Field(None, description="Manager user ID")\n    \n    # Contact info\n    phone: Optional[str] = Field(None, max_length=50, description="Phone number")\n    mobile: Optional[str] = Field(None, max_length=50, description="Mobile number")\n    address: Optional[Address] = Field(None, description="Address")\n    \n    # Preferences\n    timezone: str = Field(default="UTC", description="User timezone")\n    locale: str = Field(default="en_US", description="User locale")\n    date_format: str = Field(default="YYYY-MM-DD", description="Preferred date format")\n    time_format: str = Field(default="24h", description="Time format: 12h or 24h")\n    \n    # Profile\n    avatar_url: Optional[str] = Field(None, max_length=1000, description="Avatar URL")\n    bio: Optional[str] = Field(None, max_length=2000, description="User biography")\n    \n    # Authentication settings\n    auth_method: AuthenticationMethod = Field(default=AuthenticationMethod.PASSWORD)\n    mfa_enabled: bool = Field(default=False, description="MFA enabled")\n    mfa_method: Optional[str] = Field(None, description="MFA method: app, sms, email")\n    \n    # Additional info\n    job_title: Optional[str] = Field(None, max_length=200, description="Job title")\n    department: Optional[str] = Field(None, max_length=200, description="Department name")\n    hire_date: Optional[date] = Field(None, description="Hire date")\n    \n    metadata: Optional[Dict[str, Any]] = Field(default_factory=dict)\n    preferences: Optional[Dict[str, Any]] = Field(default_factory=dict)\n    \n    @field_validator(\'username\')\n    @classmethod\n    def validate_username(cls, v: str) -> str:\n        """Validate username format"""\n        import re\n        if not re.match(r\'^[a-zA-Z0-9._-]+$\', v):\n            raise ValueError(\'Username must contain only alphanumeric characters, dots, underscores, and hyphens\')\n        return v.lower()\n\n\nclass UserCreate(UserBase):\n    """Schema for creating a user"""\n    password: str = Field(..., min_length=8, max_length=128, description="Password")\n    confirm_password: str = Field(..., min_length=8, max_length=128, description="Confirm password")\n    role_ids: List[UUID] = Field(default_factory=list, description="Role IDs to assign")\n    company_ids: List[UUID] = Field(default_factory=list, description="Company IDs for access")\n    \n    @model_validator(mode=\'after\')\n    def validate_passwords_match(self) -> \'UserCreate\':\n        """Validate passwords match"""\n        if self.password != self.confirm_password:\n            raise ValueError(\'Passwords do not match\')\n        return self\n    \n    @field_validator(\'password\')\n    @classmethod\n    def validate_password_strength(cls, v: str) -> str:\n        """Validate password strength"""\n        import re\n        if not re.search(r\'[A-Z]\', v):\n            raise ValueError(\'Password must contain at least one uppercase letter\')\n        if not re.search(r\'[a-z]\', v):\n            raise ValueError(\'Password must contain at least one lowercase letter\')\n        if not re.search(r\'\\d\', v):\n            raise ValueError(\'Password must contain at least one digit\')\n        if not re.search(r\'[!@#$%^&*(),.?":{}|<>]\', v):\n            raise ValueError(\'Password must contain at least one special character\')\n        return v\n\n\nclass UserUpdate(BaseResponseModel):\n    """Schema for updating a user"""\n    email: Optional[EmailStr] = None\n    first_name: Optional[str] = Field(None, min_length=1, max_length=100)\n    last_name: Optional[str] = Field(None, min_length=1, max_length=100)\n    middle_name: Optional[str] = Field(None, max_length=100)\n    user_type: Optional[UserType] = None\n    employee_id: Optional[str] = Field(None, max_length=50)\n    primary_company_id: Optional[UUID] = None\n    department_id: Optional[UUID] = None\n    position_id: Optional[UUID] = None\n    manager_id: Optional[UUID] = None\n    phone: Optional[str] = Field(None, max_length=50)\n    mobile: Optional[str] = Field(None, max_length=50)\n    address: Optional[Address] = None\n    timezone: Optional[str] = None\n    locale: Optional[str] = None\n    date_format: Optional[str] = None\n    time_format: Optional[str] = None\n    avatar_url: Optional[str] = Field(None, max_length=1000)\n    bio: Optional[str] = Field(None, max_length=2000)\n    job_title: Optional[str] = Field(None, max_length=200)\n    department: Optional[str] = Field(None, max_length=200)\n    hire_date: Optional[date] = None\n    metadata: Optional[Dict[str, Any]] = None\n    preferences: Optional[Dict[str, Any]] = None\n    status: Optional[UserStatus] = None\n    is_active: Optional[bool] = None\n\n\nclass UserPasswordUpdate(BaseResponseModel):\n    """Schema for updating user password"""\n    current_password: str = Field(..., description="Current password")\n    new_password: str = Field(..., min_length=8, max_length=128, description="New password")\n    confirm_password: str = Field(..., min_length=8, max_length=128, description="Confirm new password")\n    \n    @model_validator(mode=\'after\')\n    def validate_passwords_match(self) -> \'UserPasswordUpdate\':\n        """Validate passwords match"""\n        if self.new_password != self.confirm_password:\n            raise ValueError(\'Passwords do not match\')\n        if self.current_password == self.new_password:\n            raise ValueError(\'New password must be different from current password\')\n        return self\n\n\nclass UserRoleUpdate(BaseResponseModel):\n    """Schema for updating user roles"""\n    role_ids: List[UUID] = Field(..., description="List of role IDs")\n    action: str = Field(default="replace", description="Action: add, remove, replace")\n\n\nclass UserCompanyAccessUpdate(BaseResponseModel):\n    """Schema for updating user company access"""\n    company_ids: List[UUID] = Field(..., description="List of company IDs")\n    action: str = Field(default="replace", description="Action: add, remove, replace")\n\n\nclass UserResponse(UserBase, TimestampMixin, IDMixin):\n    """Schema for user response"""\n    status: UserStatus = Field(default=UserStatus.PENDING)\n    is_active: bool = Field(default=True)\n    is_verified: bool = Field(default=False)\n    is_superuser: bool = Field(default=False)\n    \n    # Computed fields\n    full_name: str = Field(default="", description="Full name")\n    display_name: str = Field(default="", description="Display name")\n    \n    # Related data\n    roles: List[RoleListResponse] = Field(default_factory=list)\n    companies: List[Dict[str, Any]] = Field(default_factory=list, description="Accessible companies")\n    \n    # Statistics\n    last_login: Optional[datetime] = None\n    last_activity: Optional[datetime] = None\n    login_count: int = Field(default=0)\n    \n    class Config:\n        from_attributes = True\n\n\nclass UserListResponse(BaseResponseModel):\n    """Schema for user list item"""\n    id: UUID\n    username: str\n    email: str\n    first_name: str\n    last_name: str\n    full_name: str\n    user_type: UserType\n    status: UserStatus\n    is_active: bool\n    primary_company_id: Optional[UUID]\n    job_title: Optional[str]\n    department: Optional[str]\n    avatar_url: Optional[str]\n    created_at: datetime\n    \n    class Config:\n        from_attributes = True\n\n\nclass UserProfileResponse(BaseResponseModel):\n    """Schema for user profile response"""\n    user: UserResponse\n    permissions: List[str] = Field(default_factory=list)\n    preferences: Dict[str, Any] = Field(default_factory=dict)\n    notification_settings: Dict[str, Any] = Field(default_factory=dict)\n    recent_activity: List[Dict[str, Any]] = Field(default_factory=list)\n\n\n# ============================================\n# User Session Schemas\n# ============================================\n\nclass UserSessionBase(BaseResponseModel):\n    """Base schema for user session"""\n    device_type: Optional[str] = Field(None, max_length=50, description="Device type")\n    device_name: Optional[str] = Field(None, max_length=200, description="Device name")\n    browser: Optional[str] = Field(None, max_length=100, description="Browser name")\n    os: Optional[str] = Field(None, max_length=100, description="Operating system")\n    ip_address: Optional[str] = Field(None, max_length=50, description="IP address")\n    location: Optional[str] = Field(None, max_length=200, description="Geographic location")\n\n\nclass UserSessionResponse(UserSessionBase, TimestampMixin, IDMixin):\n    """Schema for user session response"""\n    user_id: UUID\n    token_hash: Optional[str] = None\n    is_active: bool = Field(default=True)\n    is_current: bool = Field(default=False)\n    expires_at: datetime\n    last_activity: Optional[datetime] = None\n    \n    class Config:\n        from_attributes = True\n\n\nclass UserSessionListResponse(BaseResponseModel):\n    """Schema for session list item"""\n    id: UUID\n    device_type: Optional[str]\n    device_name: Optional[str]\n    browser: Optional[str]\n    os: Optional[str]\n    ip_address: Optional[str]\n    location: Optional[str]\n    is_active: bool\n    is_current: bool\n    created_at: datetime\n    last_activity: Optional[datetime]\n    expires_at: datetime\n    \n    class Config:\n        from_attributes = True\n\n\n# ============================================\n# User Activity Log Schemas\n# ============================================\n\nclass ActivityType(str, Enum):\n    """Activity type enumeration"""\n    LOGIN = "login"\n    LOGOUT = "logout"\n    LOGIN_FAILED = "login_failed"\n    PASSWORD_CHANGE = "password_change"\n    PROFILE_UPDATE = "profile_update"\n    SETTINGS_CHANGE = "settings_change"\n    CREATE = "create"\n    READ = "read"\n    UPDATE = "update"\n    DELETE = "delete"\n    EXPORT = "export"\n    IMPORT = "import"\n    DOWNLOAD = "download"\n    UPLOAD = "upload"\n    SHARE = "share"\n    APPROVE = "approve"\n    REJECT = "reject"\n    SUBMIT = "submit"\n    COMMENT = "comment"\n    VIEW = "view"\n    SEARCH = "search"\n    API_CALL = "api_call"\n    ERROR = "error"\n    OTHER = "other"\n\n\nclass UserActivityLogBase(BaseResponseModel):\n    """Base schema for user activity log"""\n    activity_type: ActivityType = Field(..., description="Type of activity")\n    module: Optional[str] = Field(None, max_length=100, description="Module name")\n    action: str = Field(..., max_length=200, description="Action performed")\n    description: Optional[str] = Field(None, max_length=2000, description="Detailed description")\n    entity_type: Optional[str] = Field(None, max_length=100, description="Entity type")\n    entity_id: Optional[UUID] = Field(None, description="Entity ID")\n    company_id: Optional[UUID] = Field(None, description="Company context")\n    ip_address: Optional[str] = Field(None, max_length=50, description="IP address")\n    user_agent: Optional[str] = Field(None, max_length=500, description="User agent")\n    request_id: Optional[str] = Field(None, max_length=100, description="Request ID")\n    old_values: Optional[Dict[str, Any]] = None\n    new_values: Optional[Dict[str, Any]] = None\n    metadata: Optional[Dict[str, Any]] = None\n\n\nclass UserActivityLogResponse(UserActivityLogBase, TimestampMixin, IDMixin):\n    """Schema for user activity log response"""\n    user_id: UUID\n    session_id: Optional[UUID] = None\n    duration_ms: Optional[int] = None\n    status: str = Field(default="success", description="Activity status")\n    error_message: Optional[str] = None\n    \n    class Config:\n        from_attributes = True\n\n\nclass UserActivityLogFilterParams(PaginationParams):\n    """Filter parameters for activity log queries"""\n    user_id: Optional[UUID] = None\n    activity_type: Optional[List[ActivityType]] = None\n    module: Optional[str] = None\n    entity_type: Optional[str] = None\n    entity_id: Optional[UUID] = None\n    company_id: Optional[UUID] = None\n    status: Optional[str] = None\n    ip_address: Optional[str] = None\n    from_date: Optional[datetime] = None\n    to_date: Optional[datetime] = None\n    search: Optional[str] = None\n\n\n# ============================================\n# Authentication Schemas\n# ============================================\n\nclass LoginRequest(BaseResponseModel):\n    """Schema for login request"""\n    username: str = Field(..., min_length=3, max_length=100)\n    password: str = Field(..., min_length=1)\n    company_id: Optional[UUID] = None\n    remember_me: bool = Field(default=False)\n    mfa_code: Optional[str] = Field(None, min_length=6, max_length=8)\n\n\nclass LoginResponse(BaseResponseModel):\n    """Schema for login response"""\n    access_token: str\n    refresh_token: str\n    token_type: str = Field(default="bearer")\n    expires_in: int = Field(description="Token expiry in seconds")\n    user: UserResponse\n    companies: List[Dict[str, Any]] = Field(default_factory=list)\n    permissions: List[str] = Field(default_factory=list)\n    requires_mfa: bool = Field(default=False)\n    mfa_method: Optional[str] = None\n\n\nclass RefreshTokenRequest(BaseResponseModel):\n    """Schema for refresh token request"""\n    refresh_token: str\n\n\nclass RefreshTokenResponse(BaseResponseModel):\n    """Schema for refresh token response"""\n    access_token: str\n    refresh_token: str\n    token_type: str = Field(default="bearer")\n    expires_in: int\n\n\nclass LogoutRequest(BaseResponseModel):\n    """Schema for logout request"""\n    all_sessions: bool = Field(default=False, description="Log out from all sessions")\n\n\nclass MFASetupResponse(BaseResponseModel):\n    """Schema for MFA setup response"""\n    secret: str\n    qr_code_url: str\n    backup_codes: List[str]\n\n\nclass MFAVerifyRequest(BaseResponseModel):\n    """Schema for MFA verification request"""\n    code: str = Field(..., min_length=6, max_length=8)\n\n\n# ============================================\n# Password Reset Schemas\n# ============================================\n\nclass PasswordResetRequest(BaseResponseModel):\n    """Schema for password reset request"""\n    email: EmailStr\n\n\nclass PasswordResetConfirm(BaseResponseModel):\n    """Schema for password reset confirmation"""\n    token: str\n    new_password: str = Field(..., min_length=8, max_length=128)\n    confirm_password: str = Field(..., min_length=8, max_length=128)\n    \n    @model_validator(mode=\'after\')\n    def validate_passwords_match(self) -> \'PasswordResetConfirm\':\n        if self.new_password != self.confirm_password:\n            raise ValueError(\'Passwords do not match\')\n        return self\n\n\nclass EmailVerificationRequest(BaseResponseModel):\n    """Schema for email verification request"""\n    token: str\n\n\n# ============================================\n# Query Parameters\n# ============================================\n\nclass UserFilterParams(PaginationParams):\n    """Filter parameters for user queries"""\n    username: Optional[str] = None\n    email: Optional[str] = None\n    first_name: Optional[str] = None\n    last_name: Optional[str] = None\n    user_type: Optional[List[UserType]] = None\n    status: Optional[List[UserStatus]] = None\n    company_id: Optional[UUID] = None\n    department_id: Optional[UUID] = None\n    manager_id: Optional[UUID] = None\n    is_active: Optional[bool] = None\n    is_verified: Optional[bool] = None\n    mfa_enabled: Optional[bool] = None\n    role_id: Optional[UUID] = None\n    permission_code: Optional[str] = None\n    search: Optional[str] = None\n    created_after: Optional[datetime] = None\n    created_before: Optional[datetime] = None\n    last_login_after: Optional[datetime] = None\n    last_login_before: Optional[datetime] = None\n\n\nclass RoleFilterParams(PaginationParams):\n    """Filter parameters for role queries"""\n    name: Optional[str] = None\n    code: Optional[str] = None\n    company_id: Optional[UUID] = None\n    is_system: Optional[bool] = None\n    is_active: Optional[bool] = None\n    permission_id: Optional[UUID] = None\n    search: Optional[str] = None\n\n\nclass PermissionFilterParams(PaginationParams):\n    """Filter parameters for permission queries"""\n    code: Optional[str] = None\n    name: Optional[str] = None\n    category: Optional[str] = None\n    module: Optional[str] = None\n    scope: Optional[PermissionScope] = None\n    is_active: Optional[bool] = None\n    is_system: Optional[bool] = None\n    search: Optional[str] = None\n\n\n# ============================================\n# Bulk Operations\n# ============================================\n\nclass UserBulkCreate(BaseResponseModel):\n    """Schema for bulk creating users"""\n    users: List[UserCreate] = Field(..., min_length=1, max_length=100)\n\n\nclass UserBulkUpdate(BaseResponseModel):\n    """Schema for bulk updating users"""\n    ids: List[UUID] = Field(..., min_length=1)\n    updates: UserUpdate\n\n\nclass UserBulkDelete(BaseResponseModel):\n    """Schema for bulk deleting users"""\n    ids: List[UUID] = Field(..., min_length=1)\n    hard_delete: bool = Field(default=False)\n\n\nclass UserBulkStatusUpdate(BaseResponseModel):\n    """Schema for bulk status update"""\n    ids: List[UUID] = Field(..., min_length=1)\n    status: UserStatus\n\n\nclass UserBulkRoleAssign(BaseResponseModel):\n    """Schema for bulk role assignment"""\n    user_ids: List[UUID] = Field(..., min_length=1)\n    role_ids: List[UUID] = Field(..., min_length=1)\n    action: str = Field(default="add", description="add or remove")\n\n\n# ============================================\n# Statistics\n# ============================================\n\nclass UserStatistics(BaseResponseModel):\n    """Schema for user statistics"""\n    total_users: int = 0\n    active_users: int = 0\n    inactive_users: int = 0\n    pending_users: int = 0\n    by_type: Dict[str, int] = Field(default_factory=dict)\n    by_status: Dict[str, int] = Field(default_factory=dict)\n    by_company: Dict[str, int] = Field(default_factory=dict)\n    mfa_enabled_count: int = 0\n    verified_count: int = 0\n    online_now: int = 0\n    new_this_month: int = 0\n    logins_today: int = 0\n\n\nclass RoleStatistics(BaseResponseModel):\n    """Schema for role statistics"""\n    total_roles: int = 0\n    system_roles: int = 0\n    custom_roles: int = 0\n    by_company: Dict[str, int] = Field(default_factory=dict)\n    most_used: List[Dict[str, Any]] = Field(default_factory=list)\n    unused: List[str] = Field(default_factory=list)\n\n\n# Update forward references\nRoleResponse.model_rebuild()\nUserResponse.model_rebuild()\n</create-file>\n</function_calls>'}
{'role': 'user', 'content': '<tool_result> <create-file> ToolResult(success=True, output="File \'backend/app/schemas/user.py\' created successfully.") </create-file> </tool_result>'}
{'role': 'assistant', 'content': 'Now let me create the Accounting schemas for the double-entry bookkeeping system:\n\n\n<function_calls><create-file file_path="backend/app/schemas/accounting.py">"""\nAccounting Schemas for SAMMS ENTERPRISE SOVEREIGN OPERATING SYSTEM\nDouble-entry bookkeeping system with chart of accounts, journal entries, and financial periods\n"""\nfrom datetime import datetime, date\nfrom typing import Optional, List, Dict, Any, Union\nfrom uuid import UUID\nfrom decimal import Decimal\nfrom enum import Enum\n\nfrom pydantic import Field, field_validator, model_validator\n\nfrom .base import (\n    BaseResponseModel,\n    PaginationParams,\n    PaginatedResponse,\n    SuccessResponse,\n    ErrorResponse,\n    TimestampMixin,\n    IDMixin,\n)\n\n\nclass AccountType(str, Enum):\n    """Account type enumeration (main categories)"""\n    ASSET = "asset"\n    LIABILITY = "liability"\n    EQUITY = "equity"\n    REVENUE = "revenue"\n    EXPENSE = "expense"\n    CONTRA_ASSET = "contra_asset"\n    CONTRA_LIABILITY = "contra_liability"\n    CONTRA_EQUITY = "contra_equity"\n    CONTRA_REVENUE = "contra_revenue"\n    CONTRA_EXPENSE = "contra_expense"\n\n\nclass AccountSubType(str, Enum):\n    """Account sub-type enumeration"""\n    # Asset sub-types\n    CASH = "cash"\n    BANK = "bank"\n    RECEIVABLE = "receivable"\n    INVENTORY = "inventory"\n    PREPAID = "prepaid"\n    FIXED_ASSET = "fixed_asset"\n    INTANGIBLE = "intangible"\n    DEPOSIT = "deposit"\n    INVESTMENT = "investment"\n    OTHER_ASSET = "other_asset"\n    \n    # Liability sub-types\n    PAYABLE = "payable"\n    ACCRUED = "accrued"\n    DEFERRED_REVENUE = "deferred_revenue"\n    SHORT_TERM_DEBT = "short_term_debt"\n    LONG_TERM_DEBT = "long_term_debt"\n    OTHER_LIABILITY = "other_liability"\n    \n    # Equity sub-types\n    CAPITAL = "capital"\n    RETAINED_EARNINGS = "retained_earnings"\n    DRAWING = "drawing"\n    RESERVE = "reserve"\n    OTHER_EQUITY = "other_equity"\n    \n    # Revenue sub-types\n    SALES = "sales"\n    SERVICE = "service"\n    INTEREST_INCOME = "interest_income"\n    OTHER_INCOME = "other_income"\n    GAIN = "gain"\n    \n    # Expense sub-types\n    COST_OF_SALES = "cost_of_sales"\n    OPERATING = "operating"\n    ADMINISTRATIVE = "administrative"\n    SALES_EXPENSE = "sales_expense"\n    DEPRECIATION = "depreciation"\n    AMORTIZATION = "amortization"\n    INTEREST_EXPENSE = "interest_expense"\n    TAX_EXPENSE = "tax_expense"\n    OTHER_EXPENSE = "other_expense"\n    LOSS = "loss"\n\n\nclass AccountStatus(str, Enum):\n    """Account status enumeration"""\n    ACTIVE = "active"\n    INACTIVE = "inactive"\n    LOCKED = "locked"\n    ARCHIVED = "archived"\n\n\nclass JournalEntryStatus(str, Enum):\n    """Journal entry status enumeration"""\n    DRAFT = "draft"\n    PENDING = "pending"\n    APPROVED = "approved"\n    POSTED = "posted"\n    REVERSED = "reversed"\n    VOIDED = "voided"\n    REJECTED = "rejected"\n\n\nclass JournalEntryType(str, Enum):\n    """Journal entry type enumeration"""\n    STANDARD = "standard"\n    ADJUSTING = "adjusting"\n    CLOSING = "closing"\n    OPENING = "opening"\n    REVERSING = "reversing"\n    RECURRING = "recurring"\n    CORRECTION = "correction"\n    RECLASSIFICATION = "reclassification"\n    INTERCOMPANY = "intercompany"\n    CONSOLIDATION = "consolidation"\n    DEPRECIATION = "depreciation"\n    AMORTIZATION = "amortization"\n    ACCRUAL = "accrual"\n    DEFERRAL = "deferral"\n    SYSTEM = "system"\n\n\nclass FiscalYearStatus(str, Enum):\n    """Fiscal year status enumeration"""\n    OPEN = "open"\n    CLOSED = "closed"\n    LOCKED = "locked"\n    ADJUSTING = "adjusting"\n\n\nclass FiscalPeriodType(str, Enum):\n    """Fiscal period type enumeration"""\n    MONTH = "month"\n    QUARTER = "quarter"\n    YEAR = "year"\n    ADJUSTING = "adjusting"\n    CUSTOM = "custom"\n\n\nclass FiscalPeriodStatus(str, Enum):\n    """Fiscal period status enumeration"""\n    OPEN = "open"\n    CLOSED = "closed"\n    LOCKED = "locked"\n    ADJUSTING = "adjusting"\n\n\nclass BudgetStatus(str, Enum):\n    """Budget status enumeration"""\n    DRAFT = "draft"\n    SUBMITTED = "submitted"\n    APPROVED = "approved"\n    ACTIVE = "active"\n    ARCHIVED = "archived"\n    SUPERSEDED = "superseded"\n\n\nclass BudgetType(str, Enum):\n    """Budget type enumeration"""\n    ANNUAL = "annual"\n    QUARTERLY = "quarterly"\n    MONTHLY = "monthly"\n    ROLLING = "rolling"\n    PROJECT = "project"\n    DEPARTMENT = "department"\n    ZERO_BASED = "zero_based"\n\n\nclass DebitCredit(str, Enum):\n    """Debit/Credit enumeration"""\n    DEBIT = "debit"\n    CREDIT = "credit"\n\n\n# ============================================\n# Account Schemas\n# ============================================\n\nclass AccountBase(BaseResponseModel):\n    """Base schema for account"""\n    code: str = Field(..., min_length=1, max_length=50, description="Account code")\n    name: str = Field(..., min_length=1, max_length=200, description="Account name")\n    description: Optional[str] = Field(None, max_length=2000, description="Account description")\n    \n    # Classification\n    account_type: AccountType = Field(..., description="Main account type")\n    account_sub_type: Optional[AccountSubType] = Field(None, description="Account sub-type")\n    \n    # Hierarchy\n    parent_account_id: Optional[UUID] = Field(None, description="Parent account ID")\n    level: int = Field(default=0, ge=0, le=10, description="Account level in hierarchy")\n    \n    # Normal balance\n    normal_balance: DebitCredit = Field(..., description="Normal balance direction")\n    \n    # Company\n    company_id: UUID = Field(..., description="Company ID")\n    \n    # Flags\n    is_header: bool = Field(default=False, description="Header account (no postings)")\n    is_active: bool = Field(default=True, description="Active status")\n    is_system: bool = Field(default=False, description="System account")\n    allow_manual_entry: bool = Field(default=True, description="Allow manual journal entries")\n    \n    # Currency\n    currency: Optional[str] = Field(None, min_length=3, max_length=3, description="Account currency")\n    \n    # Additional info\n    tax_code: Optional[str] = Field(None, max_length=50, description="Associated tax code")\n    department_id: Optional[UUID] = Field(None, description="Associated department")\n    project_id: Optional[UUID] = Field(None, description="Associated project")\n    \n    metadata: Optional[Dict[str, Any]] = Field(default_factory=dict)\n    tags: List[str] = Field(default_factory=list)\n\n\nclass AccountCreate(AccountBase):\n    """Schema for creating an account"""\n    opening_balance: Optional[Decimal] = Field(None, description="Opening balance")\n    opening_balance_date: Optional[date] = Field(None, description="Opening balance date")\n    \n    @field_validator(\'code\')\n    @classmethod\n    def validate_code(cls, v: str) -> str:\n        """Validate account code format"""\n        return v.strip().upper()\n\n\nclass AccountUpdate(BaseResponseModel):\n    """Schema for updating an account"""\n    name: Optional[str] = Field(None, min_length=1, max_length=200)\n    description: Optional[str] = Field(None, max_length=2000)\n    account_sub_type: Optional[AccountSubType] = None\n    parent_account_id: Optional[UUID] = None\n    is_header: Optional[bool] = None\n    is_active: Optional[bool] = None\n    allow_manual_entry: Optional[bool] = None\n    currency: Optional[str] = Field(None, min_length=3, max_length=3)\n    tax_code: Optional[str] = Field(None, max_length=50)\n    department_id: Optional[UUID] = None\n    project_id: Optional[UUID] = None\n    metadata: Optional[Dict[str, Any]] = None\n    tags: Optional[List[str]] = None\n    status: Optional[AccountStatus] = None\n\n\nclass AccountResponse(AccountBase, TimestampMixin, IDMixin):\n    """Schema for account response"""\n    status: AccountStatus = Field(default=AccountStatus.ACTIVE)\n    \n    # Path and hierarchy\n    full_code: str = Field(default="", description="Full code including parent codes")\n    full_name: str = Field(default="", description="Full name including path")\n    path: str = Field(default="", description="Account path in hierarchy")\n    \n    # Balance information\n    balance: Decimal = Field(default=Decimal("0"), description="Current balance")\n    debit_total: Decimal = Field(default=Decimal("0"), description="Total debits")\n    credit_total: Decimal = Field(default=Decimal("0"), description="Total credits")\n    \n    # Statistics\n    entry_count: int = Field(default=0, description="Number of journal entries")\n    \n    # Relationships\n    parent_account: Optional["AccountResponse"] = None\n    child_accounts: List["AccountResponse"] = Field(default_factory=list)\n    \n    class Config:\n        from_attributes = True\n\n\nclass AccountListResponse(BaseResponseModel):\n    """Schema for account list item"""\n    id: UUID\n    code: str\n    name: str\n    account_type: AccountType\n    account_sub_type: Optional[AccountSubType]\n    normal_balance: DebitCredit\n    is_header: bool\n    is_active: bool\n    balance: Decimal\n    parent_account_id: Optional[UUID]\n    company_id: UUID\n    \n    class Config:\n        from_attributes = True\n\n\nclass AccountTreeResponse(BaseResponseModel):\n    """Schema for account tree/hierarchy"""\n    id: UUID\n    code: str\n    name: str\n    account_type: AccountType\n    is_header: bool\n    level: int\n    balance: Decimal\n    children: List["AccountTreeResponse"] = Field(default_factory=list)\n    \n    class Config:\n        from_attributes = True\n\n\n# ============================================\n# Journal Entry Schemas\n# ============================================\n\nclass JournalEntryLineBase(BaseResponseModel):\n    """Base schema for journal entry line"""\n    account_id: UUID = Field(..., description="Account ID")\n    description: Optional[str] = Field(None, max_length=500, description="Line description")\n    debit: Optional[Decimal] = Field(None, ge=0, description="Debit amount")\n    credit: Optional[Decimal] = Field(None, ge=0, description="Credit amount")\n    \n    # Dimensions\n    department_id: Optional[UUID] = None\n    project_id: Optional[UUID] = None\n    location_id: Optional[UUID] = None\n    cost_center_id: Optional[UUID] = None\n    \n    # Reference\n    reference: Optional[str] = Field(None, max_length=200, description="Line reference")\n    source_type: Optional[str] = Field(None, max_length=100, description="Source document type")\n    source_id: Optional[UUID] = Field(None, description="Source document ID")\n    \n    # Currency (for multi-currency)\n    currency: Optional[str] = Field(None, min_length=3, max_length=3)\n    exchange_rate: Optional[Decimal] = Field(None, ge=0)\n    base_debit: Optional[Decimal] = Field(None, ge=0, description="Debit in base currency")\n    base_credit: Optional[Decimal] = Field(None, ge=0, description="Credit in base currency")\n    \n    metadata: Optional[Dict[str, Any]] = None\n    \n    @model_validator(mode=\'after\')\n    def validate_amounts(self) -> \'JournalEntryLineBase\':\n        """Validate that only one of debit or credit is set"""\n        if self.debit and self.credit:\n            if self.debit > 0 and self.credit > 0:\n                raise ValueError(\'Both debit and credit cannot have positive values\')\n        return self\n\n\nclass JournalEntryLineCreate(JournalEntryLineBase):\n    """Schema for creating a journal entry line"""\n    pass\n\n\nclass JournalEntryLineUpdate(BaseResponseModel):\n    """Schema for updating a journal entry line"""\n    account_id: Optional[UUID] = None\n    description: Optional[str] = Field(None, max_length=500)\n    debit: Optional[Decimal] = Field(None, ge=0)\n    credit: Optional[Decimal] = Field(None, ge=0)\n    department_id: Optional[UUID] = None\n    project_id: Optional[UUID] = None\n    location_id: Optional[UUID] = None\n    cost_center_id: Optional[UUID] = None\n    reference: Optional[str] = Field(None, max_length=200)\n    currency: Optional[str] = Field(None, min_length=3, max_length=3)\n    exchange_rate: Optional[Decimal] = Field(None, ge=0)\n    metadata: Optional[Dict[str, Any]] = None\n\n\nclass JournalEntryLineResponse(JournalEntryLineBase, TimestampMixin, IDMixin):\n    """Schema for journal entry line response"""\n    journal_entry_id: UUID\n    line_number: int = Field(default=0, description="Line sequence number")\n    account_code: str = Field(default="", description="Account code")\n    account_name: str = Field(default="", description="Account name")\n    \n    class Config:\n        from_attributes = True\n\n\nclass JournalEntryBase(BaseResponseModel):\n    """Base schema for journal entry"""\n    entry_number: Optional[str] = Field(None, max_length=50, description="Entry number (auto if not provided)")\n    entry_date: date = Field(..., description="Journal entry date")\n    description: Optional[str] = Field(None, max_length=2000, description="Entry description")\n    \n    # Classification\n    entry_type: JournalEntryType = Field(default=JournalEntryType.STANDARD, description="Entry type")\n    \n    # Reference\n    reference: Optional[str] = Field(None, max_length=200, description="Reference number")\n    source_type: Optional[str] = Field(None, max_length=100, description="Source document type")\n    source_id: Optional[UUID] = Field(None, description="Source document ID")\n    \n    # Period\n    fiscal_year_id: Optional[UUID] = Field(None, description="Fiscal year ID")\n    fiscal_period_id: Optional[UUID] = Field(None, description="Fiscal period ID")\n    \n    # Reversal\n    is_reversing: bool = Field(default=False, description="Is this a reversing entry?")\n    reversing_date: Optional[date] = Field(None, description="Date for auto-reversal")\n    reversal_of_id: Optional[UUID] = Field(None, description="Original entry being reversed")\n    \n    # Recurring\n    is_recurring: bool = Field(default=False, description="Is this a recurring entry?")\n    recurring_schedule_id: Optional[UUID] = Field(None, description="Recurring schedule ID")\n    \n    # Approval\n    approval_required: bool = Field(default=True, description="Requires approval")\n    approved_by: Optional[UUID] = None\n    approved_at: Optional[datetime] = None\n    \n    # Currency\n    currency: str = Field(default="USD", min_length=3, max_length=3, description="Entry currency")\n    \n    # Company\n    company_id: UUID = Field(..., description="Company ID")\n    \n    metadata: Optional[Dict[str, Any]] = None\n    tags: List[str] = Field(default_factory=list)\n    attachments: List[str] = Field(default_factory=list, description="File attachments")\n\n\nclass JournalEntryCreate(JournalEntryBase):\n    """Schema for creating a journal entry"""\n    lines: List[JournalEntryLineCreate] = Field(..., min_length=2, description="Journal entry lines")\n    auto_post: bool = Field(default=False, description="Auto-post after creation")\n    \n    @model_validator(mode=\'after\')\n    def validate_balanced(self) -> \'JournalEntryCreate\':\n        """Validate that journal entry is balanced"""\n        total_debit = sum(line.debit or Decimal("0") for line in self.lines)\n        total_credit = sum(line.credit or Decimal("0") for line in self.lines)\n        if abs(total_debit - total_credit) > Decimal("0.01"):\n            raise ValueError(f\'Journal entry must be balanced. Debits: {total_debit}, Credits: {total_credit}\')\n        return self\n\n\nclass JournalEntryUpdate(BaseResponseModel):\n    """Schema for updating a journal entry"""\n    entry_date: Optional[date] = None\n    description: Optional[str] = Field(None, max_length=2000)\n    entry_type: Optional[JournalEntryType] = None\n    reference: Optional[str] = Field(None, max_length=200)\n    fiscal_period_id: Optional[UUID] = None\n    reversing_date: Optional[date] = None\n    metadata: Optional[Dict[str, Any]] = None\n    tags: Optional[List[str]] = None\n    attachments: Optional[List[str]] = None\n    lines: Optional[List[JournalEntryLineCreate]] = None\n    \n    @model_validator(mode=\'after\')\n    def validate_balanced_if_lines(self) -> \'JournalEntryUpdate\':\n        """Validate that journal entry is balanced if lines are provided"""\n        if self.lines:\n            total_debit = sum(line.debit or Decimal("0") for line in self.lines)\n            total_credit = sum(line.credit or Decimal("0") for line in self.lines)\n            if abs(total_debit - total_credit) > Decimal("0.01"):\n                raise ValueError(f\'Journal entry must be balanced. Debits: {total_debit}, Credits: {total_credit}\')\n        return self\n\n\nclass JournalEntryResponse(JournalEntryBase, TimestampMixin, IDMixin):\n    """Schema for journal entry response"""\n    status: JournalEntryStatus = Field(default=JournalEntryStatus.DRAFT)\n    \n    # Totals\n    total_debit: Decimal = Field(default=Decimal("0"), description="Total debit amount")\n    total_credit: Decimal = Field(default=Decimal("0"), description="Total credit amount")\n    line_count: int = Field(default=0, description="Number of lines")\n    \n    # Posted info\n    posted_by: Optional[UUID] = None\n    posted_at: Optional[datetime] = None\n    \n    # Reversal info\n    reversed_by_id: Optional[UUID] = None\n    reversed_at: Optional[datetime] = None\n    \n    # Workflow\n    workflow_instance_id: Optional[UUID] = None\n    \n    # Relationships\n    lines: List[JournalEntryLineResponse] = Field(default_factory=list)\n    \n    # Audit\n    created_by: Optional[UUID] = None\n    updated_by: Optional[UUID] = None\n    \n    class Config:\n        from_attributes = True\n\n\nclass JournalEntryListResponse(BaseResponseModel):\n    """Schema for journal entry list item"""\n    id: UUID\n    entry_number: str\n    entry_date: date\n    description: Optional[str]\n    entry_type: JournalEntryType\n    status: JournalEntryStatus\n    total_debit: Decimal\n    total_credit: Decimal\n    company_id: UUID\n    created_at: datetime\n    created_by: Optional[UUID]\n    \n    class Config:\n        from_attributes = True\n\n\n# ============================================\n# Fiscal Year & Period Schemas\n# ============================================\n\nclass FiscalYearBase(BaseResponseModel):\n    """Base schema for fiscal year"""\n    name: str = Field(..., min_length=1, max_length=100, description="Fiscal year name")\n    code: str = Field(..., min_length=1, max_length=20, description="Fiscal year code")\n    start_date: date = Field(..., description="Start date")\n    end_date: date = Field(..., description="End date")\n    company_id: UUID = Field(..., description="Company ID")\n    description: Optional[str] = Field(None, max_length=2000)\n    \n    @model_validator(mode=\'after\')\n    def validate_dates(self) -> \'FiscalYearBase\':\n        """Validate that end date is after start date"""\n        if self.end_date <= self.start_date:\n            raise ValueError(\'End date must be after start date\')\n        return self\n\n\nclass FiscalYearCreate(FiscalYearBase):\n    """Schema for creating a fiscal year"""\n    auto_create_periods: bool = Field(default=True, description="Auto-create monthly periods")\n    adjust_periods: Optional[List[Dict[str, Any]]] = None\n\n\nclass FiscalYearUpdate(BaseResponseModel):\n    """Schema for updating a fiscal year"""\n    name: Optional[str] = Field(None, min_length=1, max_length=100)\n    description: Optional[str] = Field(None, max_length=2000)\n    status: Optional[FiscalYearStatus] = None\n\n\nclass FiscalYearResponse(FiscalYearBase, TimestampMixin, IDMixin):\n    """Schema for fiscal year response"""\n    status: FiscalYearStatus = Field(default=FiscalYearStatus.OPEN)\n    is_current: bool = Field(default=False, description="Is current fiscal year")\n    period_count: int = Field(default=0, description="Number of periods")\n    closed_periods: int = Field(default=0, description="Number of closed periods")\n    \n    class Config:\n        from_attributes = True\n\n\nclass FiscalPeriodBase(BaseResponseModel):\n    """Base schema for fiscal period"""\n    name: str = Field(..., min_length=1, max_length=100, description="Period name")\n    period_number: int = Field(..., ge=1, le=53, description="Period number")\n    period_type: FiscalPeriodType = Field(default=FiscalPeriodType.MONTH)\n    start_date: date = Field(..., description="Start date")\n    end_date: date = Field(..., description="End date")\n    fiscal_year_id: UUID = Field(..., description="Fiscal year ID")\n    company_id: UUID = Field(..., description="Company ID")\n    description: Optional[str] = Field(None, max_length=2000)\n\n\nclass FiscalPeriodCreate(FiscalPeriodBase):\n    """Schema for creating a fiscal period"""\n    pass\n\n\nclass FiscalPeriodUpdate(BaseResponseModel):\n    """Schema for updating a fiscal period"""\n    name: Optional[str] = Field(None, min_length=1, max_length=100)\n    description: Optional[str] = Field(None, max_length=2000)\n    status: Optional[FiscalPeriodStatus] = None\n\n\nclass FiscalPeriodResponse(FiscalPeriodBase, TimestampMixin, IDMixin):\n    """Schema for fiscal period response"""\n    status: FiscalPeriodStatus = Field(default=FiscalPeriodStatus.OPEN)\n    is_current: bool = Field(default=False, description="Is current period")\n    is_adjusting: bool = Field(default=False, description="Is adjusting period")\n    \n    # Statistics\n    entry_count: int = Field(default=0)\n    total_debits: Decimal = Field(default=Decimal("0"))\n    total_credits: Decimal = Field(default=Decimal("0"))\n    \n    class Config:\n        from_attributes = True\n\n\n# ============================================\n# Account Balance Schemas\n# ============================================\n\nclass AccountBalanceBase(BaseResponseModel):\n    """Base schema for account balance"""\n    account_id: UUID = Field(..., description="Account ID")\n    fiscal_year_id: UUID = Field(..., description="Fiscal year ID")\n    fiscal_period_id: Optional[UUID] = Field(None, description="Fiscal period ID")\n    company_id: UUID = Field(..., description="Company ID")\n    \n    currency: str = Field(default="USD", min_length=3, max_length=3)\n    \n    opening_balance: Decimal = Field(default=Decimal("0"))\n    period_debit: Decimal = Field(default=Decimal("0"))\n    period_credit: Decimal = Field(default=Decimal("0"))\n    closing_balance: Decimal = Field(default=Decimal("0"))\n    \n    # Year-to-date\n    ytd_debit: Decimal = Field(default=Decimal("0"))\n    ytd_credit: Decimal = Field(default=Decimal("0"))\n    \n    metadata: Optional[Dict[str, Any]] = None\n\n\nclass AccountBalanceResponse(AccountBalanceBase, TimestampMixin, IDMixin):\n    """Schema for account balance response"""\n    account_code: str = Field(default="")\n    account_name: str = Field(default="")\n    \n    class Config:\n        from_attributes = True\n\n\nclass TrialBalanceLine(BaseResponseModel):\n    """Schema for trial balance line"""\n    account_id: UUID\n    account_code: str\n    account_name: str\n    account_type: AccountType\n    opening_debit: Decimal = Decimal("0")\n    opening_credit: Decimal = Decimal("0")\n    period_debit: Decimal = Decimal("0")\n    period_credit: Decimal = Decimal("0")\n    closing_debit: Decimal = Decimal("0")\n    closing_credit: Decimal = Decimal("0")\n\n\nclass TrialBalanceResponse(BaseResponseModel):\n    """Schema for trial balance"""\n    company_id: UUID\n    company_name: str\n    as_of_date: date\n    currency: str\n    \n    fiscal_year_id: UUID\n    fiscal_year_name: str\n    fiscal_period_id: Optional[UUID]\n    fiscal_period_name: Optional[str]\n    \n    lines: List[TrialBalanceLine] = Field(default_factory=list)\n    \n    # Totals\n    total_opening_debit: Decimal = Decimal("0")\n    total_opening_credit: Decimal = Decimal("0")\n    total_period_debit: Decimal = Decimal("0")\n    total_period_credit: Decimal = Decimal("0")\n    total_closing_debit: Decimal = Decimal("0")\n    total_closing_credit: Decimal = Decimal("0")\n    \n    is_balanced: bool = True\n    generated_at: datetime\n\n\n# ============================================\n# Budget Schemas\n# ============================================\n\nclass BudgetLineBase(BaseResponseModel):\n    """Base schema for budget line"""\n    account_id: UUID = Field(..., description="Account ID")\n    department_id: Optional[UUID] = None\n    project_id: Optional[UUID] = None\n    \n    # Budget amounts by period\n    period_amounts: Dict[str, Decimal] = Field(default_factory=dict, description="Amounts keyed by period")\n    \n    # Totals\n    annual_amount: Decimal = Field(default=Decimal("0"), description="Annual budget amount")\n    \n    # Variance analysis\n    variance_threshold: Optional[Decimal] = Field(None, description="Alert threshold")\n    \n    notes: Optional[str] = Field(None, max_length=2000)\n\n\nclass BudgetLineCreate(BudgetLineBase):\n    """Schema for creating a budget line"""\n    pass\n\n\nclass BudgetLineUpdate(BaseResponseModel):\n    """Schema for updating a budget line"""\n    period_amounts: Optional[Dict[str, Decimal]] = None\n    annual_amount: Optional[Decimal] = None\n    variance_threshold: Optional[Decimal] = None\n    notes: Optional[str] = Field(None, max_length=2000)\n\n\nclass BudgetLineResponse(BudgetLineBase, TimestampMixin, IDMixin):\n    """Schema for budget line response"""\n    budget_id: UUID\n    account_code: str = Field(default="")\n    account_name: str = Field(default="")\n    \n    # Actuals\n    actual_amount: Decimal = Field(default=Decimal("0"), description="Actual amount")\n    variance: Decimal = Field(default=Decimal("0"), description="Variance (budget - actual)")\n    variance_percent: Decimal = Field(default=Decimal("0"), description="Variance percentage")\n    \n    class Config:\n        from_attributes = True\n\n\nclass BudgetBase(BaseResponseModel):\n    """Base schema for budget"""\n    name: str = Field(..., min_length=1, max_length=200, description="Budget name")\n    code: str = Field(..., min_length=1, max_length=50, description="Budget code")\n    description: Optional[str] = Field(None, max_length=2000)\n    \n    company_id: UUID = Field(..., description="Company ID")\n    fiscal_year_id: UUID = Field(..., description="Fiscal year ID")\n    \n    budget_type: BudgetType = Field(default=BudgetType.ANNUAL, description="Budget type")\n    \n    # Dates\n    start_date: date = Field(..., description="Budget start date")\n    end_date: date = Field(..., description="Budget end date")\n    \n    # Currency\n    currency: str = Field(default="USD", min_length=3, max_length=3)\n    \n    # Approval\n    approved_by: Optional[UUID] = None\n    approved_at: Optional[datetime] = None\n    \n    metadata: Optional[Dict[str, Any]] = None\n\n\nclass BudgetCreate(BudgetBase):\n    """Schema for creating a budget"""\n    lines: List[BudgetLineCreate] = Field(default_factory=list)\n    copy_from_budget_id: Optional[UUID] = Field(None, description="Copy from existing budget")\n    adjust_percentage: Optional[Decimal] = Field(None, description="Adjust all amounts by percentage")\n\n\nclass BudgetUpdate(BaseResponseModel):\n    """Schema for updating a budget"""\n    name: Optional[str] = Field(None, min_length=1, max_length=200)\n    description: Optional[str] = Field(None, max_length=2000)\n    status: Optional[BudgetStatus] = None\n    lines: Optional[List[BudgetLineCreate]] = None\n\n\nclass BudgetResponse(BudgetBase, TimestampMixin, IDMixin):\n    """Schema for budget response"""\n    status: BudgetStatus = Field(default=BudgetStatus.DRAFT)\n    \n    # Totals\n    total_budget: Decimal = Field(default=Decimal("0"))\n    total_actual: Decimal = Field(default=Decimal("0"))\n    total_variance: Decimal = Field(default=Decimal("0"))\n    \n    line_count: int = Field(default=0)\n    \n    # Relationships\n    lines: List[BudgetLineResponse] = Field(default_factory=list)\n    \n    class Config:\n        from_attributes = True\n\n\nclass BudgetListResponse(BaseResponseModel):\n    """Schema for budget list item"""\n    id: UUID\n    name: str\n    code: str\n    company_id: UUID\n    fiscal_year_id: UUID\n    budget_type: BudgetType\n    status: BudgetStatus\n    total_budget: Decimal\n    start_date: date\n    end_date: date\n    created_at: datetime\n    \n    class Config:\n        from_attributes = True\n\n\nclass BudgetComparisonResponse(BaseResponseModel):\n    """Schema for budget vs actual comparison"""\n    budget: BudgetResponse\n    comparison_date: date\n    period_type: str\n    \n    # Summary\n    total_budget: Decimal\n    total_actual: Decimal\n    total_variance: Decimal\n    variance_percent: Decimal\n    \n    # By account type\n    by_account_type: Dict[str, Dict[str, Decimal]] = Field(default_factory=dict)\n    \n    # Alert accounts (exceeding threshold)\n    alerts: List[Dict[str, Any]] = Field(default_factory=list)\n\n\n# ============================================\n# Query Parameters\n# ============================================\n\nclass AccountFilterParams(PaginationParams):\n    """Filter parameters for account queries"""\n    code: Optional[str] = None\n    name: Optional[str] = None\n    account_type: Optional[List[AccountType]] = None\n    account_sub_type: Optional[List[AccountSubType]] = None\n    company_id: Optional[UUID] = None\n    parent_account_id: Optional[UUID] = None\n    is_header: Optional[bool] = None\n    is_active: Optional[bool] = None\n    status: Optional[List[AccountStatus]] = None\n    currency: Optional[str] = None\n    search: Optional[str] = None\n    tags: Optional[List[str]] = None\n\n\nclass JournalEntryFilterParams(PaginationParams):\n    """Filter parameters for journal entry queries"""\n    entry_number: Optional[str] = None\n    entry_date: Optional[date] = None\n    entry_date_from: Optional[date] = None\n    entry_date_to: Optional[date] = None\n    entry_type: Optional[List[JournalEntryType]] = None\n    status: Optional[List[JournalEntryStatus]] = None\n    company_id: Optional[UUID] = None\n    fiscal_year_id: Optional[UUID] = None\n    fiscal_period_id: Optional[UUID] = None\n    account_id: Optional[UUID] = None\n    source_type: Optional[str] = None\n    source_id: Optional[UUID] = None\n    amount_min: Optional[Decimal] = None\n    amount_max: Optional[Decimal] = None\n    created_by: Optional[UUID] = None\n    approved_by: Optional[UUID] = None\n    search: Optional[str] = None\n    tags: Optional[List[str]] = None\n\n\nclass FiscalYearFilterParams(PaginationParams):\n    """Filter parameters for fiscal year queries"""\n    name: Optional[str] = None\n    code: Optional[str] = None\n    company_id: Optional[UUID] = None\n    status: Optional[List[FiscalYearStatus]] = None\n    is_current: Optional[bool] = None\n    start_date_from: Optional[date] = None\n    start_date_to: Optional[date] = None\n\n\nclass BudgetFilterParams(PaginationParams):\n    """Filter parameters for budget queries"""\n    name: Optional[str] = None\n    code: Optional[str] = None\n    company_id: Optional[UUID] = None\n    fiscal_year_id: Optional[UUID] = None\n    budget_type: Optional[List[BudgetType]] = None\n    status: Optional[List[BudgetStatus]] = None\n    search: Optional[str] = None\n\n\n# ============================================\n# Bulk Operations\n# ============================================\n\nclass AccountBulkCreate(BaseResponseModel):\n    """Schema for bulk creating accounts"""\n    accounts: List[AccountCreate] = Field(..., min_length=1, max_length=500)\n\n\nclass JournalEntryBulkCreate(BaseResponseModel):\n    """Schema for bulk creating journal entries"""\n    entries: List[JournalEntryCreate] = Field(..., min_length=1, max_length=100)\n\n\nclass JournalEntryBulkPost(BaseResponseModel):\n    """Schema for bulk posting journal entries"""\n    ids: List[UUID] = Field(..., min_length=1)\n\n\nclass JournalEntryBulkVoid(BaseResponseModel):\n    """Schema for bulk voiding journal entries"""\n    ids: List[UUID] = Field(..., min_length=1)\n    reason: str = Field(..., min_length=1, max_length=500)\n\n\n# ============================================\n# Financial Statements\n# ============================================\n\nclass FinancialStatementType(str, Enum):\n    """Financial statement type enumeration"""\n    BALANCE_SHEET = "balance_sheet"\n    INCOME_STATEMENT = "income_statement"\n    CASH_FLOW = "cash_flow"\n    STATEMENT_OF_CHANGES_IN_EQUITY = "statement_of_changes_in_equity"\n    TRIAL_BALANCE = "trial_balance"\n    GENERAL_LEDGER = "general_ledger"\n\n\nclass FinancialStatementRequest(BaseResponseModel):\n    """Schema for financial statement request"""\n    statement_type: FinancialStatementType\n    company_id: UUID\n    as_of_date: Optional[date] = None\n    from_date: Optional[date] = None\n    to_date: Optional[date] = None\n    \n    # Comparison\n    comparison_type: Optional[str] = Field(None, description="period, budget, prior_year")\n    comparison_periods: int = Field(default=0, description="Number of comparison periods")\n    \n    # Format\n    currency: str = Field(default="USD")\n    include_zero_balances: bool = Field(default=False)\n    show_details: bool = Field(default=True)\n    \n    # Output\n    output_format: str = Field(default="json", description="json, pdf, excel")\n\n\nclass FinancialStatementResponse(BaseResponseModel):\n    """Schema for financial statement response"""\n    statement_type: FinancialStatementType\n    company_id: UUID\n    company_name: str\n    as_of_date: Optional[date]\n    from_date: Optional[date]\n    to_date: Optional[date]\n    currency: str\n    generated_at: datetime\n    \n    headers: List[str] = Field(default_factory=list)\n    rows: List[Dict[str, Any]] = Field(default_factory=list)\n    totals: Dict[str, Decimal] = Field(default_factory=dict)\n    \n    # PDF/Excel export\n    file_url: Optional[str] = None\n    file_format: Optional[str] = None\n\n\n# Update forward references\nAccountResponse.model_rebuild()\nAccountTreeResponse.model_rebuild()\nJournalEntryResponse.model_rebuild()\nBudgetResponse.model_rebuild()\n</create-file>\n</function_calls>'}
{'role': 'user', 'content': '<tool_result> <create-file> ToolResult(success=True, output="File \'backend/app/schemas/accounting.py\' created successfully.") </create-file> </tool_result>'}
{'role': 'assistant', 'content': 'Now let me create the Treasury schemas for banking and cash management:\n\n\n<function_calls><create-file file_path="backend/app/schemas/treasury.py">"""\nTreasury & Banking Schemas for SAMMS ENTERPRISE SOVEREIGN OPERATING SYSTEM\nBank accounts, transactions, reconciliations, and cash flow forecasting\n"""\nfrom datetime import datetime, date\nfrom typing import Optional, List, Dict, Any, Union\nfrom uuid import UUID\nfrom decimal import Decimal\nfrom enum import Enum\n\nfrom pydantic import Field, field_validator, model_validator\n\nfrom .base import (\n    BaseResponseModel,\n    PaginationParams,\n    PaginatedResponse,\n    SuccessResponse,\n    ErrorResponse,\n    TimestampMixin,\n    IDMixin,\n)\n\n\nclass BankAccountType(str, Enum):\n    """Bank account type enumeration"""\n    CHECKING = "checking"\n    SAVINGS = "savings"\n    MONEY_MARKET = "money_market"\n    CERTIFICATE_OF_DEPOSIT = "certificate_of_deposit"\n    CREDIT_LINE = "credit_line"\n    LOAN = "loan"\n    ESCROW = "escrow"\n    PAYROLL = "payroll"\n    OPERATING = "operating"\n    RESERVE = "reserve"\n    OTHER = "other"\n\n\nclass BankAccountStatus(str, Enum):\n    """Bank account status enumeration"""\n    ACTIVE = "active"\n    INACTIVE = "inactive"\n    CLOSED = "closed"\n    FROZEN = "frozen"\n    PENDING = "pending"\n    RESTRICTED = "restricted"\n\n\nclass TransactionType(str, Enum):\n    """Treasury transaction type enumeration"""\n    DEPOSIT = "deposit"\n    WITHDRAWAL = "withdrawal"\n    TRANSFER = "transfer"\n    PAYMENT = "payment"\n    RECEIPT = "receipt"\n    FEE = "fee"\n    INTEREST = "interest"\n    ADJUSTMENT = "adjustment"\n    VOID = "void"\n    REVERSAL = "reversal"\n    WIRE = "wire"\n    ACH = "ach"\n    CHECK = "check"\n    CARD = "card"\n    OTHER = "other"\n\n\nclass TransactionStatus(str, Enum):\n    """Transaction status enumeration"""\n    PENDING = "pending"\n    CLEARED = "cleared"\n    POSTED = "posted"\n    VOIDED = "voided"\n    RETURNED = "returned"\n    FAILED = "failed"\n    CANCELLED = "cancelled"\n    HOLD = "hold"\n\n\nclass ReconciliationStatus(str, Enum):\n    """Bank reconciliation status enumeration"""\n    DRAFT = "draft"\n    IN_PROGRESS = "in_progress"\n    COMPLETED = "completed"\n    APPROVED = "approved"\n    DISPUTED = "disputed"\n\n\nclass PaymentTermType(str, Enum):\n    """Payment term type enumeration"""\n    NET = "net"\n    END_OF_MONTH = "end_of_month"\n    FOLLOWING_MONTH = "following_month"\n    CASH_ON_DELIVERY = "cash_on_delivery"\n    PREPAID = "prepaid"\n    INSTALLMENT = "installment"\n    CUSTOM = "custom"\n\n\nclass CashFlowDirection(str, Enum):\n    """Cash flow direction enumeration"""\n    INFLOW = "inflow"\n    OUTFLOW = "outflow"\n    NET = "net"\n\n\nclass CashFlowCategory(str, Enum):\n    """Cash flow category enumeration"""\n    OPERATING = "operating"\n    INVESTING = "investing"\n    FINANCING = "financing"\n\n\n# ============================================\n# Bank Account Schemas\n# ============================================\n\nclass BankAccountBase(BaseResponseModel):\n    """Base schema for bank account"""\n    name: str = Field(..., min_length=1, max_length=200, description="Account name")\n    account_number: str = Field(..., min_length=1, max_length=50, description="Account number (masked)")\n    account_number_full: Optional[str] = Field(None, description="Full account number (encrypted)")\n    \n    # Bank details\n    bank_name: str = Field(..., min_length=1, max_length=200, description="Bank name")\n    bank_code: Optional[str] = Field(None, max_length=50, description="Bank code/Swift code")\n    branch_name: Optional[str] = Field(None, max_length=200, description="Branch name")\n    branch_code: Optional[str] = Field(None, max_length=50, description="Branch code")\n    \n    # Account classification\n    account_type: BankAccountType = Field(..., description="Account type")\n    currency: str = Field(default="USD", min_length=3, max_length=3, description="Account currency")\n    \n    # GL Integration\n    company_id: UUID = Field(..., description="Company ID")\n    gl_account_id: UUID = Field(..., description="Associated GL account")\n    \n    # Balance info\n    current_balance: Decimal = Field(default=Decimal("0"), description="Current balance")\n    available_balance: Decimal = Field(default=Decimal("0"), description="Available balance")\n    last_reconciled_date: Optional[date] = None\n    last_reconciled_balance: Optional[Decimal] = None\n    \n    # Limits\n    credit_limit: Optional[Decimal] = Field(None, description="Credit limit for credit lines")\n    minimum_balance: Optional[Decimal] = Field(None, description="Minimum required balance")\n    overdraft_limit: Optional[Decimal] = Field(None, description="Overdraft limit")\n    \n    # Interest\n    interest_rate: Optional[Decimal] = Field(None, description="Interest rate (percentage)")\n    interest_bearing: bool = Field(default=False, description="Whether account earns interest")\n    \n    # Additional info\n    open_date: Optional[date] = Field(None, description="Account open date")\n    close_date: Optional[date] = None\n    description: Optional[str] = Field(None, max_length=2000)\n    \n    # Contact\n    contact_name: Optional[str] = Field(None, max_length=200)\n    contact_phone: Optional[str] = Field(None, max_length=50)\n    contact_email: Optional[str] = Field(None, max_length=200)\n    \n    # Settings\n    is_primary: bool = Field(default=False, description="Primary account for company")\n    allow_negative: bool = Field(default=False, description="Allow negative balance")\n    auto_reconcile: bool = Field(default=False, description="Enable auto reconciliation")\n    \n    metadata: Optional[Dict[str, Any]] = None\n\n\nclass BankAccountCreate(BankAccountBase):\n    """Schema for creating a bank account"""\n    opening_balance: Optional[Decimal] = Field(None, description="Opening balance")\n    opening_balance_date: Optional[date] = Field(None, description="Opening balance date")\n\n\nclass BankAccountUpdate(BaseResponseModel):\n    """Schema for updating a bank account"""\n    name: Optional[str] = Field(None, min_length=1, max_length=200)\n    account_number: Optional[str] = Field(None, min_length=1, max_length=50)\n    bank_name: Optional[str] = Field(None, min_length=1, max_length=200)\n    bank_code: Optional[str] = Field(None, max_length=50)\n    branch_name: Optional[str] = Field(None, max_length=200)\n    branch_code: Optional[str] = Field(None, max_length=50)\n    account_type: Optional[BankAccountType] = None\n    currency: Optional[str] = Field(None, min_length=3, max_length=3)\n    gl_account_id: Optional[UUID] = None\n    credit_limit: Optional[Decimal] = None\n    minimum_balance: Optional[Decimal] = None\n    overdraft_limit: Optional[Decimal] = None\n    interest_rate: Optional[Decimal] = None\n    interest_bearing: Optional[bool] = None\n    close_date: Optional[date] = None\n    description: Optional[str] = Field(None, max_length=2000)\n    contact_name: Optional[str] = Field(None, max_length=200)\n    contact_phone: Optional[str] = Field(None, max_length=50)\n    contact_email: Optional[str] = Field(None, max_length=200)\n    is_primary: Optional[bool] = None\n    allow_negative: Optional[bool] = None\n    auto_reconcile: Optional[bool] = None\n    metadata: Optional[Dict[str, Any]] = None\n    status: Optional[BankAccountStatus] = None\n\n\nclass BankAccountResponse(BankAccountBase, TimestampMixin, IDMixin):\n    """Schema for bank account response"""\n    status: BankAccountStatus = Field(default=BankAccountStatus.ACTIVE)\n    is_active: bool = Field(default=True)\n    \n    # Statistics\n    transaction_count: int = Field(default=0, description="Number of transactions")\n    pending_transactions: int = Field(default=0, description="Pending transactions")\n    \n    class Config:\n        from_attributes = True\n\n\nclass BankAccountListResponse(BaseResponseModel):\n    """Schema for bank account list item"""\n    id: UUID\n    name: str\n    account_number: str\n    bank_name: str\n    account_type: BankAccountType\n    currency: str\n    current_balance: Decimal\n    available_balance: Decimal\n    company_id: UUID\n    status: BankAccountStatus\n    is_primary: bool\n    created_at: datetime\n    \n    class Config:\n        from_attributes = True\n\n\n# ============================================\n# Treasury Transaction Schemas\n# ============================================\n\nclass TreasuryTransactionBase(BaseResponseModel):\n    """Base schema for treasury transaction"""\n    transaction_date: date = Field(..., description="Transaction date")\n    value_date: Optional[date] = Field(None, description="Value/effective date")\n    \n    # Account\n    bank_account_id: UUID = Field(..., description="Bank account ID")\n    company_id: UUID = Field(..., description="Company ID")\n    \n    # Transaction details\n    transaction_type: TransactionType = Field(..., description="Transaction type")\n    amount: Decimal = Field(..., description="Transaction amount")\n    currency: str = Field(default="USD", min_length=3, max_length=3, description="Transaction currency")\n    \n    # Reference\n    reference: Optional[str] = Field(None, max_length=200, description="Bank reference")\n    internal_reference: Optional[str] = Field(None, max_length=200, description="Internal reference")\n    check_number: Optional[str] = Field(None, max_length=50, description="Check number")\n    \n    # Counterparty\n    counterparty_name: Optional[str] = Field(None, max_length=200)\n    counterparty_account: Optional[str] = Field(None, max_length=50)\n    counterparty_bank: Optional[str] = Field(None, max_length=200)\n    \n    # Description\n    description: Optional[str] = Field(None, max_length=2000)\n    memo: Optional[str] = Field(None, max_length=2000)\n    \n    # GL Integration\n    gl_account_id: Optional[UUID] = None\n    journal_entry_id: Optional[UUID] = None\n    \n    # Reconciliation\n    is_reconciled: bool = Field(default=False)\n    reconciled_date: Optional[date] = None\n    reconciliation_id: Optional[UUID] = None\n    \n    # Category\n    category: Optional[str] = Field(None, max_length=100)\n    sub_category: Optional[str] = Field(None, max_length=100)\n    cash_flow_category: Optional[CashFlowCategory] = None\n    \n    # Multi-currency\n    base_currency_amount: Optional[Decimal] = None\n    exchange_rate: Optional[Decimal] = None\n    \n    # Attachment\n    attachments: List[str] = Field(default_factory=list)\n    \n    metadata: Optional[Dict[str, Any]] = None\n    \n    @model_validator(mode=\'after\')\n    def validate_amount(self) -> \'TreasuryTransactionBase\':\n        """Validate transaction amount"""\n        if self.amount == 0:\n            raise ValueError(\'Transaction amount cannot be zero\')\n        return self\n\n\nclass TreasuryTransactionCreate(TreasuryTransactionBase):\n    """Schema for creating a treasury transaction"""\n    auto_post: bool = Field(default=False, description="Auto-post to GL")\n\n\nclass TreasuryTransactionUpdate(BaseResponseModel):\n    """Schema for updating a treasury transaction"""\n    transaction_date: Optional[date] = None\n    value_date: Optional[date] = None\n    transaction_type: Optional[TransactionType] = None\n    amount: Optional[Decimal] = None\n    currency: Optional[str] = Field(None, min_length=3, max_length=3)\n    reference: Optional[str] = Field(None, max_length=200)\n    internal_reference: Optional[str] = Field(None, max_length=200)\n    check_number: Optional[str] = Field(None, max_length=50)\n    counterparty_name: Optional[str] = Field(None, max_length=200)\n    counterparty_account: Optional[str] = Field(None, max_length=50)\n    counterparty_bank: Optional[str] = Field(None, max_length=200)\n    description: Optional[str] = Field(None, max_length=2000)\n    memo: Optional[str] = Field(None, max_length=2000)\n    gl_account_id: Optional[UUID] = None\n    category: Optional[str] = Field(None, max_length=100)\n    sub_category: Optional[str] = Field(None, max_length=100)\n    cash_flow_category: Optional[CashFlowCategory] = None\n    attachments: Optional[List[str]] = None\n    metadata: Optional[Dict[str, Any]] = None\n\n\nclass TreasuryTransactionResponse(TreasuryTransactionBase, TimestampMixin, IDMixin):\n    """Schema for treasury transaction response"""\n    transaction_number: str = Field(default="", description="System transaction number")\n    status: TransactionStatus = Field(default=TransactionStatus.PENDING)\n    \n    # Balance after transaction\n    running_balance: Optional[Decimal] = None\n    \n    # Audit\n    posted_by: Optional[UUID] = None\n    posted_at: Optional[datetime] = None\n    created_by: Optional[UUID] = None\n    \n    class Config:\n        from_attributes = True\n\n\nclass TreasuryTransactionListResponse(BaseResponseModel):\n    """Schema for transaction list item"""\n    id: UUID\n    transaction_number: str\n    transaction_date: date\n    transaction_type: TransactionType\n    amount: Decimal\n    currency: str\n    bank_account_id: UUID\n    bank_account_name: str\n    counterparty_name: Optional[str]\n    description: Optional[str]\n    is_reconciled: bool\n    status: TransactionStatus\n    created_at: datetime\n    \n    class Config:\n        from_attributes = True\n\n\n# ============================================\n# Bank Reconciliation Schemas\n# ============================================\n\nclass BankReconciliationLineBase(BaseResponseModel):\n    """Base schema for bank reconciliation line"""\n    transaction_id: Optional[UUID] = Field(None, description="Bank transaction ID")\n    \n    # Statement details\n    statement_date: date = Field(..., description="Statement date")\n    statement_amount: Decimal = Field(..., description="Amount per bank statement")\n    statement_reference: Optional[str] = Field(None, max_length=200)\n    \n    # Match details\n    is_matched: bool = Field(default=False)\n    matched_transaction_id: Optional[UUID] = None\n    match_type: Optional[str] = Field(None, description="exact, tolerance, manual")\n    match_confidence: Optional[Decimal] = None\n    \n    # Difference\n    difference: Decimal = Field(default=Decimal("0"))\n    difference_reason: Optional[str] = Field(None, max_length=2000)\n    \n    # Adjustment\n    is_adjustment: bool = Field(default=False)\n    adjustment_journal_entry_id: Optional[UUID] = None\n\n\nclass BankReconciliationLineCreate(BankReconciliationLineBase):\n    """Schema for creating reconciliation line"""\n    pass\n\n\nclass BankReconciliationLineResponse(BankReconciliationLineBase, TimestampMixin, IDMixin):\n    """Schema for reconciliation line response"""\n    reconciliation_id: UUID\n    \n    class Config:\n        from_attributes = True\n\n\nclass BankReconciliationBase(BaseResponseModel):\n    """Base schema for bank reconciliation"""\n    bank_account_id: UUID = Field(..., description="Bank account ID")\n    company_id: UUID = Field(..., description="Company ID")\n    \n    statement_date: date = Field(..., description="Bank statement date")\n    statement_number: Optional[str] = Field(None, max_length=50)\n    \n    # Balances\n    opening_balance: Decimal = Field(..., description="Opening balance per books")\n    statement_ending_balance: Decimal = Field(..., description="Ending balance per bank")\n    \n    # Summary\n    total_deposits: Decimal = Field(default=Decimal("0"))\n    total_withdrawals: Decimal = Field(default=Decimal("0"))\n    total_interest: Decimal = Field(default=Decimal("0"))\n    total_fees: Decimal = Field(default=Decimal("0"))\n    total_adjustments: Decimal = Field(default=Decimal("0"))\n    \n    # Calculated\n    calculated_book_balance: Optional[Decimal] = None\n    difference: Decimal = Field(default=Decimal("0"))\n    \n    # Status\n    notes: Optional[str] = Field(None, max_length=5000)\n    \n    metadata: Optional[Dict[str, Any]] = None\n\n\nclass BankReconciliationCreate(BankReconciliationBase):\n    """Schema for creating bank reconciliation"""\n    lines: List[BankReconciliationLineCreate] = Field(default_factory=list)\n    auto_match: bool = Field(default=True, description="Auto-match transactions")\n\n\nclass BankReconciliationUpdate(BaseResponseModel):\n    """Schema for updating bank reconciliation"""\n    statement_number: Optional[str] = Field(None, max_length=50)\n    statement_ending_balance: Optional[Decimal] = None\n    total_deposits: Optional[Decimal] = None\n    total_withdrawals: Optional[Decimal] = None\n    total_interest: Optional[Decimal] = None\n    total_fees: Optional[Decimal] = None\n    total_adjustments: Optional[Decimal] = None\n    notes: Optional[str] = Field(None, max_length=5000)\n    metadata: Optional[Dict[str, Any]] = None\n    status: Optional[ReconciliationStatus] = None\n\n\nclass BankReconciliationResponse(BankReconciliationBase, TimestampMixin, IDMixin):\n    """Schema for bank reconciliation response"""\n    status: ReconciliationStatus = Field(default=ReconciliationStatus.DRAFT)\n    \n    # Match statistics\n    total_items: int = Field(default=0)\n    matched_items: int = Field(default=0)\n    unmatched_items: int = Field(default=0)\n    \n    # Approval\n    approved_by: Optional[UUID] = None\n    approved_at: Optional[datetime] = None\n    \n    # Relationships\n    lines: List[BankReconciliationLineResponse] = Field(default_factory=list)\n    \n    class Config:\n        from_attributes = True\n\n\nclass BankReconciliationListResponse(BaseResponseModel):\n    """Schema for reconciliation list item"""\n    id: UUID\n    bank_account_id: UUID\n    bank_account_name: str\n    statement_date: date\n    statement_number: Optional[str]\n    statement_ending_balance: Decimal\n    difference: Decimal\n    status: ReconciliationStatus\n    matched_items: int\n    unmatched_items: int\n    created_at: datetime\n    \n    class Config:\n        from_attributes = True\n\n\n# ============================================\n# Cash Flow Forecast Schemas\n# ============================================\n\nclass CashFlowForecastLineBase(BaseResponseModel):\n    """Base schema for cash flow forecast line"""\n    forecast_date: date = Field(..., description="Forecast date")\n    \n    # Expected flows\n    expected_inflow: Decimal = Field(default=Decimal("0"))\n    expected_outflow: Decimal = Field(default=Decimal("0"))\n    net_flow: Decimal = Field(default=Decimal("0"))\n    \n    # Confidence\n    confidence_level: Decimal = Field(default=Decimal("0.5"), ge=0, le=1, description="Confidence level")\n    \n    # Source\n    source_type: Optional[str] = Field(None, max_length=100, description="invoice, payroll, recurring, manual")\n    source_id: Optional[UUID] = None\n    \n    # Category\n    category: Optional[CashFlowCategory] = None\n    sub_category: Optional[str] = Field(None, max_length=100)\n    description: Optional[str] = Field(None, max_length=500)\n    \n    # Bank account (optional)\n    bank_account_id: Optional[UUID] = None\n\n\nclass CashFlowForecastLineCreate(CashFlowForecastLineBase):\n    """Schema for creating forecast line"""\n    pass\n\n\nclass CashFlowForecastLineUpdate(BaseResponseModel):\n    """Schema for updating forecast line"""\n    expected_inflow: Optional[Decimal] = None\n    expected_outflow: Optional[Decimal] = None\n    confidence_level: Optional[Decimal] = Field(None, ge=0, le=1)\n    source_type: Optional[str] = Field(None, max_length=100)\n    source_id: Optional[UUID] = None\n    category: Optional[CashFlowCategory] = None\n    sub_category: Optional[str] = Field(None, max_length=100)\n    description: Optional[str] = Field(None, max_length=500)\n    bank_account_id: Optional[UUID] = None\n\n\nclass CashFlowForecastLineResponse(CashFlowForecastLineBase, TimestampMixin, IDMixin):\n    """Schema for forecast line response"""\n    forecast_id: UUID\n    running_balance: Decimal = Field(default=Decimal("0"))\n    \n    class Config:\n        from_attributes = True\n\n\nclass CashFlowForecastBase(BaseResponseModel):\n    """Base schema for cash flow forecast"""\n    name: str = Field(..., min_length=1, max_length=200)\n    description: Optional[str] = Field(None, max_length=2000)\n    \n    company_id: UUID = Field(..., description="Company ID")\n    \n    # Forecast period\n    start_date: date = Field(..., description="Forecast start date")\n    end_date: date = Field(..., description="Forecast end date")\n    \n    # Opening position\n    opening_balance: Decimal = Field(default=Decimal("0"))\n    \n    # Currency\n    currency: str = Field(default="USD", min_length=3, max_length=3)\n    \n    # Scenario\n    scenario: str = Field(default="baseline", description="baseline, optimistic, pessimistic")\n    \n    metadata: Optional[Dict[str, Any]] = None\n\n\nclass CashFlowForecastCreate(CashFlowForecastBase):\n    """Schema for creating cash flow forecast"""\n    lines: List[CashFlowForecastLineCreate] = Field(default_factory=list)\n    include_receivables: bool = Field(default=True, description="Include outstanding receivables")\n    include_payables: bool = Field(default=True, description="Include outstanding payables")\n    include_recurring: bool = Field(default=True, description="Include recurring items")\n\n\nclass CashFlowForecastUpdate(BaseResponseModel):\n    """Schema for updating cash flow forecast"""\n    name: Optional[str] = Field(None, min_length=1, max_length=200)\n    description: Optional[str] = Field(None, max_length=2000)\n    start_date: Optional[date] = None\n    end_date: Optional[date] = None\n    opening_balance: Optional[Decimal] = None\n    scenario: Optional[str] = None\n    metadata: Optional[Dict[str, Any]] = None\n    lines: Optional[List[CashFlowForecastLineCreate]] = None\n\n\nclass CashFlowForecastResponse(CashFlowForecastBase, TimestampMixin, IDMixin):\n    """Schema for cash flow forecast response"""\n    # Calculated totals\n    total_expected_inflow: Decimal = Field(default=Decimal("0"))\n    total_expected_outflow: Decimal = Field(default=Decimal("0"))\n    total_net_flow: Decimal = Field(default=Decimal("0"))\n    closing_balance: Decimal = Field(default=Decimal("0"))\n    \n    line_count: int = Field(default=0)\n    \n    # Minimum cash position\n    minimum_balance: Optional[Decimal] = Field(None, description="Minimum balance during period")\n    minimum_balance_date: Optional[date] = None\n    \n    # Relationships\n    lines: List[CashFlowForecastLineResponse] = Field(default_factory=list)\n    \n    class Config:\n        from_attributes = True\n\n\nclass CashFlowForecastListResponse(BaseResponseModel):\n    """Schema for forecast list item"""\n    id: UUID\n    name: str\n    company_id: UUID\n    start_date: date\n    end_date: date\n    scenario: str\n    opening_balance: Decimal\n    closing_balance: Decimal\n    total_net_flow: Decimal\n    created_at: datetime\n    \n    class Config:\n        from_attributes = True\n\n\n# ============================================\n# Payment Term Schemas\n# ============================================\n\nclass PaymentTermBase(BaseResponseModel):\n    """Base schema for payment terms"""\n    name: str = Field(..., min_length=1, max_length=100)\n    code: str = Field(..., min_length=1, max_length=20)\n    description: Optional[str] = Field(None, max_length=2000)\n    \n    company_id: Optional[UUID] = Field(None, description="Company ID (null for global)")\n    \n    # Term type\n    term_type: PaymentTermType = Field(default=PaymentTermType.NET)\n    \n    # Days\n    net_days: int = Field(default=30, ge=0)\n    discount_days: Optional[int] = Field(None, ge=0)\n    discount_percent: Optional[Decimal] = Field(None, ge=0, le=100)\n    \n    # Installment\n    installment_count: Optional[int] = Field(None, ge=1)\n    installment_interval: Optional[int] = Field(None, description="Days between installments")\n    \n    # Default\n    is_default: bool = Field(default=False)\n    is_active: bool = Field(default=True)\n\n\nclass PaymentTermCreate(PaymentTermBase):\n    """Schema for creating payment terms"""\n    pass\n\n\nclass PaymentTermUpdate(BaseResponseModel):\n    """Schema for updating payment terms"""\n    name: Optional[str] = Field(None, min_length=1, max_length=100)\n    description: Optional[str] = Field(None, max_length=2000)\n    term_type: Optional[PaymentTermType] = None\n    net_days: Optional[int] = Field(None, ge=0)\n    discount_days: Optional[int] = Field(None, ge=0)\n    discount_percent: Optional[Decimal] = Field(None, ge=0, le=100)\n    installment_count: Optional[int] = Field(None, ge=1)\n    installment_interval: Optional[int] = None\n    is_default: Optional[bool] = None\n    is_active: Optional[bool] = None\n\n\nclass PaymentTermResponse(PaymentTermBase, TimestampMixin, IDMixin):\n    """Schema for payment term response"""\n    usage_count: int = Field(default=0, description="Number of uses")\n    \n    class Config:\n        from_attributes = True\n\n\n# ============================================\n# Query Parameters\n# ============================================\n\nclass BankAccountFilterParams(PaginationParams):\n    """Filter parameters for bank account queries"""\n    name: Optional[str] = None\n    bank_name: Optional[str] = None\n    account_type: Optional[List[BankAccountType]] = None\n    status: Optional[List[BankAccountStatus]] = None\n    company_id: Optional[UUID] = None\n    currency: Optional[str] = None\n    is_primary: Optional[bool] = None\n    search: Optional[str] = None\n\n\nclass TreasuryTransactionFilterParams(PaginationParams):\n    """Filter parameters for treasury transaction queries"""\n    transaction_date: Optional[date] = None\n    transaction_date_from: Optional[date] = None\n    transaction_date_to: Optional[date] = None\n    transaction_type: Optional[List[TransactionType]] = None\n    status: Optional[List[TransactionStatus]] = None\n    bank_account_id: Optional[UUID] = None\n    company_id: Optional[UUID] = None\n    amount_min: Optional[Decimal] = None\n    amount_max: Optional[Decimal] = None\n    is_reconciled: Optional[bool] = None\n    counterparty_name: Optional[str] = None\n    reference: Optional[str] = None\n    search: Optional[str] = None\n\n\nclass BankReconciliationFilterParams(PaginationParams):\n    """Filter parameters for bank reconciliation queries"""\n    bank_account_id: Optional[UUID] = None\n    company_id: Optional[UUID] = None\n    statement_date_from: Optional[date] = None\n    statement_date_to: Optional[date] = None\n    status: Optional[List[ReconciliationStatus]] = None\n    has_difference: Optional[bool] = None\n\n\nclass CashFlowForecastFilterParams(PaginationParams):\n    """Filter parameters for cash flow forecast queries"""\n    company_id: Optional[UUID] = None\n    start_date_from: Optional[date] = None\n    start_date_to: Optional[date] = None\n    scenario: Optional[str] = None\n    search: Optional[str] = None\n\n\n# ============================================\n# Cash Position & Analytics\n# ============================================\n\nclass CashPositionResponse(BaseResponseModel):\n    """Schema for cash position summary"""\n    company_id: UUID\n    as_of_date: date\n    currency: str\n    \n    # Balances\n    total_cash: Decimal = Decimal("0")\n    total_available: Decimal = Decimal("0")\n    total_reserved: Decimal = Decimal("0")\n    total_in_transit: Decimal = Decimal("0")\n    \n    # By bank\n    by_bank: List[Dict[str, Any]] = Field(default_factory=list)\n    \n    # By currency\n    by_currency: Dict[str, Decimal] = Field(default_factory=dict)\n    \n    # By account type\n    by_account_type: Dict[str, Decimal] = Field(default_factory=dict)\n    \n    # Credit facilities\n    total_credit_available: Decimal = Decimal("0")\n    total_credit_used: Decimal = Decimal("0")\n    \n    generated_at: datetime\n\n\nclass CashFlowSummaryResponse(BaseResponseModel):\n    """Schema for cash flow summary"""\n    company_id: UUID\n    from_date: date\n    to_date: date\n    currency: str\n    \n    # By category\n    operating_inflow: Decimal = Decimal("0")\n    operating_outflow: Decimal = Decimal("0")\n    operating_net: Decimal = Decimal("0")\n    \n    investing_inflow: Decimal = Decimal("0")\n    investing_outflow: Decimal = Decimal("0")\n    investing_net: Decimal = Decimal("0")\n    \n    financing_inflow: Decimal = Decimal("0")\n    financing_outflow: Decimal = Decimal("0")\n    financing_net: Decimal = Decimal("0")\n    \n    total_inflow: Decimal = Decimal("0")\n    total_outflow: Decimal = Decimal("0")\n    net_change: Decimal = Decimal("0")\n    \n    # Top flows\n    top_inflows: List[Dict[str, Any]] = Field(default_factory=list)\n    top_outflows: List[Dict[str, Any]] = Field(default_factory=list)\n    \n    generated_at: datetime\n\n\n# Update forward references\nBankAccountResponse.model_rebuild()\nBankReconciliationResponse.model_rebuild()\nCashFlowForecastResponse.model_rebuild()\n</create-file>\n</function_calls>'}
{'role': 'user', 'content': '<tool_result> <create-file> ToolResult(success=True, output="File \'backend/app/schemas/treasury.py\' created successfully.") </create-file> </tool_result>'}
{'role': 'assistant', 'content': 'Let me continue creating the remaining schemas. Now I\'ll create the Invoice schemas for the Revenue & Billing module:\n\n\n<function_calls><create-file file_path="backend/app/schemas/invoice.py">"""\nInvoice & Revenue Schemas for SAMMS ENTERPRISE SOVEREIGN OPERATING SYSTEM\nContacts, Products, Invoices, Payments, Subscriptions, and Recurring Billing\n"""\nfrom datetime import datetime, date\nfrom typing import Optional, List, Dict, Any, Union\nfrom uuid import UUID\nfrom decimal import Decimal\nfrom enum import Enum\n\nfrom pydantic import Field, field_validator, model_validator\n\nfrom .base import (\n    BaseResponseModel,\n    PaginationParams,\n    PaginatedResponse,\n    SuccessResponse,\n    ErrorResponse,\n    Address,\n    ContactInfo,\n    TimestampMixin,\n    IDMixin,\n)\n\n\nclass ContactType(str, Enum):\n    """Contact type enumeration"""\n    CUSTOMER = "customer"\n    VENDOR = "vendor"\n    EMPLOYEE = "employee"\n    PARTNER = "partner"\n    CONTRACTOR = "contractor"\n    GOVERNMENT = "government"\n    OTHER = "other"\n\n\nclass ContactStatus(str, Enum):\n    """Contact status enumeration"""\n    ACTIVE = "active"\n    INACTIVE = "inactive"\n    PROSPECT = "prospect"\n    LEAD = "lead"\n    SUSPENDED = "suspended"\n    ARCHIVED = "archived"\n\n\nclass InvoiceStatus(str, Enum):\n    """Invoice status enumeration"""\n    DRAFT = "draft"\n    SENT = "sent"\n    VIEWED = "viewed"\n    PARTIAL = "partial"\n    PAID = "paid"\n    OVERDUE = "overdue"\n    CANCELLED = "cancelled"\n    VOID = "void"\n    REFUNDED = "refunded"\n    DISPUTED = "disputed"\n    WRITTEN_OFF = "written_off"\n\n\nclass InvoiceType(str, Enum):\n    """Invoice type enumeration"""\n    STANDARD = "standard"\n    PROFORMA = "proforma"\n    CREDIT_NOTE = "credit_note"\n    DEBIT_NOTE = "debit_note"\n    RECURRING = "recurring"\n    RETAINER = "retainer"\n    TIMESHEET = "timesheet"\n    MILESTONE = "milestone"\n    CONSOLIDATED = "consolidated"\n    INTERCOMPANY = "intercompany"\n\n\nclass ProductType(str, Enum):\n    """Product type enumeration"""\n    PRODUCT = "product"\n    SERVICE = "service"\n    DIGITAL = "digital"\n    SUBSCRIPTION = "subscription"\n    BUNDLE = "bundle"\n    MILESTONE = "milestone"\n    TIME = "time"\n    EXPENSE = "expense"\n    DISCOUNT = "discount"\n    OTHER = "other"\n\n\nclass PaymentStatus(str, Enum):\n    """Payment status enumeration"""\n    PENDING = "pending"\n    PROCESSING = "processing"\n    COMPLETED = "completed"\n    FAILED = "failed"\n    CANCELLED = "cancelled"\n    REFUNDED = "refunded"\n    PARTIALLY_REFUNDED = "partially_refunded"\n\n\nclass PaymentMethod(str, Enum):\n    """Payment method enumeration"""\n    CASH = "cash"\n    CHECK = "check"\n    BANK_TRANSFER = "bank_transfer"\n    ACH = "ach"\n    WIRE = "wire"\n    CREDIT_CARD = "credit_card"\n    DEBIT_CARD = "debit_card"\n    PAYPAL = "paypal"\n    OTHER = "other"\n\n\nclass SubscriptionStatus(str, Enum):\n    """Subscription status enumeration"""\n    ACTIVE = "active"\n    TRIAL = "trial"\n    PAST_DUE = "past_due"\n    CANCELLED = "cancelled"\n    EXPIRED = "expired"\n    SUSPENDED = "suspended"\n    PENDING = "pending"\n\n\nclass BillingCycle(str, Enum):\n    """Billing cycle enumeration"""\n    DAILY = "daily"\n    WEEKLY = "weekly"\n    BI_WEEKLY = "bi_weekly"\n    MONTHLY = "monthly"\n    QUARTERLY = "quarterly"\n    SEMI_ANNUALLY = "semi_annually"\n    ANNUALLY = "annually"\n    CUSTOM = "custom"\n\n\n# ============================================\n# Contact Schemas\n# ============================================\n\nclass ContactBase(BaseResponseModel):\n    """Base schema for contact"""\n    contact_type: ContactType = Field(..., description="Contact type")\n    \n    # Name/Company\n    is_company: bool = Field(default=False, description="Is a company/organization")\n    company_name: Optional[str] = Field(None, max_length=200)\n    first_name: Optional[str] = Field(None, max_length=100)\n    last_name: Optional[str] = Field(None, max_length=100)\n    display_name: str = Field(..., min_length=1, max_length=200)\n    \n    # Identification\n    contact_number: Optional[str] = Field(None, max_length=50, description="Customer/Vendor number")\n    tax_id: Optional[str] = Field(None, max_length=50)\n    registration_number: Optional[str] = Field(None, max_length=50)\n    \n    # Contact Information\n    email: Optional[str] = Field(None, max_length=200)\n    phone: Optional[str] = Field(None, max_length=50)\n    mobile: Optional[str] = Field(None, max_length=50)\n    fax: Optional[str] = Field(None, max_length=50)\n    website: Optional[str] = Field(None, max_length=500)\n    \n    # Address\n    billing_address: Optional[Address] = None\n    shipping_address: Optional[Address] = None\n    \n    # Company association\n    company_id: UUID = Field(..., description="Company ID")\n    \n    # Financial settings\n    currency: str = Field(default="USD", min_length=3, max_length=3)\n    payment_terms_id: Optional[UUID] = None\n    credit_limit: Optional[Decimal] = None\n    preferred_payment_method: Optional[PaymentMethod] = None\n    \n    # GL accounts\n    receivable_account_id: Optional[UUID] = None\n    payable_account_id: Optional[UUID] = None\n    revenue_account_id: Optional[UUID] = None\n    \n    # Tax\n    tax_exempt: bool = Field(default=False)\n    tax_code_id: Optional[UUID] = None\n    \n    # Additional info\n    notes: Optional[str] = Field(None, max_length=5000)\n    internal_notes: Optional[str] = Field(None, max_length=5000)\n    \n    # Primary contact\n    primary_contact_name: Optional[str] = Field(None, max_length=200)\n    primary_contact_email: Optional[str] = Field(None, max_length=200)\n    primary_contact_phone: Optional[str] = Field(None, max_length=50)\n    \n    # Parent (for hierarchy)\n    parent_contact_id: Optional[UUID] = None\n    \n    metadata: Optional[Dict[str, Any]] = None\n    tags: List[str] = Field(default_factory=list)\n\n\nclass ContactCreate(ContactBase):\n    """Schema for creating a contact"""\n    auto_generate_number: bool = Field(default=True, description="Auto-generate contact number")\n\n\nclass ContactUpdate(BaseResponseModel):\n    """Schema for updating a contact"""\n    contact_type: Optional[ContactType] = None\n    is_company: Optional[bool] = None\n    company_name: Optional[str] = Field(None, max_length=200)\n    first_name: Optional[str] = Field(None, max_length=100)\n    last_name: Optional[str] = Field(None, max_length=100)\n    display_name: Optional[str] = Field(None, min_length=1, max_length=200)\n    contact_number: Optional[str] = Field(None, max_length=50)\n    tax_id: Optional[str] = Field(None, max_length=50)\n    registration_number: Optional[str] = Field(None, max_length=50)\n    email: Optional[str] = Field(None, max_length=200)\n    phone: Optional[str] = Field(None, max_length=50)\n    mobile: Optional[str] = Field(None, max_length=50)\n    fax: Optional[str] = Field(None, max_length=50)\n    website: Optional[str] = Field(None, max_length=500)\n    billing_address: Optional[Address] = None\n    shipping_address: Optional[Address] = None\n    currency: Optional[str] = Field(None, min_length=3, max_length=3)\n    payment_terms_id: Optional[UUID] = None\n    credit_limit: Optional[Decimal] = None\n    preferred_payment_method: Optional[PaymentMethod] = None\n    receivable_account_id: Optional[UUID] = None\n    payable_account_id: Optional[UUID] = None\n    revenue_account_id: Optional[UUID] = None\n    tax_exempt: Optional[bool] = None\n    tax_code_id: Optional[UUID] = None\n    notes: Optional[str] = Field(None, max_length=5000)\n    internal_notes: Optional[str] = Field(None, max_length=5000)\n    primary_contact_name: Optional[str] = Field(None, max_length=200)\n    primary_contact_email: Optional[str] = Field(None, max_length=200)\n    primary_contact_phone: Optional[str] = Field(None, max_length=50)\n    parent_contact_id: Optional[UUID] = None\n    metadata: Optional[Dict[str, Any]] = None\n    tags: Optional[List[str]] = None\n    status: Optional[ContactStatus] = None\n\n\nclass ContactResponse(ContactBase, TimestampMixin, IDMixin):\n    """Schema for contact response"""\n    status: ContactStatus = Field(default=ContactStatus.ACTIVE)\n    is_active: bool = Field(default=True)\n    \n    # Statistics\n    total_revenue: Decimal = Field(default=Decimal("0"))\n    total_expenses: Decimal = Field(default=Decimal("0"))\n    outstanding_balance: Decimal = Field(default=Decimal("0"))\n    invoice_count: int = Field(default=0)\n    payment_count: int = Field(default=0)\n    \n    # Credit status\n    available_credit: Decimal = Field(default=Decimal("0"))\n    credit_used: Decimal = Field(default=Decimal("0"))\n    \n    class Config:\n        from_attributes = True\n\n\nclass ContactListResponse(BaseResponseModel):\n    """Schema for contact list item"""\n    id: UUID\n    contact_type: ContactType\n    display_name: str\n    company_name: Optional[str]\n    email: Optional[str]\n    phone: Optional[str]\n    currency: str\n    status: ContactStatus\n    company_id: UUID\n    outstanding_balance: Decimal\n    created_at: datetime\n    \n    class Config:\n        from_attributes = True\n\n\n# ============================================\n# Product Schemas\n# ============================================\n\nclass ProductBase(BaseResponseModel):\n    """Base schema for product/service"""\n    code: str = Field(..., min_length=1, max_length=50, description="Product code/SKU")\n    name: str = Field(..., min_length=1, max_length=200)\n    description: Optional[str] = Field(None, max_length=5000)\n    \n    # Type\n    product_type: ProductType = Field(default=ProductType.PRODUCT)\n    \n    # Company\n    company_id: UUID = Field(..., description="Company ID")\n    \n    # Pricing\n    unit_price: Decimal = Field(default=Decimal("0"), ge=0)\n    cost_price: Optional[Decimal] = Field(None, ge=0)\n    currency: str = Field(default="USD", min_length=3, max_length=3)\n    \n    # Unit\n    unit_of_measure: str = Field(default="EA", max_length=20)\n    unit_description: Optional[str] = Field(None, max_length=100)\n    \n    # Tax\n    is_taxable: bool = Field(default=True)\n    tax_code_id: Optional[UUID] = None\n    \n    # GL accounts\n    revenue_account_id: Optional[UUID] = None\n    cost_account_id: Optional[UUID] = None\n    inventory_account_id: Optional[UUID] = None\n    \n    # Inventory (for products)\n    track_inventory: bool = Field(default=False)\n    quantity_on_hand: Optional[Decimal] = None\n    reorder_point: Optional[Decimal] = None\n    preferred_vendor_id: Optional[UUID] = None\n    \n    # Subscription (for subscriptions)\n    billing_cycle: Optional[BillingCycle] = None\n    billing_interval: Optional[int] = None\n    \n    # Additional\n    image_url: Optional[str] = Field(None, max_length=1000)\n    category: Optional[str] = Field(None, max_length=100)\n    tags: List[str] = Field(default_factory=list)\n    \n    metadata: Optional[Dict[str, Any]] = None\n\n\nclass ProductCreate(ProductBase):\n    """Schema for creating a product"""\n    pass\n\n\nclass ProductUpdate(BaseResponseModel):\n    """Schema for updating a product"""\n    code: Optional[str] = Field(None, min_length=1, max_length=50)\n    name: Optional[str] = Field(None, min_length=1, max_length=200)\n    description: Optional[str] = Field(None, max_length=5000)\n    product_type: Optional[ProductType] = None\n    unit_price: Optional[Decimal] = Field(None, ge=0)\n    cost_price: Optional[Decimal] = Field(None, ge=0)\n    currency: Optional[str] = Field(None, min_length=3, max_length=3)\n    unit_of_measure: Optional[str] = Field(None, max_length=20)\n    unit_description: Optional[str] = Field(None, max_length=100)\n    is_taxable: Optional[bool] = None\n    tax_code_id: Optional[UUID] = None\n    revenue_account_id: Optional[UUID] = None\n    cost_account_id: Optional[UUID] = None\n    inventory_account_id: Optional[UUID] = None\n    track_inventory: Optional[bool] = None\n    quantity_on_hand: Optional[Decimal] = None\n    reorder_point: Optional[Decimal] = None\n    preferred_vendor_id: Optional[UUID] = None\n    billing_cycle: Optional[BillingCycle] = None\n    billing_interval: Optional[int] = None\n    image_url: Optional[str] = Field(None, max_length=1000)\n    category: Optional[str] = Field(None, max_length=100)\n    tags: Optional[List[str]] = None\n    metadata: Optional[Dict[str, Any]] = None\n    is_active: Optional[bool] = None\n\n\nclass ProductResponse(ProductBase, TimestampMixin, IDMixin):\n    """Schema for product response"""\n    is_active: bool = Field(default=True)\n    \n    # Statistics\n    total_sold: Decimal = Field(default=Decimal("0"))\n    total_revenue: Decimal = Field(default=Decimal("0"))\n    invoice_count: int = Field(default=0)\n    \n    class Config:\n        from_attributes = True\n\n\nclass ProductListResponse(BaseResponseModel):\n    """Schema for product list item"""\n    id: UUID\n    code: str\n    name: str\n    product_type: ProductType\n    unit_price: Decimal\n    currency: str\n    unit_of_measure: str\n    is_active: bool\n    company_id: UUID\n    created_at: datetime\n    \n    class Config:\n        from_attributes = True\n\n\n# ============================================\n# Invoice Schemas\n# ============================================\n\nclass InvoiceLineBase(BaseResponseModel):\n    """Base schema for invoice line"""\n    product_id: Optional[UUID] = Field(None, description="Product ID (if from catalog)")\n    \n    # Line details\n    description: str = Field(..., min_length=1, max_length=1000)\n    quantity: Decimal = Field(default=Decimal("1"), ge=0)\n    unit_price: Decimal = Field(default=Decimal("0"), ge=0)\n    unit_of_measure: Optional[str] = Field(None, max_length=20)\n    \n    # Discount\n    discount_type: Optional[str] = Field(None, description="percentage, fixed")\n    discount_value: Optional[Decimal] = Field(None, ge=0)\n    \n    # Tax\n    is_taxable: bool = Field(default=True)\n    tax_rate: Optional[Decimal] = Field(None, ge=0, le=100)\n    tax_amount: Optional[Decimal] = None\n    tax_code_id: Optional[UUID] = None\n    \n    # Account\n    account_id: Optional[UUID] = Field(None, description="Revenue account")\n    department_id: Optional[UUID] = None\n    project_id: Optional[UUID] = None\n    \n    # Dates\n    service_start_date: Optional[date] = None\n    service_end_date: Optional[date] = None\n    \n    # Calculated\n    subtotal: Decimal = Field(default=Decimal("0"))\n    total: Decimal = Field(default=Decimal("0"))\n    \n    metadata: Optional[Dict[str, Any]] = None\n    \n    @model_validator(mode=\'after\')\n    def calculate_totals(self) -> \'InvoiceLineBase\':\n        """Calculate line totals"""\n        self.subtotal = self.quantity * self.unit_price\n        if self.discount_type and self.discount_value:\n            if self.discount_type == "percentage":\n                self.subtotal = self.subtotal * (1 - self.discount_value / 100)\n            else:\n                self.subtotal = self.subtotal - self.discount_value\n        self.total = self.subtotal\n        if self.tax_rate and self.is_taxable:\n            self.tax_amount = self.subtotal * self.tax_rate / 100\n            self.total = self.subtotal + self.tax_amount\n        return self\n\n\nclass InvoiceLineCreate(InvoiceLineBase):\n    """Schema for creating invoice line"""\n    pass\n\n\nclass InvoiceLineUpdate(BaseResponseModel):\n    """Schema for updating invoice line"""\n    product_id: Optional[UUID] = None\n    description: Optional[str] = Field(None, min_length=1, max_length=1000)\n    quantity: Optional[Decimal] = Field(None, ge=0)\n    unit_price: Optional[Decimal] = Field(None, ge=0)\n    unit_of_measure: Optional[str] = Field(None, max_length=20)\n    discount_type: Optional[str] = None\n    discount_value: Optional[Decimal] = Field(None, ge=0)\n    is_taxable: Optional[bool] = None\n    tax_rate: Optional[Decimal] = Field(None, ge=0, le=100)\n    tax_code_id: Optional[UUID] = None\n    account_id: Optional[UUID] = None\n    department_id: Optional[UUID] = None\n    project_id: Optional[UUID] = None\n    service_start_date: Optional[date] = None\n    service_end_date: Optional[date] = None\n    metadata: Optional[Dict[str, Any]] = None\n\n\nclass InvoiceLineResponse(InvoiceLineBase, TimestampMixin, IDMixin):\n    """Schema for invoice line response"""\n    invoice_id: UUID\n    line_number: int = Field(default=0)\n    product_code: Optional[str] = None\n    product_name: Optional[str] = None\n    \n    class Config:\n        from_attributes = True\n\n\nclass InvoiceBase(BaseResponseModel):\n    """Base schema for invoice"""\n    invoice_number: Optional[str] = Field(None, max_length=50)\n    invoice_type: InvoiceType = Field(default=InvoiceType.STANDARD)\n    \n    # Contact\n    contact_id: UUID = Field(..., description="Customer/Vendor ID")\n    company_id: UUID = Field(..., description="Company ID")\n    \n    # Dates\n    invoice_date: date = Field(..., description="Invoice date")\n    due_date: date = Field(..., description="Due date")\n    service_start_date: Optional[date] = None\n    service_end_date: Optional[date] = None\n    \n    # Reference\n    purchase_order: Optional[str] = Field(None, max_length=100)\n    reference: Optional[str] = Field(None, max_length=200)\n    \n    # Currency\n    currency: str = Field(default="USD", min_length=3, max_length=3)\n    exchange_rate: Optional[Decimal] = None\n    \n    # Payment terms\n    payment_terms_id: Optional[UUID] = None\n    \n    # Addresses\n    billing_address: Optional[Address] = None\n    shipping_address: Optional[Address] = None\n    \n    # Notes\n    notes: Optional[str] = Field(None, max_length=5000)\n    terms: Optional[str] = Field(None, max_length=5000)\n    internal_notes: Optional[str] = Field(None, max_length=5000)\n    \n    # Discounts\n    discount_type: Optional[str] = None\n    discount_value: Optional[Decimal] = None\n    \n    # Tax\n    tax_inclusive: bool = Field(default=False)\n    \n    # GL\n    journal_entry_id: Optional[UUID] = None\n    \n    metadata: Optional[Dict[str, Any]] = None\n    tags: List[str] = Field(default_factory=list)\n    attachments: List[str] = Field(default_factory=list)\n\n\nclass InvoiceCreate(InvoiceBase):\n    """Schema for creating an invoice"""\n    lines: List[InvoiceLineCreate] = Field(..., min_length=1)\n    auto_generate_number: bool = Field(default=True)\n    calculate_due_date: bool = Field(default=True)\n    send_on_create: bool = Field(default=False)\n    \n    @model_validator(mode=\'after\')\n    def validate_due_date(self) -> \'InvoiceCreate\':\n        """Validate due date is after invoice date"""\n        if self.due_date < self.invoice_date:\n            raise ValueError(\'Due date must be on or after invoice date\')\n        return self\n\n\nclass InvoiceUpdate(BaseResponseModel):\n    """Schema for updating an invoice"""\n    invoice_number: Optional[str] = Field(None, max_length=50)\n    invoice_type: Optional[InvoiceType] = None\n    contact_id: Optional[UUID] = None\n    invoice_date: Optional[date] = None\n    due_date: Optional[date] = None\n    service_start_date: Optional[date] = None\n    service_end_date: Optional[date] = None\n    purchase_order: Optional[str] = Field(None, max_length=100)\n    reference: Optional[str] = Field(None, max_length=200)\n    currency: Optional[str] = Field(None, min_length=3, max_length=3)\n    exchange_rate: Optional[Decimal] = None\n    payment_terms_id: Optional[UUID] = None\n    billing_address: Optional[Address] = None\n    shipping_address: Optional[Address] = None\n    notes: Optional[str] = Field(None, max_length=5000)\n    terms: Optional[str] = Field(None, max_length=5000)\n    internal_notes: Optional[str] = Field(None, max_length=5000)\n    discount_type: Optional[str] = None\n    discount_value: Optional[Decimal] = None\n    tax_inclusive: Optional[bool] = None\n    metadata: Optional[Dict[str, Any]] = None\n    tags: Optional[List[str]] = None\n    attachments: Optional[List[str]] = None\n    lines: Optional[List[InvoiceLineCreate]] = None\n\n\nclass InvoiceResponse(InvoiceBase, TimestampMixin, IDMixin):\n    """Schema for invoice response"""\n    status: InvoiceStatus = Field(default=InvoiceStatus.DRAFT)\n    \n    # Calculated totals\n    subtotal: Decimal = Field(default=Decimal("0"))\n    total_discount: Decimal = Field(default=Decimal("0"))\n    total_tax: Decimal = Field(default=Decimal("0"))\n    total: Decimal = Field(default=Decimal("0"))\n    \n    # Payments\n    amount_paid: Decimal = Field(default=Decimal("0"))\n    amount_due: Decimal = Field(default=Decimal("0"))\n    \n    # Statistics\n    line_count: int = Field(default=0)\n    payment_count: int = Field(default=0)\n    \n    # Audit\n    sent_at: Optional[datetime] = None\n    viewed_at: Optional[datetime] = None\n    paid_at: Optional[datetime] = None\n    \n    # Relationships\n    lines: List[InvoiceLineResponse] = Field(default_factory=list)\n    \n    class Config:\n        from_attributes = True\n\n\nclass InvoiceListResponse(BaseResponseModel):\n    """Schema for invoice list item"""\n    id: UUID\n    invoice_number: str\n    invoice_type: InvoiceType\n    contact_id: UUID\n    contact_name: str\n    invoice_date: date\n    due_date: date\n    total: Decimal\n    amount_paid: Decimal\n    amount_due: Decimal\n    currency: str\n    status: InvoiceStatus\n    company_id: UUID\n    created_at: datetime\n    \n    class Config:\n        from_attributes = True\n\n\n# ============================================\n# Payment Schemas\n# ============================================\n\nclass PaymentBase(BaseResponseModel):\n    """Base schema for payment"""\n    payment_date: date = Field(..., description="Payment date")\n    \n    # Invoice association\n    invoice_id: Optional[UUID] = Field(None, description="Invoice being paid")\n    contact_id: UUID = Field(..., description="Customer/Vendor ID")\n    company_id: UUID = Field(..., description="Company ID")\n    \n    # Payment details\n    payment_method: PaymentMethod = Field(..., description="Payment method")\n    amount: Decimal = Field(..., gt=0, description="Payment amount")\n    currency: str = Field(default="USD", min_length=3, max_length=3)\n    \n    # Reference\n    reference: Optional[str] = Field(None, max_length=200)\n    transaction_id: Optional[str] = Field(None, max_length=200)\n    check_number: Optional[str] = Field(None, max_length=50)\n    \n    # Bank account\n    bank_account_id: Optional[UUID] = Field(None, description="Bank account for deposit")\n    \n    # Deposit\n    is_deposit: bool = Field(default=False, description="Is this a deposit?")\n    deposit_to: Optional[UUID] = Field(None, description="Deposit account")\n    \n    # GL\n    journal_entry_id: Optional[UUID] = None\n    \n    # Notes\n    notes: Optional[str] = Field(None, max_length=2000)\n    internal_notes: Optional[str] = Field(None, max_length=2000)\n    \n    metadata: Optional[Dict[str, Any]] = None\n    attachments: List[str] = Field(default_factory=list)\n\n\nclass PaymentCreate(PaymentBase):\n    """Schema for creating a payment"""\n    auto_post: bool = Field(default=True, description="Auto-post to GL")\n    send_receipt: bool = Field(default=True, description="Send receipt to customer")\n\n\nclass PaymentUpdate(BaseResponseModel):\n    """Schema for updating a payment"""\n    payment_date: Optional[date] = None\n    payment_method: Optional[PaymentMethod] = None\n    amount: Optional[Decimal] = Field(None, gt=0)\n    currency: Optional[str] = Field(None, min_length=3, max_length=3)\n    reference: Optional[str] = Field(None, max_length=200)\n    transaction_id: Optional[str] = Field(None, max_length=200)\n    check_number: Optional[str] = Field(None, max_length=50)\n    bank_account_id: Optional[UUID] = None\n    deposit_to: Optional[UUID] = None\n    notes: Optional[str] = Field(None, max_length=2000)\n    internal_notes: Optional[str] = Field(None, max_length=2000)\n    metadata: Optional[Dict[str, Any]] = None\n    attachments: Optional[List[str]] = None\n\n\nclass PaymentResponse(PaymentBase, TimestampMixin, IDMixin):\n    """Schema for payment response"""\n    payment_number: str = Field(default="")\n    status: PaymentStatus = Field(default=PaymentStatus.PENDING)\n    \n    # Calculated\n    amount_applied: Decimal = Field(default=Decimal("0"))\n    amount_unapplied: Decimal = Field(default=Decimal("0"))\n    \n    # Refund\n    refund_amount: Decimal = Field(default=Decimal("0"))\n    refunded_at: Optional[datetime] = None\n    \n    # Audit\n    processed_by: Optional[UUID] = None\n    processed_at: Optional[datetime] = None\n    \n    class Config:\n        from_attributes = True\n\n\nclass PaymentListResponse(BaseResponseModel):\n    """Schema for payment list item"""\n    id: UUID\n    payment_number: str\n    payment_date: date\n    contact_id: UUID\n    contact_name: str\n    payment_method: PaymentMethod\n    amount: Decimal\n    currency: str\n    status: PaymentStatus\n    company_id: UUID\n    created_at: datetime\n    \n    class Config:\n        from_attributes = True\n\n\n# ============================================\n# Subscription Schemas\n# ============================================\n\nclass SubscriptionBase(BaseResponseModel):\n    """Base schema for subscription"""\n    contact_id: UUID = Field(..., description="Customer ID")\n    company_id: UUID = Field(..., description="Company ID")\n    product_id: Optional[UUID] = Field(None, description="Product ID")\n    \n    # Subscription details\n    name: str = Field(..., min_length=1, max_length=200)\n    description: Optional[str] = Field(None, max_length=2000)\n    \n    # Billing\n    billing_cycle: BillingCycle = Field(..., description="Billing frequency")\n    billing_interval: int = Field(default=1, ge=1, description="Interval for billing cycle")\n    billing_day: Optional[int] = Field(None, ge=1, le=31, description="Day of month for billing")\n    \n    # Pricing\n    unit_price: Decimal = Field(..., ge=0)\n    quantity: Decimal = Field(default=Decimal("1"), ge=0)\n    currency: str = Field(default="USD", min_length=3, max_length=3)\n    \n    # Dates\n    start_date: date = Field(..., description="Subscription start date")\n    end_date: Optional[date] = Field(None, description="Subscription end date")\n    next_billing_date: Optional[date] = None\n    last_billing_date: Optional[date] = None\n    \n    # Trial\n    has_trial: bool = Field(default=False)\n    trial_end_date: Optional[date] = None\n    \n    # Auto-renewal\n    auto_renew: bool = Field(default=True)\n    renewal_term: Optional[int] = Field(None, description="Renewal term in months")\n    \n    # Invoice settings\n    payment_terms_id: Optional[UUID] = None\n    auto_charge: bool = Field(default=False)\n    payment_method_id: Optional[UUID] = None\n    \n    # Discounts\n    discount_percent: Optional[Decimal] = Field(None, ge=0, le=100)\n    \n    # GL\n    revenue_account_id: Optional[UUID] = None\n    receivable_account_id: Optional[UUID] = None\n    \n    notes: Optional[str] = Field(None, max_length=2000)\n    metadata: Optional[Dict[str, Any]] = None\n\n\nclass SubscriptionCreate(SubscriptionBase):\n    """Schema for creating a subscription"""\n    generate_first_invoice: bool = Field(default=True)\n\n\nclass SubscriptionUpdate(BaseResponseModel):\n    """Schema for updating a subscription"""\n    name: Optional[str] = Field(None, min_length=1, max_length=200)\n    description: Optional[str] = Field(None, max_length=2000)\n    billing_cycle: Optional[BillingCycle] = None\n    billing_interval: Optional[int] = Field(None, ge=1)\n    billing_day: Optional[int] = Field(None, ge=1, le=31)\n    unit_price: Optional[Decimal] = Field(None, ge=0)\n    quantity: Optional[Decimal] = Field(None, ge=0)\n    currency: Optional[str] = Field(None, min_length=3, max_length=3)\n    end_date: Optional[date] = None\n    auto_renew: Optional[bool] = None\n    renewal_term: Optional[int] = None\n    payment_terms_id: Optional[UUID] = None\n    auto_charge: Optional[bool] = None\n    payment_method_id: Optional[UUID] = None\n    discount_percent: Optional[Decimal] = Field(None, ge=0, le=100)\n    revenue_account_id: Optional[UUID] = None\n    receivable_account_id: Optional[UUID] = None\n    notes: Optional[str] = Field(None, max_length=2000)\n    metadata: Optional[Dict[str, Any]] = None\n    status: Optional[SubscriptionStatus] = None\n\n\nclass SubscriptionResponse(SubscriptionBase, TimestampMixin, IDMixin):\n    """Schema for subscription response"""\n    subscription_number: str = Field(default="")\n    status: SubscriptionStatus = Field(default=SubscriptionStatus.ACTIVE)\n    \n    # Calculated\n    monthly_value: Decimal = Field(default=Decimal("0"))\n    annual_value: Decimal = Field(default=Decimal("0"))\n    \n    # Statistics\n    total_invoiced: Decimal = Field(default=Decimal("0"))\n    total_paid: Decimal = Field(default=Decimal("0"))\n    invoice_count: int = Field(default=0)\n    \n    class Config:\n        from_attributes = True\n\n\nclass SubscriptionListResponse(BaseResponseModel):\n    """Schema for subscription list item"""\n    id: UUID\n    subscription_number: str\n    name: str\n    contact_id: UUID\n    contact_name: str\n    billing_cycle: BillingCycle\n    unit_price: Decimal\n    quantity: Decimal\n    currency: str\n    status: SubscriptionStatus\n    next_billing_date: Optional[date]\n    company_id: UUID\n    created_at: datetime\n    \n    class Config:\n        from_attributes = True\n\n\n# ============================================\n# Recurring Invoice Schemas\n# ============================================\n\nclass RecurringInvoiceBase(BaseResponseModel):\n    """Base schema for recurring invoice"""\n    name: str = Field(..., min_length=1, max_length=200)\n    description: Optional[str] = Field(None, max_length=2000)\n    \n    contact_id: UUID = Field(..., description="Customer ID")\n    company_id: UUID = Field(..., description="Company ID")\n    \n    # Schedule\n    frequency: BillingCycle = Field(..., description="Frequency")\n    interval: int = Field(default=1, ge=1)\n    day_of_month: Optional[int] = Field(None, ge=1, le=31)\n    day_of_week: Optional[int] = Field(None, ge=0, le=6)\n    \n    # Duration\n    start_date: date = Field(..., description="Start date")\n    end_date: Optional[date] = Field(None, description="End date")\n    max_occurrences: Optional[int] = Field(None, ge=1)\n    occurrences_count: int = Field(default=0)\n    \n    # Next generation\n    next_date: Optional[date] = None\n    last_date: Optional[date] = None\n    \n    # Invoice template\n    invoice_template: Dict[str, Any] = Field(default_factory=dict)\n    \n    # Settings\n    auto_send: bool = Field(default=False)\n    auto_charge: bool = Field(default=False)\n    \n    metadata: Optional[Dict[str, Any]] = None\n\n\nclass RecurringInvoiceCreate(RecurringInvoiceBase):\n    """Schema for creating recurring invoice"""\n    lines: List[InvoiceLineCreate] = Field(default_factory=list)\n\n\nclass RecurringInvoiceUpdate(BaseResponseModel):\n    """Schema for updating recurring invoice"""\n    name: Optional[str] = Field(None, min_length=1, max_length=200)\n    description: Optional[str] = Field(None, max_length=2000)\n    frequency: Optional[BillingCycle] = None\n    interval: Optional[int] = Field(None, ge=1)\n    day_of_month: Optional[int] = Field(None, ge=1, le=31)\n    day_of_week: Optional[int] = Field(None, ge=0, le=6)\n    start_date: Optional[date] = None\n    end_date: Optional[date] = None\n    max_occurrences: Optional[int] = Field(None, ge=1)\n    invoice_template: Optional[Dict[str, Any]] = None\n    auto_send: Optional[bool] = None\n    auto_charge: Optional[bool] = None\n    metadata: Optional[Dict[str, Any]] = None\n    lines: Optional[List[InvoiceLineCreate]] = None\n    is_active: Optional[bool] = None\n\n\nclass RecurringInvoiceResponse(RecurringInvoiceBase, TimestampMixin, IDMixin):\n    """Schema for recurring invoice response"""\n    is_active: bool = Field(default=True)\n    \n    # Statistics\n    total_generated: int = Field(default=0)\n    total_amount: Decimal = Field(default=Decimal("0"))\n    \n    class Config:\n        from_attributes = True\n\n\n# ============================================\n# Query Parameters\n# ============================================\n\nclass ContactFilterParams(PaginationParams):\n    """Filter parameters for contact queries"""\n    contact_type: Optional[List[ContactType]] = None\n    status: Optional[List[ContactStatus]] = None\n    company_id: Optional[UUID] = None\n    currency: Optional[str] = None\n    payment_terms_id: Optional[UUID] = None\n    has_outstanding: Optional[bool] = None\n    created_after: Optional[datetime] = None\n    created_before: Optional[datetime] = None\n    search: Optional[str] = None\n    tags: Optional[List[str]] = None\n\n\nclass ProductFilterParams(PaginationParams):\n    """Filter parameters for product queries"""\n    code: Optional[str] = None\n    name: Optional[str] = None\n    product_type: Optional[List[ProductType]] = None\n    company_id: Optional[UUID] = None\n    category: Optional[str] = None\n    is_active: Optional[bool] = None\n    is_taxable: Optional[bool] = None\n    track_inventory: Optional[bool] = None\n    below_reorder_point: Optional[bool] = None\n    search: Optional[str] = None\n    tags: Optional[List[str]] = None\n\n\nclass InvoiceFilterParams(PaginationParams):\n    """Filter parameters for invoice queries"""\n    invoice_number: Optional[str] = None\n    invoice_type: Optional[List[InvoiceType]] = None\n    status: Optional[List[InvoiceStatus]] = None\n    contact_id: Optional[UUID] = None\n    company_id: Optional[UUID] = None\n    invoice_date_from: Optional[date] = None\n    invoice_date_to: Optional[date] = None\n    due_date_from: Optional[date] = None\n    due_date_to: Optional[date] = None\n    currency: Optional[str] = None\n    amount_min: Optional[Decimal] = None\n    amount_max: Optional[Decimal] = None\n    overdue: Optional[bool] = None\n    has_payments: Optional[bool] = None\n    created_by: Optional[UUID] = None\n    search: Optional[str] = None\n    tags: Optional[List[str]] = None\n\n\nclass PaymentFilterParams(PaginationParams):\n    """Filter parameters for payment queries"""\n    payment_date_from: Optional[date] = None\n    payment_date_to: Optional[date] = None\n    payment_method: Optional[List[PaymentMethod]] = None\n    status: Optional[List[PaymentStatus]] = None\n    contact_id: Optional[UUID] = None\n    company_id: Optional[UUID] = None\n    invoice_id: Optional[UUID] = None\n    bank_account_id: Optional[UUID] = None\n    amount_min: Optional[Decimal] = None\n    amount_max: Optional[Decimal] = None\n    currency: Optional[str] = None\n    search: Optional[str] = None\n\n\nclass SubscriptionFilterParams(PaginationParams):\n    """Filter parameters for subscription queries"""\n    contact_id: Optional[UUID] = None\n    company_id: Optional[UUID] = None\n    product_id: Optional[UUID] = None\n    status: Optional[List[SubscriptionStatus]] = None\n    billing_cycle: Optional[List[BillingCycle]] = None\n    next_billing_from: Optional[date] = None\n    next_billing_to: Optional[date] = None\n    search: Optional[str] = None\n\n\n# ============================================\n# Revenue Statistics\n# ============================================\n\nclass RevenueSummaryResponse(BaseResponseModel):\n    """Schema for revenue summary"""\n    company_id: UUID\n    period_start: date\n    period_end: date\n    currency: str\n    \n    # Totals\n    total_revenue: Decimal = Decimal("0")\n    total_invoiced: Decimal = Decimal("0")\n    total_collected: Decimal = Decimal("0")\n    total_outstanding: Decimal = Decimal("0")\n    \n    # By status\n    by_status: Dict[str, Decimal] = Field(default_factory=dict)\n    \n    # By contact\n    top_customers: List[Dict[str, Any]] = Field(default_factory=list)\n    \n    # By product\n    by_product: List[Dict[str, Any]] = Field(default_factory=list)\n    \n    # Monthly trend\n    monthly_trend: List[Dict[str, Any]] = Field(default_factory=list)\n    \n    # Overdue\n    overdue_count: int = 0\n    overdue_amount: Decimal = Decimal("0")\n    average_days_to_pay: Decimal = Decimal("0")\n    \n    generated_at: datetime\n\n\nclass AgingReportResponse(BaseResponseModel):\n    """Schema for aging report"""\n    company_id: UUID\n    as_of_date: date\n    currency: str\n    \n    # Buckets\n    current: Decimal = Decimal("0")\n    days_1_30: Decimal = Decimal("0")\n    days_31_60: Decimal = Decimal("0")\n    days_61_90: Decimal = Decimal("0")\n    over_90: Decimal = Decimal("0")\n    \n    total: Decimal = Decimal("0")\n    \n    # By contact\n    by_contact: List[Dict[str, Any]] = Field(default_factory=list)\n    \n    generated_at: datetime\n\n\n# Update forward references\nContactResponse.model_rebuild()\nProductResponse.model_rebuild()\nInvoiceResponse.model_rebuild()\nPaymentResponse.model_rebuild()\nSubscriptionResponse.model_rebuild()\nRecurringInvoiceResponse.model_rebuild()\n</create-file>\n</function_calls>'}
{'role': 'user', 'content': '<tool_result> <create-file> ToolResult(success=True, output="File \'backend/app/schemas/invoice.py\' created successfully.") </create-file> </tool_result>'}
{'role': 'assistant', 'content': 'Let me continue creating the remaining schemas. Now I\'ll create the HR schemas:\n\n\n<function_calls><create-file file_path="backend/app/schemas/hr.py">"""\nHR & Payroll Schemas for SAMMS ENTERPRISE SOVEREIGN OPERATING SYSTEM\nDepartments, Positions, Employees, Payroll, Time Tracking, and Benefits\n"""\nfrom datetime import datetime, date, time\nfrom typing import Optional, List, Dict, Any, Union\nfrom uuid import UUID\nfrom decimal import Decimal\nfrom enum import Enum\n\nfrom pydantic import Field, field_validator, model_validator, EmailStr\n\nfrom .base import (\n    BaseResponseModel,\n    PaginationParams,\n    PaginatedResponse,\n    SuccessResponse,\n    ErrorResponse,\n    Address,\n    ContactInfo,\n    TimestampMixin,\n    IDMixin,\n)\n\n\nclass EmploymentType(str, Enum):\n    """Employment type enumeration"""\n    FULL_TIME = "full_time"\n    PART_TIME = "part_time"\n    CONTRACTOR = "contractor"\n    TEMPORARY = "temporary"\n    INTERN = "intern"\n    CONSULTANT = "consultant"\n    SEASONAL = "seasonal"\n    VOLUNTEER = "volunteer"\n\n\nclass EmploymentStatus(str, Enum):\n    """Employment status enumeration"""\n    ACTIVE = "active"\n    PROBATION = "probation"\n    TERMINATED = "terminated"\n    SUSPENDED = "suspended"\n    ON_LEAVE = "on_leave"\n    RETIRED = "retired"\n    DECEASED = "deceased"\n    REHIRED = "rehired"\n    TRANSFERRED = "transferred"\n\n\nclass PayType(str, Enum):\n    """Pay type enumeration"""\n    SALARY = "salary"\n    HOURLY = "hourly"\n    COMMISSION = "commission"\n    PIECE_RATE = "piece_rate"\n    DAILY = "daily"\n    WEEKLY = "weekly"\n\n\nclass PayFrequency(str, Enum):\n    """Pay frequency enumeration"""\n    WEEKLY = "weekly"\n    BI_WEEKLY = "bi_weekly"\n    SEMI_MONTHLY = "semi_monthly"\n    MONTHLY = "monthly"\n    QUARTERLY = "quarterly"\n    ANNUALLY = "annually"\n\n\nclass PayrollStatus(str, Enum):\n    """Payroll status enumeration"""\n    DRAFT = "draft"\n    PENDING = "pending"\n    APPROVED = "approved"\n    PROCESSING = "processing"\n    PROCESSED = "processed"\n    PAID = "paid"\n    CANCELLED = "cancelled"\n    ERROR = "error"\n\n\nclass LeaveType(str, Enum):\n    """Leave type enumeration"""\n    ANNUAL = "annual"\n    SICK = "sick"\n    PERSONAL = "personal"\n    MATERNITY = "maternity"\n    PATERNITY = "paternity"\n    BEREAVEMENT = "bereavement"\n    JURY_DUTY = "jury_duty"\n    MILITARY = "military"\n    UNPAID = "unpaid"\n    SABBATICAL = "sabbatical"\n    STUDY = "study"\n    OTHER = "other"\n\n\nclass LeaveRequestStatus(str, Enum):\n    """Leave request status enumeration"""\n    PENDING = "pending"\n    APPROVED = "approved"\n    REJECTED = "rejected"\n    CANCELLED = "cancelled"\n    COMPLETED = "completed"\n\n\nclass BenefitType(str, Enum):\n    """Benefit type enumeration"""\n    HEALTH = "health"\n    DENTAL = "dental"\n    VISION = "vision"\n    LIFE_INSURANCE = "life_insurance"\n    DISABILITY = "disability"\n    RETIREMENT = "retirement"\n    STOCK_OPTIONS = "stock_options"\n    EDUCATION = "education"\n    TRANSPORTATION = "transportation"\n    MEAL = "meal"\n    FITNESS = "fitness"\n    CHILDCARE = "childcare"\n    OTHER = "other"\n\n\nclass TimeEntryType(str, Enum):\n    """Time entry type enumeration"""\n    REGULAR = "regular"\n    OVERTIME = "overtime"\n    DOUBLE_TIME = "double_time"\n    HOLIDAY = "holiday"\n    VACATION = "vacation"\n    SICK = "sick"\n    PERSONAL = "personal"\n    TRAINING = "training"\n    MEETING = "meeting"\n    BREAK = "break"\n    OTHER = "other"\n\n\nclass DepartmentStatus(str, Enum):\n    """Department status enumeration"""\n    ACTIVE = "active"\n    INACTIVE = "inactive"\n    MERGED = "merged"\n    ARCHIVED = "archived"\n\n\n# ============================================\n# Department Schemas\n# ============================================\n\nclass DepartmentBase(BaseResponseModel):\n    """Base schema for department"""\n    name: str = Field(..., min_length=1, max_length=200)\n    code: str = Field(..., min_length=1, max_length=20)\n    description: Optional[str] = Field(None, max_length=2000)\n    \n    company_id: UUID = Field(..., description="Company ID")\n    \n    # Hierarchy\n    parent_department_id: Optional[UUID] = None\n    level: int = Field(default=0, ge=0)\n    \n    # Manager\n    manager_id: Optional[UUID] = Field(None, description="Department manager (employee)")\n    \n    # Cost center\n    cost_center: Optional[str] = Field(None, max_length=50)\n    gl_account_id: Optional[UUID] = None\n    \n    # Location\n    location: Optional[str] = Field(None, max_length=200)\n    \n    metadata: Optional[Dict[str, Any]] = None\n\n\nclass DepartmentCreate(DepartmentBase):\n    """Schema for creating a department"""\n    pass\n\n\nclass DepartmentUpdate(BaseResponseModel):\n    """Schema for updating a department"""\n    name: Optional[str] = Field(None, min_length=1, max_length=200)\n    code: Optional[str] = Field(None, min_length=1, max_length=20)\n    description: Optional[str] = Field(None, max_length=2000)\n    parent_department_id: Optional[UUID] = None\n    manager_id: Optional[UUID] = None\n    cost_center: Optional[str] = Field(None, max_length=50)\n    gl_account_id: Optional[UUID] = None\n    location: Optional[str] = Field(None, max_length=200)\n    metadata: Optional[Dict[str, Any]] = None\n    status: Optional[DepartmentStatus] = None\n\n\nclass DepartmentResponse(DepartmentBase, TimestampMixin, IDMixin):\n    """Schema for department response"""\n    status: DepartmentStatus = Field(default=DepartmentStatus.ACTIVE)\n    is_active: bool = Field(default=True)\n    \n    # Path\n    path: str = Field(default="", description="Full path in hierarchy")\n    \n    # Statistics\n    employee_count: int = Field(default=0)\n    position_count: int = Field(default=0)\n    \n    # Budget\n    budget: Optional[Decimal] = None\n    budget_used: Optional[Decimal] = None\n    \n    # Relationships\n    parent_department: Optional["DepartmentResponse"] = None\n    child_departments: List["DepartmentResponse"] = Field(default_factory=list)\n    \n    class Config:\n        from_attributes = True\n\n\nclass DepartmentListResponse(BaseResponseModel):\n    """Schema for department list item"""\n    id: UUID\n    name: str\n    code: str\n    company_id: UUID\n    parent_department_id: Optional[UUID]\n    manager_id: Optional[UUID]\n    employee_count: int\n    status: DepartmentStatus\n    created_at: datetime\n    \n    class Config:\n        from_attributes = True\n\n\n# ============================================\n# Position Schemas\n# ============================================\n\nclass PositionBase(BaseResponseModel):\n    """Base schema for position"""\n    title: str = Field(..., min_length=1, max_length=200)\n    code: str = Field(..., min_length=1, max_length=20)\n    description: Optional[str] = Field(None, max_length=5000)\n    \n    company_id: UUID = Field(..., description="Company ID")\n    department_id: UUID = Field(..., description="Department ID")\n    \n    # Classification\n    job_family: Optional[str] = Field(None, max_length=100)\n    job_level: Optional[str] = Field(None, max_length=50)\n    grade: Optional[str] = Field(None, max_length=20)\n    \n    # Reporting\n    reports_to: Optional[UUID] = Field(None, description="Reports to position")\n    \n    # Compensation range\n    min_salary: Optional[Decimal] = Field(None, ge=0)\n    max_salary: Optional[Decimal] = Field(None, ge=0)\n    mid_salary: Optional[Decimal] = Field(None, ge=0)\n    currency: str = Field(default="USD", min_length=3, max_length=3)\n    \n    # Headcount\n    headcount: int = Field(default=1, ge=1, description="Number of positions")\n    filled_positions: int = Field(default=0, ge=0)\n    \n    # Requirements\n    qualifications: Optional[str] = Field(None, max_length=5000)\n    skills: List[str] = Field(default_factory=list)\n    certifications: List[str] = Field(default_factory=list)\n    \n    # Work arrangement\n    work_location: Optional[str] = Field(None, max_length=100)\n    travel_required: Optional[Decimal] = Field(None, ge=0, le=100, description="Travel %")\n    \n    metadata: Optional[Dict[str, Any]] = None\n\n\nclass PositionCreate(PositionBase):\n    """Schema for creating a position"""\n    pass\n\n\nclass PositionUpdate(BaseResponseModel):\n    """Schema for updating a position"""\n    title: Optional[str] = Field(None, min_length=1, max_length=200)\n    code: Optional[str] = Field(None, min_length=1, max_length=20)\n    description: Optional[str] = Field(None, max_length=5000)\n    department_id: Optional[UUID] = None\n    job_family: Optional[str] = Field(None, max_length=100)\n    job_level: Optional[str] = Field(None, max_length=50)\n    grade: Optional[str] = Field(None, max_length=20)\n    reports_to: Optional[UUID] = None\n    min_salary: Optional[Decimal] = Field(None, ge=0)\n    max_salary: Optional[Decimal] = Field(None, ge=0)\n    mid_salary: Optional[Decimal] = Field(None, ge=0)\n    currency: Optional[str] = Field(None, min_length=3, max_length=3)\n    headcount: Optional[int] = Field(None, ge=1)\n    qualifications: Optional[str] = Field(None, max_length=5000)\n    skills: Optional[List[str]] = None\n    certifications: Optional[List[str]] = None\n    work_location: Optional[str] = Field(None, max_length=100)\n    travel_required: Optional[Decimal] = Field(None, ge=0, le=100)\n    metadata: Optional[Dict[str, Any]] = None\n    is_active: Optional[bool] = None\n\n\nclass PositionResponse(PositionBase, TimestampMixin, IDMixin):\n    """Schema for position response"""\n    is_active: bool = Field(default=True)\n    \n    # Calculated\n    open_positions: int = Field(default=0, description="Unfilled positions")\n    is_budgeted: bool = Field(default=True)\n    \n    # Current employees\n    employees: List[Dict[str, Any]] = Field(default_factory=list)\n    \n    class Config:\n        from_attributes = True\n\n\nclass PositionListResponse(BaseResponseModel):\n    """Schema for position list item"""\n    id: UUID\n    title: str\n    code: str\n    department_id: UUID\n    department_name: Optional[str]\n    company_id: UUID\n    headcount: int\n    filled_positions: int\n    min_salary: Optional[Decimal]\n    max_salary: Optional[Decimal]\n    is_active: bool\n    created_at: datetime\n    \n    class Config:\n        from_attributes = True\n\n\n# ============================================\n# Employee Schemas\n# ============================================\n\nclass EmployeeBase(BaseResponseModel):\n    """Base schema for employee"""\n    employee_number: Optional[str] = Field(None, max_length=50)\n    \n    # Personal info\n    first_name: str = Field(..., min_length=1, max_length=100)\n    last_name: str = Field(..., min_length=1, max_length=100)\n    middle_name: Optional[str] = Field(None, max_length=100)\n    preferred_name: Optional[str] = Field(None, max_length=100)\n    \n    # Demographics\n    date_of_birth: Optional[date] = None\n    gender: Optional[str] = Field(None, max_length=20)\n    marital_status: Optional[str] = Field(None, max_length=20)\n    nationality: Optional[str] = Field(None, max_length=100)\n    \n    # Identification\n    national_id: Optional[str] = Field(None, max_length=50)\n    passport_number: Optional[str] = Field(None, max_length=50)\n    tax_id: Optional[str] = Field(None, max_length=50)\n    \n    # Contact\n    email: Optional[EmailStr] = None\n    personal_email: Optional[EmailStr] = None\n    phone: Optional[str] = Field(None, max_length=50)\n    mobile: Optional[str] = Field(None, max_length=50)\n    address: Optional[Address] = None\n    emergency_contact: Optional[Dict[str, Any]] = None\n    \n    # Employment\n    company_id: UUID = Field(..., description="Company ID")\n    department_id: Optional[UUID] = None\n    position_id: Optional[UUID] = None\n    manager_id: Optional[UUID] = None\n    \n    # Employment details\n    employment_type: EmploymentType = Field(default=EmploymentType.FULL_TIME)\n    employment_status: EmploymentStatus = Field(default=EmploymentStatus.ACTIVE)\n    \n    # Dates\n    hire_date: date = Field(..., description="Hire date")\n    probation_end_date: Optional[date] = None\n    termination_date: Optional[date] = None\n    termination_reason: Optional[str] = Field(None, max_length=500)\n    \n    # Job details\n    job_title: Optional[str] = Field(None, max_length=200)\n    work_location: Optional[str] = Field(None, max_length=200)\n    work_schedule: Optional[str] = Field(None, max_length=100)\n    \n    # Compensation\n    pay_type: PayType = Field(default=PayType.SALARY)\n    pay_frequency: PayFrequency = Field(default=PayFrequency.MONTHLY)\n    salary: Optional[Decimal] = Field(None, ge=0)\n    hourly_rate: Optional[Decimal] = Field(None, ge=0)\n    currency: str = Field(default="USD", min_length=3, max_length=3)\n    \n    # Bank details\n    bank_name: Optional[str] = Field(None, max_length=200)\n    bank_account: Optional[str] = Field(None, max_length=50)\n    bank_routing: Optional[str] = Field(None, max_length=50)\n    \n    # Benefits eligibility\n    benefits_eligible: bool = Field(default=True)\n    benefits_start_date: Optional[date] = None\n    \n    # User link\n    user_id: Optional[UUID] = Field(None, description="Linked user account")\n    \n    # Photo\n    photo_url: Optional[str] = Field(None, max_length=1000)\n    \n    # Additional\n    skills: List[str] = Field(default_factory=list)\n    certifications: List[str] = Field(default_factory=list)\n    education: List[Dict[str, Any]] = Field(default_factory=list)\n    \n    notes: Optional[str] = Field(None, max_length=5000)\n    metadata: Optional[Dict[str, Any]] = None\n\n\nclass EmployeeCreate(EmployeeBase):\n    """Schema for creating an employee"""\n    auto_generate_number: bool = Field(default=True)\n    create_user_account: bool = Field(default=False)\n    \n    @model_validator(mode=\'after\')\n    def validate_termination(self) -> \'EmployeeCreate\':\n        """Validate termination date is after hire date"""\n        if self.termination_date and self.termination_date < self.hire_date:\n            raise ValueError(\'Termination date must be after hire date\')\n        return self\n\n\nclass EmployeeUpdate(BaseResponseModel):\n    """Schema for updating an employee"""\n    employee_number: Optional[str] = Field(None, max_length=50)\n    first_name: Optional[str] = Field(None, min_length=1, max_length=100)\n    last_name: Optional[str] = Field(None, min_length=1, max_length=100)\n    middle_name: Optional[str] = Field(None, max_length=100)\n    preferred_name: Optional[str] = Field(None, max_length=100)\n    date_of_birth: Optional[date] = None\n    gender: Optional[str] = Field(None, max_length=20)\n    marital_status: Optional[str] = Field(None, max_length=20)\n    nationality: Optional[str] = Field(None, max_length=100)\n    national_id: Optional[str] = Field(None, max_length=50)\n    passport_number: Optional[str] = Field(None, max_length=50)\n    tax_id: Optional[str] = Field(None, max_length=50)\n    email: Optional[EmailStr] = None\n    personal_email: Optional[EmailStr] = None\n    phone: Optional[str] = Field(None, max_length=50)\n    mobile: Optional[str] = Field(None, max_length=50)\n    address: Optional[Address] = None\n    emergency_contact: Optional[Dict[str, Any]] = None\n    department_id: Optional[UUID] = None\n    position_id: Optional[UUID] = None\n    manager_id: Optional[UUID] = None\n    employment_type: Optional[EmploymentType] = None\n    employment_status: Optional[EmploymentStatus] = None\n    hire_date: Optional[date] = None\n    probation_end_date: Optional[date] = None\n    termination_date: Optional[date] = None\n    termination_reason: Optional[str] = Field(None, max_length=500)\n    job_title: Optional[str] = Field(None, max_length=200)\n    work_location: Optional[str] = Field(None, max_length=200)\n    work_schedule: Optional[str] = Field(None, max_length=100)\n    pay_type: Optional[PayType] = None\n    pay_frequency: Optional[PayFrequency] = None\n    salary: Optional[Decimal] = Field(None, ge=0)\n    hourly_rate: Optional[Decimal] = Field(None, ge=0)\n    currency: Optional[str] = Field(None, min_length=3, max_length=3)\n    bank_name: Optional[str] = Field(None, max_length=200)\n    bank_account: Optional[str] = Field(None, max_length=50)\n    bank_routing: Optional[str] = Field(None, max_length=50)\n    benefits_eligible: Optional[bool] = None\n    benefits_start_date: Optional[date] = None\n    user_id: Optional[UUID] = None\n    photo_url: Optional[str] = Field(None, max_length=1000)\n    skills: Optional[List[str]] = None\n    certifications: Optional[List[str]] = None\n    education: Optional[List[Dict[str, Any]]] = None\n    notes: Optional[str] = Field(None, max_length=5000)\n    metadata: Optional[Dict[str, Any]] = None\n\n\nclass EmployeeResponse(EmployeeBase, TimestampMixin, IDMixin):\n    """Schema for employee response"""\n    is_active: bool = Field(default=True)\n    \n    # Calculated\n    full_name: str = Field(default="")\n    tenure_years: int = Field(default=0)\n    tenure_months: int = Field(default=0)\n    \n    # Department and position info\n    department_name: Optional[str] = None\n    position_title: Optional[str] = None\n    manager_name: Optional[str] = None\n    \n    # Leave balance\n    leave_balance: Dict[str, Decimal] = Field(default_factory=dict)\n    \n    # Statistics\n    ytd_gross: Decimal = Field(default=Decimal("0"))\n    ytd_net: Decimal = Field(default=Decimal("0"))\n    \n    class Config:\n        from_attributes = True\n\n\nclass EmployeeListResponse(BaseResponseModel):\n    """Schema for employee list item"""\n    id: UUID\n    employee_number: Optional[str]\n    full_name: str\n    email: Optional[str]\n    job_title: Optional[str]\n    department_id: Optional[UUID]\n    department_name: Optional[str]\n    employment_type: EmploymentType\n    employment_status: EmploymentStatus\n    hire_date: date\n    company_id: UUID\n    photo_url: Optional[str]\n    created_at: datetime\n    \n    class Config:\n        from_attributes = True\n\n\n# ============================================\n# Payroll Schemas\n# ============================================\n\nclass PayrollLineBase(BaseResponseModel):\n    """Base schema for payroll line"""\n    employee_id: UUID = Field(..., description="Employee ID")\n    pay_period_start: date = Field(..., description="Pay period start")\n    pay_period_end: date = Field(..., description="Pay period end")\n    pay_date: date = Field(..., description="Payment date")\n    \n    # Hours\n    regular_hours: Decimal = Field(default=Decimal("0"), ge=0)\n    overtime_hours: Decimal = Field(default=Decimal("0"), ge=0)\n    other_hours: Decimal = Field(default=Decimal("0"), ge=0)\n    \n    # Earnings\n    regular_earnings: Decimal = Field(default=Decimal("0"), ge=0)\n    overtime_earnings: Decimal = Field(default=Decimal("0"), ge=0)\n    bonus: Decimal = Field(default=Decimal("0"), ge=0)\n    commission: Decimal = Field(default=Decimal("0"), ge=0)\n    other_earnings: Decimal = Field(default=Decimal("0"), ge=0)\n    gross_pay: Decimal = Field(default=Decimal("0"), ge=0)\n    \n    # Deductions\n    federal_tax: Decimal = Field(default=Decimal("0"), ge=0)\n    state_tax: Decimal = Field(default=Decimal("0"), ge=0)\n    local_tax: Decimal = Field(default=Decimal("0"), ge=0)\n    social_security: Decimal = Field(default=Decimal("0"), ge=0)\n    medicare: Decimal = Field(default=Decimal("0"), ge=0)\n    retirement_401k: Decimal = Field(default=Decimal("0"), ge=0)\n    health_insurance: Decimal = Field(default=Decimal("0"), ge=0)\n    other_deductions: Decimal = Field(default=Decimal("0"), ge=0)\n    total_deductions: Decimal = Field(default=Decimal("0"), ge=0)\n    \n    # Net\n    net_pay: Decimal = Field(default=Decimal("0"), ge=0)\n    \n    # Employer contributions\n    employer_social_security: Decimal = Field(default=Decimal("0"), ge=0)\n    employer_medicare: Decimal = Field(default=Decimal("0"), ge=0)\n    employer_401k_match: Decimal = Field(default=Decimal("0"), ge=0)\n    employer_health_insurance: Decimal = Field(default=Decimal("0"), ge=0)\n    employer_other: Decimal = Field(default=Decimal("0"), ge=0)\n    total_employer_contribution: Decimal = Field(default=Decimal("0"), ge=0)\n    \n    currency: str = Field(default="USD", min_length=3, max_length=3)\n    \n    metadata: Optional[Dict[str, Any]] = None\n\n\nclass PayrollLineCreate(PayrollLineBase):\n    """Schema for creating payroll line"""\n    pass\n\n\nclass PayrollLineUpdate(BaseResponseModel):\n    """Schema for updating payroll line"""\n    regular_hours: Optional[Decimal] = Field(None, ge=0)\n    overtime_hours: Optional[Decimal] = Field(None, ge=0)\n    other_hours: Optional[Decimal] = Field(None, ge=0)\n    regular_earnings: Optional[Decimal] = Field(None, ge=0)\n    overtime_earnings: Optional[Decimal] = Field(None, ge=0)\n    bonus: Optional[Decimal] = Field(None, ge=0)\n    commission: Optional[Decimal] = Field(None, ge=0)\n    other_earnings: Optional[Decimal] = Field(None, ge=0)\n    federal_tax: Optional[Decimal] = Field(None, ge=0)\n    state_tax: Optional[Decimal] = Field(None, ge=0)\n    local_tax: Optional[Decimal] = Field(None, ge=0)\n    social_security: Optional[Decimal] = Field(None, ge=0)\n    medicare: Optional[Decimal] = Field(None, ge=0)\n    retirement_401k: Optional[Decimal] = Field(None, ge=0)\n    health_insurance: Optional[Decimal] = Field(None, ge=0)\n    other_deductions: Optional[Decimal] = Field(None, ge=0)\n    employer_401k_match: Optional[Decimal] = Field(None, ge=0)\n    employer_health_insurance: Optional[Decimal] = Field(None, ge=0)\n    employer_other: Optional[Decimal] = Field(None, ge=0)\n    metadata: Optional[Dict[str, Any]] = None\n\n\nclass PayrollLineResponse(PayrollLineBase, TimestampMixin, IDMixin):\n    """Schema for payroll line response"""\n    payroll_id: UUID\n    \n    # Employee info\n    employee_number: Optional[str] = None\n    employee_name: str = Field(default="")\n    department_name: Optional[str] = None\n    \n    class Config:\n        from_attributes = True\n\n\nclass PayrollBase(BaseResponseModel):\n    """Base schema for payroll run"""\n    name: str = Field(..., min_length=1, max_length=200)\n    description: Optional[str] = Field(None, max_length=2000)\n    \n    company_id: UUID = Field(..., description="Company ID")\n    \n    # Period\n    pay_period_start: date = Field(..., description="Pay period start")\n    pay_period_end: date = Field(..., description="Pay period end")\n    pay_date: date = Field(..., description="Payment date")\n    pay_frequency: PayFrequency = Field(default=PayFrequency.BI_WEEKLY)\n    \n    # Currency\n    currency: str = Field(default="USD", min_length=3, max_length=3)\n    \n    # Totals (calculated)\n    total_gross: Decimal = Field(default=Decimal("0"))\n    total_deductions: Decimal = Field(default=Decimal("0"))\n    total_net: Decimal = Field(default=Decimal("0"))\n    total_employer_contribution: Decimal = Field(default=Decimal("0"))\n    \n    # Counts\n    employee_count: int = Field(default=0)\n    \n    # GL\n    journal_entry_id: Optional[UUID] = None\n    \n    # Approval\n    approved_by: Optional[UUID] = None\n    approved_at: Optional[datetime] = None\n    \n    notes: Optional[str] = Field(None, max_length=2000)\n    metadata: Optional[Dict[str, Any]] = None\n\n\nclass PayrollCreate(PayrollBase):\n    """Schema for creating a payroll run"""\n    employee_ids: Optional[List[UUID]] = Field(None, description="Specific employees (all if empty)")\n    auto_calculate: bool = Field(default=True)\n    auto_post: bool = Field(default=False)\n\n\nclass PayrollUpdate(BaseResponseModel):\n    """Schema for updating a payroll run"""\n    name: Optional[str] = Field(None, min_length=1, max_length=200)\n    description: Optional[str] = Field(None, max_length=2000)\n    pay_date: Optional[date] = None\n    notes: Optional[str] = Field(None, max_length=2000)\n    metadata: Optional[Dict[str, Any]] = None\n    status: Optional[PayrollStatus] = None\n\n\nclass PayrollResponse(PayrollBase, TimestampMixin, IDMixin):\n    """Schema for payroll run response"""\n    payroll_number: str = Field(default="")\n    status: PayrollStatus = Field(default=PayrollStatus.DRAFT)\n    \n    # Processing\n    processed_by: Optional[UUID] = None\n    processed_at: Optional[datetime] = None\n    \n    # Relationships\n    lines: List[PayrollLineResponse] = Field(default_factory=list)\n    \n    class Config:\n        from_attributes = True\n\n\nclass PayrollListResponse(BaseResponseModel):\n    """Schema for payroll list item"""\n    id: UUID\n    payroll_number: str\n    name: str\n    pay_period_start: date\n    pay_period_end: date\n    pay_date: date\n    total_gross: Decimal\n    total_net: Decimal\n    employee_count: int\n    status: PayrollStatus\n    company_id: UUID\n    created_at: datetime\n    \n    class Config:\n        from_attributes = True\n\n\n# ============================================\n# Time Entry Schemas\n# ============================================\n\nclass TimeEntryBase(BaseResponseModel):\n    """Base schema for time entry"""\n    employee_id: UUID = Field(..., description="Employee ID")\n    company_id: UUID = Field(..., description="Company ID")\n    \n    # Date/time\n    entry_date: date = Field(..., description="Date of work")\n    start_time: Optional[time] = None\n    end_time: Optional[time] = None\n    \n    # Duration\n    hours: Decimal = Field(..., ge=0, description="Hours worked")\n    entry_type: TimeEntryType = Field(default=TimeEntryType.REGULAR)\n    \n    # Project/Task\n    project_id: Optional[UUID] = None\n    task_id: Optional[UUID] = None\n    department_id: Optional[UUID] = None\n    \n    # Details\n    description: Optional[str] = Field(None, max_length=1000)\n    is_billable: bool = Field(default=True)\n    hourly_rate: Optional[Decimal] = Field(None, ge=0)\n    \n    # Approval\n    approved_by: Optional[UUID] = None\n    approved_at: Optional[datetime] = None\n    \n    metadata: Optional[Dict[str, Any]] = None\n\n\nclass TimeEntryCreate(TimeEntryBase):\n    """Schema for creating a time entry"""\n    pass\n\n\nclass TimeEntryUpdate(BaseResponseModel):\n    """Schema for updating a time entry"""\n    entry_date: Optional[date] = None\n    start_time: Optional[time] = None\n    end_time: Optional[time] = None\n    hours: Optional[Decimal] = Field(None, ge=0)\n    entry_type: Optional[TimeEntryType] = None\n    project_id: Optional[UUID] = None\n    task_id: Optional[UUID] = None\n    department_id: Optional[UUID] = None\n    description: Optional[str] = Field(None, max_length=1000)\n    is_billable: Optional[bool] = None\n    hourly_rate: Optional[Decimal] = Field(None, ge=0)\n    metadata: Optional[Dict[str, Any]] = None\n    is_approved: Optional[bool] = None\n\n\nclass TimeEntryResponse(TimeEntryBase, TimestampMixin, IDMixin):\n    """Schema for time entry response"""\n    is_approved: bool = Field(default=False)\n    \n    # Calculated\n    total_amount: Decimal = Field(default=Decimal("0"))\n    \n    # Employee info\n    employee_name: str = Field(default="")\n    \n    class Config:\n        from_attributes = True\n\n\nclass TimeEntryListResponse(BaseResponseModel):\n    """Schema for time entry list item"""\n    id: UUID\n    employee_id: UUID\n    employee_name: str\n    entry_date: date\n    hours: Decimal\n    entry_type: TimeEntryType\n    project_id: Optional[UUID]\n    is_approved: bool\n    company_id: UUID\n    created_at: datetime\n    \n    class Config:\n        from_attributes = True\n\n\n# ============================================\n# Leave Request Schemas\n# ============================================\n\nclass LeaveRequestBase(BaseResponseModel):\n    """Base schema for leave request"""\n    employee_id: UUID = Field(..., description="Employee ID")\n    company_id: UUID = Field(..., description="Company ID")\n    \n    # Leave details\n    leave_type: LeaveType = Field(..., description="Type of leave")\n    \n    # Dates\n    start_date: date = Field(..., description="Start date")\n    end_date: date = Field(..., description="End date")\n    \n    # Duration\n    total_days: Decimal = Field(..., ge=0, description="Total days requested")\n    is_half_day: bool = Field(default=False)\n    \n    # Reason\n    reason: Optional[str] = Field(None, max_length=2000)\n    \n    # Approval\n    approved_by: Optional[UUID] = None\n    approved_at: Optional[datetime] = None\n    rejection_reason: Optional[str] = Field(None, max_length=1000)\n    \n    # Balance impact\n    balance_before: Optional[Decimal] = None\n    balance_after: Optional[Decimal] = None\n    \n    metadata: Optional[Dict[str, Any]] = None\n    \n    @model_validator(mode=\'after\')\n    def validate_dates(self) -> \'LeaveRequestBase\':\n        """Validate end date is after start date"""\n        if self.end_date < self.start_date:\n            raise ValueError(\'End date must be on or after start date\')\n        return self\n\n\nclass LeaveRequestCreate(LeaveRequestBase):\n    """Schema for creating a leave request"""\n    auto_approve: bool = Field(default=False)\n\n\nclass LeaveRequestUpdate(BaseResponseModel):\n    """Schema for updating a leave request"""\n    start_date: Optional[date] = None\n    end_date: Optional[date] = None\n    total_days: Optional[Decimal] = Field(None, ge=0)\n    is_half_day: Optional[bool] = None\n    reason: Optional[str] = Field(None, max_length=2000)\n    metadata: Optional[Dict[str, Any]] = None\n\n\nclass LeaveRequestResponse(LeaveRequestBase, TimestampMixin, IDMixin):\n    """Schema for leave request response"""\n    status: LeaveRequestStatus = Field(default=LeaveRequestStatus.PENDING)\n    \n    # Employee info\n    employee_name: str = Field(default="")\n    department_name: Optional[str] = None\n    \n    # Approver info\n    approver_name: Optional[str] = None\n    \n    class Config:\n        from_attributes = True\n\n\nclass LeaveRequestListResponse(BaseResponseModel):\n    """Schema for leave request list item"""\n    id: UUID\n    employee_id: UUID\n    employee_name: str\n    leave_type: LeaveType\n    start_date: date\n    end_date: date\n    total_days: Decimal\n    status: LeaveRequestStatus\n    company_id: UUID\n    created_at: datetime\n    \n    class Config:\n        from_attributes = True\n\n\n# ============================================\n# Benefit Schemas\n# ============================================\n\nclass BenefitBase(BaseResponseModel):\n    """Base schema for benefit"""\n    name: str = Field(..., min_length=1, max_length=200)\n    code: str = Field(..., min_length=1, max_length=50)\n    description: Optional[str] = Field(None, max_length=2000)\n    \n    company_id: UUID = Field(..., description="Company ID")\n    \n    benefit_type: BenefitType = Field(..., description="Type of benefit")\n    \n    # Provider\n    provider_name: Optional[str] = Field(None, max_length=200)\n    provider_plan_id: Optional[str] = Field(None, max_length=100)\n    \n    # Costs\n    employee_cost: Decimal = Field(default=Decimal("0"), ge=0)\n    employer_cost: Decimal = Field(default=Decimal("0"), ge=0)\n    currency: str = Field(default="USD", min_length=3, max_length=3)\n    \n    # Eligibility\n    waiting_period_days: int = Field(default=0, ge=0)\n    employment_types: List[EmploymentType] = Field(default_factory=list)\n    \n    # Coverage\n    coverage_amount: Optional[Decimal] = None\n    coverage_details: Optional[Dict[str, Any]] = None\n    \n    # GL\n    expense_account_id: Optional[UUID] = None\n    liability_account_id: Optional[UUID] = None\n    \n    # Effective dates\n    effective_start: Optional[date] = None\n    effective_end: Optional[date] = None\n    \n    metadata: Optional[Dict[str, Any]] = None\n\n\nclass BenefitCreate(BenefitBase):\n    """Schema for creating a benefit"""\n    pass\n\n\nclass BenefitUpdate(BaseResponseModel):\n    """Schema for updating a benefit"""\n    name: Optional[str] = Field(None, min_length=1, max_length=200)\n    code: Optional[str] = Field(None, min_length=1, max_length=50)\n    description: Optional[str] = Field(None, max_length=2000)\n    benefit_type: Optional[BenefitType] = None\n    provider_name: Optional[str] = Field(None, max_length=200)\n    provider_plan_id: Optional[str] = Field(None, max_length=100)\n    employee_cost: Optional[Decimal] = Field(None, ge=0)\n    employer_cost: Optional[Decimal] = Field(None, ge=0)\n    currency: Optional[str] = Field(None, min_length=3, max_length=3)\n    waiting_period_days: Optional[int] = Field(None, ge=0)\n    employment_types: Optional[List[EmploymentType]] = None\n    coverage_amount: Optional[Decimal] = None\n    coverage_details: Optional[Dict[str, Any]] = None\n    expense_account_id: Optional[UUID] = None\n    liability_account_id: Optional[UUID] = None\n    effective_start: Optional[date] = None\n    effective_end: Optional[date] = None\n    metadata: Optional[Dict[str, Any]] = None\n    is_active: Optional[bool] = None\n\n\nclass BenefitResponse(BenefitBase, TimestampMixin, IDMixin):\n    """Schema for benefit response"""\n    is_active: bool = Field(default=True)\n    enrollment_count: int = Field(default=0)\n    total_employee_cost: Decimal = Field(default=Decimal("0"))\n    total_employer_cost: Decimal = Field(default=Decimal("0"))\n    \n    class Config:\n        from_attributes = True\n\n\nclass BenefitListResponse(BaseResponseModel):\n    """Schema for benefit list item"""\n    id: UUID\n    name: str\n    code: str\n    benefit_type: BenefitType\n    employee_cost: Decimal\n    employer_cost: Decimal\n    currency: str\n    is_active: bool\n    company_id: UUID\n    enrollment_count: int\n    created_at: datetime\n    \n    class Config:\n        from_attributes = True\n\n\nclass EmployeeBenefitEnrollmentBase(BaseResponseModel):\n    """Base schema for employee benefit enrollment"""\n    employee_id: UUID = Field(..., description="Employee ID")\n    benefit_id: UUID = Field(..., description="Benefit ID")\n    \n    # Coverage\n    coverage_level: Optional[str] = Field(None, max_length=50)\n    coverage_amount: Optional[Decimal] = None\n    \n    # Dependents\n    dependents: List[Dict[str, Any]] = Field(default_factory=list)\n    \n    # Costs\n    employee_cost: Decimal = Field(default=Decimal("0"), ge=0)\n    employer_cost: Decimal = Field(default=Decimal("0"), ge=0)\n    \n    # Dates\n    enrollment_date: date = Field(..., description="Enrollment date")\n    effective_date: date = Field(..., description="Coverage start date")\n    termination_date: Optional[date] = None\n    \n    metadata: Optional[Dict[str, Any]] = None\n\n\nclass EmployeeBenefitEnrollmentCreate(EmployeeBenefitEnrollmentBase):\n    """Schema for creating benefit enrollment"""\n    pass\n\n\nclass EmployeeBenefitEnrollmentResponse(EmployeeBenefitEnrollmentBase, TimestampMixin, IDMixin):\n    """Schema for benefit enrollment response"""\n    is_active: bool = Field(default=True)\n    employee_name: str = Field(default="")\n    benefit_name: str = Field(default="")\n    \n    class Config:\n        from_attributes = True\n\n\n# ============================================\n# Query Parameters\n# ============================================\n\nclass DepartmentFilterParams(PaginationParams):\n    """Filter parameters for department queries"""\n    name: Optional[str] = None\n    code: Optional[str] = None\n    company_id: Optional[UUID] = None\n    parent_department_id: Optional[UUID] = None\n    manager_id: Optional[UUID] = None\n    status: Optional[List[DepartmentStatus]] = None\n    search: Optional[str] = None\n\n\nclass PositionFilterParams(PaginationParams):\n    """Filter parameters for position queries"""\n    title: Optional[str] = None\n    code: Optional[str] = None\n    company_id: Optional[UUID] = None\n    department_id: Optional[UUID] = None\n    job_family: Optional[str] = None\n    job_level: Optional[str] = None\n    is_active: Optional[bool] = None\n    has_openings: Optional[bool] = None\n    search: Optional[str] = None\n\n\nclass EmployeeFilterParams(PaginationParams):\n    """Filter parameters for employee queries"""\n    employee_number: Optional[str] = None\n    name: Optional[str] = None\n    email: Optional[str] = None\n    company_id: Optional[UUID] = None\n    department_id: Optional[UUID] = None\n    position_id: Optional[UUID] = None\n    manager_id: Optional[UUID] = None\n    employment_type: Optional[List[EmploymentType]] = None\n    employment_status: Optional[List[EmploymentStatus]] = None\n    hire_date_from: Optional[date] = None\n    hire_date_to: Optional[date] = None\n    is_active: Optional[bool] = None\n    search: Optional[str] = None\n\n\nclass PayrollFilterParams(PaginationParams):\n    """Filter parameters for payroll queries"""\n    name: Optional[str] = None\n    company_id: Optional[UUID] = None\n    pay_period_from: Optional[date] = None\n    pay_period_to: Optional[date] = None\n    pay_date_from: Optional[date] = None\n    pay_date_to: Optional[date] = None\n    status: Optional[List[PayrollStatus]] = None\n    search: Optional[str] = None\n\n\nclass TimeEntryFilterParams(PaginationParams):\n    """Filter parameters for time entry queries"""\n    employee_id: Optional[UUID] = None\n    company_id: Optional[UUID] = None\n    entry_date_from: Optional[date] = None\n    entry_date_to: Optional[date] = None\n    entry_type: Optional[List[TimeEntryType]] = None\n    project_id: Optional[UUID] = None\n    department_id: Optional[UUID] = None\n    is_approved: Optional[bool] = None\n    is_billable: Optional[bool] = None\n    search: Optional[str] = None\n\n\nclass LeaveRequestFilterParams(PaginationParams):\n    """Filter parameters for leave request queries"""\n    employee_id: Optional[UUID] = None\n    company_id: Optional[UUID] = None\n    leave_type: Optional[List[LeaveType]] = None\n    status: Optional[List[LeaveRequestStatus]] = None\n    start_date_from: Optional[date] = None\n    start_date_to: Optional[date] = None\n    approved_by: Optional[UUID] = None\n    search: Optional[str] = None\n\n\nclass BenefitFilterParams(PaginationParams):\n    """Filter parameters for benefit queries"""\n    name: Optional[str] = None\n    code: Optional[str] = None\n    company_id: Optional[UUID] = None\n    benefit_type: Optional[List[BenefitType]] = None\n    is_active: Optional[bool] = None\n    search: Optional[str] = None\n\n\n# ============================================\n# HR Statistics\n# ============================================\n\nclass HRStatisticsResponse(BaseResponseModel):\n    """Schema for HR statistics"""\n    company_id: UUID\n    as_of_date: date\n    \n    # Headcount\n    total_employees: int = 0\n    active_employees: int = 0\n    new_hires_this_month: int = 0\n    new_hires_this_year: int = 0\n    terminations_this_month: int = 0\n    terminations_this_year: int = 0\n    \n    # By department\n    by_department: Dict[str, int] = Field(default_factory=dict)\n    \n    # By employment type\n    by_employment_type: Dict[str, int] = Field(default_factory=dict)\n    \n    # By employment status\n    by_employment_status: Dict[str, int] = Field(default_factory=dict)\n    \n    # Compensation\n    total_monthly_payroll: Decimal = Decimal("0")\n    average_salary: Decimal = Decimal("0")\n    \n    # Turnover\n    turnover_rate: Decimal = Decimal("0")\n    \n    # Leave\n    pending_leave_requests: int = 0\n    employees_on_leave: int = 0\n    \n    # Positions\n    total_positions: int = 0\n    open_positions: int = 0\n    \n    generated_at: datetime\n\n\n# Update forward references\nDepartmentResponse.model_rebuild()\n</create-file>\n</function_calls>'}
{'role': 'user', 'content': '<tool_result> <create-file> ToolResult(success=True, output="File \'backend/app/schemas/hr.py\' created successfully.") </create-file> </tool_result>'}
{'role': 'assistant', 'content': 'Let me continue creating the remaining schemas. Now I\'ll create the Tax schemas for the Tax Engine:\n\n\n<function_calls><create-file file_path="backend/app/schemas/tax.py">"""\nTax Engine Schemas for SAMMS ENTERPRISE SOVEREIGN OPERATING SYSTEM\nTax rates, codes, nexus rules, filings, and cross-jurisdictional calculations\n"""\nfrom datetime import datetime, date\nfrom typing import Optional, List, Dict, Any, Union\nfrom uuid import UUID\nfrom decimal import Decimal\nfrom enum import Enum\n\nfrom pydantic import Field, field_validator, model_validator\n\nfrom .base import (\n    BaseResponseModel,\n    PaginationParams,\n    PaginatedResponse,\n    SuccessResponse,\n    ErrorResponse,\n    TimestampMixin,\n    IDMixin,\n)\n\n\nclass TaxType(str, Enum):\n    """Tax type enumeration"""\n    SALES = "sales"\n    USE = "use"\n    VAT = "vat"\n    GST = "gst"\n    INCOME = "income"\n    WITHHOLDING = "withholding"\n    PAYROLL = "payroll"\n    PROPERTY = "property"\n    EXCISE = "excise"\n    SERVICE = "service"\n    CORPORATE = "corporate"\n    FRANCHISE = "franchise"\n    IMPORT = "import"\n    EXPORT = "export"\n    OTHER = "other"\n\n\nclass TaxRateType(str, Enum):\n    """Tax rate type enumeration"""\n    PERCENTAGE = "percentage"\n    FIXED_AMOUNT = "fixed_amount"\n    GRADUATED = "graduated"\n    THRESHOLD = "threshold"\n\n\nclass TaxJurisdictionType(str, Enum):\n    """Tax jurisdiction type enumeration"""\n    FEDERAL = "federal"\n    STATE = "state"\n    COUNTY = "county"\n    CITY = "city"\n    SPECIAL_DISTRICT = "special_district"\n    COUNTRY = "country"\n    PROVINCE = "province"\n    MUNICIPALITY = "municipality"\n    OTHER = "other"\n\n\nclass TaxFilingStatus(str, Enum):\n    """Tax filing status enumeration"""\n    PENDING = "pending"\n    FILED = "filed"\n    APPROVED = "approved"\n    PAID = "paid"\n    REJECTED = "rejected"\n    AMENDED = "amended"\n    CANCELLED = "cancelled"\n    OVERDUE = "overdue"\n\n\nclass TaxFilingFrequency(str, Enum):\n    """Tax filing frequency enumeration"""\n    MONTHLY = "monthly"\n    QUARTERLY = "quarterly"\n    SEMI_ANNUALLY = "semi_annually"\n    ANNUALLY = "annually"\n    WEEKLY = "weekly"\n    DAILY = "daily"\n    AS_REQUIRED = "as_required"\n\n\nclass NexusType(str, Enum):\n    """Nexus type enumeration"""\n    PHYSICAL = "physical"\n    ECONOMIC = "economic"\n    AFFILIATE = "affiliate"\n    CLICK_THROUGH = "click_through"\n    MARKETPLACE = "marketplace"\n    VOLUNTARY = "voluntary"\n    NONE = "none"\n\n\nclass ExchangeRateSource(str, Enum):\n    """Exchange rate source enumeration"""\n    ECB = "ecb"\n    FED = "fed"\n    IMF = "imf"\n    YAHOO = "yahoo"\n    FIXER = "fixer"\n    CUSTOM = "custom"\n\n\n# ============================================\n# Tax Rate Schemas\n# ============================================\n\nclass TaxRateBase(BaseResponseModel):\n    """Base schema for tax rate"""\n    name: str = Field(..., min_length=1, max_length=200)\n    code: str = Field(..., min_length=1, max_length=50)\n    description: Optional[str] = Field(None, max_length=2000)\n    \n    company_id: Optional[UUID] = Field(None, description="Company ID (null for global)")\n    \n    # Tax classification\n    tax_type: TaxType = Field(..., description="Type of tax")\n    tax_rate_type: TaxRateType = Field(default=TaxRateType.PERCENTAGE)\n    \n    # Rate\n    rate: Decimal = Field(..., description="Tax rate (percentage or fixed amount)")\n    is_compound: bool = Field(default=False, description="Compound on other taxes")\n    \n    # Jurisdiction\n    jurisdiction_type: TaxJurisdictionType = Field(..., description="Jurisdiction type")\n    jurisdiction_code: str = Field(..., min_length=1, max_length=50, description="Jurisdiction code")\n    jurisdiction_name: str = Field(..., min_length=1, max_length=200, description="Jurisdiction name")\n    country: str = Field(..., min_length=2, max_length=3, description="Country code")\n    state: Optional[str] = Field(None, max_length=100, description="State/province")\n    county: Optional[str] = Field(None, max_length=100)\n    city: Optional[str] = Field(None, max_length=100)\n    \n    # Applicability\n    is_recoverable: bool = Field(default=False, description="Can be recovered/refunded")\n    is_included_in_price: bool = Field(default=False, description="Tax-inclusive pricing")\n    \n    # Effective dates\n    effective_from: date = Field(..., description="Effective from date")\n    effective_to: Optional[date] = Field(None, description="Effective to date")\n    \n    # Thresholds\n    threshold_amount: Optional[Decimal] = Field(None, description="Minimum amount for tax to apply")\n    exempt_amount: Optional[Decimal] = Field(None, description="Exempt amount")\n    \n    # GL accounts\n    tax_payable_account_id: Optional[UUID] = None\n    tax_receivable_account_id: Optional[UUID] = None\n    \n    metadata: Optional[Dict[str, Any]] = None\n\n\nclass TaxRateCreate(TaxRateBase):\n    """Schema for creating a tax rate"""\n    pass\n\n\nclass TaxRateUpdate(BaseResponseModel):\n    """Schema for updating a tax rate"""\n    name: Optional[str] = Field(None, min_length=1, max_length=200)\n    description: Optional[str] = Field(None, max_length=2000)\n    rate: Optional[Decimal] = None\n    is_compound: Optional[bool] = None\n    effective_from: Optional[date] = None\n    effective_to: Optional[date] = None\n    threshold_amount: Optional[Decimal] = None\n    exempt_amount: Optional[Decimal] = None\n    tax_payable_account_id: Optional[UUID] = None\n    tax_receivable_account_id: Optional[UUID] = None\n    metadata: Optional[Dict[str, Any]] = None\n    is_active: Optional[bool] = None\n\n\nclass TaxRateResponse(TaxRateBase, TimestampMixin, IDMixin):\n    """Schema for tax rate response"""\n    is_active: bool = Field(default=True)\n    usage_count: int = Field(default=0)\n    \n    # Calculated display\n    display_rate: str = Field(default="", description="Formatted rate for display")\n    \n    class Config:\n        from_attributes = True\n\n\nclass TaxRateListResponse(BaseResponseModel):\n    """Schema for tax rate list item"""\n    id: UUID\n    name: str\n    code: str\n    tax_type: TaxType\n    rate: Decimal\n    jurisdiction_code: str\n    jurisdiction_name: str\n    country: str\n    is_active: bool\n    effective_from: date\n    company_id: Optional[UUID]\n    created_at: datetime\n    \n    class Config:\n        from_attributes = True\n\n\n# ============================================\n# Tax Code Schemas\n# ============================================\n\nclass TaxCodeBase(BaseResponseModel):\n    """Base schema for tax code"""\n    code: str = Field(..., min_length=1, max_length=50)\n    name: str = Field(..., min_length=1, max_length=200)\n    description: Optional[str] = Field(None, max_length=2000)\n    \n    company_id: Optional[UUID] = Field(None, description="Company ID (null for global)")\n    \n    # Classification\n    tax_type: TaxType = Field(..., description="Type of tax")\n    \n    # Associated rates\n    tax_rate_ids: List[UUID] = Field(default_factory=list, description="Applicable tax rates")\n    \n    # Behavior\n    is_exempt: bool = Field(default=False, description="Is this an exemption code")\n    is_reverse_charge: bool = Field(default=False, description="Reverse charge mechanism")\n    \n    # Reporting\n    box_number: Optional[str] = Field(None, max_length=20, description="Tax return box number")\n    report_code: Optional[str] = Field(None, max_length=50)\n    \n    metadata: Optional[Dict[str, Any]] = None\n\n\nclass TaxCodeCreate(TaxCodeBase):\n    """Schema for creating a tax code"""\n    pass\n\n\nclass TaxCodeUpdate(BaseResponseModel):\n    """Schema for updating a tax code"""\n    name: Optional[str] = Field(None, min_length=1, max_length=200)\n    description: Optional[str] = Field(None, max_length=2000)\n    tax_rate_ids: Optional[List[UUID]] = None\n    is_exempt: Optional[bool] = None\n    is_reverse_charge: Optional[bool] = None\n    box_number: Optional[str] = Field(None, max_length=20)\n    report_code: Optional[str] = Field(None, max_length=50)\n    metadata: Optional[Dict[str, Any]] = None\n    is_active: Optional[bool] = None\n\n\nclass TaxCodeResponse(TaxCodeBase, TimestampMixin, IDMixin):\n    """Schema for tax code response"""\n    is_active: bool = Field(default=True)\n    usage_count: int = Field(default=0)\n    total_rates: int = Field(default=0)\n    \n    class Config:\n        from_attributes = True\n\n\nclass TaxCodeListResponse(BaseResponseModel):\n    """Schema for tax code list item"""\n    id: UUID\n    code: str\n    name: str\n    tax_type: TaxType\n    is_exempt: bool\n    is_active: bool\n    company_id: Optional[UUID]\n    created_at: datetime\n    \n    class Config:\n        from_attributes = True\n\n\n# ============================================\n# Tax Transaction Schemas\n# ============================================\n\nclass TaxTransactionBase(BaseResponseModel):\n    """Base schema for tax transaction"""\n    company_id: UUID = Field(..., description="Company ID")\n    \n    # Source\n    source_type: str = Field(..., max_length=100, description="invoice, purchase, payroll, etc.")\n    source_id: UUID = Field(..., description="Source document ID")\n    source_line_id: Optional[UUID] = Field(None, description="Source line ID")\n    \n    # Tax details\n    tax_rate_id: UUID = Field(..., description="Tax rate applied")\n    tax_code_id: Optional[UUID] = None\n    \n    # Amounts\n    taxable_amount: Decimal = Field(..., description="Amount subject to tax")\n    tax_amount: Decimal = Field(..., description="Calculated tax amount")\n    currency: str = Field(default="USD", min_length=3, max_length=3)\n    \n    # Jurisdiction\n    jurisdiction_code: str = Field(..., max_length=50)\n    jurisdiction_name: str = Field(..., max_length=200)\n    \n    # Date\n    transaction_date: date = Field(..., description="Transaction date")\n    \n    # Reference\n    reference: Optional[str] = Field(None, max_length=200)\n    \n    # Reversal\n    is_reversed: bool = Field(default=False)\n    reversed_by_id: Optional[UUID] = None\n    \n    # GL\n    journal_entry_id: Optional[UUID] = None\n    journal_entry_line_id: Optional[UUID] = None\n    \n    metadata: Optional[Dict[str, Any]] = None\n\n\nclass TaxTransactionCreate(TaxTransactionBase):\n    """Schema for creating a tax transaction"""\n    auto_post: bool = Field(default=False)\n\n\nclass TaxTransactionResponse(TaxTransactionBase, TimestampMixin, IDMixin):\n    """Schema for tax transaction response"""\n    transaction_number: str = Field(default="")\n    \n    # Tax rate info\n    tax_rate_name: str = Field(default="")\n    tax_rate: Decimal = Field(default=Decimal("0"))\n    tax_type: TaxType = TaxType.SALES\n    \n    # Status\n    is_posted: bool = Field(default=False)\n    posted_at: Optional[datetime] = None\n    \n    class Config:\n        from_attributes = True\n\n\nclass TaxTransactionListResponse(BaseResponseModel):\n    """Schema for tax transaction list item"""\n    id: UUID\n    transaction_number: str\n    transaction_date: date\n    tax_type: TaxType\n    taxable_amount: Decimal\n    tax_amount: Decimal\n    currency: str\n    jurisdiction_name: str\n    source_type: str\n    company_id: UUID\n    created_at: datetime\n    \n    class Config:\n        from_attributes = True\n\n\n# ============================================\n# Tax Filing Schemas\n# ============================================\n\nclass TaxFilingLineBase(BaseResponseModel):\n    """Base schema for tax filing line"""\n    tax_rate_id: UUID = Field(..., description="Tax rate ID")\n    tax_code_id: Optional[UUID] = None\n    \n    # Amounts\n    taxable_amount: Decimal = Field(default=Decimal("0"))\n    tax_amount: Decimal = Field(default=Decimal("0"))\n    adjustments: Decimal = Field(default=Decimal("0"))\n    total_amount: Decimal = Field(default=Decimal("0"))\n    \n    # Jurisdiction\n    jurisdiction_code: str = Field(..., max_length=50)\n    jurisdiction_name: str = Field(..., max_length=200)\n    \n    notes: Optional[str] = Field(None, max_length=1000)\n\n\nclass TaxFilingLineCreate(TaxFilingLineBase):\n    """Schema for creating tax filing line"""\n    pass\n\n\nclass TaxFilingLineResponse(TaxFilingLineBase, TimestampMixin, IDMixin):\n    """Schema for tax filing line response"""\n    filing_id: UUID\n    tax_rate_name: str = Field(default="")\n    tax_type: TaxType = TaxType.SALES\n    \n    class Config:\n        from_attributes = True\n\n\nclass TaxFilingBase(BaseResponseModel):\n    """Base schema for tax filing"""\n    name: str = Field(..., min_length=1, max_length=200)\n    description: Optional[str] = Field(None, max_length=2000)\n    \n    company_id: UUID = Field(..., description="Company ID")\n    \n    # Period\n    filing_period_start: date = Field(..., description="Filing period start")\n    filing_period_end: date = Field(..., description="Filing period end")\n    due_date: date = Field(..., description="Filing due date")\n    \n    # Tax type\n    tax_type: TaxType = Field(..., description="Type of tax")\n    filing_frequency: TaxFilingFrequency = Field(..., description="Filing frequency")\n    \n    # Jurisdiction\n    jurisdiction_type: TaxJurisdictionType = Field(..., description="Jurisdiction type")\n    jurisdiction_code: str = Field(..., max_length=50)\n    jurisdiction_name: str = Field(..., max_length=200)\n    \n    # Currency\n    currency: str = Field(default="USD", min_length=3, max_length=3)\n    \n    # Totals\n    total_taxable_amount: Decimal = Field(default=Decimal("0"))\n    total_tax_amount: Decimal = Field(default=Decimal("0"))\n    total_adjustments: Decimal = Field(default=Decimal("0"))\n    total_amount_due: Decimal = Field(default=Decimal("0"))\n    \n    # Payment\n    amount_paid: Decimal = Field(default=Decimal("0"))\n    payment_date: Optional[date] = None\n    payment_reference: Optional[str] = Field(None, max_length=200)\n    \n    # Filing info\n    filing_reference: Optional[str] = Field(None, max_length=200)\n    confirmation_number: Optional[str] = Field(None, max_length=200)\n    filed_by: Optional[UUID] = None\n    filed_at: Optional[datetime] = None\n    \n    # GL\n    journal_entry_id: Optional[UUID] = None\n    \n    notes: Optional[str] = Field(None, max_length=5000)\n    metadata: Optional[Dict[str, Any]] = None\n\n\nclass TaxFilingCreate(TaxFilingBase):\n    """Schema for creating a tax filing"""\n    lines: List[TaxFilingLineCreate] = Field(default_factory=list)\n    auto_calculate: bool = Field(default=True)\n\n\nclass TaxFilingUpdate(BaseResponseModel):\n    """Schema for updating a tax filing"""\n    name: Optional[str] = Field(None, min_length=1, max_length=200)\n    description: Optional[str] = Field(None, max_length=2000)\n    due_date: Optional[date] = None\n    total_adjustments: Optional[Decimal] = None\n    payment_date: Optional[date] = None\n    payment_reference: Optional[str] = Field(None, max_length=200)\n    filing_reference: Optional[str] = Field(None, max_length=200)\n    confirmation_number: Optional[str] = Field(None, max_length=200)\n    notes: Optional[str] = Field(None, max_length=5000)\n    metadata: Optional[Dict[str, Any]] = None\n    status: Optional[TaxFilingStatus] = None\n\n\nclass TaxFilingResponse(TaxFilingBase, TimestampMixin, IDMixin):\n    """Schema for tax filing response"""\n    filing_number: str = Field(default="")\n    status: TaxFilingStatus = Field(default=TaxFilingStatus.PENDING)\n    \n    # Approval\n    approved_by: Optional[UUID] = None\n    approved_at: Optional[datetime] = None\n    \n    # Relationships\n    lines: List[TaxFilingLineResponse] = Field(default_factory=list)\n    \n    class Config:\n        from_attributes = True\n\n\nclass TaxFilingListResponse(BaseResponseModel):\n    """Schema for tax filing list item"""\n    id: UUID\n    filing_number: str\n    name: str\n    tax_type: TaxType\n    filing_period_start: date\n    filing_period_end: date\n    due_date: date\n    total_amount_due: Decimal\n    amount_paid: Decimal\n    status: TaxFilingStatus\n    company_id: UUID\n    created_at: datetime\n    \n    class Config:\n        from_attributes = True\n\n\n# ============================================\n# Tax Nexus Rule Schemas\n# ============================================\n\nclass TaxNexusRuleBase(BaseResponseModel):\n    """Base schema for tax nexus rule"""\n    company_id: UUID = Field(..., description="Company ID")\n    \n    # Jurisdiction\n    jurisdiction_type: TaxJurisdictionType = Field(..., description="Jurisdiction type")\n    jurisdiction_code: str = Field(..., max_length=50)\n    jurisdiction_name: str = Field(..., max_length=200)\n    country: str = Field(..., min_length=2, max_length=3)\n    state: Optional[str] = Field(None, max_length=100)\n    \n    # Nexus type\n    nexus_type: NexusType = Field(..., description="Type of nexus")\n    \n    # Dates\n    effective_from: date = Field(..., description="Effective from date")\n    effective_to: Optional[date] = Field(None, description="Effective to date")\n    \n    # Thresholds (for economic nexus)\n    sales_threshold: Optional[Decimal] = Field(None, description="Sales threshold amount")\n    transaction_threshold: Optional[int] = Field(None, description="Transaction count threshold")\n    threshold_period: Optional[str] = Field(None, description="Threshold calculation period")\n    \n    # Current status\n    current_sales: Optional[Decimal] = Field(None, description="Current period sales")\n    current_transactions: Optional[int] = None\n    \n    # Registration\n    registration_number: Optional[str] = Field(None, max_length=100)\n    registration_date: Optional[date] = None\n    \n    # Applicable taxes\n    applicable_tax_types: List[TaxType] = Field(default_factory=list)\n    \n    notes: Optional[str] = Field(None, max_length=2000)\n    metadata: Optional[Dict[str, Any]] = None\n\n\nclass TaxNexusRuleCreate(TaxNexusRuleBase):\n    """Schema for creating a tax nexus rule"""\n    pass\n\n\nclass TaxNexusRuleUpdate(BaseResponseModel):\n    """Schema for updating a tax nexus rule"""\n    effective_to: Optional[date] = None\n    sales_threshold: Optional[Decimal] = None\n    transaction_threshold: Optional[int] = None\n    threshold_period: Optional[str] = None\n    registration_number: Optional[str] = Field(None, max_length=100)\n    registration_date: Optional[date] = None\n    applicable_tax_types: Optional[List[TaxType]] = None\n    notes: Optional[str] = Field(None, max_length=2000)\n    metadata: Optional[Dict[str, Any]] = None\n    is_active: Optional[bool] = None\n\n\nclass TaxNexusRuleResponse(TaxNexusRuleBase, TimestampMixin, IDMixin):\n    """Schema for tax nexus rule response"""\n    is_active: bool = Field(default=True)\n    \n    # Calculated\n    has_met_threshold: bool = Field(default=False, description="Threshold exceeded")\n    threshold_percentage: Decimal = Field(default=Decimal("0"), description="Progress toward threshold")\n    \n    class Config:\n        from_attributes = True\n\n\nclass TaxNexusRuleListResponse(BaseResponseModel):\n    """Schema for tax nexus rule list item"""\n    id: UUID\n    jurisdiction_code: str\n    jurisdiction_name: str\n    country: str\n    nexus_type: NexusType\n    effective_from: date\n    has_met_threshold: bool\n    is_active: bool\n    company_id: UUID\n    created_at: datetime\n    \n    class Config:\n        from_attributes = True\n\n\n# ============================================\n# Exchange Rate Schemas\n# ============================================\n\nclass ExchangeRateBase(BaseResponseModel):\n    """Base schema for exchange rate"""\n    from_currency: str = Field(..., min_length=3, max_length=3, description="Source currency")\n    to_currency: str = Field(..., min_length=3, max_length=3, description="Target currency")\n    \n    rate: Decimal = Field(..., gt=0, description="Exchange rate")\n    inverse_rate: Optional[Decimal] = Field(None, gt=0, description="Inverse exchange rate")\n    \n    rate_date: date = Field(..., description="Rate effective date")\n    \n    source: ExchangeRateSource = Field(default=ExchangeRateSource.CUSTOM)\n    source_reference: Optional[str] = Field(None, max_length=200)\n    \n    company_id: Optional[UUID] = Field(None, description="Company ID (null for global)")\n    \n    metadata: Optional[Dict[str, Any]] = None\n\n\nclass ExchangeRateCreate(ExchangeRateBase):\n    """Schema for creating an exchange rate"""\n    pass\n\n\nclass ExchangeRateUpdate(BaseResponseModel):\n    """Schema for updating an exchange rate"""\n    rate: Optional[Decimal] = Field(None, gt=0)\n    inverse_rate: Optional[Decimal] = Field(None, gt=0)\n    source: Optional[ExchangeRateSource] = None\n    source_reference: Optional[str] = Field(None, max_length=200)\n    metadata: Optional[Dict[str, Any]] = None\n\n\nclass ExchangeRateResponse(ExchangeRateBase, TimestampMixin, IDMixin):\n    """Schema for exchange rate response"""\n    is_active: bool = Field(default=True)\n    \n    class Config:\n        from_attributes = True\n\n\nclass ExchangeRateListResponse(BaseResponseModel):\n    """Schema for exchange rate list item"""\n    id: UUID\n    from_currency: str\n    to_currency: str\n    rate: Decimal\n    rate_date: date\n    source: ExchangeRateSource\n    company_id: Optional[UUID]\n    created_at: datetime\n    \n    class Config:\n        from_attributes = True\n\n\nclass CurrencyConversionRequest(BaseResponseModel):\n    """Schema for currency conversion request"""\n    amount: Decimal = Field(..., description="Amount to convert")\n    from_currency: str = Field(..., min_length=3, max_length=3)\n    to_currency: str = Field(..., min_length=3, max_length=3)\n    rate_date: Optional[date] = Field(None, description="Date for rate (today if null)")\n    company_id: Optional[UUID] = None\n\n\nclass CurrencyConversionResponse(BaseResponseModel):\n    """Schema for currency conversion response"""\n    original_amount: Decimal\n    original_currency: str\n    converted_amount: Decimal\n    converted_currency: str\n    exchange_rate: Decimal\n    rate_date: date\n    rate_source: ExchangeRateSource\n\n\n# ============================================\n# Query Parameters\n# ============================================\n\nclass TaxRateFilterParams(PaginationParams):\n    """Filter parameters for tax rate queries"""\n    name: Optional[str] = None\n    code: Optional[str] = None\n    tax_type: Optional[List[TaxType]] = None\n    jurisdiction_type: Optional[List[TaxJurisdictionType]] = None\n    jurisdiction_code: Optional[str] = None\n    country: Optional[str] = None\n    state: Optional[str] = None\n    company_id: Optional[UUID] = None\n    is_active: Optional[bool] = None\n    effective_on: Optional[date] = None\n    search: Optional[str] = None\n\n\nclass TaxCodeFilterParams(PaginationParams):\n    """Filter parameters for tax code queries"""\n    code: Optional[str] = None\n    name: Optional[str] = None\n    tax_type: Optional[List[TaxType]] = None\n    is_exempt: Optional[bool] = None\n    is_active: Optional[bool] = None\n    company_id: Optional[UUID] = None\n    search: Optional[str] = None\n\n\nclass TaxTransactionFilterParams(PaginationParams):\n    """Filter parameters for tax transaction queries"""\n    transaction_date_from: Optional[date] = None\n    transaction_date_to: Optional[date] = None\n    tax_type: Optional[List[TaxType]] = None\n    company_id: Optional[UUID] = None\n    jurisdiction_code: Optional[str] = None\n    source_type: Optional[str] = None\n    source_id: Optional[UUID] = None\n    is_reversed: Optional[bool] = None\n    is_posted: Optional[bool] = None\n    search: Optional[str] = None\n\n\nclass TaxFilingFilterParams(PaginationParams):\n    """Filter parameters for tax filing queries"""\n    name: Optional[str] = None\n    tax_type: Optional[List[TaxType]] = None\n    status: Optional[List[TaxFilingStatus]] = None\n    company_id: Optional[UUID] = None\n    jurisdiction_code: Optional[str] = None\n    filing_period_from: Optional[date] = None\n    filing_period_to: Optional[date] = None\n    due_date_from: Optional[date] = None\n    due_date_to: Optional[date] = None\n    search: Optional[str] = None\n\n\nclass TaxNexusRuleFilterParams(PaginationParams):\n    """Filter parameters for tax nexus rule queries"""\n    jurisdiction_code: Optional[str] = None\n    country: Optional[str] = None\n    nexus_type: Optional[List[NexusType]] = None\n    company_id: Optional[UUID] = None\n    is_active: Optional[bool] = None\n    has_met_threshold: Optional[bool] = None\n    search: Optional[str] = None\n\n\nclass ExchangeRateFilterParams(PaginationParams):\n    """Filter parameters for exchange rate queries"""\n    from_currency: Optional[str] = None\n    to_currency: Optional[str] = None\n    rate_date: Optional[date] = None\n    rate_date_from: Optional[date] = None\n    rate_date_to: Optional[date] = None\n    source: Optional[List[ExchangeRateSource]] = None\n    company_id: Optional[UUID] = None\n    is_active: Optional[bool] = None\n\n\n# ============================================\n# Tax Calculation Schemas\n# ============================================\n\nclass TaxCalculationRequest(BaseResponseModel):\n    """Schema for tax calculation request"""\n    company_id: UUID\n    transaction_date: date\n    \n    # Line items\n    items: List[Dict[str, Any]] = Field(..., description="Line items with taxable amounts")\n    \n    # Ship-to / Bill-to\n    ship_to_country: Optional[str] = None\n    ship_to_state: Optional[str] = None\n    ship_to_county: Optional[str] = None\n    ship_to_city: Optional[str] = None\n    ship_to_postal_code: Optional[str] = None\n    \n    # Ship-from\n    ship_from_country: Optional[str] = None\n    ship_from_state: Optional[str] = None\n    \n    # Customer\n    customer_id: Optional[UUID] = None\n    customer_tax_exempt: bool = Field(default=False)\n    customer_tax_code: Optional[str] = None\n    \n    # Currency\n    currency: str = Field(default="USD")\n\n\nclass TaxCalculationLineResponse(BaseResponseModel):\n    """Schema for tax calculation line response"""\n    line_number: int\n    taxable_amount: Decimal\n    tax_amount: Decimal\n    total_amount: Decimal\n    \n    # Tax breakdown\n    tax_details: List[Dict[str, Any]] = Field(default_factory=list)\n    \n    # Jurisdiction\n    jurisdiction_code: Optional[str] = None\n    jurisdiction_name: Optional[str] = None\n\n\nclass TaxCalculationResponse(BaseResponseModel):\n    """Schema for tax calculation response"""\n    company_id: UUID\n    transaction_date: date\n    currency: str\n    \n    # Totals\n    total_taxable_amount: Decimal = Decimal("0")\n    total_tax_amount: Decimal = Decimal("0")\n    grand_total: Decimal = Decimal("0")\n    \n    # Line results\n    lines: List[TaxCalculationLineResponse] = Field(default_factory=list)\n    \n    # Tax breakdown by jurisdiction\n    by_jurisdiction: Dict[str, Decimal] = Field(default_factory=dict)\n    \n    # Tax breakdown by type\n    by_tax_type: Dict[str, Decimal] = Field(default_factory=dict)\n    \n    # Nexus warnings\n    nexus_warnings: List[Dict[str, Any]] = Field(default_factory=list)\n    \n    calculated_at: datetime\n\n\n# ============================================\n# Tax Summary Reports\n# ============================================\n\nclass TaxSummaryResponse(BaseResponseModel):\n    """Schema for tax summary report"""\n    company_id: UUID\n    period_start: date\n    period_end: date\n    currency: str\n    \n    # By tax type\n    by_tax_type: Dict[str, Dict[str, Decimal]] = Field(default_factory=dict)\n    \n    # By jurisdiction\n    by_jurisdiction: List[Dict[str, Any]] = Field(default_factory=list)\n    \n    # Totals\n    total_collected: Decimal = Decimal("0")\n    total_paid: Decimal = Decimal("0")\n    total_adjustments: Decimal = Decimal("0")\n    net_liability: Decimal = Decimal("0")\n    \n    # Filing status\n    pending_filings: int = 0\n    overdue_filings: int = 0\n    \n    # Nexus status\n    active_nexus_count: int = 0\n    threshold_warnings: int = 0\n    \n    generated_at: datetime\n\n\nclass TaxLiabilityReportResponse(BaseResponseModel):\n    """Schema for tax liability report"""\n    company_id: UUID\n    as_of_date: date\n    currency: str\n    \n    # By tax type\n    liabilities_by_type: Dict[str, Decimal] = Field(default_factory=dict)\n    \n    # By jurisdiction\n    liabilities_by_jurisdiction: List[Dict[str, Any]] = Field(default_factory=list)\n    \n    # Summary\n    total_liability: Decimal = Decimal("0")\n    total_paid: Decimal = Decimal("0")\n    outstanding_liability: Decimal = Decimal("0")\n    \n    # Due dates\n    upcoming_due_dates: List[Dict[str, Any]] = Field(default_factory=list)\n    \n    generated_at: datetime\n\n\n# Update forward references\nTaxRateResponse.model_rebuild()\nTaxCodeResponse.model_rebuild()\nTaxFilingResponse.model_rebuild()\n</create-file>\n</function_calls>'}
{'role': 'user', 'content': '<tool_result> <create-file> ToolResult(success=True, output="File \'backend/app/schemas/tax.py\' created successfully.") </create-file> </tool_result>'}
{'role': 'assistant', 'content': 'Let me continue creating the remaining schemas. Now I\'ll create the Workflow schemas for the automation engine:\n\n\n<function_calls><create-file file_path="backend/app/schemas/workflow.py">"""\nWorkflow & Automation Engine Schemas for SAMMS ENTERPRISE SOVEREIGN OPERATING SYSTEM\nVisual workflow builder, automation rules, notifications, and approvals\n"""\nfrom datetime import datetime, date\nfrom typing import Optional, List, Dict, Any, Union, Callable\nfrom uuid import UUID\nfrom decimal import Decimal\nfrom enum import Enum\n\nfrom pydantic import Field, field_validator, model_validator\n\nfrom .base import (\n    BaseResponseModel,\n    PaginationParams,\n    PaginatedResponse,\n    SuccessResponse,\n    ErrorResponse,\n    TimestampMixin,\n    IDMixin,\n)\n\n\nclass WorkflowStatus(str, Enum):\n    """Workflow status enumeration"""\n    DRAFT = "draft"\n    ACTIVE = "active"\n    INACTIVE = "inactive"\n    ARCHIVED = "archived"\n    ERROR = "error"\n\n\nclass WorkflowExecutionStatus(str, Enum):\n    """Workflow execution status enumeration"""\n    PENDING = "pending"\n    RUNNING = "running"\n    COMPLETED = "completed"\n    FAILED = "failed"\n    CANCELLED = "cancelled"\n    PAUSED = "paused"\n    WAITING = "waiting"\n\n\nclass TriggerType(str, Enum):\n    """Trigger type enumeration"""\n    MANUAL = "manual"\n    SCHEDULED = "scheduled"\n    EVENT = "event"\n    WEBHOOK = "webhook"\n    API = "api"\n    CONDITION = "condition"\n    THRESHOLD = "threshold"\n    EMAIL = "email"\n    FORM_SUBMIT = "form_submit"\n\n\nclass ActionType(str, Enum):\n    """Action type enumeration"""\n    CREATE_RECORD = "create_record"\n    UPDATE_RECORD = "update_record"\n    DELETE_RECORD = "delete_record"\n    SEND_EMAIL = "send_email"\n    SEND_SMS = "send_sms"\n    SEND_NOTIFICATION = "send_notification"\n    CREATE_TASK = "create_task"\n    ASSIGN_TASK = "assign_task"\n    APPROVE = "approve"\n    REJECT = "reject"\n    TRANSFORM = "transform"\n    CALCULATE = "calculate"\n    CALL_API = "call_api"\n    WEBHOOK = "webhook"\n    GENERATE_REPORT = "generate_report"\n    CREATE_JOURNAL_ENTRY = "create_journal_entry"\n    POST_TO_GL = "post_to_gl"\n    DELAY = "delay"\n    WAIT = "wait"\n    BRANCH = "branch"\n    LOOP = "loop"\n    PARALLEL = "parallel"\n    SCRIPT = "script"\n    AI_SUGGEST = "ai_suggest"\n    AI_ANALYZE = "ai_analyze"\n    LOG = "log"\n    CUSTOM = "custom"\n\n\nclass ConditionOperator(str, Enum):\n    """Condition operator enumeration"""\n    EQUALS = "equals"\n    NOT_EQUALS = "not_equals"\n    GREATER_THAN = "greater_than"\n    LESS_THAN = "less_than"\n    GREATER_THAN_OR_EQUAL = "greater_than_or_equal"\n    LESS_THAN_OR_EQUAL = "less_than_or_equal"\n    CONTAINS = "contains"\n    NOT_CONTAINS = "not_contains"\n    STARTS_WITH = "starts_with"\n    ENDS_WITH = "ends_with"\n    IS_EMPTY = "is_empty"\n    IS_NOT_EMPTY = "is_not_empty"\n    IS_NULL = "is_null"\n    IS_NOT_NULL = "is_not_null"\n    IN = "in"\n    NOT_IN = "not_in"\n    BETWEEN = "between"\n    MATCHES = "matches"\n    BEFORE = "before"\n    AFTER = "after"\n    ON_OR_BEFORE = "on_or_before"\n    ON_OR_AFTER = "on_or_after"\n\n\nclass LogicalOperator(str, Enum):\n    """Logical operator enumeration"""\n    AND = "and"\n    OR = "or"\n    NOT = "not"\n\n\nclass NotificationType(str, Enum):\n    """Notification type enumeration"""\n    INFO = "info"\n    SUCCESS = "success"\n    WARNING = "warning"\n    ERROR = "error"\n    REMINDER = "reminder"\n    ALERT = "alert"\n    TASK = "task"\n    APPROVAL = "approval"\n    SYSTEM = "system"\n\n\nclass NotificationPriority(str, Enum):\n    """Notification priority enumeration"""\n    LOW = "low"\n    NORMAL = "normal"\n    HIGH = "high"\n    URGENT = "urgent"\n\n\nclass ApprovalStatus(str, Enum):\n    """Approval status enumeration"""\n    PENDING = "pending"\n    APPROVED = "approved"\n    REJECTED = "rejected"\n    CANCELLED = "cancelled"\n    ESCALATED = "escalated"\n    DELEGATED = "delegated"\n\n\nclass AutomationRuleStatus(str, Enum):\n    """Automation rule status enumeration"""\n    ACTIVE = "active"\n    INACTIVE = "inactive"\n    DRAFT = "draft"\n    ARCHIVED = "archived"\n\n\n# ============================================\n# Workflow Trigger Schemas\n# ============================================\n\nclass WorkflowTriggerBase(BaseResponseModel):\n    """Base schema for workflow trigger"""\n    trigger_type: TriggerType = Field(..., description="Type of trigger")\n    name: Optional[str] = Field(None, max_length=200)\n    description: Optional[str] = Field(None, max_length=2000)\n    \n    # Configuration\n    config: Dict[str, Any] = Field(default_factory=dict, description="Trigger configuration")\n    \n    # Schedule (for scheduled triggers)\n    schedule_cron: Optional[str] = Field(None, max_length=100, description="Cron expression")\n    schedule_timezone: Optional[str] = Field(None, max_length=50)\n    \n    # Event (for event triggers)\n    event_type: Optional[str] = Field(None, max_length=100, description="Event type to listen for")\n    event_filter: Optional[Dict[str, Any]] = None\n    \n    # Conditions\n    conditions: Optional[List[Dict[str, Any]]] = None\n    \n    # Enabled\n    is_enabled: bool = Field(default=True)\n    \n    metadata: Optional[Dict[str, Any]] = None\n\n\nclass WorkflowTriggerCreate(WorkflowTriggerBase):\n    """Schema for creating a workflow trigger"""\n    pass\n\n\nclass WorkflowTriggerResponse(WorkflowTriggerBase, TimestampMixin, IDMixin):\n    """Schema for workflow trigger response"""\n    workflow_id: UUID\n    trigger_count: int = Field(default=0, description="Number of times triggered")\n    last_triggered_at: Optional[datetime] = None\n    \n    class Config:\n        from_attributes = True\n\n\n# ============================================\n# Workflow Action Schemas\n# ============================================\n\nclass WorkflowActionBase(BaseResponseModel):\n    """Base schema for workflow action"""\n    action_type: ActionType = Field(..., description="Type of action")\n    name: str = Field(..., min_length=1, max_length=200)\n    description: Optional[str] = Field(None, max_length=2000)\n    \n    # Order\n    order: int = Field(default=0, ge=0, description="Execution order")\n    \n    # Configuration\n    config: Dict[str, Any] = Field(default_factory=dict, description="Action configuration")\n    \n    # Input/Output mapping\n    input_mapping: Optional[Dict[str, Any]] = None\n    output_mapping: Optional[Dict[str, Any]] = None\n    \n    # Error handling\n    on_error: Optional[str] = Field(None, description="What to do on error")\n    retry_count: int = Field(default=0, ge=0)\n    retry_delay: int = Field(default=0, ge=0, description="Retry delay in seconds")\n    \n    # Timeout\n    timeout: Optional[int] = Field(None, description="Timeout in seconds")\n    \n    # Conditional execution\n    condition: Optional[Dict[str, Any]] = None\n    \n    metadata: Optional[Dict[str, Any]] = None\n\n\nclass WorkflowActionCreate(WorkflowActionBase):\n    """Schema for creating a workflow action"""\n    pass\n\n\nclass WorkflowActionResponse(WorkflowActionBase, TimestampMixin, IDMixin):\n    """Schema for workflow action response"""\n    workflow_id: UUID\n    \n    class Config:\n        from_attributes = True\n\n\n# ============================================\n# Workflow Schemas\n# ============================================\n\nclass WorkflowBase(BaseResponseModel):\n    """Base schema for workflow"""\n    name: str = Field(..., min_length=1, max_length=200)\n    code: str = Field(..., min_length=1, max_length=50)\n    description: Optional[str] = Field(None, max_length=5000)\n    \n    company_id: UUID = Field(..., description="Company ID")\n    \n    # Category\n    category: Optional[str] = Field(None, max_length=100)\n    module: Optional[str] = Field(None, max_length=100)\n    \n    # Version\n    version: int = Field(default=1, ge=1)\n    \n    # Design\n    is_visual: bool = Field(default=True, description="Created via visual builder")\n    design_data: Optional[Dict[str, Any]] = None\n    \n    # Settings\n    allow_concurrent: bool = Field(default=False, description="Allow concurrent executions")\n    max_concurrent: int = Field(default=1, ge=1)\n    \n    # Error handling\n    default_error_handler: Optional[str] = None\n    notification_on_error: bool = Field(default=True)\n    error_notification_emails: List[str] = Field(default_factory=list)\n    \n    # Timeout\n    execution_timeout: Optional[int] = Field(None, description="Max execution time in seconds")\n    \n    # Audit\n    audit_enabled: bool = Field(default=True)\n    log_level: str = Field(default="info", description="Log level: debug, info, warn, error")\n    \n    metadata: Optional[Dict[str, Any]] = None\n    tags: List[str] = Field(default_factory=list)\n\n\nclass WorkflowCreate(WorkflowBase):\n    """Schema for creating a workflow"""\n    triggers: List[WorkflowTriggerCreate] = Field(default_factory=list)\n    actions: List[WorkflowActionCreate] = Field(default_factory=list)\n    \n    @field_validator(\'code\')\n    @classmethod\n    def validate_code(cls, v: str) -> str:\n        """Validate workflow code format"""\n        import re\n        if not re.match(r\'^[a-zA-Z0-9_-]+$\', v):\n            raise ValueError(\'Code must contain only alphanumeric characters, underscores, and hyphens\')\n        return v.lower()\n\n\nclass WorkflowUpdate(BaseResponseModel):\n    """Schema for updating a workflow"""\n    name: Optional[str] = Field(None, min_length=1, max_length=200)\n    description: Optional[str] = Field(None, max_length=5000)\n    category: Optional[str] = Field(None, max_length=100)\n    module: Optional[str] = Field(None, max_length=100)\n    allow_concurrent: Optional[bool] = None\n    max_concurrent: Optional[int] = Field(None, ge=1)\n    default_error_handler: Optional[str] = None\n    notification_on_error: Optional[bool] = None\n    error_notification_emails: Optional[List[str]] = None\n    execution_timeout: Optional[int] = None\n    audit_enabled: Optional[bool] = None\n    log_level: Optional[str] = None\n    metadata: Optional[Dict[str, Any]] = None\n    tags: Optional[List[str]] = None\n    status: Optional[WorkflowStatus] = None\n    triggers: Optional[List[WorkflowTriggerCreate]] = None\n    actions: Optional[List[WorkflowActionCreate]] = None\n\n\nclass WorkflowResponse(WorkflowBase, TimestampMixin, IDMixin):\n    """Schema for workflow response"""\n    status: WorkflowStatus = Field(default=WorkflowStatus.DRAFT)\n    is_active: bool = Field(default=False)\n    \n    # Statistics\n    execution_count: int = Field(default=0)\n    success_count: int = Field(default=0)\n    failure_count: int = Field(default=0)\n    last_execution_at: Optional[datetime] = None\n    last_execution_status: Optional[WorkflowExecutionStatus] = None\n    \n    # Relationships\n    triggers: List[WorkflowTriggerResponse] = Field(default_factory=list)\n    actions: List[WorkflowActionResponse] = Field(default_factory=list)\n    \n    # Audit\n    created_by: Optional[UUID] = None\n    updated_by: Optional[UUID] = None\n    published_at: Optional[datetime] = None\n    published_by: Optional[UUID] = None\n    \n    class Config:\n        from_attributes = True\n\n\nclass WorkflowListResponse(BaseResponseModel):\n    """Schema for workflow list item"""\n    id: UUID\n    name: str\n    code: str\n    category: Optional[str]\n    status: WorkflowStatus\n    version: int\n    execution_count: int\n    company_id: UUID\n    created_at: datetime\n    created_by: Optional[UUID]\n    \n    class Config:\n        from_attributes = True\n\n\n# ============================================\n# Workflow Execution Schemas\n# ============================================\n\nclass WorkflowExecutionLogBase(BaseResponseModel):\n    """Base schema for workflow execution log"""\n    action_id: Optional[UUID] = None\n    action_name: Optional[str] = None\n    action_type: Optional[ActionType] = None\n    \n    # Status\n    status: str = Field(..., description="started, completed, failed, skipped")\n    \n    # Timing\n    started_at: datetime = Field(..., description="Action start time")\n    completed_at: Optional[datetime] = None\n    duration_ms: Optional[int] = None\n    \n    # Input/Output\n    input_data: Optional[Dict[str, Any]] = None\n    output_data: Optional[Dict[str, Any]] = None\n    \n    # Error\n    error_message: Optional[str] = None\n    error_stack: Optional[str] = None\n    \n    # Retry\n    retry_count: int = Field(default=0)\n\n\nclass WorkflowExecutionLogResponse(WorkflowExecutionLogBase, TimestampMixin, IDMixin):\n    """Schema for workflow execution log response"""\n    execution_id: UUID\n    \n    class Config:\n        from_attributes = True\n\n\nclass WorkflowExecutionBase(BaseResponseModel):\n    """Base schema for workflow execution"""\n    workflow_id: UUID = Field(..., description="Workflow ID")\n    company_id: UUID = Field(..., description="Company ID")\n    \n    # Trigger info\n    trigger_type: TriggerType = Field(..., description="How execution was triggered")\n    triggered_by: Optional[UUID] = Field(None, description="User who triggered (if manual)")\n    trigger_data: Optional[Dict[str, Any]] = None\n    \n    # Context\n    context: Dict[str, Any] = Field(default_factory=dict, description="Execution context/variables")\n    \n    # Source\n    source_type: Optional[str] = Field(None, description="Source entity type")\n    source_id: Optional[UUID] = Field(None, description="Source entity ID")\n    \n    # Status\n    status: WorkflowExecutionStatus = Field(default=WorkflowExecutionStatus.PENDING)\n    \n    # Progress\n    total_actions: int = Field(default=0)\n    completed_actions: int = Field(default=0)\n    current_action: Optional[str] = None\n    \n    # Timing\n    started_at: Optional[datetime] = None\n    completed_at: Optional[datetime] = None\n    duration_ms: Optional[int] = None\n    \n    # Result\n    result_data: Optional[Dict[str, Any]] = None\n    error_message: Optional[str] = None\n    error_action_id: Optional[UUID] = None\n    \n    # Parent execution (for sub-workflows)\n    parent_execution_id: Optional[UUID] = None\n    \n    metadata: Optional[Dict[str, Any]] = None\n\n\nclass WorkflowExecutionCreate(BaseResponseModel):\n    """Schema for starting a workflow execution"""\n    workflow_id: UUID\n    trigger_type: TriggerType = Field(default=TriggerType.MANUAL)\n    context: Dict[str, Any] = Field(default_factory=dict)\n    source_type: Optional[str] = None\n    source_id: Optional[UUID] = None\n    async_execution: bool = Field(default=True)\n\n\nclass WorkflowExecutionResponse(WorkflowExecutionBase, TimestampMixin, IDMixin):\n    """Schema for workflow execution response"""\n    execution_number: str = Field(default="")\n    workflow_name: str = Field(default="")\n    workflow_version: int = Field(default=1)\n    \n    # Logs\n    logs: List[WorkflowExecutionLogResponse] = Field(default_factory=list)\n    \n    class Config:\n        from_attributes = True\n\n\nclass WorkflowExecutionListResponse(BaseResponseModel):\n    """Schema for workflow execution list item"""\n    id: UUID\n    execution_number: str\n    workflow_id: UUID\n    workflow_name: str\n    trigger_type: TriggerType\n    status: WorkflowExecutionStatus\n    started_at: Optional[datetime]\n    completed_at: Optional[datetime]\n    duration_ms: Optional[int]\n    company_id: UUID\n    created_at: datetime\n    \n    class Config:\n        from_attributes = True\n\n\n# ============================================\n# Automation Rule Schemas\n# ============================================\n\nclass AutomationConditionBase(BaseResponseModel):\n    """Base schema for automation condition"""\n    field: str = Field(..., min_length=1, max_length=200, description="Field to check")\n    operator: ConditionOperator = Field(..., description="Comparison operator")\n    value: Any = Field(..., description="Value to compare against")\n    \n    # For between operator\n    value_end: Optional[Any] = None\n\n\nclass AutomationConditionGroupBase(BaseResponseModel):\n    """Base schema for condition group"""\n    logical_operator: LogicalOperator = Field(default=LogicalOperator.AND)\n    conditions: List[Union[AutomationConditionBase, "AutomationConditionGroupBase"]] = Field(\n        default_factory=list\n    )\n\n\nclass AutomationActionConfigBase(BaseResponseModel):\n    """Base schema for automation action config"""\n    action_type: ActionType = Field(..., description="Type of action")\n    config: Dict[str, Any] = Field(default_factory=dict, description="Action configuration")\n    order: int = Field(default=0, ge=0)\n\n\nclass AutomationRuleBase(BaseResponseModel):\n    """Base schema for automation rule"""\n    name: str = Field(..., min_length=1, max_length=200)\n    code: str = Field(..., min_length=1, max_length=50)\n    description: Optional[str] = Field(None, max_length=2000)\n    \n    company_id: UUID = Field(..., description="Company ID")\n    \n    # Trigger\n    trigger_type: TriggerType = Field(..., description="Trigger type")\n    trigger_config: Dict[str, Any] = Field(default_factory=dict)\n    \n    # Module/Entity\n    module: Optional[str] = Field(None, max_length=100)\n    entity_type: Optional[str] = Field(None, max_length=100)\n    \n    # Conditions\n    conditions: Optional[AutomationConditionGroupBase] = None\n    \n    # Actions\n    actions: List[Dict[str, Any]] = Field(default_factory=list)\n    \n    # Schedule\n    schedule_cron: Optional[str] = None\n    \n    # Settings\n    priority: int = Field(default=100, ge=0)\n    \n    metadata: Optional[Dict[str, Any]] = None\n\n\nclass AutomationRuleCreate(AutomationRuleBase):\n    """Schema for creating an automation rule"""\n    pass\n\n\nclass AutomationRuleUpdate(BaseResponseModel):\n    """Schema for updating an automation rule"""\n    name: Optional[str] = Field(None, min_length=1, max_length=200)\n    description: Optional[str] = Field(None, max_length=2000)\n    trigger_config: Optional[Dict[str, Any]] = None\n    conditions: Optional[AutomationConditionGroupBase] = None\n    actions: Optional[List[Dict[str, Any]]] = None\n    schedule_cron: Optional[str] = None\n    priority: Optional[int] = Field(None, ge=0)\n    metadata: Optional[Dict[str, Any]] = None\n    status: Optional[AutomationRuleStatus] = None\n\n\nclass AutomationRuleResponse(AutomationRuleBase, TimestampMixin, IDMixin):\n    """Schema for automation rule response"""\n    status: AutomationRuleStatus = Field(default=AutomationRuleStatus.ACTIVE)\n    \n    # Statistics\n    execution_count: int = Field(default=0)\n    success_count: int = Field(default=0)\n    failure_count: int = Field(default=0)\n    last_execution_at: Optional[datetime] = None\n    \n    # Audit\n    created_by: Optional[UUID] = None\n    updated_by: Optional[UUID] = None\n    \n    class Config:\n        from_attributes = True\n\n\nclass AutomationRuleListResponse(BaseResponseModel):\n    """Schema for automation rule list item"""\n    id: UUID\n    name: str\n    code: str\n    trigger_type: TriggerType\n    entity_type: Optional[str]\n    status: AutomationRuleStatus\n    execution_count: int\n    company_id: UUID\n    created_at: datetime\n    \n    class Config:\n        from_attributes = True\n\n\n# ============================================\n# Notification Schemas\n# ============================================\n\nclass NotificationBase(BaseResponseModel):\n    """Base schema for notification"""\n    user_id: UUID = Field(..., description="Target user ID")\n    company_id: UUID = Field(..., description="Company ID")\n    \n    # Content\n    title: str = Field(..., min_length=1, max_length=200)\n    message: str = Field(..., min_length=1, max_length=2000)\n    \n    # Type and priority\n    notification_type: NotificationType = Field(default=NotificationType.INFO)\n    priority: NotificationPriority = Field(default=NotificationPriority.NORMAL)\n    \n    # Link\n    link_url: Optional[str] = Field(None, max_length=1000)\n    link_text: Optional[str] = Field(None, max_length=200)\n    \n    # Source\n    source_type: Optional[str] = Field(None, max_length=100)\n    source_id: Optional[UUID] = None\n    \n    # Action buttons\n    actions: List[Dict[str, Any]] = Field(default_factory=list)\n    \n    # Delivery\n    delivery_channels: List[str] = Field(default_factory=lambda: ["in_app"])\n    \n    # Read status\n    is_read: bool = Field(default=False)\n    read_at: Optional[datetime] = None\n    \n    # Dismissed\n    is_dismissed: bool = Field(default=False)\n    dismissed_at: Optional[datetime] = None\n    \n    # Expiry\n    expires_at: Optional[datetime] = None\n    \n    metadata: Optional[Dict[str, Any]] = None\n\n\nclass NotificationCreate(NotificationBase):\n    """Schema for creating a notification"""\n    send_email: bool = Field(default=False)\n    send_sms: bool = Field(default=False)\n\n\nclass NotificationUpdate(BaseResponseModel):\n    """Schema for updating a notification"""\n    is_read: Optional[bool] = None\n    is_dismissed: Optional[bool] = None\n\n\nclass NotificationResponse(NotificationBase, TimestampMixin, IDMixin):\n    """Schema for notification response"""\n    \n    class Config:\n        from_attributes = True\n\n\nclass NotificationListResponse(BaseResponseModel):\n    """Schema for notification list item"""\n    id: UUID\n    title: str\n    message: str\n    notification_type: NotificationType\n    priority: NotificationPriority\n    is_read: bool\n    source_type: Optional[str]\n    created_at: datetime\n    \n    class Config:\n        from_attributes = True\n\n\n# ============================================\n# Approval Workflow Schemas\n# ============================================\n\nclass ApprovalStepBase(BaseResponseModel):\n    """Base schema for approval step"""\n    name: str = Field(..., min_length=1, max_length=200)\n    description: Optional[str] = Field(None, max_length=1000)\n    \n    # Order\n    order: int = Field(default=0, ge=0)\n    \n    # Approvers\n    approver_type: str = Field(..., description="user, role, manager, group")\n    approver_ids: List[UUID] = Field(default_factory=list)\n    role_ids: List[UUID] = Field(default_factory=list)\n    \n    # Settings\n    require_all: bool = Field(default=False, description="Require all approvers")\n    allow_delegation: bool = Field(default=True)\n    allow_reassignment: bool = Field(default=True)\n    \n    # Timeout\n    timeout_hours: Optional[int] = None\n    timeout_action: Optional[str] = Field(None, description="approve, reject, escalate")\n    escalate_to: Optional[UUID] = None\n    \n    # Actions on approval/rejection\n    on_approve_actions: List[Dict[str, Any]] = Field(default_factory=list)\n    on_reject_actions: List[Dict[str, Any]] = Field(default_factory=list)\n\n\nclass ApprovalStepCreate(ApprovalStepBase):\n    """Schema for creating an approval step"""\n    pass\n\n\nclass ApprovalStepResponse(ApprovalStepBase, TimestampMixin, IDMixin):\n    """Schema for approval step response"""\n    approval_workflow_id: UUID\n    \n    class Config:\n        from_attributes = True\n\n\nclass ApprovalWorkflowBase(BaseResponseModel):\n    """Base schema for approval workflow"""\n    name: str = Field(..., min_length=1, max_length=200)\n    code: str = Field(..., min_length=1, max_length=50)\n    description: Optional[str] = Field(None, max_length=2000)\n    \n    company_id: UUID = Field(..., description="Company ID")\n    \n    # Entity\n    entity_type: Optional[str] = Field(None, max_length=100)\n    \n    # Settings\n    allow_request_changes: bool = Field(default=True)\n    allow_cancel: bool = Field(default=True)\n    auto_cancel_on_rejection: bool = Field(default=True)\n    \n    # Notifications\n    notify_on_submit: bool = Field(default=True)\n    notify_on_approve: bool = Field(default=True)\n    notify_on_reject: bool = Field(default=True)\n    notify_on_complete: bool = Field(default=True)\n    \n    metadata: Optional[Dict[str, Any]] = None\n\n\nclass ApprovalWorkflowCreate(ApprovalWorkflowBase):\n    """Schema for creating an approval workflow"""\n    steps: List[ApprovalStepCreate] = Field(default_factory=list)\n\n\nclass ApprovalWorkflowUpdate(BaseResponseModel):\n    """Schema for updating an approval workflow"""\n    name: Optional[str] = Field(None, min_length=1, max_length=200)\n    description: Optional[str] = Field(None, max_length=2000)\n    entity_type: Optional[str] = Field(None, max_length=100)\n    allow_request_changes: Optional[bool] = None\n    allow_cancel: Optional[bool] = None\n    auto_cancel_on_rejection: Optional[bool] = None\n    notify_on_submit: Optional[bool] = None\n    notify_on_approve: Optional[bool] = None\n    notify_on_reject: Optional[bool] = None\n    notify_on_complete: Optional[bool] = None\n    metadata: Optional[Dict[str, Any]] = None\n    steps: Optional[List[ApprovalStepCreate]] = None\n    is_active: Optional[bool] = None\n\n\nclass ApprovalWorkflowResponse(ApprovalWorkflowBase, TimestampMixin, IDMixin):\n    """Schema for approval workflow response"""\n    is_active: bool = Field(default=True)\n    version: int = Field(default=1)\n    \n    # Statistics\n    total_submissions: int = Field(default=0)\n    approved_count: int = Field(default=0)\n    rejected_count: int = Field(default=0)\n    pending_count: int = Field(default=0)\n    \n    # Steps\n    steps: List[ApprovalStepResponse] = Field(default_factory=list)\n    \n    class Config:\n        from_attributes = True\n\n\nclass ApprovalInstanceBase(BaseResponseModel):\n    """Base schema for approval instance"""\n    approval_workflow_id: UUID = Field(..., description="Approval workflow ID")\n    company_id: UUID = Field(..., description="Company ID")\n    \n    # Entity being approved\n    entity_type: str = Field(..., max_length=100)\n    entity_id: UUID = Field(..., description="Entity ID")\n    \n    # Submitter\n    submitted_by: UUID = Field(..., description="User who submitted")\n    submitted_at: datetime = Field(..., description="Submission time")\n    \n    # Status\n    status: ApprovalStatus = Field(default=ApprovalStatus.PENDING)\n    \n    # Current step\n    current_step_id: Optional[UUID] = None\n    current_step_order: int = Field(default=0)\n    \n    # Completion\n    completed_at: Optional[datetime] = None\n    completed_by: Optional[UUID] = None\n    \n    # Comments\n    comments: Optional[str] = Field(None, max_length=5000)\n    \n    metadata: Optional[Dict[str, Any]] = None\n\n\nclass ApprovalInstanceCreate(BaseResponseModel):\n    """Schema for creating an approval instance"""\n    approval_workflow_id: UUID\n    entity_type: str\n    entity_id: UUID\n    comments: Optional[str] = Field(None, max_length=5000)\n\n\nclass ApprovalInstanceResponse(ApprovalInstanceBase, TimestampMixin, IDMixin):\n    """Schema for approval instance response"""\n    instance_number: str = Field(default="")\n    workflow_name: str = Field(default="")\n    entity_name: Optional[str] = None\n    submitter_name: str = Field(default="")\n    \n    # Steps with status\n    steps_status: List[Dict[str, Any]] = Field(default_factory=list)\n    \n    class Config:\n        from_attributes = True\n\n\nclass ApprovalActionRequest(BaseResponseModel):\n    """Schema for approval action"""\n    action: str = Field(..., description="approve, reject, delegate, request_changes")\n    comments: Optional[str] = Field(None, max_length=2000)\n    delegate_to: Optional[UUID] = None\n\n\n# ============================================\n# Query Parameters\n# ============================================\n\nclass WorkflowFilterParams(PaginationParams):\n    """Filter parameters for workflow queries"""\n    name: Optional[str] = None\n    code: Optional[str] = None\n    status: Optional[List[WorkflowStatus]] = None\n    category: Optional[str] = None\n    module: Optional[str] = None\n    company_id: Optional[UUID] = None\n    is_active: Optional[bool] = None\n    created_by: Optional[UUID] = None\n    search: Optional[str] = None\n    tags: Optional[List[str]] = None\n\n\nclass WorkflowExecutionFilterParams(PaginationParams):\n    """Filter parameters for workflow execution queries"""\n    workflow_id: Optional[UUID] = None\n    status: Optional[List[WorkflowExecutionStatus]] = None\n    trigger_type: Optional[List[TriggerType]] = None\n    company_id: Optional[UUID] = None\n    source_type: Optional[str] = None\n    source_id: Optional[UUID] = None\n    triggered_by: Optional[UUID] = None\n    started_after: Optional[datetime] = None\n    started_before: Optional[datetime] = None\n    search: Optional[str] = None\n\n\nclass AutomationRuleFilterParams(PaginationParams):\n    """Filter parameters for automation rule queries"""\n    name: Optional[str] = None\n    code: Optional[str] = None\n    status: Optional[List[AutomationRuleStatus]] = None\n    trigger_type: Optional[List[TriggerType]] = None\n    module: Optional[str] = None\n    entity_type: Optional[str] = None\n    company_id: Optional[UUID] = None\n    search: Optional[str] = None\n\n\nclass NotificationFilterParams(PaginationParams):\n    """Filter parameters for notification queries"""\n    user_id: Optional[UUID] = None\n    company_id: Optional[UUID] = None\n    notification_type: Optional[List[NotificationType]] = None\n    priority: Optional[List[NotificationPriority]] = None\n    is_read: Optional[bool] = None\n    is_dismissed: Optional[bool] = None\n    source_type: Optional[str] = None\n    source_id: Optional[UUID] = None\n    created_after: Optional[datetime] = None\n    created_before: Optional[datetime] = None\n\n\nclass ApprovalWorkflowFilterParams(PaginationParams):\n    """Filter parameters for approval workflow queries"""\n    name: Optional[str] = None\n    code: Optional[str] = None\n    entity_type: Optional[str] = None\n    company_id: Optional[UUID] = None\n    is_active: Optional[bool] = None\n    search: Optional[str] = None\n\n\nclass ApprovalInstanceFilterParams(PaginationParams):\n    """Filter parameters for approval instance queries"""\n    approval_workflow_id: Optional[UUID] = None\n    status: Optional[List[ApprovalStatus]] = None\n    entity_type: Optional[str] = None\n    entity_id: Optional[UUID] = None\n    company_id: Optional[UUID] = None\n    submitted_by: Optional[UUID] = None\n    submitted_after: Optional[datetime] = None\n    submitted_before: Optional[datetime] = None\n    pending_approval_by: Optional[UUID] = None\n    search: Optional[str] = None\n\n\n# ============================================\n# Workflow Statistics\n# ============================================\n\nclass WorkflowStatisticsResponse(BaseResponseModel):\n    """Schema for workflow statistics"""\n    company_id: UUID\n    period_start: date\n    period_end: date\n    \n    # Workflows\n    total_workflows: int = 0\n    active_workflows: int = 0\n    \n    # Executions\n    total_executions: int = 0\n    successful_executions: int = 0\n    failed_executions: int = 0\n    average_duration_ms: int = 0\n    \n    # By status\n    by_status: Dict[str, int] = Field(default_factory=dict)\n    \n    # By trigger type\n    by_trigger_type: Dict[str, int] = Field(default_factory=dict)\n    \n    # Top workflows\n    most_executed: List[Dict[str, Any]] = Field(default_factory=list)\n    most_failed: List[Dict[str, Any]] = Field(default_factory=list)\n    \n    generated_at: datetime\n\n\n# Update forward references\nAutomationConditionGroupBase.model_rebuild()\n</create-file>\n</function_calls>'}
{'role': 'user', 'content': '<tool_result> <create-file> ToolResult(success=True, output="File \'backend/app/schemas/workflow.py\' created successfully.") </create-file> </tool_result>'}
{'role': 'assistant', 'content': 'Let me continue with the remaining schemas. I\'ll create the Legal schemas for contract lifecycle management:\n\n\n<function_calls><create-file file_path="backend/app/schemas/legal.py">"""\nLegal & Contract Lifecycle Management Schemas for SAMMS ENTERPRISE SOVEREIGN OPERATING SYSTEM\nLegal entities, contracts, documents, matters, and intellectual property\n"""\nfrom datetime import datetime, date\nfrom typing import Optional, List, Dict, Any, Union\nfrom uuid import UUID\nfrom decimal import Decimal\nfrom enum import Enum\n\nfrom pydantic import Field, field_validator, model_validator\n\nfrom .base import (\n    BaseResponseModel,\n    PaginationParams,\n    PaginatedResponse,\n    SuccessResponse,\n    ErrorResponse,\n    Address,\n    ContactInfo,\n    TimestampMixin,\n    IDMixin,\n)\n\n\nclass LegalEntityType(str, Enum):\n    """Legal entity type enumeration"""\n    CORPORATION = "corporation"\n    LLC = "llc"\n    PARTNERSHIP = "partnership"\n    SOLE_PROPRIETORSHIP = "sole_proprietorship"\n    NON_PROFIT = "non_profit"\n    TRUST = "trust"\n    COOPERATIVE = "cooperative"\n    JOINT_VENTURE = "joint_venture"\n    HOLDING_COMPANY = "holding_company"\n    SUBSIDIARY = "subsidiary"\n    BRANCH = "branch"\n    GOVERNMENT = "government"\n    OTHER = "other"\n\n\nclass ContractType(str, Enum):\n    """Contract type enumeration"""\n    SALES = "sales"\n    PURCHASE = "purchase"\n    SERVICE = "service"\n    EMPLOYMENT = "employment"\n    CONSULTING = "consulting"\n    LEASE = "lease"\n    LICENSE = "license"\n    NDA = "nda"\n    PARTNERSHIP = "partnership"\n    JOINT_VENTURE = "joint_venture"\n    DISTRIBUTION = "distribution"\n    FRANCHISE = "franchise"\n    LOAN = "loan"\n    INVESTMENT = "investment"\n    INSURANCE = "insurance"\n    SOFTWARE = "software"\n    SUPPLY = "supply"\n    MAINTENANCE = "maintenance"\n    MARKETING = "marketing"\n    ADVERTISING = "advertising"\n    OTHER = "other"\n\n\nclass ContractStatus(str, Enum):\n    """Contract status enumeration"""\n    DRAFT = "draft"\n    NEGOTIATION = "negotiation"\n    PENDING_REVIEW = "pending_review"\n    PENDING_SIGNATURE = "pending_signature"\n    ACTIVE = "active"\n    EXPIRED = "expired"\n    TERMINATED = "terminated"\n    CANCELLED = "cancelled"\n    RENEWED = "renewed"\n    AMENDED = "amended"\n    ARCHIVED = "archived"\n\n\nclass ContractPriority(str, Enum):\n    """Contract priority enumeration"""\n    LOW = "low"\n    NORMAL = "normal"\n    HIGH = "high"\n    CRITICAL = "critical"\n\n\nclass DocumentType(str, Enum):\n    """Document type enumeration"""\n    CONTRACT = "contract"\n    AMENDMENT = "amendment"\n    ADDENDUM = "addendum"\n    EXHIBIT = "exhibit"\n    SCHEDULE = "schedule"\n    NOTICE = "notice"\n    CORRESPONDENCE = "correspondence"\n    LEGAL_OPINION = "legal_opinion"\n    COURT_FILING = "court_filing"\n    REGULATORY_FILING = "regulatory_filing"\n    CERTIFICATE = "certificate"\n    LICENSE = "license"\n    PERMIT = "permit"\n    POLICY = "policy"\n    PROCEDURE = "procedure"\n    REPORT = "report"\n    MINUTES = "minutes"\n    RESOLUTION = "resolution"\n    OTHER = "other"\n\n\nclass MatterType(str, Enum):\n    """Legal matter type enumeration"""\n    LITIGATION = "litigation"\n    ARBITRATION = "arbitration"\n    MEDIATION = "mediation"\n    REGULATORY = "regulatory"\n    TRANSACTION = "transaction"\n    INTELLECTUAL_PROPERTY = "intellectual_property"\n    EMPLOYMENT = "employment"\n    CORPORATE = "corporate"\n    REAL_ESTATE = "real_estate"\n    TAX = "tax"\n    COMPLIANCE = "compliance"\n    BANKRUPTCY = "bankruptcy"\n    IMMIGRATION = "immigration"\n    ENVIRONMENTAL = "environmental"\n    OTHER = "other"\n\n\nclass MatterStatus(str, Enum):\n    """Legal matter status enumeration"""\n    NEW = "new"\n    OPEN = "open"\n    IN_PROGRESS = "in_progress"\n    PENDING = "pending"\n    SETTLED = "settled"\n    CLOSED = "closed"\n    ARCHIVED = "archived"\n    ON_HOLD = "on_hold"\n\n\nclass MatterPriority(str, Enum):\n    """Matter priority enumeration"""\n    LOW = "low"\n    NORMAL = "normal"\n    HIGH = "high"\n    URGENT = "urgent"\n    CRITICAL = "critical"\n\n\nclass IPType(str, Enum):\n    """Intellectual property type enumeration"""\n    PATENT = "patent"\n    TRADEMARK = "trademark"\n    COPYRIGHT = "copyright"\n    TRADE_SECRET = "trade_secret"\n    DOMAIN = "domain"\n    INDUSTRIAL_DESIGN = "industrial_design"\n    PLANT_VARIETY = "plant_variety"\n    GEOGRAPHICAL_INDICATION = "geographical_indication"\n    OTHER = "other"\n\n\nclass IPStatus(str, Enum):\n    """IP status enumeration"""\n    PENDING_APPLICATION = "pending_application"\n    REGISTERED = "registered"\n    GRANTED = "granted"\n    ACTIVE = "active"\n    EXPIRED = "expired"\n    ABANDONED = "abandoned"\n    CANCELLED = "cancelled"\n    REVOKED = "revoked"\n    OPPOSED = "opposed"\n    INFRINGEMENT = "infringement"\n\n\n# ============================================\n# Legal Entity Schemas\n# ============================================\n\nclass LegalEntityBase(BaseResponseModel):\n    """Base schema for legal entity"""\n    name: str = Field(..., min_length=1, max_length=200)\n    legal_name: str = Field(..., min_length=1, max_length=200)\n    entity_type: LegalEntityType = Field(..., description="Legal entity type")\n    \n    company_id: UUID = Field(..., description="Associated company ID")\n    \n    # Registration\n    registration_number: Optional[str] = Field(None, max_length=50)\n    registration_date: Optional[date] = None\n    registration_jurisdiction: Optional[str] = Field(None, max_length=100)\n    \n    # Tax\n    tax_id: Optional[str] = Field(None, max_length=50)\n    tax_jurisdiction: Optional[str] = Field(None, max_length=100)\n    \n    # Address\n    registered_address: Optional[Address] = None\n    principal_address: Optional[Address] = None\n    \n    # Contact\n    contact_info: Optional[ContactInfo] = None\n    \n    # Officers/Directors\n    officers: List[Dict[str, Any]] = Field(default_factory=list)\n    directors: List[Dict[str, Any]] = Field(default_factory=list)\n    \n    # Ownership\n    shareholders: List[Dict[str, Any]] = Field(default_factory=list)\n    beneficial_owners: List[Dict[str, Any]] = Field(default_factory=list)\n    \n    # Capital\n    authorized_capital: Optional[Decimal] = None\n    issued_capital: Optional[Decimal] = None\n    shares_outstanding: Optional[int] = None\n    share_class: Optional[str] = Field(None, max_length=50)\n    \n    # Dates\n    incorporation_date: Optional[date] = None\n    dissolution_date: Optional[date] = None\n    \n    # Filing\n    next_annual_filing: Optional[date] = None\n    annual_filing_jurisdiction: Optional[str] = Field(None, max_length=100)\n    \n    notes: Optional[str] = Field(None, max_length=5000)\n    metadata: Optional[Dict[str, Any]] = None\n\n\nclass LegalEntityCreate(LegalEntityBase):\n    """Schema for creating a legal entity"""\n    pass\n\n\nclass LegalEntityUpdate(BaseResponseModel):\n    """Schema for updating a legal entity"""\n    name: Optional[str] = Field(None, min_length=1, max_length=200)\n    legal_name: Optional[str] = Field(None, min_length=1, max_length=200)\n    entity_type: Optional[LegalEntityType] = None\n    registration_number: Optional[str] = Field(None, max_length=50)\n    registration_date: Optional[date] = None\n    registration_jurisdiction: Optional[str] = Field(None, max_length=100)\n    tax_id: Optional[str] = Field(None, max_length=50)\n    tax_jurisdiction: Optional[str] = Field(None, max_length=100)\n    registered_address: Optional[Address] = None\n    principal_address: Optional[Address] = None\n    contact_info: Optional[ContactInfo] = None\n    officers: Optional[List[Dict[str, Any]]] = None\n    directors: Optional[List[Dict[str, Any]]] = None\n    shareholders: Optional[List[Dict[str, Any]]] = None\n    beneficial_owners: Optional[List[Dict[str, Any]]] = None\n    authorized_capital: Optional[Decimal] = None\n    issued_capital: Optional[Decimal] = None\n    shares_outstanding: Optional[int] = None\n    share_class: Optional[str] = Field(None, max_length=50)\n    incorporation_date: Optional[date] = None\n    dissolution_date: Optional[date] = None\n    next_annual_filing: Optional[date] = None\n    annual_filing_jurisdiction: Optional[str] = Field(None, max_length=100)\n    notes: Optional[str] = Field(None, max_length=5000)\n    metadata: Optional[Dict[str, Any]] = None\n    is_active: Optional[bool] = None\n\n\nclass LegalEntityResponse(LegalEntityBase, TimestampMixin, IDMixin):\n    """Schema for legal entity response"""\n    is_active: bool = Field(default=True)\n    \n    # Statistics\n    contract_count: int = Field(default=0)\n    matter_count: int = Field(default=0)\n    active_contracts: int = Field(default=0)\n    \n    class Config:\n        from_attributes = True\n\n\nclass LegalEntityListResponse(BaseResponseModel):\n    """Schema for legal entity list item"""\n    id: UUID\n    name: str\n    legal_name: str\n    entity_type: LegalEntityType\n    registration_number: Optional[str]\n    company_id: UUID\n    is_active: bool\n    created_at: datetime\n    \n    class Config:\n        from_attributes = True\n\n\n# ============================================\n# Contract Schemas\n# ============================================\n\nclass ContractPartyBase(BaseResponseModel):\n    """Base schema for contract party"""\n    party_type: str = Field(..., max_length=50, description="internal, external, vendor, customer")\n    party_role: str = Field(..., max_length=50, description="first_party, second_party, guarantor, etc.")\n    \n    # Party info\n    legal_entity_id: Optional[UUID] = None\n    contact_id: Optional[UUID] = None\n    company_name: Optional[str] = Field(None, max_length=200)\n    contact_name: Optional[str] = Field(None, max_length=200)\n    \n    # Signature\n    signed_by: Optional[UUID] = None\n    signed_at: Optional[datetime] = None\n    signature_method: Optional[str] = Field(None, max_length=50)\n    \n    # Address\n    address: Optional[Address] = None\n\n\nclass ContractPartyCreate(ContractPartyBase):\n    """Schema for creating contract party"""\n    pass\n\n\nclass ContractPartyResponse(ContractPartyBase, TimestampMixin, IDMixin):\n    """Schema for contract party response"""\n    contract_id: UUID\n    \n    class Config:\n        from_attributes = True\n\n\nclass ContractMilestoneBase(BaseResponseModel):\n    """Base schema for contract milestone"""\n    name: str = Field(..., min_length=1, max_length=200)\n    description: Optional[str] = Field(None, max_length=1000)\n    \n    due_date: Optional[date] = None\n    completed_date: Optional[date] = None\n    \n    # Amount\n    amount: Optional[Decimal] = None\n    currency: Optional[str] = Field(None, min_length=3, max_length=3)\n    \n    # Status\n    is_completed: bool = Field(default=False)\n    \n    # Deliverables\n    deliverables: List[str] = Field(default_factory=list)\n    \n    notes: Optional[str] = Field(None, max_length=1000)\n\n\nclass ContractMilestoneCreate(ContractMilestoneBase):\n    """Schema for creating contract milestone"""\n    pass\n\n\nclass ContractMilestoneResponse(ContractMilestoneBase, TimestampMixin, IDMixin):\n    """Schema for contract milestone response"""\n    contract_id: UUID\n    \n    class Config:\n        from_attributes = True\n\n\nclass ContractBase(BaseResponseModel):\n    """Base schema for contract"""\n    contract_number: Optional[str] = Field(None, max_length=50)\n    title: str = Field(..., min_length=1, max_length=300)\n    description: Optional[str] = Field(None, max_length=5000)\n    \n    contract_type: ContractType = Field(..., description="Type of contract")\n    status: ContractStatus = Field(default=ContractStatus.DRAFT)\n    priority: ContractPriority = Field(default=ContractPriority.NORMAL)\n    \n    company_id: UUID = Field(..., description="Company ID")\n    legal_entity_id: Optional[UUID] = Field(None, description="Legal entity for this contract")\n    \n    # Dates\n    effective_date: Optional[date] = None\n    execution_date: Optional[date] = None\n    expiry_date: Optional[date] = None\n    termination_date: Optional[date] = None\n    \n    # Term\n    term_months: Optional[int] = None\n    auto_renew: bool = Field(default=False)\n    renewal_term_months: Optional[int] = None\n    renewal_notice_days: Optional[int] = None\n    \n    # Value\n    contract_value: Optional[Decimal] = None\n    currency: str = Field(default="USD", min_length=3, max_length=3)\n    payment_terms: Optional[str] = Field(None, max_length=200)\n    \n    # Location (for real estate)\n    property_address: Optional[Address] = None\n    \n    # Parent/Related\n    parent_contract_id: Optional[UUID] = None\n    related_contracts: List[UUID] = Field(default_factory=list)\n    \n    # Review\n    reviewed_by: Optional[UUID] = None\n    reviewed_at: Optional[datetime] = None\n    review_notes: Optional[str] = Field(None, max_length=2000)\n    \n    # Owner\n    owner_id: Optional[UUID] = Field(None, description="Contract owner")\n    department_id: Optional[UUID] = None\n    \n    # External reference\n    external_reference: Optional[str] = Field(None, max_length=200)\n    external_system: Optional[str] = Field(None, max_length=100)\n    \n    # Compliance\n    compliance_requirements: List[str] = Field(default_factory=list)\n    required_approvals: List[str] = Field(default_factory=list)\n    \n    # Keywords/Tags\n    keywords: List[str] = Field(default_factory=list)\n    tags: List[str] = Field(default_factory=list)\n    \n    # Alert settings\n    alert_days_before_expiry: int = Field(default=30)\n    alert_on_renewal: bool = Field(default=True)\n    \n    notes: Optional[str] = Field(None, max_length=5000)\n    metadata: Optional[Dict[str, Any]] = None\n\n\nclass ContractCreate(ContractBase):\n    """Schema for creating a contract"""\n    parties: List[ContractPartyCreate] = Field(default_factory=list)\n    milestones: List[ContractMilestoneCreate] = Field(default_factory=list)\n    \n    @field_validator(\'contract_number\')\n    @classmethod\n    def validate_contract_number(cls, v: Optional[str]) -> Optional[str]:\n        if v:\n            return v.upper().strip()\n        return v\n\n\nclass ContractUpdate(BaseResponseModel):\n    """Schema for updating a contract"""\n    contract_number: Optional[str] = Field(None, max_length=50)\n    title: Optional[str] = Field(None, min_length=1, max_length=300)\n    description: Optional[str] = Field(None, max_length=5000)\n    contract_type: Optional[ContractType] = None\n    status: Optional[ContractStatus] = None\n    priority: Optional[ContractPriority] = None\n    legal_entity_id: Optional[UUID] = None\n    effective_date: Optional[date] = None\n    execution_date: Optional[date] = None\n    expiry_date: Optional[date] = None\n    termination_date: Optional[date] = None\n    term_months: Optional[int] = None\n    auto_renew: Optional[bool] = None\n    renewal_term_months: Optional[int] = None\n    renewal_notice_days: Optional[int] = None\n    contract_value: Optional[Decimal] = None\n    currency: Optional[str] = Field(None, min_length=3, max_length=3)\n    payment_terms: Optional[str] = Field(None, max_length=200)\n    property_address: Optional[Address] = None\n    parent_contract_id: Optional[UUID] = None\n    related_contracts: Optional[List[UUID]] = None\n    reviewed_by: Optional[UUID] = None\n    reviewed_at: Optional[datetime] = None\n    review_notes: Optional[str] = Field(None, max_length=2000)\n    owner_id: Optional[UUID] = None\n    department_id: Optional[UUID] = None\n    external_reference: Optional[str] = Field(None, max_length=200)\n    external_system: Optional[str] = Field(None, max_length=100)\n    compliance_requirements: Optional[List[str]] = None\n    required_approvals: Optional[List[str]] = None\n    keywords: Optional[List[str]] = None\n    tags: Optional[List[str]] = None\n    alert_days_before_expiry: Optional[int] = None\n    alert_on_renewal: Optional[bool] = None\n    notes: Optional[str] = Field(None, max_length=5000)\n    metadata: Optional[Dict[str, Any]] = None\n    parties: Optional[List[ContractPartyCreate]] = None\n    milestones: Optional[List[ContractMilestoneCreate]] = None\n\n\nclass ContractResponse(ContractBase, TimestampMixin, IDMixin):\n    """Schema for contract response"""\n    # Calculated\n    days_until_expiry: Optional[int] = None\n    is_expiring_soon: bool = Field(default=False)\n    \n    # Statistics\n    amendment_count: int = Field(default=0)\n    document_count: int = Field(default=0)\n    milestone_count: int = Field(default=0)\n    completed_milestones: int = Field(default=0)\n    \n    # Relationships\n    parties: List[ContractPartyResponse] = Field(default_factory=list)\n    milestones: List[ContractMilestoneResponse] = Field(default_factory=list)\n    \n    # Audit\n    created_by: Optional[UUID] = None\n    updated_by: Optional[UUID] = None\n    \n    class Config:\n        from_attributes = True\n\n\nclass ContractListResponse(BaseResponseModel):\n    """Schema for contract list item"""\n    id: UUID\n    contract_number: Optional[str]\n    title: str\n    contract_type: ContractType\n    status: ContractStatus\n    priority: ContractPriority\n    effective_date: Optional[date]\n    expiry_date: Optional[date]\n    contract_value: Optional[Decimal]\n    currency: str\n    company_id: UUID\n    owner_id: Optional[UUID]\n    created_at: datetime\n    \n    class Config:\n        from_attributes = True\n\n\n# ============================================\n# Document Schemas\n# ============================================\n\nclass DocumentBase(BaseResponseModel):\n    """Base schema for legal document"""\n    title: str = Field(..., min_length=1, max_length=300)\n    document_type: DocumentType = Field(..., description="Type of document")\n    \n    company_id: UUID = Field(..., description="Company ID")\n    \n    # Related entities\n    contract_id: Optional[UUID] = None\n    matter_id: Optional[UUID] = None\n    legal_entity_id: Optional[UUID] = None\n    \n    # Document details\n    document_date: Optional[date] = None\n    effective_date: Optional[date] = None\n    expiry_date: Optional[date] = None\n    \n    # File info\n    file_name: str = Field(..., min_length=1, max_length=255)\n    file_path: Optional[str] = Field(None, max_length=1000)\n    file_size: Optional[int] = Field(None, ge=0)\n    file_type: Optional[str] = Field(None, max_length=100)\n    file_hash: Optional[str] = Field(None, max_length=100)\n    \n    # Version\n    version: int = Field(default=1, ge=1)\n    is_latest: bool = Field(default=True)\n    previous_version_id: Optional[UUID] = None\n    \n    # Security\n    access_level: str = Field(default="company", description="public, company, department, restricted")\n    requires_approval: bool = Field(default=False)\n    \n    # Tags\n    tags: List[str] = Field(default_factory=list)\n    \n    description: Optional[str] = Field(None, max_length=2000)\n    metadata: Optional[Dict[str, Any]] = None\n\n\nclass DocumentCreate(DocumentBase):\n    """Schema for creating a document"""\n    pass\n\n\nclass DocumentUpdate(BaseResponseModel):\n    """Schema for updating a document"""\n    title: Optional[str] = Field(None, min_length=1, max_length=300)\n    document_type: Optional[DocumentType] = None\n    contract_id: Optional[UUID] = None\n    matter_id: Optional[UUID] = None\n    legal_entity_id: Optional[UUID] = None\n    document_date: Optional[date] = None\n    effective_date: Optional[date] = None\n    expiry_date: Optional[date] = None\n    access_level: Optional[str] = None\n    requires_approval: Optional[bool] = None\n    tags: Optional[List[str]] = None\n    description: Optional[str] = Field(None, max_length=2000)\n    metadata: Optional[Dict[str, Any]] = None\n\n\nclass DocumentResponse(DocumentBase, TimestampMixin, IDMixin):\n    """Schema for document response"""\n    is_active: bool = Field(default=True)\n    \n    # Upload info\n    uploaded_by: Optional[UUID] = None\n    \n    # Approval\n    approved_by: Optional[UUID] = None\n    approved_at: Optional[datetime] = None\n    \n    # Download count\n    download_count: int = Field(default=0)\n    last_downloaded_at: Optional[datetime] = None\n    \n    class Config:\n        from_attributes = True\n\n\nclass DocumentListResponse(BaseResponseModel):\n    """Schema for document list item"""\n    id: UUID\n    title: str\n    document_type: DocumentType\n    file_name: str\n    version: int\n    company_id: UUID\n    contract_id: Optional[UUID]\n    matter_id: Optional[UUID]\n    created_at: datetime\n    uploaded_by: Optional[UUID]\n    \n    class Config:\n        from_attributes = True\n\n\n# ============================================\n# Legal Matter Schemas\n# ============================================\n\nclass LegalMatterPartyBase(BaseResponseModel):\n    """Base schema for matter party"""\n    party_type: str = Field(..., max_length=50, description="plaintiff, defendant, witness, counsel, etc.")\n    role: Optional[str] = Field(None, max_length=100)\n    \n    contact_id: Optional[UUID] = None\n    company_name: Optional[str] = Field(None, max_length=200)\n    contact_name: Optional[str] = Field(None, max_length=200)\n    \n    external_counsel: bool = Field(default=False)\n    law_firm: Optional[str] = Field(None, max_length=200)\n    \n    notes: Optional[str] = Field(None, max_length=1000)\n\n\nclass LegalMatterPartyCreate(LegalMatterPartyBase):\n    """Schema for creating matter party"""\n    pass\n\n\nclass LegalMatterPartyResponse(LegalMatterPartyBase, TimestampMixin, IDMixin):\n    """Schema for matter party response"""\n    matter_id: UUID\n    \n    class Config:\n        from_attributes = True\n\n\nclass LegalMilestoneBase(BaseResponseModel):\n    """Base schema for legal milestone"""\n    name: str = Field(..., min_length=1, max_length=200)\n    description: Optional[str] = Field(None, max_length=1000)\n    \n    due_date: Optional[date] = None\n    completed_date: Optional[date] = None\n    \n    is_completed: bool = Field(default=False)\n    is_critical: bool = Field(default=False)\n    \n    notes: Optional[str] = Field(None, max_length=1000)\n\n\nclass LegalMilestoneCreate(LegalMilestoneBase):\n    """Schema for creating legal milestone"""\n    pass\n\n\nclass LegalMilestoneResponse(LegalMilestoneBase, TimestampMixin, IDMixin):\n    """Schema for legal milestone response"""\n    matter_id: UUID\n    \n    class Config:\n        from_attributes = True\n\n\nclass LegalMatterBase(BaseResponseModel):\n    """Base schema for legal matter"""\n    matter_number: Optional[str] = Field(None, max_length=50)\n    title: str = Field(..., min_length=1, max_length=300)\n    description: Optional[str] = Field(None, max_length=5000)\n    \n    matter_type: MatterType = Field(..., description="Type of legal matter")\n    status: MatterStatus = Field(default=MatterStatus.NEW)\n    priority: MatterPriority = Field(default=MatterPriority.NORMAL)\n    \n    company_id: UUID = Field(..., description="Company ID")\n    legal_entity_id: Optional[UUID] = None\n    \n    # Jurisdiction\n    jurisdiction: Optional[str] = Field(None, max_length=100)\n    court: Optional[str] = Field(None, max_length=200)\n    case_number: Optional[str] = Field(None, max_length=100)\n    \n    # Dates\n    open_date: date = Field(..., description="Date matter opened")\n    close_date: Optional[date] = None\n    \n    # Financial\n    estimated_cost: Optional[Decimal] = None\n    actual_cost: Optional[Decimal] = None\n    reserve_amount: Optional[Decimal] = None\n    settlement_amount: Optional[Decimal] = None\n    currency: str = Field(default="USD", min_length=3, max_length=3)\n    \n    # Risk\n    risk_level: Optional[str] = Field(None, max_length=50)\n    risk_amount: Optional[Decimal] = None\n    \n    # Insurance\n    insurance_coverage: Optional[bool] = None\n    insurance_policy: Optional[str] = Field(None, max_length=100)\n    insurance_claim_number: Optional[str] = Field(None, max_length=100)\n    \n    # Lead\n    lead_attorney_id: Optional[UUID] = None\n    responsible_attorney_id: Optional[UUID] = None\n    \n    # Related\n    related_matters: List[UUID] = Field(default_factory=list)\n    related_contracts: List[UUID] = Field(default_factory=list)\n    \n    # Outcome\n    outcome: Optional[str] = Field(None, max_length=200)\n    outcome_date: Optional[date] = None\n    outcome_notes: Optional[str] = Field(None, max_length=2000)\n    \n    # Keywords\n    keywords: List[str] = Field(default_factory=list)\n    tags: List[str] = Field(default_factory=list)\n    \n    notes: Optional[str] = Field(None, max_length=5000)\n    metadata: Optional[Dict[str, Any]] = None\n\n\nclass LegalMatterCreate(LegalMatterBase):\n    """Schema for creating a legal matter"""\n    parties: List[LegalMatterPartyCreate] = Field(default_factory=list)\n    milestones: List[LegalMilestoneCreate] = Field(default_factory=list)\n\n\nclass LegalMatterUpdate(BaseResponseModel):\n    """Schema for updating a legal matter"""\n    matter_number: Optional[str] = Field(None, max_length=50)\n    title: Optional[str] = Field(None, min_length=1, max_length=300)\n    description: Optional[str] = Field(None, max_length=5000)\n    matter_type: Optional[MatterType] = None\n    status: Optional[MatterStatus] = None\n    priority: Optional[MatterPriority] = None\n    legal_entity_id: Optional[UUID] = None\n    jurisdiction: Optional[str] = Field(None, max_length=100)\n    court: Optional[str] = Field(None, max_length=200)\n    case_number: Optional[str] = Field(None, max_length=100)\n    open_date: Optional[date] = None\n    close_date: Optional[date] = None\n    estimated_cost: Optional[Decimal] = None\n    actual_cost: Optional[Decimal] = None\n    reserve_amount: Optional[Decimal] = None\n    settlement_amount: Optional[Decimal] = None\n    currency: Optional[str] = Field(None, min_length=3, max_length=3)\n    risk_level: Optional[str] = Field(None, max_length=50)\n    risk_amount: Optional[Decimal] = None\n    insurance_coverage: Optional[bool] = None\n    insurance_policy: Optional[str] = Field(None, max_length=100)\n    insurance_claim_number: Optional[str] = Field(None, max_length=100)\n    lead_attorney_id: Optional[UUID] = None\n    responsible_attorney_id: Optional[UUID] = None\n    related_matters: Optional[List[UUID]] = None\n    related_contracts: Optional[List[UUID]] = None\n    outcome: Optional[str] = Field(None, max_length=200)\n    outcome_date: Optional[date] = None\n    outcome_notes: Optional[str] = Field(None, max_length=2000)\n    keywords: Optional[List[str]] = None\n    tags: Optional[List[str]] = None\n    notes: Optional[str] = Field(None, max_length=5000)\n    metadata: Optional[Dict[str, Any]] = None\n    parties: Optional[List[LegalMatterPartyCreate]] = None\n    milestones: Optional[List[LegalMilestoneCreate]] = None\n\n\nclass LegalMatterResponse(LegalMatterBase, TimestampMixin, IDMixin):\n    """Schema for legal matter response"""\n    # Calculated\n    duration_days: Optional[int] = None\n    \n    # Statistics\n    document_count: int = Field(default=0)\n    time_logged_hours: Decimal = Field(default=Decimal("0"))\n    expense_total: Decimal = Field(default=Decimal("0"))\n    \n    # Relationships\n    parties: List[LegalMatterPartyResponse] = Field(default_factory=list)\n    milestones: List[LegalMilestoneResponse] = Field(default_factory=list)\n    \n    # Audit\n    created_by: Optional[UUID] = None\n    \n    class Config:\n        from_attributes = True\n\n\nclass LegalMatterListResponse(BaseResponseModel):\n    """Schema for legal matter list item"""\n    id: UUID\n    matter_number: Optional[str]\n    title: str\n    matter_type: MatterType\n    status: MatterStatus\n    priority: MatterPriority\n    open_date: date\n    close_date: Optional[date]\n    company_id: UUID\n    lead_attorney_id: Optional[UUID]\n    created_at: datetime\n    \n    class Config:\n        from_attributes = True\n\n\n# ============================================\n# Intellectual Property Schemas\n# ============================================\n\nclass IntellectualPropertyBase(BaseResponseModel):\n    """Base schema for intellectual property"""\n    name: str = Field(..., min_length=1, max_length=200)\n    description: Optional[str] = Field(None, max_length=5000)\n    \n    ip_type: IPType = Field(..., description="Type of IP")\n    status: IPStatus = Field(default=IPStatus.ACTIVE)\n    \n    company_id: UUID = Field(..., description="Company ID")\n    legal_entity_id: Optional[UUID] = None\n    \n    # Registration\n    registration_number: Optional[str] = Field(None, max_length=100)\n    application_number: Optional[str] = Field(None, max_length=100)\n    filing_date: Optional[date] = None\n    registration_date: Optional[date] = None\n    grant_date: Optional[date] = None\n    \n    # Jurisdiction\n    jurisdiction: Optional[str] = Field(None, max_length=100)\n    international_classes: List[str] = Field(default_factory=list)\n    \n    # Dates\n    first_use_date: Optional[date] = None\n    first_use_in_commerce: Optional[date] = None\n    expiry_date: Optional[date] = None\n    next_renewal_date: Optional[date] = None\n    \n    # Value\n    estimated_value: Optional[Decimal] = None\n    currency: str = Field(default="USD", min_length=3, max_length=3)\n    \n    # Legal protection\n    legal_protection_status: Optional[str] = Field(None, max_length=100)\n    protection_scope: Optional[str] = Field(None, max_length=500)\n    \n    # Inventors/Authors\n    inventors: List[Dict[str, Any]] = Field(default_factory=list)\n    authors: List[Dict[str, Any]] = Field(default_factory=list)\n    \n    # Assignment\n    is_assigned: bool = Field(default=False)\n    assigned_to: Optional[str] = Field(None, max_length=200)\n    \n    # Licensing\n    is_licensed: bool = Field(default=False)\n    licensees: List[Dict[str, Any]] = Field(default_factory=list)\n    \n    # Owner\n    owner_id: Optional[UUID] = None\n    \n    # Alerts\n    alert_days_before_expiry: int = Field(default=90)\n    alert_on_maintenance: bool = Field(default=True)\n    \n    tags: List[str] = Field(default_factory=list)\n    notes: Optional[str] = Field(None, max_length=5000)\n    metadata: Optional[Dict[str, Any]] = None\n\n\nclass IntellectualPropertyCreate(IntellectualPropertyBase):\n    """Schema for creating intellectual property"""\n    pass\n\n\nclass IntellectualPropertyUpdate(BaseResponseModel):\n    """Schema for updating intellectual property"""\n    name: Optional[str] = Field(None, min_length=1, max_length=200)\n    description: Optional[str] = Field(None, max_length=5000)\n    ip_type: Optional[IPType] = None\n    status: Optional[IPStatus] = None\n    legal_entity_id: Optional[UUID] = None\n    registration_number: Optional[str] = Field(None, max_length=100)\n    application_number: Optional[str] = Field(None, max_length=100)\n    filing_date: Optional[date] = None\n    registration_date: Optional[date] = None\n    grant_date: Optional[date] = None\n    jurisdiction: Optional[str] = Field(None, max_length=100)\n    international_classes: Optional[List[str]] = None\n    first_use_date: Optional[date] = None\n    first_use_in_commerce: Optional[date] = None\n    expiry_date: Optional[date] = None\n    next_renewal_date: Optional[date] = None\n    estimated_value: Optional[Decimal] = None\n    currency: Optional[str] = Field(None, min_length=3, max_length=3)\n    legal_protection_status: Optional[str] = Field(None, max_length=100)\n    protection_scope: Optional[str] = Field(None, max_length=500)\n    inventors: Optional[List[Dict[str, Any]]] = None\n    authors: Optional[List[Dict[str, Any]]] = None\n    is_assigned: Optional[bool] = None\n    assigned_to: Optional[str] = Field(None, max_length=200)\n    is_licensed: Optional[bool] = None\n    licensees: Optional[List[Dict[str, Any]]] = None\n    owner_id: Optional[UUID] = None\n    alert_days_before_expiry: Optional[int] = None\n    alert_on_maintenance: Optional[bool] = None\n    tags: Optional[List[str]] = None\n    notes: Optional[str] = Field(None, max_length=5000)\n    metadata: Optional[Dict[str, Any]] = None\n\n\nclass IntellectualPropertyResponse(IntellectualPropertyBase, TimestampMixin, IDMixin):\n    """Schema for intellectual property response"""\n    # Calculated\n    days_until_expiry: Optional[int] = None\n    days_until_renewal: Optional[int] = None\n    is_expiring_soon: bool = Field(default=False)\n    \n    # Statistics\n    document_count: int = Field(default=0)\n    \n    class Config:\n        from_attributes = True\n\n\nclass IntellectualPropertyListResponse(BaseResponseModel):\n    """Schema for IP list item"""\n    id: UUID\n    name: str\n    ip_type: IPType\n    status: IPStatus\n    registration_number: Optional[str]\n    expiry_date: Optional[date]\n    company_id: UUID\n    owner_id: Optional[UUID]\n    created_at: datetime\n    \n    class Config:\n        from_attributes = True\n\n\n# ============================================\n# Query Parameters\n# ============================================\n\nclass LegalEntityFilterParams(PaginationParams):\n    """Filter parameters for legal entity queries"""\n    name: Optional[str] = None\n    legal_name: Optional[str] = None\n    entity_type: Optional[List[LegalEntityType]] = None\n    company_id: Optional[UUID] = None\n    registration_jurisdiction: Optional[str] = None\n    is_active: Optional[bool] = None\n    search: Optional[str] = None\n\n\nclass ContractFilterParams(PaginationParams):\n    """Filter parameters for contract queries"""\n    contract_number: Optional[str] = None\n    title: Optional[str] = None\n    contract_type: Optional[List[ContractType]] = None\n    status: Optional[List[ContractStatus]] = None\n    priority: Optional[List[ContractPriority]] = None\n    company_id: Optional[UUID] = None\n    legal_entity_id: Optional[UUID] = None\n    owner_id: Optional[UUID] = None\n    department_id: Optional[UUID] = None\n    effective_date_from: Optional[date] = None\n    effective_date_to: Optional[date] = None\n    expiry_date_from: Optional[date] = None\n    expiry_date_to: Optional[date] = None\n    expiring_within_days: Optional[int] = None\n    auto_renew: Optional[bool] = None\n    search: Optional[str] = None\n    tags: Optional[List[str]] = None\n\n\nclass DocumentFilterParams(PaginationParams):\n    """Filter parameters for document queries"""\n    title: Optional[str] = None\n    document_type: Optional[List[DocumentType]] = None\n    company_id: Optional[UUID] = None\n    contract_id: Optional[UUID] = None\n    matter_id: Optional[UUID] = None\n    legal_entity_id: Optional[UUID] = None\n    uploaded_by: Optional[UUID] = None\n    access_level: Optional[str] = None\n    created_after: Optional[datetime] = None\n    created_before: Optional[datetime] = None\n    search: Optional[str] = None\n    tags: Optional[List[str]] = None\n\n\nclass LegalMatterFilterParams(PaginationParams):\n    """Filter parameters for legal matter queries"""\n    matter_number: Optional[str] = None\n    title: Optional[str] = None\n    matter_type: Optional[List[MatterType]] = None\n    status: Optional[List[MatterStatus]] = None\n    priority: Optional[List[MatterPriority]] = None\n    company_id: Optional[UUID] = None\n    legal_entity_id: Optional[UUID] = None\n    jurisdiction: Optional[str] = None\n    court: Optional[str] = None\n    lead_attorney_id: Optional[UUID] = None\n    open_date_from: Optional[date] = None\n    open_date_to: Optional[date] = None\n    close_date_from: Optional[date] = None\n    close_date_to: Optional[date] = None\n    search: Optional[str] = None\n    tags: Optional[List[str]] = None\n\n\nclass IntellectualPropertyFilterParams(PaginationParams):\n    """Filter parameters for IP queries"""\n    name: Optional[str] = None\n    ip_type: Optional[List[IPType]] = None\n    status: Optional[List[IPStatus]] = None\n    company_id: Optional[UUID] = None\n    legal_entity_id: Optional[UUID] = None\n    jurisdiction: Optional[str] = None\n    owner_id: Optional[UUID] = None\n    expiry_date_from: Optional[date] = None\n    expiry_date_to: Optional[date] = None\n    expiring_within_days: Optional[int] = None\n    search: Optional[str] = None\n    tags: Optional[List[str]] = None\n\n\n# ============================================\n# Legal Analytics\n# ============================================\n\nclass LegalDashboardResponse(BaseResponseModel):\n    """Schema for legal dashboard"""\n    company_id: UUID\n    as_of_date: date\n    \n    # Contracts\n    total_contracts: int = 0\n    active_contracts: int = 0\n    expiring_contracts: int = 0\n    contracts_by_type: Dict[str, int] = Field(default_factory=dict)\n    contracts_by_status: Dict[str, int] = Field(default_factory=dict)\n    \n    # Matters\n    total_matters: int = 0\n    open_matters: int = 0\n    matters_by_type: Dict[str, int] = Field(default_factory=dict)\n    matters_by_status: Dict[str, int] = Field(default_factory=dict)\n    \n    # IP\n    total_ip: int = 0\n    active_ip: int = 0\n    expiring_ip: int = 0\n    ip_by_type: Dict[str, int] = Field(default_factory=dict)\n    \n    # Financial\n    total_contract_value: Decimal = Decimal("0")\n    total_legal_spend: Decimal = Decimal("0")\n    total_reserve: Decimal = Decimal("0")\n    \n    # Alerts\n    upcoming_renewals: int = 0\n    upcoming_expiry: int = 0\n    overdue_milestones: int = 0\n    \n    generated_at: datetime\n\n\nclass ContractAnalysisRequest(BaseResponseModel):\n    """Schema for AI contract analysis request"""\n    contract_id: UUID\n    analysis_type: str = Field(default="full", description="full, risk, compliance, key_terms")\n    include_summary: bool = Field(default=True)\n    include_risks: bool = Field(default=True)\n    include_key_terms: bool = Field(default=True)\n    include_obligations: bool = Field(default=True)\n    custom_questions: List[str] = Field(default_factory=list)\n\n\nclass ContractAnalysisResponse(BaseResponseModel):\n    """Schema for AI contract analysis response"""\n    contract_id: UUID\n    analysis_type: str\n    \n    # Summary\n    summary: Optional[str] = None\n    \n    # Key terms\n    key_terms: Dict[str, Any] = Field(default_factory=dict)\n    \n    # Risks\n    risks: List[Dict[str, Any]] = Field(default_factory=list)\n    risk_score: Optional[int] = None\n    \n    # Obligations\n    obligations: List[Dict[str, Any]] = Field(default_factory=list)\n    \n    # Compliance\n    compliance_issues: List[Dict[str, Any]] = Field(default_factory=list)\n    \n    # Custom analysis\n    custom_analysis: Dict[str, Any] = Field(default_factory=dict)\n    \n    # Recommendations\n    recommendations: List[str] = Field(default_factory=list)\n    \n    analyzed_at: datetime\n    model_version: Optional[str] = None\n\n\n# Update forward references\nContractResponse.model_rebuild()\nLegalMatterResponse.model_rebuild()\n</create-file>\n</function_calls>'}
{'role': 'user', 'content': '<tool_result> <create-file> ToolResult(success=True, output="File \'backend/app/schemas/legal.py\' created successfully.") </create-file> </tool_result>'}