{'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 analyze the conversation chronologically:\n\n1. Initial Setup:\n- The user started with a "Do tool calling warmup" message\n- I created an empty todo.md file for warmup\n\n2. Context Continuation:\n- This session is a continuation from a previous conversation that ran out of context\n- The summary provided detailed information about building "SAMMS ENTERPRISE SOVEREIGN OPERATING SYSTEM (SESOS v6 OMEGA CONSTRAINED)"\n- This is a comprehensive enterprise software system with 27+ core modules\n\n3. Technical Stack from Previous Session:\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. Files Already Created (from previous session):\n- Backend core: config.py, database.py, redis_client.py, security.py, events.py, exceptions.py\n- Models: base.py, company.py, user.py, accounting.py, treasury.py, invoice.py, hr.py, tax.py, workflow.py, legal.py, reports.py, consolidation.py, asset.py, ai.py\n- Schemas: base.py\n\n5. My Actions in This Session:\n- Updated todo.md to reflect current progress\n- Created company schemas (backend/app/schemas/company.py)\n- Created user schemas (backend/app/schemas/user.py)\n- Created accounting schemas (backend/app/schemas/accounting.py)\n- Created treasury schemas (backend/app/schemas/treasury.py)\n- Created invoice schemas (backend/app/schemas/invoice.py)\n- Created HR schemas (backend/app/schemas/hr.py)\n- Created tax schemas (backend/app/schemas/tax.py)\n- Created workflow schemas (backend/app/schemas/workflow.py)\n- Created legal schemas (backend/app/schemas/legal.py)\n\n6. No errors were encountered - all files created successfully\n\n7. Pending Work:\n- Still need to create: Reports schemas, Consolidation schemas, Asset schemas, AI schemas\n- Then need to create services layer, API endpoints, frontend, tests, infrastructure configs\n\n8. Current Work:\n- Just completed creating the legal.py schemas file\n- Was in the process of creating all Pydantic schemas for the backend\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   \n   User explicitly stated: "Generate EVERY file sequentially... Each file MUST include: full imports, full implementation, no placeholders"\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   - Pydantic v2 for schema validation\n\n3. Files and Code Sections:\n   \n   - **todo.md** - Task tracking file updated to reflect current progress with Phase 1.5 Backend Schemas section added\n   \n   - **backend/app/schemas/company.py** - Company management schemas\n     - CompanyType, CompanyStatus, OwnershipType, IndustrySector enums\n     - CompanyGroupCreate/Update/Response schemas with hierarchy support\n     - CompanyCreate/Update/Response with full address, contact info, hierarchy\n     - CompanySettingCreate/Update/Response for company-level configuration\n     - CompanyDocumentCreate/Update/Response for document management\n     - Filter parameters and bulk operation schemas\n   \n   - **backend/app/schemas/user.py** - User management schemas\n     - UserType, UserStatus, AuthenticationMethod, PermissionScope enums\n     - PermissionCreate/Update/Response with category, module, scope\n     - RoleCreate/Update/Response with permission assignments\n     - UserCreate/Update/Response with full profile, preferences, MFA\n     - UserSessionResponse, UserActivityLogResponse for session tracking\n     - Login/Logout/RefreshToken/MFASetup/PasswordReset schemas\n     - Filter parameters for all entity types\n   \n   - **backend/app/schemas/accounting.py** - Double-entry bookkeeping schemas\n     - AccountType, AccountSubType, JournalEntryStatus, FiscalYearStatus enums\n     - AccountCreate/Update/Response with hierarchy, balance, GL integration\n     - JournalEntryLineCreate/Response with debit/credit, dimensions\n     - JournalEntryCreate/Update/Response with validation for balanced entries\n     - FiscalYear/FiscalPeriod schemas with status management\n     - AccountBalance, TrialBalance, Budget schemas\n     - FinancialStatementRequest/Response for reporting\n   \n   - **backend/app/schemas/treasury.py** - Banking and cash management schemas\n     - BankAccountType, TransactionType, ReconciliationStatus enums\n     - BankAccountCreate/Update/Response with GL integration\n     - TreasuryTransactionCreate/Update/Response with reconciliation\n     - BankReconciliationCreate/Update/Response with line matching\n     - CashFlowForecastCreate/Update/Response with line items\n     - PaymentTermCreate/Update/Response\n     - CashPositionResponse, CashFlowSummaryResponse for analytics\n   \n   - **backend/app/schemas/invoice.py** - Revenue & Billing schemas\n     - ContactType, InvoiceStatus, ProductType, PaymentStatus enums\n     - ContactCreate/Update/Response with customer/vendor management\n     - ProductCreate/Update/Response with pricing, inventory, subscription\n     - InvoiceLineCreate/Response with discount, tax calculations\n     - InvoiceCreate/Update/Response with validation, totals\n     - PaymentCreate/Update/Response with allocation\n     - SubscriptionCreate/Update/Response with billing cycles\n     - RecurringInvoiceCreate/Update/Response\n     - RevenueSummaryResponse, AgingReportResponse for analytics\n   \n   - **backend/app/schemas/hr.py** - HR & Payroll schemas\n     - EmploymentType, PayType, PayFrequency, LeaveType, BenefitType enums\n     - DepartmentCreate/Update/Response with hierarchy\n     - PositionCreate/Update/Response with salary ranges, headcount\n     - EmployeeCreate/Update/Response with full employment details\n     - PayrollLineCreate/Response with earnings, deductions, taxes\n     - PayrollCreate/Update/Response with employee lines\n     - TimeEntryCreate/Update/Response for time tracking\n     - LeaveRequestCreate/Update/Response with approval workflow\n     - BenefitCreate/Response with enrollment management\n     - HRStatisticsResponse for dashboard\n   \n   - **backend/app/schemas/tax.py** - Tax Engine schemas\n     - TaxType, TaxJurisdictionType, TaxFilingStatus, NexusType enums\n     - TaxRateCreate/Update/Response with jurisdiction, thresholds\n     - TaxCodeCreate/Update/Response with exemption handling\n     - TaxTransactionCreate/Response with GL integration\n     - TaxFilingCreate/Update/Response with line items\n     - TaxNexusRuleCreate/Update/Response for nexus tracking\n     - ExchangeRateCreate/Update/Response for multi-currency\n     - TaxCalculationRequest/Response for real-time tax calculation\n     - TaxSummaryResponse, TaxLiabilityReportResponse for reporting\n   \n   - **backend/app/schemas/workflow.py** - Workflow & Automation schemas\n     - WorkflowStatus, TriggerType, ActionType, ConditionOperator enums\n     - WorkflowTriggerCreate/Response with schedule, event config\n     - WorkflowActionCreate/Response with input/output mapping\n     - WorkflowCreate/Update/Response with visual builder support\n     - WorkflowExecutionCreate/Response with logs, context\n     - AutomationRuleCreate/Update/Response with conditions\n     - NotificationCreate/Response with multi-channel delivery\n     - ApprovalWorkflowCreate/Response with steps\n     - ApprovalInstanceCreate/Response with status tracking\n     - WorkflowStatisticsResponse for analytics\n   \n   - **backend/app/schemas/legal.py** - Legal & Contract Lifecycle schemas\n     - LegalEntityType, ContractType, ContractStatus, MatterType, IPType enums\n     - LegalEntityCreate/Update/Response with officers, directors, shareholders\n     - ContractPartyCreate/Response, ContractMilestoneCreate/Response\n     - ContractCreate/Update/Response with parties, milestones, renewals\n     - DocumentCreate/Update/Response with versioning, security\n     - LegalMatterPartyCreate/Response, LegalMilestoneCreate/Response\n     - LegalMatterCreate/Update/Response with parties, milestones\n     - IntellectualPropertyCreate/Update/Response for patents, trademarks\n     - ContractAnalysisRequest/Response for AI-powered contract analysis\n     - LegalDashboardResponse for analytics\n\n4. Errors and fixes:\n   - No errors were encountered during this session. All files were created successfully.\n\n5. Problem Solving:\n   - Successfully designed comprehensive Pydantic schemas covering multiple business domains\n   - Implemented proper validation patterns using Pydantic v2 validators\n   - Created consistent schema patterns (Base, Create, Update, Response, ListResponse)\n   - Designed filter parameter schemas for flexible querying\n   - Included forward reference rebuilding for self-referencing models\n   - Added calculated fields and statistics in response schemas\n\n6. All user messages:\n   - "Do tool calling warmup"\n   - [Context continuation message with summary of previous session and detailed system requirements]\n\n7. Pending Tasks:\n   - Create remaining schema files:\n     - Reports schemas (backend/app/schemas/reports.py)\n     - Consolidation schemas (backend/app/schemas/consolidation.py)\n     - Asset schemas (backend/app/schemas/asset.py)\n     - AI schemas (backend/app/schemas/ai.py)\n   - Create schemas __init__.py to export all schemas\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\n   - Create tests\n   - Create Docker/Kubernetes configurations\n\n8. Current Work:\n   Just completed creating `backend/app/schemas/legal.py` with comprehensive schemas for legal entity management, contracts, documents, legal matters, and intellectual property. This was part of Phase 1.5 of the todo.md which involves creating all Pydantic schemas for the backend.\n\n9. Optional Next Step:\n   Continue creating the remaining Pydantic schema files in this order:\n   1. `backend/app/schemas/reports.py` - Reports and dashboard schemas\n   2. `backend/app/schemas/consolidation.py` - Consolidation engine schemas\n   3. `backend/app/schemas/asset.py` - Fixed asset registry schemas\n   4. `backend/app/schemas/ai.py` - AI and analytics schemas\n   5. `backend/app/schemas/__init__.py` - Export all schemas\n\n   From the original specification: "Generate EVERY file sequentially... Each file MUST include: full imports, full implementation, no placeholders"\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_1775079235_709.txt'}
{'role': 'assistant', 'content': "I'll continue building the SESOS system from where we left off. Let me first read the current todo.md and the transcript to understand the exact state, then continue creating the remaining schema files.\n\n\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- [x] Create folder structure\\\\n- [x] Backend core setup (FastAPI)\\\\n- [ ] Frontend core setup (Next.js)\\\\n- [x] Database configuration\\\\n- [ ] Docker & 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\\\\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': "I see the todo.md needs to be updated to reflect the actual progress. According to the summary, I've already created schemas for company, user, accounting, treasury, invoice, hr, tax, workflow, and legal. Let me verify and then continue with the remaining schemas.\n\n<function_calls>\n<execute-command>\nls -la backend/app/schemas/\n</execute-command>\n</function_calls>"}
{'role': 'user', 'content': '<tool_result> <execute-command> ToolResult(success=True, output=\'{\\n  "output": "total 304\\\\ndrwxr-xr-x  2 root root  4096 Apr  1 21:33 .\\\\ndrwxr-xr-x 13 root root  4096 Apr  1 20:24 ..\\\\n-rw-r--r--  1 root root 33120 Apr  1 21:09 accounting.py\\\\n-rw-r--r--  1 root root  4592 Apr  1 20:53 base.py\\\\n-rw-r--r--  1 root root 19402 Apr  1 20:56 company.py\\\\n-rw-r--r--  1 root root 38523 Apr  1 21:21 hr.py\\\\n-rw-r--r--  1 root root 36061 Apr  1 21:16 invoice.py\\\\n-rw-r--r--  1 root root 37796 Apr  1 21:33 legal.py\\\\n-rw-r--r--  1 root root 28021 Apr  1 21:25 tax.py\\\\n-rw-r--r--  1 root root 28116 Apr  1 21:12 treasury.py\\\\n-rw-r--r--  1 root root 25453 Apr  1 21:04 user.py\\\\n-rw-r--r--  1 root root 30525 Apr  1 21:28 workflow.py\\\\n",\\n  "exit_code": 0,\\n  "cwd": "/workspace"\\n}\') </execute-command> </tool_result>'}
{'role': 'assistant', 'content': 'I can see the existing schemas. The summary mentioned that I still need to create: reports.py, consolidation.py, asset.py, and ai.py. Let me update the todo.md to reflect actual progress and then continue creating the remaining schemas.\n\n<function_calls>\n<full-file-rewrite file_path="todo.md">\n# SAMMS ENTERPRISE SOVEREIGN OPERATING SYSTEM - BUILD TRACKER\n\n## Phase 1: Project Setup & Infrastructure\n- [x] Create folder structure\n- [x] Backend core setup (FastAPI)\n- [ ] Frontend core setup (Next.js)\n- [x] Database configuration\n- [ ] Docker & Kubernetes configs\n\n## Phase 1.5: Backend Schemas (Pydantic)\n- [x] Base schemas\n- [x] Company schemas\n- [x] User schemas\n- [x] Accounting schemas\n- [x] Treasury schemas\n- [x] Invoice schemas\n- [x] HR schemas\n- [x] Tax schemas\n- [x] Workflow schemas\n- [x] Legal schemas\n- [ ] Reports schemas\n- [ ] Consolidation schemas\n- [ ] Asset schemas\n- [ ] AI schemas\n- [ ] Schemas __init__.py\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</full-file-rewrite>\n</function_calls>'}
{'role': 'user', 'content': '<tool_result> <full-file-rewrite> ToolResult(success=True, output="File \'todo.md\' completely rewritten successfully.") </full-file-rewrite> </tool_result>'}
{'role': 'assistant', 'content': 'Now let me continue creating the remaining schema files. I\'ll start with the Reports schemas.\n\n<function_calls>\n<create-file file_path="backend/app/schemas/reports.py">\n"""\nSAMMS Enterprise - Reports & Dashboard Schemas\nComprehensive reporting and dashboard management schemas\n"""\n\nfrom datetime import datetime, date, timedelta\nfrom typing import Optional, List, Dict, Any, Union, Literal\nfrom decimal import Decimal\nfrom enum import Enum\nfrom pydantic import BaseModel, Field, ConfigDict, field_validator, model_validator, computed_field\nfrom .base import (\n    BaseResponseSchema,\n    TimestampMixin,\n    PaginationParams,\n    ListResponseBase,\n    AuditMixin,\n    CompanyScopedMixin\n)\n\n\n# ==================== ENUMS ====================\n\nclass ReportType(str, Enum):\n    """Types of reports available in the system"""\n    FINANCIAL_STATEMENT = "financial_statement"\n    BALANCE_SHEET = "balance_sheet"\n    INCOME_STATEMENT = "income_statement"\n    CASH_FLOW = "cash_flow"\n    TRIAL_BALANCE = "trial_balance"\n    GENERAL_LEDGER = "general_ledger"\n    AGING_REPORT = "aging_report"\n    REVENUE_ANALYSIS = "revenue_analysis"\n    EXPENSE_ANALYSIS = "expense_analysis"\n    BUDGET_VARIANCE = "budget_variance"\n    TAX_SUMMARY = "tax_summary"\n    PAYROLL_SUMMARY = "payroll_summary"\n    FIXED_ASSET = "fixed_asset"\n    TREASURY = "treasury"\n    CONSOLIDATION = "consolidation"\n    CUSTOM = "custom"\n\n\nclass ReportStatus(str, Enum):\n    """Report execution status"""\n    PENDING = "pending"\n    RUNNING = "running"\n    COMPLETED = "completed"\n    FAILED = "failed"\n    CANCELLED = "cancelled"\n    SCHEDULED = "scheduled"\n\n\nclass ExportFormat(str, Enum):\n    """Export formats for reports"""\n    PDF = "pdf"\n    EXCEL = "excel"\n    CSV = "csv"\n    JSON = "json"\n    HTML = "html"\n    WORD = "word"\n\n\nclass ScheduleFrequency(str, Enum):\n    """Report scheduling frequency"""\n    ONCE = "once"\n    HOURLY = "hourly"\n    DAILY = "daily"\n    WEEKLY = "weekly"\n    BIWEEKLY = "biweekly"\n    MONTHLY = "monthly"\n    QUARTERLY = "quarterly"\n    YEARLY = "yearly"\n    CUSTOM = "custom"\n\n\nclass DashboardWidgetType(str, Enum):\n    """Types of dashboard widgets"""\n    CHART_LINE = "chart_line"\n    CHART_BAR = "chart_bar"\n    CHART_PIE = "chart_pie"\n    CHART_DOUGHNUT = "chart_doughnut"\n    CHART_AREA = "chart_area"\n    CHART_SCATTER = "chart_scatter"\n    KPI_CARD = "kpi_card"\n    TABLE = "table"\n    GAUGE = "gauge"\n    MAP = "map"\n    HEATMAP = "heatmap"\n    TREEMAP = "treemap"\n    FUNNEL = "funnel"\n    METRIC = "metric"\n    TEXT = "text"\n    IFRAME = "iframe"\n    CUSTOM = "custom"\n\n\nclass AggregationType(str, Enum):\n    """Data aggregation types"""\n    SUM = "sum"\n    AVG = "avg"\n    COUNT = "count"\n    MIN = "min"\n    MAX = "max"\n    MEDIAN = "median"\n    STDDEV = "stddev"\n    VARIANCE = "variance"\n    FIRST = "first"\n    LAST = "last"\n    PERCENTILE = "percentile"\n    RUNNING_TOTAL = "running_total"\n    MOVING_AVERAGE = "moving_average"\n\n\nclass DateRangeType(str, Enum):\n    """Predefined date range types"""\n    TODAY = "today"\n    YESTERDAY = "yesterday"\n    THIS_WEEK = "this_week"\n    LAST_WEEK = "last_week"\n    THIS_MONTH = "this_month"\n    LAST_MONTH = "last_month"\n    THIS_QUARTER = "this_quarter"\n    LAST_QUARTER = "last_quarter"\n    THIS_YEAR = "this_year"\n    LAST_YEAR = "last_year"\n    FISCAL_YEAR = "fiscal_year"\n    FISCAL_QUARTER = "fiscal_quarter"\n    CUSTOM = "custom"\n    PERIOD_TO_DATE = "period_to_date"\n    YEAR_TO_DATE = "year_to_date"\n    MONTH_TO_DATE = "month_to_date"\n    TRAILING_30 = "trailing_30"\n    TRAILING_90 = "trailing_90"\n    TRAILING_12_MONTHS = "trailing_12_months"\n\n\nclass ChartOrientation(str, Enum):\n    """Chart orientation options"""\n    VERTICAL = "vertical"\n    HORIZONTAL = "horizontal"\n\n\nclass LegendPosition(str, Enum):\n    """Legend position options"""\n    TOP = "top"\n    BOTTOM = "bottom"\n    LEFT = "left"\n    RIGHT = "right"\n    HIDDEN = "hidden"\n\n\n# ==================== REPORT TEMPLATES ====================\n\nclass ReportParameterBase(BaseModel):\n    """Base schema for report parameters"""\n    name: str = Field(..., min_length=1, max_length=100, description="Parameter name")\n    display_name: str = Field(..., min_length=1, max_length=200, description="Display name")\n    description: Optional[str] = Field(None, max_length=500, description="Parameter description")\n    parameter_type: str = Field(..., description="Parameter data type (string, number, date, boolean, select, multiselect)")\n    is_required: bool = Field(default=False, description="Whether parameter is required")\n    default_value: Optional[Any] = Field(None, description="Default value")\n    allowed_values: Optional[List[Any]] = Field(None, description="Allowed values for select/multiselect types")\n    validation_regex: Optional[str] = Field(None, description="Validation regex for string types")\n    min_value: Optional[Decimal] = Field(None, description="Minimum value for numeric types")\n    max_value: Optional[Decimal] = Field(None, description="Maximum value for numeric types")\n    depends_on: Optional[str] = Field(None, description="Parameter this depends on for cascading parameters")\n\n\nclass ReportParameterCreate(ReportParameterBase):\n    """Schema for creating report parameters"""\n    pass\n\n\nclass ReportParameterResponse(ReportParameterBase):\n    """Schema for report parameter responses"""\n    id: int\n    template_id: int\n\n    model_config = ConfigDict(from_attributes=True)\n\n\nclass ReportTemplateColumnBase(BaseModel):\n    """Base schema for report template columns"""\n    name: str = Field(..., min_length=1, max_length=100, description="Column name")\n    display_name: str = Field(..., min_length=1, max_length=200, description="Display name")\n    column_type: str = Field(..., description="Column data type")\n    width: Optional[int] = Field(None, ge=50, le=1000, description="Column width in pixels")\n    alignment: Optional[str] = Field(default="left", description="Text alignment")\n    format_pattern: Optional[str] = Field(None, description="Format pattern (e.g., #,##0.00)")\n    is_sortable: bool = Field(default=True, description="Whether column is sortable")\n    is_filterable: bool = Field(default=True, description="Whether column is filterable")\n    is_visible: bool = Field(default=True, description="Whether column is visible by default")\n    sort_order: int = Field(default=0, ge=0, description="Column sort order")\n    aggregation: Optional[AggregationType] = Field(None, description="Aggregation type for summary rows")\n\n\nclass ReportTemplateColumnCreate(ReportTemplateColumnBase):\n    """Schema for creating report template columns"""\n    pass\n\n\nclass ReportTemplateColumnResponse(ReportTemplateColumnBase):\n    """Schema for report template column responses"""\n    id: int\n    template_id: int\n\n    model_config = ConfigDict(from_attributes=True)\n\n\nclass ReportTemplateBase(BaseModel):\n    """Base schema for report templates"""\n    name: str = Field(..., min_length=1, max_length=200, description="Template name")\n    code: str = Field(..., min_length=1, max_length=50, pattern=r"^[A-Z][A-Z0-9_]*$", description="Unique template code")\n    description: Optional[str] = Field(None, max_length=2000, description="Template description")\n    category: Optional[str] = Field(None, max_length=100, description="Template category")\n    report_type: ReportType = Field(..., description="Type of report")\n    data_source: str = Field(..., min_length=1, max_length=500, description="Data source query or endpoint")\n    is_system: bool = Field(default=False, description="Whether this is a system template")\n    is_active: bool = Field(default=True, description="Whether template is active")\n    requires_company_scope: bool = Field(default=True, description="Whether report requires company filtering")\n    supports_consolidation: bool = Field(default=False, description="Whether report supports multi-company consolidation")\n    supports_comparison: bool = Field(default=False, description="Whether report supports period comparison")\n    supports_drilldown: bool = Field(default=False, description="Whether report supports drill-down")\n    default_date_range: DateRangeType = Field(default=DateRangeType.THIS_MONTH, description="Default date range")\n    default_format: ExportFormat = Field(default=ExportFormat.PDF, description="Default export format")\n    icon: Optional[str] = Field(None, max_length=50, description="Icon identifier")\n    sort_order: int = Field(default=0, ge=0, description="Sort order in category")\n\n\nclass ReportTemplateCreate(ReportTemplateBase):\n    """Schema for creating report templates"""\n    parameters: Optional[List[ReportParameterCreate]] = Field(default_factory=list, description="Report parameters")\n    columns: Optional[List[ReportTemplateColumnCreate]] = Field(default_factory=list, description="Report columns")\n\n\nclass ReportTemplateUpdate(BaseModel):\n    """Schema for updating report templates"""\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, max_length=100)\n    is_active: Optional[bool] = None\n    data_source: Optional[str] = Field(None, min_length=1, max_length=500)\n    supports_consolidation: Optional[bool] = None\n    supports_comparison: Optional[bool] = None\n    supports_drilldown: Optional[bool] = None\n    default_date_range: Optional[DateRangeType] = None\n    default_format: Optional[ExportFormat] = None\n    icon: Optional[str] = Field(None, max_length=50)\n    sort_order: Optional[int] = Field(None, ge=0)\n    parameters: Optional[List[ReportParameterCreate]] = None\n    columns: Optional[List[ReportTemplateColumnCreate]] = None\n\n\nclass ReportTemplateResponse(ReportTemplateBase, BaseResponseSchema, CompanyScopedMixin):\n    """Schema for report template responses"""\n    parameters: List[ReportParameterResponse] = Field(default_factory=list)\n    columns: List[ReportTemplateColumnResponse] = Field(default_factory=list)\n\n    model_config = ConfigDict(from_attributes=True)\n\n\n# ==================== REPORT INSTANCES ====================\n\nclass DateRange(BaseModel):\n    """Date range specification"""\n    type: DateRangeType = Field(..., description="Type of date range")\n    start_date: Optional[date] = Field(None, description="Start date for custom ranges")\n    end_date: Optional[date] = Field(None, description="End date for custom ranges")\n    fiscal_year: Optional[int] = Field(None, description="Fiscal year for fiscal ranges")\n    fiscal_quarter: Optional[int] = Field(None, ge=1, le=4, description="Fiscal quarter")\n\n    @model_validator(mode=\'after\')\n    def validate_custom_range(self):\n        if self.type == DateRangeType.CUSTOM:\n            if not self.start_date or not self.end_date:\n                raise ValueError("Custom date range requires start_date and end_date")\n            if self.start_date > self.end_date:\n                raise ValueError("Start date cannot be after end date")\n        return self\n\n\nclass ComparisonPeriod(BaseModel):\n    """Period comparison configuration"""\n    enabled: bool = Field(default=False, description="Whether comparison is enabled")\n    comparison_type: str = Field(default="previous_period", description="Comparison type: previous_period, previous_year, custom")\n    custom_range: Optional[DateRange] = Field(None, description="Custom comparison range")\n    show_variance: bool = Field(default=True, description="Show variance column")\n    show_percentage: bool = Field(default=True, description="Show percentage change")\n\n\nclass ReportExecutionParameters(BaseModel):\n    """Parameters for report execution"""\n    date_range: DateRange = Field(..., description="Date range for the report")\n    comparison: Optional[ComparisonPeriod] = Field(None, description="Comparison period configuration")\n    company_ids: Optional[List[int]] = Field(None, description="Company IDs for multi-company reports")\n    department_ids: Optional[List[int]] = Field(None, description="Department filter")\n    project_ids: Optional[List[int]] = Field(None, description="Project filter")\n    account_ids: Optional[List[int]] = Field(None, description="Account filter")\n    custom_parameters: Optional[Dict[str, Any]] = Field(None, description="Custom parameter values")\n    currency: Optional[str] = Field(None, max_length=3, description="Reporting currency")\n    include_zero_balances: bool = Field(default=False, description="Include accounts with zero balances")\n    include_unapproved: bool = Field(default=False, description="Include unapproved transactions")\n    rounding: Optional[str] = Field(default="none", description="Rounding: none, thousands, millions")\n\n\nclass ReportInstanceBase(BaseModel):\n    """Base schema for report instances"""\n    name: Optional[str] = Field(None, min_length=1, max_length=200, description="Report instance name")\n    template_id: int = Field(..., description="Report template ID")\n    parameters: ReportExecutionParameters = Field(..., description="Report parameters")\n    output_format: ExportFormat = Field(default=ExportFormat.PDF, description="Output format")\n\n\nclass ReportInstanceCreate(ReportInstanceBase):\n    """Schema for creating/executing a report"""\n    save_instance: bool = Field(default=True, description="Whether to save the report instance")\n    email_to: Optional[List[str]] = Field(None, description="Email recipients when complete")\n    callback_url: Optional[str] = Field(None, max_length=500, description="Callback URL when complete")\n\n\nclass ReportInstanceUpdate(BaseModel):\n    """Schema for updating report instances"""\n    name: Optional[str] = Field(None, min_length=1, max_length=200)\n    parameters: Optional[ReportExecutionParameters] = None\n    output_format: Optional[ExportFormat] = None\n\n\nclass ReportDataColumn(BaseModel):\n    """Column in report data"""\n    name: str\n    display_name: str\n    type: str\n    format_pattern: Optional[str] = None\n\n\nclass ReportDataRow(BaseModel):\n    """Row in report data"""\n    values: Dict[str, Any] = Field(..., description="Column values")\n    is_summary: bool = Field(default=False, description="Whether this is a summary row")\n    level: int = Field(default=0, ge=0, description="Indentation level")\n    parent_key: Optional[str] = Field(None, description="Parent row key for hierarchical data")\n\n\nclass ReportSummary(BaseModel):\n    """Report summary statistics"""\n    total_rows: int = Field(default=0, description="Total number of data rows")\n    grand_totals: Optional[Dict[str, Decimal]] = Field(None, description="Grand total values")\n    execution_time_ms: int = Field(default=0, description="Report execution time in milliseconds")\n    data_as_of: datetime = Field(..., description="Data timestamp")\n\n\nclass ReportInstanceResponse(ReportInstanceBase, BaseResponseSchema, CompanyScopedMixin):\n    """Schema for report instance responses"""\n    status: ReportStatus = Field(default=ReportStatus.PENDING)\n    started_at: Optional[datetime] = None\n    completed_at: Optional[datetime] = None\n    generated_by_id: int\n    file_path: Optional[str] = None\n    file_size_bytes: Optional[int] = None\n    page_count: Optional[int] = None\n    error_message: Optional[str] = None\n    columns: Optional[List[ReportDataColumn]] = None\n    data: Optional[List[ReportDataRow]] = None\n    summary: Optional[ReportSummary] = None\n    execution_log: Optional[List[Dict[str, Any]]] = None\n\n    model_config = ConfigDict(from_attributes=True)\n\n\n# ==================== REPORT SCHEDULES ====================\n\nclass ReportScheduleBase(BaseModel):\n    """Base schema for report schedules"""\n    name: str = Field(..., min_length=1, max_length=200, description="Schedule name")\n    template_id: int = Field(..., description="Report template ID")\n    parameters: ReportExecutionParameters = Field(..., description="Report parameters")\n    output_format: ExportFormat = Field(default=ExportFormat.PDF, description="Output format")\n    frequency: ScheduleFrequency = Field(..., description="Schedule frequency")\n    start_date: date = Field(..., description="Schedule start date")\n    end_date: Optional[date] = Field(None, description="Schedule end date")\n    next_run: Optional[datetime] = Field(None, description="Next scheduled run")\n    last_run: Optional[datetime] = Field(None, description="Last run timestamp")\n    is_active: bool = Field(default=True, description="Whether schedule is active")\n    email_recipients: List[str] = Field(default_factory=list, description="Email recipients")\n    email_subject: Optional[str] = Field(None, max_length=500, description="Email subject")\n    email_body: Optional[str] = Field(None, max_length=5000, description="Email body")\n    retention_days: int = Field(default=30, ge=1, le=365, description="Report retention in days")\n    max_instances: int = Field(default=10, ge=1, le=100, description="Maximum instances to retain")\n\n    @field_validator(\'email_recipients\')\n    @classmethod\n    def validate_emails(cls, v):\n        import re\n        email_regex = r\'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$\'\n        for email in v:\n            if not re.match(email_regex, email):\n                raise ValueError(f\'Invalid email address: {email}\')\n        return v\n\n\nclass ReportScheduleCreate(ReportScheduleBase):\n    """Schema for creating report schedules"""\n    custom_cron: Optional[str] = Field(None, description="Custom cron expression for custom frequency")\n\n\nclass ReportScheduleUpdate(BaseModel):\n    """Schema for updating report schedules"""\n    name: Optional[str] = Field(None, min_length=1, max_length=200)\n    parameters: Optional[ReportExecutionParameters] = None\n    output_format: Optional[ExportFormat] = None\n    frequency: Optional[ScheduleFrequency] = None\n    start_date: Optional[date] = None\n    end_date: Optional[date] = None\n    is_active: Optional[bool] = None\n    email_recipients: Optional[List[str]] = None\n    email_subject: Optional[str] = Field(None, max_length=500)\n    email_body: Optional[str] = Field(None, max_length=5000)\n    retention_days: Optional[int] = Field(None, ge=1, le=365)\n    max_instances: Optional[int] = Field(None, ge=1, le=100)\n    custom_cron: Optional[str] = None\n\n\nclass ReportScheduleResponse(ReportScheduleBase, BaseResponseSchema, CompanyScopedMixin):\n    """Schema for report schedule responses"""\n    custom_cron: Optional[str] = None\n    total_runs: int = Field(default=0, description="Total number of executions")\n    successful_runs: int = Field(default=0, description="Successful executions")\n    failed_runs: int = Field(default=0, description="Failed executions")\n    created_by_id: int\n\n    model_config = ConfigDict(from_attributes=True)\n\n\n# ==================== DASHBOARDS ====================\n\nclass DashboardWidgetConfigBase(BaseModel):\n    """Base schema for dashboard widget configuration"""\n    title: str = Field(..., min_length=1, max_length=200, description="Widget title")\n    subtitle: Optional[str] = Field(None, max_length=500, description="Widget subtitle")\n    widget_type: DashboardWidgetType = Field(..., description="Widget type")\n    data_source: str = Field(..., min_length=1, max_length=500, description="Data source query or endpoint")\n    refresh_interval_seconds: Optional[int] = Field(None, ge=30, le=86400, description="Auto-refresh interval")\n    date_range: Optional[DateRange] = Field(None, description="Widget date range")\n    filters: Optional[Dict[str, Any]] = Field(None, description="Widget filters")\n    color_scheme: Optional[str] = Field(None, max_length=50, description="Color scheme")\n    show_legend: bool = Field(default=True, description="Show legend")\n    legend_position: LegendPosition = Field(default=LegendPosition.BOTTOM, description="Legend position")\n    show_grid: bool = Field(default=True, description="Show grid lines")\n    show_values: bool = Field(default=False, description="Show values on chart")\n    is_stacked: bool = Field(default=False, description="Stack series")\n    orientation: ChartOrientation = Field(default=ChartOrientation.VERTICAL, description="Chart orientation")\n    drill_down_enabled: bool = Field(default=False, description="Enable drill-down")\n    drill_down_target: Optional[str] = Field(None, max_length=200, description="Drill-down target widget or report")\n    custom_options: Optional[Dict[str, Any]] = Field(None, description="Custom chart options")\n\n\nclass DashboardWidgetConfigCreate(DashboardWidgetConfigBase):\n    """Schema for creating dashboard widget configs"""\n    pass\n\n\nclass DashboardWidgetConfigResponse(DashboardWidgetConfigBase, BaseResponseSchema):\n    """Schema for dashboard widget config responses"""\n    widget_id: int\n\n    model_config = ConfigDict(from_attributes=True)\n\n\nclass DashboardWidgetPosition(BaseModel):\n    """Widget position on dashboard grid"""\n    x: int = Field(..., ge=0, description="X position in grid units")\n    y: int = Field(..., ge=0, description="Y position in grid units")\n    width: int = Field(..., ge=1, le=12, description="Width in grid units (1-12)")\n    height: int = Field(..., ge=1, le=12, description="Height in grid units (1-12)")\n    min_width: Optional[int] = Field(None, ge=1, le=12, description="Minimum width")\n    min_height: Optional[int] = Field(None, ge=1, le=12, description="Minimum height")\n\n\nclass DashboardWidgetBase(BaseModel):\n    """Base schema for dashboard widgets"""\n    config: DashboardWidgetConfigBase = Field(..., description="Widget configuration")\n    position: DashboardWidgetPosition = Field(..., description="Widget position")\n\n\nclass DashboardWidgetCreate(DashboardWidgetBase):\n    """Schema for creating dashboard widgets"""\n    pass\n\n\nclass DashboardWidgetUpdate(BaseModel):\n    """Schema for updating dashboard widgets"""\n    config: Optional[DashboardWidgetConfigBase] = None\n    position: Optional[DashboardWidgetPosition] = None\n\n\nclass DashboardWidgetResponse(DashboardWidgetBase, BaseResponseSchema):\n    """Schema for dashboard widget responses"""\n    dashboard_id: int\n\n    model_config = ConfigDict(from_attributes=True)\n\n\nclass DashboardBase(BaseModel):\n    """Base schema for dashboards"""\n    name: str = Field(..., min_length=1, max_length=200, description="Dashboard name")\n    description: Optional[str] = Field(None, max_length=2000, description="Dashboard description")\n    is_default: bool = Field(default=False, description="Whether this is the default dashboard")\n    is_public: bool = Field(default=False, description="Whether dashboard is public")\n    layout_type: str = Field(default="grid", description="Layout type: grid, freeform")\n    columns: int = Field(default=12, ge=1, le=24, description="Number of grid columns")\n    row_height: int = Field(default=100, ge=50, le=300, description="Row height in pixels")\n    background_color: Optional[str] = Field(None, max_length=20, description="Background color")\n    theme: Optional[str] = Field(None, max_length=50, description="Dashboard theme")\n    icon: Optional[str] = Field(None, max_length=50, description="Dashboard icon")\n\n\nclass DashboardCreate(DashboardBase):\n    """Schema for creating dashboards"""\n    widgets: Optional[List[DashboardWidgetCreate]] = Field(default_factory=list, description="Dashboard widgets")\n\n\nclass DashboardUpdate(BaseModel):\n    """Schema for updating dashboards"""\n    name: Optional[str] = Field(None, min_length=1, max_length=200)\n    description: Optional[str] = Field(None, max_length=2000)\n    is_default: Optional[bool] = None\n    is_public: Optional[bool] = None\n    layout_type: Optional[str] = None\n    columns: Optional[int] = Field(None, ge=1, le=24)\n    row_height: Optional[int] = Field(None, ge=50, le=300)\n    background_color: Optional[str] = Field(None, max_length=20)\n    theme: Optional[str] = Field(None, max_length=50)\n    icon: Optional[str] = Field(None, max_length=50)\n    widgets: Optional[List[DashboardWidgetCreate]] = None\n\n\nclass DashboardResponse(DashboardBase, BaseResponseSchema, CompanyScopedMixin):\n    """Schema for dashboard responses"""\n    widgets: List[DashboardWidgetResponse] = Field(default_factory=list)\n    owner_id: int\n    view_count: int = Field(default=0, description="Number of times viewed")\n    last_viewed_at: Optional[datetime] = None\n\n    model_config = ConfigDict(from_attributes=True)\n\n\n# ==================== KPI DEFINITIONS ====================\n\nclass KPICalculationType(str, Enum):\n    """KPI calculation types"""\n    SIMPLE = "simple"\n    FORMULA = "formula"\n    AGGREGATE = "aggregate"\n    CUSTOM = "custom"\n\n\nclass KPIDirection(str, Enum):\n    """KPI improvement direction"""\n    HIGHER_IS_BETTER = "higher_is_better"\n    LOWER_IS_BETTER = "lower_is_better"\n    TARGET_IS_BETTER = "target_is_better"\n    NO_DIRECTION = "no_direction"\n\n\nclass KPIDefinitionBase(BaseModel):\n    """Base schema for KPI definitions"""\n    name: str = Field(..., min_length=1, max_length=200, description="KPI name")\n    code: str = Field(..., min_length=1, max_length=50, pattern=r"^[A-Z][A-Z0-9_]*$", description="Unique KPI code")\n    description: Optional[str] = Field(None, max_length=2000, description="KPI description")\n    category: Optional[str] = Field(None, max_length=100, description="KPI category")\n    calculation_type: KPICalculationType = Field(..., description="Calculation type")\n    formula: Optional[str] = Field(None, max_length=1000, description="Formula for formula type")\n    data_source: str = Field(..., min_length=1, max_length=500, description="Data source query")\n    unit: Optional[str] = Field(None, max_length=20, description="Unit of measurement")\n    format_pattern: Optional[str] = Field(None, description="Format pattern")\n    direction: KPIDirection = Field(default=KPIDirection.HIGHER_IS_BETTER, description="Improvement direction")\n    target_value: Optional[Decimal] = Field(None, description="Target value")\n    warning_threshold: Optional[Decimal] = Field(None, description="Warning threshold")\n    critical_threshold: Optional[Decimal] = Field(None, description="Critical threshold")\n    comparison_target: Optional[str] = Field(None, description="Comparison target: budget, prior_period, prior_year")\n    is_active: bool = Field(default=True, description="Whether KPI is active")\n    display_order: int = Field(default=0, ge=0, description="Display order")\n\n\nclass KPIDefinitionCreate(KPIDefinitionBase):\n    """Schema for creating KPI definitions"""\n    pass\n\n\nclass KPIDefinitionUpdate(BaseModel):\n    """Schema for updating KPI definitions"""\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, max_length=100)\n    formula: Optional[str] = Field(None, max_length=1000)\n    data_source: Optional[str] = Field(None, min_length=1, max_length=500)\n    unit: Optional[str] = Field(None, max_length=20)\n    format_pattern: Optional[str] = None\n    direction: Optional[KPIDirection] = None\n    target_value: Optional[Decimal] = None\n    warning_threshold: Optional[Decimal] = None\n    critical_threshold: Optional[Decimal] = None\n    comparison_target: Optional[str] = None\n    is_active: Optional[bool] = None\n    display_order: Optional[int] = Field(None, ge=0)\n\n\nclass KPIValue(BaseModel):\n    """KPI computed value"""\n    value: Decimal = Field(..., description="Current value")\n    formatted_value: str = Field(..., description="Formatted value string")\n    previous_value: Optional[Decimal] = Field(None, description="Previous period value")\n    change: Optional[Decimal] = Field(None, description="Absolute change")\n    change_percent: Optional[Decimal] = Field(None, description="Percentage change")\n    trend: Optional[str] = Field(None, description="Trend: up, down, stable")\n    status: str = Field(..., description="Status: good, warning, critical, neutral")\n    sparkline: Optional[List[Decimal]] = Field(None, description="Historical values for sparkline")\n    target_value: Optional[Decimal] = Field(None, description="Target value")\n    target_percent: Optional[Decimal] = Field(None, description="Percentage of target")\n\n\nclass KPIDefinitionResponse(KPIDefinitionBase, BaseResponseSchema, CompanyScopedMixin):\n    """Schema for KPI definition responses"""\n    current_value: Optional[KPIValue] = Field(None, description="Current computed value")\n\n    model_config = ConfigDict(from_attributes=True)\n\n\n# ==================== FILTER PARAMETERS ====================\n\nclass ReportTemplateFilterParams(PaginationParams):\n    """Filter parameters for report template queries"""\n    report_type: Optional[ReportType] = None\n    category: Optional[str] = None\n    is_active: Optional[bool] = None\n    is_system: Optional[bool] = None\n    search: Optional[str] = None\n\n\nclass ReportInstanceFilterParams(PaginationParams):\n    """Filter parameters for report instance queries"""\n    template_id: Optional[int] = None\n    status: Optional[ReportStatus] = None\n    output_format: Optional[ExportFormat] = None\n    generated_by_id: Optional[int] = None\n    date_from: Optional[datetime] = None\n    date_to: Optional[datetime] = None\n\n\nclass ReportScheduleFilterParams(PaginationParams):\n    """Filter parameters for report schedule queries"""\n    template_id: Optional[int] = None\n    frequency: Optional[ScheduleFrequency] = None\n    is_active: Optional[bool] = None\n\n\nclass DashboardFilterParams(PaginationParams):\n    """Filter parameters for dashboard queries"""\n    is_public: Optional[bool] = None\n    owner_id: Optional[int] = None\n    search: Optional[str] = None\n\n\nclass KPIDefinitionFilterParams(PaginationParams):\n    """Filter parameters for KPI definition queries"""\n    category: Optional[str] = None\n    is_active: Optional[bool] = None\n    search: Optional[str] = None\n\n\n# ==================== LIST RESPONSES ====================\n\nclass ReportTemplateListResponse(ListResponseBase):\n    """List response for report templates"""\n    items: List[ReportTemplateResponse]\n\n\nclass ReportInstanceListResponse(ListResponseBase):\n    """List response for report instances"""\n    items: List[ReportInstanceResponse]\n\n\nclass ReportScheduleListResponse(ListResponseBase):\n    """List response for report schedules"""\n    items: List[ReportScheduleResponse]\n\n\nclass DashboardListResponse(ListResponseBase):\n    """List response for dashboards"""\n    items: List[DashboardResponse]\n\n\nclass KPIDefinitionListResponse(ListResponseBase):\n    """List response for KPI definitions"""\n    items: List[KPIDefinitionResponse]\n\n\n# ==================== BULK OPERATIONS ====================\n\nclass ReportBulkDelete(BaseModel):\n    """Schema for bulk deleting report instances"""\n    ids: List[int] = Field(..., min_length=1, description="Report instance IDs to delete")\n\n\nclass DashboardDuplicate(BaseModel):\n    """Schema for duplicating a dashboard"""\n    dashboard_id: int = Field(..., description="Dashboard to duplicate")\n    new_name: str = Field(..., min_length=1, max_length=200, description="Name for new dashboard")\n    copy_widgets: bool = Field(default=True, description="Copy widgets")\n\n\nclass ReportTemplateDuplicate(BaseModel):\n    """Schema for duplicating a report template"""\n    template_id: int = Field(..., description="Template to duplicate")\n    new_name: str = Field(..., min_length=1, max_length=200, description="Name for new template")\n    new_code: str = Field(..., min_length=1, max_length=50, pattern=r"^[A-Z][A-Z0-9_]*$", description="Code for new template")\n\n\n# ==================== ANALYTICS RESPONSES ====================\n\nclass ReportStatisticsResponse(BaseModel):\n    """Report module statistics"""\n    total_templates: int = 0\n    total_reports_generated: int = 0\n    total_scheduled_reports: int = 0\n    active_schedules: int = 0\n    reports_this_month: int = 0\n    avg_execution_time_ms: int = 0\n    most_used_templates: List[Dict[str, Any]] = Field(default_factory=list)\n    reports_by_type: Dict[str, int] = Field(default_factory=dict)\n    reports_by_status: Dict[str, int] = Field(default_factory=dict)\n    recent_failures: int = 0\n\n\nclass DashboardStatisticsResponse(BaseModel):\n    """Dashboard module statistics"""\n    total_dashboards: int = 0\n    public_dashboards: int = 0\n    total_widgets: int = 0\n    widgets_by_type: Dict[str, int] = Field(default_factory=dict)\n    most_viewed_dashboards: List[Dict[str, Any]] = Field(default_factory=list)\n    avg_widgets_per_dashboard: Decimal = Decimal(\'0\')\n</create-file>\n</function_calls>'}
{'role': 'user', 'content': '<tool_result> <create-file> ToolResult(success=True, output="File \'backend/app/schemas/reports.py\' created successfully.") </create-file> </tool_result>'}
{'role': 'assistant', 'content': 'Now let me create the Consolidation schemas for multi-company financial consolidation.\n\n<function_calls>\n<create-file file_path="backend/app/schemas/consolidation.py">\n"""\nSAMMS Enterprise - Consolidation Engine Schemas\nMulti-company financial consolidation and intercompany reconciliation\n"""\n\nfrom datetime import datetime, date\nfrom typing import Optional, List, Dict, Any, Union, Literal\nfrom decimal import Decimal\nfrom enum import Enum\nfrom pydantic import BaseModel, Field, ConfigDict, field_validator, model_validator, computed_field\nfrom .base import (\n    BaseResponseSchema,\n    TimestampMixin,\n    PaginationParams,\n    ListResponseBase,\n    AuditMixin,\n    CompanyScopedMixin\n)\n\n\n# ==================== ENUMS ====================\n\nclass ConsolidationStatus(str, Enum):\n    """Consolidation process status"""\n    DRAFT = "draft"\n    IN_PROGRESS = "in_progress"\n    PENDING_REVIEW = "pending_review"\n    APPROVED = "approved"\n    COMPLETED = "completed"\n    ARCHIVED = "archived"\n    REJECTED = "rejected"\n\n\nclass ConsolidationType(str, Enum):\n    """Types of consolidation"""\n    FULL = "full"\n    PARTIAL = "partial"\n    PROPORTIONATE = "proportionate"\n    EQUITY_METHOD = "equity_method"\n\n\nclass EliminationType(str, Enum):\n    """Types of intercompany eliminations"""\n    INTERCOMPANY_SALES = "intercompany_sales"\n    INTERCOMPANY_PURCHASES = "intercompany_purchases"\n    INTERCOMPANY_RECEIVABLES = "intercompany_receivables"\n    INTERCOMPANY_PAYABLES = "intercompany_payables"\n    INTERCOMPANY_LOANS = "intercompany_loans"\n    INTERCOMPANY_INTEREST = "intercompany_interest"\n    INTERCOMPANY_DIVIDENDS = "intercompany_dividends"\n    INTERCOMPANY_INVENTORY_PROFIT = "intercompany_inventory_profit"\n    INTERCOMPANY_FIXED_ASSET_PROFIT = "intercompany_fixed_asset_profit"\n    INTERCOMPANY_MANAGEMENT_FEES = "intercompany_management_fees"\n    INTERCOMPANY_ROYALTIES = "intercompany_royalties"\n    OTHER = "other"\n\n\nclass MatchingStatus(str, Enum):\n    """Intercompany transaction matching status"""\n    UNMATCHED = "unmatched"\n    PARTIALLY_MATCHED = "partially_matched"\n    FULLY_MATCHED = "fully_matched"\n    EXCEPTION = "exception"\n    MANUAL_MATCH = "manual_match"\n    AUTO_MATCHED = "auto_matched"\n\n\nclass ConsolidationScope(str, Enum):\n    """Entity consolidation scope"""\n    FULL_CONSOLIDATION = "full_consolidation"\n    PROPORTIONAL = "proportional"\n    EQUITY_METHOD = "equity_method"\n    NON_CONSOLIDATED = "non_consolidated"\n    DISCONTINUED = "discontinued"\n\n\nclass CurrencyTranslationMethod(str, Enum):\n    """Currency translation methods"""\n    CURRENT_RATE = "current_rate"\n    TEMPORAL = "temporal"\n    CLOSING_RATE = "closing_rate"\n    AVERAGE_RATE = "average_rate"\n    HISTORICAL_RATE = "historical_rate"\n\n\nclass AdjustmentType(str, Enum):\n    """Types of consolidation adjustments"""\n    ELIMINATION = "elimination"\n    RECLASSIFICATION = "reclassification"\n    CORRECTION = "correction"\n    PROVISION = "provision"\n    ACCRUAL = "accrual"\n    REVALUATION = "revaluation"\n    CURRENCY_ADJUSTMENT = "currency_adjustment"\n    GOODWILL = "goodwill"\n    MINORITY_INTEREST = "minority_interest"\n    OTHER = "other"\n\n\nclass DataSource(str, Enum):\n    """Data source for consolidation"""\n    TRIAL_BALANCE = "trial_balance"\n    GENERAL_LEDGER = "general_ledger"\n    SUBSIDIARY_SYSTEM = "subsidiary_system"\n    EXCEL_IMPORT = "excel_import"\n    API_IMPORT = "api_import"\n    MANUAL_ENTRY = "manual_entry"\n\n\n# ==================== CONSOLIDATION PERIOD ====================\n\nclass ConsolidationPeriodBase(BaseModel):\n    """Base schema for consolidation periods"""\n    name: str = Field(..., min_length=1, max_length=200, description="Period name")\n    period_type: str = Field(default="monthly", description="Period type: monthly, quarterly, yearly")\n    start_date: date = Field(..., description="Period start date")\n    end_date: date = Field(..., description="Period end date")\n    fiscal_year: int = Field(..., ge=2000, le=2100, description="Fiscal year")\n    fiscal_quarter: Optional[int] = Field(None, ge=1, le=4, description="Fiscal quarter")\n    is_locked: bool = Field(default=False, description="Whether period is locked")\n    lock_date: Optional[datetime] = Field(None, description="Date when locked")\n    locked_by_id: Optional[int] = Field(None, description="User who locked")\n\n    @model_validator(mode=\'after\')\n    def validate_dates(self):\n        if self.start_date >= self.end_date:\n            raise ValueError("Start date must be before end date")\n        return self\n\n\nclass ConsolidationPeriodCreate(ConsolidationPeriodBase):\n    """Schema for creating consolidation periods"""\n    pass\n\n\nclass ConsolidationPeriodUpdate(BaseModel):\n    """Schema for updating consolidation periods"""\n    name: Optional[str] = Field(None, min_length=1, max_length=200)\n    is_locked: Optional[bool] = None\n\n\nclass ConsolidationPeriodResponse(ConsolidationPeriodBase, BaseResponseSchema):\n    """Schema for consolidation period responses"""\n    model_config = ConfigDict(from_attributes=True)\n\n\n# ==================== SUBSIDIARY DATA ====================\n\nclass SubsidiaryConsolidationBase(BaseModel):\n    """Base schema for subsidiary consolidation settings"""\n    subsidiary_id: int = Field(..., description="Subsidiary company ID")\n    consolidation_scope: ConsolidationScope = Field(default=ConsolidationScope.FULL_CONSOLIDATION, description="Consolidation scope")\n    ownership_percentage: Decimal = Field(default=Decimal(\'100.00\'), ge=0, le=100, description="Ownership percentage")\n    voting_percentage: Optional[Decimal] = Field(None, ge=0, le=100, description="Voting percentage")\n    consolidation_method: ConsolidationType = Field(default=ConsolidationType.FULL, description="Consolidation method")\n    functional_currency: str = Field(..., max_length=3, description="Functional currency")\n    reporting_currency: str = Field(..., max_length=3, description="Reporting currency")\n    translation_method: CurrencyTranslationMethod = Field(default=CurrencyTranslationMethod.CURRENT_RATE, description="Currency translation method")\n    consolidation_date: Optional[date] = Field(None, description="Date of acquisition/consolidation")\n    divestiture_date: Optional[date] = Field(None, description="Date of divestiture")\n    is_active: bool = Field(default=True, description="Whether subsidiary is active for consolidation")\n    data_source: DataSource = Field(default=DataSource.TRIAL_BALANCE, description="Data source")\n    data_import_frequency: str = Field(default="monthly", description="Data import frequency")\n    last_import_date: Optional[datetime] = Field(None, description="Last data import timestamp")\n    include_in_consolidation: bool = Field(default=True, description="Include in consolidation")\n\n\nclass SubsidiaryConsolidationCreate(SubsidiaryConsolidationBase):\n    """Schema for creating subsidiary consolidation settings"""\n    pass\n\n\nclass SubsidiaryConsolidationUpdate(BaseModel):\n    """Schema for updating subsidiary consolidation settings"""\n    consolidation_scope: Optional[ConsolidationScope] = None\n    ownership_percentage: Optional[Decimal] = Field(None, ge=0, le=100)\n    voting_percentage: Optional[Decimal] = Field(None, ge=0, le=100)\n    consolidation_method: Optional[ConsolidationType] = None\n    translation_method: Optional[CurrencyTranslationMethod] = None\n    consolidation_date: Optional[date] = None\n    divestiture_date: Optional[date] = None\n    is_active: Optional[bool] = None\n    data_source: Optional[DataSource] = None\n    data_import_frequency: Optional[str] = None\n    include_in_consolidation: Optional[bool] = None\n\n\nclass SubsidiaryConsolidationResponse(SubsidiaryConsolidationBase, BaseResponseSchema):\n    """Schema for subsidiary consolidation responses"""\n    subsidiary_name: Optional[str] = Field(None, description="Subsidiary name from relationship")\n    minority_interest_percentage: Decimal = Field(default=Decimal(\'0.00\'), description="Calculated minority interest %")\n\n    @computed_field\n    @property\n    def minority_interest(self) -> Decimal:\n        return Decimal(\'100\') - self.ownership_percentage\n\n    model_config = ConfigDict(from_attributes=True)\n\n\n# ==================== INTERCOMPANY TRANSACTION ====================\n\nclass IntercompanyTransactionBase(BaseModel):\n    """Base schema for intercompany transactions"""\n    transaction_number: str = Field(..., min_length=1, max_length=50, description="Transaction number")\n    transaction_date: date = Field(..., description="Transaction date")\n    description: str = Field(..., min_length=1, max_length=500, description="Transaction description")\n    elimination_type: EliminationType = Field(..., description="Type of intercompany transaction")\n    source_company_id: int = Field(..., description="Source company ID")\n    target_company_id: int = Field(..., description="Target company ID")\n    source_account_id: int = Field(..., description="Source company account ID")\n    target_account_id: int = Field(..., description="Target company account ID")\n    source_amount: Decimal = Field(..., description="Amount in source company currency")\n    target_amount: Decimal = Field(..., description="Amount in target company currency")\n    source_currency: str = Field(..., max_length=3, description="Source currency")\n    target_currency: str = Field(..., max_length=3, description="Target currency")\n    reporting_amount: Decimal = Field(..., description="Amount in reporting currency")\n    source_document_type: Optional[str] = Field(None, max_length=50, description="Source document type")\n    source_document_id: Optional[int] = Field(None, description="Source document ID")\n    matching_id: Optional[str] = Field(None, max_length=50, description="Matching transaction ID")\n    matching_status: MatchingStatus = Field(default=MatchingStatus.UNMATCHED, description="Matching status")\n    matching_confidence: Optional[Decimal] = Field(None, ge=0, le=1, description="Auto-matching confidence score")\n    variance_amount: Optional[Decimal] = Field(None, description="Variance if partially matched")\n    variance_reason: Optional[str] = Field(None, max_length=500, description="Variance explanation")\n    is_eliminated: bool = Field(default=False, description="Whether eliminated in consolidation")\n    elimination_id: Optional[int] = Field(None, description="Reference to elimination entry")\n    notes: Optional[str] = Field(None, max_length=2000, description="Additional notes")\n\n    @model_validator(mode=\'after\')\n    def validate_companies(self):\n        if self.source_company_id == self.target_company_id:\n            raise ValueError("Source and target companies must be different")\n        return self\n\n\nclass IntercompanyTransactionCreate(IntercompanyTransactionBase):\n    """Schema for creating intercompany transactions"""\n    pass\n\n\nclass IntercompanyTransactionUpdate(BaseModel):\n    """Schema for updating intercompany transactions"""\n    description: Optional[str] = Field(None, min_length=1, max_length=500)\n    elimination_type: Optional[EliminationType] = None\n    source_amount: Optional[Decimal] = None\n    target_amount: Optional[Decimal] = None\n    reporting_amount: Optional[Decimal] = None\n    matching_id: Optional[str] = Field(None, max_length=50)\n    matching_status: Optional[MatchingStatus] = None\n    variance_reason: Optional[str] = Field(None, max_length=500)\n    notes: Optional[str] = Field(None, max_length=2000)\n\n\nclass IntercompanyTransactionResponse(IntercompanyTransactionBase, BaseResponseSchema, CompanyScopedMixin):\n    """Schema for intercompany transaction responses"""\n    source_company_name: Optional[str] = None\n    target_company_name: Optional[str] = None\n    source_account_code: Optional[str] = None\n    target_account_code: Optional[str] = None\n\n    model_config = ConfigDict(from_attributes=True)\n\n\n# ==================== INTERCOMPANY MATCHING ====================\n\nclass IntercompanyMatchLineBase(BaseModel):\n    """Base schema for match lines"""\n    source_transaction_id: int = Field(..., description="Source transaction ID")\n    target_transaction_id: int = Field(..., description="Target transaction ID")\n    source_amount: Decimal = Field(..., description="Source transaction amount")\n    target_amount: Decimal = Field(..., description="Target transaction amount")\n    match_amount: Decimal = Field(..., description="Matched amount")\n    variance: Decimal = Field(default=Decimal(\'0\'), description="Unmatched variance")\n\n\nclass IntercompanyMatchLineCreate(IntercompanyMatchLineBase):\n    """Schema for creating match lines"""\n    pass\n\n\nclass IntercompanyMatchLineResponse(IntercompanyMatchLineBase, BaseResponseSchema):\n    """Schema for match line responses"""\n    match_id: int\n    model_config = ConfigDict(from_attributes=True)\n\n\nclass IntercompanyMatchBase(BaseModel):\n    """Base schema for intercompany matches"""\n    match_type: str = Field(default="one_to_one", description="Match type: one_to_one, many_to_one, many_to_many")\n    elimination_type: EliminationType = Field(..., description="Type of elimination")\n    total_source_amount: Decimal = Field(..., description="Total source amount")\n    total_target_amount: Decimal = Field(..., description="Total target amount")\n    matched_amount: Decimal = Field(..., description="Matched amount")\n    variance_amount: Decimal = Field(default=Decimal(\'0\'), description="Unmatched variance")\n    matching_method: str = Field(default="manual", description="Matching method: manual, auto, rule_based")\n    matching_rule_id: Optional[int] = Field(None, description="Rule used for auto-matching")\n    matching_score: Optional[Decimal] = Field(None, ge=0, le=1, description="Matching confidence score")\n    match_date: date = Field(..., description="Date of matching")\n    notes: Optional[str] = Field(None, max_length=2000, description="Matching notes")\n\n\nclass IntercompanyMatchCreate(IntercompanyMatchBase):\n    """Schema for creating intercompany matches"""\n    lines: List[IntercompanyMatchLineCreate] = Field(..., min_length=1, description="Match lines")\n\n\nclass IntercompanyMatchUpdate(BaseModel):\n    """Schema for updating intercompany matches"""\n    notes: Optional[str] = Field(None, max_length=2000)\n\n\nclass IntercompanyMatchResponse(IntercompanyMatchBase, BaseResponseSchema, CompanyScopedMixin):\n    """Schema for intercompany match responses"""\n    lines: List[IntercompanyMatchLineResponse] = Field(default_factory=list)\n    matched_by_id: int\n\n    model_config = ConfigDict(from_attributes=True)\n\n\n# ==================== ELIMINATION ENTRY ====================\n\nclass EliminationLineBase(BaseModel):\n    """Base schema for elimination entry lines"""\n    account_id: int = Field(..., description="Account ID")\n    description: Optional[str] = Field(None, max_length=500, description="Line description")\n    debit_amount: Decimal = Field(default=Decimal(\'0\'), ge=0, description="Debit amount")\n    credit_amount: Decimal = Field(default=Decimal(\'0\'), ge=0, description="Credit amount")\n    company_id: Optional[int] = Field(None, description="Company for partial elimination")\n    dimension1_id: Optional[int] = Field(None, description="Dimension 1 (department)")\n    dimension2_id: Optional[int] = Field(None, description="Dimension 2 (project)")\n    dimension3_id: Optional[int] = Field(None, description="Dimension 3 (cost center)")\n\n    @model_validator(mode=\'after\')\n    def validate_debit_credit(self):\n        if self.debit_amount > 0 and self.credit_amount > 0:\n            raise ValueError("Line cannot have both debit and credit amounts")\n        return self\n\n\nclass EliminationLineCreate(EliminationLineBase):\n    """Schema for creating elimination lines"""\n    pass\n\n\nclass EliminationLineResponse(EliminationLineBase, BaseResponseSchema):\n    """Schema for elimination line responses"""\n    elimination_id: int\n    account_code: Optional[str] = None\n    account_name: Optional[str] = None\n\n    model_config = ConfigDict(from_attributes=True)\n\n\nclass EliminationEntryBase(BaseModel):\n    """Base schema for elimination entries"""\n    entry_number: str = Field(..., min_length=1, max_length=50, description="Entry number")\n    description: str = Field(..., min_length=1, max_length=500, description="Entry description")\n    elimination_type: EliminationType = Field(..., description="Type of elimination")\n    entry_date: date = Field(..., description="Entry date")\n    period_id: int = Field(..., description="Consolidation period ID")\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    is_adjusting: bool = Field(default=False, description="Whether this is an adjusting entry")\n    is_recurring: bool = Field(default=False, description="Whether this is a recurring elimination")\n    recurring_frequency: Optional[str] = Field(None, description="Recurring frequency")\n    reference: Optional[str] = Field(None, max_length=100, description="Reference")\n    source_transactions: Optional[List[int]] = Field(None, description="Source IC transaction IDs")\n    auto_generated: bool = Field(default=False, description="Whether auto-generated")\n    generation_rule_id: Optional[int] = Field(None, description="Rule used for generation")\n\n    @model_validator(mode=\'after\')\n    def validate_balanced(self):\n        if self.total_debit != self.total_credit:\n            raise ValueError(f"Elimination entry must be balanced. Debit: {self.total_debit}, Credit: {self.total_credit}")\n        return self\n\n\nclass EliminationEntryCreate(EliminationEntryBase):\n    """Schema for creating elimination entries"""\n    lines: List[EliminationLineCreate] = Field(..., min_length=2, description="Elimination lines")\n\n    @model_validator(mode=\'after\')\n    def calculate_totals(self):\n        total_debit = sum(line.debit_amount for line in self.lines)\n        total_credit = sum(line.credit_amount for line in self.lines)\n        self.total_debit = total_debit\n        self.total_credit = total_credit\n        return self\n\n\nclass EliminationEntryUpdate(BaseModel):\n    """Schema for updating elimination entries"""\n    description: Optional[str] = Field(None, min_length=1, max_length=500)\n    reference: Optional[str] = Field(None, max_length=100)\n    notes: Optional[str] = Field(None, max_length=2000)\n    lines: Optional[List[EliminationLineCreate]] = None\n\n\nclass EliminationEntryResponse(EliminationEntryBase, BaseResponseSchema, CompanyScopedMixin):\n    """Schema for elimination entry responses"""\n    lines: List[EliminationLineResponse] = Field(default_factory=list)\n    status: ConsolidationStatus = Field(default=ConsolidationStatus.DRAFT)\n    created_by_id: int\n    approved_by_id: Optional[int] = None\n    approved_at: Optional[datetime] = None\n\n    model_config = ConfigDict(from_attributes=True)\n\n\n# ==================== CONSOLIDATION ADJUSTMENT ====================\n\nclass ConsolidationAdjustmentBase(BaseModel):\n    """Base schema for consolidation adjustments"""\n    adjustment_number: str = Field(..., min_length=1, max_length=50, description="Adjustment number")\n    description: str = Field(..., min_length=1, max_length=500, description="Adjustment description")\n    adjustment_type: AdjustmentType = Field(..., description="Type of adjustment")\n    adjustment_date: date = Field(..., description="Adjustment date")\n    period_id: int = Field(..., description="Consolidation period ID")\n    subsidiary_id: Optional[int] = Field(None, description="Related subsidiary ID")\n    amount: Decimal = Field(..., description="Adjustment amount")\n    currency: str = Field(..., max_length=3, description="Currency")\n    reporting_amount: Decimal = Field(..., description="Amount in reporting currency")\n    reference: Optional[str] = Field(None, max_length=100, description="Reference")\n    supporting_document_id: Optional[int] = Field(None, description="Supporting document ID")\n    justification: Optional[str] = Field(None, max_length=2000, description="Adjustment justification")\n    is_recurring: bool = Field(default=False, description="Whether recurring adjustment")\n    recurring_frequency: Optional[str] = Field(None, description="Recurring frequency")\n    approval_status: str = Field(default="pending", description="Approval status")\n    approved_by_id: Optional[int] = Field(None, description="Approved by user ID")\n    approved_at: Optional[datetime] = Field(None, description="Approval timestamp")\n\n\nclass ConsolidationAdjustmentCreate(ConsolidationAdjustmentBase):\n    """Schema for creating consolidation adjustments"""\n    pass\n\n\nclass ConsolidationAdjustmentUpdate(BaseModel):\n    """Schema for updating consolidation adjustments"""\n    description: Optional[str] = Field(None, min_length=1, max_length=500)\n    adjustment_type: Optional[AdjustmentType] = None\n    amount: Optional[Decimal] = None\n    reference: Optional[str] = Field(None, max_length=100)\n    justification: Optional[str] = Field(None, max_length=2000)\n\n\nclass ConsolidationAdjustmentResponse(ConsolidationAdjustmentBase, BaseResponseSchema, CompanyScopedMixin):\n    """Schema for consolidation adjustment responses"""\n    subsidiary_name: Optional[str] = None\n    created_by_id: int\n\n    model_config = ConfigDict(from_attributes=True)\n\n\n# ==================== CONSOLIDATION WORKSHEET ====================\n\nclass WorksheetLineBase(BaseModel):\n    """Base schema for worksheet lines"""\n    account_id: int = Field(..., description="Account ID")\n    account_code: Optional[str] = None\n    account_name: Optional[str] = None\n    parent_account_id: Optional[int] = None\n    line_order: int = Field(default=0, ge=0, description="Display order")\n    is_header: bool = Field(default=False, description="Whether this is a header line")\n    indent_level: int = Field(default=0, ge=0, le=10, description="Indentation level")\n    \n    # Trial balance amounts by subsidiary\n    subsidiary_balances: Optional[Dict[str, Decimal]] = Field(None, description="Balances by subsidiary ID")\n    \n    # Consolidation entries\n    eliminations_debit: Decimal = Field(default=Decimal(\'0\'), description="Elimination debit")\n    eliminations_credit: Decimal = Field(default=Decimal(\'0\'), description="Elimination credit")\n    adjustments_debit: Decimal = Field(default=Decimal(\'0\'), description="Adjustment debit")\n    adjustments_credit: Decimal = Field(default=Decimal(\'0\'), description="Adjustment credit")\n    \n    # Calculated fields\n    consolidated_balance: Optional[Decimal] = Field(None, description="Consolidated balance")\n    prior_period_balance: Optional[Decimal] = Field(None, description="Prior period balance")\n    variance: Optional[Decimal] = Field(None, description="Period variance")\n\n\nclass WorksheetLineResponse(WorksheetLineBase, BaseResponseSchema):\n    """Schema for worksheet line responses"""\n    worksheet_id: int\n\n    model_config = ConfigDict(from_attributes=True)\n\n\nclass ConsolidationWorksheetBase(BaseModel):\n    """Base schema for consolidation worksheets"""\n    name: str = Field(..., min_length=1, max_length=200, description="Worksheet name")\n    description: Optional[str] = Field(None, max_length=2000, description="Worksheet description")\n    period_id: int = Field(..., description="Consolidation period ID")\n    worksheet_type: str = Field(default="balance_sheet", description="Worksheet type: balance_sheet, income_statement, cash_flow")\n    status: ConsolidationStatus = Field(default=ConsolidationStatus.DRAFT, description="Worksheet status")\n    reporting_currency: str = Field(..., max_length=3, description="Reporting currency")\n    include_zero_balances: bool = Field(default=False, description="Include accounts with zero balances")\n    include_unapproved: bool = Field(default=False, description="Include unapproved entries")\n    show_prior_period: bool = Field(default=True, description="Show prior period comparison")\n    show_variance: bool = Field(default=True, description="Show variance column")\n\n\nclass ConsolidationWorksheetCreate(ConsolidationWorksheetBase):\n    """Schema for creating consolidation worksheets"""\n    subsidiary_ids: Optional[List[int]] = Field(None, description="Subsidiaries to include")\n    generate_lines: bool = Field(default=True, description="Auto-generate worksheet lines")\n\n\nclass ConsolidationWorksheetUpdate(BaseModel):\n    """Schema for updating consolidation worksheets"""\n    name: Optional[str] = Field(None, min_length=1, max_length=200)\n    description: Optional[str] = Field(None, max_length=2000)\n    status: Optional[ConsolidationStatus] = None\n    include_zero_balances: Optional[bool] = None\n    include_unapproved: Optional[bool] = None\n    show_prior_period: Optional[bool] = None\n    show_variance: Optional[bool] = None\n\n\nclass ConsolidationWorksheetResponse(ConsolidationWorksheetBase, BaseResponseSchema, CompanyScopedMixin):\n    """Schema for consolidation worksheet responses"""\n    lines: List[WorksheetLineResponse] = Field(default_factory=list)\n    subsidiaries: List[SubsidiaryConsolidationResponse] = Field(default_factory=list)\n    total_eliminations: Decimal = Field(default=Decimal(\'0\'), description="Total eliminations")\n    total_adjustments: Decimal = Field(default=Decimal(\'0\'), description="Total adjustments")\n    is_balanced: bool = Field(default=True, description="Whether worksheet is balanced")\n    balance_check_amount: Decimal = Field(default=Decimal(\'0\'), description="Balance check variance")\n    created_by_id: int\n    reviewed_by_id: Optional[int] = None\n    reviewed_at: Optional[datetime] = None\n    approved_by_id: Optional[int] = None\n    approved_at: Optional[datetime] = None\n\n    model_config = ConfigDict(from_attributes=True)\n\n\n# ==================== CONSOLIDATION RUN ====================\n\nclass ConsolidationRunBase(BaseModel):\n    """Base schema for consolidation runs"""\n    name: str = Field(..., min_length=1, max_length=200, description="Run name")\n    period_id: int = Field(..., description="Consolidation period ID")\n    run_type: str = Field(default="full", description="Run type: full, incremental, simulation")\n    status: ConsolidationStatus = Field(default=ConsolidationStatus.DRAFT, description="Run status")\n    started_at: Optional[datetime] = Field(None, description="Run start timestamp")\n    completed_at: Optional[datetime] = Field(None, description="Run completion timestamp")\n    error_message: Optional[str] = Field(None, max_length=5000, description="Error message if failed")\n    processing_log: Optional[List[Dict[str, Any]]] = Field(None, description="Processing log entries")\n    statistics: Optional[Dict[str, Any]] = Field(None, description="Run statistics")\n\n\nclass ConsolidationRunCreate(ConsolidationRunBase):\n    """Schema for creating consolidation runs"""\n    subsidiary_ids: Optional[List[int]] = Field(None, description="Subsidiaries to process")\n    auto_eliminate: bool = Field(default=True, description="Auto-generate eliminations")\n    auto_match: bool = Field(default=True, description="Auto-match intercompany transactions")\n    simulation_mode: bool = Field(default=False, description="Run in simulation mode")\n\n\nclass ConsolidationRunUpdate(BaseModel):\n    """Schema for updating consolidation runs"""\n    name: Optional[str] = Field(None, min_length=1, max_length=200)\n    status: Optional[ConsolidationStatus] = None\n    error_message: Optional[str] = Field(None, max_length=5000)\n\n\nclass ConsolidationRunResponse(ConsolidationRunBase, BaseResponseSchema, CompanyScopedMixin):\n    """Schema for consolidation run responses"""\n    worksheets: List[ConsolidationWorksheetResponse] = Field(default_factory=list)\n    elimination_entries: List[EliminationEntryResponse] = Field(default_factory=list)\n    adjustments: List[ConsolidationAdjustmentResponse] = Field(default_factory=list)\n    total_subscribers: int = Field(default=0, description="Number of subsidiaries processed")\n    total_eliminations: int = Field(default=0, description="Number of elimination entries")\n    total_adjustments: int = Field(default=0, description="Number of adjustments")\n    matched_transactions: int = Field(default=0, description="Matched IC transactions")\n    unmatched_transactions: int = Field(default=0, description="Unmatched IC transactions")\n    initiated_by_id: int\n\n    model_config = ConfigDict(from_attributes=True)\n\n\n# ==================== CURRENCY TRANSLATION ====================\n\nclass ExchangeRateHistoryBase(BaseModel):\n    """Base schema for exchange rate history"""\n    from_currency: str = Field(..., max_length=3, description="Source currency")\n    to_currency: str = Field(..., max_length=3, description="Target currency")\n    rate_date: date = Field(..., description="Rate effective date")\n    rate_type: str = Field(default="spot", description="Rate type: spot, average, closing, historical")\n    rate: Decimal = Field(..., gt=0, description="Exchange rate")\n    inverse_rate: Optional[Decimal] = Field(None, gt=0, description="Inverse rate")\n    source: Optional[str] = Field(None, max_length=100, description="Rate source")\n\n\nclass ExchangeRateHistoryCreate(ExchangeRateHistoryBase):\n    """Schema for creating exchange rate history"""\n    pass\n\n\nclass ExchangeRateHistoryResponse(ExchangeRateHistoryBase, BaseResponseSchema):\n    """Schema for exchange rate history responses"""\n    model_config = ConfigDict(from_attributes=True)\n\n\nclass CurrencyTranslationResult(BaseModel):\n    """Result of currency translation"""\n    original_currency: str\n    original_amount: Decimal\n    translated_currency: str\n    translated_amount: Decimal\n    exchange_rate: Decimal\n    rate_type: str\n    rate_date: date\n    translation_method: CurrencyTranslationMethod\n    gain_loss: Optional[Decimal] = Field(None, description="Currency gain/loss")\n\n\n# ==================== MINORITY INTEREST ====================\n\nclass MinorityInterestBase(BaseModel):\n    """Base schema for minority interest"""\n    subsidiary_id: int = Field(..., description="Subsidiary company ID")\n    period_id: int = Field(..., description="Consolidation period ID")\n    minority_percentage: Decimal = Field(..., ge=0, le=100, description="Minority ownership %")\n    net_income: Decimal = Field(default=Decimal(\'0\'), description="Subsidiary net income")\n    minority_share_income: Decimal = Field(default=Decimal(\'0\'), description="Minority share of net income")\n    equity_adjustment: Decimal = Field(default=Decimal(\'0\'), description="Equity adjustment")\n    dividends_declared: Decimal = Field(default=Decimal(\'0\'), description="Dividends declared to minority")\n    ending_balance: Decimal = Field(default=Decimal(\'0\'), description="Ending minority interest balance")\n\n\nclass MinorityInterestCreate(MinorityInterestBase):\n    """Schema for creating minority interest records"""\n    pass\n\n\nclass MinorityInterestResponse(MinorityInterestBase, BaseResponseSchema, CompanyScopedMixin):\n    """Schema for minority interest responses"""\n    subsidiary_name: Optional[str] = None\n    beginning_balance: Decimal = Field(default=Decimal(\'0\'), description="Beginning balance")\n\n    model_config = ConfigDict(from_attributes=True)\n\n\n# ==================== FILTER PARAMETERS ====================\n\nclass ConsolidationPeriodFilterParams(PaginationParams):\n    """Filter parameters for consolidation period queries"""\n    fiscal_year: Optional[int] = None\n    is_locked: Optional[bool] = None\n\n\nclass IntercompanyTransactionFilterParams(PaginationParams):\n    """Filter parameters for intercompany transaction queries"""\n    source_company_id: Optional[int] = None\n    target_company_id: Optional[int] = None\n    elimination_type: Optional[EliminationType] = None\n    matching_status: Optional[MatchingStatus] = None\n    is_eliminated: Optional[bool] = None\n    date_from: Optional[date] = None\n    date_to: Optional[date] = None\n\n\nclass EliminationEntryFilterParams(PaginationParams):\n    """Filter parameters for elimination entry queries"""\n    period_id: Optional[int] = None\n    elimination_type: Optional[EliminationType] = None\n    status: Optional[ConsolidationStatus] = None\n    auto_generated: Optional[bool] = None\n\n\nclass ConsolidationWorksheetFilterParams(PaginationParams):\n    """Filter parameters for consolidation worksheet queries"""\n    period_id: Optional[int] = None\n    worksheet_type: Optional[str] = None\n    status: Optional[ConsolidationStatus] = None\n\n\nclass ConsolidationRunFilterParams(PaginationParams):\n    """Filter parameters for consolidation run queries"""\n    period_id: Optional[int] = None\n    status: Optional[ConsolidationStatus] = None\n    run_type: Optional[str] = None\n\n\n# ==================== LIST RESPONSES ====================\n\nclass ConsolidationPeriodListResponse(ListResponseBase):\n    """List response for consolidation periods"""\n    items: List[ConsolidationPeriodResponse]\n\n\nclass SubsidiaryConsolidationListResponse(ListResponseBase):\n    """List response for subsidiary consolidation settings"""\n    items: List[SubsidiaryConsolidationResponse]\n\n\nclass IntercompanyTransactionListResponse(ListResponseBase):\n    """List response for intercompany transactions"""\n    items: List[IntercompanyTransactionResponse]\n\n\nclass IntercompanyMatchListResponse(ListResponseBase):\n    """List response for intercompany matches"""\n    items: List[IntercompanyMatchResponse]\n\n\nclass EliminationEntryListResponse(ListResponseBase):\n    """List response for elimination entries"""\n    items: List[EliminationEntryResponse]\n\n\nclass ConsolidationAdjustmentListResponse(ListResponseBase):\n    """List response for consolidation adjustments"""\n    items: List[ConsolidationAdjustmentResponse]\n\n\nclass ConsolidationWorksheetListResponse(ListResponseBase):\n    """List response for consolidation worksheets"""\n    items: List[ConsolidationWorksheetResponse]\n\n\nclass ConsolidationRunListResponse(ListResponseBase):\n    """List response for consolidation runs"""\n    items: List[ConsolidationRunResponse]\n\n\nclass MinorityInterestListResponse(ListResponseBase):\n    """List response for minority interests"""\n    items: List[MinorityInterestResponse]\n\n\n# ==================== ANALYTICS RESPONSES ====================\n\nclass ConsolidationStatisticsResponse(BaseModel):\n    """Consolidation module statistics"""\n    total_subscribers: int = 0\n    active_subscribers: int = 0\n    total_ic_transactions: int = 0\n    matched_transactions: int = 0\n    unmatched_transactions: int = 0\n    match_rate: Decimal = Decimal(\'0\')\n    total_eliminations: int = 0\n    total_elimination_amount: Decimal = Decimal(\'0\')\n    pending_eliminations: int = 0\n    total_adjustments: int = 0\n    pending_adjustments: int = 0\n    consolidation_runs_this_period: int = 0\n    last_consolidation_date: Optional[datetime] = None\n    currencies_involved: List[str] = Field(default_factory=list)\n    intercompany_balances: Dict[str, Decimal] = Field(default_factory=dict)\n\n\nclass IntercompanyBalanceSummary(BaseModel):\n    """Intercompany balance summary between two entities"""\n    source_company_id: int\n    source_company_name: str\n    target_company_id: int\n    target_company_name: str\n    elimination_type: EliminationType\n    source_balance: Decimal\n    target_balance: Decimal\n    variance: Decimal\n    match_status: MatchingStatus\n    matched_amount: Decimal\n    unmatched_amount: Decimal\n\n\nclass ConsolidationValidationResult(BaseModel):\n    """Result of consolidation validation"""\n    is_valid: bool\n    errors: List[str] = Field(default_factory=list)\n    warnings: List[str] = Field(default_factory=list)\n    unbalanced_accounts: List[Dict[str, Any]] = Field(default_factory=list)\n    unmatched_transactions: List[int] = Field(default_factory=list)\n    missing_subsidiary_data: List[int] = Field(default_factory=list)\n    currency_translation_issues: List[Dict[str, Any]] = Field(default_factory=list)\n</create-file>\n</function_calls>'}
{'role': 'user', 'content': '<tool_result> <create-file> ToolResult(success=True, output="File \'backend/app/schemas/consolidation.py\' created successfully.") </create-file> </tool_result>'}
{'role': 'assistant', 'content': 'Now let me create the Asset schemas for the Fixed Asset Registry with depreciation tracking.\n\n<function_calls>\n<create-file file_path="backend/app/schemas/asset.py">\n"""\nSAMMS Enterprise - Fixed Asset Registry Schemas\nFixed asset management with depreciation and automated journal entries\n"""\n\nfrom datetime import datetime, date\nfrom typing import Optional, List, Dict, Any, Union, Literal\nfrom decimal import Decimal\nfrom enum import Enum\nfrom pydantic import BaseModel, Field, ConfigDict, field_validator, model_validator, computed_field\nfrom .base import (\n    BaseResponseSchema,\n    TimestampMixin,\n    PaginationParams,\n    ListResponseBase,\n    AuditMixin,\n    CompanyScopedMixin\n)\n\n\n# ==================== ENUMS ====================\n\nclass AssetStatus(str, Enum):\n    """Asset lifecycle status"""\n    DRAFT = "draft"\n    PENDING_APPROVAL = "pending_approval"\n    ACTIVE = "active"\n    IN_USE = "in_use"\n    UNDER_CONSTRUCTION = "under_construction"\n    IDLE = "idle"\n    HELD_FOR_SALE = "held_for_sale"\n    DISPOSED = "disposed"\n    FULLY_DEPRECIATED = "fully_depreciated"\n    WRITTEN_OFF = "written_off"\n    REVALUED = "revalued"\n    IMPAIRED = "impaired"\n\n\nclass AssetCategory(str, Enum):\n    """Asset category types"""\n    LAND = "land"\n    BUILDING = "building"\n    MACHINERY = "machinery"\n    EQUIPMENT = "equipment"\n    VEHICLE = "vehicle"\n    FURNITURE_FIXTURES = "furniture_fixtures"\n    COMPUTER_HARDWARE = "computer_hardware"\n    COMPUTER_SOFTWARE = "computer_software"\n    LEASEHOLD_IMPROVEMENTS = "leasehold_improvements"\n    INTANGIBLE_ASSETS = "intangible_assets"\n    CONSTRUCTION_IN_PROGRESS = "construction_in_progress"\n    GOODWILL = "goodwill"\n    PATENTS = "patents"\n    TRADEMARKS = "trademarks"\n    COPYRIGHTS = "copyrights"\n    LICENSES = "licenses"\n    NATURAL_RESOURCES = "natural_resources"\n    BIOLOGICAL_ASSETS = "biological_assets"\n    INVESTMENT_PROPERTY = "investment_property"\n    RIGHT_OF_USE_ASSET = "right_of_use_asset"\n    OTHER = "other"\n\n\nclass DepreciationMethod(str, Enum):\n    """Depreciation calculation methods"""\n    STRAIGHT_LINE = "straight_line"\n    DECLINING_BALANCE = "declining_balance"\n    DOUBLE_DECLINING = "double_declining"\n    SUM_OF_YEARS_DIGITS = "sum_of_years_digits"\n    UNITS_OF_PRODUCTION = "units_of_production"\n    NONE = "none"\n    CUSTOM = "custom"\n\n\nclass AssetValuationMethod(str, Enum):\n    """Asset valuation methods"""\n    HISTORICAL_COST = "historical_cost"\n    REVALUATION = "revaluation"\n    FAIR_VALUE = "fair_value"\n    NET_REALIZABLE_VALUE = "net_realizable_value"\n    PRESENT_VALUE = "present_value"\n\n\nclass DisposalMethod(str, Enum):\n    """Asset disposal methods"""\n    SALE = "sale"\n    SCRAPPING = "scrapping"\n    DONATION = "donation"\n    EXCHANGE = "exchange"\n    THEFT = "theft"\n    DESTRUCTION = "destruction"\n    TRANSFER = "transfer"\n    OTHER = "other"\n\n\nclass ImpairmentStatus(str, Enum):\n    """Asset impairment status"""\n    NOT_IMPAIRED = "not_impaired"\n    POTENTIALLY_IMPAIRED = "potentially_impaired"\n    IMPAIRED = "impaired"\n    REVERSED = "reversed"\n\n\nclass MaintenanceType(str, Enum):\n    """Types of maintenance"""\n    PREVENTIVE = "preventive"\n    CORRECTIVE = "corrective"\n    PREDICTIVE = "predictive"\n    EMERGENCY = "emergency"\n    ROUTINE = "routine"\n    OVERHAUL = "overhaul"\n\n\nclass MaintenanceStatus(str, Enum):\n    """Maintenance record status"""\n    SCHEDULED = "scheduled"\n    IN_PROGRESS = "in_progress"\n    COMPLETED = "completed"\n    CANCELLED = "cancelled"\n    OVERDUE = "overdue"\n\n\nclass InsuranceStatus(str, Enum):\n    """Insurance policy status"""\n    ACTIVE = "active"\n    EXPIRED = "expired"\n    CANCELLED = "cancelled"\n    PENDING_RENEWAL = "pending_renewal"\n\n\n# ==================== ASSET CLASS ====================\n\nclass AssetClassBase(BaseModel):\n    """Base schema for asset classes"""\n    name: str = Field(..., min_length=1, max_length=200, description="Asset class name")\n    code: str = Field(..., min_length=1, max_length=20, pattern=r"^[A-Z][A-Z0-9._-]*$", description="Unique code")\n    description: Optional[str] = Field(None, max_length=2000, description="Description")\n    category: AssetCategory = Field(..., description="Asset category")\n    parent_class_id: Optional[int] = Field(None, description="Parent asset class ID")\n    depreciation_method: DepreciationMethod = Field(default=DepreciationMethod.STRAIGHT_LINE, description="Default depreciation method")\n    useful_life_years: int = Field(..., ge=0, le=100, description="Default useful life in years")\n    useful_life_months: int = Field(default=0, ge=0, le=1199, description="Additional months")\n    salvage_value_percentage: Decimal = Field(default=Decimal(\'0\'), ge=0, le=100, description="Default salvage value %")\n    depreciation_rate: Optional[Decimal] = Field(None, ge=0, le=100, description="Depreciation rate for declining balance")\n    asset_account_id: int = Field(..., description="GL account for asset cost")\n    accumulated_depreciation_account_id: int = Field(..., description="GL account for accumulated depreciation")\n    depreciation_expense_account_id: int = Field(..., description="GL account for depreciation expense")\n    impairment_account_id: Optional[int] = Field(None, description="GL account for impairment losses")\n    gain_loss_account_id: Optional[int] = Field(None, description="GL account for disposal gain/loss")\n    is_active: bool = Field(default=True, description="Whether class is active")\n    requires_tracking: bool = Field(default=True, description="Requires individual asset tracking")\n    requires_maintenance: bool = Field(default=False, description="Requires maintenance tracking")\n    requires_insurance: bool = Field(default=False, description="Requires insurance tracking")\n    custom_fields_schema: Optional[Dict[str, Any]] = Field(None, description="Custom fields definition")\n\n\nclass AssetClassCreate(AssetClassBase):\n    """Schema for creating asset classes"""\n    pass\n\n\nclass AssetClassUpdate(BaseModel):\n    """Schema for updating asset classes"""\n    name: Optional[str] = Field(None, min_length=1, max_length=200)\n    description: Optional[str] = Field(None, max_length=2000)\n    depreciation_method: Optional[DepreciationMethod] = None\n    useful_life_years: Optional[int] = Field(None, ge=0, le=100)\n    useful_life_months: Optional[int] = Field(None, ge=0, le=1199)\n    salvage_value_percentage: Optional[Decimal] = Field(None, ge=0, le=100)\n    depreciation_rate: Optional[Decimal] = Field(None, ge=0, le=100)\n    asset_account_id: Optional[int] = None\n    accumulated_depreciation_account_id: Optional[int] = None\n    depreciation_expense_account_id: Optional[int] = None\n    impairment_account_id: Optional[int] = None\n    gain_loss_account_id: Optional[int] = None\n    is_active: Optional[bool] = None\n    requires_tracking: Optional[bool] = None\n    requires_maintenance: Optional[bool] = None\n    requires_insurance: Optional[bool] = None\n    custom_fields_schema: Optional[Dict[str, Any]] = None\n\n\nclass AssetClassResponse(AssetClassBase, BaseResponseSchema, CompanyScopedMixin):\n    """Schema for asset class responses"""\n    full_code: Optional[str] = Field(None, description="Full hierarchical code")\n    total_assets: int = Field(default=0, description="Total assets in class")\n    total_cost: Decimal = Field(default=Decimal(\'0\'), description="Total asset cost")\n    total_accumulated_depreciation: Decimal = Field(default=Decimal(\'0\'), description="Total accumulated depreciation")\n    total_net_book_value: Decimal = Field(default=Decimal(\'0\'), description="Total net book value")\n\n    model_config = ConfigDict(from_attributes=True)\n\n\n# ==================== ASSET LOCATION ====================\n\nclass AssetLocationBase(BaseModel):\n    """Base schema for asset locations"""\n    name: str = Field(..., min_length=1, max_length=200, description="Location name")\n    code: str = Field(..., min_length=1, max_length=20, description="Unique location code")\n    description: Optional[str] = Field(None, max_length=2000, description="Description")\n    parent_location_id: Optional[int] = Field(None, description="Parent location ID")\n    location_type: str = Field(default="building", description="Location type: building, floor, room, warehouse, site, etc.")\n    address_line1: Optional[str] = Field(None, max_length=200, description="Address line 1")\n    address_line2: Optional[str] = Field(None, max_length=200, description="Address line 2")\n    city: Optional[str] = Field(None, max_length=100, description="City")\n    state_province: Optional[str] = Field(None, max_length=100, description="State/Province")\n    postal_code: Optional[str] = Field(None, max_length=20, description="Postal code")\n    country: Optional[str] = Field(None, max_length=100, description="Country")\n    latitude: Optional[Decimal] = Field(None, ge=-90, le=90, description="GPS latitude")\n    longitude: Optional[Decimal] = Field(None, ge=-180, le=180, description="GPS longitude")\n    manager_id: Optional[int] = Field(None, description="Responsible manager user ID")\n    department_id: Optional[int] = Field(None, description="Owning department ID")\n    is_active: bool = Field(default=True, description="Whether location is active")\n\n\nclass AssetLocationCreate(AssetLocationBase):\n    """Schema for creating asset locations"""\n    pass\n\n\nclass AssetLocationUpdate(BaseModel):\n    """Schema for updating asset locations"""\n    name: Optional[str] = Field(None, min_length=1, max_length=200)\n    description: Optional[str] = Field(None, max_length=2000)\n    address_line1: Optional[str] = Field(None, max_length=200)\n    address_line2: Optional[str] = Field(None, max_length=200)\n    city: Optional[str] = Field(None, max_length=100)\n    state_province: Optional[str] = Field(None, max_length=100)\n    postal_code: Optional[str] = Field(None, max_length=20)\n    country: Optional[str] = Field(None, max_length=100)\n    latitude: Optional[Decimal] = Field(None, ge=-90, le=90)\n    longitude: Optional[Decimal] = Field(None, ge=-180, le=180)\n    manager_id: Optional[int] = None\n    department_id: Optional[int] = None\n    is_active: Optional[bool] = None\n\n\nclass AssetLocationResponse(AssetLocationBase, BaseResponseSchema, CompanyScopedMixin):\n    """Schema for asset location responses"""\n    full_path: Optional[str] = Field(None, description="Full hierarchical path")\n    total_assets: int = Field(default=0, description="Total assets at location")\n    total_asset_value: Decimal = Field(default=Decimal(\'0\'), description="Total asset value at location")\n\n    model_config = ConfigDict(from_attributes=True)\n\n\n# ==================== FIXED ASSET ====================\n\nclass FixedAssetBase(BaseModel):\n    """Base schema for fixed assets"""\n    asset_number: str = Field(..., min_length=1, max_length=50, description="Unique asset number")\n    name: str = Field(..., min_length=1, max_length=200, description="Asset name")\n    description: Optional[str] = Field(None, max_length=2000, description="Asset description")\n    asset_class_id: int = Field(..., description="Asset class ID")\n    category: AssetCategory = Field(..., description="Asset category")\n    status: AssetStatus = Field(default=AssetStatus.ACTIVE, description="Asset status")\n    \n    # Acquisition Information\n    acquisition_date: date = Field(..., description="Date of acquisition")\n    acquisition_cost: Decimal = Field(..., ge=0, description="Original acquisition cost")\n    acquisition_type: str = Field(default="purchase", description="How asset was acquired: purchase, construction, donation, exchange, transfer")\n    vendor_id: Optional[int] = Field(None, description="Vendor ID if purchased")\n    purchase_order_id: Optional[int] = Field(None, description="Related purchase order ID")\n    invoice_id: Optional[int] = Field(None, description="Related invoice ID")\n    invoice_number: Optional[str] = Field(None, max_length=50, description="Invoice number")\n    \n    # Depreciation Settings\n    depreciation_method: DepreciationMethod = Field(default=DepreciationMethod.STRAIGHT_LINE, description="Depreciation method")\n    useful_life_years: int = Field(..., ge=0, le=100, description="Useful life in years")\n    useful_life_months: int = Field(default=0, ge=0, le=1199, description="Additional months")\n    salvage_value: Decimal = Field(default=Decimal(\'0\'), ge=0, description="Expected salvage value")\n    depreciation_start_date: Optional[date] = Field(None, description="Depreciation start date")\n    depreciation_end_date: Optional[date] = Field(None, description="Depreciation end date")\n    \n    # Current Values\n    accumulated_depreciation: Decimal = Field(default=Decimal(\'0\'), description="Total accumulated depreciation")\n    net_book_value: Optional[Decimal] = Field(None, description="Current net book value")\n    revaluation_reserve: Decimal = Field(default=Decimal(\'0\'), description="Revaluation reserve balance")\n    impairment_loss: Decimal = Field(default=Decimal(\'0\'), description="Accumulated impairment losses")\n    \n    # Location and Custody\n    location_id: Optional[int] = Field(None, description="Physical location ID")\n    custodian_id: Optional[int] = Field(None, description="Custodian employee ID")\n    department_id: Optional[int] = Field(None, description="Owning department ID")\n    cost_center_id: Optional[int] = Field(None, description="Cost center ID")\n    \n    # Physical Details\n    serial_number: Optional[str] = Field(None, max_length=100, description="Serial number")\n    model_number: Optional[str] = Field(None, max_length=100, description="Model number")\n    manufacturer: Optional[str] = Field(None, max_length=200, description="Manufacturer")\n    brand: Optional[str] = Field(None, max_length=100, description="Brand name")\n    color: Optional[str] = Field(None, max_length=50, description="Color")\n    size: Optional[str] = Field(None, max_length=50, description="Size")\n    weight: Optional[Decimal] = Field(None, description="Weight")\n    weight_unit: Optional[str] = Field(None, max_length=10, description="Weight unit")\n    dimensions: Optional[str] = Field(None, max_length=100, description="Dimensions")\n    \n    # Identification\n    barcode: Optional[str] = Field(None, max_length=100, description="Barcode")\n    rfid_tag: Optional[str] = Field(None, max_length=100, description="RFID tag")\n    plate_number: Optional[str] = Field(None, max_length=50, description="Asset plate number")\n    \n    # Additional Information\n    warranty_expiry_date: Optional[date] = Field(None, description="Warranty expiry date")\n    insurance_policy_id: Optional[int] = Field(None, description="Insurance policy ID")\n    lease_id: Optional[int] = Field(None, description="Related lease ID")\n    project_id: Optional[int] = Field(None, description="Related project ID")\n    \n    # GL Integration\n    asset_account_id: int = Field(..., description="GL account for asset cost")\n    accumulated_depreciation_account_id: int = Field(..., description="GL account for accumulated depreciation")\n    depreciation_expense_account_id: int = Field(..., description="GL account for depreciation expense")\n    \n    # Custom Data\n    custom_fields: Optional[Dict[str, Any]] = Field(None, description="Custom field values")\n    tags: Optional[List[str]] = Field(None, description="Tags for categorization")\n    \n    # Attachments\n    image_url: Optional[str] = Field(None, max_length=500, description="Asset image URL")\n    document_ids: Optional[List[int]] = Field(None, description="Related document IDs")\n    \n    notes: Optional[str] = Field(None, max_length=5000, description="Additional notes")\n\n\nclass FixedAssetCreate(FixedAssetBase):\n    """Schema for creating fixed assets"""\n    auto_generate_depreciation: bool = Field(default=True, description="Auto-generate depreciation schedule")\n    \n    @model_validator(mode=\'after\')\n    def calculate_nbv(self):\n        if self.net_book_value is None:\n            self.net_book_value = self.acquisition_cost\n        return self\n\n\nclass FixedAssetUpdate(BaseModel):\n    """Schema for updating fixed assets"""\n    name: Optional[str] = Field(None, min_length=1, max_length=200)\n    description: Optional[str] = Field(None, max_length=2000)\n    status: Optional[AssetStatus] = None\n    location_id: Optional[int] = None\n    custodian_id: Optional[int] = None\n    department_id: Optional[int] = None\n    cost_center_id: Optional[int] = None\n    serial_number: Optional[str] = Field(None, max_length=100)\n    model_number: Optional[str] = Field(None, max_length=100)\n    barcode: Optional[str] = Field(None, max_length=100)\n    rfid_tag: Optional[str] = Field(None, max_length=100)\n    warranty_expiry_date: Optional[date] = None\n    insurance_policy_id: Optional[int] = None\n    custom_fields: Optional[Dict[str, Any]] = None\n    tags: Optional[List[str]] = None\n    image_url: Optional[str] = Field(None, max_length=500)\n    notes: Optional[str] = Field(None, max_length=5000)\n\n\nclass FixedAssetResponse(FixedAssetBase, BaseResponseSchema, CompanyScopedMixin):\n    """Schema for fixed asset responses"""\n    asset_class_name: Optional[str] = None\n    asset_class_code: Optional[str] = None\n    location_name: Optional[str] = None\n    custodian_name: Optional[str] = None\n    department_name: Optional[str] = None\n    vendor_name: Optional[str] = None\n    \n    # Calculated fields\n    total_useful_life_months: int = Field(default=0, description="Total useful life in months")\n    age_in_months: int = Field(default=0, description="Asset age in months")\n    remaining_life_months: int = Field(default=0, description="Remaining useful life in months")\n    depreciation_percentage: Decimal = Field(default=Decimal(\'0\'), description="Depreciation percentage")\n    is_fully_depreciated: bool = Field(default=False, description="Whether fully depreciated")\n    impairment_status: ImpairmentStatus = Field(default=ImpairmentStatus.NOT_IMPAIRED)\n    \n    # Statistics\n    total_depreciation_expense: Decimal = Field(default=Decimal(\'0\'), description="Total depreciation expense")\n    total_revaluations: int = Field(default=0, description="Number of revaluations")\n    total_transfers: int = Field(default=0, description="Number of transfers")\n    \n    created_by_id: int\n    approved_by_id: Optional[int] = None\n    approved_at: Optional[datetime] = None\n\n    model_config = ConfigDict(from_attributes=True)\n\n\n# ==================== DEPRECIATION SCHEDULE ====================\n\nclass DepreciationScheduleLineBase(BaseModel):\n    """Base schema for depreciation schedule lines"""\n    fiscal_year: int = Field(..., ge=2000, le=2100, description="Fiscal year")\n    fiscal_period: int = Field(..., ge=1, le=12, description="Fiscal period (month)")\n    period_start_date: date = Field(..., description="Period start date")\n    period_end_date: date = Field(..., description="Period end date")\n    opening_net_book_value: Decimal = Field(..., description="Opening NBV")\n    depreciation_amount: Decimal = Field(..., ge=0, description="Depreciation amount for period")\n    closing_net_book_value: Decimal = Field(..., description="Closing NBV")\n    is_posted: bool = Field(default=False, description="Whether journal entry is posted")\n    journal_entry_id: Optional[int] = Field(None, description="Posted journal entry ID")\n    posted_date: Optional[datetime] = Field(None, description="Date posted")\n\n\nclass DepreciationScheduleLineResponse(DepreciationScheduleLineBase, BaseResponseSchema):\n    """Schema for depreciation schedule line responses"""\n    asset_id: int\n    model_config = ConfigDict(from_attributes=True)\n\n\nclass DepreciationScheduleBase(BaseModel):\n    """Base schema for depreciation schedules"""\n    asset_id: int = Field(..., description="Asset ID")\n    schedule_type: str = Field(default="standard", description="Schedule type: standard, accelerated, custom")\n    depreciation_method: DepreciationMethod = Field(..., description="Depreciation method")\n    total_periods: int = Field(..., ge=1, description="Total depreciation periods")\n    total_depreciation: Decimal = Field(..., description="Total depreciation amount")\n    remaining_depreciation: Decimal = Field(default=Decimal(\'0\'), description="Remaining depreciation")\n    is_active: bool = Field(default=True, description="Whether schedule is active")\n\n\nclass DepreciationScheduleResponse(DepreciationScheduleBase, BaseResponseSchema):\n    """Schema for depreciation schedule responses"""\n    lines: List[DepreciationScheduleLineResponse] = Field(default_factory=list)\n    asset_number: Optional[str] = None\n    asset_name: Optional[str] = None\n\n    model_config = ConfigDict(from_attributes=True)\n\n\n# ==================== DEPRECIATION RUN ====================\n\nclass DepreciationRunLineBase(BaseModel):\n    """Base schema for depreciation run lines"""\n    asset_id: int = Field(..., description="Asset ID")\n    asset_number: str = Field(..., description="Asset number")\n    asset_name: str = Field(..., description="Asset name")\n    opening_nbv: Decimal = Field(..., description="Opening net book value")\n    depreciation_amount: Decimal = Field(..., description="Depreciation amount")\n    closing_nbv: Decimal = Field(..., description="Closing net book value")\n    depreciation_account_id: int = Field(..., description="Depreciation expense account")\n    accumulated_account_id: int = Field(..., description="Accumulated depreciation account")\n    is_selected: bool = Field(default=True, description="Whether to include in posting")\n    journal_entry_line_id: Optional[int] = Field(None, description="Created journal entry line ID")\n\n\nclass DepreciationRunLineResponse(DepreciationRunLineBase, BaseResponseSchema):\n    """Schema for depreciation run line responses"""\n    run_id: int\n    model_config = ConfigDict(from_attributes=True)\n\n\nclass DepreciationRunBase(BaseModel):\n    """Base schema for depreciation runs"""\n    name: str = Field(..., min_length=1, max_length=200, description="Run name")\n    fiscal_year: int = Field(..., ge=2000, le=2100, description="Fiscal year")\n    fiscal_period: int = Field(..., ge=1, le=12, description="Fiscal period")\n    run_date: date = Field(..., description="Run date")\n    description: Optional[str] = Field(None, max_length=2000, description="Description")\n    status: str = Field(default="draft", description="Status: draft, posted, reversed")\n    total_assets: int = Field(default=0, description="Total assets processed")\n    total_depreciation: Decimal = Field(default=Decimal(\'0\'), description="Total depreciation amount")\n    journal_entry_id: Optional[int] = Field(None, description="Created journal entry ID")\n    posted_at: Optional[datetime] = Field(None, description="Posted timestamp")\n    posted_by_id: Optional[int] = Field(None, description="Posted by user ID")\n    reversed_at: Optional[datetime] = Field(None, description="Reversed timestamp")\n    reversed_by_id: Optional[int] = Field(None, description="Reversed by user ID")\n    reversal_entry_id: Optional[int] = Field(None, description="Reversal journal entry ID")\n\n\nclass DepreciationRunCreate(DepreciationRunBase):\n    """Schema for creating depreciation runs"""\n    asset_ids: Optional[List[int]] = Field(None, description="Specific assets to include")\n    asset_class_ids: Optional[List[int]] = Field(None, description="Asset classes to include")\n    auto_post: bool = Field(default=False, description="Automatically post journal entry")\n\n\nclass DepreciationRunUpdate(BaseModel):\n    """Schema for updating depreciation runs"""\n    name: Optional[str] = Field(None, min_length=1, max_length=200)\n    description: Optional[str] = Field(None, max_length=2000)\n\n\nclass DepreciationRunResponse(DepreciationRunBase, BaseResponseSchema, CompanyScopedMixin):\n    """Schema for depreciation run responses"""\n    lines: List[DepreciationRunLineResponse] = Field(default_factory=list)\n    created_by_id: int\n\n    model_config = ConfigDict(from_attributes=True)\n\n\n# ==================== ASSET TRANSFER ====================\n\nclass AssetTransferBase(BaseModel):\n    """Base schema for asset transfers"""\n    transfer_number: str = Field(..., min_length=1, max_length=50, description="Transfer number")\n    transfer_date: date = Field(..., description="Transfer date")\n    transfer_type: str = Field(default="location", description="Transfer type: location, department, custodian, company")\n    description: Optional[str] = Field(None, max_length=2000, description="Transfer description")\n    \n    # Source information\n    from_location_id: Optional[int] = Field(None, description="Source location ID")\n    from_department_id: Optional[int] = Field(None, description="Source department ID")\n    from_custodian_id: Optional[int] = Field(None, description="Source custodian ID")\n    from_company_id: Optional[int] = Field(None, description="Source company ID")\n    \n    # Destination information\n    to_location_id: Optional[int] = Field(None, description="Destination location ID")\n    to_department_id: Optional[int] = Field(None, description="Destination department ID")\n    to_custodian_id: Optional[int] = Field(None, description="Destination custodian ID")\n    to_company_id: Optional[int] = Field(None, description="Destination company ID")\n    \n    status: str = Field(default="pending", description="Status: pending, approved, completed, cancelled")\n    approval_required: bool = Field(default=True, description="Whether approval is required")\n    approved_by_id: Optional[int] = Field(None, description="Approved by user ID")\n    approved_at: Optional[datetime] = Field(None, description="Approval timestamp")\n    completed_at: Optional[datetime] = Field(None, description="Completion timestamp")\n    notes: Optional[str] = Field(None, max_length=2000, description="Additional notes")\n\n\nclass AssetTransferCreate(AssetTransferBase):\n    """Schema for creating asset transfers"""\n    asset_ids: List[int] = Field(..., min_length=1, description="Asset IDs to transfer")\n\n\nclass AssetTransferUpdate(BaseModel):\n    """Schema for updating asset transfers"""\n    description: Optional[str] = Field(None, max_length=2000)\n    notes: Optional[str] = Field(None, max_length=2000)\n\n\nclass AssetTransferResponse(AssetTransferBase, BaseResponseSchema, CompanyScopedMixin):\n    """Schema for asset transfer responses"""\n    assets: List[FixedAssetResponse] = Field(default_factory=list)\n    from_location_name: Optional[str] = None\n    to_location_name: Optional[str] = None\n    from_department_name: Optional[str] = None\n    to_department_name: Optional[str] = None\n    from_custodian_name: Optional[str] = None\n    to_custodian_name: Optional[str] = None\n    requested_by_id: int\n\n    model_config = ConfigDict(from_attributes=True)\n\n\n# ==================== ASSET DISPOSAL ====================\n\nclass AssetDisposalLineBase(BaseModel):\n    """Base schema for disposal lines"""\n    asset_id: int = Field(..., description="Asset ID")\n    asset_number: Optional[str] = None\n    asset_name: Optional[str] = None\n    original_cost: Decimal = Field(..., description="Original asset cost")\n    accumulated_depreciation: Decimal = Field(..., description="Accumulated depreciation at disposal")\n    net_book_value: Decimal = Field(..., description="Net book value at disposal")\n    disposal_value: Decimal = Field(default=Decimal(\'0\'), description="Proceeds from disposal")\n    disposal_costs: Decimal = Field(default=Decimal(\'0\'), description="Costs of disposal")\n    gain_loss: Decimal = Field(default=Decimal(\'0\'), description="Gain or loss on disposal")\n    gain_loss_account_id: Optional[int] = Field(None, description="Gain/loss account ID")\n\n\nclass AssetDisposalLineCreate(AssetDisposalLineBase):\n    """Schema for creating disposal lines"""\n    pass\n\n\nclass AssetDisposalLineResponse(AssetDisposalLineBase, BaseResponseSchema):\n    """Schema for disposal line responses"""\n    disposal_id: int\n    model_config = ConfigDict(from_attributes=True)\n\n\nclass AssetDisposalBase(BaseModel):\n    """Base schema for asset disposals"""\n    disposal_number: str = Field(..., min_length=1, max_length=50, description="Disposal number")\n    disposal_date: date = Field(..., description="Disposal date")\n    disposal_method: DisposalMethod = Field(..., description="Method of disposal")\n    description: Optional[str] = Field(None, max_length=2000, description="Disposal description")\n    \n    # Buyer information (for sales)\n    buyer_id: Optional[int] = Field(None, description="Buyer contact ID")\n    buyer_name: Optional[str] = Field(None, max_length=200, description="Buyer name")\n    buyer_address: Optional[str] = Field(None, max_length=500, description="Buyer address")\n    \n    # Financial details\n    total_proceeds: Decimal = Field(default=Decimal(\'0\'), description="Total proceeds from disposal")\n    total_disposal_costs: Decimal = Field(default=Decimal(\'0\'), description="Total disposal costs")\n    total_gain_loss: Decimal = Field(default=Decimal(\'0\'), description="Total gain or loss")\n    \n    # Status and approval\n    status: str = Field(default="pending", description="Status: pending, approved, completed, cancelled")\n    approval_required: bool = Field(default=True, description="Whether approval is required")\n    approved_by_id: Optional[int] = Field(None, description="Approved by user ID")\n    approved_at: Optional[datetime] = Field(None, description="Approval timestamp")\n    completed_at: Optional[datetime] = Field(None, description="Completion timestamp")\n    \n    # GL Integration\n    journal_entry_id: Optional[int] = Field(None, description="Created journal entry ID")\n    \n    # Additional information\n    reference: Optional[str] = Field(None, max_length=100, description="Reference number")\n    notes: Optional[str] = Field(None, max_length=2000, description="Additional notes")\n\n\nclass AssetDisposalCreate(AssetDisposalBase):\n    """Schema for creating asset disposals"""\n    lines: List[AssetDisposalLineCreate] = Field(..., min_length=1, description="Disposal lines")\n\n\nclass AssetDisposalUpdate(BaseModel):\n    """Schema for updating asset disposals"""\n    description: Optional[str] = Field(None, max_length=2000)\n    buyer_id: Optional[int] = None\n    buyer_name: Optional[str] = Field(None, max_length=200)\n    buyer_address: Optional[str] = Field(None, max_length=500)\n    reference: Optional[str] = Field(None, max_length=100)\n    notes: Optional[str] = Field(None, max_length=2000)\n\n\nclass AssetDisposalResponse(AssetDisposalBase, BaseResponseSchema, CompanyScopedMixin):\n    """Schema for asset disposal responses"""\n    lines: List[AssetDisposalLineResponse] = Field(default_factory=list)\n    total_original_cost: Decimal = Field(default=Decimal(\'0\'), description="Total original cost")\n    total_accumulated_depreciation: Decimal = Field(default=Decimal(\'0\'), description="Total accumulated depreciation")\n    total_net_book_value: Decimal = Field(default=Decimal(\'0\'), description="Total net book value")\n    requested_by_id: int\n\n    model_config = ConfigDict(from_attributes=True)\n\n\n# ==================== ASSET REVALUATION ====================\n\nclass AssetRevaluationBase(BaseModel):\n    """Base schema for asset revaluations"""\n    revaluation_number: str = Field(..., min_length=1, max_length=50, description="Revaluation number")\n    revaluation_date: date = Field(..., description="Revaluation date")\n    description: Optional[str] = Field(None, max_length=2000, description="Description")\n    revaluation_type: str = Field(default="upward", description="Revaluation type: upward, downward")\n    \n    # Values\n    previous_cost: Decimal = Field(..., description="Previous asset cost")\n    new_cost: Decimal = Field(..., description="New asset cost")\n    cost_adjustment: Decimal = Field(..., description="Cost adjustment amount")\n    previous_accumulated_depreciation: Decimal = Field(..., description="Previous accumulated depreciation")\n    new_accumulated_depreciation: Decimal = Field(..., description="New accumulated depreciation")\n    depreciation_adjustment: Decimal = Field(..., description="Depreciation adjustment")\n    previous_net_book_value: Decimal = Field(..., description="Previous NBV")\n    new_net_book_value: Decimal = Field(..., description="New NBV")\n    revaluation_reserve: Decimal = Field(..., description="Revaluation reserve amount")\n    \n    # Independent valuation\n    valuer_name: Optional[str] = Field(None, max_length=200, description="Independent valuer name")\n    valuation_report_date: Optional[date] = Field(None, description="Valuation report date")\n    valuation_report_ref: Optional[str] = Field(None, max_length=100, description="Valuation report reference")\n    \n    # Status\n    status: str = Field(default="pending", description="Status: pending, approved, completed, cancelled")\n    approved_by_id: Optional[int] = Field(None, description="Approved by user ID")\n    approved_at: Optional[datetime] = Field(None, description="Approval timestamp")\n    \n    # GL Integration\n    journal_entry_id: Optional[int] = Field(None, description="Created journal entry ID")\n    \n    notes: Optional[str] = Field(None, max_length=2000, description="Additional notes")\n\n\nclass AssetRevaluationCreate(AssetRevaluationBase):\n    """Schema for creating asset revaluations"""\n    asset_id: int = Field(..., description="Asset ID")\n    new_useful_life_years: Optional[int] = Field(None, ge=0, le=100, description="Revised useful life years")\n    new_useful_life_months: Optional[int] = Field(None, ge=0, le=1199, description="Revised useful life months")\n\n\nclass AssetRevaluationUpdate(BaseModel):\n    """Schema for updating asset revaluations"""\n    description: Optional[str] = Field(None, max_length=2000)\n    valuer_name: Optional[str] = Field(None, max_length=200)\n    valuation_report_date: Optional[date] = None\n    valuation_report_ref: Optional[str] = Field(None, max_length=100)\n    notes: Optional[str] = Field(None, max_length=2000)\n\n\nclass AssetRevaluationResponse(AssetRevaluationBase, BaseResponseSchema, CompanyScopedMixin):\n    """Schema for asset revaluation responses"""\n    asset_id: int\n    asset_number: Optional[str] = None\n    asset_name: Optional[str] = None\n    requested_by_id: int\n\n    model_config = ConfigDict(from_attributes=True)\n\n\n# ==================== ASSET IMPAIRMENT ====================\n\nclass AssetImpairmentBase(BaseModel):\n    """Base schema for asset impairments"""\n    impairment_number: str = Field(..., min_length=1, max_length=50, description="Impairment number")\n    impairment_date: date = Field(..., description="Impairment date")\n    description: Optional[str] = Field(None, max_length=2000, description="Description")\n    impairment_type: str = Field(default="recognition", description="Type: recognition, reversal")\n    \n    # Values\n    carrying_amount: Decimal = Field(..., description="Carrying amount before impairment")\n    recoverable_amount: Decimal = Field(..., description="Recoverable amount (fair value less costs or value in use)")\n    impairment_loss: Decimal = Field(..., ge=0, description="Impairment loss amount")\n    new_carrying_amount: Decimal = Field(..., description="New carrying amount after impairment")\n    \n    # Impairment indicators\n    impairment_indicators: Optional[List[str]] = Field(None, description="Indicators of impairment")\n    \n    # Status\n    status: str = Field(default="pending", description="Status: pending, approved, completed, cancelled")\n    approved_by_id: Optional[int] = Field(None, description="Approved by user ID")\n    approved_at: Optional[datetime] = Field(None, description="Approval timestamp")\n    \n    # GL Integration\n    journal_entry_id: Optional[int] = Field(None, description="Created journal entry ID")\n    impairment_account_id: int = Field(..., description="Impairment loss account ID")\n    \n    notes: Optional[str] = Field(None, max_length=2000, description="Additional notes")\n\n\nclass AssetImpairmentCreate(AssetImpairmentBase):\n    """Schema for creating asset impairments"""\n    asset_id: int = Field(..., description="Asset ID")\n\n\nclass AssetImpairmentUpdate(BaseModel):\n    """Schema for updating asset impairments"""\n    description: Optional[str] = Field(None, max_length=2000)\n    impairment_indicators: Optional[List[str]] = None\n    notes: Optional[str] = Field(None, max_length=2000)\n\n\nclass AssetImpairmentResponse(AssetImpairmentBase, BaseResponseSchema, CompanyScopedMixin):\n    """Schema for asset impairment responses"""\n    asset_id: int\n    asset_number: Optional[str] = None\n    asset_name: Optional[str] = None\n    requested_by_id: int\n\n    model_config = ConfigDict(from_attributes=True)\n\n\n# ==================== MAINTENANCE RECORD ====================\n\nclass AssetMaintenanceBase(BaseModel):\n    """Base schema for asset maintenance records"""\n    maintenance_number: str = Field(..., min_length=1, max_length=50, description="Maintenance number")\n    maintenance_type: MaintenanceType = Field(..., description="Type of maintenance")\n    maintenance_date: date = Field(..., description="Maintenance date")\n    description: str = Field(..., min_length=1, max_length=2000, description="Maintenance description")\n    status: MaintenanceStatus = Field(default=MaintenanceStatus.SCHEDULED, description="Maintenance status")\n    \n    # Scheduling\n    scheduled_date: Optional[date] = Field(None, description="Scheduled date")\n    completed_date: Optional[date] = Field(None, description="Completion date")\n    \n    # Cost\n    labor_cost: Decimal = Field(default=Decimal(\'0\'), ge=0, description="Labor cost")\n    parts_cost: Decimal = Field(default=Decimal(\'0\'), ge=0, description="Parts/materials cost")\n    other_cost: Decimal = Field(default=Decimal(\'0\'), ge=0, description="Other costs")\n    total_cost: Decimal = Field(default=Decimal(\'0\'), ge=0, description="Total maintenance cost")\n    \n    # Vendor/Technician\n    vendor_id: Optional[int] = Field(None, description="Maintenance vendor ID")\n    technician_name: Optional[str] = Field(None, max_length=200, description="Technician name")\n    \n    # Additional information\n    work_performed: Optional[str] = Field(None, max_length=5000, description="Work performed details")\n    parts_replaced: Optional[List[str]] = Field(None, description="Parts replaced")\n    next_maintenance_date: Optional[date] = Field(None, description="Next scheduled maintenance")\n    meter_reading: Optional[Decimal] = Field(None, description="Meter reading at maintenance")\n    \n    # Capitalization\n    capitalize_cost: bool = Field(default=False, description="Capitalize maintenance cost")\n    capitalization_amount: Optional[Decimal] = Field(None, description="Amount to capitalize")\n    \n    notes: Optional[str] = Field(None, max_length=2000, description="Additional notes")\n\n\nclass AssetMaintenanceCreate(AssetMaintenanceBase):\n    """Schema for creating maintenance records"""\n    asset_id: int = Field(..., description="Asset ID")\n\n\nclass AssetMaintenanceUpdate(BaseModel):\n    """Schema for updating maintenance records"""\n    maintenance_type: Optional[MaintenanceType] = None\n    maintenance_date: Optional[date] = None\n    description: Optional[str] = Field(None, min_length=1, max_length=2000)\n    status: Optional[MaintenanceStatus] = None\n    scheduled_date: Optional[date] = None\n    completed_date: Optional[date] = None\n    labor_cost: Optional[Decimal] = Field(None, ge=0)\n    parts_cost: Optional[Decimal] = Field(None, ge=0)\n    other_cost: Optional[Decimal] = Field(None, ge=0)\n    vendor_id: Optional[int] = None\n    technician_name: Optional[str] = Field(None, max_length=200)\n    work_performed: Optional[str] = Field(None, max_length=5000)\n    parts_replaced: Optional[List[str]] = None\n    next_maintenance_date: Optional[date] = None\n    meter_reading: Optional[Decimal] = None\n    capitalize_cost: Optional[bool] = None\n    capitalization_amount: Optional[Decimal] = None\n    notes: Optional[str] = Field(None, max_length=2000)\n\n\nclass AssetMaintenanceResponse(AssetMaintenanceBase, BaseResponseSchema, CompanyScopedMixin):\n    """Schema for maintenance record responses"""\n    asset_id: int\n    asset_number: Optional[str] = None\n    asset_name: Optional[str] = None\n    vendor_name: Optional[str] = None\n\n    model_config = ConfigDict(from_attributes=True)\n\n\n# ==================== INSURANCE ====================\n\nclass AssetInsuranceBase(BaseModel):\n    """Base schema for asset insurance policies"""\n    policy_number: str = Field(..., min_length=1, max_length=50, description="Policy number")\n    policy_name: str = Field(..., min_length=1, max_length=200, description="Policy name")\n    insurance_company: str = Field(..., min_length=1, max_length=200, description="Insurance company")\n    \n    # Coverage period\n    start_date: date = Field(..., description="Coverage start date")\n    end_date: date = Field(..., description="Coverage end date")\n    status: InsuranceStatus = Field(default=InsuranceStatus.ACTIVE, description="Policy status")\n    \n    # Coverage details\n    coverage_type: str = Field(default="all_risk", description="Coverage type: all_risk, named_perils, fire_only, etc.")\n    insured_value: Decimal = Field(..., ge=0, description="Insured value")\n    deductible: Decimal = Field(default=Decimal(\'0\'), ge=0, description="Deductible amount")\n    \n    # Premium\n    premium_amount: Decimal = Field(..., ge=0, description="Premium amount")\n    premium_frequency: str = Field(default="annual", description="Premium frequency: annual, semi_annual, quarterly, monthly")\n    next_premium_date: Optional[date] = Field(None, description="Next premium due date")\n    \n    # Beneficiary\n    beneficiary: Optional[str] = Field(None, max_length=200, description="Beneficiary")\n    \n    # Agent/Broker\n    agent_name: Optional[str] = Field(None, max_length=200, description="Agent/Broker name")\n    agent_contact: Optional[str] = Field(None, max_length=200, description="Agent contact info")\n    \n    notes: Optional[str] = Field(None, max_length=2000, description="Additional notes")\n\n\nclass AssetInsuranceCreate(AssetInsuranceBase):\n    """Schema for creating insurance policies"""\n    asset_ids: Optional[List[int]] = Field(None, description="Covered asset IDs")\n\n\nclass AssetInsuranceUpdate(BaseModel):\n    """Schema for updating insurance policies"""\n    policy_name: Optional[str] = Field(None, min_length=1, max_length=200)\n    insurance_company: Optional[str] = Field(None, min_length=1, max_length=200)\n    start_date: Optional[date] = None\n    end_date: Optional[date] = None\n    status: Optional[InsuranceStatus] = None\n    coverage_type: Optional[str] = None\n    insured_value: Optional[Decimal] = Field(None, ge=0)\n    deductible: Optional[Decimal] = Field(None, ge=0)\n    premium_amount: Optional[Decimal] = Field(None, ge=0)\n    premium_frequency: Optional[str] = None\n    next_premium_date: Optional[date] = None\n    beneficiary: Optional[str] = Field(None, max_length=200)\n    agent_name: Optional[str] = Field(None, max_length=200)\n    agent_contact: Optional[str] = Field(None, max_length=200)\n    notes: Optional[str] = Field(None, max_length=2000)\n\n\nclass AssetInsuranceResponse(AssetInsuranceBase, BaseResponseSchema, CompanyScopedMixin):\n    """Schema for insurance policy responses"""\n    covered_assets: List[FixedAssetResponse] = Field(default_factory=list)\n    total_insured_value: Decimal = Field(default=Decimal(\'0\'), description="Total insured value of assets")\n    days_to_expiry: int = Field(default=0, description="Days until policy expires")\n\n    model_config = ConfigDict(from_attributes=True)\n\n\n# ==================== FILTER PARAMETERS ====================\n\nclass AssetClassFilterParams(PaginationParams):\n    """Filter parameters for asset class queries"""\n    category: Optional[AssetCategory] = None\n    is_active: Optional[bool] = None\n    parent_class_id: Optional[int] = None\n\n\nclass AssetLocationFilterParams(PaginationParams):\n    """Filter parameters for asset location queries"""\n    location_type: Optional[str] = None\n    is_active: Optional[bool] = None\n    parent_location_id: Optional[int] = None\n\n\nclass FixedAssetFilterParams(PaginationParams):\n    """Filter parameters for fixed asset queries"""\n    asset_class_id: Optional[int] = None\n    category: Optional[AssetCategory] = None\n    status: Optional[AssetStatus] = None\n    location_id: Optional[int] = None\n    department_id: Optional[int] = None\n    custodian_id: Optional[int] = None\n    vendor_id: Optional[int] = None\n    acquisition_date_from: Optional[date] = None\n    acquisition_date_to: Optional[date] = None\n    cost_from: Optional[Decimal] = None\n    cost_to: Optional[Decimal] = None\n    search: Optional[str] = None\n    is_fully_depreciated: Optional[bool] = None\n\n\nclass DepreciationRunFilterParams(PaginationParams):\n    """Filter parameters for depreciation run queries"""\n    fiscal_year: Optional[int] = None\n    fiscal_period: Optional[int] = None\n    status: Optional[str] = None\n\n\nclass AssetTransferFilterParams(PaginationParams):\n    """Filter parameters for asset transfer queries"""\n    transfer_type: Optional[str] = None\n    status: Optional[str] = None\n    transfer_date_from: Optional[date] = None\n    transfer_date_to: Optional[date] = None\n\n\nclass AssetDisposalFilterParams(PaginationParams):\n    """Filter parameters for asset disposal queries"""\n    disposal_method: Optional[DisposalMethod] = None\n    status: Optional[str] = None\n    disposal_date_from: Optional[date] = None\n    disposal_date_to: Optional[date] = None\n\n\nclass AssetMaintenanceFilterParams(PaginationParams):\n    """Filter parameters for maintenance queries"""\n    maintenance_type: Optional[MaintenanceType] = None\n    status: Optional[MaintenanceStatus] = None\n    maintenance_date_from: Optional[date] = None\n    maintenance_date_to: Optional[date] = None\n\n\nclass AssetInsuranceFilterParams(PaginationParams):\n    """Filter parameters for insurance queries"""\n    status: Optional[InsuranceStatus] = None\n    insurance_company: Optional[str] = None\n    expiring_within_days: Optional[int] = None\n\n\n# ==================== LIST RESPONSES ====================\n\nclass AssetClassListResponse(ListResponseBase):\n    """List response for asset classes"""\n    items: List[AssetClassResponse]\n\n\nclass AssetLocationListResponse(ListResponseBase):\n    """List response for asset locations"""\n    items: List[AssetLocationResponse]\n\n\nclass FixedAssetListResponse(ListResponseBase):\n    """List response for fixed assets"""\n    items: List[FixedAssetResponse]\n\n\nclass DepreciationScheduleListResponse(ListResponseBase):\n    """List response for depreciation schedules"""\n    items: List[DepreciationScheduleResponse]\n\n\nclass DepreciationRunListResponse(ListResponseBase):\n    """List response for depreciation runs"""\n    items: List[DepreciationRunResponse]\n\n\nclass AssetTransferListResponse(ListResponseBase):\n    """List response for asset transfers"""\n    items: List[AssetTransferResponse]\n\n\nclass AssetDisposalListResponse(ListResponseBase):\n    """List response for asset disposals"""\n    items: List[AssetDisposalResponse]\n\n\nclass AssetRevaluationListResponse(ListResponseBase):\n    """List response for asset revaluations"""\n    items: List[AssetRevaluationResponse]\n\n\nclass AssetImpairmentListResponse(ListResponseBase):\n    """List response for asset impairments"""\n    items: List[AssetImpairmentResponse]\n\n\nclass AssetMaintenanceListResponse(ListResponseBase):\n    """List response for maintenance records"""\n    items: List[AssetMaintenanceResponse]\n\n\nclass AssetInsuranceListResponse(ListResponseBase):\n    """List response for insurance policies"""\n    items: List[AssetInsuranceResponse]\n\n\n# ==================== ANALYTICS RESPONSES ====================\n\nclass AssetStatisticsResponse(BaseModel):\n    """Asset module statistics"""\n    total_assets: int = 0\n    active_assets: int = 0\n    total_original_cost: Decimal = Decimal(\'0\')\n    total_accumulated_depreciation: Decimal = Decimal(\'0\')\n    total_net_book_value: Decimal = Decimal(\'0\')\n    fully_depreciated_assets: int = 0\n    impaired_assets: int = 0\n    assets_under_construction: int = 0\n    held_for_sale_assets: int = 0\n    \n    # By category\n    assets_by_category: Dict[str, int] = Field(default_factory=dict)\n    value_by_category: Dict[str, Decimal] = Field(default_factory=dict)\n    \n    # By status\n    assets_by_status: Dict[str, int] = Field(default_factory=dict)\n    \n    # By location\n    top_locations_by_value: List[Dict[str, Any]] = Field(default_factory=list)\n    \n    # Depreciation\n    depreciation_this_period: Decimal = Decimal(\'0\')\n    depreciation_ytd: Decimal = Decimal(\'0\')\n    \n    # Recent activity\n    acquisitions_this_month: int = 0\n    disposals_this_month: int = 0\n    transfers_this_month: int = 0\n    \n    # Insurance\n    total_insured_value: Decimal = Decimal(\'0\')\n    expiring_insurance_policies: int = 0\n    \n    # Maintenance\n    pending_maintenance: int = 0\n    overdue_maintenance: int = 0\n    maintenance_cost_ytd: Decimal = Decimal(\'0\')\n\n\nclass DepreciationForecastResponse(BaseModel):\n    """Depreciation forecast for planning"""\n    periods: List[Dict[str, Any]] = Field(default_factory=list)\n    total_forecast_depreciation: Decimal = Decimal(\'0\')\n    assets_included: int = 0\n    forecast_start_date: date\n    forecast_end_date: date\n\n\nclass AssetRollforwardResponse(BaseModel):\n    """Asset rollforward report data"""\n    period_start: date\n    period_end: date\n    category: Optional[str] = None\n    \n    beginning_balance: Decimal = Decimal(\'0\')\n    additions: Decimal = Decimal(\'0\')\n    disposals: Decimal = Decimal(\'0\')\n    transfers_in: Decimal = Decimal(\'0\')\n    transfers_out: Decimal = Decimal(\'0\')\n    revaluations: Decimal = Decimal(\'0\')\n    impairments: Decimal = Decimal(\'0\')\n    depreciation: Decimal = Decimal(\'0\')\n    ending_balance: Decimal = Decimal(\'0\')\n    \n    details: List[Dict[str, Any]] = Field(default_factory=list)\n</create-file>\n</function_calls>'}
{'role': 'user', 'content': '<tool_result> <create-file> ToolResult(success=True, output="File \'backend/app/schemas/asset.py\' created successfully.") </create-file> </tool_result>'}
{'role': 'user', 'content': '/chat Please continue where you left off.'}
{'role': 'assistant', 'content': "I don't have any previous conversation history with you, so I'm not sure what topic you'd like me to continue discussing. This appears to be the start of our conversation.\n\nCould you please:\n1. Remind me what we were discussing, or\n2. Share the text you'd like me to continue from, or\n3. Let me know what topic you'd like help with?\n\nI'm happy to help once I have that context!"}
{'role': 'user', 'content': "🏛️ SAMMS ENTERPRISE SOVEREIGN OPERATING SYSTEM (SESOS v6 OMEGA)\n\nI'll build this complete enterprise system systematically. Let me start by creating the todo.md to track all modules and then begin generating the full codebase.\n\nNow let me create the complete folder structure and begin building the system. I'll start with the backend core infrastructure.\n\nExcellent! Now let me begin building the complete backend system. Starting with the core configuration and models.\n\nLet me continue building the backend system with schemas and services.\n\nI'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\nGood, 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\nNow let me create the Company schemas:\n\nNow let me create the User schemas:\n\nNow let me create the Accounting schemas for the double-entry bookkeeping system:\n\nNow let me create the Treasury schemas for banking and cash management:\n\nLet me continue creating the remaining schemas. Now I'll create the Invoice schemas for the Revenue & Billing module:\n\nLet me continue creating the remaining schemas. Now I'll create the HR schemas:\n\nLet me continue creating the remaining schemas. Now I'll create the Tax schemas for the Tax Engine:\n\nLet me continue creating the remaining schemas. Now I'll create the Workflow schemas for the automation engine:\n\nLet me continue with the remaining schemas. I'll create the Legal schemas for contract lifecycle management:\n\nI'll continue building the SESOS system from where we left off. Let me first read the current todo.md and the transcript to understand the exact state, then continue creating the remaining schema files.\n\nI see the todo.md needs to be updated to reflect the actual progress. According to the summary, I've already created schemas for company, user, accounting, treasury, invoice, hr, tax, workflow, and legal. Let me verify and then continue with the remaining schemas.\n\nI can see the existing schemas. The summary mentioned that I still need to create: reports.py, consolidation.py, asset.py, and ai.py. Let me update the todo.md to reflect actual progress and then continue creating the remaining schemas.\n\nNow let me continue creating the remaining schema files. I'll start with the Reports schemas.\n\nNow let me create the Consolidation schemas for multi-company financial consolidation.\n\nNow let me create the Asset schemas for the Fixed Asset Registry with depreciation tracking."}
{'role': 'assistant', 'content': 'I\'ll continue building the SAMMS ENTERPRISE SOVEREIGN OPERATING SYSTEM. Based on the context, I\'ve created the Reports, Consolidation, and Asset schemas. Now I need to create the AI schemas and then the schemas `__init__.py` file. Let me first update the todo.md and then continue.\n\n<function_calls>\n<full-file-rewrite file_path="todo.md">\n# SAMMS ENTERPRISE SOVEREIGN OPERATING SYSTEM - BUILD TRACKER\n\n## Phase 1: Project Setup & Infrastructure\n- [x] Create folder structure\n- [x] Backend core setup (FastAPI)\n- [ ] Frontend core setup (Next.js)\n- [x] Database configuration\n- [ ] Docker & Kubernetes configs\n\n## Phase 1.5: Backend Schemas (Pydantic)\n- [x] Base schemas\n- [x] Company schemas\n- [x] User schemas\n- [x] Accounting schemas\n- [x] Treasury schemas\n- [x] Invoice schemas\n- [x] HR schemas\n- [x] Tax schemas\n- [x] Workflow schemas\n- [x] Legal schemas\n- [x] Reports schemas\n- [x] Consolidation schemas\n- [x] Asset schemas\n- [ ] AI schemas\n- [ ] Schemas __init__.py\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</full-file-rewrite>\n</function_calls>'}
{'role': 'user', 'content': '<tool_result> <full-file-rewrite> ToolResult(success=True, output="File \'todo.md\' completely rewritten successfully.") </full-file-rewrite> </tool_result>'}
{'role': 'assistant', 'content': 'Now let me create the AI schemas for the Analytics & AI Engine:\n\n<function_calls>\n<create-file file_path="backend/app/schemas/ai.py">\n"""\nSAMMS Enterprise - AI & Analytics Engine Schemas\nAI-powered analytics, forecasting, anomaly detection, and decision support\n"""\n\nfrom datetime import datetime, date\nfrom typing import Optional, List, Dict, Any, Union, Literal\nfrom decimal import Decimal\nfrom enum import Enum\nfrom pydantic import BaseModel, Field, ConfigDict, field_validator, model_validator, computed_field\nfrom .base import (\n    BaseResponseSchema,\n    TimestampMixin,\n    PaginationParams,\n    ListResponseBase,\n    AuditMixin,\n    CompanyScopedMixin\n)\n\n\n# ==================== ENUMS ====================\n\nclass AIModelType(str, Enum):\n    """Types of AI/ML models"""\n    FORECASTING = "forecasting"\n    CLASSIFICATION = "classification"\n    REGRESSION = "regression"\n    CLUSTERING = "clustering"\n    ANOMALY_DETECTION = "anomaly_detection"\n    NLP = "nlp"\n    RECOMMENDATION = "recommendation"\n    OPTIMIZATION = "optimization"\n    TIME_SERIES = "time_series"\n    SENTIMENT_ANALYSIS = "sentiment_analysis"\n    ENTITY_EXTRACTION = "entity_extraction"\n    DOCUMENT_ANALYSIS = "document_analysis"\n\n\nclass ModelStatus(str, Enum):\n    """AI model lifecycle status"""\n    DRAFT = "draft"\n    TRAINING = "training"\n    VALIDATING = "validating"\n    ACTIVE = "active"\n    DEPRECATED = "deprecated"\n    ARCHIVED = "archived"\n    FAILED = "failed"\n\n\nclass AnomalyType(str, Enum):\n    """Types of anomalies detected"""\n    OUTLIER = "outlier"\n    TREND_CHANGE = "trend_change"\n    THRESHOLD_BREACH = "threshold_breach"\n    PATTERN_DEVIATION = "pattern_deviation"\n    SEASONAL_ANOMALY = "seasonal_anomaly"\n    TRANSACTION_ANOMALY = "transaction_anomaly"\n    BEHAVIORAL_ANOMALY = "behavioral_anomaly"\n    COMPLIANCE_ANOMALY = "compliance_anomaly"\n\n\nclass AnomalySeverity(str, Enum):\n    """Severity levels for anomalies"""\n    LOW = "low"\n    MEDIUM = "medium"\n    HIGH = "high"\n    CRITICAL = "critical"\n\n\nclass ForecastType(str, Enum):\n    """Types of forecasts"""\n    CASH_FLOW = "cash_flow"\n    REVENUE = "revenue"\n    EXPENSE = "expense"\n    DEMAND = "demand"\n    HEADCOUNT = "headcount"\n    INVENTORY = "inventory"\n    SALES = "sales"\n    PROFIT = "profit"\n    BUDGET = "budget"\n    CUSTOM = "custom"\n\n\nclass ForecastHorizon(str, Enum):\n    """Forecast time horizons"""\n    DAILY = "daily"\n    WEEKLY = "weekly"\n    MONTHLY = "monthly"\n    QUARTERLY = "quarterly"\n    YEARLY = "yearly"\n\n\nclass AlertType(str, Enum):\n    """Types of AI-generated alerts"""\n    THRESHOLD = "threshold"\n    ANOMALY = "anomaly"\n    FORECAST_DEVIATION = "forecast_deviation"\n    TREND = "trend"\n    COMPLIANCE = "compliance"\n    RISK = "risk"\n    OPPORTUNITY = "opportunity"\n    RECOMMENDATION = "recommendation"\n\n\nclass AlertSeverity(str, Enum):\n    """Alert severity levels"""\n    INFO = "info"\n    WARNING = "warning"\n    ERROR = "error"\n    CRITICAL = "critical"\n\n\nclass InsightType(str, Enum):\n    """Types of AI insights"""\n    TREND = "trend"\n    PATTERN = "pattern"\n    CORRELATION = "correlation"\n    OUTLIER = "outlier"\n    SEGMENT = "segment"\n    PREDICTION = "prediction"\n    RECOMMENDATION = "recommendation"\n    EXPLANATION = "explanation"\n    SUMMARY = "summary"\n    COMPARISON = "comparison"\n\n\nclass RecommendationType(str, Enum):\n    """Types of recommendations"""\n    COST_SAVING = "cost_saving"\n    REVENUE_OPTIMIZATION = "revenue_optimization"\n    RISK_MITIGATION = "risk_mitigation"\n    EFFICIENCY_IMPROVEMENT = "efficiency_improvement"\n    COMPLIANCE_ACTION = "compliance_action"\n    INVESTMENT = "investment"\n    RESOURCE_ALLOCATION = "resource_allocation"\n    PROCESS_IMPROVEMENT = "process_improvement"\n    CASH_MANAGEMENT = "cash_management"\n    VENDOR_OPTIMIZATION = "vendor_optimization"\n\n\nclass RecommendationPriority(str, Enum):\n    """Recommendation priority levels"""\n    LOW = "low"\n    MEDIUM = "medium"\n    HIGH = "high"\n    URGENT = "urgent"\n\n\nclass AnalysisType(str, Enum):\n    """Types of document/contract analysis"""\n    CONTRACT_REVIEW = "contract_review"\n    RISK_ASSESSMENT = "risk_assessment"\n    COMPLIANCE_CHECK = "compliance_check"\n    TERM_EXTRACTION = "term_extraction"\n    SENTIMENT_ANALYSIS = "sentiment_analysis"\n    SIMILARITY_CHECK = "similarity_check"\n    KEY_CLAUSE_EXTRACTION = "key_clause_extraction"\n    OBLIGATION_EXTRACTION = "obligation_extraction"\n\n\nclass DataSource(str, Enum):\n    """Data sources for AI models"""\n    GL_TRANSACTIONS = "gl_transactions"\n    JOURNAL_ENTRIES = "journal_entries"\n    INVOICES = "invoices"\n    PAYMENTS = "payments"\n    TREASURY = "treasury"\n    PAYROLL = "payroll"\n    BUDGETS = "budgets"\n    CONTRACTS = "contracts"\n    DOCUMENTS = "documents"\n    TIME_SERIES = "time_series"\n    EXTERNAL = "external"\n\n\n# ==================== AI MODEL ====================\n\nclass AIModelConfigBase(BaseModel):\n    """Base schema for AI model configuration"""\n    model_name: str = Field(..., min_length=1, max_length=200, description="Model name")\n    model_version: str = Field(default="1.0.0", description="Model version")\n    model_type: AIModelType = Field(..., description="Type of AI model")\n    algorithm: str = Field(..., min_length=1, max_length=100, description="Algorithm used")\n    framework: str = Field(default="sklearn", description="ML framework: sklearn, tensorflow, pytorch, etc.")\n    \n    # Training configuration\n    features: List[str] = Field(..., min_length=1, description="Feature columns used")\n    target_variable: Optional[str] = Field(None, description="Target variable for supervised learning")\n    hyperparameters: Optional[Dict[str, Any]] = Field(None, description="Model hyperparameters")\n    preprocessing_config: Optional[Dict[str, Any]] = Field(None, description="Data preprocessing configuration")\n    \n    # Training data\n    training_data_source: DataSource = Field(..., description="Training data source")\n    training_data_query: Optional[str] = Field(None, description="SQL query or data filter")\n    training_date_range: Optional[Dict[str, date]] = Field(None, description="Training data date range")\n    validation_split: Decimal = Field(default=Decimal(\'0.2\'), ge=0, le=0.5, description="Validation split ratio")\n    test_split: Decimal = Field(default=Decimal(\'0.1\'), ge=0, le=0.3, description="Test split ratio")\n    \n    # Training execution\n    auto_retrain: bool = Field(default=False, description="Enable automatic retraining")\n    retrain_frequency: Optional[str] = Field(None, description="Retraining frequency")\n    min_samples_retrain: Optional[int] = Field(None, ge=100, description="Minimum new samples for retrain")\n    last_trained_at: Optional[datetime] = Field(None, description="Last training timestamp")\n    training_duration_seconds: Optional[int] = Field(None, description="Training duration")\n    \n    # Performance thresholds\n    min_accuracy: Optional[Decimal] = Field(None, ge=0, le=1, description="Minimum accuracy threshold")\n    min_precision: Optional[Decimal] = Field(None, ge=0, le=1, description="Minimum precision threshold")\n    min_recall: Optional[Decimal] = Field(None, ge=0, le=1, description="Minimum recall threshold")\n    \n    # Deployment\n    is_active: bool = Field(default=False, description="Whether model is active")\n    deployment_endpoint: Optional[str] = Field(None, max_length=500, description="Model API endpoint")\n    batch_size: Optional[int] = Field(None, ge=1, description="Batch size for predictions")\n\n\nclass AIModelConfigCreate(AIModelConfigBase):\n    """Schema for creating AI model configurations"""\n    pass\n\n\nclass AIModelConfigUpdate(BaseModel):\n    """Schema for updating AI model configurations"""\n    model_name: Optional[str] = Field(None, min_length=1, max_length=200)\n    hyperparameters: Optional[Dict[str, Any]] = None\n    auto_retrain: Optional[bool] = None\n    retrain_frequency: Optional[str] = None\n    min_accuracy: Optional[Decimal] = Field(None, ge=0, le=1)\n    min_precision: Optional[Decimal] = Field(None, ge=0, le=1)\n    min_recall: Optional[Decimal] = Field(None, ge=0, le=1)\n    is_active: Optional[bool] = None\n    deployment_endpoint: Optional[str] = Field(None, max_length=500)\n\n\nclass ModelMetrics(BaseModel):\n    """Model performance metrics"""\n    accuracy: Optional[Decimal] = Field(None, description="Overall accuracy")\n    precision: Optional[Decimal] = Field(None, description="Precision score")\n    recall: Optional[Decimal] = Field(None, description="Recall score")\n    f1_score: Optional[Decimal] = Field(None, description="F1 score")\n    auc_roc: Optional[Decimal] = Field(None, description="AUC-ROC score")\n    mae: Optional[Decimal] = Field(None, description="Mean Absolute Error")\n    mse: Optional[Decimal] = Field(None, description="Mean Squared Error")\n    rmse: Optional[Decimal] = Field(None, description="Root Mean Squared Error")\n    mape: Optional[Decimal] = Field(None, description="Mean Absolute Percentage Error")\n    r_squared: Optional[Decimal] = Field(None, description="R-squared score")\n    custom_metrics: Optional[Dict[str, Decimal]] = Field(None, description="Custom metrics")\n\n\nclass FeatureImportance(BaseModel):\n    """Feature importance values"""\n    feature_name: str = Field(..., description="Feature name")\n    importance_score: Decimal = Field(..., description="Importance score")\n    rank: int = Field(..., ge=1, description="Importance rank")\n\n\nclass AIModelConfigResponse(AIModelConfigBase, BaseResponseSchema, CompanyScopedMixin):\n    """Schema for AI model configuration responses"""\n    status: ModelStatus = Field(default=ModelStatus.DRAFT)\n    metrics: Optional[ModelMetrics] = Field(None, description="Model performance metrics")\n    feature_importance: Optional[List[FeatureImportance]] = Field(None, description="Feature importance rankings")\n    training_samples: int = Field(default=0, description="Number of training samples")\n    validation_samples: int = Field(default=0, description="Number of validation samples")\n    prediction_count: int = Field(default=0, description="Total predictions made")\n    last_prediction_at: Optional[datetime] = Field(None, description="Last prediction timestamp")\n    created_by_id: int\n\n    model_config = ConfigDict(from_attributes=True)\n\n\n# ==================== ANOMALY DETECTION ====================\n\nclass AnomalyDetectionConfigBase(BaseModel):\n    """Base schema for anomaly detection configuration"""\n    name: str = Field(..., min_length=1, max_length=200, description="Configuration name")\n    description: Optional[str] = Field(None, max_length=2000, description="Description")\n    anomaly_type: AnomalyType = Field(..., description="Type of anomaly to detect")\n    data_source: DataSource = Field(..., description="Data source to monitor")\n    data_query: Optional[str] = Field(None, description="Data query/filter")\n    \n    # Detection parameters\n    detection_method: str = Field(default="statistical", description="Detection method: statistical, ml, rules, hybrid")\n    sensitivity: Decimal = Field(default=Decimal(\'0.95\'), ge=0.5, le=0.99, description="Detection sensitivity")\n    threshold_type: str = Field(default="dynamic", description="Threshold type: static, dynamic, adaptive")\n    static_threshold_low: Optional[Decimal] = Field(None, description="Static lower threshold")\n    static_threshold_high: Optional[Decimal] = Field(None, description="Static upper threshold")\n    \n    # Time window\n    lookback_period: int = Field(default=30, ge=1, le=365, description="Lookback period in days")\n    comparison_period: int = Field(default=7, ge=1, le=90, description="Comparison period in days")\n    seasonality_period: Optional[int] = Field(None, description="Seasonality period in days")\n    \n    # ML configuration\n    model_id: Optional[int] = Field(None, description="Linked ML model ID")\n    \n    # Alerting\n    generate_alerts: bool = Field(default=True, description="Generate alerts for detected anomalies")\n    alert_severity_threshold: AnomalySeverity = Field(default=AnomalySeverity.MEDIUM, description="Minimum severity for alerts")\n    notification_channels: Optional[List[str]] = Field(None, description="Notification channels")\n    \n    # Execution\n    is_active: bool = Field(default=True, description="Whether detection is active")\n    scan_frequency: str = Field(default="daily", description="Scan frequency: hourly, daily, weekly")\n    last_scan_at: Optional[datetime] = Field(None, description="Last scan timestamp")\n    next_scan_at: Optional[datetime] = Field(None, description="Next scheduled scan")\n\n\nclass AnomalyDetectionConfigCreate(AnomalyDetectionConfigBase):\n    """Schema for creating anomaly detection configurations"""\n    pass\n\n\nclass AnomalyDetectionConfigUpdate(BaseModel):\n    """Schema for updating anomaly detection configurations"""\n    name: Optional[str] = Field(None, min_length=1, max_length=200)\n    description: Optional[str] = Field(None, max_length=2000)\n    sensitivity: Optional[Decimal] = Field(None, ge=0.5, le=0.99)\n    threshold_type: Optional[str] = None\n    static_threshold_low: Optional[Decimal] = None\n    static_threshold_high: Optional[Decimal] = None\n    lookback_period: Optional[int] = Field(None, ge=1, le=365)\n    comparison_period: Optional[int] = Field(None, ge=1, le=90)\n    generate_alerts: Optional[bool] = None\n    alert_severity_threshold: Optional[AnomalySeverity] = None\n    is_active: Optional[bool] = None\n    scan_frequency: Optional[str] = None\n\n\nclass AnomalyDetectionConfigResponse(AnomalyDetectionConfigBase, BaseResponseSchema, CompanyScopedMixin):\n    """Schema for anomaly detection configuration responses"""\n    total_anomalies_detected: int = Field(default=0, description="Total anomalies detected")\n    anomalies_last_30_days: int = Field(default=0, description="Anomalies in last 30 days")\n    false_positive_rate: Optional[Decimal] = Field(None, description="Estimated false positive rate")\n    model_config = ConfigDict(from_attributes=True)\n\n\nclass DetectedAnomalyBase(BaseModel):\n    """Base schema for detected anomalies"""\n    detection_config_id: int = Field(..., description="Detection configuration ID")\n    anomaly_type: AnomalyType = Field(..., description="Type of anomaly")\n    severity: AnomalySeverity = Field(..., description="Anomaly severity")\n    detected_at: datetime = Field(..., description="Detection timestamp")\n    \n    # Anomaly details\n    entity_type: str = Field(..., description="Affected entity type: transaction, account, vendor, etc.")\n    entity_id: Optional[int] = Field(None, description="Affected entity ID")\n    entity_identifier: Optional[str] = Field(None, description="Entity identifier (e.g., transaction number)")\n    \n    # Values\n    expected_value: Optional[Decimal] = Field(None, description="Expected value")\n    actual_value: Optional[Decimal] = Field(None, description="Actual value")\n    deviation: Optional[Decimal] = Field(None, description="Deviation from expected")\n    deviation_percentage: Optional[Decimal] = Field(None, description="Deviation percentage")\n    z_score: Optional[Decimal] = Field(None, description="Z-score of the anomaly")\n    confidence_score: Decimal = Field(..., ge=0, le=1, description="Detection confidence score")\n    \n    # Context\n    detection_date: date = Field(..., description="Date of anomalous data")\n    period_context: Optional[Dict[str, Any]] = Field(None, description="Period context data")\n    related_entities: Optional[List[Dict[str, Any]]] = Field(None, description="Related entities")\n    \n    # Status\n    status: str = Field(default="new", description="Status: new, investigating, confirmed, false_positive, resolved")\n    assigned_to_id: Optional[int] = Field(None, description="Assigned user ID")\n    assigned_at: Optional[datetime] = Field(None, description="Assignment timestamp")\n    \n    # Resolution\n    resolution_notes: Optional[str] = Field(None, max_length=5000, description="Resolution notes")\n    resolved_by_id: Optional[int] = Field(None, description="User who resolved")\n    resolved_at: Optional[datetime] = Field(None, description="Resolution timestamp")\n    resolution_type: Optional[str] = Field(None, description="Resolution type: action_taken, false_positive, acceptable, other")\n    \n    # Additional context\n    description: str = Field(..., min_length=1, max_length=2000, description="Anomaly description")\n    supporting_data: Optional[Dict[str, Any]] = Field(None, description="Supporting data points")\n\n\nclass DetectedAnomalyCreate(DetectedAnomalyBase):\n    """Schema for creating detected anomaly records"""\n    pass\n\n\nclass DetectedAnomalyUpdate(BaseModel):\n    """Schema for updating detected anomalies"""\n    status: Optional[str] = None\n    assigned_to_id: Optional[int] = None\n    resolution_notes: Optional[str] = Field(None, max_length=5000)\n    resolution_type: Optional[str] = None\n\n\nclass DetectedAnomalyResponse(DetectedAnomalyBase, BaseResponseSchema, CompanyScopedMixin):\n    """Schema for detected anomaly responses"""\n    detection_config_name: Optional[str] = None\n    assigned_to_name: Optional[str] = None\n    resolved_by_name: Optional[str] = None\n    days_open: int = Field(default=0, description="Days since detection")\n    model_config = ConfigDict(from_attributes=True)\n\n\n# ==================== FORECASTING ====================\n\nclass ForecastConfigBase(BaseModel):\n    """Base schema for forecast configuration"""\n    name: str = Field(..., min_length=1, max_length=200, description="Forecast name")\n    description: Optional[str] = Field(None, max_length=2000, description="Description")\n    forecast_type: ForecastType = Field(..., description="Type of forecast")\n    forecast_horizon: ForecastHorizon = Field(default=ForecastHorizon.MONTHLY, description="Forecast horizon granularity")\n    horizon_periods: int = Field(default=12, ge=1, le=60, description="Number of periods to forecast")\n    \n    # Data source\n    data_source: DataSource = Field(..., description="Data source for forecasting")\n    data_query: Optional[str] = Field(None, description="Data query/filter")\n    historical_periods: int = Field(default=24, ge=6, le=120, description="Historical periods for training")\n    \n    # Forecasting method\n    method: str = Field(default="auto", description="Forecasting method: auto, arima, exponential_smoothing, prophet, ml, ensemble")\n    model_id: Optional[int] = Field(None, description="Linked ML model ID")\n    \n    # Parameters\n    include_seasonality: bool = Field(default=True, description="Include seasonality")\n    seasonality_type: Optional[str] = Field(None, description="Seasonality type: additive, multiplicative")\n    include_trend: bool = Field(default=True, description="Include trend component")\n    confidence_intervals: List[Decimal] = Field(default=[Decimal(\'0.80\'), Decimal(\'0.95\')], description="Confidence intervals")\n    \n    # External factors\n    external_factors: Optional[List[str]] = Field(None, description="External factor columns")\n    scenario_adjustments: Optional[Dict[str, Decimal]] = Field(None, description="Scenario adjustments")\n    \n    # Execution\n    is_active: bool = Field(default=True, description="Whether forecast is active")\n    auto_refresh: bool = Field(default=True, description="Auto-refresh forecasts")\n    refresh_frequency: str = Field(default="monthly", description="Refresh frequency")\n    last_forecast_at: Optional[datetime] = Field(None, description="Last forecast timestamp")\n    next_forecast_at: Optional[datetime] = Field(None, description="Next scheduled forecast")\n\n\nclass ForecastConfigCreate(ForecastConfigBase):\n    """Schema for creating forecast configurations"""\n    pass\n\n\nclass ForecastConfigUpdate(BaseModel):\n    """Schema for updating forecast configurations"""\n    name: Optional[str] = Field(None, min_length=1, max_length=200)\n    description: Optional[str] = Field(None, max_length=2000)\n    horizon_periods: Optional[int] = Field(None, ge=1, le=60)\n    historical_periods: Optional[int] = Field(None, ge=6, le=120)\n    method: Optional[str] = None\n    include_seasonality: Optional[bool] = None\n    include_trend: Optional[bool] = None\n    confidence_intervals: Optional[List[Decimal]] = None\n    external_factors: Optional[List[str]] = None\n    scenario_adjustments: Optional[Dict[str, Decimal]] = None\n    is_active: Optional[bool] = None\n    auto_refresh: Optional[bool] = None\n    refresh_frequency: Optional[str] = None\n\n\nclass ForecastConfigResponse(ForecastConfigBase, BaseResponseSchema, CompanyScopedMixin):\n    """Schema for forecast configuration responses"""\n    last_run_status: Optional[str] = Field(None, description="Last run status")\n    last_run_error: Optional[str] = Field(None, description="Last run error message")\n    accuracy_mape: Optional[Decimal] = Field(None, description="Forecast accuracy (MAPE)")\n    created_by_id: int\n    model_config = ConfigDict(from_attributes=True)\n\n\nclass ForecastPoint(BaseModel):\n    """Single forecast data point"""\n    period_date: date = Field(..., description="Period date")\n    period_label: str = Field(..., description="Period label")\n    forecast_value: Decimal = Field(..., description="Forecasted value")\n    lower_bound_80: Optional[Decimal] = Field(None, description="Lower bound (80% CI)")\n    upper_bound_80: Optional[Decimal] = Field(None, description="Upper bound (80% CI)")\n    lower_bound_95: Optional[Decimal] = Field(None, description="Lower bound (95% CI)")\n    upper_bound_95: Optional[Decimal] = Field(None, description="Upper bound (95% CI)")\n    actual_value: Optional[Decimal] = Field(None, description="Actual value if available")\n    is_historical: bool = Field(default=False, description="Whether this is historical data")\n\n\nclass ForecastRunBase(BaseModel):\n    """Base schema for forecast runs"""\n    config_id: int = Field(..., description="Forecast configuration ID")\n    run_date: datetime = Field(..., description="Run timestamp")\n    run_type: str = Field(default="scheduled", description="Run type: scheduled, manual, triggered")\n    status: str = Field(default="running", description="Status: running, completed, failed")\n    \n    # Model info\n    method_used: str = Field(..., description="Method used for this run")\n    model_version: Optional[str] = Field(None, description="Model version used")\n    \n    # Training metrics\n    training_start_date: Optional[date] = Field(None, description="Training data start")\n    training_end_date: Optional[date] = Field(None, description="Training data end")\n    training_periods: int = Field(default=0, description="Number of training periods")\n    \n    # Accuracy metrics\n    mape: Optional[Decimal] = Field(None, description="Mean Absolute Percentage Error")\n    mae: Optional[Decimal] = Field(None, description="Mean Absolute Error")\n    rmse: Optional[Decimal] = Field(None, description="Root Mean Squared Error")\n    \n    # Forecast period\n    forecast_start_date: date = Field(..., description="Forecast start date")\n    forecast_end_date: date = Field(..., description="Forecast end date")\n    forecast_periods: int = Field(default=0, description="Number of forecast periods")\n    \n    # Summary\n    total_forecast: Decimal = Field(default=Decimal(\'0\'), description="Total forecast value")\n    avg_forecast: Optional[Decimal] = Field(None, description="Average forecast value")\n    trend_direction: Optional[str] = Field(None, description="Trend: increasing, decreasing, stable")\n    seasonality_detected: bool = Field(default=False, description="Whether seasonality was detected")\n    \n    # Error handling\n    error_message: Optional[str] = Field(None, description="Error message if failed")\n    completed_at: Optional[datetime] = Field(None, description="Completion timestamp")\n    execution_time_seconds: Optional[int] = Field(None, description="Execution time")\n\n\nclass ForecastRunCreate(ForecastRunBase):\n    """Schema for creating forecast runs"""\n    pass\n\n\nclass ForecastRunUpdate(BaseModel):\n    """Schema for updating forecast runs"""\n    status: Optional[str] = None\n    error_message: Optional[str] = Field(None, max_length=5000)\n\n\nclass ForecastRunResponse(ForecastRunBase, BaseResponseSchema, CompanyScopedMixin):\n    """Schema for forecast run responses"""\n    forecast_points: List[ForecastPoint] = Field(default_factory=list, description="Forecast data points")\n    model_components: Optional[Dict[str, Any]] = Field(None, description="Model components (trend, seasonality, etc.)")\n    diagnostics: Optional[Dict[str, Any]] = Field(None, description="Diagnostic information")\n    initiated_by_id: int\n    model_config = ConfigDict(from_attributes=True)\n\n\n# ==================== AI INSIGHTS ====================\n\nclass AIInsightBase(BaseModel):\n    """Base schema for AI insights"""\n    title: str = Field(..., min_length=1, max_length=300, description="Insight title")\n    description: str = Field(..., min_length=1, max_length=5000, description="Insight description")\n    insight_type: InsightType = Field(..., description="Type of insight")\n    \n    # Source\n    source_module: str = Field(..., description="Source module: accounting, treasury, hr, etc.")\n    source_entity_type: Optional[str] = Field(None, description="Source entity type")\n    source_entity_id: Optional[int] = Field(None, description="Source entity ID")\n    \n    # Impact\n    impact_level: str = Field(default="medium", description="Impact level: low, medium, high")\n    impact_area: Optional[str] = Field(None, description="Impact area: revenue, cost, risk, efficiency")\n    estimated_impact_value: Optional[Decimal] = Field(None, description="Estimated financial impact")\n    \n    # Confidence and validity\n    confidence_score: Decimal = Field(default=Decimal(\'0.8\'), ge=0, le=1, description="Confidence score")\n    valid_from: date = Field(default_factory=date.today, description="Valid from date")\n    valid_until: Optional[date] = Field(None, description="Valid until date")\n    \n    # Related entities\n    related_entities: Optional[List[Dict[str, Any]]] = Field(None, description="Related entities")\n    supporting_data: Optional[Dict[str, Any]] = Field(None, description="Supporting data")\n    \n    # Actions\n    suggested_actions: Optional[List[str]] = Field(None, description="Suggested actions")\n    related_recommendation_ids: Optional[List[int]] = Field(None, description="Related recommendations")\n    \n    # Status\n    is_read: bool = Field(default=False, description="Whether insight has been read")\n    is_actioned: bool = Field(default=False, description="Whether action was taken")\n    dismissed_at: Optional[datetime] = Field(None, description="When dismissed")\n    dismissed_by_id: Optional[int] = Field(None, description="Who dismissed")\n\n\nclass AIInsightCreate(AIInsightBase):\n    """Schema for creating AI insights"""\n    pass\n\n\nclass AIInsightUpdate(BaseModel):\n    """Schema for updating AI insights"""\n    is_read: Optional[bool] = None\n    is_actioned: Optional[bool] = None\n    dismissed_at: Optional[datetime] = None\n\n\nclass AIInsightResponse(AIInsightBase, BaseResponseSchema, CompanyScopedMixin):\n    """Schema for AI insight responses"""\n    generated_by_model: Optional[str] = None\n    generation_method: str = Field(default="automated", description="automated, manual, hybrid")\n    model_config = ConfigDict(from_attributes=True)\n\n\n# ==================== RECOMMENDATIONS ====================\n\nclass RecommendationBase(BaseModel):\n    """Base schema for AI recommendations"""\n    title: str = Field(..., min_length=1, max_length=300, description="Recommendation title")\n    description: str = Field(..., min_length=1, max_length=5000, description="Recommendation description")\n    recommendation_type: RecommendationType = Field(..., description="Type of recommendation")\n    priority: RecommendationPriority = Field(default=RecommendationPriority.MEDIUM, description="Priority level")\n    \n    # Impact analysis\n    estimated_benefit: Optional[Decimal] = Field(None, description="Estimated benefit value")\n    estimated_cost: Optional[Decimal] = Field(None, description="Estimated implementation cost")\n    estimated_roi: Optional[Decimal] = Field(None, description="Estimated ROI percentage")\n    impact_timeframe: Optional[str] = Field(None, description="Impact timeframe: immediate, short_term, long_term")\n    \n    # Confidence\n    confidence_score: Decimal = Field(default=Decimal(\'0.8\'), ge=0, le=1, description="Confidence score")\n    risk_level: Optional[str] = Field(None, description="Implementation risk: low, medium, high")\n    \n    # Source and context\n    source_module: str = Field(..., description="Source module")\n    source_insight_ids: Optional[List[int]] = Field(None, description="Source insight IDs")\n    affected_entities: Optional[List[Dict[str, Any]]] = Field(None, description="Affected entities")\n    \n    # Implementation\n    implementation_steps: Optional[List[str]] = Field(None, description="Implementation steps")\n    prerequisites: Optional[List[str]] = Field(None, description="Prerequisites")\n    estimated_effort: Optional[str] = Field(None, description="Estimated effort: hours, days, weeks")\n    assigned_to_id: Optional[int] = Field(None, description="Assigned user ID")\n    \n    # Status\n    status: str = Field(default="new", description="Status: new, acknowledged, in_progress, implemented, dismissed, expired")\n    acknowledged_at: Optional[datetime] = Field(None, description="Acknowledgement timestamp")\n    acknowledged_by_id: Optional[int] = Field(None, description="Who acknowledged")\n    \n    # Implementation tracking\n    implemented_at: Optional[datetime] = Field(None, description="Implementation timestamp")\n    implemented_by_id: Optional[int] = Field(None, description="Who implemented")\n    actual_benefit: Optional[Decimal] = Field(None, description="Actual realized benefit")\n    implementation_notes: Optional[str] = Field(None, max_length=5000, description="Implementation notes")\n    \n    # Dismissal\n    dismissed_at: Optional[datetime] = Field(None, description="Dismissal timestamp")\n    dismissed_by_id: Optional[int] = Field(None, description="Who dismissed")\n    dismissal_reason: Optional[str] = Field(None, max_length=1000, description="Dismissal reason")\n    \n    # Validity\n    valid_until: Optional[datetime] = Field(None, description="Expiration timestamp")\n\n\nclass RecommendationCreate(RecommendationBase):\n    """Schema for creating recommendations"""\n    pass\n\n\nclass RecommendationUpdate(BaseModel):\n    """Schema for updating recommendations"""\n    priority: Optional[RecommendationPriority] = None\n    status: Optional[str] = None\n    assigned_to_id: Optional[int] = None\n    implementation_notes: Optional[str] = Field(None, max_length=5000)\n    actual_benefit: Optional[Decimal] = None\n    dismissal_reason: Optional[str] = Field(None, max_length=1000)\n\n\nclass RecommendationResponse(RecommendationBase, BaseResponseSchema, CompanyScopedMixin):\n    """Schema for recommendation responses"""\n    generated_by_model: Optional[str] = None\n    assigned_to_name: Optional[str] = None\n    acknowledged_by_name: Optional[str] = None\n    implemented_by_name: Optional[str] = None\n    dismissed_by_name: Optional[str] = None\n    days_since_generated: int = Field(default=0, description="Days since generation")\n    model_config = ConfigDict(from_attributes=True)\n\n\n# ==================== AI ALERTS ====================\n\nclass AIAlertBase(BaseModel):\n    """Base schema for AI alerts"""\n    alert_type: AlertType = Field(..., description="Type of alert")\n    severity: AlertSeverity = Field(default=AlertSeverity.WARNING, description="Alert severity")\n    title: str = Field(..., min_length=1, max_length=300, description="Alert title")\n    message: str = Field(..., min_length=1, max_length=5000, description="Alert message")\n    \n    # Source\n    source_module: str = Field(..., description="Source module")\n    source_entity_type: Optional[str] = Field(None, description="Source entity type")\n    source_entity_id: Optional[int] = Field(None, description="Source entity ID")\n    related_anomaly_id: Optional[int] = Field(None, description="Related anomaly ID")\n    related_forecast_id: Optional[int] = Field(None, description="Related forecast ID")\n    related_insight_id: Optional[int] = Field(None, description="Related insight ID")\n    \n    # Threshold details\n    threshold_value: Optional[Decimal] = Field(None, description="Threshold value")\n    actual_value: Optional[Decimal] = Field(None, description="Actual value")\n    threshold_breach_percentage: Optional[Decimal] = Field(None, description="Threshold breach %")\n    \n    # Context\n    context_data: Optional[Dict[str, Any]] = Field(None, description="Additional context data")\n    \n    # Notification\n    notified_users: Optional[List[int]] = Field(None, description="User IDs notified")\n    notification_channels: Optional[List[str]] = Field(None, description="Channels used: email, sms, in_app")\n    notification_sent_at: Optional[datetime] = Field(None, description="Notification timestamp")\n    \n    # Status\n    is_read: bool = Field(default=False, description="Whether alert has been read")\n    read_at: Optional[datetime] = Field(None, description="Read timestamp")\n    read_by_id: Optional[int] = Field(None, description="User who read")\n    is_acknowledged: bool = Field(default=False, description="Whether acknowledged")\n    acknowledged_at: Optional[datetime] = Field(None, description="Acknowledgement timestamp")\n    acknowledged_by_id: Optional[int] = Field(None, description="User who acknowledged")\n    is_resolved: bool = Field(default=False, description="Whether resolved")\n    resolved_at: Optional[datetime] = Field(None, description="Resolution timestamp")\n    resolution_notes: Optional[str] = Field(None, max_length=2000, description="Resolution notes")\n\n\nclass AIAlertCreate(AIAlertBase):\n    """Schema for creating AI alerts"""\n    pass\n\n\nclass AIAlertUpdate(BaseModel):\n    """Schema for updating AI alerts"""\n    is_read: Optional[bool] = None\n    is_acknowledged: Optional[bool] = None\n    is_resolved: Optional[bool] = None\n    resolution_notes: Optional[str] = Field(None, max_length=2000)\n\n\nclass AIAlertResponse(AIAlertBase, BaseResponseSchema, CompanyScopedMixin):\n    """Schema for AI alert responses"""\n    generated_at: datetime = Field(default_factory=datetime.utcnow, description="Generation timestamp")\n    model_config = ConfigDict(from_attributes=True)\n\n\n# ==================== DOCUMENT ANALYSIS ====================\n\nclass DocumentAnalysisRequestBase(BaseModel):\n    """Base schema for document analysis requests"""\n    analysis_type: AnalysisType = Field(..., description="Type of analysis")\n    document_id: Optional[int] = Field(None, description="Document ID if stored in system")\n    document_url: Optional[str] = Field(None, max_length=500, description="Document URL")\n    document_content: Optional[str] = Field(None, description="Document text content")\n    \n    # Options\n    extract_key_terms: bool = Field(default=True, description="Extract key terms")\n    extract_dates: bool = Field(default=True, description="Extract dates")\n    extract_amounts: bool = Field(default=True, description="Extract monetary amounts")\n    extract_parties: bool = Field(default=True, description="Extract parties")\n    extract_obligations: bool = Field(default=True, description="Extract obligations")\n    risk_assessment: bool = Field(default=True, description="Perform risk assessment")\n    compliance_check: bool = Field(default=False, description="Perform compliance check")\n    \n    # Custom extraction\n    custom_extractions: Optional[List[str]] = Field(None, description="Custom fields to extract")\n    \n    # Comparison\n    compare_with_template_id: Optional[int] = Field(None, description="Template to compare against")\n    compare_with_document_id: Optional[int] = Field(None, description="Document to compare against")\n\n\nclass DocumentAnalysisRequestCreate(DocumentAnalysisRequestBase):\n    """Schema for creating document analysis requests"""\n    pass\n\n\nclass ExtractedTerm(BaseModel):\n    """Extracted term from document"""\n    term_name: str = Field(..., description="Term name")\n    term_value: Any = Field(..., description="Term value")\n    confidence: Decimal = Field(..., ge=0, le=1, description="Extraction confidence")\n    location: Optional[Dict[str, int]] = Field(None, description="Location in document (page, position)")\n    context: Optional[str] = Field(None, description="Surrounding context")\n\n\nclass DocumentRisk(BaseModel):\n    """Document risk assessment"""\n    risk_type: str = Field(..., description="Type of risk")\n    risk_level: str = Field(..., description="Risk level: low, medium, high, critical")\n    description: str = Field(..., description="Risk description")\n    affected_section: Optional[str] = Field(None, description="Affected section")\n    mitigation_suggestion: Optional[str] = Field(None, description="Suggested mitigation")\n    confidence: Decimal = Field(..., ge=0, le=1, description="Risk assessment confidence")\n\n\nclass ComplianceIssue(BaseModel):\n    """Compliance issue found in document"""\n    issue_type: str = Field(..., description="Type of compliance issue")\n    regulation_reference: Optional[str] = Field(None, description="Regulation reference")\n    description: str = Field(..., description="Issue description")\n    severity: str = Field(..., description="Severity: low, medium, high")\n    affected_section: Optional[str] = Field(None, description="Affected section")\n    remediation_suggestion: Optional[str] = Field(None, description="Suggested remediation")\n\n\nclass DocumentAnalysisResult(BaseModel):\n    """Document analysis result"""\n    analysis_type: AnalysisType\n    summary: str = Field(..., description="Document summary")\n    key_terms: List[ExtractedTerm] = Field(default_factory=list, description="Extracted key terms")\n    dates: List[ExtractedTerm] = Field(default_factory=list, description="Extracted dates")\n    amounts: List[ExtractedTerm] = Field(default_factory=list, description="Extracted amounts")\n    parties: List[ExtractedTerm] = Field(default_factory=list, description="Extracted parties")\n    obligations: List[ExtractedTerm] = Field(default_factory=list, description="Extracted obligations")\n    risks: List[DocumentRisk] = Field(default_factory=list, description="Risk assessments")\n    compliance_issues: List[ComplianceIssue] = Field(default_factory=list, description="Compliance issues")\n    overall_risk_score: Optional[Decimal] = Field(None, ge=0, le=100, description="Overall risk score")\n    sentiment_score: Optional[Decimal] = Field(None, ge=-1, le=1, description="Document sentiment score")\n    custom_extractions: Optional[Dict[str, Any]] = Field(None, description="Custom extraction results")\n    comparison_result: Optional[Dict[str, Any]] = Field(None, description="Comparison result")\n    processing_time_seconds: Optional[int] = Field(None, description="Processing time")\n\n\nclass DocumentAnalysisRequestResponse(DocumentAnalysisRequestBase, BaseResponseSchema, CompanyScopedMixin):\n    """Schema for document analysis request responses"""\n    status: str = Field(default="pending", description="Status: pending, processing, completed, failed")\n    result: Optional[DocumentAnalysisResult] = Field(None, description="Analysis result")\n    error_message: Optional[str] = Field(None, description="Error message if failed")\n    requested_by_id: int\n    completed_at: Optional[datetime] = Field(None, description="Completion timestamp")\n    model_config = ConfigDict(from_attributes=True)\n\n\n# ==================== NATURAL LANGUAGE COMMANDS ====================\n\nclass NLCommandRequestBase(BaseModel):\n    """Base schema for natural language command requests"""\n    command_text: str = Field(..., min_length=1, max_length=5000, description="Natural language command")\n    context: Optional[Dict[str, Any]] = Field(None, description="Additional context")\n    conversation_history: Optional[List[Dict[str, str]]] = Field(None, description="Previous conversation")\n    \n    # Execution options\n    auto_execute: bool = Field(default=False, description="Automatically execute if safe")\n    require_confirmation: bool = Field(default=True, description="Require user confirmation")\n\n\nclass NLCommandRequestCreate(NLCommandRequestBase):\n    """Schema for creating NL command requests"""\n    pass\n\n\nclass NLCommandAction(BaseModel):\n    """Parsed action from natural language"""\n    action_type: str = Field(..., description="Action type: create, update, delete, query, analyze, etc.")\n    target_entity: str = Field(..., description="Target entity")\n    parameters: Dict[str, Any] = Field(default_factory=dict, description="Action parameters")\n    filters: Optional[Dict[str, Any]] = Field(None, description="Query filters")\n    confidence: Decimal = Field(..., ge=0, le=1, description="Parsing confidence")\n\n\nclass NLCommandRequestResponse(NLCommandRequestBase, BaseResponseSchema):\n    """Schema for NL command request responses"""\n    status: str = Field(default="pending", description="Status: pending, parsed, executed, failed")\n    \n    # Interpretation\n    intent: Optional[str] = Field(None, description="Detected intent")\n    entities: Optional[Dict[str, Any]] = Field(None, description="Extracted entities")\n    actions: Optional[List[NLCommandAction]] = Field(None, description="Parsed actions")\n    interpretation_confidence: Optional[Decimal] = Field(None, description="Interpretation confidence")\n    \n    # Clarification needed\n    needs_clarification: bool = Field(default=False, description="Whether clarification needed")\n    clarification_question: Optional[str] = Field(None, description="Question for user")\n    suggested_interpretations: Optional[List[str]] = Field(None, description="Suggested interpretations")\n    \n    # Execution\n    is_safe_to_execute: bool = Field(default=False, description="Whether safe to execute")\n    risk_level: Optional[str] = Field(None, description="Risk level: safe, low, medium, high")\n    requires_approval: bool = Field(default=False, description="Whether requires approval")\n    \n    # Result\n    execution_result: Optional[Dict[str, Any]] = Field(None, description="Execution result")\n    response_text: Optional[str] = Field(None, description="Human-readable response")\n    error_message: Optional[str] = Field(None, description="Error message if failed")\n    \n    requested_by_id: int\n    executed_at: Optional[datetime] = Field(None, description="Execution timestamp")\n    model_config = ConfigDict(from_attributes=True)\n\n\n# ==================== EXPLAINABILITY ====================\n\nclass AIExplanationBase(BaseModel):\n    """Base schema for AI explanations"""\n    entity_type: str = Field(..., description="Entity type being explained")\n    entity_id: int = Field(..., description="Entity ID")\n    explanation_type: str = Field(..., description="Explanation type: prediction, recommendation, anomaly, decision")\n    \n    # Summary\n    summary: str = Field(..., description="Human-readable explanation summary")\n    technical_explanation: Optional[str] = Field(None, description="Technical explanation")\n    \n    # Feature contributions\n    feature_contributions: Optional[List[Dict[str, Any]]] = Field(None, description="Feature contribution to decision")\n    \n    # SHAP values or similar\n    shap_values: Optional[Dict[str, Decimal]] = Field(None, description="SHAP values")\n    \n    # Decision path\n    decision_path: Optional[List[Dict[str, Any]]] = Field(None, description="Decision path taken")\n    \n    # Confidence factors\n    confidence_factors: Optional[Dict[str, Decimal]] = Field(None, description="Factors affecting confidence")\n    \n    # Similar cases\n    similar_cases: Optional[List[Dict[str, Any]]] = Field(None, description="Similar historical cases")\n    \n    # Model info\n    model_used: Optional[str] = Field(None, description="Model used for decision")\n    model_version: Optional[str] = Field(None, description="Model version")\n\n\nclass AIExplanationCreate(AIExplanationBase):\n    """Schema for creating AI explanations"""\n    pass\n\n\nclass AIExplanationResponse(AIExplanationBase, BaseResponseSchema):\n    """Schema for AI explanation responses"""\n    generated_at: datetime = Field(default_factory=datetime.utcnow)\n    model_config = ConfigDict(from_attributes=True)\n\n\n# ==================== FILTER PARAMETERS ====================\n\nclass AIModelConfigFilterParams(PaginationParams):\n    """Filter parameters for AI model config queries"""\n    model_type: Optional[AIModelType] = None\n    status: Optional[ModelStatus] = None\n    is_active: Optional[bool] = None\n\n\nclass DetectedAnomalyFilterParams(PaginationParams):\n    """Filter parameters for detected anomaly queries"""\n    anomaly_type: Optional[AnomalyType] = None\n    severity: Optional[AnomalySeverity] = None\n    status: Optional[str] = None\n    entity_type: Optional[str] = None\n    detected_from: Optional[datetime] = None\n    detected_to: Optional[datetime] = None\n\n\nclass ForecastConfigFilterParams(PaginationParams):\n    """Filter parameters for forecast config queries"""\n    forecast_type: Optional[ForecastType] = None\n    is_active: Optional[bool] = None\n\n\nclass ForecastRunFilterParams(PaginationParams):\n    """Filter parameters for forecast run queries"""\n    config_id: Optional[int] = None\n    status: Optional[str] = None\n    run_from: Optional[datetime] = None\n    run_to: Optional[datetime] = None\n\n\nclass AIInsightFilterParams(PaginationParams):\n    """Filter parameters for AI insight queries"""\n    insight_type: Optional[InsightType] = None\n    source_module: Optional[str] = None\n    is_read: Optional[bool] = None\n    is_actioned: Optional[bool] = None\n\n\nclass RecommendationFilterParams(PaginationParams):\n    """Filter parameters for recommendation queries"""\n    recommendation_type: Optional[RecommendationType] = None\n    priority: Optional[RecommendationPriority] = None\n    status: Optional[str] = None\n    assigned_to_id: Optional[int] = None\n\n\nclass AIAlertFilterParams(PaginationParams):\n    """Filter parameters for AI alert queries"""\n    alert_type: Optional[AlertType] = None\n    severity: Optional[AlertSeverity] = None\n    is_read: Optional[bool] = None\n    is_resolved: Optional[bool] = None\n    source_module: Optional[str] = None\n\n\nclass DocumentAnalysisFilterParams(PaginationParams):\n    """Filter parameters for document analysis queries"""\n    analysis_type: Optional[AnalysisType] = None\n    status: Optional[str] = None\n\n\n# ==================== LIST RESPONSES ====================\n\nclass AIModelConfigListResponse(ListResponseBase):\n    """List response for AI model configs"""\n    items: List[AIModelConfigResponse]\n\n\nclass AnomalyDetectionConfigListResponse(ListResponseBase):\n    """List response for anomaly detection configs"""\n    items: List[AnomalyDetectionConfigResponse]\n\n\nclass DetectedAnomalyListResponse(ListResponseBase):\n    """List response for detected anomalies"""\n    items: List[DetectedAnomalyResponse]\n\n\nclass ForecastConfigListResponse(ListResponseBase):\n    """List response for forecast configs"""\n    items: List[ForecastConfigResponse]\n\n\nclass ForecastRunListResponse(ListResponseBase):\n    """List response for forecast runs"""\n    items: List[ForecastRunResponse]\n\n\nclass AIInsightListResponse(ListResponseBase):\n    """List response for AI insights"""\n    items: List[AIInsightResponse]\n\n\nclass RecommendationListResponse(ListResponseBase):\n    """List response for recommendations"""\n    items: List[RecommendationResponse]\n\n\nclass AIAlertListResponse(ListResponseBase):\n    """List response for AI alerts"""\n    items: List[AIAlertResponse]\n\n\nclass DocumentAnalysisListResponse(ListResponseBase):\n    """List response for document analysis requests"""\n    items: List[DocumentAnalysisRequestResponse]\n\n\nclass NLCommandListResponse(ListResponseBase):\n    """List response for NL command requests"""\n    items: List[NLCommandRequestResponse]\n\n\nclass AIExplanationListResponse(ListResponseBase):\n    """List response for AI explanations"""\n    items: List[AIExplanationResponse]\n\n\n# ==================== ANALYTICS RESPONSES ====================\n\nclass AIStatisticsResponse(BaseModel):\n    """AI module statistics"""\n    total_models: int = 0\n    active_models: int = 0\n    total_predictions: int = 0\n    predictions_today: int = 0\n    avg_prediction_latency_ms: int = 0\n    \n    # Anomalies\n    total_anomalies_detected: int = 0\n    anomalies_last_30_days: int = 0\n    open_anomalies: int = 0\n    critical_anomalies: int = 0\n    \n    # Forecasts\n    active_forecasts: int = 0\n    forecasts_run_today: int = 0\n    avg_forecast_accuracy: Optional[Decimal] = None\n    \n    # Insights\n    total_insights: int = 0\n    unread_insights: int = 0\n    insights_last_7_days: int = 0\n    \n    # Recommendations\n    total_recommendations: int = 0\n    new_recommendations: int = 0\n    implemented_recommendations: int = 0\n    total_realized_benefit: Decimal = Decimal(\'0\')\n    \n    # Alerts\n    active_alerts: int = 0\n    unacknowledged_alerts: int = 0\n    alerts_last_24_hours: int = 0\n    \n    # Document analysis\n    documents_analyzed: int = 0\n    avg_analysis_time_seconds: int = 0\n    \n    # NL commands\n    nl_commands_today: int = 0\n    nl_commands_success_rate: Optional[Decimal] = None\n\n\nclass AIModelPerformanceHistory(BaseModel):\n    """AI model performance over time"""\n    model_id: int\n    model_name: str\n    measurement_date: date\n    accuracy: Optional[Decimal] = None\n    precision: Optional[Decimal] = None\n    recall: Optional[Decimal] = None\n    f1_score: Optional[Decimal] = None\n    prediction_count: int = 0\n    error_count: int = 0\n    avg_latency_ms: int = 0\n\n\nclass AIModelComparisonResponse(BaseModel):\n    """AI model comparison"""\n    models: List[AIModelConfigResponse]\n    comparison_metrics: List[str]\n    comparison_data: List[Dict[str, Any]]\n    best_model_by_metric: Dict[str, int]\n</create-file>\n</function_calls>'}
{'role': 'user', 'content': '<tool_result> <create-file> ToolResult(success=True, output="File \'backend/app/schemas/ai.py\' created successfully.") </create-file> </tool_result>'}
{'role': 'assistant', 'content': 'Now let me create the schemas `__init__.py` to export all schemas:\n\n<function_calls>\n<create-file file_path="backend/app/schemas/__init__.py">\n"""\nSAMMS Enterprise - Pydantic Schemas Package\nAll request/response schemas for the API layer\n"""\n\n# Base schemas\nfrom .base import (\n    BaseResponseSchema,\n    TimestampMixin,\n    PaginationParams,\n    ListResponseBase,\n    AuditMixin,\n    CompanyScopedMixin,\n)\n\n# Company schemas\nfrom .company import (\n    CompanyType,\n    CompanyStatus,\n    OwnershipType,\n    IndustrySector,\n    CompanyGroupCreate,\n    CompanyGroupUpdate,\n    CompanyGroupResponse,\n    CompanyCreate,\n    CompanyUpdate,\n    CompanyResponse,\n    CompanySettingCreate,\n    CompanySettingUpdate,\n    CompanySettingResponse,\n    CompanyDocumentCreate,\n    CompanyDocumentUpdate,\n    CompanyDocumentResponse,\n    CompanyFilterParams,\n    CompanyGroupFilterParams,\n    CompanyListResponse,\n    CompanyGroupListResponse,\n    CompanyStatisticsResponse,\n)\n\n# User schemas\nfrom .user import (\n    UserType,\n    UserStatus,\n    AuthenticationMethod,\n    PermissionScope,\n    PermissionCreate,\n    PermissionUpdate,\n    PermissionResponse,\n    RoleCreate,\n    RoleUpdate,\n    RoleResponse,\n    UserCreate,\n    UserUpdate,\n    UserResponse,\n    UserSessionResponse,\n    UserActivityLogResponse,\n    LoginRequest,\n    LoginResponse,\n    LogoutRequest,\n    RefreshTokenRequest,\n    MFASetupResponse,\n    MFAVerifyRequest,\n    PasswordResetRequest,\n    PasswordResetConfirm,\n    PermissionFilterParams,\n    RoleFilterParams,\n    UserFilterParams,\n    PermissionListResponse,\n    RoleListResponse,\n    UserListResponse,\n    UserStatisticsResponse,\n)\n\n# Accounting schemas\nfrom .accounting import (\n    AccountType,\n    AccountSubType,\n    JournalEntryStatus,\n    FiscalYearStatus,\n    AccountCreate,\n    AccountUpdate,\n    AccountResponse,\n    JournalEntryLineCreate,\n    JournalEntryLineResponse,\n    JournalEntryCreate,\n    JournalEntryUpdate,\n    JournalEntryResponse,\n    FiscalYearCreate,\n    FiscalYearUpdate,\n    FiscalYearResponse,\n    FiscalPeriodCreate,\n    FiscalPeriodUpdate,\n    FiscalPeriodResponse,\n    AccountBalanceResponse,\n    TrialBalanceResponse,\n    BudgetCreate,\n    BudgetUpdate,\n    BudgetResponse,\n    BudgetLineCreate,\n    BudgetLineResponse,\n    FinancialStatementRequest,\n    FinancialStatementResponse,\n    AccountFilterParams,\n    JournalEntryFilterParams,\n    FiscalYearFilterParams,\n    BudgetFilterParams,\n    AccountListResponse,\n    JournalEntryListResponse,\n    FiscalYearListResponse,\n    BudgetListResponse,\n    AccountingStatisticsResponse,\n)\n\n# Treasury schemas\nfrom .treasury import (\n    BankAccountType,\n    TransactionType,\n    ReconciliationStatus,\n    BankAccountCreate,\n    BankAccountUpdate,\n    BankAccountResponse,\n    TreasuryTransactionCreate,\n    TreasuryTransactionUpdate,\n    TreasuryTransactionResponse,\n    BankReconciliationCreate,\n    BankReconciliationUpdate,\n    BankReconciliationResponse,\n    ReconciliationLineCreate,\n    ReconciliationLineResponse,\n    CashFlowForecastCreate,\n    CashFlowForecastUpdate,\n    CashFlowForecastResponse,\n    CashFlowForecastLineCreate,\n    CashFlowForecastLineResponse,\n    PaymentTermCreate,\n    PaymentTermUpdate,\n    PaymentTermResponse,\n    CashPositionResponse,\n    CashFlowSummaryResponse,\n    BankAccountFilterParams,\n    TreasuryTransactionFilterParams,\n    BankReconciliationFilterParams,\n    CashFlowForecastFilterParams,\n    BankAccountListResponse,\n    TreasuryTransactionListResponse,\n    BankReconciliationListResponse,\n    CashFlowForecastListResponse,\n    PaymentTermListResponse,\n    TreasuryStatisticsResponse,\n)\n\n# Invoice schemas\nfrom .invoice import (\n    ContactType,\n    InvoiceStatus,\n    ProductType,\n    PaymentStatus,\n    ContactCreate,\n    ContactUpdate,\n    ContactResponse,\n    ProductCreate,\n    ProductUpdate,\n    ProductResponse,\n    InvoiceLineCreate,\n    InvoiceLineResponse,\n    InvoiceCreate,\n    InvoiceUpdate,\n    InvoiceResponse,\n    PaymentCreate,\n    PaymentUpdate,\n    PaymentResponse,\n    PaymentAllocationCreate,\n    PaymentAllocationResponse,\n    SubscriptionCreate,\n    SubscriptionUpdate,\n    SubscriptionResponse,\n    RecurringInvoiceCreate,\n    RecurringInvoiceUpdate,\n    RecurringInvoiceResponse,\n    RevenueSummaryResponse,\n    AgingReportResponse,\n    ContactFilterParams,\n    ProductFilterParams,\n    InvoiceFilterParams,\n    PaymentFilterParams,\n    SubscriptionFilterParams,\n    ContactListResponse,\n    ProductListResponse,\n    InvoiceListResponse,\n    PaymentListResponse,\n    SubscriptionListResponse,\n    RecurringInvoiceListResponse,\n    InvoiceStatisticsResponse,\n)\n\n# HR schemas\nfrom .hr import (\n    EmploymentType,\n    PayType,\n    PayFrequency,\n    LeaveType,\n    LeaveStatus,\n    BenefitType,\n    DepartmentCreate,\n    DepartmentUpdate,\n    DepartmentResponse,\n    PositionCreate,\n    PositionUpdate,\n    PositionResponse,\n    EmployeeCreate,\n    EmployeeUpdate,\n    EmployeeResponse,\n    PayrollLineCreate,\n    PayrollLineResponse,\n    PayrollCreate,\n    PayrollUpdate,\n    PayrollResponse,\n    TimeEntryCreate,\n    TimeEntryUpdate,\n    TimeEntryResponse,\n    LeaveRequestCreate,\n    LeaveRequestUpdate,\n    LeaveRequestResponse,\n    BenefitCreate,\n    BenefitUpdate,\n    BenefitResponse,\n    EmployeeBenefitCreate,\n    EmployeeBenefitResponse,\n    HRStatisticsResponse,\n    DepartmentFilterParams,\n    PositionFilterParams,\n    EmployeeFilterParams,\n    PayrollFilterParams,\n    TimeEntryFilterParams,\n    LeaveRequestFilterParams,\n    DepartmentListResponse,\n    PositionListResponse,\n    EmployeeListResponse,\n    PayrollListResponse,\n    TimeEntryListResponse,\n    LeaveRequestListResponse,\n    BenefitListResponse,\n)\n\n# Tax schemas\nfrom .tax import (\n    TaxType,\n    TaxJurisdictionType,\n    TaxFilingStatus,\n    NexusType,\n    TaxRateCreate,\n    TaxRateUpdate,\n    TaxRateResponse,\n    TaxCodeCreate,\n    TaxCodeUpdate,\n    TaxCodeResponse,\n    TaxTransactionCreate,\n    TaxTransactionResponse,\n    TaxFilingCreate,\n    TaxFilingUpdate,\n    TaxFilingResponse,\n    TaxFilingLineCreate,\n    TaxFilingLineResponse,\n    TaxNexusRuleCreate,\n    TaxNexusRuleUpdate,\n    TaxNexusRuleResponse,\n    ExchangeRateCreate,\n    ExchangeRateUpdate,\n    ExchangeRateResponse,\n    TaxCalculationRequest,\n    TaxCalculationResponse,\n    TaxCalculationLine,\n    TaxSummaryResponse,\n    TaxLiabilityReportResponse,\n    TaxRateFilterParams,\n    TaxCodeFilterParams,\n    TaxTransactionFilterParams,\n    TaxFilingFilterParams,\n    TaxNexusRuleFilterParams,\n    ExchangeRateFilterParams,\n    TaxRateListResponse,\n    TaxCodeListResponse,\n    TaxTransactionListResponse,\n    TaxFilingListResponse,\n    TaxNexusRuleListResponse,\n    ExchangeRateListResponse,\n    TaxStatisticsResponse,\n)\n\n# Workflow schemas\nfrom .workflow import (\n    WorkflowStatus,\n    TriggerType,\n    ActionType,\n    ConditionOperator,\n    WorkflowCreate,\n    WorkflowUpdate,\n    WorkflowResponse,\n    WorkflowTriggerCreate,\n    WorkflowTriggerResponse,\n    WorkflowActionCreate,\n    WorkflowActionResponse,\n    WorkflowExecutionCreate,\n    WorkflowExecutionUpdate,\n    WorkflowExecutionResponse,\n    ExecutionLogCreate,\n    ExecutionLogResponse,\n    AutomationRuleCreate,\n    AutomationRuleUpdate,\n    AutomationRuleResponse,\n    NotificationCreate,\n    NotificationUpdate,\n    NotificationResponse,\n    ApprovalWorkflowCreate,\n    ApprovalWorkflowUpdate,\n    ApprovalWorkflowResponse,\n    ApprovalStepCreate,\n    ApprovalStepResponse,\n    ApprovalInstanceCreate,\n    ApprovalInstanceUpdate,\n    ApprovalInstanceResponse,\n    WorkflowStatisticsResponse,\n    WorkflowFilterParams,\n    WorkflowExecutionFilterParams,\n    AutomationRuleFilterParams,\n    NotificationFilterParams,\n    ApprovalWorkflowFilterParams,\n    ApprovalInstanceFilterParams,\n    WorkflowListResponse,\n    WorkflowExecutionListResponse,\n    AutomationRuleListResponse,\n    NotificationListResponse,\n    ApprovalWorkflowListResponse,\n    ApprovalInstanceListResponse,\n)\n\n# Legal schemas\nfrom .legal import (\n    LegalEntityType,\n    ContractType,\n    ContractStatus,\n    MatterType,\n    MatterStatus,\n    MatterPriority,\n    IPType,\n    IPStatus,\n    LegalEntityCreate,\n    LegalEntityUpdate,\n    LegalEntityResponse,\n    ContractPartyCreate,\n    ContractPartyResponse,\n    ContractMilestoneCreate,\n    ContractMilestoneResponse,\n    ContractCreate,\n    ContractUpdate,\n    ContractResponse,\n    DocumentCreate,\n    DocumentUpdate,\n    DocumentResponse,\n    DocumentVersionCreate,\n    DocumentVersionResponse,\n    LegalMatterPartyCreate,\n    LegalMatterPartyResponse,\n    LegalMilestoneCreate,\n    LegalMilestoneResponse,\n    LegalMatterCreate,\n    LegalMatterUpdate,\n    LegalMatterResponse,\n    IntellectualPropertyCreate,\n    IntellectualPropertyUpdate,\n    IntellectualPropertyResponse,\n    ContractAnalysisRequest,\n    ContractAnalysisResponse,\n    ContractRisk,\n    KeyTerm,\n    LegalDashboardResponse,\n    LegalEntityFilterParams,\n    ContractFilterParams,\n    DocumentFilterParams,\n    LegalMatterFilterParams,\n    IPFilterParams,\n    LegalEntityListResponse,\n    ContractListResponse,\n    DocumentListResponse,\n    LegalMatterListResponse,\n    IPListResponse,\n)\n\n# Reports schemas\nfrom .reports import (\n    ReportType,\n    ReportStatus,\n    ExportFormat,\n    ScheduleFrequency,\n    DashboardWidgetType,\n    AggregationType,\n    DateRangeType,\n    ChartOrientation,\n    LegendPosition,\n    ReportParameterCreate,\n    ReportParameterResponse,\n    ReportTemplateColumnCreate,\n    ReportTemplateColumnResponse,\n    ReportTemplateCreate,\n    ReportTemplateUpdate,\n    ReportTemplateResponse,\n    DateRange,\n    ComparisonPeriod,\n    ReportExecutionParameters,\n    ReportInstanceCreate,\n    ReportInstanceUpdate,\n    ReportInstanceResponse,\n    ReportDataColumn,\n    ReportDataRow,\n    ReportSummary,\n    ReportScheduleCreate,\n    ReportScheduleUpdate,\n    ReportScheduleResponse,\n    DashboardWidgetConfigCreate,\n    DashboardWidgetConfigResponse,\n    DashboardWidgetPosition,\n    DashboardWidgetCreate,\n    DashboardWidgetUpdate,\n    DashboardWidgetResponse,\n    DashboardCreate,\n    DashboardUpdate,\n    DashboardResponse,\n    KPICalculationType,\n    KPIDirection,\n    KPIDefinitionCreate,\n    KPIDefinitionUpdate,\n    KPIDefinitionResponse,\n    KPIValue,\n    ReportTemplateFilterParams,\n    ReportInstanceFilterParams,\n    ReportScheduleFilterParams,\n    DashboardFilterParams,\n    KPIDefinitionFilterParams,\n    ReportTemplateListResponse,\n    ReportInstanceListResponse,\n    ReportScheduleListResponse,\n    DashboardListResponse,\n    KPIDefinitionListResponse,\n    ReportBulkDelete,\n    DashboardDuplicate,\n    ReportTemplateDuplicate,\n    ReportStatisticsResponse,\n    DashboardStatisticsResponse,\n)\n\n# Consolidation schemas\nfrom .consolidation import (\n    ConsolidationStatus,\n    ConsolidationType,\n    EliminationType,\n    MatchingStatus,\n    ConsolidationScope,\n    CurrencyTranslationMethod,\n    AdjustmentType,\n    DataSource,\n    ConsolidationPeriodCreate,\n    ConsolidationPeriodUpdate,\n    ConsolidationPeriodResponse,\n    SubsidiaryConsolidationCreate,\n    SubsidiaryConsolidationUpdate,\n    SubsidiaryConsolidationResponse,\n    IntercompanyTransactionCreate,\n    IntercompanyTransactionUpdate,\n    IntercompanyTransactionResponse,\n    IntercompanyMatchLineCreate,\n    IntercompanyMatchLineResponse,\n    IntercompanyMatchCreate,\n    IntercompanyMatchUpdate,\n    IntercompanyMatchResponse,\n    EliminationLineCreate,\n    EliminationLineResponse,\n    EliminationEntryCreate,\n    EliminationEntryUpdate,\n    EliminationEntryResponse,\n    ConsolidationAdjustmentCreate,\n    ConsolidationAdjustmentUpdate,\n    ConsolidationAdjustmentResponse,\n    WorksheetLineResponse,\n    ConsolidationWorksheetCreate,\n    ConsolidationWorksheetUpdate,\n    ConsolidationWorksheetResponse,\n    ConsolidationRunCreate,\n    ConsolidationRunUpdate,\n    ConsolidationRunResponse,\n    ExchangeRateHistoryCreate,\n    ExchangeRateHistoryResponse,\n    CurrencyTranslationResult,\n    MinorityInterestCreate,\n    MinorityInterestResponse,\n    ConsolidationPeriodFilterParams,\n    IntercompanyTransactionFilterParams,\n    EliminationEntryFilterParams,\n    ConsolidationWorksheetFilterParams,\n    ConsolidationRunFilterParams,\n    ConsolidationPeriodListResponse,\n    SubsidiaryConsolidationListResponse,\n    IntercompanyTransactionListResponse,\n    IntercompanyMatchListResponse,\n    EliminationEntryListResponse,\n    ConsolidationAdjustmentListResponse,\n    ConsolidationWorksheetListResponse,\n    ConsolidationRunListResponse,\n    MinorityInterestListResponse,\n    ConsolidationStatisticsResponse,\n    IntercompanyBalanceSummary,\n    ConsolidationValidationResult,\n)\n\n# Asset schemas\nfrom .asset import (\n    AssetStatus,\n    AssetCategory,\n    DepreciationMethod,\n    AssetValuationMethod,\n    DisposalMethod,\n    ImpairmentStatus,\n    MaintenanceType,\n    MaintenanceStatus,\n    InsuranceStatus,\n    AssetClassCreate,\n    AssetClassUpdate,\n    AssetClassResponse,\n    AssetLocationCreate,\n    AssetLocationUpdate,\n    AssetLocationResponse,\n    FixedAssetCreate,\n    FixedAssetUpdate,\n    FixedAssetResponse,\n    DepreciationScheduleLineResponse,\n    DepreciationScheduleResponse,\n    DepreciationRunLineResponse,\n    DepreciationRunCreate,\n    DepreciationRunUpdate,\n    DepreciationRunResponse,\n    AssetTransferCreate,\n    AssetTransferUpdate,\n    AssetTransferResponse,\n    AssetDisposalLineCreate,\n    AssetDisposalLineResponse,\n    AssetDisposalCreate,\n    AssetDisposalUpdate,\n    AssetDisposalResponse,\n    AssetRevaluationCreate,\n    AssetRevaluationUpdate,\n    AssetRevaluationResponse,\n    AssetImpairmentCreate,\n    AssetImpairmentUpdate,\n    AssetImpairmentResponse,\n    AssetMaintenanceCreate,\n    AssetMaintenanceUpdate,\n    AssetMaintenanceResponse,\n    AssetInsuranceCreate,\n    AssetInsuranceUpdate,\n    AssetInsuranceResponse,\n    AssetClassFilterParams,\n    AssetLocationFilterParams,\n    FixedAssetFilterParams,\n    DepreciationRunFilterParams,\n    AssetTransferFilterParams,\n    AssetDisposalFilterParams,\n    AssetMaintenanceFilterParams,\n    AssetInsuranceFilterParams,\n    AssetClassListResponse,\n    AssetLocationListResponse,\n    FixedAssetListResponse,\n    DepreciationScheduleListResponse,\n    DepreciationRunListResponse,\n    AssetTransferListResponse,\n    AssetDisposalListResponse,\n    AssetRevaluationListResponse,\n    AssetImpairmentListResponse,\n    AssetMaintenanceListResponse,\n    AssetInsuranceListResponse,\n    AssetStatisticsResponse,\n    DepreciationForecastResponse,\n    AssetRollforwardResponse,\n)\n\n# AI schemas\nfrom .ai import (\n    AIModelType,\n    ModelStatus,\n    AnomalyType,\n    AnomalySeverity,\n    ForecastType,\n    ForecastHorizon,\n    AlertType,\n    AlertSeverity,\n    InsightType,\n    RecommendationType,\n    RecommendationPriority,\n    AnalysisType,\n    AIModelConfigCreate,\n    AIModelConfigUpdate,\n    AIModelConfigResponse,\n    ModelMetrics,\n    FeatureImportance,\n    AnomalyDetectionConfigCreate,\n    AnomalyDetectionConfigUpdate,\n    AnomalyDetectionConfigResponse,\n    DetectedAnomalyCreate,\n    DetectedAnomalyUpdate,\n    DetectedAnomalyResponse,\n    ForecastConfigCreate,\n    ForecastConfigUpdate,\n    ForecastConfigResponse,\n    ForecastPoint,\n    ForecastRunCreate,\n    ForecastRunUpdate,\n    ForecastRunResponse,\n    AIInsightCreate,\n    AIInsightUpdate,\n    AIInsightResponse,\n    RecommendationCreate,\n    RecommendationUpdate,\n    RecommendationResponse,\n    AIAlertCreate,\n    AIAlertUpdate,\n    AIAlertResponse,\n    DocumentAnalysisRequestCreate,\n    ExtractedTerm,\n    DocumentRisk,\n    ComplianceIssue,\n    DocumentAnalysisResult,\n    DocumentAnalysisRequestResponse,\n    NLCommandRequestCreate,\n    NLCommandAction,\n    NLCommandRequestResponse,\n    AIExplanationCreate,\n    AIExplanationResponse,\n    AIModelConfigFilterParams,\n    DetectedAnomalyFilterParams,\n    ForecastConfigFilterParams,\n    ForecastRunFilterParams,\n    AIInsightFilterParams,\n    RecommendationFilterParams,\n    AIAlertFilterParams,\n    DocumentAnalysisFilterParams,\n    AIModelConfigListResponse,\n    AnomalyDetectionConfigListResponse,\n    DetectedAnomalyListResponse,\n    ForecastConfigListResponse,\n    ForecastRunListResponse,\n    AIInsightListResponse,\n    RecommendationListResponse,\n    AIAlertListResponse,\n    DocumentAnalysisListResponse,\n    NLCommandListResponse,\n    AIExplanationListResponse,\n    AIStatisticsResponse,\n    AIModelPerformanceHistory,\n    AIModelComparisonResponse,\n)\n\n__all__ = [\n    # Base\n    "BaseResponseSchema",\n    "TimestampMixin",\n    "PaginationParams",\n    "ListResponseBase",\n    "AuditMixin",\n    "CompanyScopedMixin",\n    \n    # Company\n    "CompanyType",\n    "CompanyStatus",\n    "OwnershipType",\n    "IndustrySector",\n    "CompanyGroupCreate",\n    "CompanyGroupUpdate",\n    "CompanyGroupResponse",\n    "CompanyCreate",\n    "CompanyUpdate",\n    "CompanyResponse",\n    "CompanySettingCreate",\n    "CompanySettingUpdate",\n    "CompanySettingResponse",\n    "CompanyDocumentCreate",\n    "CompanyDocumentUpdate",\n    "CompanyDocumentResponse",\n    "CompanyFilterParams",\n    "CompanyGroupFilterParams",\n    "CompanyListResponse",\n    "CompanyGroupListResponse",\n    "CompanyStatisticsResponse",\n    \n    # User\n    "UserType",\n    "UserStatus",\n    "AuthenticationMethod",\n    "PermissionScope",\n    "PermissionCreate",\n    "PermissionUpdate",\n    "PermissionResponse",\n    "RoleCreate",\n    "RoleUpdate",\n    "RoleResponse",\n    "UserCreate",\n    "UserUpdate",\n    "UserResponse",\n    "UserSessionResponse",\n    "UserActivityLogResponse",\n    "LoginRequest",\n    "LoginResponse",\n    "LogoutRequest",\n    "RefreshTokenRequest",\n    "MFASetupResponse",\n    "MFAVerifyRequest",\n    "PasswordResetRequest",\n    "PasswordResetConfirm",\n    "PermissionFilterParams",\n    "RoleFilterParams",\n    "UserFilterParams",\n    "PermissionListResponse",\n    "RoleListResponse",\n    "UserListResponse",\n    "UserStatisticsResponse",\n    \n    # Accounting\n    "AccountType",\n    "AccountSubType",\n    "JournalEntryStatus",\n    "FiscalYearStatus",\n    "AccountCreate",\n    "AccountUpdate",\n    "AccountResponse",\n    "JournalEntryLineCreate",\n    "JournalEntryLineResponse",\n    "JournalEntryCreate",\n    "JournalEntryUpdate",\n    "JournalEntryResponse",\n    "FiscalYearCreate",\n    "FiscalYearUpdate",\n    "FiscalYearResponse",\n    "FiscalPeriodCreate",\n    "FiscalPeriodUpdate",\n    "FiscalPeriodResponse",\n    "AccountBalanceResponse",\n    "TrialBalanceResponse",\n    "BudgetCreate",\n    "BudgetUpdate",\n    "BudgetResponse",\n    "BudgetLineCreate",\n    "BudgetLineResponse",\n    "FinancialStatementRequest",\n    "FinancialStatementResponse",\n    "AccountFilterParams",\n    "JournalEntryFilterParams",\n    "FiscalYearFilterParams",\n    "BudgetFilterParams",\n    "AccountListResponse",\n    "JournalEntryListResponse",\n    "FiscalYearListResponse",\n    "BudgetListResponse",\n    "AccountingStatisticsResponse",\n    \n    # Treasury\n    "BankAccountType",\n    "TransactionType",\n    "ReconciliationStatus",\n    "BankAccountCreate",\n    "BankAccountUpdate",\n    "BankAccountResponse",\n    "TreasuryTransactionCreate",\n    "TreasuryTransactionUpdate",\n    "TreasuryTransactionResponse",\n    "BankReconciliationCreate",\n    "BankReconciliationUpdate",\n    "BankReconciliationResponse",\n    "ReconciliationLineCreate",\n    "ReconciliationLineResponse",\n    "CashFlowForecastCreate",\n    "CashFlowForecastUpdate",\n    "CashFlowForecastResponse",\n    "CashFlowForecastLineCreate",\n    "CashFlowForecastLineResponse",\n    "PaymentTermCreate",\n    "PaymentTermUpdate",\n    "PaymentTermResponse",\n    "CashPositionResponse",\n    "CashFlowSummaryResponse",\n    "BankAccountFilterParams",\n    "TreasuryTransactionFilterParams",\n    "BankReconciliationFilterParams",\n    "CashFlowForecastFilterParams",\n    "BankAccountListResponse",\n    "TreasuryTransactionListResponse",\n    "BankReconciliationListResponse",\n    "CashFlowForecastListResponse",\n    "PaymentTermListResponse",\n    "TreasuryStatisticsResponse",\n    \n    # Invoice\n    "ContactType",\n    "InvoiceStatus",\n    "ProductType",\n    "PaymentStatus",\n    "ContactCreate",\n    "ContactUpdate",\n    "ContactResponse",\n    "ProductCreate",\n    "ProductUpdate",\n    "ProductResponse",\n    "InvoiceLineCreate",\n    "InvoiceLineResponse",\n    "InvoiceCreate",\n    "InvoiceUpdate",\n    "InvoiceResponse",\n    "PaymentCreate",\n    "PaymentUpdate",\n    "PaymentResponse",\n    "PaymentAllocationCreate",\n    "PaymentAllocationResponse",\n    "SubscriptionCreate",\n    "SubscriptionUpdate",\n    "SubscriptionResponse",\n    "RecurringInvoiceCreate",\n    "RecurringInvoiceUpdate",\n    "RecurringInvoiceResponse",\n    "RevenueSummaryResponse",\n    "AgingReportResponse",\n    "ContactFilterParams",\n    "ProductFilterParams",\n    "InvoiceFilterParams",\n    "PaymentFilterParams",\n    "SubscriptionFilterParams",\n    "ContactListResponse",\n    "ProductListResponse",\n    "InvoiceListResponse",\n    "PaymentListResponse",\n    "SubscriptionListResponse",\n    "RecurringInvoiceListResponse",\n    "InvoiceStatisticsResponse",\n    \n    # HR\n    "EmploymentType",\n    "PayType",\n    "PayFrequency",\n    "LeaveType",\n    "LeaveStatus",\n    "BenefitType",\n    "DepartmentCreate",\n    "DepartmentUpdate",\n    "DepartmentResponse",\n    "PositionCreate",\n    "PositionUpdate",\n    "PositionResponse",\n    "EmployeeCreate",\n    "EmployeeUpdate",\n    "EmployeeResponse",\n    "PayrollLineCreate",\n    "PayrollLineResponse",\n    "PayrollCreate",\n    "PayrollUpdate",\n    "PayrollResponse",\n    "TimeEntryCreate",\n    "TimeEntryUpdate",\n    "TimeEntryResponse",\n    "LeaveRequestCreate",\n    "LeaveRequestUpdate",\n    "LeaveRequestResponse",\n    "BenefitCreate",\n    "BenefitUpdate",\n    "BenefitResponse",\n    "EmployeeBenefitCreate",\n    "EmployeeBenefitResponse",\n    "HRStatisticsResponse",\n    "DepartmentFilterParams",\n    "PositionFilterParams",\n    "EmployeeFilterParams",\n    "PayrollFilterParams",\n    "TimeEntryFilterParams",\n    "LeaveRequestFilterParams",\n    "DepartmentListResponse",\n    "PositionListResponse",\n    "EmployeeListResponse",\n    "PayrollListResponse",\n    "TimeEntryListResponse",\n    "LeaveRequestListResponse",\n    "BenefitListResponse",\n    \n    # Tax\n    "TaxType",\n    "TaxJurisdictionType",\n    "TaxFilingStatus",\n    "NexusType",\n    "TaxRateCreate",\n    "TaxRateUpdate",\n    "TaxRateResponse",\n    "TaxCodeCreate",\n    "TaxCodeUpdate",\n    "TaxCodeResponse",\n    "TaxTransactionCreate",\n    "TaxTransactionResponse",\n    "TaxFilingCreate",\n    "TaxFilingUpdate",\n    "TaxFilingResponse",\n    "TaxFilingLineCreate",\n    "TaxFilingLineResponse",\n    "TaxNexusRuleCreate",\n    "TaxNexusRuleUpdate",\n    "TaxNexusRuleResponse",\n    "ExchangeRateCreate",\n    "ExchangeRateUpdate",\n    "ExchangeRateResponse",\n    "TaxCalculationRequest",\n    "TaxCalculationResponse",\n    "TaxCalculationLine",\n    "TaxSummaryResponse",\n    "TaxLiabilityReportResponse",\n    "TaxRateFilterParams",\n    "TaxCodeFilterParams",\n    "TaxTransactionFilterParams",\n    "TaxFilingFilterParams",\n    "TaxNexusRuleFilterParams",\n    "ExchangeRateFilterParams",\n    "TaxRateListResponse",\n    "TaxCodeListResponse",\n    "TaxTransactionListResponse",\n    "TaxFilingListResponse",\n    "TaxNexusRuleListResponse",\n    "ExchangeRateListResponse",\n    "TaxStatisticsResponse",\n    \n    # Workflow\n    "WorkflowStatus",\n    "TriggerType",\n    "ActionType",\n    "ConditionOperator",\n    "WorkflowCreate",\n    "WorkflowUpdate",\n    "WorkflowResponse",\n    "WorkflowTriggerCreate",\n    "WorkflowTriggerResponse",\n    "WorkflowActionCreate",\n    "WorkflowActionResponse",\n    "WorkflowExecutionCreate",\n    "WorkflowExecutionUpdate",\n    "WorkflowExecutionResponse",\n    "ExecutionLogCreate",\n    "ExecutionLogResponse",\n    "AutomationRuleCreate",\n    "AutomationRuleUpdate",\n    "AutomationRuleResponse",\n    "NotificationCreate",\n    "NotificationUpdate",\n    "NotificationResponse",\n    "ApprovalWorkflowCreate",\n    "ApprovalWorkflowUpdate",\n    "ApprovalWorkflowResponse",\n    "ApprovalStepCreate",\n    "ApprovalStepResponse",\n    "ApprovalInstanceCreate",\n    "ApprovalInstanceUpdate",\n    "ApprovalInstanceResponse",\n    "WorkflowStatisticsResponse",\n    "WorkflowFilterParams",\n    "WorkflowExecutionFilterParams",\n    "AutomationRuleFilterParams",\n    "NotificationFilterParams",\n    "ApprovalWorkflowFilterParams",\n    "ApprovalInstanceFilterParams",\n    "WorkflowListResponse",\n    "WorkflowExecutionListResponse",\n    "AutomationRuleListResponse",\n    "NotificationListResponse",\n    "ApprovalWorkflowListResponse",\n    "ApprovalInstanceListResponse",\n    \n    # Legal\n    "LegalEntityType",\n    "ContractType",\n    "ContractStatus",\n    "MatterType",\n    "MatterStatus",\n    "MatterPriority",\n    "IPType",\n    "IPStatus",\n    "LegalEntityCreate",\n    "LegalEntityUpdate",\n    "LegalEntityResponse",\n    "ContractPartyCreate",\n    "ContractPartyResponse",\n    "ContractMilestoneCreate",\n    "ContractMilestoneResponse",\n    "ContractCreate",\n    "ContractUpdate",\n    "ContractResponse",\n    "DocumentCreate",\n    "DocumentUpdate",\n    "DocumentResponse",\n    "DocumentVersionCreate",\n    "DocumentVersionResponse",\n    "LegalMatterPartyCreate",\n    "LegalMatterPartyResponse",\n    "LegalMilestoneCreate",\n    "LegalMilestoneResponse",\n    "LegalMatterCreate",\n    "LegalMatterUpdate",\n    "LegalMatterResponse",\n    "IntellectualPropertyCreate",\n    "IntellectualPropertyUpdate",\n    "IntellectualPropertyResponse",\n    "ContractAnalysisRequest",\n    "ContractAnalysisResponse",\n    "ContractRisk",\n    "KeyTerm",\n    "LegalDashboardResponse",\n    "LegalEntityFilterParams",\n    "ContractFilterParams",\n    "DocumentFilterParams",\n    "LegalMatterFilterParams",\n    "IPFilterParams",\n    "LegalEntityListResponse",\n    "ContractListResponse",\n    "DocumentListResponse",\n    "LegalMatterListResponse",\n    "IPListResponse",\n    \n    # Reports\n    "ReportType",\n    "ReportStatus",\n    "ExportFormat",\n    "ScheduleFrequency",\n    "DashboardWidgetType",\n    "AggregationType",\n    "DateRangeType",\n    "ChartOrientation",\n    "LegendPosition",\n    "ReportParameterCreate",\n    "ReportParameterResponse",\n    "ReportTemplateColumnCreate",\n    "ReportTemplateColumnResponse",\n    "ReportTemplateCreate",\n    "ReportTemplateUpdate",\n    "ReportTemplateResponse",\n    "DateRange",\n    "ComparisonPeriod",\n    "ReportExecutionParameters",\n    "ReportInstanceCreate",\n    "ReportInstanceUpdate",\n    "ReportInstanceResponse",\n    "ReportDataColumn",\n    "ReportDataRow",\n    "ReportSummary",\n    "ReportScheduleCreate",\n    "ReportScheduleUpdate",\n    "ReportScheduleResponse",\n    "DashboardWidgetConfigCreate",\n    "DashboardWidgetConfigResponse",\n    "DashboardWidgetPosition",\n    "DashboardWidgetCreate",\n    "DashboardWidgetUpdate",\n    "DashboardWidgetResponse",\n    "DashboardCreate",\n    "DashboardUpdate",\n    "DashboardResponse",\n    "KPICalculationType",\n    "KPIDirection",\n    "KPIDefinitionCreate",\n    "KPIDefinitionUpdate",\n    "KPIDefinitionResponse",\n    "KPIValue",\n    "ReportTemplateFilterParams",\n    "ReportInstanceFilterParams",\n    "ReportScheduleFilterParams",\n    "DashboardFilterParams",\n    "KPIDefinitionFilterParams",\n    "ReportTemplateListResponse",\n    "ReportInstanceListResponse",\n    "ReportScheduleListResponse",\n    "DashboardListResponse",\n    "KPIDefinitionListResponse",\n    "ReportBulkDelete",\n    "DashboardDuplicate",\n    "ReportTemplateDuplicate",\n    "ReportStatisticsResponse",\n    "DashboardStatisticsResponse",\n    \n    # Consolidation\n    "ConsolidationStatus",\n    "ConsolidationType",\n    "EliminationType",\n    "MatchingStatus",\n    "ConsolidationScope",\n    "CurrencyTranslationMethod",\n    "AdjustmentType",\n    "DataSource",\n    "ConsolidationPeriodCreate",\n    "ConsolidationPeriodUpdate",\n    "ConsolidationPeriodResponse",\n    "SubsidiaryConsolidationCreate",\n    "SubsidiaryConsolidationUpdate",\n    "SubsidiaryConsolidationResponse",\n    "IntercompanyTransactionCreate",\n    "IntercompanyTransactionUpdate",\n    "IntercompanyTransactionResponse",\n    "IntercompanyMatchLineCreate",\n    "IntercompanyMatchLineResponse",\n    "IntercompanyMatchCreate",\n    "IntercompanyMatchUpdate",\n    "IntercompanyMatchResponse",\n    "EliminationLineCreate",\n    "EliminationLineResponse",\n    "EliminationEntryCreate",\n    "EliminationEntryUpdate",\n    "EliminationEntryResponse",\n    "ConsolidationAdjustmentCreate",\n    "ConsolidationAdjustmentUpdate",\n    "ConsolidationAdjustmentResponse",\n    "WorksheetLineResponse",\n    "ConsolidationWorksheetCreate",\n    "ConsolidationWorksheetUpdate",\n    "ConsolidationWorksheetResponse",\n    "ConsolidationRunCreate",\n    "ConsolidationRunUpdate",\n    "ConsolidationRunResponse",\n    "ExchangeRateHistoryCreate",\n    "ExchangeRateHistoryResponse",\n    "CurrencyTranslationResult",\n    "MinorityInterestCreate",\n    "MinorityInterestResponse",\n    "ConsolidationPeriodFilterParams",\n    "IntercompanyTransactionFilterParams",\n    "EliminationEntryFilterParams",\n    "ConsolidationWorksheetFilterParams",\n    "ConsolidationRunFilterParams",\n    "ConsolidationPeriodListResponse",\n    "SubsidiaryConsolidationListResponse",\n    "IntercompanyTransactionListResponse",\n    "IntercompanyMatchListResponse",\n    "EliminationEntryListResponse",\n    "ConsolidationAdjustmentListResponse",\n    "ConsolidationWorksheetListResponse",\n    "ConsolidationRunListResponse",\n    "MinorityInterestListResponse",\n    "ConsolidationStatisticsResponse",\n    "IntercompanyBalanceSummary",\n    "ConsolidationValidationResult",\n    \n    # Asset\n    "AssetStatus",\n    "AssetCategory",\n    "DepreciationMethod",\n    "AssetValuationMethod",\n    "DisposalMethod",\n    "ImpairmentStatus",\n    "MaintenanceType",\n    "MaintenanceStatus",\n    "InsuranceStatus",\n    "AssetClassCreate",\n    "AssetClassUpdate",\n    "AssetClassResponse",\n    "AssetLocationCreate",\n    "AssetLocationUpdate",\n    "AssetLocationResponse",\n    "FixedAssetCreate",\n    "FixedAssetUpdate",\n    "FixedAssetResponse",\n    "DepreciationScheduleLineResponse",\n    "DepreciationScheduleResponse",\n    "DepreciationRunLineResponse",\n    "DepreciationRunCreate",\n    "DepreciationRunUpdate",\n    "DepreciationRunResponse",\n    "AssetTransferCreate",\n    "AssetTransferUpdate",\n    "AssetTransferResponse",\n    "AssetDisposalLineCreate",\n    "AssetDisposalLineResponse",\n    "AssetDisposalCreate",\n    "AssetDisposalUpdate",\n    "AssetDisposalResponse",\n    "AssetRevaluationCreate",\n    "AssetRevaluationUpdate",\n    "AssetRevaluationResponse",\n    "AssetImpairmentCreate",\n    "AssetImpairmentUpdate",\n    "AssetImpairmentResponse",\n    "AssetMaintenanceCreate",\n    "AssetMaintenanceUpdate",\n    "AssetMaintenanceResponse",\n    "AssetInsuranceCreate",\n    "AssetInsuranceUpdate",\n    "AssetInsuranceResponse",\n    "AssetClassFilterParams",\n    "AssetLocationFilterParams",\n    "FixedAssetFilterParams",\n    "DepreciationRunFilterParams",\n    "AssetTransferFilterParams",\n    "AssetDisposalFilterParams",\n    "AssetMaintenanceFilterParams",\n    "AssetInsuranceFilterParams",\n    "AssetClassListResponse",\n    "AssetLocationListResponse",\n    "FixedAssetListResponse",\n    "DepreciationScheduleListResponse",\n    "DepreciationRunListResponse",\n    "AssetTransferListResponse",\n    "AssetDisposalListResponse",\n    "AssetRevaluationListResponse",\n    "AssetImpairmentListResponse",\n    "AssetMaintenanceListResponse",\n    "AssetInsuranceListResponse",\n    "AssetStatisticsResponse",\n    "DepreciationForecastResponse",\n    "AssetRollforwardResponse",\n    \n    # AI\n    "AIModelType",\n    "ModelStatus",\n    "AnomalyType",\n    "AnomalySeverity",\n    "ForecastType",\n    "ForecastHorizon",\n    "AlertType",\n    "AlertSeverity",\n    "InsightType",\n    "RecommendationType",\n    "RecommendationPriority",\n    "AnalysisType",\n    "AIModelConfigCreate",\n    "AIModelConfigUpdate",\n    "AIModelConfigResponse",\n    "ModelMetrics",\n    "FeatureImportance",\n    "AnomalyDetectionConfigCreate",\n    "AnomalyDetectionConfigUpdate",\n    "AnomalyDetectionConfigResponse",\n    "DetectedAnomalyCreate",\n    "DetectedAnomalyUpdate",\n    "DetectedAnomalyResponse",\n    "ForecastConfigCreate",\n    "ForecastConfigUpdate",\n    "ForecastConfigResponse",\n    "ForecastPoint",\n    "ForecastRunCreate",\n    "ForecastRunUpdate",\n    "ForecastRunResponse",\n    "AIInsightCreate",\n    "AIInsightUpdate",\n    "AIInsightResponse",\n    "RecommendationCreate",\n    "RecommendationUpdate",\n    "RecommendationResponse",\n    "AIAlertCreate",\n    "AIAlertUpdate",\n    "AIAlertResponse",\n    "DocumentAnalysisRequestCreate",\n    "ExtractedTerm",\n    "DocumentRisk",\n    "ComplianceIssue",\n    "DocumentAnalysisResult",\n    "DocumentAnalysisRequestResponse",\n    "NLCommandRequestCreate",\n    "NLCommandAction",\n    "NLCommandRequestResponse",\n    "AIExplanationCreate",\n    "AIExplanationResponse",\n    "AIModelConfigFilterParams",\n    "DetectedAnomalyFilterParams",\n    "ForecastConfigFilterParams",\n    "ForecastRunFilterParams",\n    "AIInsightFilterParams",\n    "RecommendationFilterParams",\n    "AIAlertFilterParams",\n    "DocumentAnalysisFilterParams",\n    "AIModelConfigListResponse",\n    "AnomalyDetectionConfigListResponse",\n    "DetectedAnomalyListResponse",\n    "ForecastConfigListResponse",\n    "ForecastRunListResponse",\n    "AIInsightListResponse",\n    "RecommendationListResponse",\n    "AIAlertListResponse",\n    "DocumentAnalysisListResponse",\n    "NLCommandListResponse",\n    "AIExplanationListResponse",\n    "AIStatisticsResponse",\n    "AIModelPerformanceHistory",\n    "AIModelComparisonResponse",\n]\n</create-file>\n</function_calls>'}
{'role': 'user', 'content': '<tool_result> <create-file> ToolResult(success=True, output="File \'backend/app/schemas/__init__.py\' created successfully.") </create-file> </tool_result>'}
{'role': 'assistant', 'content': 'Now let me update the todo.md to reflect the completed schemas phase and move on to the next phase - creating the repository layer for data access:\n\n<function_calls>\n<str-replace file_path="todo.md">\n<old_str>## Phase 1.5: Backend Schemas (Pydantic)\n- [x] Base schemas\n- [x] Company schemas\n- [x] User schemas\n- [x] Accounting schemas\n- [x] Treasury schemas\n- [x] Invoice schemas\n- [x] HR schemas\n- [x] Tax schemas\n- [x] Workflow schemas\n- [x] Legal schemas\n- [x] Reports schemas\n- [x] Consolidation schemas\n- [x] Asset schemas\n- [ ] AI schemas\n- [ ] Schemas __init__.py</old_str>\n<new_str>## Phase 1.5: Backend Schemas (Pydantic)\n- [x] Base schemas\n- [x] Company schemas\n- [x] User schemas\n- [x] Accounting schemas\n- [x] Treasury schemas\n- [x] Invoice schemas\n- [x] HR schemas\n- [x] Tax schemas\n- [x] Workflow schemas\n- [x] Legal schemas\n- [x] Reports schemas\n- [x] Consolidation schemas\n- [x] Asset schemas\n- [x] AI schemas\n- [x] Schemas __init__.py\n\n## Phase 1.6: Backend Repositories (Data Access Layer)\n- [ ] Base repository\n- [ ] Company repository\n- [ ] User repository\n- [ ] Account repository\n- [ ] Journal entry repository\n- [ ] Treasury repository\n- [ ] Invoice repository\n- [ ] HR repository\n- [ ] Tax repository\n- [ ] Workflow repository\n- [ ] Legal repository\n- [ ] Reports repository\n- [ ] Consolidation repository\n- [ ] Asset repository\n- [ ] AI repository\n- [ ] Repositories __init__.py</new_str>\n</str-replace>\n</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 base repository with common CRUD operations:\n\n<function_calls>\n<execute-command>\nmkdir -p backend/app/repositories\n</execute-command>\n</function_calls>'}
{'role': 'user', 'content': '<tool_result> <execute-command> ToolResult(success=True, output=\'{\\n  "output": "",\\n  "exit_code": 0,\\n  "cwd": "/workspace"\\n}\') </execute-command> </tool_result>'}
{'role': 'assistant', 'content': '<function_calls>\n<create-file file_path="backend/app/repositories/base.py">\n"""\nSAMMS Enterprise - Base Repository\nGeneric repository with common CRUD operations\n"""\n\nfrom typing import TypeVar, Generic, Type, Optional, List, Dict, Any, Union\nfrom datetime import datetime\nfrom decimal import Decimal\nimport uuid\nfrom sqlalchemy import select, update, delete, func, or_, and_\nfrom sqlalchemy.ext.asyncio import AsyncSession\nfrom sqlalchemy.orm import selectinload, joinedload\nfrom pydantic import BaseModel\n\nfrom ..models.base import Base\nfrom ..schemas.base import PaginationParams, ListResponseBase\n\nModelType = TypeVar("ModelType", bound=Base)\nCreateSchemaType = TypeVar("CreateSchemaType", bound=BaseModel)\nUpdateSchemaType = TypeVar("UpdateSchemaType", bound=BaseModel)\nResponseSchemaType = TypeVar("ResponseSchemaType", bound=BaseModel)\nFilterParamsType = TypeVar("FilterParamsType", bound=PaginationParams)\n\n\nclass BaseRepository(Generic[ModelType, CreateSchemaType, UpdateSchemaType]):\n    """\n    Base repository providing generic CRUD operations.\n    \n    All repositories should inherit from this class and can override\n    methods for custom behavior or add new methods for specific needs.\n    """\n    \n    def __init__(self, model: Type[ModelType], session: AsyncSession):\n        """\n        Initialize repository with model class and database session.\n        \n        Args:\n            model: SQLAlchemy model class\n            session: Async database session\n        """\n        self.model = model\n        self.session = session\n    \n    async def create(self, data: CreateSchemaType, created_by_id: Optional[int] = None) -> ModelType:\n        """\n        Create a new record.\n        \n        Args:\n            data: Create schema with record data\n            created_by_id: ID of user creating the record\n            \n        Returns:\n            Created model instance\n        """\n        db_obj = self.model(**data.model_dump(exclude_unset=True))\n        \n        if created_by_id and hasattr(db_obj, \'created_by_id\'):\n            db_obj.created_by_id = created_by_id\n        \n        self.session.add(db_obj)\n        await self.session.flush()\n        await self.session.refresh(db_obj)\n        \n        return db_obj\n    \n    async def get_by_id(\n        self, \n        id: int, \n        load_relationships: Optional[List[str]] = None\n    ) -> Optional[ModelType]:\n        """\n        Get a record by ID.\n        \n        Args:\n            id: Record ID\n            load_relationships: List of relationship names to eager load\n            \n        Returns:\n            Model instance or None if not found\n        """\n        query = select(self.model).where(self.model.id == id)\n        \n        if load_relationships:\n            for rel in load_relationships:\n                query = query.options(selectinload(getattr(self.model, rel)))\n        \n        result = await self.session.execute(query)\n        return result.scalar_one_or_none()\n    \n    async def get_by_ids(\n        self, \n        ids: List[int], \n        load_relationships: Optional[List[str]] = None\n    ) -> List[ModelType]:\n        """\n        Get multiple records by IDs.\n        \n        Args:\n            ids: List of record IDs\n            load_relationships: List of relationship names to eager load\n            \n        Returns:\n            List of model instances\n        """\n        if not ids:\n            return []\n        \n        query = select(self.model).where(self.model.id.in_(ids))\n        \n        if load_relationships:\n            for rel in load_relationships:\n                query = query.options(selectinload(getattr(self.model, rel)))\n        \n        result = await self.session.execute(query)\n        return result.scalars().all()\n    \n    async def update(\n        self, \n        id: int, \n        data: UpdateSchemaType, \n        updated_by_id: Optional[int] = None\n    ) -> Optional[ModelType]:\n        """\n        Update a record.\n        \n        Args:\n            id: Record ID\n            data: Update schema with updated fields\n            updated_by_id: ID of user updating the record\n            \n        Returns:\n            Updated model instance or None if not found\n        """\n        db_obj = await self.get_by_id(id)\n        \n        if not db_obj:\n            return None\n        \n        update_data = data.model_dump(exclude_unset=True)\n        \n        for field, value in update_data.items():\n            setattr(db_obj, field, value)\n        \n        if updated_by_id and hasattr(db_obj, \'updated_by_id\'):\n            db_obj.updated_by_id = updated_by_id\n        \n        if hasattr(db_obj, \'updated_at\'):\n            db_obj.updated_at = datetime.utcnow()\n        \n        await self.session.flush()\n        await self.session.refresh(db_obj)\n        \n        return db_obj\n    \n    async def delete(self, id: int, deleted_by_id: Optional[int] = None) -> bool:\n        """\n        Delete a record (soft delete if model supports it).\n        \n        Args:\n            id: Record ID\n            deleted_by_id: ID of user deleting the record\n            \n        Returns:\n            True if deleted, False if not found\n        """\n        db_obj = await self.get_by_id(id)\n        \n        if not db_obj:\n            return False\n        \n        # Check if model supports soft delete\n        if hasattr(db_obj, \'is_deleted\'):\n            db_obj.is_deleted = True\n            db_obj.deleted_at = datetime.utcnow()\n            if deleted_by_id and hasattr(db_obj, \'deleted_by_id\'):\n                db_obj.deleted_by_id = deleted_by_id\n        else:\n            # Hard delete\n            await self.session.delete(db_obj)\n        \n        await self.session.flush()\n        return True\n    \n    async def restore(self, id: int) -> Optional[ModelType]:\n        """\n        Restore a soft-deleted record.\n        \n        Args:\n            id: Record ID\n            \n        Returns:\n            Restored model instance or None if not found\n        """\n        db_obj = await self.get_by_id(id)\n        \n        if not db_obj or not hasattr(db_obj, \'is_deleted\'):\n            return None\n        \n        db_obj.is_deleted = False\n        db_obj.deleted_at = None\n        if hasattr(db_obj, \'deleted_by_id\'):\n            db_obj.deleted_by_id = None\n        \n        await self.session.flush()\n        await self.session.refresh(db_obj)\n        \n        return db_obj\n    \n    async def hard_delete(self, id: int) -> bool:\n        """\n        Permanently delete a record.\n        \n        Args:\n            id: Record ID\n            \n        Returns:\n            True if deleted, False if not found\n        """\n        db_obj = await self.get_by_id(id)\n        \n        if not db_obj:\n            return False\n        \n        await self.session.delete(db_obj)\n        await self.session.flush()\n        return True\n    \n    async def list_all(\n        self,\n        skip: int = 0,\n        limit: int = 100,\n        load_relationships: Optional[List[str]] = None,\n        order_by: Optional[str] = None,\n        ascending: bool = True\n    ) -> List[ModelType]:\n        """\n        List all records with pagination.\n        \n        Args:\n            skip: Number of records to skip\n            limit: Maximum number of records to return\n            load_relationships: List of relationship names to eager load\n            order_by: Column name to order by\n            ascending: Sort ascending if True, descending if False\n            \n        Returns:\n            List of model instances\n        """\n        query = select(self.model)\n        \n        # Filter out soft-deleted records\n        if hasattr(self.model, \'is_deleted\'):\n            query = query.where(self.model.is_deleted == False)\n        \n        # Eager load relationships\n        if load_relationships:\n            for rel in load_relationships:\n                query = query.options(selectinload(getattr(self.model, rel)))\n        \n        # Apply ordering\n        if order_by and hasattr(self.model, order_by):\n            column = getattr(self.model, order_by)\n            query = query.order_by(column.asc() if ascending else column.desc())\n        elif hasattr(self.model, \'created_at\'):\n            query = query.order_by(self.model.created_at.desc())\n        \n        query = query.offset(skip).limit(limit)\n        \n        result = await self.session.execute(query)\n        return result.scalars().all()\n    \n    async def count(self) -> int:\n        """\n        Count total records (excluding soft-deleted).\n        \n        Returns:\n            Total record count\n        """\n        query = select(func.count()).select_from(self.model)\n        \n        if hasattr(self.model, \'is_deleted\'):\n            query = query.where(self.model.is_deleted == False)\n        \n        result = await self.session.execute(query)\n        return result.scalar() or 0\n    \n    async def exists(self, id: int) -> bool:\n        """\n        Check if a record exists.\n        \n        Args:\n            id: Record ID\n            \n        Returns:\n            True if exists, False otherwise\n        """\n        query = select(func.count()).select_from(self.model).where(self.model.id == id)\n        \n        if hasattr(self.model, \'is_deleted\'):\n            query = query.where(self.model.is_deleted == False)\n        \n        result = await self.session.execute(query)\n        return (result.scalar() or 0) > 0\n    \n    async def get_by_field(\n        self, \n        field: str, \n        value: Any,\n        load_relationships: Optional[List[str]] = None\n    ) -> Optional[ModelType]:\n        """\n        Get a record by a specific field value.\n        \n        Args:\n            field: Field name\n            value: Field value\n            load_relationships: List of relationship names to eager load\n            \n        Returns:\n            Model instance or None if not found\n        """\n        if not hasattr(self.model, field):\n            raise ValueError(f"Model {self.model.__name__} has no field \'{field}\'")\n        \n        query = select(self.model).where(getattr(self.model, field) == value)\n        \n        if hasattr(self.model, \'is_deleted\'):\n            query = query.where(self.model.is_deleted == False)\n        \n        if load_relationships:\n            for rel in load_relationships:\n                query = query.options(selectinload(getattr(self.model, rel)))\n        \n        result = await self.session.execute(query)\n        return result.scalar_one_or_none()\n    \n    async def list_by_field(\n        self,\n        field: str,\n        value: Any,\n        skip: int = 0,\n        limit: int = 100,\n        load_relationships: Optional[List[str]] = None\n    ) -> List[ModelType]:\n        """\n        List records by a specific field value.\n        \n        Args:\n            field: Field name\n            value: Field value\n            skip: Number of records to skip\n            limit: Maximum number of records to return\n            load_relationships: List of relationship names to eager load\n            \n        Returns:\n            List of model instances\n        """\n        if not hasattr(self.model, field):\n            raise ValueError(f"Model {self.model.__name__} has no field \'{field}\'")\n        \n        query = select(self.model).where(getattr(self.model, field) == value)\n        \n        if hasattr(self.model, \'is_deleted\'):\n            query = query.where(self.model.is_deleted == False)\n        \n        if load_relationships:\n            for rel in load_relationships:\n                query = query.options(selectinload(getattr(self.model, rel)))\n        \n        query = query.offset(skip).limit(limit)\n        \n        result = await self.session.execute(query)\n        return result.scalars().all()\n    \n    async def search(\n        self,\n        search_term: str,\n        search_fields: List[str],\n        skip: int = 0,\n        limit: int = 100\n    ) -> List[ModelType]:\n        """\n        Search records by term in specified fields.\n        \n        Args:\n            search_term: Search term\n            search_fields: List of fields to search in\n            skip: Number of records to skip\n            limit: Maximum number of records to return\n            \n        Returns:\n            List of matching model instances\n        """\n        conditions = []\n        \n        for field in search_fields:\n            if hasattr(self.model, field):\n                conditions.append(\n                    getattr(self.model, field).ilike(f"%{search_term}%")\n                )\n        \n        if not conditions:\n            return []\n        \n        query = select(self.model).where(or_(*conditions))\n        \n        if hasattr(self.model, \'is_deleted\'):\n            query = query.where(self.model.is_deleted == False)\n        \n        query = query.offset(skip).limit(limit)\n        \n        result = await self.session.execute(query)\n        return result.scalars().all()\n    \n    async def bulk_create(\n        self, \n        data_list: List[CreateSchemaType], \n        created_by_id: Optional[int] = None\n    ) -> List[ModelType]:\n        """\n        Create multiple records at once.\n        \n        Args:\n            data_list: List of create schemas\n            created_by_id: ID of user creating the records\n            \n        Returns:\n            List of created model instances\n        """\n        db_objs = []\n        \n        for data in data_list:\n            db_obj = self.model(**data.model_dump(exclude_unset=True))\n            \n            if created_by_id and hasattr(db_obj, \'created_by_id\'):\n                db_obj.created_by_id = created_by_id\n            \n            db_objs.append(db_obj)\n        \n        self.session.add_all(db_objs)\n        await self.session.flush()\n        \n        for db_obj in db_objs:\n            await self.session.refresh(db_obj)\n        \n        return db_objs\n    \n    async def bulk_update(\n        self, \n        updates: List[Dict[str, Any]],\n        updated_by_id: Optional[int] = None\n    ) -> int:\n        """\n        Update multiple records at once.\n        \n        Args:\n            updates: List of dictionaries with \'id\' and update fields\n            updated_by_id: ID of user updating the records\n            \n        Returns:\n            Number of records updated\n        """\n        count = 0\n        \n        for update_data in updates:\n            if \'id\' not in update_data:\n                continue\n            \n            id = update_data.pop(\'id\')\n            db_obj = await self.get_by_id(id)\n            \n            if db_obj:\n                for field, value in update_data.items():\n                    if hasattr(db_obj, field):\n                        setattr(db_obj, field, value)\n                \n                if updated_by_id and hasattr(db_obj, \'updated_by_id\'):\n                    db_obj.updated_by_id = updated_by_id\n                \n                if hasattr(db_obj, \'updated_at\'):\n                    db_obj.updated_at = datetime.utcnow()\n                \n                count += 1\n        \n        await self.session.flush()\n        return count\n    \n    async def bulk_delete(\n        self, \n        ids: List[int], \n        deleted_by_id: Optional[int] = None\n    ) -> int:\n        """\n        Delete multiple records at once.\n        \n        Args:\n            ids: List of record IDs to delete\n            deleted_by_id: ID of user deleting the records\n            \n        Returns:\n            Number of records deleted\n        """\n        count = 0\n        \n        for id in ids:\n            if await self.delete(id, deleted_by_id):\n                count += 1\n        \n        return count\n    \n    async def get_or_create(\n        self,\n        defaults: Optional[Dict[str, Any]] = None,\n        **kwargs\n    ) -> tuple[ModelType, bool]:\n        """\n        Get a record or create it if it doesn\'t exist.\n        \n        Args:\n            defaults: Default values for creation\n            **kwargs: Field values to search/create with\n            \n        Returns:\n            Tuple of (model instance, created boolean)\n        """\n        conditions = []\n        \n        for field, value in kwargs.items():\n            if hasattr(self.model, field):\n                conditions.append(getattr(self.model, field) == value)\n        \n        if conditions:\n            query = select(self.model).where(and_(*conditions))\n            \n            if hasattr(self.model, \'is_deleted\'):\n                query = query.where(self.model.is_deleted == False)\n            \n            result = await self.session.execute(query)\n            existing = result.scalar_one_or_none()\n            \n            if existing:\n                return existing, False\n        \n        # Create new record\n        create_data = dict(kwargs)\n        if defaults:\n            create_data.update(defaults)\n        \n        db_obj = self.model(**create_data)\n        self.session.add(db_obj)\n        await self.session.flush()\n        await self.session.refresh(db_obj)\n        \n        return db_obj, True\n    \n    async def update_or_create(\n        self,\n        defaults: Optional[Dict[str, Any]] = None,\n        **kwargs\n    ) -> tuple[ModelType, bool]:\n        """\n        Update a record or create it if it doesn\'t exist.\n        \n        Args:\n            defaults: Values to update/create with\n            **kwargs: Field values to search by\n            \n        Returns:\n            Tuple of (model instance, created boolean)\n        """\n        obj, created = await self.get_or_create(defaults=defaults, **kwargs)\n        \n        if not created and defaults:\n            for field, value in defaults.items():\n                if hasattr(obj, field):\n                    setattr(obj, field, value)\n            \n            if hasattr(obj, \'updated_at\'):\n                obj.updated_at = datetime.utcnow()\n            \n            await self.session.flush()\n            await self.session.refresh(obj)\n        \n        return obj, created\n    \n    async def paginate(\n        self,\n        query,\n        params: PaginationParams,\n        response_class: Type[ListResponseBase]\n    ) -> ListResponseBase:\n        """\n        Apply pagination to a query and return paginated response.\n        \n        Args:\n            query: SQLAlchemy select query\n            params: Pagination parameters\n            response_class: Response class to use\n            \n        Returns:\n            Paginated response\n        """\n        # Get total count\n        count_query = select(func.count()).select_from(query.subquery())\n        total_result = await self.session.execute(count_query)\n        total = total_result.scalar() or 0\n        \n        # Apply pagination\n        query = query.offset(params.skip).limit(params.limit)\n        \n        result = await self.session.execute(query)\n        items = result.scalars().all()\n        \n        return response_class(\n            items=items,\n            total=total,\n            page=params.page,\n            page_size=params.page_size,\n            total_pages=(total + params.page_size - 1) // params.page_size\n        )\n\n\nclass CompanyScopedRepository(\n    Generic[ModelType, CreateSchemaType, UpdateSchemaType],\n    BaseRepository[ModelType, CreateSchemaType, UpdateSchemaType]\n):\n    """\n    Repository for company-scoped models.\n    \n    Automatically filters by company_id for all queries.\n    """\n    \n    async def list_by_company(\n        self,\n        company_id: int,\n        skip: int = 0,\n        limit: int = 100,\n        load_relationships: Optional[List[str]] = None,\n        order_by: Optional[str] = None,\n        ascending: bool = True\n    ) -> List[ModelType]:\n        """\n        List records for a specific company.\n        \n        Args:\n            company_id: Company ID\n            skip: Number of records to skip\n            limit: Maximum number of records to return\n            load_relationships: List of relationship names to eager load\n            order_by: Column name to order by\n            ascending: Sort ascending if True, descending if False\n            \n        Returns:\n            List of model instances\n        """\n        if not hasattr(self.model, \'company_id\'):\n            raise ValueError(f"Model {self.model.__name__} is not company-scoped")\n        \n        query = select(self.model).where(\n            self.model.company_id == company_id,\n            self.model.is_deleted == False if hasattr(self.model, \'is_deleted\') else True\n        )\n        \n        if load_relationships:\n            for rel in load_relationships:\n                query = query.options(selectinload(getattr(self.model, rel)))\n        \n        if order_by and hasattr(self.model, order_by):\n            column = getattr(self.model, order_by)\n            query = query.order_by(column.asc() if ascending else column.desc())\n        elif hasattr(self.model, \'created_at\'):\n            query = query.order_by(self.model.created_at.desc())\n        \n        query = query.offset(skip).limit(limit)\n        \n        result = await self.session.execute(query)\n        return result.scalars().all()\n    \n    async def count_by_company(self, company_id: int) -> int:\n        """\n        Count records for a specific company.\n        \n        Args:\n            company_id: Company ID\n            \n        Returns:\n            Record count\n        """\n        query = select(func.count()).select_from(self.model).where(\n            self.model.company_id == company_id\n        )\n        \n        if hasattr(self.model, \'is_deleted\'):\n            query = query.where(self.model.is_deleted == False)\n        \n        result = await self.session.execute(query)\n        return result.scalar() or 0\n    \n    async def get_by_id_and_company(\n        self,\n        id: int,\n        company_id: int,\n        load_relationships: Optional[List[str]] = None\n    ) -> Optional[ModelType]:\n        """\n        Get a record by ID, ensuring it belongs to the company.\n        \n        Args:\n            id: Record ID\n            company_id: Company ID\n            load_relationships: List of relationship names to eager load\n            \n        Returns:\n            Model instance or None if not found\n        """\n        query = select(self.model).where(\n            self.model.id == id,\n            self.model.company_id == company_id\n        )\n        \n        if hasattr(self.model, \'is_deleted\'):\n            query = query.where(self.model.is_deleted == False)\n        \n        if load_relationships:\n            for rel in load_relationships:\n                query = query.options(selectinload(getattr(self.model, rel)))\n        \n        result = await self.session.execute(query)\n        return result.scalar_one_or_none()\n</create-file>\n</function_calls>'}
{'role': 'user', 'content': '<tool_result> <create-file> ToolResult(success=True, output="File \'backend/app/repositories/base.py\' created successfully.") </create-file> </tool_result>'}
{'role': 'assistant', 'content': 'Now let me create the Company repository:\n\n<function_calls>\n<create-file file_path="backend/app/repositories/company.py">\n"""\nSAMMS Enterprise - Company Repository\nData access layer for company management\n"""\n\nfrom typing import Optional, List, Dict, Any\nfrom datetime import datetime\nfrom decimal import Decimal\nfrom sqlalchemy import select, update, delete, func, or_, and_\nfrom sqlalchemy.ext.asyncio import AsyncSession\nfrom sqlalchemy.orm import selectinload, joinedload\n\nfrom .base import BaseRepository, CompanyScopedRepository\nfrom ..models.company import Company, CompanyGroup, CompanySetting, CompanyDocument\nfrom ..schemas.company import (\n    CompanyCreate, CompanyUpdate,\n    CompanyGroupCreate, CompanyGroupUpdate,\n    CompanySettingCreate, CompanySettingUpdate,\n    CompanyDocumentCreate, CompanyDocumentUpdate,\n    CompanyFilterParams, CompanyGroupFilterParams,\n)\nfrom ..models.base import Base\n\n\nclass CompanyGroupRepository(BaseRepository[CompanyGroup, CompanyGroupCreate, CompanyGroupUpdate]):\n    """Repository for company group operations"""\n    \n    def __init__(self, session: AsyncSession):\n        super().__init__(CompanyGroup, session)\n    \n    async def get_by_code(self, code: str) -> Optional[CompanyGroup]:\n        """Get a company group by its code"""\n        return await self.get_by_field(\'code\', code)\n    \n    async def get_root_groups(self) -> List[CompanyGroup]:\n        """Get all root-level company groups (no parent)"""\n        query = select(CompanyGroup).where(\n            CompanyGroup.parent_id == None,\n            CompanyGroup.is_deleted == False\n        ).order_by(CompanyGroup.name)\n        \n        result = await self.session.execute(query)\n        return result.scalars().all()\n    \n    async def get_children(self, parent_id: int) -> List[CompanyGroup]:\n        """Get all child groups of a parent group"""\n        query = select(CompanyGroup).where(\n            CompanyGroup.parent_id == parent_id,\n            CompanyGroup.is_deleted == False\n        ).order_by(CompanyGroup.name)\n        \n        result = await self.session.execute(query)\n        return result.scalars().all()\n    \n    async def get_full_hierarchy(self, group_id: int) -> List[CompanyGroup]:\n        """Get the full hierarchy from root to the specified group"""\n        hierarchy = []\n        current = await self.get_by_id(group_id)\n        \n        while current:\n            hierarchy.insert(0, current)\n            if current.parent_id:\n                current = await self.get_by_id(current.parent_id)\n            else:\n                break\n        \n        return hierarchy\n    \n    async def get_all_descendants(self, group_id: int) -> List[int]:\n        """Get IDs of all descendant groups (recursive)"""\n        descendant_ids = [group_id]\n        \n        children = await self.get_children(group_id)\n        for child in children:\n            descendant_ids.extend(await self.get_all_descendants(child.id))\n        \n        return descendant_ids\n    \n    async def list_with_stats(self, skip: int = 0, limit: int = 100) -> List[Dict[str, Any]]:\n        """List company groups with company count statistics"""\n        query = select(\n            CompanyGroup,\n            func.count(Company.id).filter(Company.is_deleted == False).label(\'company_count\')\n        ).outerjoin(\n            Company, CompanyGroup.id == Company.group_id\n        ).where(\n            CompanyGroup.is_deleted == False\n        ).group_by(CompanyGroup.id).order_by(CompanyGroup.name)\n        \n        query = query.offset(skip).limit(limit)\n        \n        result = await self.session.execute(query)\n        return [\n            {\n                \'group\': row[0],\n                \'company_count\': row[1]\n            }\n            for row in result.all()\n        ]\n    \n    async def code_exists(self, code: str, exclude_id: Optional[int] = None) -> bool:\n        """Check if a group code already exists"""\n        query = select(func.count()).select_from(CompanyGroup).where(\n            CompanyGroup.code == code,\n            CompanyGroup.is_deleted == False\n        )\n        \n        if exclude_id:\n            query = query.where(CompanyGroup.id != exclude_id)\n        \n        result = await self.session.execute(query)\n        return (result.scalar() or 0) > 0\n\n\nclass CompanyRepository(BaseRepository[Company, CompanyCreate, CompanyUpdate]):\n    """Repository for company operations"""\n    \n    def __init__(self, session: AsyncSession):\n        super().__init__(Company, session)\n    \n    async def get_by_code(self, code: str) -> Optional[Company]:\n        """Get a company by its code"""\n        return await self.get_by_field(\'code\', code)\n    \n    async def get_by_registration_number(self, registration_number: str) -> Optional[Company]:\n        """Get a company by registration number"""\n        return await self.get_by_field(\'registration_number\', registration_number)\n    \n    async def get_by_tax_id(self, tax_id: str) -> Optional[Company]:\n        """Get a company by tax ID"""\n        return await self.get_by_field(\'tax_id\', tax_id)\n    \n    async def get_headquarters(self) -> List[Company]:\n        """Get all headquarters companies (no parent)"""\n        query = select(Company).where(\n            Company.parent_id == None,\n            Company.is_deleted == False\n        ).order_by(Company.name)\n        \n        result = await self.session.execute(query)\n        return result.scalars().all()\n    \n    async def get_subsidaries(self, parent_id: int) -> List[Company]:\n        """Get all subsidiary companies of a parent"""\n        query = select(Company).where(\n            Company.parent_id == parent_id,\n            Company.is_deleted == False\n        ).order_by(Company.name)\n        \n        result = await self.session.execute(query)\n        return result.scalars().all()\n    \n    async def get_all_descendants(self, company_id: int) -> List[int]:\n        """Get IDs of all descendant companies (recursive)"""\n        descendant_ids = [company_id]\n        \n        children = await self.get_subsidaries(company_id)\n        for child in children:\n            descendant_ids.extend(await self.get_all_descendants(child.id))\n        \n        return descendant_ids\n    \n    async def get_by_group(self, group_id: int, include_subgroups: bool = True) -> List[Company]:\n        """Get all companies in a group"""\n        if include_subgroups:\n            # Get all descendant group IDs\n            group_repo = CompanyGroupRepository(self.session)\n            group_ids = await group_repo.get_all_descendants(group_id)\n        else:\n            group_ids = [group_id]\n        \n        query = select(Company).where(\n            Company.group_id.in_(group_ids),\n            Company.is_deleted == False\n        ).order_by(Company.name)\n        \n        result = await self.session.execute(query)\n        return result.scalars().all()\n    \n    async def get_by_status(self, status: str) -> List[Company]:\n        """Get all companies with a specific status"""\n        query = select(Company).where(\n            Company.status == status,\n            Company.is_deleted == False\n        ).order_by(Company.name)\n        \n        result = await self.session.execute(query)\n        return result.scalars().all()\n    \n    async def get_by_type(self, company_type: str) -> List[Company]:\n        """Get all companies of a specific type"""\n        query = select(Company).where(\n            Company.company_type == company_type,\n            Company.is_deleted == False\n        ).order_by(Company.name)\n        \n        result = await self.session.execute(query)\n        return result.scalars().all()\n    \n    async def get_consolidation_tree(self, root_company_id: Optional[int] = None) -> List[Dict[str, Any]]:\n        """Get the company hierarchy for consolidation"""\n        async def build_tree(parent_id: Optional[int]) -> List[Dict[str, Any]]:\n            query = select(Company).where(\n                Company.parent_id == parent_id,\n                Company.is_deleted == False\n            ).order_by(Company.name)\n            \n            result = await self.session.execute(query)\n            companies = result.scalars().all()\n            \n            tree = []\n            for company in companies:\n                node = {\n                    \'id\': company.id,\n                    \'name\': company.name,\n                    \'code\': company.code,\n                    \'company_type\': company.company_type,\n                    \'ownership_percentage\': company.ownership_percentage,\n                    \'children\': await build_tree(company.id)\n                }\n                tree.append(node)\n            \n            return tree\n        \n        return await build_tree(root_company_id)\n    \n    async def search(\n        self,\n        params: CompanyFilterParams,\n        load_relationships: Optional[List[str]] = None\n    ) -> List[Company]:\n        """Search companies with filters"""\n        query = select(Company).where(Company.is_deleted == False)\n        \n        # Apply filters\n        if params.search:\n            search_term = f"%{params.search}%"\n            query = query.where(\n                or_(\n                    Company.name.ilike(search_term),\n                    Company.code.ilike(search_term),\n                    Company.legal_name.ilike(search_term)\n                )\n            )\n        \n        if params.company_type:\n            query = query.where(Company.company_type == params.company_type)\n        \n        if params.status:\n            query = query.where(Company.status == params.status)\n        \n        if params.group_id:\n            query = query.where(Company.group_id == params.group_id)\n        \n        if params.parent_id is not None:\n            query = query.where(Company.parent_id == params.parent_id)\n        \n        if params.country:\n            query = query.where(Company.country == params.country)\n        \n        if params.industry:\n            query = query.where(Company.industry_sector == params.industry)\n        \n        if params.is_active is not None:\n            query = query.where(Company.is_active == params.is_active)\n        \n        # Load relationships\n        if load_relationships:\n            for rel in load_relationships:\n                query = query.options(selectinload(getattr(Company, rel)))\n        \n        # Apply ordering\n        query = query.order_by(Company.name)\n        \n        # Apply pagination\n        query = query.offset(params.skip).limit(params.limit)\n        \n        result = await self.session.execute(query)\n        return result.scalars().all()\n    \n    async def count_with_filters(self, params: CompanyFilterParams) -> int:\n        """Count companies matching filters"""\n        query = select(func.count()).select_from(Company).where(Company.is_deleted == False)\n        \n        if params.search:\n            search_term = f"%{params.search}%"\n            query = query.where(\n                or_(\n                    Company.name.ilike(search_term),\n                    Company.code.ilike(search_term),\n                    Company.legal_name.ilike(search_term)\n                )\n            )\n        \n        if params.company_type:\n            query = query.where(Company.company_type == params.company_type)\n        \n        if params.status:\n            query = query.where(Company.status == params.status)\n        \n        if params.group_id:\n            query = query.where(Company.group_id == params.group_id)\n        \n        if params.country:\n            query = query.where(Company.country == params.country)\n        \n        if params.is_active is not None:\n            query = query.where(Company.is_active == params.is_active)\n        \n        result = await self.session.execute(query)\n        return result.scalar() or 0\n    \n    async def code_exists(self, code: str, exclude_id: Optional[int] = None) -> bool:\n        """Check if a company code already exists"""\n        query = select(func.count()).select_from(Company).where(\n            Company.code == code,\n            Company.is_deleted == False\n        )\n        \n        if exclude_id:\n            query = query.where(Company.id != exclude_id)\n        \n        result = await self.session.execute(query)\n        return (result.scalar() or 0) > 0\n    \n    async def get_statistics(self) -> Dict[str, Any]:\n        """Get company statistics"""\n        # Total companies\n        total_query = select(func.count()).select_from(Company).where(Company.is_deleted == False)\n        total = (await self.session.execute(total_query)).scalar() or 0\n        \n        # By type\n        type_query = select(\n            Company.company_type,\n            func.count().label(\'count\')\n        ).where(\n            Company.is_deleted == False\n        ).group_by(Company.company_type)\n        \n        type_result = await self.session.execute(type_query)\n        by_type = {row[0]: row[1] for row in type_result.all()}\n        \n        # By status\n        status_query = select(\n            Company.status,\n            func.count().label(\'count\')\n        ).where(\n            Company.is_deleted == False\n        ).group_by(Company.status)\n        \n        status_result = await self.session.execute(status_query)\n        by_status = {row[0]: row[1] for row in status_result.all()}\n        \n        # By country\n        country_query = select(\n            Company.country,\n            func.count().label(\'count\')\n        ).where(\n            Company.is_deleted == False,\n            Company.country != None\n        ).group_by(Company.country).order_by(func.count().desc()).limit(10)\n        \n        country_result = await self.session.execute(country_query)\n        by_country = {row[0]: row[1] for row in country_result.all()}\n        \n        return {\n            \'total_companies\': total,\n            \'by_type\': by_type,\n            \'by_status\': by_status,\n            \'by_country\': by_country\n        }\n\n\nclass CompanySettingRepository(CompanyScopedRepository[CompanySetting, CompanySettingCreate, CompanySettingUpdate]):\n    """Repository for company settings"""\n    \n    def __init__(self, session: AsyncSession):\n        super().__init__(CompanySetting, session)\n    \n    async def get_by_company(self, company_id: int) -> Optional[CompanySetting]:\n        """Get settings for a company"""\n        query = select(CompanySetting).where(\n            CompanySetting.company_id == company_id,\n            CompanySetting.is_deleted == False\n        )\n        \n        result = await self.session.execute(query)\n        return result.scalar_one_or_none()\n    \n    async def get_setting_value(\n        self, \n        company_id: int, \n        setting_key: str, \n        default: Any = None\n    ) -> Any:\n        """Get a specific setting value for a company"""\n        settings = await self.get_by_company(company_id)\n        \n        if settings and hasattr(settings, setting_key):\n            return getattr(settings, setting_key)\n        \n        return default\n    \n    async def update_setting(\n        self, \n        company_id: int, \n        setting_key: str, \n        value: Any\n    ) -> Optional[CompanySetting]:\n        """Update a specific setting for a company"""\n        settings = await self.get_by_company(company_id)\n        \n        if settings and hasattr(settings, setting_key):\n            setattr(settings, setting_key, value)\n            settings.updated_at = datetime.utcnow()\n            await self.session.flush()\n            await self.session.refresh(settings)\n            return settings\n        \n        return None\n\n\nclass CompanyDocumentRepository(CompanyScopedRepository[CompanyDocument, CompanyDocumentCreate, CompanyDocumentUpdate]):\n    """Repository for company documents"""\n    \n    def __init__(self, session: AsyncSession):\n        super().__init__(CompanyDocument, session)\n    \n    async def get_by_company(\n        self, \n        company_id: int,\n        document_type: Optional[str] = None,\n        skip: int = 0,\n        limit: int = 100\n    ) -> List[CompanyDocument]:\n        """Get documents for a company"""\n        query = select(CompanyDocument).where(\n            CompanyDocument.company_id == company_id,\n            CompanyDocument.is_deleted == False\n        )\n        \n        if document_type:\n            query = query.where(CompanyDocument.document_type == document_type)\n        \n        query = query.order_by(CompanyDocument.created_at.desc())\n        query = query.offset(skip).limit(limit)\n        \n        result = await self.session.execute(query)\n        return result.scalars().all()\n    \n    async def get_by_document_number(\n        self, \n        company_id: int, \n        document_number: str\n    ) -> Optional[CompanyDocument]:\n        """Get a document by its number"""\n        query = select(CompanyDocument).where(\n            CompanyDocument.company_id == company_id,\n            CompanyDocument.document_number == document_number,\n            CompanyDocument.is_deleted == False\n        )\n        \n        result = await self.session.execute(query)\n        return result.scalar_one_or_none()\n    \n    async def get_expiring_documents(\n        self, \n        company_id: int, \n        days_ahead: int = 30\n    ) -> List[CompanyDocument]:\n        """Get documents expiring within specified days"""\n        from datetime import timedelta\n        \n        expiry_date = datetime.utcnow().date() + timedelta(days=days_ahead)\n        \n        query = select(CompanyDocument).where(\n            CompanyDocument.company_id == company_id,\n            CompanyDocument.expiry_date != None,\n            CompanyDocument.expiry_date <= expiry_date,\n            CompanyDocument.expiry_date >= datetime.utcnow().date(),\n            CompanyDocument.is_deleted == False\n        ).order_by(CompanyDocument.expiry_date)\n        \n        result = await self.session.execute(query)\n        return result.scalars().all()\n</create-file>\n</function_calls>'}
{'role': 'user', 'content': '<tool_result> <create-file> ToolResult(success=True, output="File \'backend/app/repositories/company.py\' created successfully.") </create-file> </tool_result>'}
{'role': 'assistant', 'content': 'Now let me create the User repository:\n\n<function_calls>\n<create-file file_path="backend/app/repositories/user.py">\n"""\nSAMMS Enterprise - User Repository\nData access layer for user management and authentication\n"""\n\nfrom typing import Optional, List, Dict, Any\nfrom datetime import datetime, timedelta\nfrom decimal import Decimal\nfrom sqlalchemy import select, update, delete, func, or_, and_\nfrom sqlalchemy.ext.asyncio import AsyncSession\nfrom sqlalchemy.orm import selectinload, joinedload\nimport secrets\nimport hashlib\n\nfrom .base import BaseRepository, CompanyScopedRepository\nfrom ..models.user import User, Role, Permission, UserSession, UserActivityLog\nfrom ..schemas.user import (\n    UserCreate, UserUpdate,\n    RoleCreate, RoleUpdate,\n    PermissionCreate, PermissionUpdate,\n    UserFilterParams, RoleFilterParams, PermissionFilterParams,\n)\nfrom ..core.security import get_password_hash, verify_password\n\n\nclass PermissionRepository(BaseRepository[Permission, PermissionCreate, PermissionUpdate]):\n    """Repository for permission operations"""\n    \n    def __init__(self, session: AsyncSession):\n        super().__init__(Permission, session)\n    \n    async def get_by_code(self, code: str) -> Optional[Permission]:\n        """Get a permission by its code"""\n        return await self.get_by_field(\'code\', code)\n    \n    async def get_by_module(self, module: str) -> List[Permission]:\n        """Get all permissions for a module"""\n        query = select(Permission).where(\n            Permission.module == module,\n            Permission.is_deleted == False\n        ).order_by(Permission.name)\n        \n        result = await self.session.execute(query)\n        return result.scalars().all()\n    \n    async def get_by_category(self, category: str) -> List[Permission]:\n        """Get all permissions for a category"""\n        query = select(Permission).where(\n            Permission.category == category,\n            Permission.is_deleted == False\n        ).order_by(Permission.name)\n        \n        result = await self.session.execute(query)\n        return result.scalars().all()\n    \n    async def get_all_grouped(self) -> Dict[str, List[Permission]]:\n        """Get all permissions grouped by module"""\n        query = select(Permission).where(\n            Permission.is_deleted == False\n        ).order_by(Permission.module, Permission.name)\n        \n        result = await self.session.execute(query)\n        permissions = result.scalars().all()\n        \n        grouped = {}\n        for perm in permissions:\n            if perm.module not in grouped:\n                grouped[perm.module] = []\n            grouped[perm.module].append(perm)\n        \n        return grouped\n    \n    async def search(\n        self,\n        params: PermissionFilterParams\n    ) -> List[Permission]:\n        """Search permissions with filters"""\n        query = select(Permission).where(Permission.is_deleted == False)\n        \n        if params.search:\n            search_term = f"%{params.search}%"\n            query = query.where(\n                or_(\n                    Permission.name.ilike(search_term),\n                    Permission.code.ilike(search_term),\n                    Permission.description.ilike(search_term)\n                )\n            )\n        \n        if params.module:\n            query = query.where(Permission.module == params.module)\n        \n        if params.category:\n            query = query.where(Permission.category == params.category)\n        \n        if params.is_active is not None:\n            query = query.where(Permission.is_active == params.is_active)\n        \n        query = query.order_by(Permission.module, Permission.name)\n        query = query.offset(params.skip).limit(params.limit)\n        \n        result = await self.session.execute(query)\n        return result.scalars().all()\n    \n    async def code_exists(self, code: str, exclude_id: Optional[int] = None) -> bool:\n        """Check if a permission code already exists"""\n        query = select(func.count()).select_from(Permission).where(\n            Permission.code == code,\n            Permission.is_deleted == False\n        )\n        \n        if exclude_id:\n            query = query.where(Permission.id != exclude_id)\n        \n        result = await self.session.execute(query)\n        return (result.scalar() or 0) > 0\n\n\nclass RoleRepository(BaseRepository[Role, RoleCreate, RoleUpdate]):\n    """Repository for role operations"""\n    \n    def __init__(self, session: AsyncSession):\n        super().__init__(Role, session)\n    \n    async def get_by_code(self, code: str) -> Optional[Role]:\n        """Get a role by its code"""\n        return await self.get_by_field(\'code\', code)\n    \n    async def get_with_permissions(self, role_id: int) -> Optional[Role]:\n        """Get a role with its permissions loaded"""\n        query = select(Role).where(\n            Role.id == role_id,\n            Role.is_deleted == False\n        ).options(selectinload(Role.permissions))\n        \n        result = await self.session.execute(query)\n        return result.scalar_one_or_none()\n    \n    async def get_by_company(\n        self, \n        company_id: int,\n        include_global: bool = True\n    ) -> List[Role]:\n        """Get roles for a company"""\n        conditions = [Role.is_deleted == False]\n        \n        if include_global:\n            conditions.append(\n                or_(\n                    Role.company_id == company_id,\n                    Role.is_global == True\n                )\n            )\n        else:\n            conditions.append(Role.company_id == company_id)\n        \n        query = select(Role).where(*conditions).order_by(Role.name)\n        \n        result = await self.session.execute(query)\n        return result.scalars().all()\n    \n    async def get_system_roles(self) -> List[Role]:\n        """Get all system-defined roles"""\n        query = select(Role).where(\n            Role.is_system == True,\n            Role.is_deleted == False\n        ).order_by(Role.name)\n        \n        result = await self.session.execute(query)\n        return result.scalars().all()\n    \n    async def assign_permissions(\n        self, \n        role_id: int, \n        permission_ids: List[int]\n    ) -> Optional[Role]:\n        """Assign permissions to a role"""\n        role = await self.get_with_permissions(role_id)\n        \n        if not role:\n            return None\n        \n        # Get permission objects\n        perm_query = select(Permission).where(Permission.id.in_(permission_ids))\n        perm_result = await self.session.execute(perm_query)\n        permissions = perm_result.scalars().all()\n        \n        role.permissions = list(permissions)\n        role.updated_at = datetime.utcnow()\n        \n        await self.session.flush()\n        await self.session.refresh(role)\n        \n        return role\n    \n    async def remove_permissions(\n        self, \n        role_id: int, \n        permission_ids: List[int]\n    ) -> Optional[Role]:\n        """Remove permissions from a role"""\n        role = await self.get_with_permissions(role_id)\n        \n        if not role:\n            return None\n        \n        role.permissions = [\n            p for p in role.permissions if p.id not in permission_ids\n        ]\n        role.updated_at = datetime.utcnow()\n        \n        await self.session.flush()\n        await self.session.refresh(role)\n        \n        return role\n    \n    async def search(\n        self,\n        params: RoleFilterParams,\n        company_id: Optional[int] = None\n    ) -> List[Role]:\n        """Search roles with filters"""\n        query = select(Role).where(Role.is_deleted == False)\n        \n        if params.search:\n            search_term = f"%{params.search}%"\n            query = query.where(\n                or_(\n                    Role.name.ilike(search_term),\n                    Role.code.ilike(search_term),\n                    Role.description.ilike(search_term)\n                )\n            )\n        \n        if params.is_active is not None:\n            query = query.where(Role.is_active == params.is_active)\n        \n        if params.is_system is not None:\n            query = query.where(Role.is_system == params.is_system)\n        \n        if company_id:\n            query = query.where(\n                or_(\n                    Role.company_id == company_id,\n                    Role.is_global == True\n                )\n            )\n        \n        query = query.order_by(Role.name)\n        query = query.offset(params.skip).limit(params.limit)\n        \n        result = await self.session.execute(query)\n        return result.scalars().all()\n    \n    async def code_exists(self, code: str, company_id: Optional[int] = None, exclude_id: Optional[int] = None) -> bool:\n        """Check if a role code already exists"""\n        query = select(func.count()).select_from(Role).where(\n            Role.code == code,\n            Role.is_deleted == False\n        )\n        \n        if company_id:\n            query = query.where(Role.company_id == company_id)\n        \n        if exclude_id:\n            query = query.where(Role.id != exclude_id)\n        \n        result = await self.session.execute(query)\n        return (result.scalar() or 0) > 0\n\n\nclass UserRepository(BaseRepository[User, UserCreate, UserUpdate]):\n    """Repository for user operations"""\n    \n    def __init__(self, session: AsyncSession):\n        super().__init__(User, session)\n    \n    async def get_by_username(self, username: str) -> Optional[User]:\n        """Get a user by username"""\n        return await self.get_by_field(\'username\', username)\n    \n    async def get_by_email(self, email: str) -> Optional[User]:\n        """Get a user by email"""\n        return await self.get_by_field(\'email\', email)\n    \n    async def get_by_employee_id(self, employee_id: int) -> Optional[User]:\n        """Get a user by employee ID"""\n        return await self.get_by_field(\'employee_id\', employee_id)\n    \n    async def get_with_roles(self, user_id: int) -> Optional[User]:\n        """Get a user with roles loaded"""\n        query = select(User).where(\n            User.id == user_id,\n            User.is_deleted == False\n        ).options(\n            selectinload(User.roles).selectinload(Role.permissions)\n        )\n        \n        result = await self.session.execute(query)\n        return result.scalar_one_or_none()\n    \n    async def get_with_company(self, user_id: int) -> Optional[User]:\n        """Get a user with company loaded"""\n        query = select(User).where(\n            User.id == user_id,\n            User.is_deleted == False\n        ).options(\n            selectinload(User.company)\n        )\n        \n        result = await self.session.execute(query)\n        return result.scalar_one_or_none()\n    \n    async def get_by_company(\n        self, \n        company_id: int,\n        skip: int = 0,\n        limit: int = 100\n    ) -> List[User]:\n        """Get users for a company"""\n        query = select(User).where(\n            User.company_id == company_id,\n            User.is_deleted == False\n        ).order_by(User.name).offset(skip).limit(limit)\n        \n        result = await self.session.execute(query)\n        return result.scalars().all()\n    \n    async def get_active_users(self, company_id: Optional[int] = None) -> List[User]:\n        """Get all active users"""\n        query = select(User).where(\n            User.is_active == True,\n            User.is_deleted == False\n        )\n        \n        if company_id:\n            query = query.where(User.company_id == company_id)\n        \n        query = query.order_by(User.name)\n        \n        result = await self.session.execute(query)\n        return result.scalars().all()\n    \n    async def authenticate(self, username: str, password: str) -> Optional[User]:\n        """Authenticate a user by username/email and password"""\n        # Try to find user by username or email\n        query = select(User).where(\n            or_(User.username == username, User.email == username),\n            User.is_deleted == False\n        )\n        \n        result = await self.session.execute(query)\n        user = result.scalar_one_or_none()\n        \n        if not user:\n            return None\n        \n        if not user.is_active:\n            return None\n        \n        if not verify_password(password, user.password_hash):\n            return None\n        \n        # Update last login\n        user.last_login_at = datetime.utcnow()\n        user.login_count = (user.login_count or 0) + 1\n        await self.session.flush()\n        \n        return user\n    \n    async def set_password(self, user_id: int, password: str) -> bool:\n        """Set user password"""\n        user = await self.get_by_id(user_id)\n        \n        if not user:\n            return False\n        \n        user.password_hash = get_password_hash(password)\n        user.password_changed_at = datetime.utcnow()\n        user.force_password_change = False\n        user.updated_at = datetime.utcnow()\n        \n        await self.session.flush()\n        return True\n    \n    async def assign_roles(\n        self, \n        user_id: int, \n        role_ids: List[int]\n    ) -> Optional[User]:\n        """Assign roles to a user"""\n        user = await self.get_with_roles(user_id)\n        \n        if not user:\n            return None\n        \n        # Get role objects\n        role_query = select(Role).where(Role.id.in_(role_ids))\n        role_result = await self.session.execute(role_query)\n        roles = role_result.scalars().all()\n        \n        user.roles = list(roles)\n        user.updated_at = datetime.utcnow()\n        \n        await self.session.flush()\n        await self.session.refresh(user)\n        \n        return user\n    \n    async def remove_roles(\n        self, \n        user_id: int, \n        role_ids: List[int]\n    ) -> Optional[User]:\n        """Remove roles from a user"""\n        user = await self.get_with_roles(user_id)\n        \n        if not user:\n            return None\n        \n        user.roles = [\n            r for r in user.roles if r.id not in role_ids\n        ]\n        user.updated_at = datetime.utcnow()\n        \n        await self.session.flush()\n        await self.session.refresh(user)\n        \n        return user\n    \n    async def get_all_permissions(self, user_id: int) -> List[Permission]:\n        """Get all permissions for a user through their roles"""\n        user = await self.get_with_roles(user_id)\n        \n        if not user:\n            return []\n        \n        permissions = set()\n        for role in user.roles:\n            if role.is_active:\n                for perm in role.permissions:\n                    if perm.is_active:\n                        permissions.add(perm)\n        \n        return list(permissions)\n    \n    async def has_permission(self, user_id: int, permission_code: str) -> bool:\n        """Check if user has a specific permission"""\n        permissions = await self.get_all_permissions(user_id)\n        return any(p.code == permission_code for p in permissions)\n    \n    async def search(\n        self,\n        params: UserFilterParams,\n        company_id: Optional[int] = None\n    ) -> List[User]:\n        """Search users with filters"""\n        query = select(User).where(User.is_deleted == False)\n        \n        if params.search:\n            search_term = f"%{params.search}%"\n            query = query.where(\n                or_(\n                    User.name.ilike(search_term),\n                    User.username.ilike(search_term),\n                    User.email.ilike(search_term)\n                )\n            )\n        \n        if params.user_type:\n            query = query.where(User.user_type == params.user_type)\n        \n        if params.status:\n            query = query.where(User.status == params.status)\n        \n        if params.is_active is not None:\n            query = query.where(User.is_active == params.is_active)\n        \n        if company_id:\n            query = query.where(User.company_id == company_id)\n        \n        if params.role_id:\n            query = query.join(User.roles).where(Role.id == params.role_id)\n        \n        if params.department_id:\n            query = query.where(User.department_id == params.department_id)\n        \n        query = query.order_by(User.name)\n        query = query.offset(params.skip).limit(params.limit)\n        \n        result = await self.session.execute(query)\n        return result.scalars().all()\n    \n    async def username_exists(self, username: str, exclude_id: Optional[int] = None) -> bool:\n        """Check if a username already exists"""\n        query = select(func.count()).select_from(User).where(\n            User.username == username,\n            User.is_deleted == False\n        )\n        \n        if exclude_id:\n            query = query.where(User.id != exclude_id)\n        \n        result = await self.session.execute(query)\n        return (result.scalar() or 0) > 0\n    \n    async def email_exists(self, email: str, exclude_id: Optional[int] = None) -> bool:\n        """Check if an email already exists"""\n        query = select(func.count()).select_from(User).where(\n            User.email == email,\n            User.is_deleted == False\n        )\n        \n        if exclude_id:\n            query = query.where(User.id != exclude_id)\n        \n        result = await self.session.execute(query)\n        return (result.scalar() or 0) > 0\n    \n    async def generate_password_reset_token(self, email: str) -> Optional[str]:\n        """Generate a password reset token for a user"""\n        user = await self.get_by_email(email)\n        \n        if not user:\n            return None\n        \n        token = secrets.token_urlsafe(32)\n        user.password_reset_token = hashlib.sha256(token.encode()).hexdigest()\n        user.password_reset_expires = datetime.utcnow() + timedelta(hours=24)\n        \n        await self.session.flush()\n        return token\n    \n    async def verify_password_reset_token(self, token: str) -> Optional[User]:\n        """Verify a password reset token"""\n        token_hash = hashlib.sha256(token.encode()).hexdigest()\n        \n        query = select(User).where(\n            User.password_reset_token == token_hash,\n            User.password_reset_expires > datetime.utcnow(),\n            User.is_deleted == False\n        )\n        \n        result = await self.session.execute(query)\n        user = result.scalar_one_or_none()\n        \n        return user\n    \n    async def clear_password_reset_token(self, user_id: int) -> None:\n        """Clear password reset token"""\n        user = await self.get_by_id(user_id)\n        \n        if user:\n            user.password_reset_token = None\n            user.password_reset_expires = None\n            await self.session.flush()\n\n\nclass UserSessionRepository(BaseRepository[UserSession, dict, dict]):\n    """Repository for user session operations"""\n    \n    def __init__(self, session: AsyncSession):\n        super().__init__(UserSession, session)\n    \n    async def get_by_token(self, token: str) -> Optional[UserSession]:\n        """Get a session by token"""\n        query = select(UserSession).where(\n            UserSession.token == token,\n            UserSession.is_active == True\n        )\n        \n        result = await self.session.execute(query)\n        return result.scalar_one_or_none()\n    \n    async def get_active_sessions(self, user_id: int) -> List[UserSession]:\n        """Get all active sessions for a user"""\n        query = select(UserSession).where(\n            UserSession.user_id == user_id,\n            UserSession.is_active == True\n        ).order_by(UserSession.created_at.desc())\n        \n        result = await self.session.execute(query)\n        return result.scalars().all()\n    \n    async def create_session(\n        self, \n        user_id: int, \n        token: str,\n        ip_address: Optional[str] = None,\n        user_agent: Optional[str] = None,\n        expires_at: Optional[datetime] = None\n    ) -> UserSession:\n        """Create a new session"""\n        session = UserSession(\n            user_id=user_id,\n            token=token,\n            ip_address=ip_address,\n            user_agent=user_agent,\n            expires_at=expires_at or datetime.utcnow() + timedelta(days=7),\n            is_active=True\n        )\n        \n        self.session.add(session)\n        await self.session.flush()\n        await self.session.refresh(session)\n        \n        return session\n    \n    async def invalidate_session(self, token: str) -> bool:\n        """Invalidate a session"""\n        session = await self.get_by_token(token)\n        \n        if not session:\n            return False\n        \n        session.is_active = False\n        session.ended_at = datetime.utcnow()\n        await self.session.flush()\n        \n        return True\n    \n    async def invalidate_all_sessions(self, user_id: int) -> int:\n        """Invalidate all sessions for a user"""\n        query = update(UserSession).where(\n            UserSession.user_id == user_id,\n            UserSession.is_active == True\n        ).values(\n            is_active=False,\n            ended_at=datetime.utcnow()\n        )\n        \n        result = await self.session.execute(query)\n        await self.session.flush()\n        \n        return result.rowcount\n    \n    async def cleanup_expired_sessions(self) -> int:\n        """Clean up expired sessions"""\n        query = update(UserSession).where(\n            UserSession.expires_at < datetime.utcnow(),\n            UserSession.is_active == True\n        ).values(\n            is_active=False,\n            ended_at=datetime.utcnow()\n        )\n        \n        result = await self.session.execute(query)\n        await self.session.flush()\n        \n        return result.rowcount\n\n\nclass UserActivityLogRepository(BaseRepository[UserActivityLog, dict, dict]):\n    """Repository for user activity log operations"""\n    \n    def __init__(self, session: AsyncSession):\n        super().__init__(UserActivityLog, session)\n    \n    async def log_activity(\n        self,\n        user_id: int,\n        action: str,\n        entity_type: Optional[str] = None,\n        entity_id: Optional[int] = None,\n        ip_address: Optional[str] = None,\n        user_agent: Optional[str] = None,\n        details: Optional[Dict[str, Any]] = None\n    ) -> UserActivityLog:\n        """Log a user activity"""\n        log = UserActivityLog(\n            user_id=user_id,\n            action=action,\n            entity_type=entity_type,\n            entity_id=entity_id,\n            ip_address=ip_address,\n            user_agent=user_agent,\n            details=details\n        )\n        \n        self.session.add(log)\n        await self.session.flush()\n        await self.session.refresh(log)\n        \n        return log\n    \n    async def get_user_activities(\n        self,\n        user_id: int,\n        skip: int = 0,\n        limit: int = 100\n    ) -> List[UserActivityLog]:\n        """Get activities for a user"""\n        query = select(UserActivityLog).where(\n            UserActivityLog.user_id == user_id\n        ).order_by(UserActivityLog.created_at.desc())\n        \n        query = query.offset(skip).limit(limit)\n        \n        result = await self.session.execute(query)\n        return result.scalars().all()\n    \n    async def get_entity_activities(\n        self,\n        entity_type: str,\n        entity_id: int,\n        skip: int = 0,\n        limit: int = 100\n    ) -> List[UserActivityLog]:\n        """Get activities for an entity"""\n        query = select(UserActivityLog).where(\n            UserActivityLog.entity_type == entity_type,\n            UserActivityLog.entity_id == entity_id\n        ).order_by(UserActivityLog.created_at.desc())\n        \n        query = query.offset(skip).limit(limit)\n        \n        result = await self.session.execute(query)\n        return result.scalars().all()\n    \n    async def get_recent_activities(\n        self,\n        company_id: int,\n        hours: int = 24,\n        skip: int = 0,\n        limit: int = 100\n    ) -> List[UserActivityLog]:\n        """Get recent activities for a company"""\n        since = datetime.utcnow() - timedelta(hours=hours)\n        \n        query = select(UserActivityLog).join(User).where(\n            User.company_id == company_id,\n            UserActivityLog.created_at >= since\n        ).order_by(UserActivityLog.created_at.desc())\n        \n        query = query.offset(skip).limit(limit)\n        \n        result = await self.session.execute(query)\n        return result.scalars().all()\n</create-file>\n</function_calls>'}
{'role': 'user', 'content': '<tool_result> <create-file> ToolResult(success=True, output="File \'backend/app/repositories/user.py\' created successfully.") </create-file> </tool_result>'}